diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/base_stages/00_train_final_mog_ddp.sh b/bbflow_base/code_exports/a30_redesign_source_20260719/base_stages/00_train_final_mog_ddp.sh new file mode 100644 index 0000000000000000000000000000000000000000..f108452f35825e8a14793b6da8955756c3691f0d --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/base_stages/00_train_final_mog_ddp.sh @@ -0,0 +1,228 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +PROJECT_ROOT="$(cd "${BBFLOW_ROOT}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_final_mog_k8_m2_30ep_ddp}" +GPU_IDS="${GPU_IDS:-0,1,2}" +NUM_DEVICES="${NUM_DEVICES:-3}" + +DEFAULT_BASE_CKPT="${BBFLOW_ROOT}/models/bbflow-0.1/bbflow-0.1.ckpt" +if [[ ! -f "${DEFAULT_BASE_CKPT}" && -f "${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" ]]; then + DEFAULT_BASE_CKPT="${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" +fi +BASE_CKPT="${BASE_CKPT:-${DEFAULT_BASE_CKPT}}" +LATENT_DIM="${LATENT_DIM:-16}" +NUM_MODES="${NUM_MODES:-8}" +MIXTURE_COMPONENTS="${MIXTURE_COMPONENTS:-2}" +Q_LSTSQ_RIDGE="${Q_LSTSQ_RIDGE:-1e-4}" +Q_CHOLESKY_JITTER="${Q_CHOLESKY_JITTER:-1e-4}" +Q_DETACH_PROJECTION="${Q_DETACH_PROJECTION:-true}" +Q_DETACH_SHARED_ENCODER="${Q_DETACH_SHARED_ENCODER:-false}" +ENERGY_FROM_Q="${ENERGY_FROM_Q:-false}" +ENERGY_FROM_Q_FULL_COV="${ENERGY_FROM_Q_FULL_COV:-false}" +LAMBDA_MOTION="${LAMBDA_MOTION:-1.0}" +LAMBDA_Q="${LAMBDA_Q:-1.0}" +LAMBDA_MODE_ORTH="${LAMBDA_MODE_ORTH:-0.0}" +LAMBDA_MODE_RECON="${LAMBDA_MODE_RECON:-0.0}" +LAMBDA_PCA_ALIGN="${LAMBDA_PCA_ALIGN:-0.0}" +LAMBDA_CONDITION_CYCLE="${LAMBDA_CONDITION_CYCLE:-0.0}" +PCA_ALIGN_TOP_M="${PCA_ALIGN_TOP_M:-2}" +MOTION_MESSAGE_PASSING_LAYERS="${MOTION_MESSAGE_PASSING_LAYERS:-4}" +CROSS_COV_NEAR_DISTANCE="${CROSS_COV_NEAR_DISTANCE:-12.0}" +TEMPLATE_RESIDUAL_SCALE="${TEMPLATE_RESIDUAL_SCALE:-0.1}" +TEMPLATE_REMOVE_ROTATION="${TEMPLATE_REMOVE_ROTATION:-true}" +MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-400000}" +MAX_BATCH_SIZE="${MAX_BATCH_SIZE:-32}" +ENSEMBLE_GROUP_SIZE="${ENSEMBLE_GROUP_SIZE:-0}" +if [[ "${ENSEMBLE_GROUP_SIZE}" -gt 1 ]]; then + FORCE_GROUPED_BATCH=true +else + FORCE_GROUPED_BATCH=false +fi +PRECISION="${PRECISION:-bf16-mixed}" +ACTIVATION_CHECKPOINT="${ACTIVATION_CHECKPOINT:-true}" +MAX_EPOCHS="${MAX_EPOCHS:-30}" +MIN_EPOCHS="${MIN_EPOCHS:-1}" +MAX_STEPS="${MAX_STEPS:--1}" +TRAINER_PROFILER="${TRAINER_PROFILER:-null}" +SELF_CONDITION="${SELF_CONDITION:-true}" +EMBED_SELF_CONDITIONING="${EMBED_SELF_CONDITIONING:-true}" +if [[ "${EMBED_SELF_CONDITIONING}" != "true" ]]; then + echo "[base:00] ERROR: EMBED_SELF_CONDITIONING must stay true for checkpoint-compatible BBFlow inputs; set SELF_CONDITION=false to disable the extra self-conditioning forward." >&2 + return 2 2>/dev/null || exit 2 +fi +DIAGNOSTIC_INTERVAL_STEPS="${DIAGNOSTIC_INTERVAL_STEPS:-50}" +TRACK_CONDITION_DEBUG="${TRACK_CONDITION_DEBUG:-false}" +EPOCH_CONDITION_PROBE="${EPOCH_CONDITION_PROBE:-false}" +LOG_EVERY_N_STEPS="${LOG_EVERY_N_STEPS:-50}" +VALID_SAMPLES_PER_PROTEIN="${VALID_SAMPLES_PER_PROTEIN:-6}" +CHECKPOINT_EVERY_N_EPOCHS="${CHECKPOINT_EVERY_N_EPOCHS:-1}" +CHECKPOINT_SAVE_LAST="${CHECKPOINT_SAVE_LAST:-true}" +CHECKPOINT_SAVE_TOP_K="${CHECKPOINT_SAVE_TOP_K:--1}" +RESET_EPOCH="${RESET_EPOCH:-false}" +RESET_OPTIMIZER_ON_LOAD="${RESET_OPTIMIZER_ON_LOAD:-false}" +LAMBDA_GENERATOR_COV="${LAMBDA_GENERATOR_COV:-0.0}" +GENERATOR_COV_USE_CROSS="${GENERATOR_COV_USE_CROSS:-false}" +FREEZE_FOUNDATION="${FREEZE_FOUNDATION:-false}" +GENERATOR_COV_T_MIN="${GENERATOR_COV_T_MIN:-0.1}" +GENERATOR_COV_T_MAX="${GENERATOR_COV_T_MAX:-0.6}" +GENERATOR_COV_DELTA_SCALE="${GENERATOR_COV_DELTA_SCALE:-1.0}" +GENERATOR_COV_NUM_DELTAS="${GENERATOR_COV_NUM_DELTAS:-2}" +GENERATOR_COV_STUDENT_CHUNK_DELTAS="${GENERATOR_COV_STUDENT_CHUNK_DELTAS:-1}" +GENERATOR_COV_TEACHER_NUM_DELTAS="${GENERATOR_COV_TEACHER_NUM_DELTAS:-1}" +GENERATOR_COV_TEACHER_REUSE_STUDENT_DELTA="${GENERATOR_COV_TEACHER_REUSE_STUDENT_DELTA:-true}" +GENERATOR_COV_TEACHER_TRACE_DENOMINATOR="${GENERATOR_COV_TEACHER_TRACE_DENOMINATOR:-teacher}" +GENERATOR_COV_CHECKPOINT="${GENERATOR_COV_CHECKPOINT:-false}" +GENERATOR_COV_INITIAL_TRACE_ANCHOR="${GENERATOR_COV_INITIAL_TRACE_ANCHOR:-true}" +GENERATOR_COV_AMPLITUDE_ANCHOR="${GENERATOR_COV_AMPLITUDE_ANCHOR:-md_trace}" +GENERATOR_COV_ROLLOUT_CALIBRATION="${GENERATOR_COV_ROLLOUT_CALIBRATION:-false}" +GENERATOR_COV_ROLLOUT_STEPS="${GENERATOR_COV_ROLLOUT_STEPS:-2}" +GENERATOR_COV_ROLLOUT_NUM_DELTAS="${GENERATOR_COV_ROLLOUT_NUM_DELTAS:-1}" +GENERATOR_COV_ROLLOUT_MAX_EXAMPLES="${GENERATOR_COV_ROLLOUT_MAX_EXAMPLES:-4}" +GENERATOR_COV_ROLLOUT_INTERVAL_STEPS="${GENERATOR_COV_ROLLOUT_INTERVAL_STEPS:-200}" +GENERATOR_COV_ROLLOUT_EMA_DECAY="${GENERATOR_COV_ROLLOUT_EMA_DECAY:-0.9}" +LAMBDA_GEN_LOCAL_SHAPE="${LAMBDA_GEN_LOCAL_SHAPE:-1.0}" +LAMBDA_GEN_CROSS_SHAPE="${LAMBDA_GEN_CROSS_SHAPE:-1.0}" +LAMBDA_GEN_TRACE_ANCHOR="${LAMBDA_GEN_TRACE_ANCHOR:-0.05}" +FINGERPRINT_CACHE="${FINGERPRINT_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k${NUM_MODES}.pt}" +EXTRA_HYDRA_ARGS="${EXTRA_HYDRA_ARGS:-}" + +TRAIN_CSV="${TRAIN_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/train/ATLAS_train.csv}" +VAL_CSV="${VAL_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/validation/ATLAS_validation.csv}" +TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +ATLAS_DATASET_DIR="${ATLAS_DATASET_DIR:-${ATLAS_REPRO_ROOT}/datasets/ATLAS}" + +mkdir -p "${RUN_DIR}" + +CACHE_REQUIRE_FIELDS=(local_cov cross_cov rmsf oracle_mean_disp) +if [[ "${LAMBDA_PCA_ALIGN}" != "0" && "${LAMBDA_PCA_ALIGN}" != "0.0" ]]; then + CACHE_REQUIRE_FIELDS+=(oracle_modes oracle_energy) +fi + +python scripts/validate_motion_target_cache.py \ + --path "${FINGERPRINT_CACHE}" \ + --require "${CACHE_REQUIRE_FIELDS[@]}" + +echo "[base:00] Train final MoG per-conformation BBFlow" +echo " RUN_DIR=${RUN_DIR}" +echo " GPU_IDS=${GPU_IDS} NUM_DEVICES=${NUM_DEVICES} MAX_EPOCHS=${MAX_EPOCHS} VALID_SAMPLES_PER_PROTEIN=${VALID_SAMPLES_PER_PROTEIN}" +echo " BASE_CKPT=${BASE_CKPT}" +echo " NUM_MODES=${NUM_MODES} MIXTURE_COMPONENTS=${MIXTURE_COMPONENTS} Q_RIDGE=${Q_LSTSQ_RIDGE} Q_DETACH_PROJECTION=${Q_DETACH_PROJECTION} Q_DETACH_SHARED_ENCODER=${Q_DETACH_SHARED_ENCODER}" +echo " ENERGY_FROM_Q=${ENERGY_FROM_Q} ENERGY_FROM_Q_FULL_COV=${ENERGY_FROM_Q_FULL_COV}" +echo " LAMBDA_MOTION=${LAMBDA_MOTION} LAMBDA_Q=${LAMBDA_Q} LAMBDA_MODE_ORTH=${LAMBDA_MODE_ORTH} LAMBDA_MODE_RECON=${LAMBDA_MODE_RECON} LAMBDA_PCA_ALIGN=${LAMBDA_PCA_ALIGN} LAMBDA_CONDITION_CYCLE=${LAMBDA_CONDITION_CYCLE} PCA_ALIGN_TOP_M=${PCA_ALIGN_TOP_M} MOTION_TARGET_CACHE=${FINGERPRINT_CACHE}" +echo " GROUPED_BATCH=${FORCE_GROUPED_BATCH} ENSEMBLE_GROUP_SIZE=${ENSEMBLE_GROUP_SIZE}" +echo " CHECKPOINT_EVERY_N_EPOCHS=${CHECKPOINT_EVERY_N_EPOCHS} CHECKPOINT_SAVE_LAST=${CHECKPOINT_SAVE_LAST} CHECKPOINT_SAVE_TOP_K=${CHECKPOINT_SAVE_TOP_K}" +echo " RESET_EPOCH=${RESET_EPOCH} RESET_OPTIMIZER_ON_LOAD=${RESET_OPTIMIZER_ON_LOAD}" +echo " LAMBDA_GENERATOR_COV=${LAMBDA_GENERATOR_COV} GEN_NUM_DELTAS=${GENERATOR_COV_NUM_DELTAS} GEN_STUDENT_CHUNK_DELTAS=${GENERATOR_COV_STUDENT_CHUNK_DELTAS} GEN_TEACHER_NUM_DELTAS=${GENERATOR_COV_TEACHER_NUM_DELTAS} GEN_TEACHER_REUSE_STUDENT_DELTA=${GENERATOR_COV_TEACHER_REUSE_STUDENT_DELTA} GEN_TEACHER_TRACE_DENOMINATOR=${GENERATOR_COV_TEACHER_TRACE_DENOMINATOR} GEN_USE_CROSS=${GENERATOR_COV_USE_CROSS} GEN_TRACE_ANCHOR=${LAMBDA_GEN_TRACE_ANCHOR}" +echo " GEN_AMPLITUDE_ANCHOR=${GENERATOR_COV_AMPLITUDE_ANCHOR} GEN_ROLLOUT_CAL=${GENERATOR_COV_ROLLOUT_CALIBRATION} GEN_ROLLOUT_STEPS=${GENERATOR_COV_ROLLOUT_STEPS} GEN_ROLLOUT_NUM_DELTAS=${GENERATOR_COV_ROLLOUT_NUM_DELTAS} GEN_ROLLOUT_MAX_EXAMPLES=${GENERATOR_COV_ROLLOUT_MAX_EXAMPLES} GEN_ROLLOUT_INTERVAL=${GENERATOR_COV_ROLLOUT_INTERVAL_STEPS} GEN_ROLLOUT_EMA=${GENERATOR_COV_ROLLOUT_EMA_DECAY}" +echo " TRAIN: c*=lstsq(U, Kabsch(x_t,x_eq)-x_eq); INFER: c~q(c|x_eq)" +echo " INJECT_EMBEDDER=true INJECT_FILM=true SAMPLE_COEFFICIENTS=true FREEZE_FOUNDATION=${FREEZE_FOUNDATION}" + +CUDA_VISIBLE_DEVICES="${GPU_IDS}" python experiments/train.py \ + latent.enable=true \ + latent.dim="${LATENT_DIM}" \ + latent.num_modes="${NUM_MODES}" \ + +latent.mixture_components="${MIXTURE_COMPONENTS}" \ + +latent.q_lstsq_ridge="${Q_LSTSQ_RIDGE}" \ + +latent.q_cholesky_jitter="${Q_CHOLESKY_JITTER}" \ + +latent.q_detach_projection="${Q_DETACH_PROJECTION}" \ + +latent.q_detach_shared_encoder="${Q_DETACH_SHARED_ENCODER}" \ + +latent.energy_from_q="${ENERGY_FROM_Q}" \ + +latent.energy_from_q_full_cov="${ENERGY_FROM_Q_FULL_COV}" \ + +latent.sample_coefficients=true \ + latent.motion_message_passing_layers="${MOTION_MESSAGE_PASSING_LAYERS}" \ + latent.cross_cov_near_distance="${CROSS_COV_NEAR_DISTANCE}" \ + +latent.pca_align_top_m="${PCA_ALIGN_TOP_M}" \ + latent.template_residual_scale="${TEMPLATE_RESIDUAL_SCALE}" \ + latent.template_remove_rotation="${TEMPLATE_REMOVE_ROTATION}" \ + latent.node_cond_dim="${NUM_MODES}" \ + latent.edge_cond_dim="${NUM_MODES}" \ + latent.freeze_foundation="${FREEZE_FOUNDATION}" \ + latent.inject_embedder=true \ + latent.inject_film=true \ + latent.activation_checkpoint="${ACTIVATION_CHECKPOINT}" \ + latent.track_condition_debug="${TRACK_CONDITION_DEBUG}" \ + model.embed.embed_self_conditioning="${EMBED_SELF_CONDITIONING}" \ + interpolant.self_condition="${SELF_CONDITION}" \ + latent.shape_fingerprint_k=5 \ + latent.shape_fingerprint_cache_path="${FINGERPRINT_CACHE}" \ + latent.motion_target_cache_path="${FINGERPRINT_CACHE}" \ + latent.z_stochastic=false \ + experiment.num_devices="${NUM_DEVICES}" \ + experiment.training.force_grouped_batch="${FORCE_GROUPED_BATCH}" \ + experiment.training.ensemble_group_size="${ENSEMBLE_GROUP_SIZE}" \ + +experiment.training.per_frame_coeff_condition=true \ + experiment.training.lambda_shape=1.0 \ + +experiment.training.lambda_motion="${LAMBDA_MOTION}" \ + +experiment.training.lambda_q="${LAMBDA_Q}" \ + +experiment.training.lambda_mode_orth="${LAMBDA_MODE_ORTH}" \ + experiment.training.lambda_mode_recon="${LAMBDA_MODE_RECON}" \ + +experiment.training.lambda_pca_align="${LAMBDA_PCA_ALIGN}" \ + +experiment.training.lambda_condition_cycle="${LAMBDA_CONDITION_CYCLE}" \ + experiment.training.lambda_local_cov=1.0 \ + experiment.training.lambda_cross_cov=1.0 \ + experiment.training.lambda_rmsf=0.25 \ + experiment.training.enm_warmup_epochs=0 \ + +experiment.training.oracle_condition=false \ + +experiment.training.grad_flow_check=true \ + +experiment.training.log_optimizer_coverage=true \ + experiment.training.epoch_condition_probe="${EPOCH_CONDITION_PROBE}" \ + experiment.training.lambda_generator_cov="${LAMBDA_GENERATOR_COV}" \ + experiment.training.generator_cov_use_cross="${GENERATOR_COV_USE_CROSS}" \ + experiment.training.generator_cov_t_min="${GENERATOR_COV_T_MIN}" \ + experiment.training.generator_cov_t_max="${GENERATOR_COV_T_MAX}" \ + experiment.training.generator_cov_delta_scale="${GENERATOR_COV_DELTA_SCALE}" \ + experiment.training.generator_cov_num_deltas="${GENERATOR_COV_NUM_DELTAS}" \ + experiment.training.generator_cov_student_chunk_deltas="${GENERATOR_COV_STUDENT_CHUNK_DELTAS}" \ + experiment.training.generator_cov_teacher_num_deltas="${GENERATOR_COV_TEACHER_NUM_DELTAS}" \ + experiment.training.generator_cov_teacher_reuse_student_delta="${GENERATOR_COV_TEACHER_REUSE_STUDENT_DELTA}" \ + experiment.training.generator_cov_teacher_trace_denominator="${GENERATOR_COV_TEACHER_TRACE_DENOMINATOR}" \ + experiment.training.generator_cov_checkpoint="${GENERATOR_COV_CHECKPOINT}" \ + experiment.training.generator_cov_initial_trace_anchor="${GENERATOR_COV_INITIAL_TRACE_ANCHOR}" \ + experiment.training.generator_cov_amplitude_anchor="${GENERATOR_COV_AMPLITUDE_ANCHOR}" \ + experiment.training.generator_cov_rollout_calibration="${GENERATOR_COV_ROLLOUT_CALIBRATION}" \ + experiment.training.generator_cov_rollout_steps="${GENERATOR_COV_ROLLOUT_STEPS}" \ + experiment.training.generator_cov_rollout_num_deltas="${GENERATOR_COV_ROLLOUT_NUM_DELTAS}" \ + experiment.training.generator_cov_rollout_max_examples="${GENERATOR_COV_ROLLOUT_MAX_EXAMPLES}" \ + experiment.training.generator_cov_rollout_interval_steps="${GENERATOR_COV_ROLLOUT_INTERVAL_STEPS}" \ + experiment.training.generator_cov_rollout_ema_decay="${GENERATOR_COV_ROLLOUT_EMA_DECAY}" \ + experiment.training.lambda_gen_local_shape="${LAMBDA_GEN_LOCAL_SHAPE}" \ + experiment.training.lambda_gen_cross_shape="${LAMBDA_GEN_CROSS_SHAPE}" \ + experiment.training.lambda_gen_trace_anchor="${LAMBDA_GEN_TRACE_ANCHOR}" \ + data.sampler.max_num_res_squared="${MAX_NUM_RES_SQUARED}" \ + data.sampler.max_batch_size="${MAX_BATCH_SIZE}" \ + experiment.trainer.precision="${PRECISION}" \ + experiment.trainer.default_root_dir="${RUN_DIR}" \ + experiment.trainer.log_every_n_steps="${LOG_EVERY_N_STEPS}" \ + experiment.use_wandb=false \ + experiment.warm_start="${BASE_CKPT}" \ + experiment.warm_start_cfg_override=false \ + experiment.reset_epoch="${RESET_EPOCH}" \ + experiment.reset_optimizer_on_load="${RESET_OPTIMIZER_ON_LOAD}" \ + experiment.wandb.name="$(basename "${RUN_DIR}")" \ + experiment.trainer.max_epochs="${MAX_EPOCHS}" \ + experiment.trainer.min_epochs="${MIN_EPOCHS}" \ + +experiment.trainer.max_steps="${MAX_STEPS}" \ + +experiment.trainer.profiler="${TRAINER_PROFILER}" \ + experiment.training.diagnostic_interval_steps="${DIAGNOSTIC_INTERVAL_STEPS}" \ + data.validation.samples_per_valid_protein="${VALID_SAMPLES_PER_PROTEIN}" \ + +experiment.trainer.num_sanity_val_steps=0 \ + experiment.first_val_epoch=inf \ + experiment.checkpointer.dirpath="${RUN_DIR}" \ + experiment.checkpointer.every_n_epochs="${CHECKPOINT_EVERY_N_EPOCHS}" \ + experiment.checkpointer.save_last="${CHECKPOINT_SAVE_LAST}" \ + experiment.checkpointer.save_top_k="${CHECKPOINT_SAVE_TOP_K}" \ + data.dataset.train_csv_path="${TRAIN_CSV}" \ + "data.dataset.valid_csv_paths=[${VAL_CSV}]" \ + "data.dataset.valid_dataset_names=[ATLAS_validation]" \ + data.dataset.test_csv_path="${TEST_CSV}" \ + data.dataset.split_path="${RUN_DIR}" \ + "data.validation.valid_xtc_paths=[${ATLAS_DATASET_DIR}]" \ + ${EXTRA_HYDRA_ARGS} + +echo "[base:00] Latent metrics: ${RUN_DIR}/latent_train_epoch_metrics.csv" diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/data/interpolant_bbflow.py b/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/data/interpolant_bbflow.py new file mode 100644 index 0000000000000000000000000000000000000000..f17f6249e14fff3f09ca6f6260cb735b05ec15ae --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/data/interpolant_bbflow.py @@ -0,0 +1,312 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import torch +import numpy as np +from scipy.spatial.transform import Rotation +import os +import contextlib +from scipy.optimize import linear_sum_assignment +from sklearn.metrics import pairwise_distances +from tqdm.auto import tqdm +import pandas as pd +import logging +from torch.utils.data.distributed import dist + +from gafl.data import so3_utils +from gafl.data import utils as du +from gafl.data import all_atom +from gafl.data.interpolant import ( + Interpolant, + _centered_gaussian, + _uniform_so3, + _trans_diffuse_mask, + _rots_diffuse_mask +) + + +class InterpolantBBFlow(Interpolant): + + def __init__(self, cfg): + self._cfg = cfg + self._rots_cfg = cfg.rots + self._trans_cfg = cfg.trans + self._sample_cfg = cfg.sampling + self._rot_distribution = self._rots_cfg.distribution + self._igso3 = None + self._log = logging.getLogger(__name__) + + super().__init__(cfg) + + def _fp32_linalg_context(self): + device_type = getattr(getattr(self, "_device", None), "type", None) + if device_type == "cuda": + return torch.autocast(device_type="cuda", enabled=False) + return contextlib.nullcontext() + + def _intra_batch_ot(self, trans_1, trans_0, t, res_mask): + B, N = trans_0.shape[:2] + + if self._cfg.batch_ot == "intra_permute": + + trans_0_ordered = torch.zeros_like(trans_0) + for b in range(B): + cost_matrix_x = pairwise_distances( + trans_1[b].numpy(force=True), + trans_0[b].numpy(force=True) + ) + + cost_matrix = cost_matrix_x #+ cost_matrix_r + _, col_ind = linear_sum_assignment(cost_matrix) + + aligned_0, _, _ = du.batch_align_structures( + trans_0[b].clone()[col_ind].unsqueeze(0), + trans_1[b].unsqueeze(0) + ) + trans_0_ordered[b] = aligned_0[0] + + return trans_0_ordered + else: + trans_0, trans_1, _ = du.batch_align_structures( + trans_0, trans_1, mask=res_mask + ) + return trans_0 + + def _corrupt_trans(self, trans_1, trans_0, t, res_mask): + + if self._cfg.batch_ot == "inter": + trans_0 = self._batch_ot(trans_0, trans_1, res_mask) + elif self._cfg.batch_ot in ["intra", "intra_permute"]: + trans_0 = self._intra_batch_ot(trans_1, trans_0, t, res_mask) + elif self._cfg.batch_ot == "none": + pass + else: + raise ValueError(f'Unknown batch ot type {self._cfg.batch_ot}') + trans_t = (1 - t[..., None]) * trans_0 + t[..., None] * trans_1 + trans_t = _trans_diffuse_mask(trans_t, trans_1, res_mask) + + return trans_t * res_mask[..., None] + + def _corrupt_rotmats(self, rotmats_1, rotmats_0, t, res_mask): + rotmats_t = so3_utils.geodesic_t(t[..., None], rotmats_1, rotmats_0) + identity = torch.eye(3, device=self._device) + rotmats_t = ( + rotmats_t * res_mask[..., None, None] + + identity[None, None] * (1 - res_mask[..., None, None]) + ) + return _rots_diffuse_mask(rotmats_t, rotmats_1, res_mask) + + def corrupt_batch(self, batch, t=None): + noisy_batch = dict(batch) + + trans_equilibrium = batch["trans_equilibrium"].float() + rotmats_equilibrium = batch["rotmats_equilibrium"].float() + B, N = trans_equilibrium.shape[:2] + with self._fp32_linalg_context(): + trans_0, rotmats_0 = self.sample_from_prior( + B, N, + trans_equilibrium, + rotmats_equilibrium, + ) + + if t is None: + # [B, 1] + t = self.sample_t(B)[:, None] + t = t.float() + + # [B, N, 3] + trans_1 = batch['trans_1'].float() # Angstrom + + # [B, N, 3, 3] + rotmats_1 = batch['rotmats_1'].float() + + # [B, N] + res_mask = batch['res_mask'].float() + + # Apply corruptions + trans_t = self._corrupt_trans(trans_1, trans_0, t, res_mask) + rotmats_t = self._corrupt_rotmats(rotmats_1, rotmats_0, t, res_mask) + + noisy_batch['t'] = t + noisy_batch['trans_t'] = trans_t + noisy_batch['rotmats_t'] = rotmats_t + return noisy_batch + + def _pure_noise_prior(self, num_batch, num_res, rotmats_1): + trans_nm_0 = _centered_gaussian(num_batch, num_res, self._device) + trans_0 = trans_nm_0 * du.NM_TO_ANG_SCALE + trans_0 *= self.noise_scale + + # make the noise blob larger the longer the protein is: + if self.noise_res_scaling_power > 0: + trans_0 *= (trans_0.shape[1] / 128.)**self.noise_res_scaling_power + + if self._rot_distribution == 'uniform': + rotmats_0 = _uniform_so3(num_batch, num_res, self._device) + elif self._rot_distribution == 'igso3': + noisy_rotmats = self.igso3.sample( + torch.tensor([1.5]), + num_batch*num_res + ).to(self._device) + noisy_rotmats = noisy_rotmats.reshape(num_batch, num_res, 3, 3) + rotmats_0 = torch.einsum("...ij,...jk->...ik", rotmats_1, noisy_rotmats) + else: + raise ValueError(f'Unknown SO(3) distribution {self._rot_distribution}') + + return trans_0, rotmats_0 + + def _conditional_prior(self, num_batch, num_res, trans_equilibrium, rotmats_equilibrium): + res_mask = torch.ones(num_batch, num_res, device=self._device) + trans_equilibrium = trans_equilibrium.float() + rotmats_equilibrium = rotmats_equilibrium.float() + trans_0, rotmats_0 = self._pure_noise_prior(num_batch, num_res, rotmats_equilibrium) + + trans_0 = self._corrupt_trans( + trans_equilibrium, + trans_0, + self._cfg.prior_conditional.gamma_trans * torch.ones(num_batch, 1, device=self._device, dtype=torch.float32), + res_mask + ) + rotmats_0 = self._corrupt_rotmats( + rotmats_equilibrium, + rotmats_0, + self._cfg.prior_conditional.gamma_rots * torch.ones(num_batch, 1, device=self._device, dtype=torch.float32), + res_mask + ) + + return trans_0, rotmats_0 + + def sample_from_prior( + self, + num_batch, + num_res, + trans_equilibrium, + rotmats_equilibrium, + ): + + prior_type = self._cfg.prior + + if prior_type == 'conditional': + with self._fp32_linalg_context(): + return self._conditional_prior( + num_batch, num_res, trans_equilibrium, rotmats_equilibrium + ) + elif prior_type == 'pure_noise': + return self._pure_noise_prior(num_batch, num_res, rotmats_equilibrium) + + else: + raise ValueError(f'Unknown prior type {prior_type}') + + + def sample( + self, + num_batch, + num_res, + model, + trans_equilibrium, + rotmats_equilibrium, + seq, + z=None, + return_trajectory=True, + cache_static_features=True, + ): + + res_mask = torch.ones(num_batch, num_res, device=self._device) + + # Set-up initial prior samples + trans_0, rotmats_0 = self.sample_from_prior( + num_batch, num_res, trans_equilibrium, rotmats_equilibrium + ) + batch = { + "res_mask": res_mask, + "trans_equilibrium": trans_equilibrium, + "rotmats_equilibrium": rotmats_equilibrium, + "seq": seq, + } + if z is not None: + batch["z"] = z + if cache_static_features and hasattr(model, "prepare_inference_static"): + batch["_embedder_static"] = model.prepare_inference_static(batch) + + # Set-up time + ts = torch.linspace( + self._cfg.min_t, 1.0, self._sample_cfg.num_timesteps) + t_1 = ts[0] + + prot_traj = [(trans_0, rotmats_0)] if return_trajectory else None + clean_traj = [] + trans_current, rotmats_current = trans_0, rotmats_0 + if self._cfg.use_tqdm: + iterator = tqdm( + ts[1:], + leave=False, + desc=f'Sampl. {num_batch} states, len {num_res}, rank {dist.get_rank()} - timesteps' + ) + + else: + iterator = ts[1:] + for t_2 in iterator: + + # Run model. + trans_t_1, rotmats_t_1 = trans_current, rotmats_current + t = torch.ones((num_batch, 1), device=self._device) * t_1 + batch['trans_t'] = trans_t_1 + batch['rotmats_t'] = rotmats_t_1 + batch['t'] = t + with torch.no_grad(): + model_out = model(batch) + # Process model output. + pred_trans_1 = model_out['pred_trans'] + pred_rotmats_1 = model_out['pred_rotmats'] + if return_trajectory: + clean_traj.append( + (pred_trans_1.detach().cpu(), pred_rotmats_1.detach().cpu()) + ) + if self._cfg.self_condition: + batch['trans_sc'] = pred_trans_1 + + d_t = t_2 - t_1 + # Take reverse step + trans_t_2 = self._trans_euler_step( + d_t, t_1, pred_trans_1, trans_t_1) + rotmats_t_2 = self._rots_euler_step( + d_t, t_1, pred_rotmats_1, rotmats_t_1) + + trans_current, rotmats_current = trans_t_2, rotmats_t_2 + if return_trajectory: + prot_traj.append((trans_t_2, rotmats_t_2)) + t_1 = t_2 + + + + t_1 = ts[-1] + trans_t_1, rotmats_t_1 = trans_current, rotmats_current + t = torch.ones((num_batch, 1), device=self._device) * t_1 + batch['trans_t'] = trans_t_1 + batch['rotmats_t'] = rotmats_t_1 + batch['t'] = t + + with torch.no_grad(): + model_out = model(batch) + # Process model output. + pred_trans_1 = model_out['pred_trans'] + pred_rotmats_1 = model_out['pred_rotmats'] + if return_trajectory: + clean_traj.append( + (pred_trans_1.detach().cpu(), pred_rotmats_1.detach().cpu()) + ) + prot_traj.append((pred_trans_1, pred_rotmats_1)) + else: + # Keep the historical return structure, but materialize only the + # final state that inference actually writes. + prot_traj = [(pred_trans_1, pred_rotmats_1)] + clean_traj = [(pred_trans_1, pred_rotmats_1)] + + # Convert trajectories to atom37. + atom37_traj = all_atom.transrot_to_atom37(prot_traj, res_mask) + clean_atom37_traj = all_atom.transrot_to_atom37(clean_traj, res_mask) + + return atom37_traj, clean_atom37_traj, clean_traj + diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/bbflow_model.py b/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/bbflow_model.py new file mode 100644 index 0000000000000000000000000000000000000000..af56c6cb0efcd2f70f7208774ffb54f1ebb330c5 --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/bbflow_model.py @@ -0,0 +1,266 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import numpy as np +import torch +import torch.nn as nn +from torch.utils.checkpoint import checkpoint + +from gafl.models import ipa_pytorch +from gafl.data import utils as du +from gafl.models.gafl.pga_utils import embed_frames, EquiLayerNorm +from gafl.models.gafl.cfa import GeometricFrameAttention, Linear, BackboneUpdate + +from bbflow.models.embedder import Embedder + + +from omegaconf import DictConfig, OmegaConf +from omegaconf.base import ContainerMetadata +# depending on the torch version (higher than 2.6), we need to add the DictConfig and ContainerMetadata to the safe globals: +import torch +import builtins +from typing import Any +from collections import defaultdict +from omegaconf import DictConfig, OmegaConf, ListConfig +from omegaconf.nodes import AnyNode +from omegaconf.base import ContainerMetadata, Metadata + +# depending on the torch version (>=2.6), we need to add all types the checkpoint asked for +if hasattr(torch.serialization, "add_safe_globals"): + torch.serialization.add_safe_globals([ + (Any, "typing.Any"), + (defaultdict, "collections.defaultdict"), + (DictConfig, "omegaconf.dictconfig.DictConfig"), + (ListConfig, "omegaconf.listconfig.ListConfig"), + (AnyNode, "omegaconf.nodes.AnyNode"), + (ContainerMetadata, "omegaconf.base.ContainerMetadata"), + (Metadata, "omegaconf.base.Metadata"), + (builtins.dict, "builtins.dict"), + (builtins.int, "builtins.int"), + (builtins.list, "builtins.list"), + ]) + + +class BBFlowModel(nn.Module): + + def __init__(self, model_conf, latent_cfg=None): + super(BBFlowModel, self).__init__() + + self._model_conf = model_conf + self._gfa_conf = model_conf.gfa + self.rigids_ang_to_nm = lambda x: x.apply_trans_fn(lambda x: x * du.ANG_TO_NM_SCALE) + self.rigids_nm_to_ang = lambda x: x.apply_trans_fn(lambda x: x * du.NM_TO_ANG_SCALE) + self.embedder = Embedder(model_conf, latent_cfg=latent_cfg) + self.latent_enabled = bool(latent_cfg is not None and getattr(latent_cfg, "enable", False)) + self.inject_film = bool( + self.latent_enabled and getattr(latent_cfg, "inject_film", True) + ) + self.activation_checkpoint = bool( + latent_cfg is not None and getattr(latent_cfg, "activation_checkpoint", False) + ) + + # Attention trunk + self.trunk = nn.ModuleDict() + for b in range(self._gfa_conf.num_blocks): + self.trunk[f'gfa_{b}'] = GeometricFrameAttention(self._gfa_conf, geometric_input=bool(b), geometric_output=True) + self.trunk[f'gfa_ln_{b}'] = nn.LayerNorm(self._gfa_conf.c_s) + self.trunk[f'g_ln_{b}'] = EquiLayerNorm() + tfmr_in = self._gfa_conf.c_s + tfmr_layer = nn.TransformerEncoderLayer( + d_model=tfmr_in, + nhead=self._gfa_conf.seq_tfmr_num_heads, + dim_feedforward=tfmr_in, + batch_first=True, + dropout=0.0, + norm_first=False + ) + self.trunk[f'seq_tfmr_{b}'] = nn.TransformerEncoder( + tfmr_layer, self._gfa_conf.seq_tfmr_num_layers, enable_nested_tensor=False) + self.trunk[f'post_tfmr_{b}'] = Linear( + tfmr_in, self._gfa_conf.c_s, init="final") + self.trunk[f'node_transition_{b}'] = ipa_pytorch.StructureModuleTransition( + c=self._gfa_conf.c_s) + self.trunk[f'bb_update_{b}'] = BackboneUpdate( + self._gfa_conf.c_s, + self._gfa_conf.no_v_points, + self._gfa_conf.no_heads,) + + if b < self._gfa_conf.num_blocks-1: + # No edge update on the last block. + edge_in = self._model_conf.edge_embed_size + self.trunk[f'edge_transition_{b}'] = ipa_pytorch.EdgeTransition( + node_embed_size=self._gfa_conf.c_s, + edge_embed_in=edge_in, + edge_embed_out=self._model_conf.edge_embed_size, + ) + + if self.inject_film: + self.latent_dim = int(getattr(latent_cfg, "dim", 16)) + self.film_cond_dim = int(getattr(latent_cfg, "node_cond_dim", getattr(latent_cfg, "num_modes", self.latent_dim))) + self.film_mlp = nn.Sequential( + nn.Linear(self.film_cond_dim, self._gfa_conf.c_s), + nn.ReLU(), + nn.Linear(self._gfa_conf.c_s, 2 * self._gfa_conf.c_s), + ) + nn.init.zeros_(self.film_mlp[-1].weight) + nn.init.zeros_(self.film_mlp[-1].bias) + else: + self.latent_dim = 0 + self.film_cond_dim = 0 + self.film_mlp = None + + def _apply_latent_film(self, node_embed, z): + if not self.inject_film: + return node_embed + if isinstance(z, dict): + cond = z.get("node_cond") + else: + cond = z + if cond is None: + cond = torch.zeros( + node_embed.shape[0], + node_embed.shape[1], + self.film_cond_dim, + device=node_embed.device, + dtype=node_embed.dtype, + ) + if cond.dim() == 2: + cond = cond[:, None, :].expand(node_embed.shape[0], node_embed.shape[1], -1) + gamma_beta = self.film_mlp(cond.to(dtype=node_embed.dtype)) + gamma, beta = torch.chunk(gamma_beta, 2, dim=-1) + return node_embed * (1.0 + gamma) + beta + + def prepare_inference_static(self, batch): + B, N = batch["res_mask"].shape[:2] + return self.embedder.prepare_inference_static({ + "B,N": (B, N), + "device": batch["res_mask"].device, + "CA_pos": { + "trans_equilibrium": batch["trans_equilibrium"], + }, + "rotmats_equilibrium": batch["rotmats_equilibrium"], + "seq": batch["seq"], + "z": batch.get("z"), + }) + + def _run_gfa(self, block_idx, node_embed, g, edge_embed, curr_frames, node_mask): + gfa = self.trunk[f'gfa_{block_idx}'] + if not (self.training and self.activation_checkpoint and torch.is_grad_enabled()): + return gfa(node_embed, g, edge_embed, curr_frames, node_mask) + if g is None: + return gfa(node_embed, g, edge_embed, curr_frames, node_mask) + + def gfa_forward(node_embed_, g_, edge_embed_, curr_frames_, node_mask_): + return gfa(node_embed_, g_, edge_embed_, curr_frames_, node_mask_) + + return checkpoint( + gfa_forward, + node_embed, + g, + edge_embed, + curr_frames, + node_mask, + use_reentrant=False, + preserve_rng_state=False, + ) + + + def forward(self, input_feats): + node_mask = input_feats['res_mask'] + edge_mask = node_mask[:, None] * node_mask[:, :, None] + continuous_t = input_feats['t'] + trans_t = input_feats['trans_t'] + rotmats_t = input_feats['rotmats_t'] + + # Initialize node and edge embeddings + if 'trans_sc' not in input_feats: + trans_sc = torch.zeros_like(trans_t) + else: + trans_sc = input_feats['trans_sc'] + + B, N = node_mask.shape[:2] + CA_pos = { + "trans_t": trans_t, + "trans_sc": trans_sc, + "trans_equilibrium": input_feats["trans_equilibrium"] + } + embedder_input_feats = { + "B,N": (B, N), + "device": node_mask.device, + "time": continuous_t, + "CA_pos": CA_pos, + "rotmats_equilibrium": input_feats["rotmats_equilibrium"], + "seq": input_feats["seq"], + } + if "dataset_type_onehot" in input_feats: + embedder_input_feats["dataset_type_onehot"] = input_feats["dataset_type_onehot"] + if "z" in input_feats: + embedder_input_feats["z"] = input_feats["z"] + if "_embedder_static" in input_feats: + embedder_input_feats["inference_static"] = input_feats["_embedder_static"] + init_node_embed, init_edge_embed = self.embedder(embedder_input_feats) + + + # Initial rigids + # curr_frames = embed_frames(rotmats_t, trans_t * du.ANG_TO_NM_SCALE) + curr_rigids = du.create_rigid(rotmats_t, trans_t,) + curr_rigids = self.rigids_ang_to_nm(curr_rigids) + curr_frames = embed_frames(rotmats_t, trans_t * du.ANG_TO_NM_SCALE) + + # Main trunk + init_node_embed = init_node_embed * node_mask[..., None] + node_embed = init_node_embed * node_mask[..., None] + edge_embed = init_edge_embed * edge_mask[..., None] + g = None + for b in range(self._gfa_conf.num_blocks): + gfa_embed, g_gfa, gfa_rel = self._run_gfa( + b, + node_embed, + g, + edge_embed, + curr_frames, + node_mask) + gfa_embed *= node_mask[..., None] + gfa_rel = gfa_rel * node_mask[..., None, None] + node_embed = self.trunk[f'gfa_ln_{b}'](node_embed + gfa_embed) + + if g is not None: + g = self.trunk[f'g_ln_{b}'](g + g_gfa) + else: + g = self.trunk[f'g_ln_{b}'](g_gfa) + g = g * node_mask[..., None, None] + + seq_tfmr_out = self.trunk[f'seq_tfmr_{b}']( + node_embed, src_key_padding_mask=(1 - node_mask).bool()) + node_embed = node_embed + self.trunk[f'post_tfmr_{b}'](seq_tfmr_out) + node_embed = self.trunk[f'node_transition_{b}'](node_embed) + node_embed = node_embed * node_mask[..., None] + update_node_embed = node_embed + if b == self._gfa_conf.num_blocks - 1: + update_node_embed = self._apply_latent_film( + node_embed, + input_feats.get("z", None), + ) + curr_frames, curr_rigids = self.trunk[f'bb_update_{b}']( + update_node_embed, + g, + gfa_rel, + curr_frames, + curr_rigids, + node_mask[..., None],) + + if b < self._gfa_conf.num_blocks-1: + edge_embed = self.trunk[f'edge_transition_{b}']( + node_embed, edge_embed) + edge_embed *= edge_mask[..., None] + + curr_rigids = self.rigids_nm_to_ang(curr_rigids) + pred_trans = curr_rigids.get_trans() + pred_rotmats = curr_rigids.get_rots().get_rot_mats() + + return { + 'pred_trans': pred_trans, + 'pred_rotmats': pred_rotmats, + } diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/bbflow_module.py b/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/bbflow_module.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f465b6d320bda6afd0081d17830c5790beae6c --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/bbflow_module.py @@ -0,0 +1,1923 @@ +# 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.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_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", +] + + +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.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() + 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_epoch_start(self): + self._set_frozen_foundation_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 + ) + if needs_oracle_modes: + optional_fields = ["oracle_modes", "oracle_energy", "oracle_mean_disp"] + 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 + with torch.no_grad(): + 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) + else: + raise ValueError(f"Unknown inference.condition_mode={condition_mode}") + return self._scale_condition(z, condition_scale) + + 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 _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] + 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._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(()) + mode_orth_loss = self.latent_encoder.mode_orthogonality_loss( + 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") + condition, coeff_target = self.latent_encoder.frame_condition_from_projection( + noisy_batch["trans_1"], + noisy_batch["trans_equilibrium"], + 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(): + gram_metrics = self.latent_encoder.mode_gram_diagnostics( + 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)) + latent_regularizer = ( + lambda_motion * motion_loss + + lambda_q * q_fit_loss + + lambda_mode_orth * mode_orth_loss + + lambda_mode_recon * mode_recon_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() + return ( + condition, + torch.arange(num_batch, device=device, dtype=torch.long), + 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 + + # 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, + ) + 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_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"] + 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) + 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() + + 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._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_"], + "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 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. + with torch.autocast(device_type="cuda", enabled=False): + noisy_batch = self.interpolant.corrupt_batch(batch) + 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 + + if ( + z is not None + and isinstance(z, dict) + and "u_global" in z + and int(self.global_step) % 100 == 0 + ): + # DDP-safe mode-collapse watch. Every rank computes its worst mode + # norm -- the exact quantity whose 1/norm^2 gradient explodes in + # mode_orthogonality_loss -- then all-reduces to the GLOBAL min/max + # so a collapse on any rank is caught, and prints on rank 0 only. + # Gated purely on the synced global_step + config-level z structure, + # so every rank enters the collective together (no deadlock). + with torch.no_grad(): + _basis = z["u_global"].detach().float() * noisy_batch["res_mask"].float()[:, :, None, None] + _gram = torch.einsum("bnkd,bnld->bkl", _basis, _basis) + _mode_norms = torch.diagonal(_gram, dim1=-2, dim2=-1).clamp_min(0.0).sqrt() + _min_norm = _mode_norms.min().detach().clone() + _max_norm = _mode_norms.max().detach().clone() + if self.trainer.world_size > 1 and dist.is_initialized(): + dist.all_reduce(_min_norm, op=dist.ReduceOp.MIN) + dist.all_reduce(_max_norm, op=dist.ReduceOp.MAX) + if int(getattr(self, "global_rank", 0)) == 0: + logging.info( + "[mode-watch] step=%d min_mode_norm=%.3e max_mode_norm=%.3e", + int(self.global_step), + float(_min_norm), + float(_max_norm), + ) + + log_latent_batch_debug = bool( + getattr(self._exp_cfg.training, "log_latent_batch_debug", False) + ) + if log_latent_batch_debug and (self.global_step < 20 or self.global_step % 500 == 0): + 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")), + ) + + if self._interpolant_cfg.self_condition and random.random() > 0.5: + with torch.no_grad(): + model_sc = self.model(noisy_batch) + noisy_batch['trans_sc'] = model_sc['pred_trans'] + + model_output = self.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) + 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'] + ) + train_loss = ( + official_loss + + float(getattr(self._exp_cfg.training, "lambda_shape", 1.0)) * shape_recon_loss + + condition_cycle_loss + + gen_cov_loss + ) + + nan_detected = torch.isnan(train_loss).float() + if self.trainer.world_size > 1: + dist.all_reduce(nan_detected, op=dist.ReduceOp.SUM) + + if nan_detected > 0: + self.nan_steps += 1 + if self.nan_steps > 5: + raise ValueError('NaN loss encountered too many times in a row') + if self.global_rank == 0: + logging.info(f"NaN detected in loss (epoch {self.current_epoch}). Skipping this step.") + return None + else: + self.nan_steps = 0 + + 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) + 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] + batch_size = self._infer_cfg.samples.num_res_squared / N**2 + batch_size = max( + 1, + min( + self._infer_cfg.samples.batch_size, + int(batch_size/5)*5 + ) + ) + + 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") diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/embedder.py b/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..f725e1c43bc09773d65a23b831ea04419c385af9 --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/embedder.py @@ -0,0 +1,463 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import functools as fn +import numpy as np +import torch +import torch.nn as nn +from torch.nn import functional as F + +import gafl.models.utils as mu +from gafl.data import utils as du + +from gafl.models.ipa_pytorch import Linear +from gafl.models.utils import get_index_embedding, get_time_embedding, get_length_embedding + +class MLP(nn.Module): + def __init__(self, c1, c2, num_layers=2, use_layer_norm=True, dropout=0) -> None: + super(MLP, self).__init__() + + self.layers = [] + for _ in range(num_layers-1): + self.layers.append(Linear(c1, c1, init="relu")) + self.layers.append(nn.ReLU()) + self.layers.append(nn.Dropout(dropout)) + self.layers.append(Linear(c1, c1, init="final")) + self.layers = nn.Sequential(*self.layers) + + if c1 != c2: + self.final_layer = nn.Linear(c1, c2) + else: + self.final_layer = nn.Identity() + + self.use_layer_norm = use_layer_norm + if use_layer_norm: + self.layer_norm = nn.LayerNorm(c2) + + def forward(self, x): + x = self.layers(x) + x + x = self.final_layer(x) + if self.use_layer_norm: + x = self.layer_norm(x) + return x + + +def embed_direction(trans, rots, dist_cutoff=np.inf): + """ + Compute the position of the other residues from the + perspective of each residue. + + Args: + trans: [B, N, 3] translation vectors + rots: [B, N, 3, 3] rotation matrices + Returns: + [B, N, N, 3] relative positions from each residue to each other residue + """ + + B, N, _ = trans.shape + device = trans.device + + frames = du.create_rigid(rots, trans) + rel_pos = frames[:,:,None].invert_apply(trans[:,None,:]) + # rel_pos.shape = [B, N, N, 3] + distances = torch.linalg.norm(rel_pos, dim=-1) + rel_pos = rel_pos / (distances[...,None] + 1e-6) + indices = torch.arange(N, device=device) + rel_pos[:, indices, indices, :] = torch.zeros(3, device=device) + if dist_cutoff < np.inf: + # Set all direction vectors to zero if the distance is greater than dist_cutoff + mask = distances > dist_cutoff + rel_pos[mask,:] = 0 + + return rel_pos + + + + +class Embedder(nn.Module): + def __init__(self, model_conf, latent_cfg=None): + super(Embedder, self).__init__() + self.model_conf = model_conf + self.embed_aatype = model_conf.embed.embed_aatype + self.latent_enabled = bool(latent_cfg is not None and getattr(latent_cfg, "enable", False)) + self.inject_embedder = bool( + self.latent_enabled and getattr(latent_cfg, "inject_embedder", True) + ) + self.track_condition_debug = bool( + self.latent_enabled and getattr(latent_cfg, "track_condition_debug", False) + ) + + if "time_embed_dim" in model_conf.embed: + self.time_embed_dim = model_conf.embed.time_embed_dim + else: + self.time_embed_dim = 0 + + if "embed_distogram" in model_conf.embed: + self.embed_distogram = model_conf.embed.embed_distogram + else: + self.embed_distogram = True + + if "embed_self_conditioning" in model_conf.embed: + self.embed_self_conditioning = model_conf.embed.embed_self_conditioning + else: + self.embed_self_conditioning = True + + + length_embed_dim = model_conf.embed.length_embed_dim + + node_dim_in = self.time_embed_dim + length_embed_dim + + edge_dim_in = 2 * self.time_embed_dim + edge_dim_in += 2 * model_conf.node_embed_size + edge_dim_in += self.model_conf.embed.num_bins_distance + if self.embed_distogram: + edge_dim_in += self.model_conf.embed.num_bins_distance + if self.embed_self_conditioning: + edge_dim_in += self.model_conf.embed.num_bins_distance + + self.embed_direction = model_conf.embed.embed_direction + if self.embed_direction: + if hasattr(model_conf.embed, "embed_direction_cutoff") and model_conf.embed.embed_direction_cutoff is not None: + self.embed_direction_cutoff = model_conf.embed.embed_direction_cutoff + else: + self.embed_direction_cutoff = np.inf + edge_dim_in += 3 + + # positional encoding + # if model_conf.embed.index_embed_dim > 0: + if hasattr(model_conf.embed, "index_embed_type"): + self.index_embed_type = model_conf.embed.index_embed_type + self.index_embed_dim = model_conf.embed.index_embed_dim + else: + self.index_embed_dim = model_conf.embed.index_embed_dim + self.index_embed_type = None if self.index_embed_dim == 0 else "full" + + if self.index_embed_type is None or self.index_embed_type == "none": + self.index_embed_type = None + elif self.index_embed_type == "full": + assert self.index_embed_dim > 0, "index_embed_dim must be > 0 if index_embed_type is 'full'." + node_dim_in += self.index_embed_dim + edge_dim_in += self.index_embed_dim + self.linear_relpos = nn.Linear( + self.index_embed_dim, self.index_embed_dim + ) + elif self.index_embed_type == "neighbor": + edge_dim_in += 1 + else: + raise ValueError("index_embed_type must be None/\"none\", 'full' or 'neighbor'.") + + + if self.embed_aatype: + self.aatype_embedding = nn.Linear(21, model_conf.embed.aatype_embed_dim) + node_dim_in += model_conf.embed.aatype_embed_dim + + if self.inject_embedder: + self.latent_dim = int(getattr(latent_cfg, "dim", 16)) + self.num_modes = int(getattr(latent_cfg, "num_modes", self.latent_dim)) + self.node_cond_dim = int(getattr(latent_cfg, "node_cond_dim", self.num_modes)) + self.edge_cond_dim = int(getattr(latent_cfg, "edge_cond_dim", self.num_modes)) + self.z_node_adapter = nn.Sequential( + nn.Linear(self.node_cond_dim, model_conf.node_embed_size), + nn.ReLU(), + nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size), + ) + self.z_edge_adapter = nn.Sequential( + nn.Linear(self.edge_cond_dim, model_conf.edge_embed_size), + nn.ReLU(), + nn.Linear(model_conf.edge_embed_size, model_conf.edge_embed_size), + ) + self.disp_node_adapter = nn.Sequential( + nn.Linear(3, model_conf.node_embed_size), + nn.ReLU(), + nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size), + ) + self.disp_edge_adapter = nn.Sequential( + nn.Linear(1, model_conf.edge_embed_size), + nn.ReLU(), + nn.Linear(model_conf.edge_embed_size, model_conf.edge_embed_size), + ) + nn.init.zeros_(self.z_node_adapter[-1].weight) + nn.init.zeros_(self.z_node_adapter[-1].bias) + nn.init.zeros_(self.z_edge_adapter[-1].weight) + nn.init.zeros_(self.z_edge_adapter[-1].bias) + nn.init.zeros_(self.disp_node_adapter[-1].weight) + nn.init.zeros_(self.disp_node_adapter[-1].bias) + nn.init.zeros_(self.disp_edge_adapter[-1].weight) + nn.init.zeros_(self.disp_edge_adapter[-1].bias) + else: + self.latent_dim = 0 + self.num_modes = 0 + self.node_cond_dim = 0 + self.edge_cond_dim = 0 + self.z_node_adapter = None + self.z_edge_adapter = None + self.disp_node_adapter = None + self.disp_edge_adapter = None + + self.linear_s_p = nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size) + + self.node_embedding = MLP(node_dim_in, model_conf.node_embed_size, num_layers=2) + self.edge_embedding = MLP(edge_dim_in, model_conf.edge_embed_size, num_layers=2) + + + self.timestep_embedder = fn.partial( + get_time_embedding, + embedding_dim=self.time_embed_dim, + ) + self.index_embedder = fn.partial( + get_index_embedding, + embed_size=self.model_conf.embed.index_embed_dim, + ) + self.length_embedder = fn.partial( + get_length_embedding, + embed_size=self.model_conf.embed.length_embed_dim, + max_len=2056 + ) + + def prepare_inference_static(self, input_features): + """Cache O(N^2) features that are constant across ODE timesteps.""" + B, N = input_features["B,N"] + device = input_features["device"] + cache = {} + + if self.embed_aatype: + cache["aatype_embedding"] = self.aatype_embedding(input_features["seq"]) + + cache["length_embedding"] = self.length_embedder( + torch.empty(1, N, device=device) + ).repeat([B, 1, 1]) + + if self.index_embed_type == "full": + seq_idx = torch.arange(N, device=device).repeat(B, 1) + cache["index_node_embedding"] = self.index_embedder(seq_idx) + rel_seq_offset = seq_idx[:, :, None] - seq_idx[:, None, :] + cache["index_edge_embedding"] = self.linear_relpos( + self.index_embedder(rel_seq_offset.reshape([B, N**2])) + ) + elif self.index_embed_type == "neighbor": + neighbors = ( + torch.diag_embed(torch.ones(N - 1, device=device), offset=1) + + torch.diag_embed(torch.ones(N - 1, device=device), offset=-1) + ) + cache["index_edge_embedding"] = ( + neighbors[None].repeat(B, 1, 1).reshape([B, N**2, 1]) + ) + + if self.embed_distogram: + cache["equilibrium_distogram"] = mu.calc_distogram( + input_features["CA_pos"]["trans_equilibrium"], + self.model_conf.embed.min_bin_distance, + self.model_conf.embed.max_bin_distance, + self.model_conf.embed.num_bins_distance, + ).reshape([B, N**2, -1]) + + if self.embed_direction: + cache["direction_embedding"] = embed_direction( + input_features["CA_pos"]["trans_equilibrium"], + input_features["rotmats_equilibrium"], + dist_cutoff=self.embed_direction_cutoff, + ).reshape([B, N**2, -1]) + + if self.inject_embedder: + payload = input_features.get("z") + if isinstance(payload, dict): + node_cond = payload.get("node_cond") + edge_cond = payload.get("edge_cond") + disp_node_cond = payload.get("disp_node_cond") + disp_edge_cond = payload.get("disp_edge_cond") + else: + node_cond = payload + edge_cond = payload + disp_node_cond = None + disp_edge_cond = None + if node_cond is None: + node_cond = torch.zeros(B, N, self.node_cond_dim, device=device) + if edge_cond is None: + edge_cond = torch.zeros(B, N, N, self.edge_cond_dim, device=device) + if disp_node_cond is None: + disp_node_cond = torch.zeros(B, N, 3, device=device) + if disp_edge_cond is None: + disp_edge_cond = torch.zeros(B, N, N, 1, device=device) + if node_cond.dim() == 2: + node_cond = node_cond[:, None, :].expand(B, N, -1) + if edge_cond.dim() == 2: + edge_cond = edge_cond[:, None, None, :].expand(B, N, N, -1) + cache["node_condition_embedding"] = ( + self.z_node_adapter(node_cond) + + self.disp_node_adapter(disp_node_cond) + ) + cache["edge_condition_embedding"] = ( + self.z_edge_adapter(edge_cond) + + self.disp_edge_adapter(disp_edge_cond) + ) + return cache + + def forward(self, input_features): + """ + Args: + t: + [*, ] time step sampled from [0, 1] + fixed_mask: + [*, N_res] mask of fixed (motif) residues + self_conditioning_ca: + [*, N_res, 3] Ca positions of self-conditioning input + rigids: + [*, N_res] Frame object + Returns: + [*, N_res, node_dim] initial node features + [*, N_res, N_res, edge_dim] initial edge features + """ + B, N = input_features["B,N"] + device = input_features["device"] + static = input_features.get("inference_static") + + h_0 = [] + z_0 = [] + + if self.time_embed_dim > 0: + t_embed = self.timestep_embedder(input_features["time"][:,0])[:, None, :].repeat(1, N, 1) + h_0.append(t_embed) + z_0.append(self._cross_concat(t_embed, B, N)) + + if self.embed_aatype: + if static is not None and "aatype_embedding" in static: + h_0.append(static["aatype_embedding"]) + else: + h_0.append(self.aatype_embedding(input_features["seq"])) + + if self.inject_embedder: + z_payload = input_features.get("z", None) + self._last_z_seen = z_payload is not None + if isinstance(z_payload, dict): + node_cond = z_payload.get("node_cond") + edge_cond = z_payload.get("edge_cond") + disp_node_cond = z_payload.get("disp_node_cond") + disp_edge_cond = z_payload.get("disp_edge_cond") + else: + node_cond = z_payload + edge_cond = z_payload + disp_node_cond = None + disp_edge_cond = None + if node_cond is None: + node_cond = torch.zeros(B, N, self.node_cond_dim, device=device) + if edge_cond is None: + edge_cond = torch.zeros(B, N, N, self.edge_cond_dim, device=device) + if disp_node_cond is None: + disp_node_cond = torch.zeros(B, N, 3, device=device) + if disp_edge_cond is None: + disp_edge_cond = torch.zeros(B, N, N, 1, device=device) + if node_cond.dim() == 2: + node_cond = node_cond[:, None, :].expand(B, N, -1) + if edge_cond.dim() == 2: + edge_cond = edge_cond[:, None, None, :].expand(B, N, N, -1) + self._last_z_requires_grad = bool(node_cond.requires_grad or edge_cond.requires_grad or disp_node_cond.requires_grad or disp_edge_cond.requires_grad) + self._last_z_shape = { + "node_cond": tuple(node_cond.shape), + "edge_cond": tuple(edge_cond.shape), + "disp_node_cond": tuple(disp_node_cond.shape), + "disp_edge_cond": tuple(disp_edge_cond.shape), + } + if self.track_condition_debug: + self._last_z_abs_mean = float( + ((node_cond.detach().float().abs().mean() + + edge_cond.detach().float().abs().mean() + + disp_node_cond.detach().float().abs().mean() + + disp_edge_cond.detach().float().abs().mean()) / 4.0).cpu().item() + ) + + for ca_pos_name, ca_pos in input_features["CA_pos"].items(): + if not self.embed_distogram and ca_pos_name == "trans_equilibrium": + continue + if ( + static is not None + and ca_pos_name == "trans_equilibrium" + and "equilibrium_distogram" in static + ): + z_0.append(static["equilibrium_distogram"]) + else: + ca_dgram = mu.calc_distogram( + ca_pos, + self.model_conf.embed.min_bin_distance, + self.model_conf.embed.max_bin_distance, + self.model_conf.embed.num_bins_distance, + ) + z_0.append(ca_dgram.reshape([B, N**2, -1])) + + if self.embed_direction: + if static is not None and "direction_embedding" in static: + z_0.append(static["direction_embedding"]) + else: + direction_embedding = embed_direction( + input_features["CA_pos"]["trans_equilibrium"], + input_features["rotmats_equilibrium"], + dist_cutoff=self.embed_direction_cutoff + ) + z_0.append(direction_embedding.reshape([B, N**2, -1])) + + + # TODO: get_length_embedding expects a tensor of shape [...,N]. + # It ignores elements and just uses .shape[-1] and device. + # Don't want to change it, so we just pass in an empty tensor. + if static is not None and "length_embedding" in static: + length_embedding = static["length_embedding"] + else: + length_embedding = self.length_embedder( + torch.empty(1, N).to(device=device) + ) + length_embedding = length_embedding.repeat([B, 1, 1]) + h_0.append(length_embedding) + + if self.index_embed_type is None: + pass + elif self.index_embed_type == "full": + if static is not None and "index_node_embedding" in static: + h_0.append(static["index_node_embedding"]) + z_0.append(static["index_edge_embedding"]) + else: + seq_idx = torch.arange(N).repeat(B, 1).to(device=device) + h_0.append(self.index_embedder(seq_idx)) + rel_seq_offset = seq_idx[:, :, None] - seq_idx[:, None, :] + rel_seq_offset = rel_seq_offset.reshape([B, N**2]) + z_0.append(self.linear_relpos(self.index_embedder(rel_seq_offset))) + elif self.index_embed_type == "neighbor": + if static is not None and "index_edge_embedding" in static: + z_0.append(static["index_edge_embedding"]) + else: + neighbors = torch.diag_embed(torch.ones(N-1, device=device), offset=1) + \ + torch.diag_embed(torch.ones(N-1, device=device), offset=-1) + neighbors = neighbors[None].repeat(B, 1, 1).reshape([B, N**2])[...,None] + z_0.append(neighbors) + else: + raise ValueError("index_embed_type must be None/'none', 'full' or 'neighbor'.") + + h_0 = torch.cat(h_0, dim=-1) + h_0 = self.node_embedding(h_0) + if self.inject_embedder: + if static is not None and "node_condition_embedding" in static: + h_0 = h_0 + static["node_condition_embedding"].to(dtype=h_0.dtype) + else: + h_0 = h_0 + self.z_node_adapter(node_cond.to(dtype=h_0.dtype)) + h_0 = h_0 + self.disp_node_adapter(disp_node_cond.to(dtype=h_0.dtype)) + + z_0.append(self._cross_concat(self.linear_s_p(h_0), B, N)) + + z_0 = torch.cat(z_0, dim=-1) + z_0 = self.edge_embedding(z_0) + z_0 = z_0.reshape([B, N, N, -1]) + if self.inject_embedder: + if static is not None and "edge_condition_embedding" in static: + z_0 = z_0 + static["edge_condition_embedding"].to(dtype=z_0.dtype) + else: + z_0 = z_0 + self.z_edge_adapter(edge_cond.to(dtype=z_0.dtype)) + z_0 = z_0 + self.disp_edge_adapter(disp_edge_cond.to(dtype=z_0.dtype)) + + return h_0, z_0 + + def _cross_concat(self, feats_1d, B, N): + return torch.cat([ + feats_1d[:, :, None, :].expand(-1, -1, N, -1), + feats_1d[:, None, :, :].expand(-1, N, -1, -1), + ], dim=-1).float().reshape([B, N**2, -1]) + diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/latent.py b/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/latent.py new file mode 100644 index 0000000000000000000000000000000000000000..b5405820308130a8ce18741fb0063ee5350d3a4d --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/latent.py @@ -0,0 +1,1317 @@ +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from bbflow.data.alignment import kabsch_align + +class _MotionPriorBlock(nn.Module): + """Single edge/node message passing block for the motion prior.""" + + def __init__(self, hidden_dim): + super().__init__() + self.edge_norm = nn.LayerNorm(3 * hidden_dim) + self.node_norm = nn.LayerNorm(2 * hidden_dim) + self.edge_update = nn.Sequential( + nn.Linear(3 * hidden_dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + ) + self.node_update = nn.Sequential( + nn.Linear(2 * hidden_dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + ) + + def forward(self, node_state, edge_state, pair_mask): + pair_mask = pair_mask[..., None] + masked_edge = edge_state * pair_mask + + src = node_state[:, :, None, :].expand(-1, -1, node_state.shape[1], -1) + dst = node_state[:, None, :, :].expand(-1, node_state.shape[1], -1, -1) + + edge_input = torch.cat([masked_edge, src, dst], dim=-1) + edge_state = edge_state + self.edge_update(self.edge_norm(edge_input)) + edge_state = edge_state * pair_mask + + node_mask = pair_mask.squeeze(-1).sum(dim=2).clamp_min(1.0)[..., None] + incoming = (edge_state * pair_mask).sum(dim=2) / node_mask + outgoing = (edge_state * pair_mask).sum(dim=1) / node_mask + node_input = torch.cat([incoming, outgoing], dim=-1) + node_state = node_state + self.node_update(self.node_norm(node_input)) + return node_state, edge_state + + +class LatentEncoder(nn.Module): + """Equilibrium-conditioned template-mode motion prior. + + The prior predicts K global template motion fields from x_eq. Each mode has a + shared template generated by omega/v/center plus signed per-residue participation + and a small local-frame residual. The resulting modes reconstruct local/cross + covariance targets and provide node/edge conditions for BBFlow adapters. + """ + + def __init__(self, latent_cfg): + super().__init__() + self.dim = int(getattr(latent_cfg, "dim", 16)) + self.num_modes = int(getattr(latent_cfg, "num_modes", 8)) + self.node_cond_dim = self.num_modes + self.edge_cond_dim = self.num_modes + self.z_stochastic = False + hidden_dim = int(getattr(latent_cfg, "motion_hidden_dim", 128)) + dist_bins = int(getattr(latent_cfg, "motion_dist_bins", 16)) + self.register_buffer("dist_centers", torch.linspace(0.0, 40.0, dist_bins)) + self.dist_width = float(getattr(latent_cfg, "motion_dist_width", 4.0)) + # Raised 1e-6 -> 1e-4 (norm floor 1e-3 -> 1e-2): bounds how far a collapsing + # mode's normalization can amplify in the forward, hardening against overflow + # in the u^4 covariance terms under bf16. + self.mode_norm_eps = float(getattr(latent_cfg, "mode_norm_eps", 1e-4)) + self.cross_cov_near_distance = float(getattr(latent_cfg, "cross_cov_near_distance", 12.0)) + self.pca_align_top_m = int(getattr(latent_cfg, "pca_align_top_m", 2)) + if bool(getattr(latent_cfg, "use_enm_features", False)): + raise ValueError("ENM cannot be used as a forward feature; use experiment.training.enm_warmup_epochs for ENM initialization only.") + self.use_enm_features = False + self.enm_num_modes = int(getattr(latent_cfg, "enm_num_modes", self.num_modes)) + self.enm_cutoff = float(getattr(latent_cfg, "enm_cutoff", 12.0)) + self.enm_eps = float(getattr(latent_cfg, "enm_eps", 1e-6)) + self.mixture_components = int(getattr(latent_cfg, "mixture_components", 2)) + self.q_lstsq_ridge = float(getattr(latent_cfg, "q_lstsq_ridge", 1e-4)) + self.q_cholesky_jitter = float(getattr(latent_cfg, "q_cholesky_jitter", 1e-4)) + self.q_detach_projection = bool(getattr(latent_cfg, "q_detach_projection", True)) + self.q_detach_shared_encoder = bool( + getattr(latent_cfg, "q_detach_shared_encoder", False) + ) + self.sample_coefficients = bool(getattr(latent_cfg, "sample_coefficients", False)) + self.energy_from_q = bool(getattr(latent_cfg, "energy_from_q", False)) + self.energy_from_q_full_cov = bool(getattr(latent_cfg, "energy_from_q_full_cov", False)) + tril = torch.tril_indices(self.num_modes, self.num_modes) + self.register_buffer("mixture_tril_rows", tril[0], persistent=False) + self.register_buffer("mixture_tril_cols", tril[1], persistent=False) + + # The scalar prior encoder must be rotation-invariant. Vector quantities + # are recovered later as weighted sums of coordinates or local-frame + # residuals; feeding raw coordinates/rotations here breaks equivariance. + node_in = 1 + 21 + dist_bins + pair_in = dist_bins + self.prior_node_mlp = nn.Sequential( + nn.Linear(node_in, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + ) + self.prior_pair_mlp = nn.Sequential( + nn.Linear(pair_in, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + ) + self.motion_message_passing_layers = int(getattr(latent_cfg, "motion_message_passing_layers", 4)) + self.prior_message_passing_layers = nn.ModuleList( + [_MotionPriorBlock(hidden_dim) for _ in range(self.motion_message_passing_layers)] + ) + self.prior_update = nn.Sequential( + nn.Linear(2 * hidden_dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + ) + self.energy_out = nn.Sequential( + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, self.num_modes), + ) + self.template_residual_scale = float(getattr(latent_cfg, "template_residual_scale", 0.1)) + self.template_remove_rotation = bool(getattr(latent_cfg, "template_remove_rotation", True)) + self.template_center_logits = nn.Linear(hidden_dim, self.num_modes) + self.template_omega_logits = nn.Linear(hidden_dim, self.num_modes) + self.template_velocity_logits = nn.Linear(hidden_dim, self.num_modes) + self.template_participation = nn.Linear(hidden_dim, self.num_modes) + self.template_residual = nn.Linear(hidden_dim, self.num_modes * 3) + self.mixture_logits_out = nn.Linear(hidden_dim, self.mixture_components) + self.mixture_mu_out = nn.Linear(hidden_dim, self.mixture_components * self.num_modes) + self.mixture_tril_out = nn.Linear( + hidden_dim, + self.mixture_components * (self.num_modes * (self.num_modes + 1) // 2), + ) + + @staticmethod + def _masked_mean(x, mask): + denom = mask.sum(dim=1, keepdim=True).clamp_min(1.0) + return (x * mask[..., None]).sum(dim=1) / denom + + @staticmethod + def _masked_std(x, mask): + mean = LatentEncoder._masked_mean(x[..., None], mask).squeeze(-1) + denom = mask.sum(dim=1).clamp_min(1.0) + var = (((x - mean[:, None]) ** 2) * mask).sum(dim=1) / denom + return torch.sqrt(var.clamp_min(1e-12)) + + @staticmethod + def align_to_reference(trans, ref_trans, res_mask): + return kabsch_align(trans, ref_trans, res_mask) + + @staticmethod + def relative_displacement(trans, ref_trans, res_mask): + aligned = LatentEncoder.align_to_reference(trans, ref_trans, res_mask) + if ref_trans.dim() == 2: + ref_trans = ref_trans.unsqueeze(0).expand_as(aligned) + return aligned - ref_trans + + @staticmethod + def _group_mean(x, group_index): + groups = torch.unique(group_index, sorted=True) + pooled = [] + for group in groups: + pooled.append(x[group_index == group].mean(dim=0)) + return torch.stack(pooled, dim=0), groups + + def _pair_rbf(self, trans_eq, res_mask): + with torch.autocast(device_type=trans_eq.device.type, enabled=False): + trans = trans_eq.float() + dists = torch.cdist(trans, trans) + centers = self.dist_centers.to(device=trans_eq.device, dtype=torch.float32) + rbf = torch.exp(-((dists[..., None] - centers) / self.dist_width) ** 2) + pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :] + return rbf.to(dtype=trans_eq.dtype), pair_mask.to(dtype=trans_eq.dtype) + + def _pair_distance_features(self, trans_eq, res_mask): + rbf, pair_mask = self._pair_rbf(trans_eq, res_mask) + denom = pair_mask.sum(dim=2, keepdim=True).clamp_min(1.0) + return (rbf * pair_mask[..., None]).sum(dim=2) / denom + + def _enm_modes_and_weights_single(self, coords, mask): + valid = mask.bool() + n_total = coords.shape[0] + out = coords.new_zeros(n_total, self.enm_num_modes, 3, dtype=torch.float32) + weights = coords.new_zeros(self.enm_num_modes, dtype=torch.float32) + coords_valid = coords[valid].float() + n_valid = coords_valid.shape[0] + if n_valid < 3: + return out, weights + + diff = coords_valid[:, None, :] - coords_valid[None, :, :] + dist = torch.linalg.norm(diff, dim=-1).clamp_min(self.enm_eps) + contact = (dist < self.enm_cutoff) & (~torch.eye(n_valid, device=coords.device, dtype=torch.bool)) + if not contact.any(): + return out, weights + + unit = diff / dist[..., None] + outer = unit[..., :, None] * unit[..., None, :] + off_diag = -outer * contact[..., None, None].float() + h_blocks = off_diag.clone() + diag_blocks = -off_diag.sum(dim=1) + idx = torch.arange(n_valid, device=coords.device) + h_blocks[idx, idx] = diag_blocks + hessian = h_blocks.permute(0, 2, 1, 3).reshape(3 * n_valid, 3 * n_valid) + hessian = 0.5 * (hessian + hessian.transpose(0, 1)) + + evals, evecs = torch.linalg.eigh(hessian) + start = min(6, evecs.shape[1]) + stop = min(start + self.enm_num_modes, evecs.shape[1]) + if stop <= start: + return out, weights + modes = evecs[:, start:stop].reshape(n_valid, 3, stop - start).permute(0, 2, 1).contiguous() + inv_evals = 1.0 / evals[start:stop].float().clamp_min(self.enm_eps) + inv_evals = inv_evals / inv_evals.mean().clamp_min(self.enm_eps) + + flat = modes.reshape(modes.shape[0], modes.shape[1], 3) + for mode_idx in range(modes.shape[1]): + values = flat[:, mode_idx, :].reshape(-1) + max_idx = values.abs().argmax() + sign = torch.sign(values[max_idx]).clamp_min(0.0) * 2.0 - 1.0 + modes[:, mode_idx, :] = modes[:, mode_idx, :] * sign + out[valid, :modes.shape[1], :] = modes + weights[:modes.shape[1]] = inv_evals + return out, weights + + def _enm_modes_single(self, coords, mask): + modes, _ = self._enm_modes_and_weights_single(coords, mask) + return modes + + def _enm_modes_batch(self, trans_eq, res_mask): + modes = [] + with torch.no_grad(), torch.autocast(device_type=trans_eq.device.type, enabled=False): + for coords, mask in zip(trans_eq.float(), res_mask.float()): + modes.append(self._enm_modes_single(coords, mask)) + return torch.stack(modes, dim=0).to(device=trans_eq.device, dtype=torch.float32) + + def _enm_modes_and_weights_batch(self, trans_eq, res_mask): + modes = [] + weights = [] + with torch.no_grad(), torch.autocast(device_type=trans_eq.device.type, enabled=False): + for coords, mask in zip(trans_eq.float(), res_mask.float()): + mode, weight = self._enm_modes_and_weights_single(coords, mask) + modes.append(mode) + weights.append(weight) + return ( + torch.stack(modes, dim=0).to(device=trans_eq.device, dtype=torch.float32), + torch.stack(weights, dim=0).to(device=trans_eq.device, dtype=torch.float32), + ) + + def _enm_motion_targets(self, trans_eq, res_mask): + modes, energy = self._enm_modes_and_weights_batch(trans_eq, res_mask) + if modes.shape[2] < self.num_modes: + pad = modes.new_zeros(modes.shape[0], modes.shape[1], self.num_modes - modes.shape[2], 3) + modes = torch.cat([modes, pad], dim=2) + energy = torch.cat([energy, energy.new_zeros(energy.shape[0], self.num_modes - energy.shape[1])], dim=1) + modes = modes[:, :, : self.num_modes, :] + energy = energy[:, : self.num_modes] + mask = res_mask.float() + local_cov = torch.einsum("bk,bnki,bnkj->bnij", energy, modes, modes) * mask[:, :, None, None] + cross_cov = torch.einsum("bk,bikd,bjkd->bij", energy, modes, modes) * mask[:, :, None] * mask[:, None, :] + rmsf = torch.sqrt(torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)) * mask + return { + "enm_modes": modes, + "enm_energy": energy, + "local_cov": local_cov, + "cross_cov": cross_cov, + "rmsf": rmsf, + } + def _enm_node_features(self, trans_eq, rotmats_eq, res_mask): + del rotmats_eq + enm_global = self._enm_modes_batch(trans_eq, res_mask) + enm_mag = torch.linalg.norm(enm_global, dim=-1) * res_mask.float()[:, :, None] + return enm_mag.to(dtype=trans_eq.dtype) + + def _enm_pair_features(self, trans_eq, res_mask): + enm_global = self._enm_modes_batch(trans_eq, res_mask) + enm_pair = torch.einsum("bikd,bjkd->bijk", enm_global, enm_global) + pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :] + return (enm_pair * pair_mask[..., None]).to(dtype=trans_eq.dtype) + + def _equilibrium_node_feature_segments(self, trans_eq, rotmats_eq, seq, res_mask): + center = self._masked_mean(trans_eq, res_mask) + centered = trans_eq - center[:, None, :] + radius = torch.linalg.norm(centered, dim=-1, keepdim=True) + dist_feat = self._pair_distance_features(trans_eq, res_mask).to(dtype=trans_eq.dtype) + segments = [ + ("radius_from_center", radius), + ("sequence_onehot", seq), + ("pair_distance_rbf_mean", dist_feat), + ] + return segments + + def _equilibrium_node_features(self, trans_eq, rotmats_eq, seq, res_mask): + segments = self._equilibrium_node_feature_segments(trans_eq, rotmats_eq, seq, res_mask) + return torch.cat([tensor for _, tensor in segments], dim=-1) + + def prior_feature_breakdown(self, trans_eq, rotmats_eq, seq, res_mask): + segments = self._equilibrium_node_feature_segments(trans_eq, rotmats_eq, seq, res_mask) + rows = [] + start = 0 + for name, tensor in segments: + dim = int(tensor.shape[-1]) + end = start + dim + valid = tensor[res_mask.bool()] + rows.append({ + "name": name, + "start": start, + "end": end, + "dim": dim, + "shape": list(tensor.shape), + "mean_abs": float(valid.detach().float().abs().mean().cpu().item()) if valid.numel() else 0.0, + "std": float(valid.detach().float().std().cpu().item()) if valid.numel() > 1 else 0.0, + }) + start = end + node_features = torch.cat([tensor for _, tensor in segments], dim=-1) + expected_dim = int(self.prior_node_mlp[0].in_features) + return { + "segments": rows, + "total_dim": int(node_features.shape[-1]), + "expected_prior_node_in": expected_dim, + "matches_prior_node_in": int(node_features.shape[-1]) == expected_dim, + "order": [name for name, _ in segments], + } + + def _encode_equilibrium(self, trans_eq, rotmats_eq, seq, res_mask): + node_features = self._equilibrium_node_features(trans_eq, rotmats_eq, seq, res_mask) + node_state = self.prior_node_mlp(node_features) + pair_rbf, pair_mask = self._pair_rbf(trans_eq, res_mask) + pair_features = pair_rbf + edge_state = self.prior_pair_mlp(pair_features.to(dtype=node_state.dtype)) + pair_mask = pair_mask.to(dtype=node_state.dtype) + for block in self.prior_message_passing_layers: + node_state, edge_state = block(node_state, edge_state, pair_mask) + denom = pair_mask.sum(dim=2, keepdim=True).clamp_min(1.0) + pair_context = (edge_state * pair_mask[..., None]).sum(dim=2) / denom + return self.prior_update(torch.cat([node_state, pair_context], dim=-1)) + + @staticmethod + def _masked_mode_softmax(logits, res_mask): + mask = res_mask.bool()[:, None, :] + logits = logits.float().masked_fill(~mask, -1e9) + return torch.softmax(logits, dim=-1) + + @staticmethod + def _global_to_local(u_global, rotmats_eq): + return torch.einsum("bnij,bnki->bnkj", rotmats_eq.float(), u_global.float()) + + @staticmethod + def _rotation_design(coords): + x, y, z = coords.unbind(dim=-1) + zeros = torch.zeros_like(x) + return torch.stack([ + torch.stack([zeros, z, -y], dim=-1), + torch.stack([-z, zeros, x], dim=-1), + torch.stack([y, -x, zeros], dim=-1), + ], dim=-2) + def _fit_rigid_motion(self, u_global, centered_coords, res_mask): + mask = res_mask.float() + translation = (u_global.float() * mask[:, :, None, None]).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)[:, None, None] + centered = (u_global.float() - translation[:, None, :, :]) * mask[:, :, None, None] + eye = torch.eye(3, device=u_global.device, dtype=torch.float32) + omega_out = [] + rigid_out = [] + coords = centered_coords.float() + for batch_idx in range(u_global.shape[0]): + valid = res_mask[batch_idx].bool() + if valid.sum() < 3: + omega_out.append(u_global.new_zeros(self.num_modes, 3)) + rigid_out.append(centered[batch_idx]) + continue + design = self._rotation_design(coords[batch_idx, valid]).reshape(-1, 3) + gram = design.transpose(0, 1) @ design + 1e-4 * eye + mode_omegas = [] + mode_rigid = [] + for mode_idx in range(self.num_modes): + target = centered[batch_idx, valid, mode_idx].reshape(-1) + rhs = design.transpose(0, 1) @ target + omega = torch.linalg.solve(gram, rhs) + rigid = (design @ omega).reshape(-1, 3) + full = centered[batch_idx, :, mode_idx].clone() + full[valid] = centered[batch_idx, valid, mode_idx] - rigid + mode_omegas.append(omega) + mode_rigid.append(full) + omega_out.append(torch.stack(mode_omegas, dim=0)) + rigid_out.append(torch.stack(mode_rigid, dim=1)) + return translation, torch.stack(omega_out, dim=0), torch.stack(rigid_out, dim=0) + + def _remove_rigid_component(self, u_global, centered_coords, res_mask): + translation, _, cleaned = self._fit_rigid_motion(u_global, centered_coords, res_mask) + del translation + return cleaned * res_mask.float()[:, :, None, None] + def _mixture_params(self, pooled): + logits = self.mixture_logits_out(pooled) + mu = self.mixture_mu_out(pooled).reshape( + pooled.shape[0], self.mixture_components, self.num_modes + ) + raw_tril = self.mixture_tril_out(pooled).reshape( + pooled.shape[0], + self.mixture_components, + self.num_modes * (self.num_modes + 1) // 2, + ) + scale_tril = raw_tril.new_zeros( + pooled.shape[0], self.mixture_components, self.num_modes, self.num_modes + ) + rows = self.mixture_tril_rows.to(device=raw_tril.device) + cols = self.mixture_tril_cols.to(device=raw_tril.device) + scale_tril[:, :, rows, cols] = raw_tril + diag = torch.diagonal(scale_tril, dim1=-2, dim2=-1) + scale_tril = scale_tril - torch.diag_embed(diag) + scale_tril = scale_tril + torch.diag_embed(F.softplus(diag) + self.q_cholesky_jitter) + return { + "mixture_logits": logits, + "mixture_log_probs": F.log_softmax(logits.float(), dim=-1).to(dtype=logits.dtype), + "mixture_mu": mu, + "mixture_scale_tril": scale_tril, + } + + @staticmethod + def _mixture_entropy(logits): + probs = torch.softmax(logits.float(), dim=-1) + return -(probs * probs.clamp_min(1e-8).log()).sum(dim=-1) + + @staticmethod + def mixture_second_moment(condition): + logits = condition["mixture_logits"].float() + mu = condition["mixture_mu"].float() + scale_tril = condition["mixture_scale_tril"].float() + probs = torch.softmax(logits, dim=-1) + cov = torch.einsum("bmik,bmjk->bmij", scale_tril, scale_tril) + second = cov + torch.einsum("bmi,bmj->bmij", mu, mu) + return torch.einsum("bm,bmij->bij", probs, second) + + def mixture_nll(self, condition, coefficients): + coefficients = coefficients.float() + logits = condition["mixture_logits"].float() + mu = condition["mixture_mu"].float() + scale_tril = condition["mixture_scale_tril"].float() + diff = coefficients[:, None, :] - mu + solved = torch.linalg.solve_triangular( + scale_tril, + diff[..., None], + upper=False, + ).squeeze(-1) + maha = solved.square().sum(dim=-1) + logdet = torch.diagonal(scale_tril, dim1=-2, dim2=-1).clamp_min(1e-8).log().sum(dim=-1) + normalizer = self.num_modes * math.log(2.0 * math.pi) + comp_log_prob = -0.5 * (normalizer + maha) - logdet + log_prob = torch.logsumexp(F.log_softmax(logits, dim=-1) + comp_log_prob, dim=-1) + return -log_prob.mean() + + def sample_coefficients_from_q(self, condition): + logits = condition["mixture_logits"].float() + mu = condition["mixture_mu"].float() + scale_tril = condition["mixture_scale_tril"].float() + component = torch.distributions.Categorical(logits=logits).sample() + batch = torch.arange(logits.shape[0], device=logits.device) + selected_mu = mu[batch, component] + selected_scale = scale_tril[batch, component] + eps = torch.randn_like(selected_mu) + coeff = selected_mu + torch.einsum("bij,bj->bi", selected_scale, eps) + return coeff.to(dtype=condition["u_global"].dtype), component + + def _condition_from_modes(self, u_global, rotmats_eq, res_mask, h, extra=None): + mask = res_mask.float()[:, :, None] + mode_norm = torch.sqrt( + ((u_global.float().square().sum(dim=-1) * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)).clamp_min(self.mode_norm_eps) + ) + # Stop-gradient on the gauge norm. Backprop through 1/mode_norm carries a + # 1/mode_norm^2 term that explodes once a mode collapses (norm -> the eps + # floor), which blows up the shared encoder into NaN. Detaching keeps the + # forward normalization identical while removing that runaway gradient. + u_global = u_global.float() / mode_norm.detach()[:, None, :, None] + u_local = self._global_to_local(u_global, rotmats_eq) + pooled = self._masked_mean(h, res_mask) + q_pooled = pooled.detach() if self.q_detach_shared_encoder else pooled + mixture = self._mixture_params(q_pooled) + q_second_moment = self.mixture_second_moment(mixture) + raw_energy = F.softplus(self.energy_out(pooled)) + 1e-6 + if self.energy_from_q or self.energy_from_q_full_cov: + energy = torch.diagonal(q_second_moment, dim1=-2, dim2=-1).clamp_min(1e-8) + energy = energy + raw_energy * 0.0 + else: + energy = raw_energy + sqrt_energy = torch.sqrt(energy).to(dtype=u_local.dtype) + node_cond = torch.linalg.norm(u_global.float(), dim=-1).to(dtype=u_local.dtype) * sqrt_energy[:, None, :] + disp_global = torch.einsum("bk,bnkd->bnd", sqrt_energy.float(), u_global.float()) + disp_local = torch.einsum("bnij,bni->bnj", rotmats_eq.float(), disp_global) + disp_local = disp_local * res_mask.float()[:, :, None] + disp_edge_cond = torch.einsum("bid,bjd->bij", disp_global, disp_global)[:, :, :, None] + pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :] + disp_edge_cond = disp_edge_cond * pair_mask[:, :, :, None] + dot = torch.einsum("bikd,bjkd->bijk", u_global.float(), u_global.float()) + edge_cond = dot.to(dtype=u_local.dtype) * energy[:, None, None, :].to(dtype=u_local.dtype) + if self.energy_from_q_full_cov: + local_cov_pred = torch.einsum( + "bkl,bnki,bnlj->bnij", + q_second_moment, + u_global.float(), + u_global.float(), + ) + cross_cov_pred = torch.einsum( + "bkl,bikd,bjld->bij", + q_second_moment, + u_global.float(), + u_global.float(), + ) + else: + local_cov_pred = torch.einsum("bk,bnki,bnkj->bnij", energy.float(), u_global.float(), u_global.float()) + cross_cov_pred = edge_cond.float().sum(dim=-1) + rmsf_pred = torch.sqrt(torch.diagonal(local_cov_pred, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)) + condition = { + "node_cond": node_cond, + "edge_cond": edge_cond, + "disp_node_cond": disp_local.to(dtype=rotmats_eq.dtype), + "disp_edge_cond": disp_edge_cond.to(dtype=rotmats_eq.dtype), + "u_local": u_local.to(dtype=rotmats_eq.dtype), + "u_global": u_global.to(dtype=rotmats_eq.dtype), + "energy": energy.to(dtype=rotmats_eq.dtype), + "mode_norm": mode_norm.to(dtype=rotmats_eq.dtype), + "local_cov_pred": local_cov_pred.to(dtype=rotmats_eq.dtype), + "cross_cov_pred": cross_cov_pred.to(dtype=rotmats_eq.dtype), + "rmsf_pred": rmsf_pred.to(dtype=rotmats_eq.dtype), + "q_second_moment": q_second_moment.to(dtype=rotmats_eq.dtype), + } + condition.update(mixture) + + if extra: + condition.update(extra) + return condition + + def condition_from_mode_coefficients( + self, + u_global, + coefficients, + rotmats_eq, + res_mask, + extra=None, + include_statistics=True, + ): + """Build a sample-specific condition from fixed modes and per-frame coefficients. + + Per-frame training uses signed mode coordinates c* from the current MD frame, + giving d_i = sum_k c*_k U_k[i] rather than a static sqrt(energy) field. + """ + mask = res_mask.float()[:, :, None] + u_global = u_global.float() + coefficients = coefficients.float() + mode_norm = torch.sqrt( + ((u_global.square().sum(dim=-1) * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)).clamp_min(self.mode_norm_eps) + ) + # Stop-gradient on the gauge norm (same 1/mode_norm^2 explosion as above). + # Detaching in BOTH the division and the compensating multiply leaves the + # forward product coeff*u_global identical while removing the runaway gradient. + mode_norm_sg = mode_norm.detach() + u_global = u_global / mode_norm_sg[:, None, :, None] + coefficients = coefficients * mode_norm_sg + u_local = self._global_to_local(u_global, rotmats_eq) + coeff_abs = coefficients.abs().to(dtype=u_local.dtype) + node_cond = torch.linalg.norm(u_global, dim=-1).to(dtype=u_local.dtype) * coeff_abs[:, None, :] + disp_global = torch.einsum("bk,bnkd->bnd", coefficients, u_global) + disp_local = torch.einsum("bnij,bni->bnj", rotmats_eq.float(), disp_global) + disp_local = disp_local * res_mask.float()[:, :, None] + pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :] + disp_edge_cond = torch.einsum("bid,bjd->bij", disp_global, disp_global)[:, :, :, None] + disp_edge_cond = disp_edge_cond * pair_mask[:, :, :, None] + dot = torch.einsum("bikd,bjkd->bijk", u_global, u_global) + edge_cond = dot.to(dtype=u_local.dtype) * coefficients.square()[:, None, None, :].to(dtype=u_local.dtype) + energy = coefficients.square() + condition = { + "node_cond": node_cond, + "edge_cond": edge_cond, + "disp_node_cond": disp_local.to(dtype=rotmats_eq.dtype), + "disp_edge_cond": disp_edge_cond.to(dtype=rotmats_eq.dtype), + "u_local": u_local.to(dtype=rotmats_eq.dtype), + "u_global": u_global.to(dtype=rotmats_eq.dtype), + "energy": energy.to(dtype=rotmats_eq.dtype), + "mode_coefficients": coefficients.to(dtype=rotmats_eq.dtype), + "mode_norm": mode_norm.to(dtype=rotmats_eq.dtype), + } + if include_statistics: + local_cov_pred = torch.einsum( + "bk,bnki,bnkj->bnij", energy, u_global, u_global + ) + condition.update({ + "local_cov_pred": local_cov_pred.to(dtype=rotmats_eq.dtype), + "cross_cov_pred": edge_cond.float().sum(dim=-1).to(dtype=rotmats_eq.dtype), + "rmsf_pred": torch.sqrt( + torch.diagonal(local_cov_pred, dim1=-2, dim2=-1) + .sum(dim=-1) + .clamp_min(1e-8) + ).to(dtype=rotmats_eq.dtype), + }) + if extra: + condition.update(extra) + return condition + + def oracle_condition_from_targets(self, trans_1, trans_eq, rotmats_eq, res_mask, targets): + modes = targets["oracle_modes"].to(device=trans_eq.device, dtype=torch.float32) + mean_disp = targets.get("oracle_mean_disp") + if mean_disp is None: + mean_disp = torch.zeros_like(trans_eq, dtype=torch.float32) + else: + mean_disp = mean_disp.to(device=trans_eq.device, dtype=torch.float32) + disp = self.relative_displacement(trans_1.float(), trans_eq.float(), res_mask) + centered_disp = (disp - mean_disp) * res_mask.float()[:, :, None] + coefficients = self.project_displacement_to_modes(centered_disp, modes, res_mask) + recon = torch.einsum("bk,bnkd->bnd", coefficients.float(), modes.float()) + return self.condition_from_mode_coefficients( + modes, + coefficients, + rotmats_eq, + res_mask, + extra={ + "oracle_centered_disp": centered_disp.to(dtype=rotmats_eq.dtype), + "oracle_recon_disp": recon.to(dtype=rotmats_eq.dtype), + }, + ) + + def frame_condition_from_projection( + self, + trans_1, + trans_eq, + rotmats_eq, + res_mask, + prior_condition, + mean_disp=None, + ): + """Project the frame's centered fluctuation onto predicted motion modes. + + Motion covariance targets are centered over MD time, so the coefficient + target must remove the same per-protein mean displacement. The solve uses + detached modes by default, while flow loss still reaches the original modes + through the reconstructed generator condition. + """ + raw_disp = self.relative_displacement(trans_1.float(), trans_eq.float(), res_mask) + mask = res_mask.float()[:, :, None] + if mean_disp is None: + raise ValueError( + "per-frame mode projection requires oracle_mean_disp in the motion-target cache; " + "regenerate the cache or use one that contains centered MD targets" + ) + mean_disp = mean_disp.to(device=raw_disp.device, dtype=raw_disp.dtype) + disp = (raw_disp - mean_disp) * mask + coefficients = self.project_displacement_lstsq( + disp, + prior_condition["u_global"], + res_mask, + ridge=self.q_lstsq_ridge, + detach_modes=self.q_detach_projection, + ) + recon_objective = self.projection_reconstruction_objective( + disp, + prior_condition["u_global"], + coefficients, + res_mask, + ridge=self.q_lstsq_ridge, + ) + recon = recon_objective["recon"] + uncentered_error = ((raw_disp - recon).square() * mask).sum(dim=(1, 2)).sqrt() + uncentered_denom = (raw_disp.square() * mask).sum(dim=(1, 2)).sqrt().clamp_min(1e-8) + passthrough = { + key: prior_condition[key] + for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"] + if key in prior_condition + } + condition = self.condition_from_mode_coefficients( + prior_condition["u_global"], + coefficients, + rotmats_eq, + res_mask, + extra=passthrough, + include_statistics=False, + ) + condition["projection_uncentered_target_disp"] = raw_disp.to(dtype=rotmats_eq.dtype) + condition["projection_mean_disp"] = mean_disp.to(dtype=rotmats_eq.dtype) + condition["projection_target_disp"] = disp.to(dtype=rotmats_eq.dtype) + condition["projection_recon_disp"] = recon.to(dtype=rotmats_eq.dtype) + condition["projection_recon_loss"] = recon_objective["loss"].to(dtype=rotmats_eq.dtype) + condition["projection_recon_rel_error"] = recon_objective["rel_error"].to(dtype=rotmats_eq.dtype) + condition["projection_uncentered_recon_rel_error"] = ( + uncentered_error / uncentered_denom + ).to(dtype=rotmats_eq.dtype) + return condition, coefficients + + def _mode_predictions(self, h, trans_eq, rotmats_eq, res_mask): + center = self._masked_mean(trans_eq.float(), res_mask) + centered = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None] + + residual_local = torch.tanh(self.template_residual(h).reshape(h.shape[0], h.shape[1], self.num_modes, 3)) + residual_global = torch.einsum("bnij,bnkj->bnki", rotmats_eq.float(), residual_local.float()) + residual_global = self.template_residual_scale * residual_global + + center_logits = self.template_center_logits(h).transpose(1, 2) + omega_logits = self.template_omega_logits(h).transpose(1, 2) + velocity_logits = self.template_velocity_logits(h).transpose(1, 2) + center_weights = self._masked_mode_softmax(center_logits, res_mask) + omega_weights = self._masked_mode_softmax(omega_logits, res_mask) + velocity_weights = self._masked_mode_softmax(velocity_logits, res_mask) + + mode_center = torch.einsum("bkn,bnd->bkd", center_weights, centered) + omega = torch.einsum("bkn,bnd->bkd", omega_weights, centered) + velocity = torch.einsum("bkn,bnd->bkd", velocity_weights, centered) + participation = self.template_participation(h) + + rel = centered[:, :, None, :] - mode_center[:, None, :, :] + base = torch.cross(omega[:, None, :, :].expand_as(rel), rel, dim=-1) + velocity[:, None, :, :] + u_global = participation[..., None].float() * base + residual_global + u_global = self._remove_rigid_component(u_global, centered, res_mask) + extra = { + "template_center": mode_center.to(dtype=rotmats_eq.dtype), + "template_omega": omega.to(dtype=rotmats_eq.dtype), + "template_velocity": velocity.to(dtype=rotmats_eq.dtype), + "template_participation": participation.to(dtype=rotmats_eq.dtype), + "template_residual_global": residual_global.to(dtype=rotmats_eq.dtype), + } + return self._condition_from_modes(u_global, rotmats_eq, res_mask, h, extra=extra) + + def forward_prior(self, trans_eq, rotmats_eq, seq, res_mask): + h = self._encode_equilibrium(trans_eq, rotmats_eq, seq, res_mask) + return self._mode_predictions(h, trans_eq, rotmats_eq, res_mask), None + + def sample_prior_z(self, trans_eq, rotmats_eq, seq, res_mask): + condition, _ = self.forward_prior(trans_eq, rotmats_eq, seq, res_mask) + if not self.sample_coefficients: + return condition + coefficients, component = self.sample_coefficients_from_q(condition) + sampled = self.condition_from_mode_coefficients( + condition["u_global"], + coefficients, + rotmats_eq, + res_mask, + extra={ + key: condition[key] + for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"] + if key in condition + }, + ) + sampled["sampled_mixture_component"] = component + return sampled + @staticmethod + def repeat_condition(condition, batch_size): + repeated = {} + for key, value in condition.items(): + if torch.is_tensor(value): + repeated[key] = value.repeat(batch_size, *([1] * (value.dim() - 1))) + else: + repeated[key] = value + return repeated + + @staticmethod + def compute_motion_targets(frames_group, x_eq, res_mask, num_modes=8): + """Offline targets from full MD: covariance targets plus oracle PCA modes.""" + with torch.no_grad(): + disp = LatentEncoder.relative_displacement( + frames_group.float(), + x_eq.float(), + res_mask, + ) + if res_mask.dim() == 1: + mask = res_mask.float() + else: + mask = res_mask[0].float() + valid = mask.bool() + disp_centered = disp - disp.mean(dim=0, keepdim=True) + denom = float(max(disp_centered.shape[0] - 1, 1)) + local_cov = torch.einsum("tni,tnj->nij", disp_centered, disp_centered) / denom + cross_cov = torch.einsum("tnd,tmd->nm", disp_centered, disp_centered) / denom + rmsf = torch.sqrt(torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)) + local_var = torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8) + dccm = cross_cov / torch.sqrt(local_var[:, None] * local_var[None, :]).clamp_min(1e-8) + local_cov = local_cov * mask[:, None, None] + cross_cov = cross_cov * mask[:, None] * mask[None, :] + dccm = dccm * mask[:, None] * mask[None, :] + rmsf = rmsf * mask + oracle_modes, oracle_energy = LatentEncoder.pca_modes_from_centered_displacement( + disp_centered, + mask, + num_modes=num_modes, + ) + return { + "local_cov": local_cov.detach().cpu(), + "cross_cov": cross_cov.detach().cpu(), + "dccm": dccm.detach().cpu(), + "rmsf": rmsf.detach().cpu(), + "res_mask": mask.detach().cpu(), + "oracle_modes": oracle_modes.detach().cpu(), + "oracle_energy": oracle_energy.detach().cpu(), + "oracle_mean_disp": (disp.mean(dim=0) * mask[:, None]).detach().cpu(), + "num_res": torch.tensor(int(valid.sum().item()), dtype=torch.long), + } + + @staticmethod + def pca_modes_from_centered_displacement(disp_centered, res_mask, num_modes=8): + mask = res_mask.float() + flat = (disp_centered.float() * mask[None, :, None]).reshape(disp_centered.shape[0], -1) + flat = flat - flat.mean(dim=0, keepdim=True) + if flat.shape[0] < 2 or flat.abs().sum() <= 0: + return ( + disp_centered.new_zeros(disp_centered.shape[1], num_modes, 3), + disp_centered.new_zeros(num_modes), + ) + _, singular_values, vh = torch.linalg.svd(flat, full_matrices=False) + take = min(num_modes, vh.shape[0]) + modes = disp_centered.new_zeros(disp_centered.shape[1], num_modes, 3) + modes[:, :take, :] = vh[:take].reshape(take, disp_centered.shape[1], 3).permute(1, 0, 2) + energy = disp_centered.new_zeros(num_modes) + energy[:take] = singular_values[:take].square() / float(max(flat.shape[0] - 1, 1)) + return modes * mask[:, None, None], energy + + @staticmethod + def project_displacement_to_modes(centered_disp, modes, res_mask): + mask = res_mask.float()[:, :, None, None] + modes = modes.float() * mask + disp = centered_disp.float() * res_mask.float()[:, :, None] + numerator = torch.einsum("bnd,bnkd->bk", disp, modes) + denom = modes.square().sum(dim=(1, 3)).clamp_min(1e-8) + return numerator / denom + + @staticmethod + def mode_orthogonality_loss(modes, res_mask): + """Scale-invariant squared cosine penalty over distinct mode pairs.""" + basis = modes.float() * res_mask.float()[:, :, None, None] + gram = torch.einsum("bnkd,bnld->bkl", basis, basis) + norms = torch.diagonal(gram, dim1=-2, dim2=-1).clamp_min(1e-8).sqrt() + # Detach the per-mode norm in the cosine denominator. Backprop through + # 1/norm carries a 1/norm^2 term (up to ~1e12 at the clamp floor) that + # explodes when a mode collapses, sending a runaway gradient into the + # shared encoder and NaN-ing mixture_logits on the next forward. Detaching + # keeps the forward cosine identical while removing the runaway gradient -- + # the same fix already applied to the gauge norm in _condition_from_modes. + denom = (norms[:, :, None] * norms[:, None, :]).detach() + cosine = gram / denom + eye = torch.eye(gram.shape[-1], device=gram.device, dtype=gram.dtype)[None] + offdiag = 1.0 - eye + return (cosine.square() * offdiag).sum() / ( + offdiag.sum() * gram.shape[0] + ).clamp_min(1.0) + + @staticmethod + def mode_gram_diagnostics(modes, res_mask): + """Measure mode collinearity after masking, without changing the modes.""" + basis = modes.detach().float() * res_mask.float()[:, :, None, None] + gram = torch.einsum("bnkd,bnld->bkl", basis, basis) + eigvals = torch.linalg.eigvalsh(gram) + min_eig = eigvals[:, 0].clamp_min(0.0) + max_eig = eigvals[:, -1].clamp_min(0.0) + condition = max_eig / min_eig.clamp_min(1e-12) + + norms = torch.diagonal(gram, dim1=-2, dim2=-1).clamp_min(1e-12).sqrt() + cosine = gram / (norms[:, :, None] * norms[:, None, :]) + eye = torch.eye(gram.shape[-1], device=gram.device, dtype=torch.bool)[None] + max_cosine = cosine.abs().masked_fill(eye, 0.0).amax(dim=(1, 2)) + return { + "mode_gram_min_eig": min_eig, + "mode_gram_max_eig": max_eig, + "mode_gram_condition": condition, + "mode_max_cosine_abs": max_cosine, + } + + @staticmethod + def project_displacement_lstsq(displacement, modes, res_mask, ridge=1e-4, detach_modes=True): + basis = modes.float() + if detach_modes: + basis = basis.detach() + mask = res_mask.float() + basis = basis * mask[:, :, None, None] + disp = displacement.float() * mask[:, :, None] + gram = torch.einsum("bnkd,bnld->bkl", basis, basis) + rhs = torch.einsum("bnd,bnkd->bk", disp, basis) + eye = torch.eye(modes.shape[2], device=modes.device, dtype=gram.dtype)[None] + # Relative (Levenberg-Marquardt) ridge: an absolute `ridge` (e.g. 1e-4) is + # numerically swallowed in float32 once the unnormalized modes make the gram + # scale large (mode-norm gauge -> gram entries up to ~1e13), leaving a + # near-collinear batch element singular and crashing torch.linalg.solve. + # Scaling the damping by the mean diagonal keeps it effective at every gauge. + scale = torch.diagonal(gram, dim1=-2, dim2=-1).mean(dim=-1).clamp_min(1e-8) + coeff = torch.linalg.solve( + gram + (float(ridge) * scale)[:, None, None] * eye, rhs[..., None] + ).squeeze(-1) + return coeff + + @staticmethod + def projection_reconstruction_objective( + displacement, + modes, + coefficients, + res_mask, + ridge=1e-4, + eps=1e-8, + ): + """Evaluate the ridge least-squares value with stop-gradient coefficients.""" + mask = res_mask.float()[:, :, None] + disp = displacement.float() * mask + basis = modes.float() * mask[:, :, None] + coefficients_for_recon = coefficients.detach().float() + recon = torch.einsum( + "bk,bnkd->bnd", coefficients_for_recon, basis + ) + residual_sq = ((disp - recon).square() * mask).sum(dim=(1, 2)) + target_sq = (disp.square() * mask).sum(dim=(1, 2)).clamp_min(float(eps)) + ridge_sq = float(ridge) * coefficients_for_recon.square().sum(dim=-1) + return { + "loss": (residual_sq + ridge_sq) / target_sq, + "rel_error": torch.sqrt(residual_sq / target_sq), + "recon": recon, + } + + @staticmethod + def _masked_corr(pred, target, mask): + pred = pred.float()[mask.bool()] + target = target.float()[mask.bool()] + if pred.numel() < 2: + return pred.new_zeros(()) + pred = pred - pred.mean() + target = target - target.mean() + denom = pred.norm() * target.norm() + if denom <= 1e-8: + return pred.new_zeros(()) + return (pred * target).sum() / denom + + @staticmethod + def _top_abs_sign_agree(pred, target, mask, fraction=0.1): + pred = pred.float()[mask.bool()] + target = target.float()[mask.bool()] + if pred.numel() == 0: + return pred.new_zeros(()) + k = max(1, int(round(float(pred.numel()) * fraction))) + k = min(k, pred.numel()) + idx = torch.topk(target.abs(), k=k, largest=True).indices + return (torch.sign(pred[idx]) == torch.sign(target[idx])).float().mean() + + def motion_alignment_metrics(self, condition, targets, res_mask, spatial_dists): + with torch.no_grad(): + mask = res_mask.float() + pair_mask = mask[:, :, None] * mask[:, None, :] + eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None] + offdiag_mask = pair_mask * (1.0 - eye) + spatial_dists = spatial_dists.to(device=mask.device, dtype=condition["cross_cov_pred"].dtype) + near_mask = offdiag_mask * (spatial_dists <= self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype) + far_mask = offdiag_mask * (spatial_dists > self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype) + pred = condition["cross_cov_pred"].detach().float() + target = targets["cross_cov"].to(device=pred.device, dtype=pred.dtype) + return { + "cross_cov_corr_all": self._masked_corr(pred, target, offdiag_mask), + "cross_cov_near_corr": self._masked_corr(pred, target, near_mask), + "cross_cov_far_corr": self._masked_corr(pred, target, far_mask), + "cross_cov_near_top10_sign_agree": self._top_abs_sign_agree(pred, target, near_mask), + "cross_cov_far_top10_sign_agree": self._top_abs_sign_agree(pred, target, far_mask), + "cross_cov_near_pred_abs_mean": (pred.abs() * near_mask).sum() / near_mask.sum().clamp_min(1.0), + "cross_cov_near_true_abs_mean": (target.abs() * near_mask).sum() / near_mask.sum().clamp_min(1.0), + "cross_cov_far_pred_abs_mean": (pred.abs() * far_mask).sum() / far_mask.sum().clamp_min(1.0), + "cross_cov_far_true_abs_mean": (target.abs() * far_mask).sum() / far_mask.sum().clamp_min(1.0), + } + + def rigid_component_metrics(self, condition, trans_eq, res_mask): + with torch.no_grad(): + center = self._masked_mean(trans_eq.float(), res_mask) + coords = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None] + translation, omega, _ = self._fit_rigid_motion(condition["u_global"], coords, res_mask) + translation = translation.float() + omega = omega.float() + return { + "rigid_translation_abs_mean": translation.abs().mean(), + "rigid_translation_abs_max": translation.abs().max(), + "rigid_rotation_omega_abs_mean": omega.abs().mean(), + "rigid_rotation_omega_abs_max": omega.abs().max(), + } + + @staticmethod + def _mode_subspace_basis(u_global, res_mask): + mask = res_mask.float()[:, :, None, None] + u = (u_global.float() * mask).permute(0, 2, 1, 3).reshape(u_global.shape[0], u_global.shape[2], -1) + bases = [] + for sample in u: + matrix = sample.transpose(0, 1) + q, _ = torch.linalg.qr(matrix, mode="reduced") + bases.append(q) + return torch.stack(bases, dim=0) + + @staticmethod + def _mode_subspace_loss(pred_modes, target_modes, res_mask): + pred_basis = LatentEncoder._mode_subspace_basis(pred_modes, res_mask) + target_basis = LatentEncoder._mode_subspace_basis(target_modes, res_mask) + overlap = torch.matmul(pred_basis.transpose(-1, -2), target_basis).square().sum(dim=(-1, -2)) + num_modes = pred_basis.shape[-1] + normalized_overlap = (overlap / float(max(num_modes, 1))).clamp(0.0, 1.0) + return 1.0 - normalized_overlap.mean(), normalized_overlap.mean().detach() + + @staticmethod + def _masked_flat_modes(modes, res_mask): + mask = res_mask.float()[:, :, None, None] + modes = modes.float() * mask + return modes.permute(0, 2, 1, 3).reshape(modes.shape[0], modes.shape[2], -1) + + def pca_alignment_loss(self, condition, targets, res_mask, top_m=2): + """Favor assigning high predicted energy to modes aligned with MD top PCs.""" + pred_modes = condition["u_global"].float() + target_modes = targets["oracle_modes"].to( + device=pred_modes.device, + dtype=torch.float32, + ) + top_m = int(max(1, min(top_m, pred_modes.shape[2], target_modes.shape[2]))) + target_modes = target_modes[:, :, :top_m, :] + + pred_flat = F.normalize(self._masked_flat_modes(pred_modes, res_mask), dim=-1, eps=1e-8) + target_basis = self._mode_subspace_basis(target_modes, res_mask) + mode_overlap = torch.matmul(pred_flat, target_basis).square().sum(dim=-1).clamp(0.0, 1.0) + + energy = condition["energy"].float().clamp_min(1e-8) + weights = energy / energy.sum(dim=-1, keepdim=True).clamp_min(1e-8) + weighted_overlap = (weights * mode_overlap).sum(dim=-1) + pca_align_loss = 1.0 - weighted_overlap.mean() + + with torch.no_grad(): + order = torch.argsort(energy, dim=-1, descending=True) + top1_overlap = mode_overlap.gather(1, order[:, :1]).mean() + best_overlap = mode_overlap.max(dim=-1).values.mean() + top_idx = order[:, :top_m] + gather_idx = top_idx[:, None, :, None].expand(-1, pred_modes.shape[1], -1, pred_modes.shape[-1]) + pred_top_modes = pred_modes.gather(2, gather_idx) + _, top_subspace_overlap = self._mode_subspace_loss(pred_top_modes, target_modes, res_mask) + + return { + "pca_align_loss": pca_align_loss, + "pca_align_weighted_overlap": weighted_overlap.detach().mean(), + "pca_align_best_overlap": best_overlap, + "pca_align_top_energy_overlap": top1_overlap, + "pca_align_top_energy_subspace_overlap": top_subspace_overlap, + } + + def enm_initialization_loss(self, condition, trans_eq, res_mask): + """Warmup loss that aligns only the ENM direction subspace. + + ENM is used only as an initialization target. It is not an input feature + and does not appear in the mode forward formula. The projection loss is + invariant to per-mode sign flips and rotations inside a near-degenerate + ENM subspace, unlike ordered mode-by-mode cosine matching. + """ + targets = self._enm_motion_targets(trans_eq, res_mask) + target_modes = targets["enm_modes"].to(device=condition["u_global"].device, dtype=torch.float32) + center = self._masked_mean(trans_eq.float(), res_mask) + centered = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None] + if self.template_remove_rotation: + target_modes = self._remove_rigid_component(target_modes, centered, res_mask) + subspace_loss, subspace_overlap = self._mode_subspace_loss( + condition["u_global"].float(), + target_modes, + res_mask, + ) + with torch.autocast(device_type=trans_eq.device.type, enabled=False): + spatial_dists = torch.cdist(trans_eq.float(), trans_eq.float()) + align = self.motion_alignment_metrics(condition, targets, res_mask, spatial_dists) + metrics = { + "enm_warmup_loss": subspace_loss, + "enm_warmup_subspace_loss": subspace_loss.detach(), + "enm_warmup_subspace_overlap": subspace_overlap, + } + metrics.update({f"enm_warmup_{key}": value for key, value in align.items()}) + + return metrics + def motion_recon_loss(self, condition, targets, res_mask, spatial_dists=None): + mask = res_mask.float() + pair_mask = mask[:, :, None] * mask[:, None, :] + eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None] + offdiag_mask = pair_mask * (1.0 - eye) + local_mask = mask[..., None, None] + + local_target = targets["local_cov"].to(condition["local_cov_pred"].device, condition["local_cov_pred"].dtype) + cross_target = targets["cross_cov"].to(condition["cross_cov_pred"].device, condition["cross_cov_pred"].dtype) + rmsf_target = targets["rmsf"].to(condition["rmsf_pred"].device, condition["rmsf_pred"].dtype) + + local_diff = (condition["local_cov_pred"] - local_target) * local_mask + local_denom = ((local_target * local_mask).square().sum() / local_mask.sum().clamp_min(1.0)).clamp_min(1e-6) + local_cov_loss = (local_diff.square().sum() / local_mask.sum().clamp_min(1.0)) / local_denom + + if spatial_dists is None: + raise ValueError("spatial_dists is required for near/far cross-cov diagnostics") + spatial_dists = spatial_dists.to(device=mask.device, dtype=condition["cross_cov_pred"].dtype) + near_mask = offdiag_mask * (spatial_dists <= self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype) + far_mask = offdiag_mask * (spatial_dists > self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype) + + cross_diff = (condition["cross_cov_pred"] - cross_target) * offdiag_mask + cross_denom = ((cross_target * offdiag_mask).square().sum() / offdiag_mask.sum().clamp_min(1.0)).clamp_min(1e-6) + cross_cov_loss = (cross_diff.square().sum() / offdiag_mask.sum().clamp_min(1.0)) / cross_denom + + near_diff = (condition["cross_cov_pred"] - cross_target) * near_mask + near_denom = ((cross_target * near_mask).square().sum() / near_mask.sum().clamp_min(1.0)).clamp_min(1e-6) + cross_cov_near_loss = (near_diff.square().sum() / near_mask.sum().clamp_min(1.0)) / near_denom + + far_diff = (condition["cross_cov_pred"] - cross_target) * far_mask + far_denom = ((cross_target * far_mask).square().sum() / far_mask.sum().clamp_min(1.0)).clamp_min(1e-6) + cross_cov_far_loss = (far_diff.square().sum() / far_mask.sum().clamp_min(1.0)) / far_denom + + rmsf_diff = (condition["rmsf_pred"] - rmsf_target) * mask + rmsf_denom = ((rmsf_target * mask).square().sum() / mask.sum().clamp_min(1.0)).clamp_min(1e-6) + rmsf_loss = (rmsf_diff.square().sum() / mask.sum().clamp_min(1.0)) / rmsf_denom + + losses = { + "local_cov_loss": local_cov_loss, + "cross_cov_loss": cross_cov_loss, + "cross_cov_near_loss": cross_cov_near_loss, + "cross_cov_far_loss": cross_cov_far_loss, + "rmsf_loss": rmsf_loss, + } + if "oracle_modes" in targets: + losses.update(self.pca_alignment_loss( + condition, + targets, + res_mask, + top_m=int(getattr(self, "pca_align_top_m", 2)), + )) + return losses + + def generator_response_cov_loss( + self, + response_deltas, + res_mask, + targets, + use_cross=False, + sample_weight=None, + teacher_response_deltas=None, + teacher_trace_anchor=None, + teacher_trace_denominator="teacher", + amplitude_anchor="teacher_trace", + trace_target_scale=None, + ): + """Match generator response shape without rewarding global expansion. + + ``response_deltas`` has shape ``(S, B, N, 3)`` and contains antithetic + central-difference responses for S independent coefficient perturbations. + The loss first averages ``d d^T`` over S and then normalizes by total + response trace before comparing to MD covariance. This avoids the v1 + shortcut where a single rank-1 sample, or a globally amplified response, + can reduce the generator-response objective. + + If ``teacher_response_deltas`` is provided, a weak trace anchor keeps the + current response norm near the frozen initial/A30 response under the same + ``t`` and coefficient perturbations. This anchor does not assume that + one-step trace equals the 20-step inference ensemble trace. + """ + with torch.autocast(device_type=res_mask.device.type, enabled=False): + d = response_deltas.float() + if d.dim() == 3: + d = d[None] + mask = res_mask.float() + if sample_weight is not None: + mask = mask * sample_weight.float().to(mask.device)[:, None] + d = d * mask[None, :, :, None] + + local_target = targets["local_cov"].to(device=d.device, dtype=d.dtype) + target_mask = res_mask.float().to(device=d.device, dtype=d.dtype) + local_mask = mask[:, :, None, None] + target_local_mask = target_mask[:, :, None, None] + + local_sample = torch.einsum("sbni,sbnj->bnij", d, d) / float(d.shape[0]) + trace_sample = ( + torch.diagonal(local_sample, dim1=-2, dim2=-1).sum(dim=-1) * mask + ).sum(dim=-1).clamp_min(1e-8) + trace_target = ( + torch.diagonal(local_target, dim1=-2, dim2=-1).sum(dim=-1) * target_mask + ).sum(dim=-1).clamp_min(1e-8) + local_sample_norm = local_sample / trace_sample[:, None, None, None] + local_target_norm = local_target / trace_target[:, None, None, None] + local_diff = (local_sample_norm - local_target_norm) * local_mask + local_denom = ( + (local_target_norm * target_local_mask).square().sum() + / target_local_mask.sum().clamp_min(1.0) + ).clamp_min(1e-8) + local_shape_loss = ( + local_diff.square().sum() / local_mask.sum().clamp_min(1.0) + ) / local_denom + + losses = { + "gen_local_shape_loss": local_shape_loss, + } + metrics = { + "gen_response_abs_mean": d.detach().abs().mean(), + "gen_response_trace_mean": trace_sample.detach().mean(), + "gen_response_active_frac": ( + mask.sum() / res_mask.float().sum().clamp_min(1.0) + ).detach(), + } + + anchor_trace = None + if amplitude_anchor in ("md_trace", "rollout_trace"): + # Anchor the response magnitude to the MD ensemble's own trace. + # trace_target is already computed above for the shape normalization, + # so this needs no teacher and no extra forwards. + # "rollout_trace" divides the MD trace by a detached no-grad + # rollout-measured trace amplification factor before anchoring. + # + # The "teacher_trace" anchor below is unusable in this codebase: the frozen + # teacher is deep-copied from the model at step 0, where every condition + # adapter (embedder z_*/disp_* adapters and bbflow_model film_mlp) is + # zero-initialized so that a warm-started model reproduces vanilla BBFlow. + # The teacher's response to c is therefore identically zero forever, so + # teacher_trace pins to the 1e-8 clamp floor and log(trace_sample/1e-8)^2 + # drives the student's response to zero -- the opposite of the anchor's + # purpose. A model that ignores c cannot calibrate a response to c. + anchor_trace = trace_target + if trace_target_scale is not None: + scale = trace_target_scale.to(device=d.device, dtype=d.dtype) + anchor_trace = anchor_trace * scale.reshape(-1)[0].clamp_min(1e-8) + elif amplitude_anchor != "none" and ( + teacher_response_deltas is not None or teacher_trace_anchor is not None + ): + if teacher_trace_anchor is not None: + teacher_trace = teacher_trace_anchor.to(device=d.device, dtype=d.dtype) + if teacher_trace.dim() > 1: + teacher_trace = teacher_trace.reshape(teacher_trace.shape[0], -1).mean(dim=-1) + teacher_trace = teacher_trace.reshape(-1).clamp_min(1e-8) + else: + teacher_d = teacher_response_deltas.float() + if teacher_d.dim() == 3: + teacher_d = teacher_d[None] + teacher_d = teacher_d.to(device=d.device, dtype=d.dtype) * mask[None, :, :, None] + if teacher_trace_denominator == "teacher": + teacher_denom = float(teacher_d.shape[0]) + elif teacher_trace_denominator == "student": + teacher_denom = float(d.shape[0]) + elif teacher_trace_denominator == "none": + teacher_denom = 1.0 + else: + raise ValueError( + "teacher_trace_denominator must be one of " + f"'teacher', 'student', or 'none'; got {teacher_trace_denominator!r}" + ) + teacher_local = ( + torch.einsum("sbni,sbnj->bnij", teacher_d, teacher_d) + / teacher_denom + ) + teacher_trace = ( + torch.diagonal(teacher_local, dim1=-2, dim2=-1).sum(dim=-1) * mask + ).sum(dim=-1).clamp_min(1e-8) + anchor_trace = teacher_trace + + if anchor_trace is not None: + valid = (mask.sum(dim=-1) > 0).to(dtype=d.dtype) + trace_ratio = (trace_sample / anchor_trace).clamp_min(1e-8) + trace_loss = (trace_ratio.log().square() * valid).sum() / valid.sum().clamp_min(1.0) + losses["gen_trace_anchor_loss"] = trace_loss + # Ratio to whichever amplitude anchor is active (MD trace or teacher trace). + # Healthy value is ~1; orders of magnitude away means the anchor is broken. + metrics["gen_trace_ratio_to_teacher"] = ( + (trace_sample.detach() / anchor_trace.detach()).clamp_min(1e-8) + * valid + ).sum() / valid.sum().clamp_min(1.0) + metrics["gen_trace_ratio_to_anchor"] = metrics["gen_trace_ratio_to_teacher"] + metrics["gen_trace_anchor_mean"] = anchor_trace.detach().mean() + + if use_cross: + pair_mask = mask[:, :, None] * mask[:, None, :] + target_pair_mask = target_mask[:, :, None] * target_mask[:, None, :] + eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None] + offdiag_mask = pair_mask * (1.0 - eye) + target_offdiag_mask = target_pair_mask * (1.0 - eye) + cross_target = targets["cross_cov"].to(device=d.device, dtype=d.dtype) + cross_sample = torch.einsum("sbnd,sbmd->bnm", d, d) / float(d.shape[0]) + cross_sample_norm = cross_sample / trace_sample[:, None, None] + cross_target_norm = cross_target / trace_target[:, None, None] + cross_diff = (cross_sample_norm - cross_target_norm) * offdiag_mask + cross_denom = ( + (cross_target_norm * target_offdiag_mask).square().sum() + / target_offdiag_mask.sum().clamp_min(1.0) + ).clamp_min(1e-8) + cross_shape_loss = ( + cross_diff.square().sum() / offdiag_mask.sum().clamp_min(1.0) + ) / cross_denom + losses["gen_cross_shape_loss"] = cross_shape_loss + return losses, metrics + + def motion_metrics(self, condition, res_mask): + with torch.no_grad(): + mask = res_mask.float() + energy = condition["energy"].float() + energy_sum = energy.sum(dim=-1).clamp_min(1e-8) + prob = energy / energy_sum[:, None] + entropy = -(prob * prob.clamp_min(1e-8).log()).sum(dim=-1) + effective_modes = torch.exp(entropy) + u_flat = condition["u_global"].float().permute(0, 2, 1, 3).reshape(condition["u_global"].shape[0], condition["u_global"].shape[2], -1) + u_flat = F.normalize(u_flat, dim=-1) + if self.num_modes > 1: + cos = torch.matmul(u_flat, u_flat.transpose(-1, -2)) + eye = torch.eye(self.num_modes, device=cos.device, dtype=torch.bool)[None].expand_as(cos) + mode_cosine_abs = cos.masked_select(~eye).abs().mean() + else: + mode_cosine_abs = energy.new_zeros(()) + metrics = { + "latent_energy_mean": energy.mean(), + "latent_energy_std": energy.std(), + "latent_effective_modes": effective_modes.mean(), + "latent_mode_cosine_abs": mode_cosine_abs, + "latent_node_cond_abs": condition["node_cond"].detach().abs().mean(), + "latent_edge_cond_abs": condition["edge_cond"].detach().abs().mean(), + "latent_u_global_abs": condition["u_global"].detach().abs().mean(), + "latent_u_position_std": (condition["u_global"].detach().float() * mask[:, :, None, None]).std(), + } + if "template_participation" in condition: + metrics.update({ + "latent_template_participation_abs": condition["template_participation"].detach().float().abs().mean(), + "latent_template_omega_abs": condition["template_omega"].detach().float().abs().mean(), + "latent_template_velocity_abs": condition["template_velocity"].detach().float().abs().mean(), + "latent_template_residual_abs": condition["template_residual_global"].detach().float().abs().mean(), + }) + if "mixture_logits" in condition: + diag = torch.diagonal(condition["mixture_scale_tril"].detach().float(), dim1=-2, dim2=-1) + metrics.update({ + "q_mixture_entropy": self._mixture_entropy(condition["mixture_logits"].detach()).mean(), + "q_mu_abs": condition["mixture_mu"].detach().float().abs().mean(), + "q_scale_diag_mean": diag.mean(), + "q_scale_diag_std": diag.std(), + }) + return metrics diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/configs/experiment/default.yaml b/bbflow_base/code_exports/a30_redesign_source_20260719/configs/experiment/default.yaml new file mode 100644 index 0000000000000000000000000000000000000000..78153b3fcf4fc50972828def72e0be3dd7784ceb --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/configs/experiment/default.yaml @@ -0,0 +1,116 @@ +debug: False +use_wandb: True +use_tqdm: True + +seed: 123 +num_devices: 1 +warm_start: null +warm_start_cfg_override: True +use_swa: False +first_val_epoch: 0 +reset_epoch: False + +batch_ot: + enabled: True + cost: kabsch + noise_per_sample: 1 + # permute: False +training: + min_plddt_mask: null + loss: se3_vf_loss + bb_atom_scale: 0.1 + trans_scale: 0.1 + translation_loss_weight: 2.0 + t_normalize_clip: 0.9 + rotation_loss_weights: 1.0 + aux_loss_weight: 1.0 + aux_loss_t_pass: 0.75 + t_bins: 4 + ca_distmat_loss_weight: 0.0 + ensemble_group_size: 0 + force_grouped_batch: false + lambda_shape: 1.0 + lambda_local_cov: 1.0 + lambda_cross_cov: 1.0 + lambda_rmsf: 0.25 + lambda_mode_recon: 0.0 + enm_warmup_epochs: 0 + lambda_enm_warmup: 1.0 + log_latent_batch_debug: false + epoch_condition_probe: true + condition_probe_scale: 2.0 + diagnostic_interval_steps: 50 + lambda_generator_cov: 0.0 + generator_cov_use_cross: false + generator_cov_t_min: 0.1 + generator_cov_t_max: 0.6 + generator_cov_delta_scale: 1.0 + generator_cov_num_deltas: 2 + generator_cov_student_chunk_deltas: 1 + generator_cov_teacher_num_deltas: 1 + generator_cov_teacher_reuse_student_delta: true + generator_cov_teacher_trace_denominator: teacher + generator_cov_checkpoint: false + generator_cov_initial_trace_anchor: true + generator_cov_amplitude_anchor: md_trace + generator_cov_rollout_calibration: false + generator_cov_rollout_steps: 2 + generator_cov_rollout_num_deltas: 1 + generator_cov_rollout_max_examples: 4 + generator_cov_rollout_interval_steps: 200 + generator_cov_rollout_ema_decay: 0.9 + lambda_gen_local_shape: 1.0 + lambda_gen_cross_shape: 1.0 + lambda_gen_trace_anchor: 0.05 +wandb: + name: baseline + project: bbflow + save_dir: outputs/ + # save_code: True + tags: [] +optimizer: + lr: 0.0001 +reset_optimizer_on_load: False +warmup_lr: False +warmup_lr_factor: 0.01 +trainer: + overfit_batches: 0 + min_epochs: 1 # prevents early stopping + max_epochs: 250 + accelerator: gpu + precision: bf16-mixed + log_every_n_steps: 1 + deterministic: False + strategy: ddp + check_val_every_n_epoch: 1 + default_root_dir: outputs/ + accumulate_grad_batches: 1 +checkpointer: + dirpath: outputs/ckpt/${experiment.wandb.project}/${experiment.wandb.name}/${now:%Y-%m-%d}_${now:%H-%M-%S} + save_last: True + save_on_train_epoch_end: True + filename: "epoch:{epoch:03d}" + every_n_epochs: 1 + save_top_k: -1 + auto_insert_metric_name: False +checkpointer2: null # TODO: maybe remove/change + # dirpath: outputs/ckpt/${experiment.wandb.project}/${experiment.wandb.name}/${now:%Y-%m-%d}_${now:%H-%M-%S} + # save_last: False + # filename: "sec_dev:{sec_deviation:.2f}-epoch:{epoch:03d}" + # save_top_k: 10 + # monitor: valid/sec_deviation + # mode: min + # every_n_epochs: 1 + # first_epoch: ${experiment.first_val_epoch} + # auto_insert_metric_name: False +profiler: + enabled: False + modules: null # Optional list of modules which should be profiled + profile: + use_cuda: True + with_stack: False + stats: + group_by_stack_n: 0 + group_by_input_shapes: False + prefixes: ['layer_0::', 'layer_1::'] + sort_by: 'cpu_time_total' diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/configs/inference.yaml b/bbflow_base/code_exports/a30_redesign_source_20260719/configs/inference.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ab860ee65b899572e6c6c4525ebfbb04d41e31c8 --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/configs/inference.yaml @@ -0,0 +1,93 @@ +defaults: + - data: default + - experiment: default + - interpolant: default + - model: default + - _self_ + +hydra: + run: + dir: outputs/hydra/ + +latent: + enable: true + dim: 16 + num_modes: 8 + motion_message_passing_layers: 4 + cross_cov_near_distance: 12.0 + template_residual_scale: 0.1 + template_remove_rotation: true + use_enm_features: false + enm_num_modes: 8 + enm_cutoff: 12.0 + enm_eps: 1e-6 + node_cond_dim: 8 + edge_cond_dim: 8 + freeze_foundation: true + inject_embedder: true + inject_film: true + activation_checkpoint: true + shape_fingerprint_k: 5 + shape_fingerprint_cache_path: null + motion_target_cache_path: null + z_stochastic: false + +inference: + # Use this to write with date-time stamp. + name: run_${now:%Y-%m-%d}_${now:%H-%M} + seed: 123 + ckpt_path: models/bbflow-mini-0.1/bbflow-mini-0.1.ckpt + output_dir: outputs/inference/ + use_ckpt_name_in_outpath: True + + use_gpu: True + num_gpus: 1 + precision: 32-true + + use_tqdm: True + log_times: False + z_per_sample: False + condition_mode: real # real, zero, shuffled + condition_scale: 1.0 + postprocess_bfactors: True + + csv_path: ./dataset_csv/test/ATLAS_test.csv + sort: False + num_proteins: null # null = all proteins + num_workers: 2 + + min_length: null # null = no lower limit + max_length: null # null = no upper limit + + save_traj: False + final_only: True + cache_static_features: True + single_file: True + + interpolant: + use_tqdm: ${inference.use_tqdm} + min_t: 0.00 + max_t: 0.99 + rots: + distribution: uniform # uniform, igso3 + sample_schedule: exp + exp_rate: 10 + trans: + sample_schedule: linear + sampling: + num_timesteps: 20 + self_condition: True + + prior: "conditional" # "conditional", "pure_noise" + prior_conditional: + gamma_trans: 0.2 + gamma_rots: 0.2 + + + samples: + + samples_per_protein: 25 + + batch_size: 10 + + num_res_squared: 2_900_000 diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/configs/train.yaml b/bbflow_base/code_exports/a30_redesign_source_20260719/configs/train.yaml new file mode 100644 index 0000000000000000000000000000000000000000..80fa5c7b88bbe226dfc22ff136d8515028ce5808 --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/configs/train.yaml @@ -0,0 +1,34 @@ +defaults: + - data: default + - experiment: default + - interpolant: default + - model: default + - _self_ + +hydra: + run: + dir: outputs/hydra/ + +latent: + enable: true + dim: 16 + num_modes: 8 + motion_message_passing_layers: 4 + cross_cov_near_distance: 12.0 + template_residual_scale: 0.1 + template_remove_rotation: true + use_enm_features: false + enm_num_modes: 8 + enm_cutoff: 12.0 + enm_eps: 1e-6 + node_cond_dim: 8 + edge_cond_dim: 8 + freeze_foundation: false + inject_embedder: true + inject_film: true + activation_checkpoint: true + track_condition_debug: false + shape_fingerprint_k: 5 + shape_fingerprint_cache_path: null + motion_target_cache_path: null + z_stochastic: false diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/docs/HANDOFF_2026-07-17.txt b/bbflow_base/code_exports/a30_redesign_source_20260719/docs/HANDOFF_2026-07-17.txt new file mode 100644 index 0000000000000000000000000000000000000000..a0d360077bd63627989e77da9137184fa0d0ea43 --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/docs/HANDOFF_2026-07-17.txt @@ -0,0 +1,924 @@ +================================================================================ +HANDOFF DOCUMENT - BBFlow generator-response covariance line +Date: 2026-07-17 +Audience: the next Claude / engineer picking this up cold +================================================================================ + +HOW TO USE THIS DOC +------------------- +Read sections 1-4 first (goal, scoreboard, the core diagnosis). Then section 6 +(current mechanism) and section 8 (THE TEACHER BUG - do not repeat it). +Section 14 lists process rules that were learned the expensive way. + +This doc supplements docs/experiment_trace_2026-07-05.md, which holds the older +experiment log. Where they disagree, this doc is newer. + + +================================================================================ +1. PROJECT GOAL AND HARD CONSTRAINTS +================================================================================ + +GOAL + Beat BBFlow (Wolf et al., NeurIPS 2025) on the ATLAS test set (82 proteins, + 250 conformations each) on its own official metrics: + - RMSF correlation (r) and RMSF MAE + - Pairwise RMSD MAE + - PCA W2 + +USER'S HARD CONSTRAINT (stated repeatedly, non-negotiable) + "We must be better than BBFlow." Tying is not accepted as a result. Do not + propose a paper narrative that relies only on cross-covariance / auxiliary + metrics while conceding the official table. + +STANDING PROHIBITIONS (user has explicitly rejected these; do not re-propose) + - ENM (elastic network model) as a basis or forward feature. Absolutely refused. + - Oracle information in any deployable component. See section 12. + - Expensive full ensemble-rollout training losses (20-step sampling per step). + - Multi-seed re-runs purely to measure noise floor ("100% against 多跑"). + +CONTEXT ON WHY THE USER IS FRUSTRATED + This line has burned weeks. Multiple runs were wasted on OOM crashes and on a + silent bug (section 8). Be precise, verify before proposing commands, and do + not over-promise speedups or "free" fixes. Two things this session were + over-claimed and had to be retracted: (a) "1 delta is unbiased and free" - + false for the normalized-shape objective, see section 6; (b) "removing the + teacher restores v1 speed" - it was only ~15%. + + +================================================================================ +2. ENVIRONMENT AND PATHS +================================================================================ + +MACHINES + Local (Windows): D:\pycharm\pythonProject\protein\bbflow_base + - This is a CODE MIRROR ONLY. There is NO python and NO torch installed. + You can read and edit code here. You CANNOT run, test, or syntax-check + by execution. Only careful reading. + - The user copies files to the server MANUALLY. + Server: gn11 / gn14, 3x NVIDIA H100 PCIe 80GB + Repo: /home/wangyusong/LD-FPG-main/bbflow_base + Conda: `protein` env (also seen: /data/shared/conda_envs/ldfpg) + +KEY PATHS + Official BBFlow checkpoint (warm-start source for everything): + /home/wangyusong/LD-FPG-main/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt + NOTE the path is under .../LD-FPG-main/bbflow/ (NOT bbflow_base/). + + Repro root: + /data/shared/wangyusong/atals/bbflow_official_reproduction + + "Version A" reference run (the protected baseline to beat/compare against): + ${REPRO}/outputs/checkpoints/ + bbflow_base_energy_from_q_diag_orth1_recon0_30ep_3gpu_20260707_165355 + + Motion target cache (used by the current runs): + /home/wangyusong/LD-FPG-main/bbflow_official_reproduction/shape_fingerprints/ + atlas_full_md_motion_targets_k8_kabsch_v1.pt + WARNING: docs/experiment_trace_2026-07-05.md lists caches under + ${REPRO}/shape_fingerprints/. The running command uses the /home/... path. + These may be different copies. VERIFY before trusting a comparison to A. + Required cache fields: local_cov, cross_cov, rmsf, oracle_mean_disp. + Optional: gen_response_trace_anchor, oracle_modes, oracle_energy. + +LAUNCHER / SCRIPT INTERFACES (never write commands from memory - read them) + Training: base_stages/00_train_final_mog_ddp.sh + env-var interface + EXTRA_HYDRA_ARGS passthrough. + `+experiment.training.X=Y` adds NEW hydra keys; existing keys + take no `+`. + Sampling: reproduction/02_sample_test.sh + Uses REPRO_ROOT, METADATA_ROOT, CKPT_PATH, GPU_ID, + SAMPLES_PER_PROTEIN, SAMPLE_BATCH_SIZE, MAX_NUM_RES_SQUARED, + INFERENCE_NAME, CONDITION_MODE, CONDITION_SCALE, ... + It IGNORES OUTPUT_DIR and writes to ${REPRO_ROOT}/inference + Evaluation: reproduction/03_evaluate.sh + Uses ENSEMBLE_DIR, ATLAS_VIEW_ROOT, METRICS_DIR, TEST_CSV, + METHOD_NAME, METHOD_TIME_SECONDS, NUM_WORKERS + ATLAS_VIEW_ROOT must point at the REAL trajectories: + ${REPRO}/datasets/ATLAS + If you see "No reference trajectory found ... reproduction/ + outputs/data/ATLAS", STOP - the metrics are invalid. + +OUTPUTS PER RUN + ${RUN_DIR}/config.yaml <- the ONLY source of truth for + what actually ran + ${RUN_DIR}/latent_train_epoch_metrics.csv <- one row per epoch, ALL metrics + (rank 0 only). This is the file + to read/paste for diagnosis. + ${RUN_DIR}/epoch:0NN.ckpt, last.ckpt + Console line per epoch: "[epoch NNN md] key=val, ..." driven by + MD_EPOCH_SUMMARY_KEYS in bbflow/models/bbflow_module.py + + +================================================================================ +3. THE SCOREBOARD (this is what everything is measured against) +================================================================================ + + Method RMSF r RMSF MAE Pairwise MAE PCA W2 + -------------------------------------- ------ -------- ------------ ------ + BBFlow official rerun (250 samples) 0.89 0.48 0.77 1.34 + (same official, second record) 0.89 0.47 0.78 1.34 + Version A (energy_from_q_diag, 30ep) 0.89 0.45 0.79 1.35 + Long finetune orth1/recon0 100ep 0.88 0.48 0.81 1.35 + A with SHUFFLED condition 0.89 0.48 1.27 1.51 + +READING OF THE SCOREBOARD + - A WINS RMSF MAE (0.45 vs 0.47-0.48). This is a real, repeated win. + - A ties RMSF r. + - A is behind on Pairwise (0.79 vs 0.77-0.78) and PCA W2 (1.35 vs 1.34) by + 0.01-0.02 - i.e. by roughly the amount BBFlow's own two records differ from + each other (0.77 vs 0.78; 0.47 vs 0.48). + - Shuffled-condition collapse (Pairwise 0.79 -> 1.27) proves the condition + carries real information. + - NOBODY HAS EVER MEASURED THE SEED-TO-SEED VARIANCE of these numbers. The + user has refused multi-seed runs. So "we are 0.01 behind" is currently not + distinguishable from noise, and cannot be, under the current constraints. + A paired significance test over the 82 per-protein values from the EXISTING + saved runs would answer it at zero GPU cost, if the per-protein metric CSVs + still exist on the server. This was suggested and declined; it remains the + cheapest unexploited information in the project. + + Upper bound reference (NOT deployable, oracle): + per-protein oracle scale selection gives Pairwise MAE 0.5583. + Best-scale distribution is bimodal (scale12: 31 proteins, scale30: 27), + length does not predict it, no deployable predictor was ever found. + + +================================================================================ +4. THE CORE DIAGNOSIS (the reason this whole line exists) +================================================================================ + +THE ARCHITECTURE + x_eq --> LatentEncoder --> modes U, prior q(c | x_eq) + | + sample c ~ q + | + (x_eq, c) --> BBFlow generator --> conformation + repeat 250x -----------------> ensemble --> official metrics + +THE BUG IN THE OBJECTIVE (not a code bug - a design gap) + The existing losses: + local_cov_loss, cross_cov_loss, rmsf_loss + supervise the PRIOR's THEORETICAL covariance: + Sigma_prior = sum_k energy_k * U_k U_k^T ( = U E_q[cc^T] U^T ) + This quantity contains NO GENERATOR PARAMETERS AT ALL. + + The official metrics measure the GENERATOR's OUTPUT ensemble covariance: + Sigma_gen = Cov(x_1 ... x_250) + + There was never a loss connecting the two. The generator hears c (verified: + condition injection works, FiLM adapters receive nonzero grad, signed paths + alive) but was never required to turn c into the correct ensemble statistics. + + This single fact explains the entire history: + - probe/proxy metrics improve (they measure the prior) + - downstream stays flat (it measures the generator) + - more training on proxies makes downstream worse (30->60 pca_align) + - the generator UNDER-DISPERSES: contraction diagnostics measured + gen_amp_median/MD = 0.71-0.79, PC1 var/MD = 0.34-0.54 + i.e. the generator systematically compresses the ensemble. + + Plain statement: "the generator was never controlled at the ensemble level." + +WHY THE MECHANISM'S SIGNAL DOESN'T SHOW UP IN THE OFFICIAL TABLE + The condition's information lives in cross-covariance / collective directional + structure (far cross_cov corr is the one metric that reliably improves). The + three official metrics are mostly amplitude/spread statistics that BBFlow + already does well. The improved dimension is largely orthogonal to what the + metrics reward. That is why proxies win and the table doesn't move. + + +================================================================================ +5. WHAT WAS TRIED BEFORE AND FAILED (condensed - details in experiment_trace) +================================================================================ + + - Long latent finetune (100ep, orth1/recon0): worse than official on Pairwise. + - PCA-align loss (lambda 0.1, 30ep): train proxies improve, held-out test82 + mode-PCA alignment DROPS. Not a downstream win. + NOTE: even ON THE TRAINING SET, with a loss explicitly pushing it, the + energy-weighted overlap with MD top-2 PCs saturated at only ~0.22 (60ep + ~0.31). Learning MD principal DIRECTIONS from x_eq appears intrinsically + hard here. Also: pca_align uses oracle_modes as a training target, which + the "non-negotiable oracle policy" (section 12) appears to forbid. This + tension was never resolved. + - PCA-align 30 -> 60 epochs: proxies keep improving, downstream degrades. + - Global condition_scale sweep on the 60ep ckpt: no globally good scale exists. + Larger scale fixes the median but not the MAE; PCA W2 best near scale10. + - Per-protein oracle scale: strong upper bound (0.5583) but bimodal and no + inference-time predictor was found. Length does not explain the split. + - Condition cycle loss (lambda 0.05): internal targets improve, downstream + worse. MECHANISM: cycle forces each frame to equal sum_k c_k U_k exactly, + which CONTRACTS the ensemble and kills diversity. It is ANTAGONISTIC to the + current generator-response loss (one contracts, one wants correct + dispersion). KEEP lambda_condition_cycle = 0.0. + - q temperature (tau) scaling: improves far cross-cov, hurts Pairwise/PCA. + - fullcov variant: PCA improves, Pairwise breaks. + + PATTERN: every local knob produces a seesaw - improve one metric, break + another. The trace explicitly warns against per-protein drilldowns as a + default next step; they consumed time without producing decisions. + + +================================================================================ +6. THE CURRENT MECHANISM: generator-response covariance loss +================================================================================ + +IDEA + Put a loss on the GENERATOR'S OWN OUTPUT response to the condition, cheaply, + without any 20-step rollout. + +ANTITHETIC CENTRAL DIFFERENCE + For one protein, one noisy state, sample a zero-mean fluctuation of q: + delta = (c_sample - mu_bar) * delta_scale, c_sample ~ q, + mu_bar = softmax(mixture_logits) . mixture_mu (the mean of q) + Build two conditions and run the generator on both: + c_plus = mu_bar + delta + c_minus = mu_bar - delta + Take the one-step clean predictions (model_output["pred_trans"]), align both + to trans_equilibrium (Kabsch, same convention as the MD targets), and take: + d = ( align(pred(c_plus)) - align(pred(c_minus)) ) / 2 + + d[i] is the 3D displacement of residue i caused by this fluctuation. Because + +delta and -delta share the same background noisy state, subtracting cancels + everything not caused by c. + +WHY IT IS STATISTICALLY VALID WITH FEW SAMPLES + To first order d = J*delta, so + E_delta[ d d^T ] = J Cov_q J^T = the generator's response covariance. + You NEVER reconstruct the 250-sample covariance. Each step contributes one + unbiased rank-1 sample and SGD averages over thousands of steps - exactly the + way flow matching learns a whole distribution one noisy sample at a time. + "8 vs 250" is a non-issue because nothing is estimated per-step. + + IMPORTANT CORRECTION (this cost us an argument, get it right): + The above unbiasedness holds for RAW covariance matching (v1). It does NOT + hold for the NORMALIZED shape objective (v2), because C/tr(C) is NONLINEAR: + E[ C / tr(C) ] != E[C] / tr(E[C]) + A single-delta rank-1 normalized outer product is a BIASED estimator of the + target normalized covariance. Therefore, under v2, going from 2 deltas to + 1 delta CHANGES THE OBJECTIVE - it is not merely a variance increase, and it + is not "free". DO NOT cut student deltas to 1 to save time. + +WHY NORMALIZED SHAPE (v2 over v1) + Raw covariance matching lets the model take a shortcut: globally amplify the + response. That can improve PCA W2 while blowing up RMSF/Pairwise. v2 compares + SHAPE only: + C/tr(C) vs C_MD/tr(C_MD) + which is scale-invariant, so amplification cannot reduce the shape loss. It + forces the model to learn WHICH residues/directions move together. + +WHY AN AMPLITUDE ANCHOR IS THEN REQUIRED + Shape normalization removes ALL amplitude constraint. Without an anchor the + response magnitude drifts freely. So a weak anchor pins the trace: + trace_anchor_loss = mean( log( tr(C) / tr(anchor) )^2 ) + Current anchor target = tr(local_cov_MD), i.e. the MD ensemble's own trace. + +COST + Extra forwards per step = 2 * num_deltas (= 4 with 2 deltas), all gradient + checkpointed. The condition is DETACHED, so gradients flow ONLY into the + generator - this deliberately isolates "make the generator honor the given + condition" from the prior/q fit. U and q are NOT trained by this loss. + +APPLIED ONLY IN A NOISE BAND + Only samples with t in [GENERATOR_COV_T_MIN, GENERATOR_COV_T_MAX] = [0.1, 0.6] + contribute. CONVENTION: interpolant_bbflow.py does + trans_t = (1 - t)*noise + t*data + so t=1 is CLEAN and t=0 is PURE NOISE. "mid-high noise" = low-to-mid t. + The extra forwards run on the WHOLE batch every step regardless (out-of-band + samples get loss weight 0) - this is deliberate, to keep the DDP autograd + graph STATIC. Do not "optimize" this into a conditional skip without thinking + about DDP dynamic-graph errors. + + +================================================================================ +7. CURRENT CODE: WHAT IS WHERE +================================================================================ + +LINEAGE WARNING + The v1 implementation (single delta, raw covariance) was written by Claude and + has been ENTIRELY OVERWRITTEN by Codex's v2 rewrite. Do not look for v1 config + names (lambda_gen_local_cov, lambda_gen_rmsf, generator_cov_use_cross was v1 + too). The md_trace fix (section 8) was applied on top of v2. + +bbflow/models/latent.py + def generator_response_cov_loss( + self, response_deltas, res_mask, targets, + use_cross=False, sample_weight=None, + teacher_response_deltas=None, teacher_trace_anchor=None, + teacher_trace_denominator="teacher", + amplitude_anchor="teacher_trace") + - response_deltas has shape (S, B, N, 3), S = number of independent deltas. + - CRITICAL ORDER (do not break this): + C = mean_s( d_s d_s^T ) # combine across ALL deltas + trace_sample = tr(C) + C_norm = C / trace_sample # normalize ONCE, afterwards + loss = || C_norm - C_MD_norm ||^2 / denom + You must NOT compute a shape loss per delta and average them. Because the + normalization is nonlinear, mean_i( C_i/tr(C_i) ) != (sum_i C_i)/tr(sum_i C_i). + This invariant holds at EVERY chunking granularity, so chunking the forwards + is safe; splitting the loss is not. + - amplitude_anchor == "md_trace" -> anchor_trace = trace_target (MD's trace) + - amplitude_anchor == "teacher_trace" -> DEAD PATH, see section 8. + - Everything is wrapped in torch.autocast(enabled=False) and .float(), so the + covariance/trace/normalization math stays FP32 even under bf16-mixed. This + is why bf16-mixed is safe for this loss. + +bbflow/models/bbflow_module.py + - _generator_response_cov_loss(...) : builds the deltas, the +/- conditions, + runs the chunked student forwards, optionally the teacher, calls the loss. + - _initial_generator_response_teacher() : deepcopy(self.model), eval(), + requires_grad_(False). ONLY reached when amplitude_anchor=="teacher_trace". + DO NOT RE-ENABLE. See section 8. + - _latent_group_z(): looks up motion_targets and stashes self._gen_cov_targets + - training_step(): calls the loss, adds gen_cov_loss into train_loss, and the + existing NaN guard covers it (NaN -> step skipped, 5 in a row -> raise). + - MD_EPOCH_SUMMARY_KEYS: the console per-epoch summary key list. + +LOSS COMPOSITION (as actually assembled) + train_loss = official_loss (flow matching) + + lambda_shape * latent_regularizer (motion/q/orth - PRIOR side) + + condition_cycle_loss (currently 0) + + gen_cov_loss + + gen_cov_loss = lambda_generator_cov * ( + lambda_gen_local_shape * gen_local_shape_loss + + lambda_gen_cross_shape * gen_cross_shape_loss (if use_cross) + + lambda_gen_trace_anchor * gen_trace_anchor_loss ) + +METRIC NAME LANDMINE + `gen_trace_ratio_to_teacher` IS A MISNOMER. Since the md_trace fix it reports + tr(C_student) / tr(local_cov_MD) + It has nothing to do with a teacher any more. The name was never updated. + Read it as "generator response amplitude / MD amplitude". 1.0 = matched. + + +================================================================================ +8. THE TEACHER BUG - THE MOST IMPORTANT THING IN THIS DOC +================================================================================ + +WHAT v2 ORIGINALLY DID + It anchored the response amplitude to a "frozen teacher" = + copy.deepcopy(self.model) taken at training step 0, run under no_grad with the + same deltas. + +WHY IT WAS CATASTROPHICALLY WRONG + The condition-injection adapters are ZERO-INITIALIZED on purpose, so that a + warm-started model initially reproduces vanilla BBFlow exactly: + bbflow/models/embedder.py:181-188 + nn.init.zeros_ on z_node_adapter[-1], z_edge_adapter[-1], + disp_node_adapter[-1], disp_edge_adapter[-1] + (both weight and bias) + bbflow/models/bbflow_model.py:107-108 + nn.init.zeros_ on film_mlp[-1] (weight and bias) + + Therefore at step 0 the model's response to c is IDENTICALLY ZERO. The teacher + is a frozen snapshot of exactly that state, so the teacher's response to c is + zero FOREVER. Then: + teacher_trace -> clamp_min(1e-8) -> pinned at the floor + trace_ratio = student_trace / 1e-8 -> ~1e6 + anchor loss = log(ratio)^2, minimized at student_trace = 1e-8 + => THE ANCHOR WAS ACTIVELY TRAINING THE STUDENT'S RESPONSE TO ZERO. + A model that ignores c cannot serve as a calibration reference for a response + to c. The anchor's purpose was inverted. + +THE EVIDENCE (how it was caught - reuse this technique) + epoch 0: trace_mean=0.03611, ratio=4.363e6 + epoch 1: trace_mean=0.004766, ratio=5.438e5 + trace ratio between epochs: 0.03611/0.004766 = 7.58 + metric ratio between epochs: 4.363e6/5.438e5 = 8.02 + The two agree => the DENOMINATOR IS A CONSTANT => teacher_trace is pinned at + the 1e-8 clamp floor. Also 0.03611/1e-8 = 3.6e6, the right order of magnitude. + Meanwhile gen_response_abs_mean was dying: 0.001946 -> 0.0006519. + +THE FIX (already applied, in the code now) + New config: generator_cov_amplitude_anchor, DEFAULT "md_trace". + "md_trace" -> anchor_trace = trace_target = tr(local_cov_MD). + Physically real, nonzero, needs NO teacher and NO extra + forwards (trace_target is already computed for the shape + normalization). + "teacher_trace" -> the old, broken path. Retained as dead code. + generator_cov_initial_trace_anchor=false sets amplitude_anchor="none". + latent.py carries a comment recording this diagnosis at the md_trace branch. + +RULE + DO NOT set generator_cov_amplitude_anchor=teacher_trace. If you ever want a + teacher-style anchor, the teacher must be a checkpoint whose adapters are + ALREADY TRAINED (e.g. A30), not a step-0 snapshot. + + +================================================================================ +9. VALIDATION RUN - EVIDENCE THE MECHANISM WORKS +================================================================================ + +RUN: bbflow_base_gen_cov_v2_mdtrace_k8_10ep_3gpu_120k_bs10_20260717_003351 +CONFIG: use_cross=false, lambda_gen_trace_anchor=0.05, md_trace anchor, + bf16-mixed, 120000/bs10, 3 GPU, warm start from official BBFlow. +KILLED at ~epoch 5 (validation achieved; config cannot win PCA W2). + + metric ep0 ep1 ep2 ep3 ep4 ep5 + ---------------------- ------ ------ ------ ------ ------ ------ + gen_trace_ratio(vs MD) 1.044 1.077 1.061 0.655 0.650 0.632 + gen_response_abs_mean 0.512 0.593 0.554 0.460 0.453 0.478 + gen_local_shape_loss 0.706 0.654 0.637 0.563 0.532 0.516 + gen_trace_anchor_loss 1.168 0.658 0.656 0.467 0.325 0.299 + official_loss - 0.760 0.477 0.473 0.442 0.427 + rmsf_loss 0.487 0.488 0.438 0.428 0.429 0.439 + cross_cov_far_corr 0.013 0.063 0.119 0.151 0.178 0.190 + mode_gram_condition 2.3e5 1.8e5 8146 819.9 15.29 6.307 + mode_max_cosine_abs 0.907 0.968 0.809 0.547 0.459 0.375 + +VERDICT: THE MECHANISM IS ENGAGED. All four validation criteria passed: + - ratio starts at ~1.04 (the 4.36e6 pathology is gone) + - gen_response_abs_mean stable ~0.45-0.6 (previously dying to 0.0006) + - gen_local_shape_loss MONOTONICALLY DECREASING 0.706 -> 0.516 + => the generator IS learning to match MD's covariance SHAPE + - official_loss healthy 0.760 -> 0.427 (the new loss did not wreck training) +Also good: mode basis conditioning collapsed from 2.3e5 to 6.3, modes becoming +orthogonal (max_cosine 0.907 -> 0.375), far cross-cov corr rising 0.013 -> 0.190. + + +================================================================================ +10. THE KNOWN OPEN PROBLEM: AMPLITUDE DRIFT +================================================================================ + +OBSERVATION + gen_trace_ratio drifts 1.044 -> 0.632 and is still falling. The generator's + response amplitude is only ~63% of MD's -> UNDER-DISPERSED BY ~37%. + +WHY + - gen_local_shape_loss (lambda 1.0) is SCALE-INVARIANT: it constrains nothing + about amplitude. + - gen_trace_anchor_loss is the ONLY amplitude constraint, at lambda 0.05 - + 20x weaker. + - official_loss / motion_loss structurally PREFER contraction (predicting the + conditional mean is the safe play for a single-frame objective). + => the weak anchor loses; amplitude sinks. + +WHY IT MATTERS + This is exactly the project's known failure mode: contraction diagnostics + measured gen_amp/MD = 0.71-0.79 and PC1 var/MD = 0.34-0.54. Under-dispersion + directly damages Pairwise RMSD (spread too small) and PCA W2. + +A TRAP IN READING THE METRICS (do not misdiagnose this) + gen_trace_anchor_loss DECREASES (1.168 -> 0.299) WHILE the ratio drifts AWAY + from 1. That is not a contradiction: + - the metric is mean(ratio) + - the loss is mean(log(ratio)^2) + ep0: log(1.044)^2 = 0.002, but loss = 1.168 => almost ALL of it is spread. + RMS(log) ~ 1.08 => per-sample ratios spanned roughly [0.34, 2.9] and + merely AVERAGED to 1.04. + ep5: log(0.632)^2 = 0.211, loss = 0.299 => only 0.088 is spread. + So the anchor IS working - it tightened the distribution - but it tightened + around the WRONG CENTER (0.63 instead of 1.0). + +THE FIX (to be tested in the next run) + Raise lambda_gen_trace_anchor from 0.05 to 0.3. + Watch: if ratio still sinks below ~0.8 by epoch 3 -> raise to 0.5-1.0. + if official_loss starts climbing / NaNs appear -> drop to 0.15. + +A SUBTLETY WORTH KNOWING (unresolved, probably benign) + Anchoring the c-INDUCED response trace to MD's FULL trace implicitly asks c + alone to explain all of MD's variance, ignoring that at inference the flow's + own noise (different x_0 per sample) also contributes spread. Strictly, the + ideal target may be < 1.0. BUT empirically the full generated ensemble is + UNDER-dispersed (0.7-0.8 of MD), so pushing up is the right direction. If a + future run over-disperses, lower the anchor target to ~0.8 rather than + abandoning the anchor. + + +================================================================================ +11. WHAT IS RUNNING / THE NEXT RUN +================================================================================ + +STATUS AS OF 2026-07-17: the validation run was KILLED at ~epoch 5. Nothing is +training. epoch:005.ckpt from that run still exists and could be evaluated +downstream on idle GPUs for a free read on local-shape-only (low priority - it +targets RMSF, the metric already won). + +NEXT RUN = validation config + EXACTLY TWO CHANGES: + GENERATOR_COV_USE_CROSS : false -> true (the EXPERIMENT: cross shape is + the only component that can + move PCA W2) + LAMBDA_GEN_TRACE_ANCHOR : 0.05 -> 0.3 (a BUG FIX for section 10) + +Two changes at once is justified here: one is the experiment, one is a fix for a +measured defect. Running cross with a provably sinking amplitude would waste the +run. + +COMMAND: + +pkill -u wangyusong -9 -f experiments/train.py; sleep 3 + +cd ~/LD-FPG-main/bbflow_base +export PYTHONPATH=$PWD:${PYTHONPATH:-} + +ATLAS_REPRO_ROOT=/data/shared/wangyusong/atals/bbflow_official_reproduction \ +RUN_DIR=/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_gen_cov_v2_mdtrace_cross_k8_10ep_3gpu_120k_bs10_$(date +%Y%m%d_%H%M%S) \ +FINGERPRINT_CACHE=/home/wangyusong/LD-FPG-main/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt \ +GPU_IDS=0,1,2 NUM_DEVICES=3 MAX_EPOCHS=10 \ +CHECKPOINT_EVERY_N_EPOCHS=1 CHECKPOINT_SAVE_LAST=true CHECKPOINT_SAVE_TOP_K=-1 \ +PRECISION=bf16-mixed MAX_NUM_RES_SQUARED=120000 MAX_BATCH_SIZE=10 \ +ENERGY_FROM_Q=true ENERGY_FROM_Q_FULL_COV=false Q_DETACH_SHARED_ENCODER=false \ +LAMBDA_MOTION=1.0 LAMBDA_Q=1.0 LAMBDA_MODE_ORTH=1.0 LAMBDA_MODE_RECON=0.0 LAMBDA_PCA_ALIGN=0.0 \ +LAMBDA_CONDITION_CYCLE=0.0 \ +LAMBDA_GENERATOR_COV=1.0 GENERATOR_COV_USE_CROSS=true \ +GENERATOR_COV_T_MIN=0.1 GENERATOR_COV_T_MAX=0.6 GENERATOR_COV_DELTA_SCALE=1.0 \ +GENERATOR_COV_NUM_DELTAS=2 GENERATOR_COV_STUDENT_CHUNK_DELTAS=1 \ +GENERATOR_COV_CHECKPOINT=true GENERATOR_COV_INITIAL_TRACE_ANCHOR=true \ +LAMBDA_GEN_LOCAL_SHAPE=1.0 LAMBDA_GEN_CROSS_SHAPE=1.0 LAMBDA_GEN_TRACE_ANCHOR=0.3 \ +bash base_stages/00_train_final_mog_ddp.sh + +POST-LAUNCH AUDIT (mandatory - a stray value already cost one run): + RUN_DIR=$(ls -dt .../bbflow_base_gen_cov_v2_mdtrace_cross_* | head -1) + grep -nE "generator_cov_use_cross|lambda_gen_trace_anchor|lambda_condition_cycle|precision" "$RUN_DIR/config.yaml" + MUST SEE: use_cross: true / trace_anchor: 0.3 / condition_cycle: 0.0 / + precision: bf16-mixed + +WATCH IN THE FIRST FEW EPOCHS: + 1. gen_cross_shape_loss APPEARS and DECREASES. If the key never appears, + use_cross did not take effect. + 2. gen_trace_ratio_to_teacher (= tr(C)/tr(MD)) holds ~0.9-1.0, does not sink + to 0.6 again. + 3. official_loss keeps falling smoothly (0.76 -> 0.43 last run). + +DECISION RULE: if by epoch 3 the ratio is holding and cross shape is falling, +let it run to 10. Otherwise stop and adjust the anchor rather than burning 20h. + + +================================================================================ +12. THE ORACLE POLICY (verbatim intent, from the trace, 2026-07-09) +================================================================================ + - Oracle information is forbidden in training, checkpoint selection, + inference, calibration, routing, gating, or any deployable component. + - This includes test/validation MD frames, projected per-frame oracle + coefficients, oracle PCA modes/energies, oracle best scales, and any + feature derived from the target ensemble. + - Oracle quantities may only be used AFTER generation as offline diagnostic + labels or upper-bound analyses. + + UNRESOLVED TENSION: the policy text explicitly lists "oracle PCA modes/ + energies" as forbidden from influencing model parameters, yet + pca_alignment_loss trains on oracle_modes. Whoever picks this up should get a + ruling from the user before using oracle_modes as a training target. + + GOOD NEWS: the CURRENT generator-response line uses NO oracle quantities. It + supervises against local_cov / cross_cov / rmsf, which are the ordinary MD + targets the core method has always used (computed from each TRAINING + protein's own MD). Keep it that way - it is a genuine advantage of this + design over pca_align. + + +================================================================================ +13. INFRASTRUCTURE: THE OOM AND SPEED SAGA (so you don't repeat it) +================================================================================ + +THE MEMORY WALL + Version A already ran at ~76 GB / 79 GB. There were only ~3 GB of headroom. + Adding ANY extra forwards OOMs. Two runs were destroyed learning this. + OOM site: gafl/models/gafl/cfa.py, the attention-like tensor + `a[..., None, :, :, None]` (a 7.85 GiB single allocation). GAFL's CFA + materializes a large intermediate; it is memory-bandwidth bound. + +WHAT ACTUALLY FIXED IT (all four stacked) + 1. PRECISION=bf16-mixed (was 32-true - on an H100 that was throwing away + more than half the tensor-core throughput AND doubling activations). + The loss math is FP32-guarded, so this is safe. + 2. 2+2 chunking: merge ONE delta's +/- into a single 2x-batch forward and do + 2 such calls, instead of merging all 4 into one 4x-batch call. Halves the + attention peak. The statistical target is UNCHANGED (see section 7 - the + d_s are identical regardless of how the forwards are batched; only the + "combine C then normalize once" invariant matters). + 3. GENERATOR_COV_CHECKPOINT=true: gradient-checkpoint the extra forwards + (activations recomputed in backward instead of stored). + 4. MAX_NUM_RES_SQUARED 400000 -> 120000, MAX_BATCH_SIZE 32 -> 10. + +MEMORY MEASUREMENT RULE (learned painfully) + A spot reading of 16 GB was a TROUGH, not the peak; the peak was ~70/80 GB. + Batch composition varies hugely with protein size. ALWAYS measure the peak: + nvidia-smi --query-gpu=memory.used --format=csv -l 5 + over several minutes before concluding there is headroom. + +SPEED FACTS + ~1h55m per epoch, 3147 batches/rank, ~0.44 it/s, 3 GPUs, 10 epochs ~19h. + examples_per_second only ~1.4-3.3 for a 19.8M-parameter model on 3 H100s - + the GPUs are STARVED (tiny batch + CFA memory-bandwidth bound), not + compute-limited. + Removing the teacher gave only ~15% (0.38 -> 0.44 it/s), because with + teacher_num_deltas=1 + reuse_student_delta the teacher was only ONE merged + 2x-batch no_grad call, not four forwards. + +REMAINING SPEED LEVERS (in order) + 1. GENERATOR_COV_CHECKPOINT=false - saves recomputing 4 student forwards. + ONLY if the measured PEAK allows it. The teacher's removal freed a whole + 19.2M-param deepcopy plus its activations, so this may now fit. MEASURE + FIRST. + 2. Raise batch back up toward A's 400000/32 if peak allows - improves H100 + utilization AND restores a cleaner comparison to A (the reduced batch is + currently a confound vs A). + 3. Remove NCCL_P2P_DISABLE=1 if it is set and P2P is healthy (it forces + allreduce through host memory). + 4. CFA query-dimension chunking to re-enable full 4x merging. This is a real + project (patching third-party gafl attention). Only worth it if the method + is validated and many runs are needed. + +DDP NOTES + strategy: ddp (Lightning default => find_unused_parameters=False, + static_graph=False). Multiple forwards + a SINGLE backward is fine. The graph + is kept static on purpose (extra forwards run every step when enabled). Do not + make the extra forwards conditional per-step without handling DDP dynamic + graphs. If you ever see "mark a variable ready only once", suspect + checkpointing interactions. + + +================================================================================ +14. HARD-WON PROCESS RULES +================================================================================ + 1. NEVER write a path/command from memory. Read the script or + ${RUN_DIR}/config.yaml first. This rule exists because it was broken + repeatedly (02_sample_test.sh ignores OUTPUT_DIR; 03_evaluate.sh needs + ATLAS_VIEW_ROOT; a hydra +ckpt_path override was silently ignored and a + "resume" started from scratch). + 2. config.yaml IS THE TRUTH. A stray LAMBDA_CONDITION_CYCLE=0.05 slipped into + a v2 command and was only caught by grepping config.yaml. Audit every run + before letting it burn hours. + 3. VERIFY RESUME by the loaded epoch/global_step in the first log lines, never + by the output directory name. + 4. THE LOCAL MACHINE CANNOT RUN ANYTHING. No python, no torch. Code you write + is unverified beyond careful reading. Say so plainly; do not hand over a + large untested training change and imply it is safe. + 5. Do not turn on several loss terms at once - attribution becomes impossible. + The local-shape-then-cross staging exists for this reason. + 6. Do not propose per-protein drilldowns as a default next step (the trace + explicitly bans this; they burned time without producing decisions). + 7. Watch the FIRST ~50 steps of any new run (gen_* finite and nonzero, + response nonzero). That costs nothing and catches silent no-ops. + 8. When a metric looks impossible (e.g. ratio = 4e6), check whether a + denominator is pinned at a clamp floor. Cross-check by seeing whether the + metric scales EXACTLY with the numerator across epochs. + + +================================================================================ +15. OPEN QUESTIONS / UNRESOLVED RISKS +================================================================================ + 1. ONE-STEP vs 20-STEP GAP. The response uses pred_trans, a single-step clean + prediction, not the 20-step ODE sampler's output. This is a known bias. The + defence is that a biased GENERATOR-AWARE signal beats the previous + GENERATOR-BLIND prior loss (whose bias was 100%). Unquantified. + 2. FIRST-ORDER / LINEARITY. +/-delta captures only the linear response. It can + be self-checked cheaply via the second difference + pred(+d)+pred(-d)-2*pred(0): small => linear regime holds. NEVER MEASURED. + Would cost one extra forward. + 3. c-INDUCED vs TOTAL VARIANCE (section 10 subtlety). + 4. NO DOWNSTREAM NUMBER EXISTS for ANY generator-response checkpoint. The + whole line is still validated only by training-side metrics. The first real + read must come from reproduction/02_sample_test.sh + 03_evaluate.sh. + 5. CROSS SHAPE IS UNTESTED. use_cross=true has never actually run. It is the + only component that can move PCA W2, and it is also the highest-variance, + N x N term - historically the seesaw's favourite. + 6. SIGNIFICANCE IS UNMEASURED (section 3). The 0.01-0.02 gaps may be noise. + 7. CACHE PATH DISCREPANCY (section 2) - /home/... vs ${REPRO}/... may not be + the same file as A used. Verify before claiming a clean A-vs-A+loss + ablation. + 8. BATCH SIZE CONFOUND. The current runs use 120000/10 while A used 400000/32. + Strictly this is not a clean ablation against A. Restore if memory permits. + + +================================================================================ +16. IMMEDIATE NEXT STEPS +================================================================================ + 1. Launch the cross+anchor run (section 11). Audit config.yaml immediately. + 2. At epoch 0-1, confirm gen_cross_shape_loss exists and falls, and that the + ratio holds near 0.9-1.0. If not, stop and fix the anchor weight rather + than running 10 epochs. + 3. First real deliverable: take a checkpoint (epoch 4 or later) through + 02_sample_test.sh (250 samples, CONDITION_MODE=real) and 03_evaluate.sh, + and put the four official numbers next to the section 3 scoreboard. THIS + HAS NEVER BEEN DONE FOR THIS MECHANISM. Everything so far is training-side. + 4. Only after a downstream number exists should anyone invest in CFA tiling, + batch restoration, or further loss engineering. + 5. If the downstream number is flat: the honest options are (a) the one-step + proxy is too weak and a real ensemble-level objective is needed (expensive, + previously rejected), or (b) revisit whether the official metrics can + measure what this method improves at all (section 4, last paragraph). +================================================================================ + + +================================================================================ +17. G-CALIBRATION + DIVERGENCE ROOT CAUSE + DIRECTION UPDATE (2026-07-18/19) +================================================================================ + +WHERE A30 ACTUALLY STANDS (do not understate this again) + A30 = bbflow_base_energy_from_q_diag_orth1_recon0_30ep. Full 250-sample: + RMSF r 0.89 | RMSF MAE 0.45 | Pairwise 0.79 | PCA W2 1.35. + - It WINS RMSF MAE (0.45 vs 0.47-0.48, real repeated), TIES RMSF r, and is + within BBFlow's own record-to-record noise on Pairwise/PCA W2 (0.01-0.02). + - SHUFFLED-condition control: Pairwise 0.79->1.27, PCA W2 1.35->1.51. So the + condition carries real, protein-specific information. A30 is a genuine + partial success, NOT "= BBFlow". The missing piece is a BROAD win (also beat + Pairwise AND PCA W2), which A30's generator-BLIND prior supervision cannot + reach - it sits on a documented seesaw (push PCA W2, lose Pairwise). + +WHAT THE CURRENT LINE CHANGES vs A30 + - generator-BLIND -> generator-AWARE: instead of supervising the prior + covariance, perturb c by +/-delta and supervise the GENERATOR's actual + response covariance. Directly targets the generator output structure (PCA + W2), the thing A30 structurally cannot move. + - G-calibration: measure G = T_full/T_1step where T_full is the c-response + trace on the REAL sampler (shared prior noise x0, full linspace(min_t,1,20) + grid, no_grad), then anchor the single-step response to md_trace/G. Fixes the + single-step-vs-20-step amplitude gap (measured G ~6.5-10x, i.e. the old + single-step anchor over-shot ~6-10x -> that was the source of the RMSF-4.6 + over-dispersion, NOT "unfrozen backbone"). + +BUGS FOUND AND FIXED THIS ROUND (all in the crash/over-disperse path) + - teacher anchor trained response to 0 -> replaced with md_trace reference. + - single-step vs 20-step 6.5x miscalibration -> G-calibration (rollout T_full + rewritten to start from shared prior noise x0 over the full grid; Codex's + first cut wrongly started from the training trans_t over 2 coarse steps). + - relative (LM) ridge in project_displacement_lstsq (absolute 1e-4 ridge was + swallowed in fp32 -> singular solve crash). + - THE DIVERGENCE ROOT CAUSE: mode normalization `u_global / mode_norm` + (latent.py ~469 and ~552) had NO stop-gradient. Backprop carries a + 1/mode_norm^2 term; once a mode collapses (norm -> the eps floor 1e-3) that + gradient explodes ~1e6x, burns the shared encoder to NaN (mixture logits NaN + -> Categorical crash at epoch 3). A positive feedback: shape loss nudges + modes collinear -> normalization amplifies the collapsed-mode gradient -> + more collapse. mode_orth (lambda 1) cannot beat a 1e6x amplified gradient. + FIX: detach mode_norm in both normalizations (forward identical, kills the + 1/c^2 path) + raise mode_norm_eps 1e-6 -> 1e-4. This is a real defect fix, + NOT gradient clipping (clipping would mask the divergence, not cure it). + +KEY DIRECTION UPDATE - RECONSIDER FREEZING + - Freezing the base was introduced to stop the cross-run over-dispersion. But + that over-dispersion was really the AMPLITUDE miscalibration, which G-cal now + fixes. A30 ran UNFROZEN and was stable + good, so "unfrozen" was never the + cause. + - Freezing also introduced the ADDITIVE CEILING: a frozen base can only ADD + motion, not REDISTRIBUTE it, and PCA W2 needs redistribution. So freezing + fights the actual goal. + - RECOMMENDED next run: UNFROZEN + G-cal + generator-aware response + anchor + warmup (0->target over ~3 epochs), NO gradient clipping (the mode_norm fix is + the real fix). This keeps A30's redistribution ability and adds generator- + aware targeting with the amplitude now calibrated. Watch official_loss (must + stay ~0.85, not rise = backbone degrading), mode_max_cosine_abs (<0.9), + cross_cov_far_corr (up = PCA proxy moving). + - Console epoch log was trimmed (bbflow_module.py on_train_epoch_end) to loss + + 5 tagged watch metrics, one per line. Full metrics remain in + latent_train_epoch_metrics.csv. + +DECISION RULE + - Next clean run's downstream (250 samples, real condition) vs A30/BBFlow: + - PCA W2 moves below 1.34 WITHOUT losing Pairwise -> generator-aware breaks + the seesaw; push it (possibly toward a fully differentiable few-step + rollout objective on the whole ensemble = the only form that can truly + force redistribution). + - PCA W2 flat / seesaw persists -> the additive/response-shaping family is + exhausted; A30 remains the best banked result and the only remaining bet is + the differentiable rollout objective, not more anchor/scale tuning. +================================================================================ + + +================================================================================ +18. ENDPOINT COVARIANCE TRANSPORT ROUTE (2026-07-19) +================================================================================ + +WHY THIS ROUTE EXISTS + The additive / single-step generator-response family kept falling into the same + two endpoints: + - unfrozen/additive response -> over-dispersed endpoint ensembles; + - frozen/weak response -> inert, approximately BBFlow. + + The new route does NOT retrain the generator and does NOT approximate 20-step + dynamics with fewer steps. It starts after true 20-step BBFlow sampling has + already produced endpoint structures. It then applies a cheap endpoint-level + covariance transport: + + base stream : official BBFlow, eq -> individual endpoint frames; + ensemble stream : low-rank learned/oracle correlation structure, applied as + an endpoint redistribution transform. + + The key constraint is marginal preservation: + + C* = D_B^1/2 [(1-lambda) R_B + lambda R_target] D_B^1/2 + + D_B is the diagonal variance of the BBFlow endpoint ensemble. Therefore the + transform is intended to preserve BBFlow's per-coordinate fluctuation scale and + total trace while changing only correlation/PCA structure. This is the first + cheap route that directly acts on real 20-step endpoints and can redistribute + variance instead of adding extra variance. + +IMPLEMENTED FILES + 1. scripts/covariance_transport_batch.py + - Batch transport for a standard ensemble directory. + - Inputs: + --ensemble_dir existing BBFlow sampled endpoint directory + --atlas_root ATLAS MD root with /.pdb and R1/R2/R3 xtc + --test_csv test CSV, normally dataset_csv/test/ATLAS_test.csv + --out_dir output directory with /sampled_conformations.pdb + --mode oracle or a30 + --lam global correlation mixing coefficient + - Output is CA-only multi-model sampled_conformations.pdb. This is enough + for the standard RMSF / Pairwise / PCA-W2 path because evaluation slices + both reference and model to CA for those metrics. Do NOT use CA-only output + to claim full backbone geometry quality. + - Uses sample-space whitening/coloring, not dense 3N x 3N eigendecomposition. + This keeps the cost bounded by the generated ensemble rank. + + 2. scripts/export_condition_modes.py + - Exports A30 learned condition modes from a checkpoint: + /.npy with shape [N,K,3]. + - Needed only for --mode a30. Oracle transport does not depend on A30. + +DISCIPLINED EXECUTION ORDER + Step 1: ORACLE transport first. + Purpose: test whether the transport mechanism itself can improve PCA-W2 while + keeping RMSF/Pairwise clean. This separates "transport is flawed" from "A30 + modes are not good enough". + + Step 2: Only if oracle is clean, export A30 modes and run A30 transport. + Purpose: measure how much of the oracle gain the learned A30 mode subspace can + realize. A30 mode-PC overlap on test82 was only around 0.4, so expected gain is + small, not transformational. + + Step 3: Evaluate with reproduction/03_evaluate.sh. + Required checks: + - RMSF MAE must not regress vs BBFlow/A30. + - Pairwise MAE must not regress. + - PCA W2 must improve below BBFlow's 1.34 to count as useful. + - If possible, add a separate structure-quality check before any paper claim, + because CA-only transport does not validate N/C/O geometry. + +SERVER COMMAND TEMPLATE - ORACLE TRANSPORT + cd ~/LD-FPG-main/bbflow_base + export PYTHONPATH=$PWD:${PYTHONPATH:-} + + REPRO_ROOT=/data/shared/wangyusong/atals/bbflow_official_reproduction + ENSEMBLE_DIR=$REPRO_ROOT/inference/checkpoints/ + OUT_DIR=$REPRO_ROOT/inference/cov_transport_oracle_lam0p50 + + python scripts/covariance_transport_batch.py \ + --ensemble_dir "$ENSEMBLE_DIR" \ + --atlas_root "$REPRO_ROOT/datasets/ATLAS" \ + --test_csv "$REPRO_ROOT/dataset_csv/test/ATLAS_test.csv" \ + --out_dir "$OUT_DIR" \ + --mode oracle \ + --lam 0.50 \ + --md_stride 1 \ + --overwrite + + ENSEMBLE_DIR="$OUT_DIR" \ + METRICS_DIR="$REPRO_ROOT/metrics/cov_transport_oracle_lam0p50" \ + METHOD_NAME="BBFlow-oracle-cov-transport-lam0p50" \ + ATLAS_VIEW_ROOT="$REPRO_ROOT/datasets/ATLAS" \ + TEST_CSV="$REPRO_ROOT/dataset_csv/test/ATLAS_test.csv" \ + NUM_WORKERS=8 \ + bash reproduction/03_evaluate.sh + +SERVER COMMAND TEMPLATE - A30 MODE TRANSPORT + cd ~/LD-FPG-main/bbflow_base + export PYTHONPATH=$PWD:${PYTHONPATH:-} + + REPRO_ROOT=/data/shared/wangyusong/atals/bbflow_official_reproduction + A30_CKPT= + MODES_DIR=$REPRO_ROOT/diagnostics/a30_condition_modes_test82 + ENSEMBLE_DIR=$REPRO_ROOT/inference/checkpoints/ + OUT_DIR=$REPRO_ROOT/inference/cov_transport_a30_lam0p50 + + python scripts/export_condition_modes.py \ + --ckpt_path "$A30_CKPT" \ + --csv_path "$REPRO_ROOT/dataset_csv/test/ATLAS_test.csv" \ + --output_dir "$MODES_DIR" \ + --overwrite + + python scripts/covariance_transport_batch.py \ + --ensemble_dir "$ENSEMBLE_DIR" \ + --atlas_root "$REPRO_ROOT/datasets/ATLAS" \ + --test_csv "$REPRO_ROOT/dataset_csv/test/ATLAS_test.csv" \ + --out_dir "$OUT_DIR" \ + --mode a30 \ + --modes_dir "$MODES_DIR" \ + --lam 0.50 \ + --md_stride 1 \ + --overwrite + + ENSEMBLE_DIR="$OUT_DIR" \ + METRICS_DIR="$REPRO_ROOT/metrics/cov_transport_a30_lam0p50" \ + METHOD_NAME="BBFlow-A30-cov-transport-lam0p50" \ + ATLAS_VIEW_ROOT="$REPRO_ROOT/datasets/ATLAS" \ + TEST_CSV="$REPRO_ROOT/dataset_csv/test/ATLAS_test.csv" \ + NUM_WORKERS=8 \ + bash reproduction/03_evaluate.sh + +FILES TO SYNC TO SERVER FOR THIS ROUTE + - scripts/covariance_transport_batch.py + - scripts/export_condition_modes.py + - docs/HANDOFF_2026-07-17.txt + +DECISION RULE + - Oracle transport fails or breaks metrics -> stop this route. The endpoint + transport mechanism is not viable. + - Oracle wins but A30 does not -> mechanism is viable, but A30's learned mode + subspace lacks enough test-time correlation information. + - A30 transport improves PCA W2 while preserving RMSF/Pairwise -> this is the + cleanest current "dual-stream" story: BBFlow supplies individual frames and + learned low-rank modes reshape endpoint ensemble correlations. +================================================================================ diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/docs/experiment_trace_2026-07-05.md b/bbflow_base/code_exports/a30_redesign_source_20260719/docs/experiment_trace_2026-07-05.md new file mode 100644 index 0000000000000000000000000000000000000000..fa6747a1a7e53619e4ff9e31112aaff1e1f3072f --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/docs/experiment_trace_2026-07-05.md @@ -0,0 +1,1367 @@ +# BBFlow / Latent Motion Experiments Trace + +Date: 2026-07-05 +Scope: local record of experiments, code changes, key configs, what each run tried to prove, and what it actually proved. + +This document is a working memory file. It should be updated whenever a run is launched, evaluated, killed, or reinterpreted. + +## Core Goal + +We are trying to improve BBFlow downstream ensemble quality on ATLAS test proteins, especially: + +- RMSF correlation / MAE +- Pairwise RMSD MAE +- PCA W2 + +The central scientific question became: + +> The latent condition/prior can improve some covariance/proxy statistics, but does that improvement actually transfer through the generator into saved conformations and downstream metrics? + +So far, multiple proxy metrics have failed to directly predict downstream performance. This motivated the current emphasis on mini-downstream validation and saved-conformation evaluation. + +## Important Code Files + +Core model/training: + +- `bbflow/models/latent.py` + - Latent motion prior. + - MoG coefficient prior. + - Motion target reconstruction losses. + - Added `pca_alignment_loss`. + +- `bbflow/models/bbflow_module.py` + - Integrates latent prior into training/inference. + - Looks up motion targets by current batch `pdb_name`. + - Added `lambda_pca_align` handling and PCA alignment logging. + +- `base_stages/00_train_final_mog_ddp.sh` + - Main 3/2-GPU latent training launcher. + - Supports `LAMBDA_MODE_ORTH`, `LAMBDA_MODE_RECON`, `LAMBDA_PCA_ALIGN`, `PCA_ALIGN_TOP_M`. + - Uses `experiment.warm_start` for official/model warm start or Lightning resume depending on checkpoint type. + +Downstream / inference: + +- `reproduction/02_sample_test.sh` + - Standard inference. + - Saves conformations as `sampled_conformations.pdb`. + - Supports `CONDITION_MODE`, `CONDITION_SCALE`, `POSTPROCESS_BFACTORS`, `SAMPLE_BATCH_SIZE`, `MAX_NUM_RES_SQUARED`. + +- `reproduction/03_evaluate.sh` + - Standard downstream evaluation on saved conformations. + - Computes RMSD/RMSF/PCA-W2. + +Analysis/diagnostics: + +- `scripts/diagnose_mode_pca_alignment.py` + - Compares learned prior modes against MD PCA modes on a chosen CSV. + - Outputs `summary.json` and per-protein CSV. + +- `scripts/evaluate_saved_condition_covariances.py` + - Evaluates generated/saved ensembles against MD covariance targets. + +- `scripts/plot_epoch_metrics.py` + - Plots training metrics from `latent_train_epoch_metrics.csv`. + +- `scripts/diagnose_training_contraction.py` + - Added after the PCA-align scale sweep. + - Reads existing epoch metrics and saved `sampled_conformations.pdb` files. + - Diagnoses whether downstream degradation is caused by ensemble amplitude contraction, MD-PC projection variance loss, or proxy/downstream mismatch. + +- `scripts/extract_shape_fingerprints.py` + - Generates motion-target cache. + - Newer caches should include alignment version `row_kabsch_u_d_vh_v1`. + - Can store `oracle_modes`, `oracle_energy`, `oracle_mean_disp`. + +- `scripts/validate_motion_target_cache.py` + - Checks required cache fields before expensive training. + +## Important Data / Checkpoint Paths + +Official BBFlow checkpoint: + +```text +/home/wangyusong/LD-FPG-main/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt +``` + +Official checkpoint rerun output: + +```text +/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/official_bbflow_rerun_250 +``` + +Main long finetune run: + +```text +/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_official_modelonly_long_finetune_orth1_recon0_100ep_3gpu_20260630_191404 +``` + +PCA-align 0.1 run: + +```text +/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_pca_align_orth1_recon0_30ep_3gpu_20260704_055826 +``` + +Scratch run currently being resumed: + +```text +/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_scratch_mog_k8_m2_orth1_recon0_30ep_2gpu_20260703_192644 +``` + +Motion target caches: + +```text +/data/shared/wangyusong/atals/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt +/data/shared/wangyusong/atals/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1_oracle.pt +``` + +Notes: + +- `_kabsch_v1.pt` is the non-oracle cache used by scratch run. +- `_kabsch_v1_oracle.pt` includes oracle PCA fields and was used for PCA-align training/diagnostics. +- Cache containing test entries is not automatically leakage. Leakage only happens if test proteins enter the training dataloader. The training dataloader uses `train_csv_path`; lookup into cache only happens for batch `pdb_name`. + +## Confirmed Code Behavior + +### Training Split vs Cache + +`PdbDataModuleBBFlow` reads: + +```text +data.dataset.train_csv_path +``` + +The train dataloader uses only `_train_dataset`. The motion target cache is a dictionary; `_lookup_motion_targets` only retrieves entries for the current batch `pdb_name`. + +Therefore: + +```text +cache contains test82 != test82 used in training +``` + +Actual leakage criterion: + +```text +train_csv names intersect test_csv names +``` + +User confirmed there was no train/test overlap. + +### Checkpoint Saving + +Current BBFlow training uses Lightning `ModelCheckpoint`: + +```yaml +save_last: True +save_on_train_epoch_end: True +filename: "epoch:{epoch:03d}" +every_n_epochs: 1 +save_top_k: -1 +``` + +Meaning: + +- Saves every epoch. +- Updates `last.ckpt`. +- Does not choose best checkpoint by validation metric. +- Base stage scripts set `experiment.first_val_epoch=inf`, so training does not run real validation/downstream. + +Current downstream commands usually test: + +```text +CKPT_PATH="$RUN_DIR/last.ckpt" +``` + +So by default we evaluate the final epoch, not best-val. + +## Experiment Log + +### 1. Official BBFlow Rerun + +Purpose: + +Prove that the evaluation pipeline and official checkpoint are correct. + +Checkpoint: + +```text +/home/wangyusong/LD-FPG-main/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt +``` + +Output: + +```text +/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/official_bbflow_rerun_250 +``` + +Result: + +```text +BBFlow-official-rerun-250: +RMSF r 0.89 +RMSF MAE 0.48 +Pairwise RMSD MAE 0.77 +PCA W2 1.34 +``` + +Conclusion: + +The checkpoint and downstream evaluation process are sound. The official result is reproducible enough. Any poorer latent-finetune result is probably real, not a pipeline artifact. + +### 2. Long Finetune, Official Warm Start, Orth1/ReCon0, 100 Epochs + +Run: + +```text +bbflow_base_official_modelonly_long_finetune_orth1_recon0_100ep_3gpu_20260630_191404 +``` + +Purpose: + +Test whether latent condition with orthogonal mode regularization and no mode recon loss improves standard downstream. + +Core config: + +```text +official BBFlow model-only warm start +3 GPU +100 epochs +lambda_mode_orth=1 +lambda_mode_recon=0 +sample_coefficients=true +freeze_foundation=false +condition_mode=real for inference +``` + +Downstream real result: + +```text +BBFlow-long-ft-orth1-recon0-real: +RMSF r 0.88 +RMSF MAE 0.48 +Pairwise RMSD MAE 0.81 +PCA W2 1.35 +``` + +Official rerun baseline: + +```text +RMSF r 0.89 +RMSF MAE 0.48 +Pairwise RMSD MAE 0.77 +PCA W2 1.34 +``` + +Conclusion: + +Long finetune did not beat official BBFlow. It is slightly worse, especially Pairwise RMSD. + +### 3. Shuffled Condition Downstream + +Purpose: + +Check whether real condition actually matters relative to a corrupted condition. + +Result: + +```text +BBFlow-long-ft-orth1-recon0-shuffled: +RMSF r 0.89 +RMSF MAE 0.48 +Pairwise RMSD MAE 1.27 +PCA W2 1.51 +``` + +Conclusion: + +Real condition is much better than shuffled for Pairwise/PCA. However, user judged shuffled/zero comparisons as non-substantive because official BBFlow still outperforms the real condition. Do not keep focusing on zero/shuffled unless specifically needed. + +### 4. Probe: Real vs Zero/Shuffled Covariance + +Purpose: + +Mechanistic check whether condition affects covariance/cross-covariance statistics. + +Key result: + +Real condition improved far cross-covariance correlation over zero/shuffled in probe. + +Representative deltas: + +```text +real - zero far_cross_cov_corr delta ≈ +0.045 +real - shuffled far_cross_cov_corr delta ≈ +0.029 +``` + +But rel_loss often got worse: + +```text +far_cross_cov_rel_loss delta worse by ~0.36-0.38 +``` + +Conclusion: + +Condition can improve some correlation structure, but scale/amplitude can be wrong. Also, probe statistics do not automatically transfer to saved-conformation downstream metrics. + +### 5. Mode-PCA Alignment Diagnosis on Long Finetune + +Purpose: + +Test whether learned prior modes align with MD principal motion directions. + +Command used `scripts/diagnose_mode_pca_alignment.py` on test82. + +Old long-finetune values: + +```text +all_learned_vs_md_top2_subspace_mean_sq_cos: 0.4848 +all_learned_vs_md_top2_subspace_min_sq_cos: 0.3500 +best_abs_cos_to_md_pc1: 0.5149 +best_abs_cos_to_md_pc2: 0.5416 +top_energy_abs_cos_to_md_pc1: 0.3302 +top_energy_abs_cos_to_md_pc2: 0.3461 +top2_energy_vs_md_top2_subspace_mean_sq_cos: 0.3086 +top2_energy_vs_md_top2_subspace_min_sq_cos: 0.1185 +``` + +Interpretation at the time: + +The learned mode set contains directions that partially align with MD PCs, but the energy-ranked top modes are not the best-aligned modes. This suggested an energy ranking/allocation problem. + +### 6. PCA Alignment Loss Added + +Purpose: + +Directly train energy-weighted learned modes to align with MD top PCA subspace. + +Code: + +- Added `LatentEncoder.pca_alignment_loss`. +- Added `lambda_pca_align`. +- Added metrics: + - `pca_align_loss` + - `pca_align_weighted_overlap` + - `pca_align_best_overlap` + - `pca_align_top_energy_overlap` + - `pca_align_top_energy_subspace_overlap` + +Loss idea: + +```text +learned modes U +MD oracle top PC1/PC2 +mode_overlap = squared projection of each learned mode into MD top-PC subspace +energy weights = predicted mode energy / total energy +loss = 1 - sum_k energy_weight_k * mode_overlap_k +``` + +This is not inference-time PCA. PCA is only used as training supervision where enabled. + +### 7. PCA-Align 0.1 Run, 30 Epochs, 3 GPU + +Run: + +```text +bbflow_base_pca_align_orth1_recon0_30ep_3gpu_20260704_055826 +``` + +Core config: + +```text +official BBFlow model-only warm start +3 GPU +30 epochs +lambda_mode_orth=1 +lambda_mode_recon=0 +lambda_pca_align=0.1 +pca_align_top_m=2 +condition real for inference +``` + +Training behavior: + +Metrics improved in train: + +```text +pca_align_weighted_overlap: +epoch 6 ≈ 0.0567 +epoch 17 ≈ 0.0799 +epoch 28 ≈ 0.1114 + +pca_align_top_energy_overlap: +epoch 6 ≈ 0.0969 +epoch 17 ≈ 0.1374 +epoch 28 ≈ 0.2160 + +mode_max_cosine_abs: +epoch 6 ≈ 0.6512 +epoch 17 ≈ 0.4076 +epoch 28 ≈ 0.3673 + +mode_gram_condition: +epoch 6 ≈ 809.9 +epoch 17 ≈ 4.297 +epoch 28 ≈ 3.758 + +cross_cov_far_corr: +epoch 6 ≈ 0.1811 +epoch 17 ≈ 0.2663 +epoch 28 ≈ 0.3009 +``` + +Initial interpretation: + +Training dynamics looked healthy. Alignment improved without mode collapse. + +Test82 mode-PCA diagnosis: + +```text +all_learned_vs_md_top2_subspace_mean_sq_cos: 0.3420 +best_abs_cos_to_md_pc1: 0.3997 +best_abs_cos_to_md_pc2: 0.4432 +top_energy_abs_cos_to_md_pc1: 0.2613 +top_energy_abs_cos_to_md_pc2: 0.2992 +top2_energy_vs_md_top2_subspace_mean_sq_cos: 0.2408 +``` + +Compared to old long-finetune diagnosis, all key alignment values decreased. + +Conclusion: + +`lambda_pca_align=0.1` improves training proxy metrics but does not generalize to held-out test82 mode-PCA alignment. It may overfit train proteins or distort the learned prior mode subspace. This checkpoint should not be treated as a positive result without downstream evidence. + +### 8. Leakage Clarification for PCA Oracle Cache + +Concern: + +The oracle cache included train/val/test entries: + +```text +atlas_full_md_motion_targets_k8_kabsch_v1_oracle.pt +``` + +At first, this was incorrectly called leakage. + +Corrected reasoning: + +- Cache can contain many proteins. +- Training only looks up current batch names. +- Current batch names come from train CSV. +- Therefore leakage only happens if test proteins are present in train CSV. + +User confirmed no train/test overlap. + +Conclusion: + +The test82 mode-PCA drop for PCA-align 0.1 is a clean negative result, not explained by train/test leakage. + +### 9. Scratch Run + +Run: + +```text +bbflow_base_scratch_mog_k8_m2_orth1_recon0_30ep_2gpu_20260703_192644 +``` + +Config from `config.yaml`: + +```text +warm_start: null +num_devices: 2 +lambda_mode_orth: 1.0 +lambda_mode_recon: 0.0 +lambda_pca_align: not present / 0 +num_modes: 8 +mixture_components: 2 +freeze_foundation: false +sample_coefficients: true +motion_target_cache_path: + /data/shared/wangyusong/atals/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt +``` + +Important correction: + +Resume should use the cache from this config: + +```text +atlas_full_md_motion_targets_k8_kabsch_v1.pt +``` + +Not the old default: + +```text +atlas_full_md_motion_targets_k8.pt +``` + +If resume is done with a Lightning checkpoint: + +```text +BASE_CKPT="$SCRATCH_RUN/last.ckpt" +RUN_DIR="$SCRATCH_RUN" +``` + +Then Lightning should restore epoch/optimizer/scheduler state. + +## Current Pending / Running Items + +### PCA-align 0.1 Downstream + +Purpose: + +Even though test82 mode-PCA alignment dropped, run full downstream to see whether this diagnosis correlates with saved-conformation metrics. + +Command intent: + +```text +single GPU +82 proteins +250 conformations/protein +SAMPLE_BATCH_SIZE=20 +MAX_NUM_RES_SQUARED=400000 +CONDITION_MODE=real +save sampled_conformations.pdb +evaluate RMSF / Pairwise RMSD / PCA W2 +``` + +Question to answer: + +```text +Does poorer mode-PCA alignment imply poorer downstream? +``` + +If yes: + +Mode-PCA diagnosis is useful as a negative filter. + +If no: + +Mode-PCA diagnosis is not reliable enough as a checkpoint selector. + +### Scratch Resume + +Purpose: + +Continue scratch training on GPUs 1,2 while GPU 0 can run downstream. + +Must use: + +```text +RUN_DIR = scratch run directory +BASE_CKPT = scratch last.ckpt +FINGERPRINT_CACHE = atlas_full_md_motion_targets_k8_kabsch_v1.pt +GPU_IDS=1,2 +NUM_DEVICES=2 +``` + +Do not accidentally resume scratch with oracle PCA cache or old non-versioned cache. + +## Lessons Learned + +### Proxy metrics are not enough + +The following are useful but not sufficient: + +- `cross_cov_far_corr` +- `cross_cov_far_loss` +- `pca_align_*` +- `mode_max_cosine_abs` +- `mode_gram_condition` + +They can improve in training while downstream or test82 diagnosis fails. + +### Need mini-downstream validation + +Current BBFlow saves every epoch but chooses `last.ckpt`, not best-val. This is weak model selection. + +Recommended next system: + +```text +Every N epochs or selected checkpoints: + sample 5-10 validation proteins + 50-100 conformations/protein + compute real downstream-like metrics: + RMSF + Pairwise RMSD + PCA W2 + generated covariance metrics + use this to choose checkpoint +``` + +This is not a training loss, but it is much closer to downstream than current proxy metrics. + +### Downstream tests must save conformations + +User requirement: + +> During testing/evaluation, always save conformations. Downstream metrics are first priority. + +Probe-only statistics do not replace standard downstream. + +### Checkpoint path discipline + +Never guess checkpoint paths. Confirm with: + +```bash +test -f "$CKPT_PATH" +grep relevant fields "$RUN_DIR/config.yaml" +``` + +Official checkpoint: + +```text +/home/wangyusong/LD-FPG-main/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt +``` + +Do not invent: + +```text +/data/.../bbflow_official_atlas/last.ckpt +models/bbflow-0.1/... under bbflow_base if absent +``` + +### Cache path discipline + +There are multiple caches with similar names: + +```text +atlas_full_md_motion_targets_k8.pt +atlas_full_md_motion_targets_k8_kabsch_v1.pt +atlas_full_md_motion_targets_k8_kabsch_v1_oracle.pt +``` + +Using the wrong one can cause: + +```text +alignment_version mismatch +missing oracle_modes/oracle_energy +changed training target +``` + +Before resume, read the run config and reuse the original cache unless intentionally changing the experiment. + +## Recommended Next Steps + +1. Do not keep trying to rescue the 60-epoch PCA-align checkpoint with a global scale. +2. Run the scale-group diagnosis: + - low group: proteins whose oracle best scale is `scale12` + - high group: proteins whose oracle best scale is `scale30` + - mid group: all remaining best scales +3. Compare low vs high groups using existing features: + - learned mode energies + - mode-PCA alignment diagnostics + - MD pairwise RMSD / PCA W2 + - generated amplitude and MD-PC variance diagnostics +4. Inspect the two extreme failure examples: + - `6qj0A`: over-spread at all scales + - `7c45A`: under-spread at all scales +5. If low/high groups separate cleanly by available inference-time features, test a per-protein scale rule. +6. If low/high groups do not separate, treat oracle per-protein scale as an upper bound that is not currently usable. +7. Implement mini-downstream validation so checkpoint selection is based on actual validation metrics, not only proxy losses. +8. If trying PCA-align again, lower `LAMBDA_PCA_ALIGN` such as `0.03` and early-stop by mini-downstream metrics. +9. Resume scratch only with the exact scratch config/cache and verify Lightning restore. + +## Claims We Can Make Now + +Safe claims: + +- Official BBFlow checkpoint and downstream evaluation pipeline are reproduced. +- Long latent finetune did not beat official BBFlow on standard downstream. +- Real condition is better than shuffled condition, but that is not sufficient because official BBFlow still wins. +- Probe/covariance improvements do not automatically imply downstream gains. +- PCA-align loss with `lambda=0.1` improves training alignment metrics but worsens held-out test82 mode-PCA diagnosis. +- Current BBFlow checkpoint selection is last-epoch, not best-validation. +- PCA-align `lambda=0.1` at 30 epochs can improve PCA W2 slightly under selected inference scales, but the standard downstream tradeoff is not a broad win because Pairwise RMSD MAE remains worse than official BBFlow. +- Continuing the same PCA-align run from 30 to 60 epochs improves proxy losses but degrades downstream, especially Pairwise RMSD and many scale settings. +- Global `condition_scale` cannot solve the 60-epoch checkpoint: median statistics can be moved, but per-protein Pairwise MAE remains poor. +- Per-protein oracle scale selection over the existing scale grid has a strong upper bound (`Pairwise RMSD MAE = 0.5583`), proving the scale issue is heterogeneous across proteins. +- Protein length alone does not explain the per-protein best scale split. + +Unsafe claims: + +- PCA-align improves downstream. +- Mode-PCA alignment is a reliable downstream predictor. +- Current PCA-align checkpoint is useful for final paper claims. +- Test leakage occurred just because cache contained test entries. +- A practical per-protein scale rule has been found. +- The oracle per-protein scale result is usable at inference time without a predictor. + +## 2026-07-07 Update: PCA-Align 30->60, Scale Sweep, and Per-Protein Scale + +### Runs / Outputs + +Main run: + +```text +/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_pca_align_orth1_recon0_30ep_3gpu_20260704_055826 +``` + +Important generated/evaluation directories: + +```text +standard_downstream_extend60_scale05_250 +standard_downstream_extend60_scale07_250 +standard_downstream_extend60_scale10_250 +standard_downstream_extend60_scale_gt1_grid_250 +contraction_diagnostics_30to60 +per_protein_scale_error_analysis +scale_group_diagnosis +``` + +### 30->60 Training Metrics + +The 30-epoch checkpoint was resumed to epoch 59/60 with Lightning optimizer state preserved. Training proxy metrics continued to improve: + +```text +motion_loss 1.664174 -> 1.323183 (-0.340991) +local_cov_loss 0.707414 -> 0.567489 (-0.139924) +cross_cov_loss 0.792517 -> 0.623544 (-0.168973) +cross_cov_far_corr 0.320930 -> 0.472915 (+0.151985) +cross_cov_far_loss 0.964359 -> 0.818648 (-0.145711) +rmsf_loss 0.302754 -> 0.203370 (-0.099384) +pca_align_loss 0.885546 -> 0.813072 (-0.072474) +pca_align_weighted_overlap 0.114454 -> 0.186928 (+0.072474) +pca_align_top_energy_overlap 0.207225 -> 0.310178 (+0.102954) +mode_coeff_abs 0.305543 -> 0.355761 (+0.050217) +mode_coeff_std 0.451974 -> 0.535341 (+0.083367) +q_nll_per_dim 0.099669 -> 0.184764 (+0.085096) +``` + +Interpretation: + +- The condition coefficient magnitude did not collapse; it increased. +- The model became better at the proxy losses. +- Downstream got worse anyway, proving the proxy/downstream gap is real. + +### 60-Epoch Global Scale Sweep + +Downstream for 60-epoch PCA-align checkpoint: + +```text +Official BBFlow: Pairwise MAE 0.78, Pairwise median 2.76, PCA W2 1.34, RMSF MAE 0.47 + +scale10: Pairwise MAE 0.88, Pairwise median 2.52, PCA W2 1.31, RMSF MAE 0.48 +scale12: Pairwise MAE 0.87, Pairwise median 2.74, PCA W2 1.39, RMSF MAE 0.49 +scale14: Pairwise MAE 0.92, Pairwise median 2.91, PCA W2 1.41, RMSF MAE 0.49 +scale16: Pairwise MAE 0.95, Pairwise median 3.05, PCA W2 1.39, RMSF MAE 0.52 +scale18: Pairwise MAE 0.98, Pairwise median 3.23, PCA W2 1.39, RMSF MAE 0.54 +scale20: Pairwise MAE 1.06, Pairwise median 3.33, PCA W2 1.45, RMSF MAE 0.58 +scale30: Pairwise MAE 1.49, Pairwise median 3.99, PCA W2 1.52, RMSF MAE 0.74 +``` + +Interpretation: + +- Increasing scale fixes the global Pairwise median around `scale12` to `scale14`. +- It does not fix Pairwise MAE. +- PCA W2 is best around `scale10`; larger scales damage PCA W2. +- Global `condition_scale` only moves overall amplitude; it cannot fix per-protein distribution shape. +- The 60-epoch checkpoint has no globally good scale. + +### Amplitude / Direction Diagnosis + +`diagnose_training_contraction.py` compared generated ensembles with MD amplitude and MD top-PC projection. + +For 60-epoch scales: + +```text + gen_amp_median/MD gen_amp_q90/MD PC1 var/MD PC2 var/MD residue RMS ratio +scale05 0.7112 0.7253 0.3385 0.5951 0.7260 +scale07 0.7458 0.7697 0.4147 0.7216 0.7620 +scale10 0.7947 0.8402 0.5364 0.9140 0.8208 +``` + +Interpretation: + +- Generated ensembles are too small at scales <= 1.0. +- PC1 variance is especially under-dispersed. +- But increasing global scale later showed that amplitude correction alone does not recover Pairwise MAE or PCA W2. + +### Per-Protein Scale Oracle + +Existing scale grid: + +```text +scale12, scale14, scale16, scale18, scale20, scale30 +``` + +For each protein, choosing the best scale by Pairwise RMSD absolute error gives: + +```text +oracle_pairwise_mae: 0.5583 +oracle_model_pairwise_median: 2.8824 +md_pairwise_median: 2.8905 +oracle_md_pca_w2_median: 1.346 +oracle_joint_pca_w2_median: 1.8231 +``` + +This is much better than: + +```text +official Pairwise MAE: 0.78 +best global 60ep scale Pairwise MAE: ~0.87 +``` + +Interpretation: + +- The 6-way discrete oracle is a strong signal, not a tiny tuning artifact. +- Different proteins need very different scales. +- The oracle is not usable directly because it uses MD ground truth to choose scale. +- It provides an upper bound and motivates a per-protein scale predictor/classifier. + +Best scale distribution: + +```text +scale12 31 proteins +scale30 27 proteins +scale18 9 proteins +scale20 7 proteins +scale14 7 proteins +scale16 1 protein +``` + +Interpretation: + +- The distribution is bimodal/extreme-heavy. +- This looks more like a classification problem than a continuous scale-regression problem. +- A simple global scale or simple length-based formula is unlikely to work. + +Length correlation: + +```text +corr(length, signed_error): about -0.10 to -0.12 across scales +corr(length, abs_error): about -0.03 to +0.04 +``` + +Interpretation: + +- Protein length alone does not explain whether a protein needs low or high scale. + +### Extreme Failure Examples + +Over-spread at all scales: + +```text +6qj0A +scale12: MD 3.4330, model 10.4792, diff +7.0462 +scale30: MD 3.4776, model 16.8809, diff +13.4032 +``` + +Under-spread at all scales: + +```text +7c45A +scale12: MD 9.6570, model 4.2683, diff -5.3888 +scale30: MD 9.6113, model 6.6184, diff -2.9929 +``` + +Interpretation: + +- These represent opposite failure modes. +- `6qj0A` is too mobile even at low scale. +- `7c45A` is too conservative even at extreme scale. +- This suggests that failure is not just a scalar amplitude problem; learned mode quality/energy or generator response differs qualitatively by protein. + +### Current Scientific Interpretation + +The project has moved through these stages: + +1. Latent condition improves some proxy statistics. +2. Standard downstream does not broadly improve over official BBFlow. +3. PCA-align can move PCA-related metrics but hurts or fails Pairwise RMSD. +4. More PCA-align training improves proxy losses but worsens downstream. +5. Global inference scale cannot solve the 60-epoch checkpoint. +6. Per-protein oracle scale has strong potential, but only if a non-oracle predictor can identify protein-specific scale needs. + +Plain-language summary: + +```text +The method has signal, but different proteins fail in opposite ways. +Some are already too energetic and need low scale. +Some are too conservative and need high scale. +A single global scale averages these failures and cannot win. +The next useful question is whether the low-scale and high-scale proteins can be distinguished using features available at inference time. +``` + +### Immediate Next Analysis + +Run the scale-group diagnosis: + +```text +low_scale12 = proteins whose oracle best scale is scale12 +high_scale30 = proteins whose oracle best scale is scale30 +mid_scale = all others +``` + +Compare group features: + +```text +num_res +md_pairwise +md_pca_w2 +joint_pca_w2 +learned_energy_top0/top1 +top_energy_abs_cos_to_md_pc1/pc2 +top2_energy_vs_md_top2_subspace_mean_sq_cos +all_learned_vs_md_top2_subspace_mean_sq_cos +generated amplitude diagnostics if merged +``` + +Important methodological point: + +- Do not rely only on Pearson correlation with continuous scale. +- The best-scale distribution is bimodal. +- Use group comparison / classification-style diagnostics first. + +Outcome criteria: + +- If low/high groups separate by inference-time features, test a per-protein scale rule. +- If they only separate by MD-ground-truth features, the oracle is not deployable. +- If they do not separate, treat per-protein oracle scale as an informative upper bound but not a practical method yet. + +## 2026-07-08 Command/Path Failure Reflection + +### What Happened + +During evaluation of the `energy_from_q_diag` 30-epoch run, I repeatedly gave wrong run/evaluation commands because I relied on memory of old command conventions instead of reading the current shell scripts first. + +The concrete failures were: + +1. I assumed `reproduction/02_sample_test.sh` accepted an `OUTPUT_DIR` environment variable. +2. In reality, `02_sample_test.sh` ignores `OUTPUT_DIR` and writes to: + +```text +${REPRO_ROOT}/inference +``` + +3. I therefore looked for generated conformations under the checkpoint `RUN_DIR`, where they did not exist. +4. I also assumed `reproduction/03_evaluate.sh` accepted `ATLAS_ROOT` and `OUT_DIR`. +5. In reality, `03_evaluate.sh` uses: + +```text +ENSEMBLE_DIR +ATLAS_VIEW_ROOT +METRICS_DIR +TEST_CSV +METHOD_NAME +``` + +6. Because I used the wrong reference variable, evaluation fell back to the default: + +```text +bbflow_base/reproduction/outputs/data/ATLAS +``` + +and produced repeated `No reference trajectory found` warnings. + +### Root Cause + +The root cause was not a confusing directory structure. The root cause was a bad operating procedure: + +```text +I wrote commands from memory before checking the current script interfaces. +``` + +This violated the project rule that paths and runtime commands must be checked against the actual code before being given. + +### Correct Script Interfaces + +For sampling: + +```bash +reproduction/02_sample_test.sh +``` + +uses: + +```text +REPRO_ROOT +METADATA_ROOT +CKPT_PATH +GPU_ID +SAMPLES_PER_PROTEIN +SAMPLE_BATCH_SIZE +MAX_NUM_RES_SQUARED +INFERENCE_NAME +CONDITION_MODE +CONDITION_SCALE +POSTPROCESS_BFACTORS +INFERENCE_NUM_WORKERS +``` + +and writes to: + +```text +${REPRO_ROOT}/inference +``` + +For evaluation: + +```bash +reproduction/03_evaluate.sh +``` + +uses: + +```text +ENSEMBLE_DIR +ATLAS_VIEW_ROOT +METRICS_DIR +TEST_CSV +METHOD_NAME +METHOD_TIME_SECONDS +NUM_WORKERS +``` + +and passes the reference trajectory directory through: + +```text +--md_dirs "${ATLAS_VIEW_ROOT}" +``` + +### Correct Evaluation Command Pattern + +For the `energy_from_q_diag` run, the correct structure is: + +```bash +RUN_DIR=/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_energy_from_q_diag_orth1_recon0_30ep_3gpu_20260707_165355 + +ENSEMBLE_DIR=/data/shared/wangyusong/atals/bbflow_official_reproduction/inference/checkpoints/bbflow_base_energy_from_q_diag_orth1_recon0_30ep_3gpu_20260707_165355/last/atlas_test_250_real \ +ATLAS_VIEW_ROOT=/data/shared/wangyusong/atals/bbflow_official_reproduction/datasets/ATLAS \ +METRICS_DIR="$RUN_DIR/standard_downstream_metrics_real_250" \ +METHOD_NAME="BBFlow-energy-from-q-diag-30ep-real-250" \ +TEST_CSV=/data/shared/wangyusong/atals/bbflow_official_reproduction/dataset_csv/test/ATLAS_test.csv \ +bash reproduction/03_evaluate.sh +``` + +### Rule Going Forward + +Before giving any command involving paths, output directories, or environment variables: + +```bash +grep -n "VARIABLE_NAME\|script_argument" target_script.sh +``` + +or open the script directly. + +No command should be given from memory when the script interface is available. + +Minimum checklist: + +1. Read the sampling/evaluation script. +2. Confirm the exact environment variables it accepts. +3. Confirm where it writes outputs. +4. Confirm the real generated directory with `find`. +5. Only then provide the final command. + +This is especially mandatory for: + +```text +02_sample_test.sh +03_evaluate.sh +training scripts +checkpoint resume commands +cleanup commands +``` +# Non-negotiable oracle policy (2026-07-09) + +- Oracle information is forbidden in training, checkpoint selection, inference, + calibration, routing, gating, or any deployable method component. +- This includes test/validation MD frames, projected per-frame oracle + coefficients, oracle PCA modes/energies, oracle best scales, and any feature + derived from the target ensemble. +- Oracle quantities may only be used after generation as offline diagnostic + labels or upper-bound analyses. They must never influence model parameters, + hyperparameters selected on test data, or per-protein inference behavior. +- Before every run, verify the effective config and cache path. A cache that + contains oracle fields must not be used by a training or inference command, + even if the current code path appears not to read those fields. +- Any proposed experiment that conditions the generator on projected target + coefficients is diagnostic-only and cannot be presented as an inference + method or used to select a deployable checkpoint. + +## Inference performance lesson (2026-07-09) + +- Do not call multi-GPU parallelism an algorithmic inference speedup. Report + single-GPU latency separately from throughput scaling. +- The old sampler performed avoidable work at every ODE step: it copied every + clean prediction to CPU, retained the complete rigid trajectory, converted + every step to atom37, recomputed equilibrium geometry, and reran condition + adapter MLPs even though only the final frame was written. +- The optimized path keeps only the current ODE state and final frame, caches + equilibrium/condition features once per sample batch, and exposes the number + of function evaluations explicitly. +- A true order-of-magnitude latency reduction requires reducing ODE model + evaluations (for example 20 to 5) in addition to removing implementation + waste. Any lower-NFE preset must pass downstream-quality comparison before it + replaces the 20-step reference. + +## Diagnostic script reliability lesson (2026-07-10) + +- Do not assume metadata columns. The ATLAS test CSV used here contains only + `name` and `pdb_path`; diagnostic scripts must derive the protein folder from + `Path(pdb_path).parent` or fail loudly. +- Do not use guessed MD frame indices. If `num_conformations` is absent, read + the real frame count from the trajectory file. If the trajectory cannot be + opened, stop the diagnostic instead of silently using early frames. +- Do not rely on upstream device placement in diagnostic code. Any function that + combines generated tensors with dataset frames must explicitly move all inputs + to the generated tensor's device at the function boundary. This is mandatory + for projection/cycle-consistency diagnostics where generated coordinates, + equilibrium coordinates, mode tensors, and masks are mixed. +- Before asking the user to rerun a new diagnostic script on the server, run a + local syntax check and inspect every path where CPU/GPU tensors are mixed. + Repeated server failures from avoidable metadata or device assumptions waste + GPU time and user trust. + +## Checkpoint resume lesson (2026-07-11) + +- Do not assume a Hydra override such as `+ckpt_path=...` will be consumed by a + training wrapper. If the wrapper script does not explicitly forward that key + to `Trainer.fit(ckpt_path=...)`, the run may silently start from scratch while + still writing into the intended `RUN_DIR`. +- Before giving any resume command, inspect the training wrapper for the exact + resume variable/name it supports, then verify the command line printed by the + script contains that value. +- A resume command is not considered valid until the first log lines show the + loaded checkpoint epoch/global_step or the next epoch continues after the + checkpoint. If `last.ckpt` was epoch 15, seeing `Epoch 0/1/2` means the command + failed and must be stopped immediately. +- Never continue a suspected resume run just because the config path or `RUN_DIR` + looks correct. Effective resume state is determined by loaded optimizer state + and epoch/global_step, not by output directory names. + +## Evaluation reference path lesson (2026-07-11) + +- Evaluation commands must explicitly set the real ATLAS reference trajectory + directory. Do not allow `reproduction/03_evaluate.sh` or + `scripts/analysis_script.py` to fall back to + `reproduction/outputs/data/ATLAS`, because that local default does not contain + the ATLAS trajectories used for these runs. +- Before every evaluation, inspect `reproduction/03_evaluate.sh` and pass the + exact reference variable it supports, pointing to: + `/data/shared/wangyusong/atals/bbflow_official_reproduction/datasets/ATLAS`. +- If warnings say `No reference trajectory found for ... in + /home/wangyusong/LD-FPG-main/bbflow_base/reproduction/outputs/data/ATLAS`, + stop the evaluation immediately. The generated ensembles may be correct, but + the evaluation command is using the wrong reference path and the metrics are + invalid. + +## Per-protein analysis lesson (2026-07-11) + +- Do not propose per-protein drilldowns as the default next step. In this + project, repeated per-protein analyses have consumed time without producing + stable design decisions. +- Avoid narratives based on a few named proteins or post-hoc per-protein + examples unless the user explicitly asks for case studies. +- Prefer mechanism-level diagnostics that aggregate over a fixed protein set: + subspace vs residual decomposition, distribution-level statistics, paired + checkpoint comparisons, and controlled ablations. +- If a proposed analysis requires interpreting individual protein identities, + treat it as low priority and do not use it to decide the next method change. + +## Code-inspection-before-guessing lesson (2026-07-13) + +- If the answer is determined by repository code, generated configs, or wrapper + scripts, inspect those files before advising the user. Do not answer with + "probably", "likely", "should", or similar uncertainty when the code can give + a concrete answer. +- Before saying an inference job can resume, skip existing proteins, preserve + partial outputs, or avoid overwriting, inspect the exact inference script and + output-writing path. Do not infer skip/overwrite behavior from naming + conventions or previous runs. +- Before recommending checkpoint paths or checkpoint cadence, list the actual + checkpoint files and read the saved run `config.yaml`. Log epochs are not + checkpoint files, and `last.ckpt` only reflects the configured checkpoint + trigger. +- When a prior answer was based on an unchecked assumption, stop and correct the + workflow by reading the relevant code/config first; do not ask the user to + continue experiments based on that assumption. + +## Do-not-close-experiments lesson (2026-07-13) + +- Do not declare an experiment line finished, archived, or ready to stop unless + the user explicitly says to conclude it. A negative or mixed result should be + recorded as a stage observation, not as a terminal decision. +- Phrases like "archive this route", "stop this line", or "this is the final + conclusion" require explicit user approval. Until then, continue treating the + result as evidence for the next design decision. +- When reporting a failed or mixed checkpoint, separate the measured fact from + the decision: state what changed in the metrics, then propose next options + without closing the project direction on the user's behalf. + +## Training launch lesson (2026-07-13) + +- Do not start long training jobs with a trailing background `&` in commands + given to the user unless the user explicitly asks for background execution. + The shell job marker like `[1] 1350285` is not useful operational feedback and + has repeatedly made process control harder. +- Prefer foreground commands with `2>&1 | tee "$RUN_DIR/train_console.log"` so + the user sees failures immediately while logs are still saved. Use `tmux`, + `screen`, or an explicit scheduler only when the user requests detached runs. +- If a previous command used background execution and must be stopped, give + concrete `pkill`/`ps` checks before any new launch command. + +## DDP/NCCL launch stability lesson (2026-07-14) + +- On `gn11`, do not "simplify" or delete the known-good DDP/NCCL environment + block when only testing model, loss, or batch-size changes. This mistake has + repeatedly produced startup hangs where both H100s show about 660 MiB memory + and 100% GPU utilization before real training begins. +- The current stable dual-GPU launch template for `00_train_final_mog_ddp.sh` + must keep: + - `NCCL_DEBUG=WARN` + - `NCCL_ASYNC_ERROR_HANDLING=1` + - `NCCL_IB_DISABLE=1` + - `NCCL_P2P_DISABLE=1` + - `NCCL_SOCKET_IFNAME=enp1s0` + - `GLOO_SOCKET_IFNAME=enp1s0` + - `MASTER_ADDR=127.0.0.1` + - `MASTER_PORT=$((20000 + RANDOM % 20000))` + - `EXTRA_HYDRA_ARGS="experiment.trainer.strategy=ddp"` +- For controlled experiments, change only the intended experimental variables + such as `MAX_NUM_RES_SQUARED`, `MAX_BATCH_SIZE`, loss weights, epoch counts, + or generator-cov settings. Do not change communication variables at the same + time; otherwise a hang cannot be attributed to the model change. +- If `nvidia-smi` shows tiny memory use with 100% GPU utilization, treat it as a + DDP/NCCL launch hang first. Kill the training PIDs, restore the known-good + DDP/NCCL block above, and only then retry. + +## Generator-response downstream reckoning (2026-07-18) + +This is the first session where the generator-response line was ever measured on +DOWNSTREAM ensemble metrics (sampling + analysis_script), not just training-side +proxies. Every conclusion below is grounded in a measured 5znjA/82-protein read. + +### 0. What was fixed at the start, and what it exposed +- The `teacher_trace` anchor was diagnosed as a dead reference: the teacher is a + `deepcopy` of the model at the first step, when all condition adapters are still + zero-init, so its condition response is identically 0. `clamp_min(1e-8)` pinned + `teacher_trace` to a constant, and `trace_loss=log(trace_sample/1e-8)^2` was + actively training the student response TO ZERO. Confirmed by arithmetic on the + logged `trace_mean`/`ratio` (ratio proportional to student trace; teacher const). +- Fix applied: anchor reference switched teacher -> MD trace (`md_trace`, reuses + `trace_target` already computed for shape normalization). Teacher forwards + skipped entirely. `latent.py` `project_displacement_lstsq` also got a relative + (Levenberg-Marquardt) ridge because the absolute 1e-4 ridge was swallowed in + float32 once unnormalized-mode gram scale grew large -> `torch.linalg.solve` + crashed mid-epoch (singular). Both are correct fixes, but see section 3. + +### 1. First downstream numbers (gen_cov + cross, md_trace anchor, UNFROZEN) +5znjA + full 82. BBFlow (Ours) reference row RMSF-MAE/Pairwise-MAE/PCA-W2 = +0.47 / 0.78 / 1.34. Measured `gen_cov_cross_ep{0,2,4}`: +- RMSF MAE 6.04 / 6.97 / 5.19 (~10x worse) +- Pairwise 7.34 / 8.83 / 6.40 (~8x worse) +- PCA W2 3.12 / 1.70 / 1.58 +- RMSF r 0.06 / 0.59 / 0.70 (PATTERN is learned and improving) +Scale-invariant metrics (r, PCA-W2) improve while absolute-A metrics are ~3x +inflated -> "correct pattern, wrong magnitude" = over-dispersion, not garbage. +5znjA pseudo-RMSF mean 4.72, uniform (median 4.71, min 3.28), NO rigid core. + +### 2. Ruling out the pipeline and the config (both clean) +- `analysis_script.py:31-37` the leaderboard rows (BBFlow 0.47 etc.) are HARDCODED + paper constants, NOT recomputed. The table cannot validate the pipeline. +- Kabsch-aligning the 100 samples: 4.72 -> 4.65. Superposition removes nothing -> + the dispersion is genuine internal conformational spread, not a framing artifact. +- `condition_scale` sweep on ep004: 1.0/0.5/0.25 -> 4.62/4.51/4.56. SCALE-INVARIANT + -> the over-dispersion is in the BASE/backbone, not the condition. The condition + is nearly inert at sampling; the backbone absorbed both the pattern (r up) and + the diffuseness. +- CONTROL: official `bbflow-0.1.ckpt` (latent OFF) through the SAME pipeline -> + pseudo-RMSF 1.46 (matches MD median 1.48), 59% residues < 1.5 (proper rigid + core). Pipeline + sampler are CORRECT. The problem is 100% our model. +- Config-mismatch also ruled out: re-sampling ep004 with the checkpoint's exact + latent config (`energy_from_q`, `sample_coefficients`, etc., which `inference.yaml` + omits and would silently drop under `strict=False`) still gave 4.62. + +### 3. Root cause (corrected twice; final version) +- `freeze_foundation` was ALWAYS false (backbone always trainable). It is NOT the + differentiator vs older "comparable-at-best" runs. (First wrong hypothesis.) +- The real change this session was teacher->md_trace, which flipped the condition + from SUPPRESSED (teacher anchor trained response->0 => condition inert => model + ~= base BBFlow => old runs looked "fine / slightly worse") to ALIVE for the + first time. An alive condition whose amplitude is calibrated on the SINGLE-STEP + `pred_trans` response (training `gen_trace_ratio ~= 1.0`) over-disperses ~3x once + run through the real 20-step ODE sampler. official_loss rose 0.85 (no-cross) -> + 1.5 (cross) and stayed elevated: aux losses degraded the trainable base. +- `condition_scale`-invariance is the tell: the damage is baked into the backbone, + not delivered by the condition at sample time. + +### 4. Frozen isolation run (freeze_foundation=true, trace_anchor=0, shape only) +`_freeze_foundation_model` (bbflow_module.py:171) freezes all of `self.model` +except 5 injection modules (z_node/z_edge/disp_node/disp_edge adapters + film_mlp); +`_set_frozen_foundation_eval` re-applies eval() every epoch. Verified clean. +- BASE PRESERVED: official_loss 0.88 -> 0.66 -> 0.44 (falling, not rising). Freeze + protects marginals by construction. This half of the thesis WORKS. +- CONDITION WENT INERT: gen_response_abs_mean 0.018 (vs 0.48), gen_trace_mean + ~1.9 (vs 1103), gen_trace_ratio 0.0016 (~0.2% of MD). cross_cov_far_corr flat + ~0.11. Reason: with trace_anchor=0 there is NOTHING driving condition amplitude, + and the shape losses are SCALE-INVARIANT (indifferent to amplitude). Zero-init + adapters + no amplitude driver => condition stays ~0, shaping a negligible signal. +- Net: frozen+no-anchor -> ~= BBFlow (base preserved, no gain). + +### 5. The design box, and the fundamental diagnosis +- trace_anchor ON at single-step MD -> 20-step overshoot ~3x (unfrozen: 4.6). +- trace_anchor OFF -> condition starves to inert (frozen: ~BBFlow). +- A scaled anchor target (e.g. md/9) would be a FUDGE FACTOR for the single-step + vs 20-step gap -> parameter tuning, not a cure. +- ROOT CAUSE of all of it: the objective measures the SINGLE-STEP `pred_trans` + response, never the actual 20-step sampled ensemble. Amplitude is therefore + miscalibrated by construction and every proxy (trace ratio, shape losses) is + measured on the wrong quantity (generator-blind). +- Additional structural limit: a FROZEN base can mostly only ADD motion, not + REDISTRIBUTE it; improving PCA W2 requires redistribution (less motion in wrong + directions, more in MD directions). So even a perfectly amplitude-calibrated + frozen run likely has a PCA-W2 ceiling. (FiLM gives partial redistribution.) +- FUNDAMENTAL CURE (not yet built): compute the objective on a differentiable + FEW-STEP rollout of the real sampler and match MD ensemble statistics on it. + Then amplitude is correct by construction, the signal is generator-aware, no + per-protein fudge factor, and it works frozen or unfrozen. This is a real + implementation (differentiable 2-4 step rollout + ensemble covariance), not a knob. + +### 6. Lessons +- Training-side proxies on this line do NOT predict downstream and repeatedly + misled (trace_ratio ~1 while the sampler was 3x over-dispersed). Always get a + downstream read before concluding a generator-response run is good or bad. +- The leaderboard table printed by `03_evaluate` is hardcoded reference values; + never treat "BBFlow (Ours)" appearing next to your row as pipeline validation. +- To sample a latent checkpoint, `experiments/inference.py` must be given the + checkpoint's latent config explicitly (`+latent.energy_from_q`, `sample_coefficients`, + `mixture_components`, ...). `inference.yaml` omits them; `strict=False` then + silently loads a random q-head and produces garbage that looks like a model fail. +- `00_train_final_mog_ddp.sh` hardcoded `latent.freeze_foundation=false`; it is now + an env var (`FREEZE_FOUNDATION`). Verify freeze at runtime via the first + `[grad-flow-check]` line: `bbflow_backbone ... params_with_grad` drops 534 -> ~20. + +## Rollout-aware G-calibration: works, then diverges (2026-07-18, later) + +Built rollout amplitude calibration: measure G = T_full / T_1step where T_full is the +c-response trace on the REAL sampler (shared prior noise x0, full linspace(min_t,1,20) +grid, no_grad, few proteins, once per interval), then anchor the single-step response to +md_trace * (1/G_ema). Fixes the single-step vs 20-step miscalibration WITHOUT a fudge +factor. (Codex's first cut measured T_full from the training-time trans_t over 2 coarse +steps -> silently wrong G; corrected to prior-noise + full grid in `_rollout_final_pred_trans`.) + +RESULT of frozen + G-cal + anchor 0.3 (bbflow_frozen_Gcal, run 20260718_172144): +- The mechanism WORKS. G measured ~6.5 -> 10.5 (EMA), empirically confirming the 20-step + sampler amplifies the single-step response ~6-10x (bigger than the ~3x guessed earlier; + this is exactly why the old single-step anchor over-dispersed). Condition went ALIVE: + gen_response_abs_mean 0.16 (vs 0.018 inert / 0.48 over), gen_trace_ratio_to_anchor + 0.63 -> 0.93 -> 0.99 converging to the calibrated target. First stable-ish "alive, + calibrated" condition ever observed. +- But it DIVERGED. Latent mode geometry collapsed monotonically from epoch 0: + mode_max_cosine_abs 0.928 -> 0.987 -> 0.989, mode_gram_min_eig 1.14 -> 0.031, + mode_gram_condition 2.8e5 -> 3.1e5 -> 5.4e13; official_loss 4.3 -> 5.7 (high, and the + frozen backbone cannot be the cause). At epoch 3 step 220 (a NON-measure step, so the + rollout is NOT in the crash path) the prior mixture head produced NaN logits -> + Categorical crash in sample_coefficients_from_q. There is NO gradient clipping anywhere + in the codebase. +- Reading: the calibrated anchor driving the condition to MD amplitude, on a frozen base + whose amplitude is already correct, fights the mode structure (mode_orth loss at 1.0 did + not hold it) and collapses the latent to NaN. This is the "additive tension" made concrete + as a divergence. Frozen+additive is now boxed both ways: no anchor -> inert; anchor -> diverge. + +OPEN: is the divergence a maskable instability or a genuine defect? Decided NOT to paper it +with gradient clipping (that hides the divergence signal instead of finding the root cause). +Next when resumed: find the actual NaN source in the latent forward (mixture head / mode +normalization / the near-degenerate-gram path) rather than clipping; and evaluate the +pre-NaN checkpoint (epoch 1, condition alive, geometry not yet fully collapsed) downstream +to see whether an alive-but-pre-collapse condition moved PCA W2 at all -- the only signal +this run line can still yield. diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/docs/protein_project_conversation_record_2026-07-13.txt b/bbflow_base/code_exports/a30_redesign_source_20260719/docs/protein_project_conversation_record_2026-07-13.txt new file mode 100644 index 0000000000000000000000000000000000000000..303d9841675885ff53decc8d01593ca34da9b3be --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/docs/protein_project_conversation_record_2026-07-13.txt @@ -0,0 +1,71 @@ +Protein Project Conversation Record +Date: 2026-07-13 + +Raw local Codex storage: +C:\Users\wykstc\.codex\sessions\2026\... +C:\Users\wykstc\.codex\archived_sessions\... + +Project context: +- Workspace: D:\pycharm\pythonProject\protein +- Main repo discussed: bbflow_base +- Goal: improve BBFlow-like protein generation and evaluation, especially checkpoint handling, inference behavior, and post-training diagnosis. + +Key conversation record: + +1. Training resume and checkpoint behavior +- We traced why a resumed run only had epoch:004.ckpt and last.ckpt, both at epoch=4/global_step=17995. +- The server run used a config with every_n_epochs: 5, so checkpoints were only written every five epochs. +- We added a project lesson that code/config must be inspected before claiming resume/skip/checkpoint behavior. +- We updated the local training launcher bbflow_base/base_stages/00_train_base_ddp.sh to expose checkpoint cadence explicitly through: + CHECKPOINT_EVERY_N_EPOCHS + CHECKPOINT_SAVE_LAST + CHECKPOINT_SAVE_TOP_K +- Default behavior in that script is now every epoch save, save_last=true, save_top_k=-1. + +2. Inference and resume lessons +- We confirmed that the inference pipeline can skip proteins that already have sampled_conformations.pdb, by checking the code path in bbflow_module.py. +- We added a lesson to the project trace: do not assume inference will skip or resume safely unless the code path is inspected. +- We confirmed that a killed inference run can be resumed with the same INFERENCE_NAME if complete protein outputs already exist; completed proteins are skipped, incomplete ones are recomputed. +- We recorded that the raw inference logs and outputs live under the shared reproduction tree, not in the repo itself. + +3. Generator-response training direction +- We introduced and implemented a generator-response covariance loss path in bbflow_module.py. +- The implementation samples a perturbation around q, forms c_plus and c_minus, runs two extra generator forwards, and uses their difference to compute a covariance-like training signal. +- The motivation was to make the covariance supervision pass through the generator instead of only living in the prior/q statistics. +- Internal metric trends during the run were promising: + - gen_response_abs_mean increased steadily. + - gen_rmsf_loss and gen_cov_loss decreased. + - cross_cov_far_corr improved. +- The run was interrupted by host fan warnings and SIGTERM. + +4. Inference run interruption and file protection +- We stopped an inference run when the host fan health alarms triggered. +- The run was started with: + INFERENCE_NAME=atlas_test_250_genresp_v1_epoch004_5ep_real + CKPT_PATH=.../epoch:004.ckpt +- We confirmed the inference code skips already-completed proteins based on the presence of sampled_conformations.pdb in the output directory. +- We recorded that partial outputs are not automatically guaranteed to be safely reused unless that file exists. + +5. Diagnostic rigor lessons +- We documented multiple times that code/config must be checked directly before claiming: + - checkpoint cadence + - resume behavior + - inference skip behavior + - device placement + - reference-path selection +- We explicitly recorded that the project should not rely on "probably" or "likely" when the repository code can determine the answer. +- We also recorded that per-protein drilldowns are low priority unless explicitly needed. + +6. Where the raw conversation is stored +- The Codex desktop app keeps its local session archive under: + C:\Users\wykstc\.codex\sessions\YYYY\MM\DD\rollout-*.jsonl +- Older archived sessions may also appear under: + C:\Users\wykstc\.codex\archived_sessions\rollout-*.jsonl +- The project repo itself does not store the raw full transcript automatically unless we write a copy into docs/. + +7. Working conclusion at the end of this thread +- The current best recoverable checkpoint from the interrupted run is epoch:004.ckpt. +- The correct next action is to infer from that checkpoint if needed, or resume from it with explicit checkpoint saving cadence set to every epoch. +- The repository now contains a direct note that checkpoint behavior must be verified from config.yaml and actual ckpt files rather than from log epoch labels. + +End of record. diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/experiments/inference.py b/bbflow_base/code_exports/a30_redesign_source_20260719/experiments/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..029d90ac45f7042b38ecf7480c4e28a6ba1c49a6 --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/experiments/inference.py @@ -0,0 +1,171 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""DDP inference script.""" +import os +import time +import numpy as np +import hydra +import torch +from torch.utils.data import DataLoader +from typing import Optional +from pathlib import Path +import pandas as pd +from pytorch_lightning import Trainer +from omegaconf import DictConfig, OmegaConf +import logging + +from gafl import experiment_utils as eu + +from bbflow.models.bbflow_module import BBFlowModule +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb + +log = eu.get_pylogger(__name__) +logging.getLogger('MDAnalysis.analysis.base').setLevel(logging.WARNING) +logging.getLogger('MDAnalysis.analysis.align').setLevel(logging.WARNING) +torch.set_float32_matmul_precision('high') + +class Sampler: + + def __init__(self, cfg: DictConfig): + """Initialize sampler. + + Args: + cfg: inference config. + """ + ckpt_path = cfg.inference.ckpt_path + assert os.path.isfile(ckpt_path), f'Checkpoint path {ckpt_path} does not exist!' + ckpt_dir = os.path.dirname(ckpt_path) + cfg_path = os.path.join(ckpt_dir, 'config.yaml') + assert os.path.isfile(cfg_path), f'Config file {cfg_path} does not exist!' + ckpt_cfg = OmegaConf.load(os.path.join(ckpt_dir, 'config.yaml')) + + # Set-up config. + OmegaConf.set_struct(cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(cfg, ckpt_cfg) + cfg.experiment.checkpointer.dirpath = './' + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + # both only necessary if prior != pure_noise + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.model.embed = ckpt_cfg.model.embed + + self._cfg = cfg + self._ckpt_cfg = ckpt_cfg + self._infer_cfg = cfg.inference + self._samples_cfg = self._infer_cfg.samples + self._rng = np.random.default_rng(self._infer_cfg.seed) + + # Set-up directories to write results to + if self._infer_cfg.use_ckpt_name_in_outpath: + self._ckpt_name = '/'.join(ckpt_path.replace('.ckpt', '').split('/')[-3:]) + self._output_dir = os.path.join( + self._infer_cfg.output_dir, + self._ckpt_name, + self._infer_cfg.name, + ) + else: + self._output_dir = os.path.join( + self._infer_cfg.output_dir, + self._infer_cfg.name, + ) + os.makedirs(self._output_dir, exist_ok=True) + config_path = os.path.join(self._output_dir, 'config.yaml') + with open(config_path, 'w') as f: + OmegaConf.save(config=self._cfg, f=f) + log.info(f'Saving inference config to {config_path}') + + self._flow_module = self.load_module(ckpt_path) + self._flow_module.eval() + self._flow_module._infer_cfg = self._infer_cfg + self._flow_module._samples_cfg = self._samples_cfg + self._flow_module._output_dir = self._output_dir + + def load_module(self, ckpt_path): + # Keep the module on CPU until Lightning assigns one copy to each DDP rank. + ckpt = torch.load(ckpt_path, map_location='cpu') + module = BBFlowModule(self._cfg) + current_state = module.state_dict() + compatible_state = { + k: v for k, v in ckpt["state_dict"].items() + if k in current_state and current_state[k].shape == v.shape + } + module.load_state_dict(compatible_state, strict=False) + return module + + def run_sampling(self): + visible_device_count = torch.cuda.device_count() + requested_devices = int(self._infer_cfg.num_gpus) + if visible_device_count < requested_devices: + raise RuntimeError( + f"Requested {requested_devices} CUDA device(s), but PyTorch sees " + f"{visible_device_count}. Check CUDA_VISIBLE_DEVICES." + ) + devices = list(range(requested_devices)) + device_names = [torch.cuda.get_device_name(i) for i in devices] + log.info(f"Using devices: {devices} ({device_names})") + # eval_dataset = eu.LengthDataset(self._samples_cfg) + + if self._infer_cfg.csv_path is not None: + csv = pd.read_csv(self._infer_cfg.csv_path) + # randomly subsample proteins if num_proteins is set + if self._infer_cfg.num_proteins is not None: + csv = csv.sample( + n=self._infer_cfg.num_proteins, + random_state=self._infer_cfg.seed, + ).reset_index(drop=True) + dataset = PDBDatasetBBFlowFromPdb( + csv, + sort=self._infer_cfg.sort, + min_length=0 if self._infer_cfg.min_length is None else self._infer_cfg.min_length, + max_length=np.inf if self._infer_cfg.max_length is None else self._infer_cfg.max_length, + ) + else: + raise ValueError('No csv path provided') + + log.info(f"Sampling {self._infer_cfg.samples.samples_per_protein} conformations per Protein for {len(dataset)} proteins.") + + dataloader = DataLoader( + dataset, + batch_size=1, + shuffle=False, + num_workers=int(getattr(self._infer_cfg, "num_workers", 2)), + prefetch_factor=None if int(getattr(self._infer_cfg, "num_workers", 2)) == 0 else 2, + persistent_workers=int(getattr(self._infer_cfg, "num_workers", 2)) > 0, + ) + + trainer = Trainer( + accelerator="gpu", + strategy="ddp" if requested_devices > 1 else "auto", + devices=devices, + precision=str(getattr( + self._infer_cfg, + "precision", + self._cfg.experiment.trainer.precision, + )), + enable_progress_bar=self._infer_cfg.use_tqdm, + ) + + hashtagline = '#' * 80 + log.info(f'\n\n{hashtagline}\n' + f'Starting inference run: {self._infer_cfg.name}\nSaving results to {self._output_dir}\n{hashtagline}\n') + + trainer.predict(self._flow_module, dataloaders=dataloader) + + +@hydra.main(version_base=None, config_path="../configs", config_name="inference") +def run(cfg: DictConfig) -> None: + + # Read model checkpoint. + log.info(f'Starting inference with {cfg.inference.num_gpus} GPUs') + start_time = time.time() + sampler = Sampler(cfg) + sampler.run_sampling() + elapsed_time = time.time() - start_time + log.info(f'Finished in {elapsed_time:.2f}s') + +if __name__ == '__main__': + run() diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/experiments/train.py b/bbflow_base/code_exports/a30_redesign_source_20260719/experiments/train.py new file mode 100644 index 0000000000000000000000000000000000000000..d3bbf3022989492c14a41a6314a1d4115a679f96 --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/experiments/train.py @@ -0,0 +1,180 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import os +import torch + +# import torch.multiprocessing as mp +# mp.set_start_method('spawn', force=True) + +import hydra +from omegaconf import DictConfig, OmegaConf + +# Pytorch lightning imports +import pytorch_lightning as pl +from pytorch_lightning import LightningDataModule, LightningModule, Trainer +from pytorch_lightning.loggers.wandb import WandbLogger +from pytorch_lightning.trainer import Trainer +from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor +import wandb +import logging + +from gafl import experiment_utils as eu + +from bbflow.models.bbflow_module import BBFlowModule +from bbflow.data.pdb_dataloader_bbflow import PdbDataModuleBBFlow + +from packaging import version + + +log = eu.get_pylogger(__name__) +torch.set_float32_matmul_precision('high') + + +class Experiment: + + def __init__(self, *, cfg: DictConfig): + os.makedirs(cfg.experiment.checkpointer.dirpath, exist_ok=True) + self._cfg = cfg + self._data_cfg = cfg.data + self._exp_cfg = cfg.experiment + + self.create_data_module() + self.create_module() + + def create_module(self): + self._model: LightningModule = BBFlowModule(self._cfg) + + def create_data_module(self): + latent_cfg = self._cfg.latent if hasattr(self._cfg, "latent") else None + self._datamodule: LightningDataModule = PdbDataModuleBBFlow( + self._data_cfg, + training_cfg=self._exp_cfg.training, + latent_cfg=latent_cfg, + ) + + def train(self): + callbacks = [] + if self._exp_cfg.debug: + log.info("Debug mode.") + logger = None + self._exp_cfg.num_devices = 1 + self._data_cfg.loader.num_workers = 0 + else: + if self._exp_cfg.use_wandb: + logger = WandbLogger( + **self._exp_cfg.wandb, + ) + else: + logger = False + + # Checkpoint directory. + ckpt_dir = self._exp_cfg.checkpointer.dirpath + os.makedirs(ckpt_dir, exist_ok=True) + log.info(f"Checkpoints saved to {ckpt_dir}") + + # Model checkpoints + callbacks.append(ModelCheckpoint(**self._exp_cfg.checkpointer)) + callbacks.append(eu.ValidationCallback(self._exp_cfg.first_val_epoch)) + + scheduler_cfg = self._exp_cfg.get("scheduler") + if scheduler_cfg is not None and scheduler_cfg.get("enabled", False) and logger is not None: + lr_monitor = LearningRateMonitor(logging_interval='epoch') + callbacks.append(lr_monitor) + + # Save config + cfg_path = os.path.join(ckpt_dir, 'config.yaml') + with open(cfg_path, 'w') as f: + OmegaConf.save(config=self._cfg, f=f.name) + cfg_dict = OmegaConf.to_container(self._cfg, resolve=True) + flat_cfg = dict(eu.flatten_dict(cfg_dict)) + if self._exp_cfg.use_wandb and isinstance(logger.experiment.config, wandb.sdk.wandb_config.Config): + logger.experiment.config.update(flat_cfg) + + visible_device_count = torch.cuda.device_count() + requested_devices = int(self._exp_cfg.num_devices) + if visible_device_count < requested_devices: + raise RuntimeError( + f"Requested {requested_devices} CUDA device(s), but PyTorch sees " + f"{visible_device_count}. Check CUDA_VISIBLE_DEVICES." + ) + devices = list(range(requested_devices)) + device_names = [torch.cuda.get_device_name(i) for i in devices] + log.info(f"Using devices: {devices} ({device_names})") + + trainer_kwargs = dict( + **self._exp_cfg.trainer, + callbacks=callbacks, + logger=logger, + enable_progress_bar=self._exp_cfg.use_tqdm, + enable_model_summary=True, + devices=devices, + ) + + # the `replace_sampler_ddp` flag is deprecated in newer versions of PL + PL_VERSION = version.parse(pl.__version__) + if PL_VERSION >= version.parse("2.3.0"): + trainer_kwargs["use_distributed_sampler"] = False + else: + trainer_kwargs["replace_sampler_ddp"] = False + + trainer = Trainer( + **trainer_kwargs + ) + + fit_ckpt_path = self._exp_cfg.warm_start + if fit_ckpt_path is not None: + ckpt = torch.load(fit_ckpt_path, map_location="cpu", weights_only=True) + if "pytorch-lightning_version" not in ckpt: + model_ckpt = ckpt["state_dict"] + model_ckpt = {k.replace("model.", ""): v for k, v in model_ckpt.items()} + current_state = self._model.model.state_dict() + compatible_state = { + k: v for k, v in model_ckpt.items() + if k in current_state and current_state[k].shape == v.shape + } + missing, unexpected = self._model.model.load_state_dict(compatible_state, strict=False) + log.info( + "Loaded non-Lightning warm start into model only: " + f"{len(compatible_state)} tensors, missing={len(missing)}, unexpected={len(unexpected)}" + ) + fit_ckpt_path = None + + trainer.fit( + model=self._model, + datamodule=self._datamodule, + ckpt_path=fit_ckpt_path + ) + +@hydra.main(version_base=None, config_path="../configs", config_name="train.yaml") +def main(cfg: DictConfig): + + if cfg.experiment.warm_start is not None and cfg.experiment.warm_start_cfg_override: + # Loads warm start config. + warm_start_cfg_path = os.path.join( + os.path.dirname(cfg.experiment.warm_start), 'config.yaml') + warm_start_cfg = OmegaConf.load(warm_start_cfg_path) + + # Warm start config may not have latest fields in the base config. + # Add these fields to the warm start config. + OmegaConf.set_struct(cfg.model, False) + OmegaConf.set_struct(warm_start_cfg.model, False) + cfg.model = OmegaConf.merge(cfg.model, warm_start_cfg.model) + OmegaConf.set_struct(cfg.model, True) + log.info(f'Loaded warm start config from {warm_start_cfg_path}') + + # Ensure that all processes write to the same output directory. + if int(os.environ.get("LOCAL_RANK", 0)) == 0: + base_output_dir = cfg.experiment.checkpointer.dirpath + else: + base_output_dir = os.environ.get("HYDRA_OUTPUT_DIR", cfg.experiment.checkpointer.dirpath) + os.environ['HYDRA_OUTPUT_DIR'] = base_output_dir + cfg.experiment.checkpointer.dirpath = base_output_dir + + exp = Experiment(cfg=cfg) + exp.train() + +if __name__ == "__main__": + main() diff --git a/bbflow_base/reproduction/00_prepare_data.sh b/bbflow_base/reproduction/00_prepare_data.sh new file mode 100644 index 0000000000000000000000000000000000000000..26e0a3c2a29c44df995687e06d67c58a079aafa9 --- /dev/null +++ b/bbflow_base/reproduction/00_prepare_data.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +set -euo pipefail + +BBFLOW_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cd "${BBFLOW_ROOT}" + +ATLAS_RAW_ROOT="${ATLAS_RAW_ROOT:-/data/shared/wangyusong/atals}" +REPRO_ROOT="${REPRO_ROOT:-${BBFLOW_ROOT}/reproduction/outputs}" +ATLAS_VIEW_ROOT="${ATLAS_VIEW_ROOT:-${REPRO_ROOT}/data/ATLAS}" +METADATA_ROOT="${METADATA_ROOT:-${REPRO_ROOT}/metadata}" + +python reproduction/prepare_atlas_view.py \ + --raw-root "${ATLAS_RAW_ROOT}" \ + --split-root "${BBFLOW_ROOT}/dataset_csv/ATLAS_split" \ + --view-root "${ATLAS_VIEW_ROOT}" \ + --metadata-root "${METADATA_ROOT}" + +python - </dev/null 2>&1; then + echo "[official:data] Existing official dataset is complete; skipping download" + else + python scripts/download_atlas.py \ + --out_folder "${DATA_ROOT}" \ + --train_csv "${BBFLOW_ROOT}/dataset_csv/ATLAS_split/ATLAS_train.csv" \ + --validation_csv "${BBFLOW_ROOT}/dataset_csv/ATLAS_split/ATLAS_validation.csv" \ + --test_csv "${BBFLOW_ROOT}/dataset_csv/ATLAS_split/ATLAS_test.csv" \ + --out_csv_folder "${CSV_ROOT}" \ + --max_retries "${DOWNLOAD_MAX_RETRIES}" \ + --retry_delay "${DOWNLOAD_RETRY_DELAY}" + fi + check_official_data +fi + +if run_stage model; then + echo "============================================================" + echo "[official:model] Downloading/checking upstream bbflow-0.1" + python - <<'PY' +from bbflow.deployment.utils import ckpt_path_from_tag + +path = ckpt_path_from_tag("bbflow-0.1") +print(f"[official:model] checkpoint={path}") +print(f"[official:model] config={path.parent / 'config.yaml'}") +PY + [[ -f "${CKPT_PATH}" ]] || { + echo "[official:model] Missing checkpoint after download: ${CKPT_PATH}" + exit 1 + } + [[ -f "${BBFLOW_ROOT}/models/bbflow-0.1/config.yaml" ]] || { + echo "[official:model] Missing official model config" + exit 1 + } +fi + +if run_stage sample; then + echo "============================================================" + echo "[official:sample] Generating ${SAMPLES_PER_PROTEIN} samples for 82 proteins" + echo " GPU_IDS=${GPU_IDS}" + echo " NUM_GPUS=${NUM_GPUS}" + check_official_data + [[ -f "${CKPT_PATH}" ]] || { + echo "[official:sample] Missing ${CKPT_PATH}; run STAGE=model first" + exit 1 + } + echo "[official:sample] Removing previous inference output: ${INFERENCE_DIR}" + rm -rf -- "${INFERENCE_DIR}" + echo "[official:sample] Removing previous evaluation output: ${METRICS_ROOT}" + rm -rf -- "${METRICS_ROOT}" + env -u NVIDIA_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES="${GPU_IDS}" \ + python experiments/inference.py \ + "inference.ckpt_path=${CKPT_PATH}" \ + "inference.csv_path=${TEST_CSV}" \ + "inference.output_dir=${INFERENCE_ROOT}" \ + "inference.name=${INFERENCE_NAME}" \ + "inference.num_gpus=${NUM_GPUS}" \ + "inference.samples.samples_per_protein=${SAMPLES_PER_PROTEIN}" \ + "inference.samples.batch_size=${SAMPLE_BATCH_SIZE}" \ + "inference.log_times=true" + check_official_samples +fi + +if run_stage eval; then + echo "============================================================" + echo "[official:eval] Running unmodified BBFlow analysis" + check_official_data + check_official_samples + if [[ -f "${SUMMARY_PATH}" ]]; then + echo "[official:eval] Existing summary found; skipping evaluation" + else + ENSEMBLE_DIR="${INFERENCE_DIR}" \ + ATLAS_VIEW_ROOT="${DATA_ROOT}" \ + TEST_CSV="${TEST_CSV}" \ + NUM_WORKERS="${NUM_WORKERS}" \ + METRICS_DIR="${METRICS_ROOT}" \ + bash reproduction/03_evaluate.sh + fi + [[ -f "${SUMMARY_PATH}" ]] || { + echo "[official:eval] Missing summary after evaluation: ${SUMMARY_PATH}" + exit 1 + } + echo + echo "[official:eval] Final BBFlow metrics" + cat "${SUMMARY_PATH}" +fi + +if [[ "${STAGE}" == "all" ]]; then + echo + echo "[official] Reproduction complete" + echo " checkpoint=${CKPT_PATH}" + echo " ensembles=${INFERENCE_DIR}" + echo " metrics=${SUMMARY_PATH}" +fi diff --git a/bbflow_base/reproduction/01_download_official.sh b/bbflow_base/reproduction/01_download_official.sh new file mode 100644 index 0000000000000000000000000000000000000000..b67c5d14092780b9eafa690f47c257d9632752db --- /dev/null +++ b/bbflow_base/reproduction/01_download_official.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail + +BBFLOW_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cd "${BBFLOW_ROOT}" +export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}" + +python - <<'PY' +from bbflow.deployment.utils import ckpt_path_from_tag + +path = ckpt_path_from_tag("bbflow-0.1") +print(f"[bbflow:official] checkpoint={path}") +print(f"[bbflow:official] config={path.parent / 'config.yaml'}") +PY diff --git a/bbflow_base/reproduction/01_train.sh b/bbflow_base/reproduction/01_train.sh new file mode 100644 index 0000000000000000000000000000000000000000..db3910c7ef8f7e8f7a767d54bca0f62f755ca602 --- /dev/null +++ b/bbflow_base/reproduction/01_train.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +set -euo pipefail + +BBFLOW_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cd "${BBFLOW_ROOT}" +export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}" + +REPRO_ROOT="${REPRO_ROOT:-${BBFLOW_ROOT}/reproduction/outputs}" +RUN_NAME="${RUN_NAME:-bbflow_official_atlas_2gpu}" +GPU_IDS="${GPU_IDS:-0,1}" +NUM_DEVICES="${NUM_DEVICES:-2}" +NUM_WORKERS="${NUM_WORKERS:-8}" +MAX_EPOCHS="${MAX_EPOCHS:-250}" +CHECKPOINT_EVERY_N_EPOCHS="${CHECKPOINT_EVERY_N_EPOCHS:-1}" +RESUME_CKPT="${RESUME_CKPT:-}" + +TRAIN_CSV="${REPRO_ROOT}/metadata/train/ATLAS_train.csv" +VALID_CSV="${REPRO_ROOT}/metadata/validation/ATLAS_validation.csv" +TEST_CSV="${REPRO_ROOT}/metadata/test/ATLAS_test.csv" +ATLAS_VIEW_ROOT="${REPRO_ROOT}/data/ATLAS" +CHECKPOINT_DIR="${REPRO_ROOT}/checkpoints/${RUN_NAME}" + +for path in "${TRAIN_CSV}" "${VALID_CSV}" "${TEST_CSV}"; do + [[ -f "${path}" ]] || { + echo "[bbflow:train] Missing prepared metadata: ${path}" + echo "Run reproduction/00_prepare_data.sh first." + exit 1 + } +done + +[[ -d "${ATLAS_VIEW_ROOT}" ]] || { + echo "[bbflow:train] Missing prepared ATLAS view: ${ATLAS_VIEW_ROOT}" + exit 1 +} + +mkdir -p "${CHECKPOINT_DIR}" + +WARM_START_ARGS=() +if [[ -n "${RESUME_CKPT}" ]]; then + [[ -f "${RESUME_CKPT}" ]] || { + echo "[bbflow:train] Missing resume checkpoint: ${RESUME_CKPT}" + exit 1 + } + WARM_START_ARGS=( + "experiment.warm_start=${RESUME_CKPT}" + "experiment.warm_start_cfg_override=false" + ) +fi + +echo "[bbflow:train] Upstream BBFlow ATLAS training" +echo " GPU_IDS=${GPU_IDS}" +echo " NUM_DEVICES=${NUM_DEVICES}" +echo " NUM_WORKERS=${NUM_WORKERS} per rank" +echo " MAX_EPOCHS=${MAX_EPOCHS}" +echo " sampler.max_num_res_squared=200000 (upstream default)" +echo " sampler.max_conformations=20 (upstream default)" +echo " validation=every epoch (upstream default)" +echo " checkpoints=${CHECKPOINT_DIR}" + +env -u NVIDIA_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES="${GPU_IDS}" \ +python experiments/train.py \ + "data.dataset.train_csv_path=${TRAIN_CSV}" \ + "data.dataset.valid_csv_paths=[${VALID_CSV}]" \ + "data.dataset.valid_dataset_names=[ATLAS_validation]" \ + "data.dataset.test_csv_path=${TEST_CSV}" \ + "data.dataset.split_path=${CHECKPOINT_DIR}" \ + "data.validation.valid_xtc_paths=[${ATLAS_VIEW_ROOT}]" \ + "data.loader.num_workers=${NUM_WORKERS}" \ + "experiment.wandb.name=${RUN_NAME}" \ + "experiment.use_wandb=false" \ + "experiment.num_devices=${NUM_DEVICES}" \ + "experiment.first_val_epoch=0" \ + "experiment.trainer.max_epochs=${MAX_EPOCHS}" \ + "experiment.checkpointer.every_n_epochs=${CHECKPOINT_EVERY_N_EPOCHS}" \ + "experiment.checkpointer.dirpath=${CHECKPOINT_DIR}" \ + "${WARM_START_ARGS[@]}" diff --git a/bbflow_base/reproduction/02_sample_test.sh b/bbflow_base/reproduction/02_sample_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b58ba3f5ec6d4e5148bd745c8dfc9cdc658b68a --- /dev/null +++ b/bbflow_base/reproduction/02_sample_test.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +set -euo pipefail + +BBFLOW_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cd "${BBFLOW_ROOT}" +export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}" + +GPU_ID="${GPU_ID:-0}" +GPU_IDS="${GPU_IDS:-${GPU_ID}}" +NUM_GPUS="${NUM_GPUS:-1}" +REPRO_ROOT="${REPRO_ROOT:-${BBFLOW_ROOT}/reproduction/outputs}" +METADATA_ROOT="${METADATA_ROOT:-${REPRO_ROOT}/metadata}" +CKPT_PATH="${CKPT_PATH:-${REPRO_ROOT}/checkpoints/bbflow_official_atlas/last.ckpt}" +SAMPLES_PER_PROTEIN="${SAMPLES_PER_PROTEIN:-250}" +SAMPLE_BATCH_SIZE="${SAMPLE_BATCH_SIZE:-20}" +MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-2900000}" +INFERENCE_NAME="${INFERENCE_NAME:-atlas_test_250}" +CONDITION_MODE="${CONDITION_MODE:-real}" +CONDITION_SCALE="${CONDITION_SCALE:-1.0}" +POSTPROCESS_BFACTORS="${POSTPROCESS_BFACTORS:-true}" +INFERENCE_NUM_WORKERS="${INFERENCE_NUM_WORKERS:-2}" +INFERENCE_PRECISION="${INFERENCE_PRECISION:-32-true}" +INFERENCE_FINAL_ONLY="${INFERENCE_FINAL_ONLY:-true}" +INFERENCE_CACHE_STATIC="${INFERENCE_CACHE_STATIC:-true}" +INFERENCE_NUM_TIMESTEPS="${INFERENCE_NUM_TIMESTEPS:-20}" + +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-1}" +export MKL_NUM_THREADS="${MKL_NUM_THREADS:-1}" +export OPENBLAS_NUM_THREADS="${OPENBLAS_NUM_THREADS:-1}" +export NUMEXPR_NUM_THREADS="${NUMEXPR_NUM_THREADS:-1}" + +[[ -f "${CKPT_PATH}" ]] || { + echo "[bbflow:sample] Checkpoint does not exist: ${CKPT_PATH}" + exit 1 +} + +env -u NVIDIA_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES="${GPU_IDS}" \ +python experiments/inference.py \ + "inference.ckpt_path=${CKPT_PATH}" \ + "inference.csv_path=${METADATA_ROOT}/test/ATLAS_test.csv" \ + "inference.output_dir=${REPRO_ROOT}/inference" \ + "inference.name=${INFERENCE_NAME}" \ + "inference.num_gpus=${NUM_GPUS}" \ + "inference.samples.samples_per_protein=${SAMPLES_PER_PROTEIN}" \ + "inference.samples.batch_size=${SAMPLE_BATCH_SIZE}" \ + "inference.samples.num_res_squared=${MAX_NUM_RES_SQUARED}" \ + "inference.condition_mode=${CONDITION_MODE}" \ + "inference.condition_scale=${CONDITION_SCALE}" \ + "inference.postprocess_bfactors=${POSTPROCESS_BFACTORS}" \ + "inference.num_workers=${INFERENCE_NUM_WORKERS}" \ + "inference.precision=${INFERENCE_PRECISION}" \ + "inference.final_only=${INFERENCE_FINAL_ONLY}" \ + "inference.cache_static_features=${INFERENCE_CACHE_STATIC}" \ + "inference.interpolant.sampling.num_timesteps=${INFERENCE_NUM_TIMESTEPS}" \ + "inference.log_times=true" diff --git a/bbflow_base/reproduction/03_evaluate.sh b/bbflow_base/reproduction/03_evaluate.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed647c503726e90d93246af5989d8089841626f1 --- /dev/null +++ b/bbflow_base/reproduction/03_evaluate.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail + +BBFLOW_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cd "${BBFLOW_ROOT}" +export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}" + +REPRO_ROOT="${REPRO_ROOT:-${BBFLOW_ROOT}/reproduction/outputs}" +ATLAS_VIEW_ROOT="${ATLAS_VIEW_ROOT:-${REPRO_ROOT}/data/ATLAS}" +ENSEMBLE_DIR="${ENSEMBLE_DIR:-}" +NUM_WORKERS="${NUM_WORKERS:-8}" +METRICS_DIR="${METRICS_DIR:-${REPRO_ROOT}/metrics}" +TEST_CSV="${TEST_CSV:-${REPRO_ROOT}/metadata/test/ATLAS_test.csv}" +METHOD_NAME="${METHOD_NAME:-BBFlow-base-prior-z}" +METHOD_TIME_SECONDS="${METHOD_TIME_SECONDS:-}" + +[[ -n "${ENSEMBLE_DIR}" ]] || { + echo "[bbflow:eval] Set ENSEMBLE_DIR to the inference run containing protein folders." + exit 1 +} +[[ -d "${ENSEMBLE_DIR}" ]] || { + echo "[bbflow:eval] Ensemble directory does not exist: ${ENSEMBLE_DIR}" + exit 1 +} +[[ -f "${TEST_CSV}" ]] || { + echo "[bbflow:eval] Test metadata does not exist: ${TEST_CSV}" + exit 1 +} +mkdir -p "${METRICS_DIR}" + +mapfile -t TEST_NAMES < <(tail -n +2 "${TEST_CSV}" | cut -d, -f1 | tr -d '\r') +[[ "${#TEST_NAMES[@]}" -eq 82 ]] || { + echo "[bbflow:eval] Expected 82 test proteins, found ${#TEST_NAMES[@]} in ${TEST_CSV}" + exit 1 +} + +ANALYSIS_ARGS=( + scripts/analysis_script.py + --md_dirs "${ATLAS_VIEW_ROOT}" + --ensemble_dirs "${ENSEMBLE_DIR}" + --names "${TEST_NAMES[@]}" + --num_workers "${NUM_WORKERS}" + --metrics RMSD RMSF PCA-W2 + --analysis_data_path "${METRICS_DIR}/analysis_data.pkl" + --analysis_metrics_path "${METRICS_DIR}/summary_metrics.csv" + --compact_metrics_path "${METRICS_DIR}/compact_metrics.csv" + --compact_method_name "${METHOD_NAME}" + --print_metrics +) + +if [[ -n "${METHOD_TIME_SECONDS}" ]]; then + ANALYSIS_ARGS+=(--compact_time_seconds "${METHOD_TIME_SECONDS}") +fi + +python "${ANALYSIS_ARGS[@]}" + +echo "[bbflow:eval] Metrics: ${METRICS_DIR}/summary_metrics.csv" +echo "[bbflow:eval] Compact metrics: ${METRICS_DIR}/compact_metrics.csv" diff --git a/bbflow_base/reproduction/10h_sweep_then_resume.sh b/bbflow_base/reproduction/10h_sweep_then_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..275e42273547efbdd2214916938902ed10874909 --- /dev/null +++ b/bbflow_base/reproduction/10h_sweep_then_resume.sh @@ -0,0 +1,133 @@ +#!/usr/bin/env bash +# ============================================================================== +# 10h window plan: +# PHASE 1 (mandatory, high value): downstream sweep over epoch 0/2/4 of the +# crashed cross run. This is the FIRST real downstream read on the +# entire generator-response line. Runs on CURRENT code -- inference +# samples from q (sample_coefficients_from_q) and never touches the +# singular lstsq path, so no code change is needed for the sweep. +# PHASE 2 (optional, default OFF): resume-with-ridge-fix toward epoch 9 to +# produce a fully-trained, evaluable checkpoint for the NEXT window. +# Resume is a documented landmine in this repo -- do not run it +# unattended without reading the verification note at the bottom. +# +# Fresh restart is deliberately NOT offered: in 10h it only reaches ~epoch 5 +# (where it crashed) = zero new information, and discards 4 trained epochs. +# ============================================================================== +set -euo pipefail + +# ------------------------------------------------------------------ CONFIRM ME +# The 4 paths below are the only things that can silently break this run. +BBFLOW_ROOT="${BBFLOW_ROOT:-$HOME/LD-FPG-main/bbflow_base}" +REPRO_ROOT="${REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +CRASHED_RUN="${CRASHED_RUN:-${REPRO_ROOT}/outputs/checkpoints/bbflow_base_gen_cov_v2_mdtrace_cross_k8_10ep_3gpu_120k_bs10_20260717_125700}" +# ATLAS real trajectories for eval. Handoff section 2 warns /home vs ${REPRO} +# may differ -- verify this is the SAME data the official baseline was scored on. +ATLAS_VIEW_ROOT="${ATLAS_VIEW_ROOT:-${REPRO_ROOT}/datasets/ATLAS}" +TEST_CSV="${TEST_CSV:-${REPRO_ROOT}/metadata/test/ATLAS_test.csv}" +METADATA_ROOT="${METADATA_ROOT:-${REPRO_ROOT}/metadata}" +# ----------------------------------------------------------------------------- + +# ---- sweep knobs ---- +SWEEP_EPOCHS=(4 0 2) # endpoints first, middle last (survives a timeout) +SWEEP_SAMPLES="${SWEEP_SAMPLES:-100}" # same across all 3; 250 is the official full count +SAMPLE_BATCH_SIZE="${SAMPLE_BATCH_SIZE:-20}" +GPU_IDS="${GPU_IDS:-0,1,2}" +NUM_GPUS="${NUM_GPUS:-3}" + +# ---- phase 2 (resume) toggle ---- +RUN_RESUME="${RUN_RESUME:-false}" # set true ONLY after reading the note below +RESUME_FROM_EPOCH="${RESUME_FROM_EPOCH:-004}" + +cd "${BBFLOW_ROOT}" +export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}" + +die() { echo "[10h] FATAL: $*" >&2; exit 1; } + +# ---- preflight: every checkpoint the sweep needs must exist ---- +for e in "${SWEEP_EPOCHS[@]}"; do + ep=$(printf "%03d" "$e") + [[ -f "${CRASHED_RUN}/epoch:${ep}.ckpt" ]] || die "missing ${CRASHED_RUN}/epoch:${ep}.ckpt" +done +[[ -f "${TEST_CSV}" ]] || die "TEST_CSV not found: ${TEST_CSV}" +[[ -d "${ATLAS_VIEW_ROOT}" ]] || die "ATLAS_VIEW_ROOT not found: ${ATLAS_VIEW_ROOT}" +echo "[10h] preflight OK. sweep epochs=${SWEEP_EPOCHS[*]} samples=${SWEEP_SAMPLES}" + +# =============================== PHASE 1: SWEEP =============================== +for e in "${SWEEP_EPOCHS[@]}"; do + ep=$(printf "%03d" "$e") + name="sweep_ep${ep}" + echo "======================================================================" + echo "[10h] PHASE1 epoch ${ep}: sampling ${SWEEP_SAMPLES}/protein" + t0=$(date +%s) + + CKPT_PATH="${CRASHED_RUN}/epoch:${ep}.ckpt" \ + INFERENCE_NAME="${name}" \ + SAMPLES_PER_PROTEIN="${SWEEP_SAMPLES}" \ + SAMPLE_BATCH_SIZE="${SAMPLE_BATCH_SIZE}" \ + GPU_IDS="${GPU_IDS}" NUM_GPUS="${NUM_GPUS}" \ + REPRO_ROOT="${REPRO_ROOT}" METADATA_ROOT="${METADATA_ROOT}" \ + bash reproduction/02_sample_test.sh + + # auto-detect the ensemble dir 02 wrote (the folder holding the 82 proteins) + ENSEMBLE_DIR=$(find "${REPRO_ROOT}/inference" -type d -path "*${name}*" 2>/dev/null \ + | while read -r d; do + n=$(find "$d" -maxdepth 1 -mindepth 1 -type d | wc -l) + [[ "$n" -ge 82 ]] && echo "$d" + done | head -1) + [[ -n "${ENSEMBLE_DIR}" ]] || die "could not locate ensemble dir for ${name} under ${REPRO_ROOT}/inference (ls it and set ENSEMBLE_DIR by hand)" + echo "[10h] ensemble: ${ENSEMBLE_DIR}" + + ENSEMBLE_DIR="${ENSEMBLE_DIR}" \ + METRICS_DIR="${REPRO_ROOT}/metrics/${name}" \ + METHOD_NAME="gen_cov_cross_ep${ep}" \ + ATLAS_VIEW_ROOT="${ATLAS_VIEW_ROOT}" TEST_CSV="${TEST_CSV}" \ + REPRO_ROOT="${REPRO_ROOT}" \ + bash reproduction/03_evaluate.sh + + echo "[10h] PHASE1 epoch ${ep} DONE in $(( $(date +%s) - t0 ))s" + echo "[10h] metrics -> ${REPRO_ROOT}/metrics/${name}/compact_metrics.csv" +done + +echo "======================================================================" +echo "[10h] SWEEP COMPLETE. Compare across epochs (PCA-W2 lower=better, RMSF, Pairwise):" +for e in "${SWEEP_EPOCHS[@]}"; do + ep=$(printf "%03d" "$e") + echo " --- ep${ep} ---" + cat "${REPRO_ROOT}/metrics/sweep_ep${ep}/compact_metrics.csv" 2>/dev/null || echo " (missing)" +done + +# ============================= PHASE 2: RESUME =============================== +# Default OFF. Only produces value if you have read the verification note. +if [[ "${RUN_RESUME}" != "true" ]]; then + echo "[10h] PHASE2 skipped (RUN_RESUME=false). Sweep-only, as planned." + exit 0 +fi + +echo "[10h] PHASE2: resume from epoch:${RESUME_FROM_EPOCH} with relative-ridge fix" +pkill -u "$USER" -9 -f experiments/train.py; sleep 3 +export ATLAS_REPRO_ROOT="${REPRO_ROOT}" + +# Resume works by pointing warm_start (BASE_CKPT) at the Lightning ckpt of the +# crashed run: train.py:130 sees the pytorch-lightning_version key and hands it +# to trainer.fit(ckpt_path=...) = full resume with optimizer + epoch state. +BASE_CKPT="${CRASHED_RUN}/epoch:${RESUME_FROM_EPOCH}.ckpt" \ +RUN_DIR="${CRASHED_RUN}_resume_$(date +%Y%m%d_%H%M%S)" \ +FINGERPRINT_CACHE=/home/wangyusong/LD-FPG-main/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt \ +GPU_IDS=0,1,2 NUM_DEVICES=3 MAX_EPOCHS=10 \ +CHECKPOINT_EVERY_N_EPOCHS=1 CHECKPOINT_SAVE_LAST=true CHECKPOINT_SAVE_TOP_K=-1 \ +PRECISION=bf16-mixed MAX_NUM_RES_SQUARED=120000 MAX_BATCH_SIZE=10 \ +ENERGY_FROM_Q=true ENERGY_FROM_Q_FULL_COV=false Q_DETACH_SHARED_ENCODER=false \ +LAMBDA_MOTION=1.0 LAMBDA_Q=1.0 LAMBDA_MODE_ORTH=1.0 LAMBDA_MODE_RECON=0.0 LAMBDA_PCA_ALIGN=0.0 \ +LAMBDA_CONDITION_CYCLE=0.0 \ +LAMBDA_GENERATOR_COV=1.0 GENERATOR_COV_USE_CROSS=true \ +GENERATOR_COV_T_MIN=0.1 GENERATOR_COV_T_MAX=0.6 GENERATOR_COV_DELTA_SCALE=1.0 \ +GENERATOR_COV_NUM_DELTAS=2 GENERATOR_COV_STUDENT_CHUNK_DELTAS=1 \ +GENERATOR_COV_CHECKPOINT=true GENERATOR_COV_INITIAL_TRACE_ANCHOR=true \ +LAMBDA_GEN_LOCAL_SHAPE=1.0 LAMBDA_GEN_CROSS_SHAPE=1.0 LAMBDA_GEN_TRACE_ANCHOR=0.3 \ +bash base_stages/00_train_final_mog_ddp.sh + +# VERIFY RESUME TOOK EFFECT (see note): the first progress line MUST read +# "Epoch 5/9", NOT "Epoch 0/9", and the warm-start log MUST NOT say +# "Loaded non-Lightning warm start into model only". If it starts at Epoch 0, +# resume silently failed -- kill it, do not waste the window. diff --git a/bbflow_base/reproduction/README.md b/bbflow_base/reproduction/README.md new file mode 100644 index 0000000000000000000000000000000000000000..76fa33b14efdcbb34833e87754e23154f8ee2897 --- /dev/null +++ b/bbflow_base/reproduction/README.md @@ -0,0 +1,25 @@ +# BBFlow ATLAS reproduction + +This directory runs the upstream BBFlow implementation without changing its +model or loss. It creates a lightweight symlink view of an existing raw ATLAS +download, trains on the official 1269/39/82 split, samples 250 conformations +for each test protein, and evaluates with BBFlow's own analysis code. + +```bash +cd bbflow +bash reproduction/00_prepare_data.sh +bash reproduction/01_download_official.sh +CKPT_PATH="$PWD/models/bbflow-0.1/bbflow-0.1.ckpt" \ + GPU_ID=0 bash reproduction/02_sample_test.sh +ENSEMBLE_DIR=/absolute/path/to/inference/run \ + bash reproduction/03_evaluate.sh +``` + +The commands above reproduce the published model first. To reproduce training +from scratch, run `GPU_ID=0 bash reproduction/01_train.sh`, then pass the +resulting `last.ckpt` to `02_sample_test.sh`. + +Training defaults match the upstream configuration: 250 epochs, conditional +prior, intra-protein batch OT, and at most 20 conformations per protein per +epoch. Checkpoints are saved every 5 epochs by default, with `last.ckpt` +retained. Set `RESUME_CKPT=/path/to/last.ckpt` to resume training. diff --git a/bbflow_base/reproduction/__pycache__/prepare_atlas_view.cpython-39.pyc b/bbflow_base/reproduction/__pycache__/prepare_atlas_view.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83aced217ebbfb17c8342645431f701e605a3705 Binary files /dev/null and b/bbflow_base/reproduction/__pycache__/prepare_atlas_view.cpython-39.pyc differ diff --git a/bbflow_base/reproduction/outputs/metrics/compact_metrics.csv b/bbflow_base/reproduction/outputs/metrics/compact_metrics.csv new file mode 100644 index 0000000000000000000000000000000000000000..cf166ee71ce3ef0a2df715262bd3eccd871efdc2 --- /dev/null +++ b/bbflow_base/reproduction/outputs/metrics/compact_metrics.csv @@ -0,0 +1,9 @@ +Method,RMSF r (↑),RMSF MAE (↓),RMSF Median (1.48),Pairwise RMSD MAE (↓),Pairwise RMSD Median (2.90),PCA W2 (↓),Time [s] +AlphaFlow,0.86,0.59 (0.01),1.51,1.34 (0.01),2.89,1.47 (0.03),32.0 +ConfDiff,0.88,0.62 (0.01),2.00,1.45 (0.01),3.43,1.41 (0.03),20.2 +AlphaFlow-T,0.92,0.41 (0.01),1.17,0.91 (0.01),2.18,1.28 (0.03),32.6 +ESMFlow-T,0.92,0.52 (0.01),0.94,1.22 (0.01),2.00,1.48 (0.03),11.2 +AlphaFlow-T dist,0.92,0.68 (0.01),0.90,1.41 (0.01),1.73,1.44 (0.03),3.3 +"AlphaFlow-T 12L,dist",0.90,0.85 (0.01),0.68,1.80 (0.01),1.40,1.60 (0.03),1.2 +BBFlow (Ours),0.89,0.47 (0.01),1.48,0.78 (0.01),2.76,1.34 (0.03),0.9 +BBFlow-genresp-v1-epoch004-5ep-250,0.90,0.53,1.79,0.83,3.39,1.29,- diff --git a/bbflow_base/reproduction/outputs/metrics/summary_metrics.csv b/bbflow_base/reproduction/outputs/metrics/summary_metrics.csv new file mode 100644 index 0000000000000000000000000000000000000000..b5e00bb71d16901f948feb7b1202a5af4ac9e809 --- /dev/null +++ b/bbflow_base/reproduction/outputs/metrics/summary_metrics.csv @@ -0,0 +1,28 @@ +, +MD pairwise RMSD,2.8955 +Pairwise RMSD,3.3919 +MD pairwise RMSD mean,3.5538 +Pairwise RMSD mean,3.8871 +Pairwise RMSD r,0.8386 +Pairwise RMSD MAE,0.8274 +Pairwise RMSD RMSE,1.1859 +Pairwise RMSD MAE max,4.8212 +Pairwise RMSD RMSE max,4.8212 +MD RMSF,1.4819 +RMSF,1.7858 +MD RMSF mean,2.1219 +RMSF mean,2.3659 +Global RMSF r,0.8307 +Global RMSF MAE,0.7416 +Global RMSF RMSE,1.2232 +Per target RMSF r,0.8961 +Per target RMSF r mean,0.8727 +Per target RMSF r min,0.475 +Per target RMSF MAE,0.5291 +Per target RMSF MAE mean,0.7324 +Per target RMSF MAE max,2.5885 +Per target RMSF RMSE,0.7741 +Per target RMSF RMSE mean,0.9988 +Per target RMSF RMSE max,4.1436 +MD PCA W2,1.2921 +Joint PCA W2,1.9396 diff --git a/bbflow_base/reproduction/prepare_atlas_view.py b/bbflow_base/reproduction/prepare_atlas_view.py new file mode 100644 index 0000000000000000000000000000000000000000..d727cc9c3e33556ddd9ec3a4c93a26c8faf644bf --- /dev/null +++ b/bbflow_base/reproduction/prepare_atlas_view.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +import argparse +import os +import re +from pathlib import Path + +import pandas as pd + + +SPLITS = { + "train": "ATLAS_train.csv", + "validation": "ATLAS_validation.csv", + "test": "ATLAS_test.csv", +} + + +def normalized(value): + return re.sub(r"[^a-z0-9]", "", str(value).lower()) + + +def canonical_name(value): + value = str(value).strip() + if "_" in value: + pdb_id, chain = value.split("_", 1) + return f"{pdb_id[:4].lower()}{chain[:1].upper()}" + return f"{value[:4].lower()}{value[4:5].upper()}" + + +def build_file_index(raw_root, excluded_root): + index = {} + excluded_root = excluded_root.resolve() + for root, dirs, files in os.walk(raw_root): + root_path = Path(root).resolve() + dirs[:] = [ + dirname + for dirname in dirs + if not (root_path / dirname).resolve().is_relative_to(excluded_root) + ] + for filename in files: + path = root_path / filename + suffix = path.suffix.lower() + if suffix not in {".pdb", ".xtc"}: + continue + index.setdefault((normalized(path.stem), suffix), []).append(path) + return index + + +def choose(index, keys, suffix, entry): + matches = [] + for key in keys: + matches.extend(index.get((normalized(key), suffix), [])) + matches = sorted(set(matches), key=lambda path: (len(str(path)), str(path))) + if not matches: + raise FileNotFoundError( + f"Missing {suffix} for {entry}; searched stems={keys}" + ) + if len(matches) > 1: + print(f"[prepare] {entry}: using {matches[0]} among {len(matches)} matches") + return matches[0] + + +def link_file(source, destination): + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.is_symlink() or destination.exists(): + if destination.resolve() == source.resolve(): + return + destination.unlink() + destination.symlink_to(source.resolve()) + + +def prepare_split(split, source_csv, index, view_root, metadata_root): + source = pd.read_csv(source_csv) + rows = [] + for _, row in source.iterrows(): + name = canonical_name(row["name"]) + target_dir = (view_root / name).resolve() + original = str(row["name"]).strip() + pdb = choose( + index, + [name, original, f"{name[:4]}_{name[4]}", f"{original}_analysis"], + ".pdb", + name, + ) + trajectories = [ + choose( + index, + [ + f"{name}_R{replicate}", + f"{name[:4]}_{name[4]}_R{replicate}", + f"{original}_R{replicate}", + ], + ".xtc", + name, + ) + for replicate in range(1, 4) + ] + + link_file(pdb, target_dir / f"{name}.pdb") + for replicate, trajectory in enumerate(trajectories, start=1): + link_file(trajectory, target_dir / f"{name}_R{replicate}.xtc") + + output = { + "name": name, + "pdb_path": str(target_dir / f"{name}.pdb"), + } + if split == "train": + output.update( + modeled_seq_len=int(row["modeled_seq_len"]), + folder=str(target_dir), + num_conformations=int(row["num_conformations"]), + ) + rows.append(output) + + output_dir = metadata_root / split + output_dir.mkdir(parents=True, exist_ok=True) + output_path = output_dir / f"ATLAS_{split}.csv" + frame = pd.DataFrame(rows) + if split == "train": + frame = frame.sort_values("modeled_seq_len").reset_index(drop=True) + frame.to_csv(output_path, index=False) + print(f"[prepare] {split}: {len(frame)} entries -> {output_path}") + return len(frame) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--raw-root", required=True, type=Path) + parser.add_argument("--split-root", required=True, type=Path) + parser.add_argument("--view-root", required=True, type=Path) + parser.add_argument("--metadata-root", required=True, type=Path) + args = parser.parse_args() + + raw_root = args.raw_root.resolve() + split_root = args.split_root.resolve() + view_root = args.view_root.resolve() + metadata_root = args.metadata_root.resolve() + if not raw_root.is_dir(): + raise NotADirectoryError(f"ATLAS raw root does not exist: {raw_root}") + + view_root.mkdir(parents=True, exist_ok=True) + metadata_root.mkdir(parents=True, exist_ok=True) + print(f"[prepare] indexing PDB/XTC files under {raw_root}") + index = build_file_index(raw_root, view_root) + print(f"[prepare] indexed {sum(len(paths) for paths in index.values())} files") + + counts = {} + for split, filename in SPLITS.items(): + source_csv = split_root / filename + if not source_csv.is_file(): + raise FileNotFoundError(f"Missing official split CSV: {source_csv}") + counts[split] = prepare_split( + split, source_csv, index, view_root, metadata_root + ) + + expected = {"train": 1269, "validation": 39, "test": 82} + if counts != expected: + raise RuntimeError(f"Unexpected split counts: {counts}; expected {expected}") + print("[prepare] BBFlow ATLAS view is complete: train=1269 validation=39 test=82") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/reproduction/watch_train_then_infer.sh b/bbflow_base/reproduction/watch_train_then_infer.sh new file mode 100644 index 0000000000000000000000000000000000000000..bf96d5975190e00b90572a1c2822786da20f99ca --- /dev/null +++ b/bbflow_base/reproduction/watch_train_then_infer.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Watch the frozen training run; when it EXITS (completes or is killed), auto-run +# downstream inference on the latest checkpoint: quick 5znjA read, then full 82. +# Launch in background: nohup bash reproduction/watch_train_then_infer.sh > ~/watch_frozen.log 2>&1 & +set -uo pipefail + +REPRO_ROOT=/data/shared/wangyusong/atals/bbflow_official_reproduction +BBFLOW="$HOME/LD-FPG-main/bbflow_base" +# latest frozen run dir (auto-detect; override by exporting RUN_DIR before launch) +RUN_DIR="${RUN_DIR:-$(ls -dt ${REPRO_ROOT}/outputs/checkpoints/bbflow_base_frozen_shape_notrace_* | head -1)}" + +# latent config that MUST match the frozen checkpoint (else q-head loads random -> garbage) +LATENT_ARGS="latent.enable=true \ ++latent.mixture_components=2 \ ++latent.energy_from_q=true +latent.energy_from_q_full_cov=false +latent.sample_coefficients=true \ ++latent.q_detach_projection=true +latent.q_detach_shared_encoder=false \ ++latent.q_lstsq_ridge=1e-4 +latent.q_cholesky_jitter=1e-4" + +TEST_CSV=${REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv +ATLAS_VIEW_ROOT=${REPRO_ROOT}/datasets/ATLAS + +cd "$BBFLOW"; export PYTHONPATH="$PWD:${PYTHONPATH:-}" +echo "[watch] RUN_DIR=$RUN_DIR" + +rmsf_check () { # $1 = inference name, $2 = protein + python - "$1" "$2" <<'EOF' +import numpy as np, glob, sys +name, prot = sys.argv[1], sys.argv[2] +REPRO="/data/shared/wangyusong/atals/bbflow_official_reproduction" +fs=sorted(glob.glob(f"{REPRO}/inference/**/{name}/**/{prot}/sampled_conformations.pdb", recursive=True)) +if not fs: print(f"[watch] no output for {name}/{prot}"); sys.exit(0) +M=[];c=[] +for ln in open(fs[0]): + if ln.startswith("MODEL"): c=[] + elif ln.startswith("ENDMDL"): + if c: M.append(c) + elif ln.startswith(("ATOM","HETATM")) and ln[12:16].strip()=="CA": + c.append([float(ln[30:38]),float(ln[38:46]),float(ln[46:54])]) +X=np.array(M); r=X.std(0).mean(-1) +print(f"[watch] {name}/{prot} RMSF mean/median: {r.mean():.2f}/{np.median(r):.2f} | <1.5 frac: {(r<1.5).mean():.3f}") +EOF +} + +# 1) wait for training to exit, then let GPUs settle +echo "[watch] waiting for training to finish... ($(date))" +while pgrep -u "$USER" -f experiments/train.py >/dev/null; do sleep 120; done +echo "[watch] training gone at $(date). waiting 60s for GPU release."; sleep 60 + +# 2) latest checkpoint +CKPT=$(ls -t "$RUN_DIR"/epoch:*.ckpt 2>/dev/null | head -1); [[ -z "$CKPT" ]] && CKPT="$RUN_DIR/last.ckpt" +[[ -f "$CKPT" ]] || { echo "[watch] no checkpoint in $RUN_DIR"; exit 1; } +echo "[watch] evaluating $CKPT" + +# 3) QUICK: single protein for an immediate base-preserved read +head -1 "$TEST_CSV" > /tmp/one_5znjA.csv; grep -E "^5znjA," "$TEST_CSV" >> /tmp/one_5znjA.csv +env -u NVIDIA_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES=0 \ +python experiments/inference.py $LATENT_ARGS \ + inference.ckpt_path="$CKPT" inference.csv_path=/tmp/one_5znjA.csv \ + inference.output_dir="$REPRO_ROOT/inference" inference.name=frozen_quick_5znjA \ + inference.num_gpus=1 inference.samples.samples_per_protein=100 inference.samples.batch_size=20 \ + inference.samples.num_res_squared=2900000 inference.precision=32-true \ + inference.final_only=true inference.interpolant.sampling.num_timesteps=20 +rmsf_check frozen_quick_5znjA 5znjA + +# 4) FULL: 82 proteins on 3 GPUs, then 03 eval (PCA W2 vs BBFlow) +env -u NVIDIA_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES=0,1,2 \ +python experiments/inference.py $LATENT_ARGS \ + inference.ckpt_path="$CKPT" inference.csv_path="$TEST_CSV" \ + inference.output_dir="$REPRO_ROOT/inference" inference.name=frozen_full \ + inference.num_gpus=3 inference.samples.samples_per_protein=100 inference.samples.batch_size=20 \ + inference.samples.num_res_squared=2900000 inference.precision=32-true \ + inference.final_only=true inference.interpolant.sampling.num_timesteps=20 + +ENSEMBLE_DIR=$(find "$REPRO_ROOT/inference" -type d -path "*frozen_full*" \ + | while read -r d; do [[ $(find "$d" -maxdepth 1 -mindepth 1 -type d|wc -l) -ge 82 ]] && echo "$d"; done | head -1) +if [[ -n "$ENSEMBLE_DIR" ]]; then + ENSEMBLE_DIR="$ENSEMBLE_DIR" METRICS_DIR="$REPRO_ROOT/metrics/frozen_full" METHOD_NAME=frozen_shape \ + ATLAS_VIEW_ROOT="$ATLAS_VIEW_ROOT" TEST_CSV="$TEST_CSV" REPRO_ROOT="$REPRO_ROOT" NUM_WORKERS=8 \ + bash reproduction/03_evaluate.sh + echo "[watch] DONE. metrics -> $REPRO_ROOT/metrics/frozen_full/compact_metrics.csv" + cat "$REPRO_ROOT/metrics/frozen_full/compact_metrics.csv" +else + echo "[watch] full ensemble dir not found; check $REPRO_ROOT/inference for frozen_full" +fi diff --git a/bbflow_base/scripts/__init__.py b/bbflow_base/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5472ab88c0c38d7b7139ef81e355c5af557775b8 --- /dev/null +++ b/bbflow_base/scripts/__init__.py @@ -0,0 +1 @@ +"""Executable diagnostics and experiment utilities.""" diff --git a/bbflow_base/scripts/__pycache__/__init__.cpython-310.pyc b/bbflow_base/scripts/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a97107121d5de352d7a0c3a26d299f9ba451f2c Binary files /dev/null and b/bbflow_base/scripts/__pycache__/__init__.cpython-310.pyc differ diff --git a/bbflow_base/scripts/__pycache__/check_directional_condition_equivariance.cpython-39.pyc b/bbflow_base/scripts/__pycache__/check_directional_condition_equivariance.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47fb97b9fb799baaeec759855b35ca3021584c01 Binary files /dev/null and b/bbflow_base/scripts/__pycache__/check_directional_condition_equivariance.cpython-39.pyc differ diff --git a/bbflow_base/scripts/__pycache__/diagnose_film.cpython-39.pyc b/bbflow_base/scripts/__pycache__/diagnose_film.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4964b8337cdc1cac83a670f2cb986fca032afd69 Binary files /dev/null and b/bbflow_base/scripts/__pycache__/diagnose_film.cpython-39.pyc differ diff --git a/bbflow_base/scripts/__pycache__/diagnose_pca_projection_ceiling.cpython-39.pyc b/bbflow_base/scripts/__pycache__/diagnose_pca_projection_ceiling.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..955aa2b0d800269f0114e05ae3fcb6a29432d49d Binary files /dev/null and b/bbflow_base/scripts/__pycache__/diagnose_pca_projection_ceiling.cpython-39.pyc differ diff --git a/bbflow_base/scripts/__pycache__/diagnose_z.cpython-311.pyc b/bbflow_base/scripts/__pycache__/diagnose_z.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a949e6788d896de786282e4a85f045f67598c1f7 Binary files /dev/null and b/bbflow_base/scripts/__pycache__/diagnose_z.cpython-311.pyc differ diff --git a/bbflow_base/scripts/__pycache__/fit_motion_template_upper_bound.cpython-311.pyc b/bbflow_base/scripts/__pycache__/fit_motion_template_upper_bound.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a63a93c503c64032d4faf3890f179c4eb6aecdc8 Binary files /dev/null and b/bbflow_base/scripts/__pycache__/fit_motion_template_upper_bound.cpython-311.pyc differ diff --git a/bbflow_base/scripts/__pycache__/fit_motion_template_upper_bound.cpython-39.pyc b/bbflow_base/scripts/__pycache__/fit_motion_template_upper_bound.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c3acb212e62dd75d4f39f0e42e8c5b798968618 Binary files /dev/null and b/bbflow_base/scripts/__pycache__/fit_motion_template_upper_bound.cpython-39.pyc differ diff --git a/bbflow_base/scripts/__pycache__/probe_condition_ensemble_cov.cpython-39.pyc b/bbflow_base/scripts/__pycache__/probe_condition_ensemble_cov.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d74113bd559b17e62bcf573efa7c345a509beec Binary files /dev/null and b/bbflow_base/scripts/__pycache__/probe_condition_ensemble_cov.cpython-39.pyc differ diff --git a/bbflow_base/scripts/__pycache__/probe_sample_condition.cpython-39.pyc b/bbflow_base/scripts/__pycache__/probe_sample_condition.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2752031d375852452c9d087a99cd99796dc0c35a Binary files /dev/null and b/bbflow_base/scripts/__pycache__/probe_sample_condition.cpython-39.pyc differ diff --git a/bbflow_base/scripts/__pycache__/rescore_pca_w2.cpython-311.pyc b/bbflow_base/scripts/__pycache__/rescore_pca_w2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b718477a587cc1a2d3abd611db0bfb9e7ec4c90f Binary files /dev/null and b/bbflow_base/scripts/__pycache__/rescore_pca_w2.cpython-311.pyc differ diff --git a/bbflow_base/scripts/__pycache__/spectral_calibration.cpython-310.pyc b/bbflow_base/scripts/__pycache__/spectral_calibration.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41921fe3e264de00685056d616f46dfa77b956b7 Binary files /dev/null and b/bbflow_base/scripts/__pycache__/spectral_calibration.cpython-310.pyc differ diff --git a/bbflow_base/scripts/analysis_script.py b/bbflow_base/scripts/analysis_script.py new file mode 100644 index 0000000000000000000000000000000000000000..c129122e239beb88b888c0b0e6930f1396534387 --- /dev/null +++ b/bbflow_base/scripts/analysis_script.py @@ -0,0 +1,327 @@ +import argparse +import os +import pickle +import pandas as pd +import numpy as np +import functools +from multiprocessing import Pool +from tqdm import tqdm +from scipy.stats import bootstrap +from typing import List, Tuple, Dict, Union, Optional + +from bbflow.analysis.analyse_bbflow import ( + _load_ref_traj_full, + _load_ref_traj_subset, + _load_model_traj, + _calc_metrics_bootstrap, + _analyze_data, +) + +default_metrics = [ + "RMSD", + "RMSF", + "DCCM", + "RMWD", + "PCA-W2", + "Cosine Sim", + "Weak Transient Contacts", +] + +COMPACT_BASELINE_ROWS = [ + ("AlphaFlow", "0.86", "0.59 (0.01)", "1.51", "1.34 (0.01)", "2.89", "1.47 (0.03)", "32.0"), + ("ConfDiff", "0.88", "0.62 (0.01)", "2.00", "1.45 (0.01)", "3.43", "1.41 (0.03)", "20.2"), + ("AlphaFlow-T", "0.92", "0.41 (0.01)", "1.17", "0.91 (0.01)", "2.18", "1.28 (0.03)", "32.6"), + ("ESMFlow-T", "0.92", "0.52 (0.01)", "0.94", "1.22 (0.01)", "2.00", "1.48 (0.03)", "11.2"), + ("AlphaFlow-T dist", "0.92", "0.68 (0.01)", "0.90", "1.41 (0.01)", "1.73", "1.44 (0.03)", "3.3"), + ("AlphaFlow-T 12L,dist", "0.90", "0.85 (0.01)", "0.68", "1.80 (0.01)", "1.40", "1.60 (0.03)", "1.2"), + ("BBFlow (Ours)", "0.89", "0.47 (0.01)", "1.48", "0.78 (0.01)", "2.76", "1.34 (0.03)", "0.9"), +] + + +def _fmt_metric(metrics_dict, key, digits=2): + value = metrics_dict.get(key) + if value is None or pd.isna(value): + return "-" + return f"{float(value):.{digits}f}" + + +def _compact_metrics_df(metrics_dict, method_name, time_seconds=None): + md_rmsf = _fmt_metric(metrics_dict, "MD RMSF", digits=2) + md_pairwise = _fmt_metric(metrics_dict, "MD pairwise RMSD", digits=2) + time_value = "-" if time_seconds is None else f"{time_seconds:.1f}" + columns = [ + "Method", + "RMSF r (↑)", + "RMSF MAE (↓)", + f"RMSF Median ({md_rmsf})", + "Pairwise RMSD MAE (↓)", + f"Pairwise RMSD Median ({md_pairwise})", + "PCA W2 (↓)", + "Time [s]", + ] + rows = [dict(zip(columns, row)) for row in COMPACT_BASELINE_ROWS] + rows.append({ + "Method": method_name, + "RMSF r (↑)": _fmt_metric(metrics_dict, "Per target RMSF r", digits=2), + "RMSF MAE (↓)": _fmt_metric(metrics_dict, "Per target RMSF MAE", digits=2), + f"RMSF Median ({md_rmsf})": _fmt_metric(metrics_dict, "RMSF", digits=2), + "Pairwise RMSD MAE (↓)": _fmt_metric(metrics_dict, "Pairwise RMSD MAE", digits=2), + f"Pairwise RMSD Median ({md_pairwise})": _fmt_metric(metrics_dict, "Pairwise RMSD", digits=2), + "PCA W2 (↓)": _fmt_metric(metrics_dict, "MD PCA W2", digits=2), + "Time [s]": time_value, + }) + return pd.DataFrame(rows, columns=columns) + + +def calc_metrics( + names: Union[List[str]]=None, + md_dirs: Optional[List[str]]=None, + ensemble_dirs: Optional[List[str]]=None, + paths: Optional[List[Tuple]]=None, + num_workers: int=8, + metrics_subset: Optional[List[str]]=None, + use_tqdm: bool=True, + analysis_data_path: str="", + analysis_metrics_path: str="", + compact_metrics_path: str="", + compact_method_name: str="BBFlow-base-prior-z", + compact_time_seconds: Optional[float]=None, + print_metrics: bool=True, +): + """ + Calculate metrics for protein ensembles against reference MD trajectories. + + Either provide: + 1. names, md_dirs and ensemble_dirs + or + 2. paths: list of tuples, each containing + (model_ensemble_pdb, reference_pdb, reference_traj1, ..., reference_trajN) + + Args: + names: + List of names of the ensembles to analyze. For each name, there must + be a corresponding pdb file or directory in each of the ensemble_dirs, + i.e. `ensemble_dirs[i]/name.pdb` or `ensemble_dirs[i]/name/sampled_conformations.pdb`, + as well as a corresponding reference pdb and trajs in each of the md_dirs, + i.e. `md_dirs[i]/name.pdb` and `md_dirs[i]/name/name_traj_R{j}.xtc` for j=1,2,3. + md_dirs: + List of directories containing reference MD data. Each directory must contain + reference pdbs and 3 trajectories. + ensemble_dirs: + List of directories containing model ensembles. Each directory must contain + pdb files or directories for each ensemble. + paths: + List of tuples, each containing + (model_ensemble.pdb, reference.pdb, reference_traj1.xtc, ..., reference_trajN.xtc) + num_workers: + Number of parallel workers to use. + metrics_subset: + Subset of metrics to calculate. If None, all metrics are calculated. + use_tqdm: + Whether to use tqdm progress bar. + analysis_data_path: + Path to save raw analysis data (pickle file). If empty, no file is saved. + analysis_metrics_path: + Path to save metrics summary (CSV file). If empty, no file is saved. + print_metrics: + Whether to print metrics to console. + """ + if paths is not None: + if names is not None or md_dirs is not None or ensemble_dirs is not None: + raise ValueError("Either provide paths OR names, md_dirs and ensemble_dirs.") + names = paths + + if metrics_subset is None: + metrics_subset = default_metrics + + if num_workers > 1: + p = Pool(num_workers) + p.__enter__() + __map__ = p.imap + else: + __map__ = map + + _calc_metrics_partial = functools.partial( + _calc_metrics_bootstrap, + reference_dirs=md_dirs, + pdbdirs=ensemble_dirs, + metrics_subset=metrics_subset + ) + if use_tqdm: + out = dict(tqdm(__map__(_calc_metrics_partial, names), total=len(names), leave=False)) + else: + out = dict(__map__(_calc_metrics_partial, names)) + if num_workers > 1: + p.__exit__(None, None, None) + + out = {k: v for k, v in out.items() if v is not None} + if len(out) == 0: + raise ValueError("No valid trajectories were loaded.") + + metrics_dict = _analyze_data(out, metrics_subset) + + if analysis_data_path != "": + if paths is not None: + # replace keys with range(len(paths)), otherwise keys are unreadable tuples + out = {f"path_{i}": out[k] for i, k in enumerate(out.keys())} + with open(analysis_data_path, 'wb') as f: + pickle.dump(out, f) + + if analysis_metrics_path != "": + df = pd.DataFrame({"": metrics_dict}).round(4) + df = df.reindex([k for k in metrics_dict.keys()]) + df.to_csv(analysis_metrics_path) + + compact_df = _compact_metrics_df( + metrics_dict, + method_name=compact_method_name, + time_seconds=compact_time_seconds, + ) + if compact_metrics_path != "": + compact_df.to_csv(compact_metrics_path, index=False) + + if print_metrics: + print(compact_df.to_string(index=False)) + + +def main(): + """ + Command line interface for calculating metrics. + + Usage: + 1. Provide md_dirs, ensemble_dirs and names: + + ` + python analysis_script.py --md_dirs md_dir1 md_dir2 ... \ + --ensemble_dirs ensemble_dir1 ensemble_dir2 ... \ + --names name1 name2 ... + ` + + 2. Provide md_dirs, ensemble_dirs and auto-detect names from ensemble_dirs: + + ` + python analysis_script.py --md_dirs md_dir1 md_dir2 ... \ + --ensemble_dirs ensemble_dir1 ensemble_dir2 ... + ` + + 3. Provide paths directly of the form: + + ` + python analysis_script.py --paths \ + model1.pdb ref1.pdb ref_traj1.xtc ... ref_trajN1.xtc \ + model2.pdb ref2.pdb ref_traj1.xtc ... ref_trajN2.xtc ... + ` + + + Additional arguments: + + ``` + --num_workers N : Number of parallel workers (default: 8) + --metrics metric1 metric2 ... : Subset of metrics to calculate (default: all) + --use_tqdm : Show progress bar + --analysis_data_path path : Path to save raw analysis data (pickle file) + --analysis_metrics_path path : Path to save metrics summary (CSV file) + --print_metrics : Print metrics to console + ``` + + """ + parser = argparse.ArgumentParser() + parser.add_argument('--md_dirs', nargs='*', default=[]) + parser.add_argument('--ensemble_dirs', nargs='*', default=[]) + parser.add_argument('--names', nargs='*', default=[]) + parser.add_argument('--paths', nargs='*', default=[]) + parser.add_argument('--num_workers', type=int, default=1) + parser.add_argument('--metrics', nargs='*', default=default_metrics) + parser.add_argument('--no_tqdm', action='store_true') + parser.add_argument('--analysis_data_path', type=str, default='') + parser.add_argument('--analysis_metrics_path', type=str, default='') + parser.add_argument('--compact_metrics_path', type=str, default='') + parser.add_argument('--compact_method_name', type=str, default='BBFlow-base-prior-z') + parser.add_argument('--compact_time_seconds', type=float, default=None) + parser.add_argument('--print_metrics', action='store_true') + args = parser.parse_args() + + # Either provide md_dirs, ensemble_dirs and names, + # or provide paths where each path contains both md and ensemble pdbs. + if len(args.paths) > 0: + if len(args.md_dirs) > 0 or len(args.ensemble_dirs) > 0 or len(args.names) > 0: + raise ValueError("Either provide --paths OR --md_dirs, --ensemble_dirs and --names.") + args.md_dirs = None + args.ensemble_dirs = None + args.names = None + paths = [] + # args.paths must be in the format: + # model1.pdb, ref1.pdb, ref_traj1.xtc, ..., ref_trajN1.xtc, + # model2.pdb, ref2.pdb, ref_traj1.xtc, ..., ref_trajN2.xtc, + # ... + paths.append([]) + for p in args.paths: + if p.endswith('.pdb') and len(paths[-1]) < 2: + # model ensemble pdb or reference pdb + paths[-1].append(p) + elif p.endswith('.pdb') and len(paths[-1]) >= 3: + # start a new entry + paths.append([p]) + elif p.endswith('.xtc'): + # reference traj + if len(paths[-1]) < 2: + raise ValueError("Reference traj provided before model ensemble pdb or reference pdb.") + paths[-1].append(p) + elif p.endswith('.pdb') and len(paths[-1]) == 2: + raise ValueError("More than two pdbs provided before reference trajs.") + + if len(paths[-1]) == 0: + paths = paths[:-1] + + if len(paths) == 0: + raise ValueError("No valid paths provided.") + + if not paths[-1][-1].endswith('.xtc'): + raise ValueError("Last entry in paths missing reference trajs.") + + for i in range(len(paths)): + paths[i] = tuple(paths[i]) + + names = None + + else: + paths = None + if len(args.names) == 0: + # auto-detect names from ensemble_dirs. + # Include all pdbs and dirs in ensemble_dirs + names = [] + for ensemble_dir in args.ensemble_dirs: + names_ = [ + f for f in os.listdir(ensemble_dir) + if f.endswith('.pdb') or os.path.isdir(os.path.join(ensemble_dir, f)) + ] + names.extend(names_) + names = list(set(names)) + print(f"Found {len(names)} generated ensembles to analyze:") + print(names) + else: + names = args.names + + assert len(names) > 0, "No names provided for analysis." + + + calc_metrics( + names=names, + md_dirs=args.md_dirs, + ensemble_dirs=args.ensemble_dirs, + paths=paths, + num_workers=args.num_workers, + metrics_subset=args.metrics, + use_tqdm=not args.no_tqdm, + analysis_data_path=args.analysis_data_path, + analysis_metrics_path=args.analysis_metrics_path, + compact_metrics_path=args.compact_metrics_path, + compact_method_name=args.compact_method_name, + compact_time_seconds=args.compact_time_seconds, + print_metrics=args.print_metrics, + ) + + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/analyze_fullcov_pca_contraction.py b/bbflow_base/scripts/analyze_fullcov_pca_contraction.py new file mode 100644 index 0000000000000000000000000000000000000000..c3f3118341ba245ed968f1be44b4b2b3746d6fb2 --- /dev/null +++ b/bbflow_base/scripts/analyze_fullcov_pca_contraction.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python +import argparse +import pickle +from pathlib import Path + +import numpy as np +import pandas as pd + + +def load_analysis(path: Path, tag: str) -> pd.DataFrame: + with path.open("rb") as handle: + payload = pickle.load(handle) + + rows = [] + for name, values in payload.items(): + model_rmsf = np.asarray(values["model_rmsf"], dtype=float) + ref_rmsf = np.asarray(values["ref_rmsf"], dtype=float) + rows.append( + { + "pdb_name": name, + f"{tag}_pca_w2": float(values["md_pca_w2"]), + f"{tag}_joint_pca_w2": float(values["joint_pca_w2"]), + f"{tag}_model_pairwise": float(values["model_mean_pairwise_rmsd"]), + f"{tag}_ref_pairwise": float(values["ref_mean_pairwise_rmsd"]), + f"{tag}_pairwise_abs_error": abs( + float(values["model_mean_pairwise_rmsd"]) + - float(values["ref_mean_pairwise_rmsd"]) + ), + f"{tag}_model_rmsf_mean": float(np.mean(model_rmsf)), + f"{tag}_rmsf_mae": float(np.mean(np.abs(model_rmsf - ref_rmsf))), + } + ) + return pd.DataFrame(rows) + + +def regression_summary(frame: pd.DataFrame, start: str, end: str) -> dict: + delta_pca = frame[f"{end}_pca_w2"] - frame[f"{start}_pca_w2"] + delta_pairwise = ( + frame[f"{end}_model_pairwise"] - frame[f"{start}_model_pairwise"] + ) + delta_rmsf = ( + frame[f"{end}_model_rmsf_mean"] - frame[f"{start}_model_rmsf_mean"] + ) + + x = np.column_stack( + [np.ones(len(frame)), delta_pairwise.to_numpy(), delta_rmsf.to_numpy()] + ) + y = delta_pca.to_numpy() + coef, *_ = np.linalg.lstsq(x, y, rcond=None) + prediction = x @ coef + ss_total = np.sum((y - y.mean()) ** 2) + r2 = 1.0 - np.sum((y - prediction) ** 2) / ss_total if ss_total > 0 else np.nan + + amplitude_change = np.sqrt( + delta_pairwise.to_numpy() ** 2 + delta_rmsf.to_numpy() ** 2 + ) + stable_cutoff = float(np.quantile(amplitude_change, 0.25)) + stable = amplitude_change <= stable_cutoff + + return { + "comparison": f"{start}_to_{end}", + "n": len(frame), + "median_delta_pca_w2": float(delta_pca.median()), + "pca_improved_fraction": float((delta_pca < 0).mean()), + "median_delta_model_pairwise": float(delta_pairwise.median()), + "pearson_delta_pca_vs_pairwise": float( + delta_pca.corr(delta_pairwise, method="pearson") + ), + "spearman_delta_pca_vs_pairwise": float( + delta_pca.corr(delta_pairwise, method="spearman") + ), + "amplitude_regression_r2": float(r2), + "coef_delta_pairwise": float(coef[1]), + "coef_delta_rmsf": float(coef[2]), + "stable_amplitude_cutoff": stable_cutoff, + "stable_amplitude_n": int(stable.sum()), + "stable_amplitude_median_delta_pca": float(np.median(y[stable])), + "stable_amplitude_pca_improved_fraction": float(np.mean(y[stable] < 0)), + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--epoch10", type=Path, required=True) + parser.add_argument("--epoch30", type=Path, required=True) + parser.add_argument("--epoch40", type=Path, required=True) + parser.add_argument("--output_dir", type=Path, required=True) + args = parser.parse_args() + + frames = [ + load_analysis(args.epoch10, "epoch10"), + load_analysis(args.epoch30, "epoch30"), + load_analysis(args.epoch40, "epoch40"), + ] + merged = frames[0] + for frame in frames[1:]: + merged = merged.merge(frame, on="pdb_name", how="inner", validate="one_to_one") + + for end in ("epoch30", "epoch40"): + merged[f"{end}_minus_epoch10_pca_w2"] = ( + merged[f"{end}_pca_w2"] - merged["epoch10_pca_w2"] + ) + merged[f"{end}_minus_epoch10_model_pairwise"] = ( + merged[f"{end}_model_pairwise"] - merged["epoch10_model_pairwise"] + ) + merged[f"{end}_minus_epoch10_model_rmsf_mean"] = ( + merged[f"{end}_model_rmsf_mean"] - merged["epoch10_model_rmsf_mean"] + ) + + summaries = pd.DataFrame( + [ + regression_summary(merged, "epoch10", "epoch30"), + regression_summary(merged, "epoch10", "epoch40"), + regression_summary(merged, "epoch30", "epoch40"), + ] + ) + + args.output_dir.mkdir(parents=True, exist_ok=True) + merged.to_csv(args.output_dir / "per_protein_pca_contraction.csv", index=False) + summaries.to_csv(args.output_dir / "pca_contraction_summary.csv", index=False) + + delta_pca = merged["epoch40_minus_epoch10_pca_w2"].abs() + delta_amp = merged["epoch40_minus_epoch10_model_pairwise"].abs() + stable = delta_amp <= delta_amp.quantile(0.25) + informative = merged.loc[ + stable & (merged["epoch40_minus_epoch10_pca_w2"] < 0) + ].sort_values("epoch40_minus_epoch10_pca_w2") + informative.to_csv( + args.output_dir / "pca_improved_with_stable_pairwise.csv", index=False + ) + + print(f"proteins: {len(merged)}") + print("\n=== paired change and amplitude-control summary ===") + print(summaries.to_string(index=False, float_format=lambda value: f"{value:.4f}")) + print("\n=== strongest PCA improvements with stable Pairwise amplitude ===") + columns = [ + "pdb_name", + "epoch10_pca_w2", + "epoch40_pca_w2", + "epoch40_minus_epoch10_pca_w2", + "epoch10_model_pairwise", + "epoch40_model_pairwise", + "epoch40_minus_epoch10_model_pairwise", + ] + print(informative[columns].head(15).to_string(index=False)) + print(f"\nSaved to: {args.output_dir}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/audit_condition_branch_weights.py b/bbflow_base/scripts/audit_condition_branch_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..da1ac5ea7001a9b34644e8045941a14e9005e856 --- /dev/null +++ b/bbflow_base/scripts/audit_condition_branch_weights.py @@ -0,0 +1,70 @@ +from pathlib import Path +import argparse +import json +import torch + + +def tensor_norm(x): + x = x.detach().float() + return { + "shape": list(x.shape), + "l2": float(x.norm().cpu()), + "mean_abs": float(x.abs().mean().cpu()), + "max_abs": float(x.abs().max().cpu()), + } + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt", required=True) + ap.add_argument("--out", required=True) + args = ap.parse_args() + + ckpt = torch.load(args.ckpt, map_location="cpu", weights_only=False) + sd = ckpt.get("state_dict", ckpt) + + groups = { + "unsigned_node_z_node_adapter": ["z_node_adapter"], + "signed_node_disp_node_adapter": ["disp_node_adapter"], + "unsigned_edge_z_edge_adapter": ["z_edge_adapter"], + "signed_edge_disp_edge_adapter": ["disp_edge_adapter"], + "unsigned_film_mlp": ["film_mlp"], + } + + report = {} + for group, tokens in groups.items(): + items = {} + for k, v in sd.items(): + if not torch.is_tensor(v): + continue + if all(t in k for t in tokens): + items[k] = tensor_norm(v) + report[group] = items + + summary = {} + for group, items in report.items(): + total_l2_sq = 0.0 + last_layer_l2_sq = 0.0 + n = 0 + for k, stats in items.items(): + total_l2_sq += stats["l2"] ** 2 + n += 1 + if any(s in k for s in ["2.weight", "2.bias", "film_mlp.2.weight", "film_mlp.2.bias"]): + last_layer_l2_sq += stats["l2"] ** 2 + summary[group] = { + "num_tensors": n, + "total_l2": total_l2_sq ** 0.5, + "last_layer_l2": last_layer_l2_sq ** 0.5, + } + + out = Path(args.out) + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps({"summary": summary, "details": report}, indent=2), encoding="utf-8") + + print("===== condition branch weight summary =====") + print(json.dumps(summary, indent=2)) + print("\nSaved:", out) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/audit_condition_forward_paths.py b/bbflow_base/scripts/audit_condition_forward_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..36d53b266edcb96e829f811b8a084ab59dfca670 --- /dev/null +++ b/bbflow_base/scripts/audit_condition_forward_paths.py @@ -0,0 +1,427 @@ +#!/usr/bin/env python +"""Forward audit for signed vs unsigned latent-condition paths. + +Diagnostic only: no training, no source mutation, no checkpoint mutation. + +This script uses matched frame pairs and measures, on the same forward batch: + * unsigned adapter outputs vs signed adapter outputs; + * cosine between unsigned and signed adapter outputs after projection; + * FiLM gamma/beta amplitudes, separated; + * c -> -c effects versus c_a -> c_b effects at final update and pred_trans. +""" +import argparse +import copy +import json +from pathlib import Path +import sys + +import numpy as np +import pandas as pd +import torch +from omegaconf import OmegaConf + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from bbflow.data.interpolant_bbflow import InterpolantBBFlow +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow +from bbflow.models.bbflow_module import BBFlowModule + +from scripts.diagnose_condition_interface import ( + frame_indices_for_row, + mean_disp_from_frames, + move_item_to_device, + build_cstar_condition, +) + + +def load_module(ckpt_path, device, num_timesteps=None): + ckpt_path = Path(ckpt_path) + cfg_path = ckpt_path.with_name("config.yaml") + if not cfg_path.exists(): + raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}") + + infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(cfg_path) + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.inference.interpolant.use_tqdm = False + cfg.model.embed = ckpt_cfg.model.embed + if num_timesteps is not None: + cfg.inference.interpolant.rots.num_timesteps = int(num_timesteps) + cfg.inference.interpolant.trans.num_timesteps = int(num_timesteps) + + module = BBFlowModule(cfg) + checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False) + current = module.state_dict() + compatible = { + key: value + for key, value in checkpoint["state_dict"].items() + if key in current and current[key].shape == value.shape + } + missing, unexpected = module.load_state_dict(compatible, strict=False) + module.to(device) + module.eval() + interpolant = InterpolantBBFlow(cfg.inference.interpolant) + interpolant.set_device(device) + module.interpolant = interpolant + return module, { + "loaded": len(compatible), + "missing": len(missing), + "unexpected": len(unexpected), + } + + +def normalize_csv(df): + df = df.copy() + if "name" not in df.columns and "pdb_name" in df.columns: + df["name"] = df["pdb_name"] + if "folder" not in df.columns and "pdb_path" in df.columns: + df["folder"] = df["pdb_path"].map(lambda p: str(Path(str(p)).parent)) + return df + + +def clone_condition(condition): + return { + key: value.clone() if torch.is_tensor(value) else copy.deepcopy(value) + for key, value in condition.items() + } + + +def condition_from_coeff(module, prior, coeff, rotmats_eq, res_mask): + extra = { + key: prior[key] + for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"] + if key in prior + } + return module.latent_encoder.condition_from_mode_coefficients( + prior["u_global"], + coeff, + rotmats_eq, + res_mask, + extra=extra, + include_statistics=False, + ) + + +def masked_mean_abs(tensor, mask=None, edge=False): + x = tensor.detach().float().abs() + if mask is None: + return float(x.mean().cpu().item()) + m = mask.float() + if edge: + m = m[:, :, None] * m[:, None, :] + while m.dim() < x.dim(): + m = m[..., None] + else: + while m.dim() < x.dim(): + m = m[..., None] + return float(((x * m).sum() / m.sum().clamp_min(1.0)).cpu().item()) + + +def rms(tensor, mask=None, edge=False): + x = tensor.detach().float().square() + if mask is None: + return float(x.mean().sqrt().cpu().item()) + m = mask.float() + if edge: + m = m[:, :, None] * m[:, None, :] + while m.dim() < x.dim(): + m = m[..., None] + else: + while m.dim() < x.dim(): + m = m[..., None] + return float(((x * m).sum() / m.sum().clamp_min(1.0)).sqrt().cpu().item()) + + +def flat_cosine(a, b, mask=None, edge=False): + aa = a.detach().float() + bb = b.detach().float().to(device=aa.device) + if mask is not None: + m = mask.float() + if edge: + m = m[:, :, None] * m[:, None, :] + while m.dim() < aa.dim(): + m = m[..., None] + else: + while m.dim() < aa.dim(): + m = m[..., None] + aa = aa * m + bb = bb * m + aa = aa.reshape(-1) + bb = bb.reshape(-1) + denom = aa.norm().clamp_min(1e-8) * bb.norm().clamp_min(1e-8) + return float((aa * bb).sum().div(denom).cpu().item()) + + +def rel_delta(reference, changed, mask=None, edge=False): + denom = masked_mean_abs(reference, mask=mask, edge=edge) + delta = masked_mean_abs(changed - reference, mask=mask, edge=edge) + return float(delta / max(denom, 1e-8)) + + +def adapter_outputs(module, condition): + embedder = module.model.embedder + return { + "z_node": embedder.z_node_adapter(condition["node_cond"]), + "disp_node": embedder.disp_node_adapter(condition["disp_node_cond"]), + "z_edge": embedder.z_edge_adapter(condition["edge_cond"]), + "disp_edge": embedder.disp_edge_adapter(condition["disp_edge_cond"]), + } + + +def film_outputs(module, condition): + model = module.model + if not getattr(model, "inject_film", False): + return None + cond = condition["node_cond"] + gamma_beta = model.film_mlp(cond) + gamma, beta = torch.chunk(gamma_beta, 2, dim=-1) + return {"gamma": gamma, "beta": beta} + + +def build_forward_batch(module, item, condition, seed): + device = item["trans_equilibrium"].device + trans_eq = item["trans_equilibrium"] + rotmats_eq = item["rotmats_equilibrium"] + seq = item["seq"] + res_mask = torch.ones_like(trans_eq[..., 0]) + _, num_res = trans_eq.shape[:2] + torch.manual_seed(int(seed)) + np.random.seed(int(seed) % (2**32 - 1)) + trans_t, rotmats_t = module.interpolant.sample_from_prior( + 1, int(num_res), trans_eq, rotmats_eq + ) + return { + "res_mask": res_mask, + "trans_equilibrium": trans_eq, + "rotmats_equilibrium": rotmats_eq, + "seq": seq, + "trans_t": trans_t, + "rotmats_t": rotmats_t, + "t": torch.full( + (1, 1), + module.interpolant._cfg.min_t, + device=device, + dtype=trans_eq.dtype, + ), + "z": condition, + } + + +def run_model_capture(module, base_batch, condition): + captured = {} + model = module.model + last_block = model._gfa_conf.num_blocks - 1 + last_update = model.trunk[f"bb_update_{last_block}"] + + def pre_hook(_mod, args): + captured["final_update_node_embed"] = args[0].detach().clone() + + handle = last_update.register_forward_pre_hook(pre_hook) + batch = dict(base_batch) + batch["z"] = condition + try: + with torch.no_grad(): + out = model(batch) + finally: + handle.remove() + return { + "final_update_node_embed": captured["final_update_node_embed"], + "pred_trans": out["pred_trans"].detach().clone(), + } + + +def summarize_rows(df, value_cols): + out = {} + for col in value_cols: + vals = pd.to_numeric(df[col], errors="coerce").replace([np.inf, -np.inf], np.nan).dropna() + if len(vals) == 0: + continue + out[col] = { + "n": int(len(vals)), + "mean": float(vals.mean()), + "median": float(vals.median()), + "min": float(vals.min()), + "max": float(vals.max()), + } + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt_path", required=True) + ap.add_argument("--csv_path", required=True) + ap.add_argument("--matched_csv", required=True) + ap.add_argument("--out_dir", required=True) + ap.add_argument("--device", default="cuda") + ap.add_argument("--num_frames", type=int, default=6) + ap.add_argument("--seed", type=int, default=20260712) + ap.add_argument("--num_timesteps", type=int, default=20) + args = ap.parse_args() + + device = torch.device(args.device if (args.device == "cpu" or torch.cuda.is_available()) else "cpu") + module, load_info = load_module(args.ckpt_path, device, args.num_timesteps) + + df = normalize_csv(pd.read_csv(args.csv_path)) + matched = pd.read_csv(args.matched_csv) + dataset = PDBDatasetBBFlow(df) + by_name = {str(name): idx for idx, name in enumerate(dataset.pdb_names)} + + rows = [] + for row_idx, matched_row in matched.iterrows(): + name = str(matched_row["pdb_name"]) + if name not in by_name: + raise ValueError(f"pdb_name from matched_csv not found in csv_path: {name}") + protein_idx = by_name[name] + csv_row = dataset.csv.iloc[protein_idx] + frame_ids = frame_indices_for_row(csv_row, args.num_frames) + + a_id = int(matched_row["frame_a"]) + b_id = int(matched_row["frame_b"]) + item_a = move_item_to_device(dataset[(protein_idx, 0, a_id)], device) + item_b = move_item_to_device(dataset[(protein_idx, 0, b_id)], device) + res_mask = torch.ones_like(item_a["trans_equilibrium"][..., 0]) + + with torch.no_grad(): + prior, _ = module.latent_encoder.forward_prior( + item_a["trans_equilibrium"], + item_a["rotmats_equilibrium"], + item_a["seq"], + res_mask, + ) + mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device) + cond_a, coeff_a = build_cstar_condition(module, item_a, prior, mean_disp=mean_disp) + cond_b, coeff_b = build_cstar_condition(module, item_b, prior, mean_disp=mean_disp) + cond_neg_a = condition_from_coeff( + module, + prior, + -coeff_a, + item_a["rotmats_equilibrium"], + res_mask, + ) + + adapters_a = adapter_outputs(module, cond_a) + film_a = film_outputs(module, cond_a) + film_neg_a = film_outputs(module, cond_neg_a) + film_b = film_outputs(module, cond_b) + + base_batch = build_forward_batch(module, item_a, cond_a, args.seed + int(row_idx)) + forward_a = run_model_capture(module, base_batch, cond_a) + forward_neg_a = run_model_capture(module, base_batch, cond_neg_a) + forward_b = run_model_capture(module, base_batch, cond_b) + + record = { + "pdb_name": name, + "frame_a": a_id, + "frame_b": b_id, + "frame_gap": abs(b_id - a_id), + "num_res": int(item_a["trans_equilibrium"].shape[1]), + "coeff_cos_ab": flat_cosine(coeff_a, coeff_b), + "coeff_signflip_frac_ab": float(((coeff_a * coeff_b) < 0).float().mean().detach().cpu().item()), + "node_unsigned_abs": masked_mean_abs(adapters_a["z_node"], res_mask), + "node_signed_abs": masked_mean_abs(adapters_a["disp_node"], res_mask), + "node_signed_over_unsigned": masked_mean_abs(adapters_a["disp_node"], res_mask) / max(masked_mean_abs(adapters_a["z_node"], res_mask), 1e-8), + "node_adapter_cosine": flat_cosine(adapters_a["z_node"], adapters_a["disp_node"], res_mask), + "edge_unsigned_abs": masked_mean_abs(adapters_a["z_edge"], res_mask, edge=True), + "edge_signed_abs": masked_mean_abs(adapters_a["disp_edge"], res_mask, edge=True), + "edge_signed_over_unsigned": masked_mean_abs(adapters_a["disp_edge"], res_mask, edge=True) / max(masked_mean_abs(adapters_a["z_edge"], res_mask, edge=True), 1e-8), + "edge_adapter_cosine": flat_cosine(adapters_a["z_edge"], adapters_a["disp_edge"], res_mask, edge=True), + "final_embed_rel_delta_signflip": rel_delta( + forward_a["final_update_node_embed"], forward_neg_a["final_update_node_embed"], res_mask + ), + "final_embed_rel_delta_ab": rel_delta( + forward_a["final_update_node_embed"], forward_b["final_update_node_embed"], res_mask + ), + "pred_trans_rel_delta_signflip": rel_delta(forward_a["pred_trans"], forward_neg_a["pred_trans"], res_mask), + "pred_trans_rel_delta_ab": rel_delta(forward_a["pred_trans"], forward_b["pred_trans"], res_mask), + "pred_trans_signflip_over_ab": rel_delta(forward_a["pred_trans"], forward_neg_a["pred_trans"], res_mask) / max(rel_delta(forward_a["pred_trans"], forward_b["pred_trans"], res_mask), 1e-8), + "final_embed_signflip_over_ab": rel_delta(forward_a["final_update_node_embed"], forward_neg_a["final_update_node_embed"], res_mask) / max(rel_delta(forward_a["final_update_node_embed"], forward_b["final_update_node_embed"], res_mask), 1e-8), + } + if film_a is not None: + for key in ["gamma", "beta"]: + record[f"film_{key}_abs"] = masked_mean_abs(film_a[key], res_mask) + record[f"film_{key}_rms"] = rms(film_a[key], res_mask) + record[f"film_{key}_rel_delta_signflip"] = rel_delta(film_a[key], film_neg_a[key], res_mask) + record[f"film_{key}_rel_delta_ab"] = rel_delta(film_a[key], film_b[key], res_mask) + rows.append(record) + + result = pd.DataFrame(rows) + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + result.to_csv(out_dir / "condition_forward_audit_rows.csv", index=False) + + value_cols = [ + "node_unsigned_abs", + "node_signed_abs", + "node_signed_over_unsigned", + "node_adapter_cosine", + "edge_unsigned_abs", + "edge_signed_abs", + "edge_signed_over_unsigned", + "edge_adapter_cosine", + "film_gamma_abs", + "film_gamma_rms", + "film_gamma_rel_delta_signflip", + "film_gamma_rel_delta_ab", + "film_beta_abs", + "film_beta_rms", + "film_beta_rel_delta_signflip", + "film_beta_rel_delta_ab", + "final_embed_rel_delta_signflip", + "final_embed_rel_delta_ab", + "final_embed_signflip_over_ab", + "pred_trans_rel_delta_signflip", + "pred_trans_rel_delta_ab", + "pred_trans_signflip_over_ab", + ] + value_cols = [c for c in value_cols if c in result.columns] + summary = { + "load_info": load_info, + "n": int(len(result)), + "ckpt_path": str(args.ckpt_path), + "matched_csv": str(args.matched_csv), + "metrics": summarize_rows(result, value_cols), + } + (out_dir / "condition_forward_audit_summary.json").write_text( + json.dumps(summary, indent=2), + encoding="utf-8", + ) + + compact_cols = [ + "node_signed_over_unsigned", + "node_adapter_cosine", + "edge_signed_over_unsigned", + "edge_adapter_cosine", + "film_gamma_abs", + "film_beta_abs", + "film_gamma_rel_delta_signflip", + "film_gamma_rel_delta_ab", + "film_beta_rel_delta_signflip", + "film_beta_rel_delta_ab", + "final_embed_signflip_over_ab", + "pred_trans_signflip_over_ab", + ] + compact_cols = [c for c in compact_cols if c in result.columns] + compact = result[compact_cols].agg(["mean", "median", "min", "max"]).T + compact.to_csv(out_dir / "condition_forward_audit_compact.csv") + + print("===== forward audit compact =====") + print(compact.to_string()) + print("\n===== key interpretation helpers =====") + print(json.dumps({ + "n": int(len(result)), + "film_unsigned_expected": "film_*_rel_delta_signflip should be 0 or near 0 because FiLM sees node_cond=|c|", + "signflip_vs_ab": "ratios near 1 mean c->-c changes output as much as switching to c_b; ratios far below 1 mean sign direction is weak", + "adapter_cosine": "high positive cosine means signed and unsigned adapter outputs are aligned/redundant after projection", + }, indent=2)) + print("\nSaved:", out_dir) + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/audit_condition_sign_loss.py b/bbflow_base/scripts/audit_condition_sign_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..a715d8aa2789daf0346a994fc7123478745c419c --- /dev/null +++ b/bbflow_base/scripts/audit_condition_sign_loss.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python +import argparse +import json +import math +import sys +from pathlib import Path + +import mdtraj +import numpy as np +import pandas as pd +import torch +from omegaconf import OmegaConf + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow +from bbflow.models.bbflow_module import BBFlowModule + + +def normalize_csv(csv_path): + df = pd.read_csv(csv_path) + if "folder" not in df.columns: + if "pdb_path" not in df.columns: + raise RuntimeError(f"{csv_path} has neither folder nor pdb_path") + df = df.copy() + df["folder"] = df["pdb_path"].map(lambda x: str(Path(str(x)).parent)) + return df + + +def load_module(ckpt_path, device): + ckpt_path = Path(ckpt_path) + cfg_path = ckpt_path.with_name("config.yaml") + if not cfg_path.exists(): + raise FileNotFoundError(f"Missing config next to checkpoint: {cfg_path}") + + infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(cfg_path) + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.inference.interpolant.use_tqdm = False + cfg.model.embed = ckpt_cfg.model.embed + + module = BBFlowModule(cfg) + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + current = module.state_dict() + compatible = { + k: v for k, v in ckpt["state_dict"].items() + if k in current and current[k].shape == v.shape + } + module.load_state_dict(compatible, strict=False) + module.to(device) + module.eval() + return module + + +def infer_num_frames(row): + for key in ["num_conformations", "num_frames", "n_frames", "traj_num_frames"]: + if key in row and pd.notna(row[key]): + return int(row[key]) + name = str(row["name"]) + folder = Path(str(row["folder"])) + xtc = folder / f"{name}_R1.xtc" + if not xtc.exists(): + raise FileNotFoundError(f"Missing trajectory: {xtc}") + with mdtraj.open(str(xtc)) as handle: + return int(handle.n_frames if hasattr(handle, "n_frames") else len(handle)) + + +def move_item(item, device): + out = {} + for k, v in item.items(): + out[k] = v[None].to(device) if torch.is_tensor(v) else v + return out + + +def mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device): + disps = [] + for fid in frame_ids: + item = move_item(dataset[(protein_idx, 0, int(fid))], device) + mask = torch.ones_like(item["trans_equilibrium"][..., 0]) + disp = module.latent_encoder.relative_displacement( + item["trans_1"].float(), + item["trans_equilibrium"].float(), + mask, + ) + disps.append(disp) + return torch.cat(disps, dim=0).mean(dim=0, keepdim=True) + + +def coeff_for_frame(module, dataset, protein_idx, frame_id, prior, mean_disp, device): + item = move_item(dataset[(protein_idx, 0, int(frame_id))], device) + cond, coeff = module.latent_encoder.frame_condition_from_projection( + item["trans_1"], + item["trans_equilibrium"], + item["rotmats_equilibrium"], + torch.ones_like(item["trans_equilibrium"][..., 0]), + prior, + mean_disp=mean_disp, + ) + return cond, coeff.detach().float() + + +def rel_l2(a, b): + a = a.detach().float() + b = b.detach().float().to(a.device) + return float(((a - b).norm() / a.norm().clamp_min(1e-8)).detach().cpu()) + + +def cosine(a, b): + a = a.detach().float().reshape(-1) + b = b.detach().float().reshape(-1).to(a.device) + return float(((a * b).sum() / (a.norm().clamp_min(1e-8) * b.norm().clamp_min(1e-8))).detach().cpu()) + + +def sign_flip_fraction(a, b): + a = a.detach().float().reshape(-1) + b = b.detach().float().reshape(-1).to(a.device) + valid = (a.abs() > 1e-8) & (b.abs() > 1e-8) + if valid.sum() == 0: + return float("nan") + return float(((a[valid] * b[valid]) < 0).float().mean().detach().cpu()) + + +def condition_for_coeff(module, prior, coeff, item): + return module.latent_encoder.condition_from_mode_coefficients( + prior["u_global"], + coeff, + item["rotmats_equilibrium"], + torch.ones_like(item["trans_equilibrium"][..., 0]), + extra={ + key: prior[key] + for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"] + if key in prior + }, + ) + + +def selected_rows_from_matched(matched_csv, dataset): + matched = pd.read_csv(matched_csv) + by_name = {str(name): i for i, name in enumerate(dataset.pdb_names)} + rows = [] + for _, r in matched.iterrows(): + name = str(r["pdb_name"]) + if name not in by_name: + continue + if "frame_a" not in r or "frame_b" not in r: + raise RuntimeError("matched_csv must contain frame_a and frame_b columns") + rows.append((by_name[name], r)) + return rows + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt_path", required=True) + ap.add_argument("--csv_path", required=True) + ap.add_argument("--matched_csv", required=True) + ap.add_argument("--out_dir", required=True) + ap.add_argument("--device", default="cuda") + ap.add_argument("--num_mean_frames", type=int, default=6) + args = ap.parse_args() + + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + device = torch.device(args.device if args.device.startswith("cuda") and torch.cuda.is_available() else "cpu") + module = load_module(args.ckpt_path, device) + + df = normalize_csv(args.csv_path) + dataset = PDBDatasetBBFlow(csv=df) + + matched_rows = selected_rows_from_matched(args.matched_csv, dataset) + print(f"[audit] matched rows loaded: {len(matched_rows)}", flush=True) + + rows = [] + + with torch.no_grad(): + for protein_idx, matched in matched_rows: + meta = dataset.csv.iloc[protein_idx] + name = str(meta["name"]) + total = infer_num_frames(meta) + + # Reconstruct the same mean-disp convention used by earlier diagnostics: + # spread frames across trajectory. This is only for aggregate testing. + frame_grid = sorted(set(np.linspace(0, total - 1, args.num_mean_frames, dtype=int).tolist())) + frame_a = int(matched["frame_a"]) + frame_b = int(matched["frame_b"]) + for fid in [frame_a, frame_b]: + if fid not in frame_grid: + frame_grid.append(fid) + frame_grid = sorted(set(frame_grid)) + + eq_item = move_item(dataset[(protein_idx, 0, frame_grid[0])], device) + mask = torch.ones_like(eq_item["trans_equilibrium"][..., 0]) + prior, _ = module.latent_encoder.forward_prior( + eq_item["trans_equilibrium"], + eq_item["rotmats_equilibrium"], + eq_item["seq"], + mask, + ) + mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_grid, device) + + cond_a, coeff_a = coeff_for_frame(module, dataset, protein_idx, frame_a, prior, mean_disp, device) + cond_b, coeff_b = coeff_for_frame(module, dataset, protein_idx, frame_b, prior, mean_disp, device) + + # Exact sign-flip audit on condition tensors for coeff_a vs -coeff_a. + cond_pos = condition_for_coeff(module, prior, coeff_a, eq_item) + cond_neg = condition_for_coeff(module, prior, -coeff_a, eq_item) + + # Direct a-vs-b condition distance. + even_keys = ["node_cond", "edge_cond", "disp_edge_cond"] + odd_keys = ["disp_node_cond"] + + row = { + "pdb_name": name, + "frame_a": frame_a, + "frame_b": frame_b, + "coeff_cos_ab": cosine(coeff_a, coeff_b), + "coeff_sign_flip_frac_ab": sign_flip_fraction(coeff_a, coeff_b), + "coeff_norm_ratio_b_over_a": float((coeff_b.norm() / coeff_a.norm().clamp_min(1e-8)).detach().cpu()), + "a_condition_correct_fraction": float(matched.get("a_condition_correct_fraction", float("nan"))), + "b_condition_correct_fraction": float(matched.get("b_condition_correct_fraction", float("nan"))), + "mean_correct_fraction": float(matched.get("mean_correct_fraction", float("nan"))), + } + + for key in even_keys + odd_keys: + row[f"flip_rel_l2_{key}"] = rel_l2(cond_pos[key], cond_neg[key]) + row[f"ab_rel_l2_{key}"] = rel_l2(cond_a[key], cond_b[key]) + + rows.append(row) + print(f"[audit] {name} done", flush=True) + + result = pd.DataFrame(rows) + result.to_csv(out_dir / "condition_sign_loss_audit.csv", index=False) + + summary = { + "n": int(len(result)), + "coeff_cos_ab_mean": float(result["coeff_cos_ab"].mean()), + "coeff_cos_ab_median": float(result["coeff_cos_ab"].median()), + "coeff_sign_flip_frac_mean": float(result["coeff_sign_flip_frac_ab"].mean()), + "b_correct_mean": float(result["b_condition_correct_fraction"].mean()), + "a_correct_mean": float(result["a_condition_correct_fraction"].mean()), + "mean_correct_mean": float(result["mean_correct_fraction"].mean()), + } + + # Static exactness: c vs -c should leave even paths almost unchanged and flip linear path. + for key in ["node_cond", "edge_cond", "disp_edge_cond", "disp_node_cond"]: + summary[f"flip_rel_l2_{key}_mean"] = float(result[f"flip_rel_l2_{key}"].mean()) + summary[f"flip_rel_l2_{key}_median"] = float(result[f"flip_rel_l2_{key}"].median()) + + # Correlations. No per-protein story, only aggregate statistics. + corr_cols = [ + "b_condition_correct_fraction", + "a_condition_correct_fraction", + "mean_correct_fraction", + ] + for y in corr_cols: + valid = result[["coeff_cos_ab", "coeff_sign_flip_frac_ab", y]].dropna() + if len(valid) >= 3: + summary[f"pearson_coeff_cos_vs_{y}"] = float(valid["coeff_cos_ab"].corr(valid[y], method="pearson")) + summary[f"spearman_coeff_cos_vs_{y}"] = float(valid["coeff_cos_ab"].corr(valid[y], method="spearman")) + summary[f"pearson_signflip_vs_{y}"] = float(valid["coeff_sign_flip_frac_ab"].corr(valid[y], method="pearson")) + summary[f"spearman_signflip_vs_{y}"] = float(valid["coeff_sign_flip_frac_ab"].corr(valid[y], method="spearman")) + + # Distribution bins, still aggregate. + bins = [-1.01, -0.5, 0.0, 0.5, 1.01] + labels = ["cos<-0.5", "-0.5<=cos<0", "0<=cos<0.5", "cos>=0.5"] + result["coeff_cos_bin"] = pd.cut(result["coeff_cos_ab"], bins=bins, labels=labels) + grouped = result.groupby("coeff_cos_bin", observed=False).agg( + n=("pdb_name", "count"), + b_correct_mean=("b_condition_correct_fraction", "mean"), + a_correct_mean=("a_condition_correct_fraction", "mean"), + mean_correct=("mean_correct_fraction", "mean"), + signflip_mean=("coeff_sign_flip_frac_ab", "mean"), + ).reset_index() + grouped.to_csv(out_dir / "condition_sign_loss_bins.csv", index=False) + + (out_dir / "condition_sign_loss_summary.json").write_text( + json.dumps(summary, indent=2, sort_keys=True) + "\n" + ) + + print("\n=== condition sign-loss summary ===") + print(json.dumps(summary, indent=2, sort_keys=True)) + print("\n=== coeff cosine bins ===") + print(grouped.to_string(index=False)) + print("\nSaved:", out_dir) + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/audit_condition_sign_loss_min.py b/bbflow_base/scripts/audit_condition_sign_loss_min.py new file mode 100644 index 0000000000000000000000000000000000000000..360dd4f078627574f8152bcdb9ff05ffe2aca476 --- /dev/null +++ b/bbflow_base/scripts/audit_condition_sign_loss_min.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python +import argparse +import json +import sys +from pathlib import Path + +import mdtraj +import numpy as np +import pandas as pd +import torch +from omegaconf import OmegaConf + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow +from bbflow.models.bbflow_module import BBFlowModule + + +def normalize_csv(path): + df = pd.read_csv(path) + if "folder" not in df.columns: + if "pdb_path" not in df.columns: + raise RuntimeError(f"{path} has neither folder nor pdb_path column") + df = df.copy() + df["folder"] = df["pdb_path"].map(lambda x: str(Path(str(x)).parent)) + return df + + +def load_module(ckpt_path, device): + ckpt_path = Path(ckpt_path) + infer_cfg = OmegaConf.load(ROOT / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(ckpt_path.with_name("config.yaml")) + + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.model.embed = ckpt_cfg.model.embed + + module = BBFlowModule(cfg) + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + + current = module.state_dict() + compatible = { + key: value + for key, value in ckpt["state_dict"].items() + if key in current and current[key].shape == value.shape + } + + module.load_state_dict(compatible, strict=False) + module.to(device) + module.eval() + return module + + +def move_item(item, device): + out = {} + for key, value in item.items(): + if torch.is_tensor(value): + out[key] = value[None].to(device) + else: + out[key] = value + return out + + +def infer_num_frames(row): + name = str(row["name"]) + folder = Path(str(row["folder"])) + xtc = folder / f"{name}_R1.xtc" + if not xtc.exists(): + raise FileNotFoundError(f"Missing trajectory: {xtc}") + + with mdtraj.open(str(xtc)) as handle: + return int(handle.n_frames if hasattr(handle, "n_frames") else len(handle)) + + +def mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device): + disps = [] + for frame_id in frame_ids: + item = move_item(dataset[(protein_idx, 0, int(frame_id))], device) + mask = torch.ones_like(item["trans_equilibrium"][..., 0]) + disp = module.latent_encoder.relative_displacement( + item["trans_1"].float(), + item["trans_equilibrium"].float(), + mask, + ) + disps.append(disp) + + return torch.cat(disps, dim=0).mean(dim=0, keepdim=True) + + +def coeff_for_frame(module, dataset, protein_idx, frame_id, prior, mean_disp, device): + item = move_item(dataset[(protein_idx, 0, int(frame_id))], device) + + condition, coeff = module.latent_encoder.frame_condition_from_projection( + item["trans_1"], + item["trans_equilibrium"], + item["rotmats_equilibrium"], + torch.ones_like(item["trans_equilibrium"][..., 0]), + prior, + mean_disp=mean_disp, + ) + + return item, condition, coeff.detach().float() + + +def condition_for_coeff(module, prior, coeff, item): + extra = { + key: prior[key] + for key in [ + "mixture_logits", + "mixture_log_probs", + "mixture_mu", + "mixture_scale_tril", + ] + if key in prior + } + + return module.latent_encoder.condition_from_mode_coefficients( + prior["u_global"], + coeff, + item["rotmats_equilibrium"], + torch.ones_like(item["trans_equilibrium"][..., 0]), + extra=extra, + ) + + +def rel_l2(a, b): + a = a.detach().float() + b = b.detach().float().to(a.device) + return float(((a - b).norm() / a.norm().clamp_min(1e-8)).detach().cpu()) + + +def cosine(a, b): + a = a.detach().float().reshape(-1) + b = b.detach().float().reshape(-1).to(a.device) + denom = a.norm().clamp_min(1e-8) * b.norm().clamp_min(1e-8) + return float(((a * b).sum() / denom).detach().cpu()) + + +def signflip_fraction(a, b): + a = a.detach().float().reshape(-1) + b = b.detach().float().reshape(-1).to(a.device) + + valid = (a.abs() > 1e-8) & (b.abs() > 1e-8) + if valid.sum() == 0: + return float("nan") + + return float(((a[valid] * b[valid]) < 0).float().mean().detach().cpu()) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--csv_path", required=True) + parser.add_argument("--matched_csv", required=True) + parser.add_argument("--out_dir", required=True) + parser.add_argument("--device", default="cuda") + args = parser.parse_args() + + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + device = torch.device( + args.device + if args.device.startswith("cuda") and torch.cuda.is_available() + else "cpu" + ) + + module = load_module(args.ckpt_path, device) + + metadata = normalize_csv(args.csv_path) + dataset = PDBDatasetBBFlow(csv=metadata) + + matched = pd.read_csv(args.matched_csv) + name_to_idx = {str(name): idx for idx, name in enumerate(dataset.pdb_names)} + + rows = [] + + with torch.no_grad(): + for _, row in matched.iterrows(): + pdb_name = str(row["pdb_name"]) + if pdb_name not in name_to_idx: + continue + + protein_idx = name_to_idx[pdb_name] + total_frames = infer_num_frames(dataset.csv.iloc[protein_idx]) + + frame_a = int(row["frame_a"]) + frame_b = int(row["frame_b"]) + + frame_grid = np.linspace(0, total_frames - 1, 6, dtype=int).tolist() + frame_grid = sorted(set(frame_grid + [frame_a, frame_b])) + + eq_item = move_item(dataset[(protein_idx, 0, int(frame_grid[0]))], device) + mask = torch.ones_like(eq_item["trans_equilibrium"][..., 0]) + + prior, _ = module.latent_encoder.forward_prior( + eq_item["trans_equilibrium"], + eq_item["rotmats_equilibrium"], + eq_item["seq"], + mask, + ) + + mean_disp = mean_disp_from_frames( + module, + dataset, + protein_idx, + frame_grid, + device, + ) + + item_a, cond_a, coeff_a = coeff_for_frame( + module, + dataset, + protein_idx, + frame_a, + prior, + mean_disp, + device, + ) + + _, cond_b, coeff_b = coeff_for_frame( + module, + dataset, + protein_idx, + frame_b, + prior, + mean_disp, + device, + ) + + cond_pos = condition_for_coeff(module, prior, coeff_a, item_a) + cond_neg = condition_for_coeff(module, prior, -coeff_a, item_a) + + audit_row = { + "pdb_name": pdb_name, + "frame_a": frame_a, + "frame_b": frame_b, + "coeff_cos_ab": cosine(coeff_a, coeff_b), + "coeff_signflip_frac_ab": signflip_fraction(coeff_a, coeff_b), + "coeff_norm_ratio_b_over_a": float( + (coeff_b.norm() / coeff_a.norm().clamp_min(1e-8)) + .detach() + .cpu() + ), + "a_condition_correct_fraction": float( + row.get("a_condition_correct_fraction", np.nan) + ), + "b_condition_correct_fraction": float( + row.get("b_condition_correct_fraction", np.nan) + ), + "mean_correct_fraction": float( + row.get("mean_correct_fraction", np.nan) + ), + } + + for key in [ + "node_cond", + "edge_cond", + "disp_edge_cond", + "disp_node_cond", + ]: + audit_row[f"flip_rel_l2_{key}"] = rel_l2( + cond_pos[key], + cond_neg[key], + ) + audit_row[f"ab_rel_l2_{key}"] = rel_l2( + cond_a[key], + cond_b[key], + ) + + rows.append(audit_row) + print(f"[audit] {pdb_name}", flush=True) + + result = pd.DataFrame(rows) + result.to_csv(out_dir / "condition_sign_loss_audit.csv", index=False) + + summary = { + "n": int(len(result)), + "coeff_cos_ab_mean": float(result["coeff_cos_ab"].mean()), + "coeff_cos_ab_median": float(result["coeff_cos_ab"].median()), + "coeff_signflip_frac_mean": float( + result["coeff_signflip_frac_ab"].mean() + ), + "a_correct_mean": float( + result["a_condition_correct_fraction"].mean() + ), + "b_correct_mean": float( + result["b_condition_correct_fraction"].mean() + ), + "mean_correct_mean": float(result["mean_correct_fraction"].mean()), + } + + for key in [ + "node_cond", + "edge_cond", + "disp_edge_cond", + "disp_node_cond", + ]: + summary[f"flip_rel_l2_{key}_mean"] = float( + result[f"flip_rel_l2_{key}"].mean() + ) + summary[f"flip_rel_l2_{key}_median"] = float( + result[f"flip_rel_l2_{key}"].median() + ) + summary[f"ab_rel_l2_{key}_mean"] = float( + result[f"ab_rel_l2_{key}"].mean() + ) + summary[f"ab_rel_l2_{key}_median"] = float( + result[f"ab_rel_l2_{key}"].median() + ) + + for metric in [ + "b_condition_correct_fraction", + "a_condition_correct_fraction", + "mean_correct_fraction", + ]: + valid = result[ + ["coeff_cos_ab", "coeff_signflip_frac_ab", metric] + ].dropna() + + summary[f"pearson_coeff_cos_vs_{metric}"] = float( + valid["coeff_cos_ab"].corr(valid[metric], method="pearson") + ) + summary[f"spearman_coeff_cos_vs_{metric}"] = float( + valid["coeff_cos_ab"].corr(valid[metric], method="spearman") + ) + summary[f"pearson_signflip_vs_{metric}"] = float( + valid["coeff_signflip_frac_ab"].corr(valid[metric], method="pearson") + ) + summary[f"spearman_signflip_vs_{metric}"] = float( + valid["coeff_signflip_frac_ab"].corr(valid[metric], method="spearman") + ) + + bins = [-1.01, -0.5, 0.0, 0.5, 1.01] + labels = ["cos<-0.5", "-0.5<=cos<0", "0<=cos<0.5", "cos>=0.5"] + + result["coeff_cos_bin"] = pd.cut( + result["coeff_cos_ab"], + bins=bins, + labels=labels, + ) + + grouped = ( + result.groupby("coeff_cos_bin", observed=False) + .agg( + n=("pdb_name", "count"), + b_correct_mean=("b_condition_correct_fraction", "mean"), + a_correct_mean=("a_condition_correct_fraction", "mean"), + mean_correct=("mean_correct_fraction", "mean"), + signflip_mean=("coeff_signflip_frac_ab", "mean"), + ) + .reset_index() + ) + + grouped.to_csv(out_dir / "condition_sign_loss_bins.csv", index=False) + + (out_dir / "condition_sign_loss_summary.json").write_text( + json.dumps(summary, indent=2, sort_keys=True) + "\n" + ) + + print("\n=== condition sign-loss summary ===") + print(json.dumps(summary, indent=2, sort_keys=True)) + + print("\n=== coeff cosine bins ===") + print(grouped.to_string(index=False)) + + print("\nSaved:", out_dir) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/audit_condition_source_paths.py b/bbflow_base/scripts/audit_condition_source_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..f5e5736d17cd73b0bec94c7ed06c82b7322a78d0 --- /dev/null +++ b/bbflow_base/scripts/audit_condition_source_paths.py @@ -0,0 +1,265 @@ +from pathlib import Path +import argparse +import json +import re + + +def read_text(path): + return Path(path).read_text(encoding="utf-8", errors="replace") + + +def line_no_offsets(text): + starts = [0] + for m in re.finditer("\n", text): + starts.append(m.end()) + return starts + + +def pos_to_line(starts, pos): + lo, hi = 0, len(starts) - 1 + while lo <= hi: + mid = (lo + hi) // 2 + if starts[mid] <= pos: + lo = mid + 1 + else: + hi = mid - 1 + return hi + 1 + + +def extract_def(text, name): + pattern = re.compile(rf"^(\s*)def\s+{re.escape(name)}\s*\(", re.MULTILINE) + m = pattern.search(text) + if not m: + return None + + indent = len(m.group(1)) + start = m.start() + lines = text[start:].splitlines() + out = [] + for i, line in enumerate(lines): + if i > 0 and line.strip(): + cur_indent = len(line) - len(line.lstrip(" ")) + if cur_indent <= indent and re.match(r"\s*(def|class)\s+", line): + break + out.append(line) + return "\n".join(out) + + +def extract_class_method(text, method_name): + return extract_def(text, method_name) + + +def grep_files(root, patterns, include_ext=(".py",)): + root = Path(root) + hits = [] + for path in root.rglob("*"): + if not path.is_file(): + continue + if path.suffix not in include_ext: + continue + try: + text = read_text(path) + except Exception: + continue + starts = line_no_offsets(text) + for pat in patterns: + for m in re.finditer(pat, text): + hits.append({ + "file": str(path), + "line": pos_to_line(starts, m.start()), + "pattern": pat, + "text": text[m.start(): text.find("\n", m.start()) if text.find("\n", m.start()) != -1 else m.end()], + }) + return hits + + +def find_file_containing(root, token): + root = Path(root) + found = [] + for path in root.rglob("*.py"): + try: + text = read_text(path) + except Exception: + continue + if token in text: + found.append(path) + return found + + +def bool_pattern(text, pattern): + return bool(re.search(pattern, text, flags=re.MULTILINE | re.DOTALL)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--repo", default=".") + ap.add_argument("--out_dir", required=True) + args = ap.parse_args() + + repo = Path(args.repo).resolve() + out = Path(args.out_dir) + out.mkdir(parents=True, exist_ok=True) + + bbflow = repo / "bbflow" + models = bbflow / "models" + data = bbflow / "data" + + report = { + "repo": str(repo), + "checks": {}, + "files": {}, + "hits": {}, + } + + print("===== locate condition_from_mode_coefficients =====") + cond_files = find_file_containing(bbflow, "condition_from_mode_coefficients") + report["files"]["condition_from_mode_coefficients"] = [str(p) for p in cond_files] + for p in cond_files: + print(p) + + print("\n===== condition_from_mode_coefficients source =====") + for p in cond_files: + text = read_text(p) + src = extract_def(text, "condition_from_mode_coefficients") + if src: + print(f"\n--- {p} ---") + print(src) + (out / f"{p.name}.condition_from_mode_coefficients.txt").write_text(src, encoding="utf-8") + + report["checks"]["condition_uses_coefficients"] = { + "coeff_abs": "coeff_abs" in src, + "coefficients_abs": "abs" in src and "coeff" in src, + "coefficients_square": "coefficients.square" in src or ".square()" in src, + "disp_global_from_coefficients": bool_pattern( + src, + r"disp_global\s*=.*coefficients|coefficients.*disp_global|einsum\(.*coefficients|matmul\(.*coefficients", + ), + "disp_local_from_disp_global": "disp_local" in src and "disp_global" in src, + "has_detach": ".detach()" in src or "detach(" in src, + "has_no_grad": "no_grad" in src, + } + + print("\n===== locate FiLM / adapter functions =====") + film_files = [] + for token in ["_apply_latent_film", "z_node_adapter", "disp_node_adapter", "node_condition_embedding"]: + files = find_file_containing(models, token) + report["files"][token] = [str(p) for p in files] + for p in files: + if p not in film_files: + film_files.append(p) + print(token, "=>", p) + + print("\n===== _apply_latent_film source =====") + for p in film_files: + text = read_text(p) + src = extract_class_method(text, "_apply_latent_film") + if src: + print(f"\n--- {p} ---") + print(src) + (out / f"{p.name}._apply_latent_film.txt").write_text(src, encoding="utf-8") + report["checks"]["film"] = { + "uses_node_cond": "node_cond" in src, + "uses_disp_node_cond": "disp_node_cond" in src, + "uses_edge_cond": "edge_cond" in src, + "uses_disp_edge_cond": "disp_edge_cond" in src, + "uses_tanh": "tanh" in src, + "has_detach": ".detach()" in src or "detach(" in src, + } + + print("\n===== adapter / condition embedding relevant lines =====") + adapter_patterns = [ + r"node_condition_embedding.*", + r"edge_condition_embedding.*", + r"z_node_adapter.*", + r"disp_node_adapter.*", + r"z_edge_adapter.*", + r"disp_edge_adapter.*", + r"node_cond.*", + r"disp_node_cond.*", + r"edge_cond.*", + r"disp_edge_cond.*", + ] + adapter_hits = grep_files(models, adapter_patterns) + report["hits"]["adapter_lines"] = adapter_hits + for h in adapter_hits[:220]: + print(f"{h['file']}:{h['line']}: {h['text']}") + + print("\n===== detach / no_grad / requires_grad near condition paths =====") + detach_patterns = [ + r".{0,80}detach\(\).{0,80}", + r".{0,80}no_grad.{0,80}", + r".{0,80}requires_grad.{0,80}", + ] + detach_hits = [] + for h in grep_files(bbflow, detach_patterns): + low = h["text"].lower() + if any(k in low for k in ["condition", "coeff", "disp", "latent", "film", "adapter", "mode"]): + detach_hits.append(h) + report["hits"]["detach_lines"] = detach_hits + for h in detach_hits[:160]: + print(f"{h['file']}:{h['line']}: {h['text']}") + + print("\n===== loss terms involving coefficients / condition =====") + loss_patterns = [ + r".{0,80}condition_cycle.{0,80}", + r".{0,80}cycle_loss.{0,80}", + r".{0,80}motion_loss.{0,80}", + r".{0,80}q_nll.{0,80}", + r".{0,80}mode_coeff.{0,80}", + r".{0,80}cross_cov_loss.{0,80}", + r".{0,80}local_cov_loss.{0,80}", + ] + loss_hits = grep_files(bbflow, loss_patterns) + report["hits"]["loss_lines"] = loss_hits + for h in loss_hits[:220]: + print(f"{h['file']}:{h['line']}: {h['text']}") + + print("\n===== possible sampled-c inference path =====") + infer_patterns = [ + r".{0,80}sample_coefficients_from_q.{0,80}", + r".{0,80}condition_from_mode_coefficients.{0,80}", + r".{0,80}sample_prior_z.{0,80}", + r".{0,80}forward_prior.{0,80}", + r".{0,80}condition_scale.{0,80}", + r".{0,80}condition_mode.{0,80}", + ] + infer_hits = grep_files(bbflow, infer_patterns) + report["hits"]["inference_condition_lines"] = infer_hits + for h in infer_hits[:220]: + print(f"{h['file']}:{h['line']}: {h['text']}") + + print("\n===== automatic verdict =====") + verdict = {} + + cond_check = report["checks"].get("condition_uses_coefficients", {}) + film_check = report["checks"].get("film", {}) + + verdict["disp_path_source"] = ( + "likely_from_coefficients" + if cond_check.get("disp_global_from_coefficients") and cond_check.get("disp_local_from_disp_global") + else "unclear_check_source_snippet" + ) + verdict["condition_path_has_detach_in_function"] = bool(cond_check.get("has_detach") or cond_check.get("has_no_grad")) + verdict["node_edge_sign_invariant_by_construction"] = bool( + cond_check.get("coeff_abs") or cond_check.get("coefficients_square") + ) + verdict["film_signed_or_unsigned"] = ( + "unsigned_only_node_cond" + if film_check.get("uses_node_cond") and not film_check.get("uses_disp_node_cond") + else "uses_signed_disp_or_unclear" + ) + verdict["film_has_tanh"] = bool(film_check.get("uses_tanh")) + + print(json.dumps(verdict, indent=2, ensure_ascii=False)) + + report["verdict"] = verdict + (out / "condition_source_audit_report.json").write_text( + json.dumps(report, indent=2, ensure_ascii=False), + encoding="utf-8", + ) + + print("\nSaved:", out) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/audit_covariance_transport.py b/bbflow_base/scripts/audit_covariance_transport.py new file mode 100644 index 0000000000000000000000000000000000000000..246bb1ead9804f668588c95db4889e5d247cc4e9 --- /dev/null +++ b/bbflow_base/scripts/audit_covariance_transport.py @@ -0,0 +1,427 @@ +#!/usr/bin/env python +"""Audit endpoint covariance transport outputs. + +This is a verification script, not a generator. It checks the exact concerns +raised after the first oracle transport run: + +* same-batch base vs transported statistics; +* lambda=0 near-identity after per-model Kabsch alignment; +* input residue metadata agreement; +* det(R)=+1 for all Kabsch rotations used by this audit; +* output-vs-target covariance errors, including off-diagonal error; +* top-PC subspace overlap; +* CA continuity, CA clashes, and radius of gyration. + +All coordinates are CA-only and reported in Angstrom. +""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Iterable + +import mdtraj +import numpy as np + + +def read_test_names(csv_path: Path) -> list[str]: + with csv_path.open(newline="") as handle: + reader = csv.DictReader(handle) + if reader.fieldnames is None: + raise ValueError(f"Empty CSV: {csv_path}") + key = "pdb_name" if "pdb_name" in reader.fieldnames else reader.fieldnames[0] + return [str(row[key]).strip() for row in reader if str(row[key]).strip()] + + +def load_ca_traj(pdb_path: Path) -> tuple[mdtraj.Trajectory, np.ndarray]: + traj = mdtraj.load(str(pdb_path)) + ca = traj.topology.select("name CA") + if ca.size == 0: + raise ValueError(f"No CA atoms in {pdb_path}") + return traj, np.asarray(traj.xyz[:, ca, :] * 10.0, dtype=np.float64) + + +def load_md_ca(atlas_root: Path, pdb_name: str, stride: int, max_frames: int, seed: int) -> tuple[mdtraj.Trajectory, np.ndarray]: + entry = atlas_root / pdb_name + top_path = entry / f"{pdb_name}.pdb" + if not top_path.exists(): + raise FileNotFoundError(top_path) + top = mdtraj.load(str(top_path)) + ca = top.topology.select("name CA") + if ca.size == 0: + raise ValueError(f"No CA atoms in {top_path}") + frames = [] + for replica in (1, 2, 3): + xtc = entry / f"{pdb_name}_R{replica}.xtc" + if not xtc.exists(): + raise FileNotFoundError(xtc) + traj = mdtraj.load(str(xtc), top=str(top_path), atom_indices=ca, stride=max(1, stride)) + frames.append(np.asarray(traj.xyz * 10.0, dtype=np.float64)) + coords = np.concatenate(frames, axis=0) + if max_frames and coords.shape[0] > max_frames: + rng = np.random.default_rng(seed) + idx = np.sort(rng.choice(coords.shape[0], size=max_frames, replace=False)) + coords = coords[idx] + return top, coords + + +def ca_residue_signature(traj: mdtraj.Trajectory) -> list[tuple[int, int, str, str]]: + ca = traj.topology.select("name CA") + sig = [] + for atom_idx in ca: + atom = traj.topology.atom(int(atom_idx)) + residue = atom.residue + chain_index = residue.chain.index + # mdtraj PDB loaders do not consistently expose insertion codes, so keep + # the fields it reliably preserves. + sig.append((chain_index, residue.resSeq, residue.name, atom.name)) + return sig + + +def kabsch(P: np.ndarray, Q: np.ndarray) -> tuple[np.ndarray, float]: + H = P.T @ Q + U, _, Vt = np.linalg.svd(H, full_matrices=False) + sign = np.sign(np.linalg.det(Vt.T @ U.T)) + if sign == 0: + sign = 1.0 + D = np.diag([1.0, 1.0, sign]) + R = U @ D @ Vt + return R, float(np.linalg.det(R)) + + +def center_frames(X: np.ndarray) -> np.ndarray: + return X - X.mean(axis=1, keepdims=True) + + +def superpose_to_reference(X: np.ndarray, ref: np.ndarray) -> tuple[np.ndarray, list[float]]: + out = [] + dets = [] + ref_c = ref - ref.mean(axis=0, keepdims=True) + for frame in X: + frame_c = frame - frame.mean(axis=0, keepdims=True) + R, det = kabsch(frame_c, ref_c) + out.append(frame_c @ R) + dets.append(det) + return np.stack(out, axis=0), dets + + +def superpose_to_mean(X: np.ndarray, iterations: int = 3) -> tuple[np.ndarray, np.ndarray, list[float]]: + Xc = center_frames(X) + ref = Xc[0] + dets_all = [] + aligned = Xc + for _ in range(iterations): + frames = [] + for frame in aligned: + R, det = kabsch(frame - frame.mean(axis=0, keepdims=True), ref) + frames.append((frame - frame.mean(axis=0, keepdims=True)) @ R) + dets_all.append(det) + aligned = np.stack(frames, axis=0) + ref = aligned.mean(axis=0) + ref = ref - ref.mean(axis=0, keepdims=True) + return aligned, ref, dets_all + + +def flatten_centered(X: np.ndarray) -> np.ndarray: + return X.reshape(X.shape[0], -1) - X.reshape(X.shape[0], -1).mean(axis=0, keepdims=True) + + +def covariance(X: np.ndarray) -> np.ndarray: + Xc = X - X.mean(axis=0, keepdims=True) + return (Xc.T @ Xc) / max(Xc.shape[0] - 1, 1) + + +def covariance_diag(X: np.ndarray) -> np.ndarray: + return np.var(X, axis=0, ddof=1) + + +def offdiag_mask(size: int) -> np.ndarray: + mask = np.ones((size, size), dtype=bool) + np.fill_diagonal(mask, False) + return mask + + +def oracle_target_cov(Fg: np.ndarray, Fr: np.ndarray, lam: float, eps: float) -> np.ndarray: + Cg = covariance(Fg) + Cr = covariance(Fr) + dg = np.clip(np.diag(Cg), eps, None) + dr = np.clip(np.diag(Cr), eps, None) + scale = np.sqrt(dg / dr) + Cr_scaled = Cr * scale[:, None] * scale[None, :] + return (1.0 - lam) * Cg + lam * Cr_scaled + + +def rel_fro(A: np.ndarray, B: np.ndarray, mask: np.ndarray | None = None, eps: float = 1e-8) -> float: + if mask is not None: + A = A[mask] + B = B[mask] + return float(np.linalg.norm(A - B) / max(np.linalg.norm(B), eps)) + + +def top_pc_overlap(Ca: np.ndarray, Cb: np.ndarray, k: int) -> float: + k = min(k, Ca.shape[0], Cb.shape[0]) + if k <= 0: + return float("nan") + _, Va = np.linalg.eigh((Ca + Ca.T) * 0.5) + _, Vb = np.linalg.eigh((Cb + Cb.T) * 0.5) + Qa = Va[:, -k:] + Qb = Vb[:, -k:] + s = np.linalg.svd(Qa.T @ Qb, compute_uv=False) + return float(np.mean(s * s)) + + +def pairwise_rmsd_mean(X: np.ndarray) -> float: + F = X.reshape(X.shape[0], -1) + diff = F[:, None, :] - F[None, :, :] + dist = np.sqrt(np.mean(diff * diff, axis=-1)) + return float(dist.mean()) + + +def rmsf_profile(X: np.ndarray, ref: np.ndarray) -> np.ndarray: + X_al, _ = superpose_to_reference(X, ref) + return np.sqrt(np.mean(np.sum((X_al - ref[None]) ** 2, axis=-1), axis=0)) + + +def radius_of_gyration(X: np.ndarray) -> np.ndarray: + centered = X - X.mean(axis=1, keepdims=True) + return np.sqrt(np.mean(np.sum(centered * centered, axis=-1), axis=1)) + + +def ca_continuity_stats(X: np.ndarray) -> dict[str, float]: + d = np.linalg.norm(X[:, 1:, :] - X[:, :-1, :], axis=-1) + return { + "ca_neighbor_dist_mean": float(d.mean()), + "ca_neighbor_dist_max": float(d.max()), + "ca_neighbor_break_frac_gt4p5": float((d > 4.5).mean()), + } + + +def ca_clash_frac(X: np.ndarray, threshold: float) -> float: + n = X.shape[1] + diff = X[:, :, None, :] - X[:, None, :, :] + dist = np.linalg.norm(diff, axis=-1) + sep = np.abs(np.arange(n)[:, None] - np.arange(n)[None, :]) + mask = sep > 1 + return float((dist[:, mask] < threshold).mean()) + + +def bootstrap_delta(values_a: np.ndarray, values_b: np.ndarray, seed: int, samples: int) -> dict[str, float]: + values_a = np.asarray(values_a, dtype=np.float64) + values_b = np.asarray(values_b, dtype=np.float64) + delta = values_b - values_a + rng = np.random.default_rng(seed) + boot = [] + for _ in range(samples): + idx = rng.integers(0, len(delta), size=len(delta)) + boot.append(delta[idx].mean()) + boot = np.asarray(boot) + return { + "base_mean": float(values_a.mean()), + "transport_mean": float(values_b.mean()), + "delta_transport_minus_base": float(delta.mean()), + "delta_ci95_low": float(np.quantile(boot, 0.025)), + "delta_ci95_high": float(np.quantile(boot, 0.975)), + } + + +def audit_one( + pdb_name: str, + base_dir: Path, + transport_dir: Path, + atlas_root: Path, + lam: float, + md_stride: int, + max_md_frames: int, + seed: int, + eps: float, + top_pc_k: int, +) -> dict[str, float | int | str | bool]: + base_pdb = base_dir / pdb_name / "sampled_conformations.pdb" + trans_pdb = transport_dir / pdb_name / "sampled_conformations.pdb" + if not base_pdb.exists(): + return {"pdb_name": pdb_name, "status": "missing_base"} + if not trans_pdb.exists(): + return {"pdb_name": pdb_name, "status": "missing_transport"} + + base_traj, Xb_raw = load_ca_traj(base_pdb) + trans_traj, Xt_raw = load_ca_traj(trans_pdb) + md_top, Xm_raw = load_md_ca(atlas_root, pdb_name, md_stride, max_md_frames, seed) + + base_sig = ca_residue_signature(base_traj) + md_sig = ca_residue_signature(md_top) + residue_exact_match = base_sig == md_sig + residue_name_match_frac = float(np.mean([a[2] == b[2] for a, b in zip(base_sig, md_sig)])) if len(base_sig) == len(md_sig) else 0.0 + + if Xb_raw.shape != Xt_raw.shape: + raise ValueError(f"{pdb_name}: base/transport shape mismatch {Xb_raw.shape} vs {Xt_raw.shape}") + if Xb_raw.shape[1] != Xm_raw.shape[1]: + raise ValueError(f"{pdb_name}: base/MD residue mismatch {Xb_raw.shape[1]} vs {Xm_raw.shape[1]}") + + Xb, mean_b, dets_b = superpose_to_mean(Xb_raw) + Xm, mean_m, dets_m = superpose_to_mean(Xm_raw) + Rb2m, det_b2m = kabsch(mean_b, mean_m) + Xb = Xb @ Rb2m + mean_b = mean_b @ Rb2m + Xt_aligned, dets_t = superpose_to_reference(Xt_raw, mean_b) + + Fb = flatten_centered(Xb) + Ft = flatten_centered(Xt_aligned) + Fm = flatten_centered(Xm) + Cb = covariance(Fb) + Ct = covariance(Ft) + Ctarget = oracle_target_cov(Fb, Fm, lam=lam, eps=eps) + mask_off = offdiag_mask(Cb.shape[0]) + + ref = Xb.mean(axis=0) + rmsf_b = rmsf_profile(Xb_raw, ref) + rmsf_t = rmsf_profile(Xt_raw, ref) + + # Per-frame identity error after Kabsch. This should be PDB quantization level + # for lambda=0 if the transform is actually identity-like. + aligned_t_to_b = [] + dets_identity = [] + for frame_b, frame_t in zip(Xb_raw, Xt_raw): + b = frame_b - frame_b.mean(axis=0, keepdims=True) + t = frame_t - frame_t.mean(axis=0, keepdims=True) + R, det = kabsch(t, b) + aligned_t_to_b.append(t @ R) + dets_identity.append(det) + aligned_t_to_b = np.stack(aligned_t_to_b, axis=0) + centered_b_raw = center_frames(Xb_raw) + identity_diff = aligned_t_to_b - centered_b_raw + + rg_b = radius_of_gyration(Xb_raw) + rg_t = radius_of_gyration(Xt_raw) + cont_b = ca_continuity_stats(Xb_raw) + cont_t = ca_continuity_stats(Xt_raw) + + row: dict[str, float | int | str | bool] = { + "pdb_name": pdb_name, + "status": "ok", + "num_res": int(Xb_raw.shape[1]), + "num_frames": int(Xb_raw.shape[0]), + "residue_exact_match_base_md": bool(residue_exact_match), + "residue_name_match_frac_base_md": residue_name_match_frac, + "det_min": float(min(dets_b + dets_m + dets_t + dets_identity + [det_b2m])), + "det_max": float(max(dets_b + dets_m + dets_t + dets_identity + [det_b2m])), + "trace_base": float(np.trace(Cb)), + "trace_transport": float(np.trace(Ct)), + "trace_target": float(np.trace(Ctarget)), + "diag_rel_l1_base_transport": float(np.mean(np.abs(np.diag(Ct) - np.diag(Cb))) / max(np.mean(np.diag(Cb)), eps)), + "cov_rel_fro_transport_vs_target": rel_fro(Ct, Ctarget, eps=eps), + "cov_offdiag_rel_fro_transport_vs_target": rel_fro(Ct, Ctarget, mask=mask_off, eps=eps), + "cov_offdiag_rel_fro_transport_vs_base": rel_fro(Ct, Cb, mask=mask_off, eps=eps), + "top_pc_overlap_transport_target": top_pc_overlap(Ct, Ctarget, top_pc_k), + "top_pc_overlap_transport_md": top_pc_overlap(Ct, covariance(Fm), top_pc_k), + "top_pc_overlap_base_md": top_pc_overlap(Cb, covariance(Fm), top_pc_k), + "identity_rmsd_mean": float(np.sqrt(np.mean(identity_diff * identity_diff))), + "identity_rmsd_max": float(np.sqrt(np.max(np.mean(identity_diff * identity_diff, axis=(1, 2))))), + "rmsf_mae_base_transport": float(np.mean(np.abs(rmsf_t - rmsf_b))), + "rmsf_median_base": float(np.median(rmsf_b)), + "rmsf_median_transport": float(np.median(rmsf_t)), + "pairwise_mean_base": pairwise_rmsd_mean(Xb_raw), + "pairwise_mean_transport": pairwise_rmsd_mean(Xt_raw), + "rg_mean_base": float(rg_b.mean()), + "rg_mean_transport": float(rg_t.mean()), + "rg_delta_mean": float((rg_t - rg_b).mean()), + "ca_clash_frac_base_lt3p0": ca_clash_frac(Xb_raw, 3.0), + "ca_clash_frac_transport_lt3p0": ca_clash_frac(Xt_raw, 3.0), + } + for key, value in cont_b.items(): + row[f"base_{key}"] = value + for key, value in cont_t.items(): + row[f"transport_{key}"] = value + return row + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--base_dir", required=True, type=Path) + parser.add_argument("--transport_dir", required=True, type=Path) + parser.add_argument("--atlas_root", required=True, type=Path) + parser.add_argument("--test_csv", required=True, type=Path) + parser.add_argument("--out_dir", required=True, type=Path) + parser.add_argument("--lam", type=float, default=0.0) + parser.add_argument("--md_stride", type=int, default=1) + parser.add_argument("--max_md_frames", type=int, default=0) + parser.add_argument("--seed", type=int, default=123) + parser.add_argument("--bootstrap_samples", type=int, default=2000) + parser.add_argument("--top_pc_k", type=int, default=2) + parser.add_argument("--limit", type=int, default=0) + parser.add_argument("--eps", type=float, default=1e-8) + return parser.parse_args() + + +def numeric_summary(rows: list[dict[str, object]], seed: int, bootstrap_samples: int) -> dict[str, object]: + ok = [row for row in rows if row.get("status") == "ok"] + summary: dict[str, object] = {"n": len(rows), "n_ok": len(ok)} + if not ok: + return summary + keys = sorted({key for row in ok for key, value in row.items() if isinstance(value, (int, float, bool))}) + for key in keys: + vals = np.asarray([float(row[key]) for row in ok if key in row], dtype=np.float64) + if vals.size: + summary[f"{key}_mean"] = float(vals.mean()) + summary[f"{key}_median"] = float(np.median(vals)) + + for base_key, transport_key, label in [ + ("pairwise_mean_base", "pairwise_mean_transport", "pairwise_mean"), + ("rg_mean_base", "rg_mean_transport", "rg_mean"), + ("ca_clash_frac_base_lt3p0", "ca_clash_frac_transport_lt3p0", "ca_clash_frac_lt3p0"), + ("base_ca_neighbor_break_frac_gt4p5", "transport_ca_neighbor_break_frac_gt4p5", "ca_neighbor_break_frac_gt4p5"), + ]: + if all(base_key in row and transport_key in row for row in ok): + summary[f"paired_{label}"] = bootstrap_delta( + np.asarray([row[base_key] for row in ok], dtype=np.float64), + np.asarray([row[transport_key] for row in ok], dtype=np.float64), + seed=seed, + samples=bootstrap_samples, + ) + return summary + + +def main() -> None: + args = parse_args() + names = read_test_names(args.test_csv) + if args.limit > 0: + names = names[: args.limit] + args.out_dir.mkdir(parents=True, exist_ok=True) + + rows = [] + for idx, name in enumerate(names, start=1): + print(f"[{idx}/{len(names)}] audit {name}") + row = audit_one( + pdb_name=name, + base_dir=args.base_dir, + transport_dir=args.transport_dir, + atlas_root=args.atlas_root, + lam=args.lam, + md_stride=args.md_stride, + max_md_frames=args.max_md_frames, + seed=args.seed + idx, + eps=args.eps, + top_pc_k=args.top_pc_k, + ) + rows.append(row) + print(json.dumps(row, sort_keys=True)) + + payload = { + "base_dir": str(args.base_dir), + "transport_dir": str(args.transport_dir), + "atlas_root": str(args.atlas_root), + "test_csv": str(args.test_csv), + "lambda": args.lam, + "rows": rows, + "summary": numeric_summary(rows, seed=args.seed, bootstrap_samples=args.bootstrap_samples), + } + out_path = args.out_dir / "covariance_transport_audit.json" + with out_path.open("w") as handle: + json.dump(payload, handle, indent=2, sort_keys=True) + print(f"Saved: {out_path}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/audit_frame_gap_confound.py b/bbflow_base/scripts/audit_frame_gap_confound.py new file mode 100644 index 0000000000000000000000000000000000000000..859d84805e766b96f2aa6604382709c799d995e9 --- /dev/null +++ b/bbflow_base/scripts/audit_frame_gap_confound.py @@ -0,0 +1,160 @@ +from pathlib import Path +import argparse +import json +import numpy as np +import pandas as pd + + +def rank(a): + return pd.Series(a).rank(method="average").to_numpy(float) + + +def pearson(x, y): + x = np.asarray(x, float) + y = np.asarray(y, float) + if len(x) < 3 or np.std(x) == 0 or np.std(y) == 0: + return float("nan") + return float(np.corrcoef(x, y)[0, 1]) + + +def corr(df, x, y, method="pearson"): + z = df[[x, y]].replace([np.inf, -np.inf], np.nan).dropna() + xx = z[x].to_numpy(float) + yy = z[y].to_numpy(float) + if method == "spearman": + xx = rank(xx) + yy = rank(yy) + return pearson(xx, yy) + + +def residualize(y, controls): + y = np.asarray(y, float) + X = [np.ones_like(y)] + for c in controls: + X.append(np.asarray(c, float)) + X = np.stack(X, axis=1) + beta, *_ = np.linalg.lstsq(X, y, rcond=None) + return y - X @ beta + + +def partial_corr(df, x, y, controls, method="pearson"): + cols = [x, y] + controls + z = df[cols].replace([np.inf, -np.inf], np.nan).dropna() + if len(z) < len(controls) + 3: + return float("nan") + xx = z[x].to_numpy(float) + yy = z[y].to_numpy(float) + cc = [z[c].to_numpy(float) for c in controls] + if method == "spearman": + xx = rank(xx) + yy = rank(yy) + cc = [rank(c) for c in cc] + return pearson(residualize(xx, cc), residualize(yy, cc)) + + +def leave_one_out(df, x, y, method="pearson"): + vals = [] + for i in range(len(df)): + vals.append(corr(df.drop(df.index[i]), x, y, method)) + vals = np.array([v for v in vals if np.isfinite(v)], float) + return { + "min": float(vals.min()) if len(vals) else float("nan"), + "max": float(vals.max()) if len(vals) else float("nan"), + "median": float(np.median(vals)) if len(vals) else float("nan"), + } + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--joined_csv", required=True) + ap.add_argument("--out_dir", required=True) + args = ap.parse_args() + + out = Path(args.out_dir) + out.mkdir(parents=True, exist_ok=True) + + df = pd.read_csv(args.joined_csv) + df["frame_gap"] = (df["frame_b"] - df["frame_a"]).abs() + + y_cols = ["direction_score", "gain_score", "cycle_error_mean"] + rows = [] + for y in y_cols: + rows.append({ + "y": y, + "n": int(len(df)), + "corr_cos_y_pearson": corr(df, "coeff_cos_ab", y, "pearson"), + "corr_cos_y_spearman": corr(df, "coeff_cos_ab", y, "spearman"), + "corr_framegap_y_pearson": corr(df, "frame_gap", y, "pearson"), + "corr_framegap_y_spearman": corr(df, "frame_gap", y, "spearman"), + "corr_cos_framegap_pearson": corr(df, "coeff_cos_ab", "frame_gap", "pearson"), + "corr_cos_framegap_spearman": corr(df, "coeff_cos_ab", "frame_gap", "spearman"), + "partial_cos_y_control_target": partial_corr(df, "coeff_cos_ab", y, ["target_pair_rmsd"], "pearson"), + "partial_cos_y_control_framegap": partial_corr(df, "coeff_cos_ab", y, ["frame_gap"], "pearson"), + "partial_cos_y_control_both": partial_corr(df, "coeff_cos_ab", y, ["target_pair_rmsd", "frame_gap"], "pearson"), + "partial_cos_y_control_both_spearman": partial_corr(df, "coeff_cos_ab", y, ["target_pair_rmsd", "frame_gap"], "spearman"), + "loo_pearson_min": leave_one_out(df, "coeff_cos_ab", y, "pearson")["min"], + "loo_pearson_max": leave_one_out(df, "coeff_cos_ab", y, "pearson")["max"], + }) + + full = pd.DataFrame(rows) + + no_qj0 = df[df["pdb_name"] != "6qj0A"].copy() + outlier_rows = [] + for y in y_cols: + outlier_rows.append({ + "removed": "6qj0A", + "y": y, + "n": int(len(no_qj0)), + "corr_cos_y_pearson": corr(no_qj0, "coeff_cos_ab", y, "pearson"), + "corr_cos_y_spearman": corr(no_qj0, "coeff_cos_ab", y, "spearman"), + "partial_cos_y_control_both": partial_corr(no_qj0, "coeff_cos_ab", y, ["target_pair_rmsd", "frame_gap"], "pearson"), + "partial_cos_y_control_both_spearman": partial_corr(no_qj0, "coeff_cos_ab", y, ["target_pair_rmsd", "frame_gap"], "spearman"), + }) + no_qj0_df = pd.DataFrame(outlier_rows) + + bins = pd.cut( + df["frame_gap"], + bins=[-1, 200, 400, 600, 800, 2000], + labels=["<=200", "201-400", "401-600", "601-800", ">800"], + ) + gap_bins = df.groupby(bins, observed=False).agg( + n=("pdb_name", "count"), + coeff_cos_mean=("coeff_cos_ab", "mean"), + target_pair_rmsd_mean=("target_pair_rmsd", "mean"), + direction_score_mean=("direction_score", "mean"), + gain_score_mean=("gain_score", "mean"), + cycle_error_mean=("cycle_error_mean", "mean"), + ).reset_index().rename(columns={"frame_gap": "frame_gap_bin"}) + + scatter = df[[ + "pdb_name", "frame_a", "frame_b", "frame_gap", + "coeff_cos_ab", "target_pair_rmsd", + "direction_score", "gain_score", "cycle_error_mean", + "generated_pair_rmsd", + ]].sort_values("coeff_cos_ab") + + summary = { + "n": int(len(df)), + "n_without_6qj0A": int(len(no_qj0)), + "frame_gap_values": sorted([int(x) for x in df["frame_gap"].unique()]), + } + + full.to_csv(out / "frame_gap_confound_full.csv", index=False) + no_qj0_df.to_csv(out / "frame_gap_confound_without_6qj0A.csv", index=False) + gap_bins.to_csv(out / "frame_gap_bins.csv", index=False) + scatter.to_csv(out / "frame_gap_scatter.csv", index=False) + (out / "frame_gap_confound_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") + + print("===== summary =====") + print(json.dumps(summary, indent=2)) + print("\n===== full correlations =====") + print(full.to_string(index=False)) + print("\n===== without 6qj0A =====") + print(no_qj0_df.to_string(index=False)) + print("\n===== frame gap bins =====") + print(gap_bins.to_string(index=False)) + print("\nSaved:", out) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/audit_sign_loss_confound.py b/bbflow_base/scripts/audit_sign_loss_confound.py new file mode 100644 index 0000000000000000000000000000000000000000..09e6aa8c2bf8b1a47c7d98b20458158f945f178e --- /dev/null +++ b/bbflow_base/scripts/audit_sign_loss_confound.py @@ -0,0 +1,244 @@ +from pathlib import Path +import argparse +import json +import math +import numpy as np +import pandas as pd + + +def clean_xy(df, x, y): + z = df[[x, y]].replace([np.inf, -np.inf], np.nan).dropna() + return z[x].to_numpy(float), z[y].to_numpy(float) + + +def pearson_np(x, y): + if len(x) < 3: + return float("nan") + if np.std(x) == 0 or np.std(y) == 0: + return float("nan") + return float(np.corrcoef(x, y)[0, 1]) + + +def rankdata(a): + s = pd.Series(a) + return s.rank(method="average").to_numpy(float) + + +def corr(df, x, y, method): + xx, yy = clean_xy(df, x, y) + if method == "spearman": + xx, yy = rankdata(xx), rankdata(yy) + return pearson_np(xx, yy) + + +def residualize(y, x): + y = np.asarray(y, float) + x = np.asarray(x, float) + X = np.stack([np.ones_like(x), x], axis=1) + beta, *_ = np.linalg.lstsq(X, y, rcond=None) + return y - X @ beta + + +def partial_corr(df, x, y, control, method): + cols = [x, y, control] + z = df[cols].replace([np.inf, -np.inf], np.nan).dropna() + if len(z) < 4: + return float("nan") + xx = z[x].to_numpy(float) + yy = z[y].to_numpy(float) + cc = z[control].to_numpy(float) + if method == "spearman": + xx, yy, cc = rankdata(xx), rankdata(yy), rankdata(cc) + rx = residualize(xx, cc) + ry = residualize(yy, cc) + return pearson_np(rx, ry) + + +def permutation_pvalue(df, x, y, method, n_perm=20000, seed=20260712): + z = df[[x, y]].replace([np.inf, -np.inf], np.nan).dropna() + if len(z) < 3: + return float("nan") + xx = z[x].to_numpy(float) + yy = z[y].to_numpy(float) + if method == "spearman": + xx, yy = rankdata(xx), rankdata(yy) + observed = abs(pearson_np(xx, yy)) + if not np.isfinite(observed): + return float("nan") + rng = np.random.default_rng(seed) + count = 0 + for _ in range(n_perm): + yp = rng.permutation(yy) + if abs(pearson_np(xx, yp)) >= observed: + count += 1 + return float((count + 1) / (n_perm + 1)) + + +def leave_one_out(df, x, y, method): + vals = [] + for i in range(len(df)): + sub = df.drop(df.index[i]) + vals.append(corr(sub, x, y, method)) + vals = np.array(vals, dtype=float) + vals = vals[np.isfinite(vals)] + if len(vals) == 0: + return { + "min": float("nan"), + "max": float("nan"), + "mean": float("nan"), + "median": float("nan"), + } + return { + "min": float(vals.min()), + "max": float(vals.max()), + "mean": float(vals.mean()), + "median": float(np.median(vals)), + } + + +def summarize_series(s): + a = pd.Series(s).replace([np.inf, -np.inf], np.nan).dropna().to_numpy(float) + if len(a) == 0: + return {} + return { + "n": int(len(a)), + "mean": float(np.mean(a)), + "median": float(np.median(a)), + "min": float(np.min(a)), + "max": float(np.max(a)), + "q25": float(np.quantile(a, 0.25)), + "q75": float(np.quantile(a, 0.75)), + } + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--joined_csv", required=True) + ap.add_argument("--out_dir", required=True) + args = ap.parse_args() + + joined_csv = Path(args.joined_csv) + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + df = pd.read_csv(joined_csv) + + required = ["coeff_cos_ab", "target_pair_rmsd", "direction_score", "gain_score", "cycle_error_mean"] + missing = [c for c in required if c not in df.columns] + if missing: + raise ValueError(f"Missing required columns: {missing}. Existing columns: {df.columns.tolist()}") + + pairs = [ + ("coeff_cos_ab", "direction_score"), + ("coeff_cos_ab", "gain_score"), + ("coeff_cos_ab", "cycle_error_mean"), + ("coeff_cos_ab", "target_pair_rmsd"), + ("target_pair_rmsd", "direction_score"), + ("target_pair_rmsd", "gain_score"), + ("target_pair_rmsd", "cycle_error_mean"), + ] + + rows = [] + for x, y in pairs: + rows.append({ + "x": x, + "y": y, + "n": int(df[[x, y]].replace([np.inf, -np.inf], np.nan).dropna().shape[0]), + "pearson": corr(df, x, y, "pearson"), + "pearson_perm_p": permutation_pvalue(df, x, y, "pearson"), + "spearman": corr(df, x, y, "spearman"), + "spearman_perm_p": permutation_pvalue(df, x, y, "spearman"), + "loo_pearson_min": leave_one_out(df, x, y, "pearson")["min"], + "loo_pearson_max": leave_one_out(df, x, y, "pearson")["max"], + "loo_spearman_min": leave_one_out(df, x, y, "spearman")["min"], + "loo_spearman_max": leave_one_out(df, x, y, "spearman")["max"], + }) + corr_df = pd.DataFrame(rows) + + partial_rows = [] + for y in ["direction_score", "gain_score", "cycle_error_mean"]: + partial_rows.append({ + "x": "coeff_cos_ab", + "y": y, + "control": "target_pair_rmsd", + "partial_pearson": partial_corr(df, "coeff_cos_ab", y, "target_pair_rmsd", "pearson"), + "partial_spearman": partial_corr(df, "coeff_cos_ab", y, "target_pair_rmsd", "spearman"), + }) + partial_df = pd.DataFrame(partial_rows) + + bin_df = pd.DataFrame() + bins = pd.cut( + df["coeff_cos_ab"], + bins=[-1.01, -0.9, -0.75, -0.5, 0.0, 0.5, 1.01], + labels=["cos<-0.9", "-0.9<=cos<-0.75", "-0.75<=cos<-0.5", "-0.5<=cos<0", "0<=cos<0.5", "cos>=0.5"], + ) + bin_df = df.groupby(bins, observed=False).agg( + n=("coeff_cos_ab", "count"), + target_pair_rmsd_mean=("target_pair_rmsd", "mean"), + target_pair_rmsd_median=("target_pair_rmsd", "median"), + direction_score_mean=("direction_score", "mean"), + direction_score_median=("direction_score", "median"), + gain_score_mean=("gain_score", "mean"), + gain_score_median=("gain_score", "median"), + cycle_error_mean=("cycle_error_mean", "mean"), + ).reset_index().rename(columns={"coeff_cos_ab": "coeff_cos_bin"}) + + distribution = { + "n": int(len(df)), + "coeff_cos_ab": summarize_series(df["coeff_cos_ab"]), + "target_pair_rmsd": summarize_series(df["target_pair_rmsd"]), + "direction_score": summarize_series(df["direction_score"]), + "gain_score": summarize_series(df["gain_score"]), + "cycle_error_mean": summarize_series(df["cycle_error_mean"]), + } + if "coeff_signflip_frac_ab" in df.columns: + distribution["coeff_signflip_frac_ab"] = summarize_series(df["coeff_signflip_frac_ab"]) + + counts = { + "n_total": int(len(df)), + "n_cos_lt_minus_0p9": int((df["coeff_cos_ab"] < -0.9).sum()), + "n_cos_lt_minus_0p75": int((df["coeff_cos_ab"] < -0.75).sum()), + "n_cos_lt_minus_0p5": int((df["coeff_cos_ab"] < -0.5).sum()), + "n_cos_ge_0p5": int((df["coeff_cos_ab"] >= 0.5).sum()), + } + + scatter_cols = [ + "pdb_name", + "frame_a", + "frame_b", + "coeff_cos_ab", + "target_pair_rmsd", + "direction_score", + "gain_score", + "cycle_error_mean", + "generated_pair_rmsd", + ] + if "coeff_signflip_frac_ab" in df.columns: + scatter_cols.append("coeff_signflip_frac_ab") + scatter_cols = [c for c in scatter_cols if c in df.columns] + scatter_df = df[scatter_cols].sort_values("coeff_cos_ab") + + corr_df.to_csv(out_dir / "confound_correlations.csv", index=False) + partial_df.to_csv(out_dir / "confound_partial_correlations.csv", index=False) + bin_df.to_csv(out_dir / "confound_coeff_cos_bins.csv", index=False) + scatter_df.to_csv(out_dir / "confound_scatter_points.csv", index=False) + (out_dir / "confound_distribution.json").write_text(json.dumps(distribution, indent=2), encoding="utf-8") + (out_dir / "confound_counts.json").write_text(json.dumps(counts, indent=2), encoding="utf-8") + + print("===== counts =====") + print(json.dumps(counts, indent=2)) + print("\n===== distributions =====") + print(json.dumps(distribution, indent=2)) + print("\n===== correlations and permutation p-values =====") + print(corr_df.to_string(index=False)) + print("\n===== partial correlations controlling target_pair_rmsd =====") + print(partial_df.to_string(index=False)) + print("\n===== coeff cosine bins =====") + print(bin_df.to_string(index=False)) + print("\n===== scatter points sorted by coeff_cos_ab =====") + print(scatter_df.to_string(index=False)) + print("\nSaved:", out_dir) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/audit_sign_loss_vs_response.py b/bbflow_base/scripts/audit_sign_loss_vs_response.py new file mode 100644 index 0000000000000000000000000000000000000000..d28ec9050bea9e9dffe41b5bf9ed165b2ae44dc9 --- /dev/null +++ b/bbflow_base/scripts/audit_sign_loss_vs_response.py @@ -0,0 +1,125 @@ +from pathlib import Path +import argparse +import json +import numpy as np +import pandas as pd + + +def corr(x, y, method): + valid = pd.DataFrame({"x": x, "y": y}).replace([np.inf, -np.inf], np.nan).dropna() + if len(valid) < 3: + return float("nan") + if valid["x"].nunique() < 2 or valid["y"].nunique() < 2: + return float("nan") + return float(valid["x"].corr(valid["y"], method=method)) + + +def find_audit_csv(audit_dir: Path): + candidates = [] + for p in audit_dir.glob("*.csv"): + try: + cols = set(pd.read_csv(p, nrows=2).columns) + except Exception: + continue + score = 0 + for c in ["coeff_cos_ab", "coeff_signflip_frac_ab", "pdb_name", "frame_a", "frame_b"]: + if c in cols: + score += 1 + if score >= 2: + candidates.append((score, p)) + if not candidates: + raise FileNotFoundError(f"No usable audit csv found in {audit_dir}") + return sorted(candidates, reverse=True)[0][1] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--audit_dir", required=True) + ap.add_argument("--matched_csv", required=True) + ap.add_argument("--out_dir", required=True) + args = ap.parse_args() + + audit_dir = Path(args.audit_dir) + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + audit_csv = find_audit_csv(audit_dir) + audit = pd.read_csv(audit_csv) + matched = pd.read_csv(args.matched_csv) + + rename = {} + if "name" in audit.columns and "pdb_name" not in audit.columns: + rename["name"] = "pdb_name" + audit = audit.rename(columns=rename) + + join_cols = [c for c in ["pdb_name", "frame_a", "frame_b"] if c in audit.columns and c in matched.columns] + if "pdb_name" not in join_cols: + raise ValueError(f"Cannot join: audit columns={audit.columns.tolist()} matched columns={matched.columns.tolist()}") + + merged = matched.merge(audit, on=join_cols, how="inner", suffixes=("", "_audit")) + if len(merged) == 0: + raise ValueError("Join produced zero rows.") + + x_cols = [c for c in ["coeff_cos_ab", "coeff_signflip_frac_ab"] if c in merged.columns] + y_cols = [ + "direction_score", + "gain_score", + "cycle_error_mean", + "generated_pair_rmsd", + "coeff_direction_score", + "coeff_gain_score", + ] + y_cols = [c for c in y_cols if c in merged.columns] + + rows = [] + for x in x_cols: + for y in y_cols: + rows.append({ + "x": x, + "y": y, + "n": int(merged[[x, y]].replace([np.inf, -np.inf], np.nan).dropna().shape[0]), + "pearson": corr(merged[x], merged[y], "pearson"), + "spearman": corr(merged[x], merged[y], "spearman"), + }) + corr_df = pd.DataFrame(rows) + + if "coeff_cos_ab" in merged.columns: + bins = pd.cut( + merged["coeff_cos_ab"], + bins=[-1.01, -0.5, 0.0, 0.5, 1.01], + labels=["cos<-0.5", "-0.5<=cos<0", "0<=cos<0.5", "cos>=0.5"], + ) + bin_df = merged.groupby(bins, observed=False).agg( + n=("pdb_name", "count"), + direction_score_mean=("direction_score", "mean"), + gain_score_mean=("gain_score", "mean"), + cycle_error_mean=("cycle_error_mean", "mean"), + generated_pair_rmsd_mean=("generated_pair_rmsd", "mean"), + coeff_signflip_frac_mean=("coeff_signflip_frac_ab", "mean") if "coeff_signflip_frac_ab" in merged.columns else ("pdb_name", "count"), + ).reset_index().rename(columns={"coeff_cos_ab": "coeff_cos_bin"}) + else: + bin_df = pd.DataFrame() + + summary = { + "audit_csv": str(audit_csv), + "n_joined": int(len(merged)), + "audit_columns": audit.columns.tolist(), + "matched_columns": matched.columns.tolist(), + } + + merged.to_csv(out_dir / "sign_loss_response_joined.csv", index=False) + corr_df.to_csv(out_dir / "sign_loss_response_correlations.csv", index=False) + bin_df.to_csv(out_dir / "sign_loss_response_bins.csv", index=False) + (out_dir / "sign_loss_response_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") + + print("===== joined summary =====") + print(json.dumps(summary, indent=2)) + print("\n===== correlations =====") + print(corr_df.to_string(index=False)) + print("\n===== coeff cosine bins =====") + print(bin_df.to_string(index=False)) + print("\nSaved:", out_dir) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/canonical_paired_eval.py b/bbflow_base/scripts/canonical_paired_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..cc583638bb37821657bb46322ed5ad98143042b5 --- /dev/null +++ b/bbflow_base/scripts/canonical_paired_eval.py @@ -0,0 +1,249 @@ +"""Reconcile the metric, then test the headline estimand with the right statistic. + +Why this exists +--------------- +Two problems have to be settled before any claim is made. + +**The numbers do not agree.** Three values exist for quantities that should match: the +published baseline 1.34, a paired script's baseline 1.2890, and 1.2236 versus 1.2396 for +the same run measured two different ways. Until that is explained, the very small paired +standard error is not known to describe the same thing the headline reports. + +A likely cause is visible in the canonical implementation: + + RAND1 = np.random.randint(0, ref_traj.n_frames, model_traj.n_frames) + +The reference cloud is drawn at random and **unseeded**, so two runs of the official +scorer on identical files return different PCA-W2. This measures that noise floor +directly, by repeating the draw, before attributing any difference to something real. + +**The wrong estimand was tested.** A paired comparison showed mean per-protein PCA-W2 +lower by 0.132 at p = 0.0006. But the reported headline is the *median across proteins*, +which moves only 1.2890 -> 1.2498, about 0.039. A handful of proteins with large gains can +make the paired mean overwhelmingly significant while barely moving the median. The +p-value for the mean cannot defend a median headline, and 0.039 still sits inside the +0.06-0.08 selection band established for this cohort. + +So the headline estimand is tested here on its own terms: a paired bootstrap that +resamples proteins jointly, recomputes both medians, and takes their difference. The mean +difference and the median paired difference are reported beside it, clearly separated, +because they are different claims. + +What this does not fix +---------------------- +Nothing here removes the selection objection. These 82 proteins have already informed +15-30 comparisons and the design of this analysis. A tighter interval on the same cohort +quantifies uncertainty; it cannot undo cohort reuse. Only a genuinely untouched cohort can +do that, and this script's `--emit_provenance` output is what a later frozen comparison +would be built on. +""" + +import argparse +import hashlib +import os + +import numpy as np + + +def canonical_pca_w2(ref_xyz, model_xyz, n_atoms, rng, n_draws): + """PCA-W2 exactly as `analyse_bbflow` computes it, repeated over reference draws. + + Uses the project's own `_get_pca` and `_pca_w2` rather than a reimplementation: the + PCA is fitted on the full reference trajectory, the model is projected with it, and + the reference is subsampled to the model's frame count with replacement. + """ + from bbflow.analysis.analyse_bbflow import _get_pca, _pca_w2 + ref_pca, ref_coords = _get_pca(ref_xyz) + model_coords = ref_pca.transform(model_xyz.reshape(model_xyz.shape[0], -1)) + vals = [] + for _ in range(n_draws): + idx = rng.integers(0, ref_coords.shape[0], model_xyz.shape[0]) + vals.append(float(_pca_w2(ref_coords[idx], model_coords, n_atoms, K=2)["pca_w2"])) + return np.array(vals) + + +def file_fingerprint(path): + st = os.stat(path) + h = hashlib.sha256() + with open(path, "rb") as f: + h.update(f.read(1 << 20)) # first MiB is enough to catch a different file + return f"{st.st_size}:{h.hexdigest()[:12]}" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--md_dir", required=True) + ap.add_argument("--ensemble_dirs", nargs="+", required=True) + ap.add_argument("--names", nargs="+", required=True) + ap.add_argument("--reference", default="", + help="name of the run every other run is compared against") + ap.add_argument("--n_draws", type=int, default=20, + help="reference draws per protein; their spread is the metric's own " + "noise floor, which has to be known before any difference is " + "called real") + ap.add_argument("--require_segments", type=int, default=3) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out_csv", default="") + ap.add_argument("--compare_csv", default="", + help="an existing per-protein CSV with columns name,run,pca_w2 to " + "localise where previously reported numbers disagree") + args = ap.parse_args() + + if len(args.names) != len(args.ensemble_dirs): + raise SystemExit("--names must match --ensemble_dirs in length") + ref_name = args.reference or args.names[0] + if ref_name not in args.names: + raise SystemExit(f"--reference {ref_name} is not one of --names") + + from centroid_reliability import load_generated, load_reference, stable_seed + import pandas as pd + + cohort = sorted(set.intersection(*[ + {d for d in os.listdir(e) if os.path.isdir(os.path.join(e, d))} + for e in args.ensemble_dirs])) + print(f"cohort common to all runs: {len(cohort)} proteins", flush=True) + for nm, e in zip(args.names, args.ensemble_dirs): + own = len([d for d in os.listdir(e) if os.path.isdir(os.path.join(e, d))]) + print(f" {nm:<16} {own:>4} protein directories" + f"{'' if own == len(cohort) else ' <- NOT the common cohort'}") + + rows, failures = [], [] + for i, prot in enumerate(cohort): + try: + ref, md_flat, n_atoms, _ = load_reference(prot, args.md_dir, + args.require_segments) + except Exception as exc: # noqa: BLE001 + failures.append(f"{prot}: {exc}") + continue + ref_xyz = md_flat.reshape(len(md_flat), n_atoms, 3) + for nm, ens in zip(args.names, args.ensemble_dirs): + try: + gen = load_generated(prot, ens, ref) + path = os.path.join(ens, prot, "sampled_conformations.pdb") + v = canonical_pca_w2(ref_xyz, gen.reshape(len(gen), n_atoms, 3), n_atoms, + np.random.default_rng(stable_seed(prot, args.seed)), + args.n_draws) + rows.append({"name": prot, "run": nm, "pca_w2": float(v.mean()), + "pca_w2_draw_sd": float(v.std(ddof=1)), + "pca_w2_first_draw": float(v[0]), + "n_gen": len(gen), "n_md": len(md_flat), "n_res": n_atoms, + "file": file_fingerprint(path)}) + except Exception as exc: # noqa: BLE001 + failures.append(f"{prot}/{nm}: {exc}") + if (i + 1) % 10 == 0: + print(f" {i+1}/{len(cohort)}", flush=True) + + if failures: + print(f"\n{len(failures)} failures; first 5:") + for f in failures[:5]: + print(f" {f}") + + df = pd.DataFrame(rows) + if df.empty: + raise SystemExit("nothing measured") + counts = df.groupby("name")["run"].nunique() + shared = set(counts[counts == len(args.names)].index) + df = df[df.name.isin(shared)] + if args.out_csv: + df.to_csv(args.out_csv, index=False) + print(f"\nper-protein values -> {args.out_csv}") + + piv = df.pivot(index="name", columns="run", values="pca_w2") + + print(f"\n{'='*76}\n 1. the metric's own noise floor\n{'='*76}") + print(f" reference draws per protein: {args.n_draws}. The canonical scorer draws the") + print(f" reference once, unseeded, so a single official run lands somewhere in this") + print(f" spread. Any difference smaller than it is not a real difference.") + print(f"\n {'run':<16}{'median PCA-W2':>16}{'per-protein draw SD':>22}" + f"{'SD of the median':>18}") + for nm in args.names: + s = df[df.run == nm] + # spread of the aggregate median induced by redrawing the reference + med_sd = float(s.pca_w2_draw_sd.median() / np.sqrt(len(s))) + print(f" {nm:<16}{s.pca_w2.median():>16.4f}{s.pca_w2_draw_sd.median():>22.4f}" + f"{med_sd:>18.4f}") + print(f"\n a single unseeded run of one protein moves by about " + f"{df.pca_w2_draw_sd.median():.4f};") + print(f" the aggregate median moves far less, so draw noise explains per-protein") + print(f" disagreements much more readily than headline disagreements") + + print(f"\n{'='*76}\n 2. the headline estimand: difference of aggregate medians\n{'='*76}") + print(f" reference run: {ref_name}") + rng = np.random.default_rng(0) + n = len(piv) + idx = rng.integers(0, n, (4000, n)) + print(f"\n {'run':<16}{'median':>10}{'d(median)':>12}{'paired bootstrap 95%':>26}" + f"{'wins':>8}") + base_col = piv[ref_name].to_numpy() + for nm in args.names: + if nm == ref_name: + print(f" {nm:<16}{piv[nm].median():>10.4f}{'-':>12}{'-':>26}{'-':>8}") + continue + col = piv[nm].to_numpy() + d_med = float(np.median(col) - np.median(base_col)) + # resample proteins jointly, recompute BOTH medians, difference them + boot = np.median(col[idx], axis=1) - np.median(base_col[idx], axis=1) + lo, hi = np.percentile(boot, [2.5, 97.5]) + wins = int((col < base_col).sum()) + print(f" {nm:<16}{piv[nm].median():>10.4f}{d_med:>12.4f}" + f"{f'[{lo:+.4f}, {hi:+.4f}]':>26}{wins:>4}/{n}") + + print(f"\n{'='*76}\n 3. the paired estimands, which are DIFFERENT claims\n{'='*76}") + print(f" {'run':<16}{'mean diff':>12}{'mean 95%':>24}{'median diff':>14}" + f"{'median 95%':>24}") + for nm in args.names: + if nm == ref_name: + continue + d = piv[nm].to_numpy() - base_col + bm = d[idx].mean(axis=1) + bmd = np.median(d[idx], axis=1) + lo_m, hi_m = np.percentile(bm, [2.5, 97.5]) + lo_d, hi_d = np.percentile(bmd, [2.5, 97.5]) + print(f" {nm:<16}{d.mean():>12.4f}{f'[{lo_m:+.4f}, {hi_m:+.4f}]':>24}" + f"{np.median(d):>14.4f}{f'[{lo_d:+.4f}, {hi_d:+.4f}]':>24}") + print("\n 'mean diff' is what the earlier paired test reported. It is NOT the") + print(" headline: a few proteins improving a lot can make it large and highly") + print(" significant while the aggregate median in section 2 barely moves. Quote") + print(" section 2 against the published table, and section 3 only as the") + print(" per-protein claim it actually is.") + + if args.compare_csv: + print(f"\n{'='*76}\n 4. where the previously reported numbers disagree\n{'='*76}") + old = pd.read_csv(args.compare_csv) + need = {"name", "run", "pca_w2"} + if not need <= set(old.columns): + print(f" {args.compare_csv} lacks {need - set(old.columns)}; skipped") + else: + for nm in args.names: + a = df[df.run == nm].set_index("name")["pca_w2"] + b = old[old.run == nm].set_index("name")["pca_w2"] + if b.empty: + continue + common = a.index.intersection(b.index) + only_new, only_old = set(a.index) - set(b.index), set(b.index) - set(a.index) + d = (a.loc[common] - b.loc[common]) + print(f"\n {nm}: {len(common)} shared, {len(only_new)} only here, " + f"{len(only_old)} only there") + print(f" median difference {d.median():+.4f}, " + f"largest |difference| {d.abs().max():.4f} on {d.abs().idxmax()}") + print(f" aggregate medians: here {a.median():.4f}, " + f"there {b.median():.4f}") + if len(only_new) or len(only_old): + print(f" protein sets differ -- that alone can move an aggregate " + f"median and must be resolved first") + + print(f"\n{'='*76}\n what this does and does not settle\n{'='*76}") + print(" Settles: whether the disagreeing numbers are draw noise, a different protein") + print(" set, or different files (the fingerprints in the CSV identify the last), and") + print(" what the headline median difference actually is with an interval built for") + print(" that estimand rather than borrowed from the mean.") + print() + print(" Does not settle: selection. These 82 proteins have already informed 15-30") + print(" comparisons and this analysis was designed while looking at them. An") + print(" interval computed here is conditional on that history; a median gain inside") + print(" the 0.06-0.08 band is not evidence no matter how tight the interval is.") + print(" Only an untouched cohort settles that.") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/centroid_reliability.py b/bbflow_base/scripts/centroid_reliability.py new file mode 100644 index 0000000000000000000000000000000000000000..2f9a9da1731a8b08b8fda267bca0284f92369043 --- /dev/null +++ b/bbflow_base/scripts/centroid_reliability.py @@ -0,0 +1,858 @@ +"""Is the reference centroid a stable target, or an artefact of a finite trajectory window? + +An oracle experiment showed that correcting the generated ensemble's mean in the scored +2-D plane recovers 0.34-0.53 Angstrom of PCA-W2, two to five times what correcting the +covariance recovers. That correction used the test protein's own MD. Before anything is +built on it, the target has to be shown to be a property of the protein rather than of the +window it was estimated in. + +Why almost no transport is computed +----------------------------------- +The metric is a true empirical W2: `analyse_bbflow._get_wasserstein` squares the distance +matrix, assigns, means, takes the root, and asserts the matrix is square. So the mean +separates exactly. For a fixed pairing the squared cost splits into a mean term plus a +centred term, the mean term does not depend on the pairing, so the optimal pairing is the +same for the centred clouds and + + W2^2(G, R) = ||mu_G - mu_R||^2 + C, C = W2^2(G - mu_G, R - mu_R) + +Translating `G` moves only the first term. One transport per block pair gives `C`, and +every arm, every correction strength, and the random-direction control are then closed +form. `--verify` checks this against transport actually computed on a shifted cloud. + +The two results +--------------- +**Primary**, at the production cloud size: a centroid estimated on one whole trajectory +segment, applied, and scored against a draw from a different segment. This is the estimand +the question is about and the only row a threshold is applied to. + +**Diagnostic ladder**, every row at one common cloud size, one common number of +centroid-estimation frames, and one common reference support, so the rows differ in +temporal separation and nothing else. The support matters as much as the rest: a 100-frame +sub-block and a 1001-frame segment drawn to the same cloud size have very different +duplicate rates, and `C` sits inside every square root. + + no separation a random disjoint subset of the scored block itself + within L a contiguous gap-separated sub-block, short lag + adjacent the other half of the same segment, both directions, medium lag + between a different segment, long lag + +`retention` is the fraction of the no-separation gain that survives at each lag. It is +explanatory only. **The gate is the absolute transferred gain**, because retention of 0.30 +against a 0.40 Angstrom achievable gain is still 0.12 Angstrom, and because a ratio is +unstable when its denominator is small. + +Estimand hazards this script tries not to fall into +--------------------------------------------------- + The oracle never uses the frames being scored. Taking its centroid in sample lets it + chase the particular draw, which inflates the denominator and depresses retention. + + Transferred and oracle centroids are estimated from the *same number* of frames. The + distant block is longer than the scored block's disjoint remainder, and leaving that + unequal hands the transferred arm an advantage that has nothing to do with lag. + + The scored draw is taken with replacement from a disjoint pool, matching what + `analyse_bbflow` does (`np.random.randint`), while keeping the estimation frames out. + + The no-separation control draws its transferred estimate from a *third* disjoint pool. + Taking it from the whole scored block would let it overlap the frames being scored + while the oracle cannot, which handicaps the oracle instead of controlling anything. + + The random-direction control is the expectation of the W2, `E[sqrt(C + m)]`, by 64-point + angular quadrature. Using `sqrt(C + E[m])` instead is an RMS over directions, is larger + by Jensen, and makes "beats random" too easy. + + The primary arm is the one place estimation sizes are deliberately *not* matched: its + estimand is the best correction the whole of segment A affords, and cutting A to the + oracle's precision would discard half the segment and could manufacture a false + negative. Retention for the primary is therefore not reported; the ladder's + "different segment" row is the matched-size version. + +Both between-segment arms are always computed. In one, the model-side centroid the +correction subtracts is the scored cloud's own mean, so the correction sets the shifted +centroid exactly and cancels the realized Monte Carlo error of that draw. That is fine for +an inference-time procedure that recentres every cloud, and it is not evidence about a +learned objective, which can move a population mean but cannot know one draw's error. In +the other the model-side centroid comes from a disjoint half of the generated frames, +which necessarily halves the scored cloud, so **it gets no verdict**: its Angstroms are +not the metric the threshold was set on. It does gate the verdict qualitatively -- a +primary pass whose held-out counterpart collapses is reported as unresolved, because the +ceiling would then be partly the leak. + +What a pass would and would not mean +------------------------------------ +The transferred gain is a ceiling. It says a centroid estimated somewhere else is worth +that much, not that anything can predict one. A pass justifies running the MD-free +prediction test and nothing more. The fractional-strength rows exist to make the +predictor-efficiency assumption explicit before that test rather than after it. + +Stability is also not enough on its own: these PCA coordinates carry an arbitrary sign and +an arbitrary rotation inside a near-degenerate leading pair, so the shift is not itself a +cross-protein prediction target. A deployable predictor would emit a structural correction +in a deterministic frame, projected only for evaluation. + +Note also that the pooled PCA axes here come from the held-out protein's full MD. That is +correct for evaluating the published metric and impossible for a deployable method. +""" + +import argparse +import hashlib +import os + +import numpy as np +from scipy.optimize import linear_sum_assignment + +VERIFY_TOL = 1e-9 +# Two effective observations is enough to say "almost no information", not enough to +# clear a stability result. Cells below this are masked out of every median. +MIN_ESS_CELL = 5.0 +FRACTIONS = (0.25, 0.5, 0.75) + + +def stable_seed(name, base): + h = hashlib.sha256(name.encode()).digest() + return (base + int.from_bytes(h[:4], "big")) % (2 ** 32) + + +def _ca_signature(traj): + return tuple(f"{a.residue.name}{a.residue.resSeq}{a.residue.chain.index}" + for a in traj.top.atoms) + + +def load_reference(name, md_dir, require_segments): + """The MD side. Everything here depends on the protein alone, never on a checkpoint.""" + import mdtraj + top = os.path.join(md_dir, name, f"{name}.pdb") + if not os.path.exists(top): + raise FileNotFoundError(f"{name}: no reference topology at {top}") + + ref = mdtraj.load(top) + ca = ref.top.select("name CA") + if ca.size < 4: + raise ValueError(f"{name}: {ca.size} CA atoms") + ref = ref.atom_slice(ca) + + md, bounds = None, [] + for i in (1, 2, 3): + p = os.path.join(md_dir, name, f"{name}_R{i}.xtc") + if not os.path.exists(p): + continue + part = mdtraj.load(p, top=top).atom_slice(ca) + lo = 0 if md is None else md.n_frames + md = part if md is None else md + part + bounds.append((lo, md.n_frames)) + if md is None or len(bounds) < require_segments: + raise FileNotFoundError(f"{name}: {len(bounds)} trajectory segments, " + f"{require_segments} required") + md.superpose(ref) + return ref, md.xyz.reshape(md.n_frames, -1).astype(np.float64), ca.size, bounds + + +def load_generated(name, ensemble_dir, ref): + gen = os.path.join(ensemble_dir, name, "sampled_conformations.pdb") + if not os.path.exists(gen): + raise FileNotFoundError(f"{name}: no generated ensemble at {gen}") + import mdtraj + g = mdtraj.load(gen) + g = g.atom_slice(g.top.select("name CA")) + if _ca_signature(g) != _ca_signature(ref): + raise ValueError(f"{name}: CA residue identity differs between reference and ensemble") + g.superpose(ref) + return g.xyz.reshape(g.n_frames, -1).astype(np.float64) + + +def md_context(name, md_dir, k_dim, require_segments): + """Projection basis, segments and autocorrelations, computed once per protein. + + The pooled SVD of a 3003 x 3N trajectory dominates the runtime and depends only on + the MD, so recomputing it per checkpoint would multiply the cost of comparing runs by + the number of runs for no new information. + """ + ref, md_flat, n_atoms, bounds = load_reference(name, md_dir, require_segments) + md_mean_all = md_flat.mean(0, keepdims=True) + _, sing, vh = np.linalg.svd(md_flat - md_mean_all, full_matrices=False) + basis = vh[:k_dim] + md_p = (md_flat - md_mean_all) @ basis.T + segs = [md_p[a:b] for a, b in bounds] + return {"ref": ref, "n_atoms": n_atoms, "n_md": md_flat.shape[0], "bounds": bounds, + "centre": md_mean_all, "basis": basis, "md_p": md_p, "segs": segs, + "acs": [ac for s in segs for ac in autocorr_set(s)], "sing": sing} + + +def w2_sq(a, b, scale): + """Empirical squared W2 in the metric's units. Both clouds must have equal size.""" + if a.shape[0] != b.shape[0]: + raise ValueError(f"unequal cloud sizes {a.shape[0]} vs {b.shape[0]}") + d = np.square(a[:, None] - b[None]).sum(-1) * scale ** 2 + r, c = linear_sum_assignment(d) + return float(d[r, c].mean()) + + +def autocorr_set(x, max_lag_frac=0.5): + """`(tau, rho)` for every projected coordinate, `rho` cut at the Geyer truncation. + + Geyer's initial monotone positive sequence: sum the paired autocovariances + `Gamma_m = rho_2m + rho_2m+1`, stop at the first non-positive pair, then enforce + monotonicity. Truncating on individual `rho_k` stops far too early on noisy MD and + overstates independence, which would let a null be cleared that the data cannot + support. + + Every coordinate is returned rather than only the one with the largest asymptotic + tau, because the slowest coordinate at infinite lag is not necessarily the one with + the least independent content in a 100-frame block, and the block mask wants the + worst of those. Only the projected coordinates are examined, so a slow direction that + is a mixture of PC1 and PC2 can still be understated: these are upper bounds. + """ + n = x.shape[0] + max_lag = max(2, int(n * max_lag_frac)) + out = [] + for j in range(x.shape[1]): + v = x[:, j] - x[:, j].mean() + denom = float(v @ v) + if denom <= 0: + continue + rho = np.array([1.0] + [float(v[:-k] @ v[k:]) / denom for k in range(1, max_lag)]) + gammas, m = [], 0 + while 2 * m + 1 < len(rho): + g = rho[2 * m] + rho[2 * m + 1] + if g <= 0: + break + gammas.append(g) + m += 1 + for i in range(1, len(gammas)): + gammas[i] = min(gammas[i], gammas[i - 1]) + tau = max(2.0 * sum(gammas) - 1.0, 1.0) if gammas else 1.0 + # Cut at the Geyer truncation. Past it the sample autocorrelations are noise + # each carrying a -1/n bias, and summing hundreds of them cancels the signal + # outright: on AR(1) at phi 0.5 the untruncated sum called all 4000 frames + # independent instead of 1333. + out.append((tau, rho[:max(2 * len(gammas), 1)])) + return out or [(1.0, np.array([1.0]))] + + +def ess_block(rho, length): + """Effective sample size of a mean over `length` contiguous frames. + + Uses the finite-length form with the triangular weight, `1 + 2 sum (1 - k/L) rho_k`. + Scaling a whole-segment ESS by `L / segment_length` instead assumes independent + content grows linearly in block length, which is optimistic exactly where it matters, + when the block is near or below the correlation time. + """ + k = np.arange(1, min(length, len(rho))) + if k.size == 0: + return float(length) + tau = 1.0 + 2.0 * float(((1.0 - k / length) * rho[k]).sum()) + return float(length / max(tau, 1.0)) + + +def moving_block_se(x, block, rng, n_boot): + """Centroid standard error under a moving-block bootstrap, correlation preserved.""" + n = x.shape[0] + block = max(1, min(int(block), n)) + n_blocks = int(np.ceil(n / block)) + means = np.empty((n_boot, x.shape[1])) + for b in range(n_boot): + starts = rng.integers(0, n - block + 1, n_blocks) + means[b] = x[np.concatenate([np.arange(s, s + block) for s in starts])[:n]].mean(0) + return float(np.linalg.norm(means.std(0, ddof=1))) + + +def quadrature_directions(k, n_quad, seed=0): + """Deterministic unit directions for the random-shift expectation.""" + if k == 2: + th = np.arange(n_quad) * (2 * np.pi / n_quad) + return np.stack([np.cos(th), np.sin(th)], axis=1) + d = np.random.default_rng(seed).normal(size=(n_quad, k)) + return d / np.linalg.norm(d, axis=1, keepdims=True) + + +def score_pair(gen_score, mu_apply, mu_trn, mu_oracle, ref_score, scale, quad, n_est, + group=0): + """All arms for one block pair, sharing the single transport that gives `C`. + + Sharing `C` is exact, not an approximation, and it is what makes the arms paired. + + When `mu_apply` is a held-out generated centroid, `transferred_alt` repeats the + transferred arm using the scored cloud's own mean instead, on the identical cloud, + reference draw and A centroid. The difference between the two isolates exactly what + sample recentring buys, at matched `n` and perfectly paired -- comparing a 250-sample + in-sample arm with a 125-sample held-out one confounds the leak with the cloud size. + """ + mu_b, mu_gs, s2 = ref_score.mean(0), gen_score.mean(0), scale ** 2 + c = w2_sq(gen_score - mu_gs, ref_score - mu_b, scale) + d = mu_gs - mu_b + + def w2_of(shift): + return float(np.square(d + shift).sum() * s2 + c) ** 0.5 + + step = mu_trn - mu_apply + out = {"uncorrected": w2_of(0.0), "oracle": w2_of(mu_oracle - mu_apply), + "transferred": w2_of(step), "transferred_alt": w2_of(mu_trn - mu_gs), "C": c, + "m_trn": float(np.square(d + step).sum()) * s2, + "n_used": gen_score.shape[0], "n_est": n_est, "group": group} + for a in FRACTIONS: + out[f"frac{int(a*100)}"] = w2_of(a * step) + # The expected W2 under a random direction of the same length as the correct + # correction: E[sqrt(C + m)], by quadrature. sqrt(C + E[m]) is an RMS over + # directions, is larger by Jensen, and would make "beats random" too easy. + r = quad * float(np.linalg.norm(step)) + out["random"] = float(np.mean(np.sqrt(np.square(d + r).sum(1) * s2 + c))) + return out + + +def block_pair(gen_p, est_block, score_block, n_score, scale, rng, gen_holdout, quad, + n_est_cap=None, equalize=True, support_cap=None, full_support=False, + group=0): + """Score one (estimation block, scored block) pair. + + The scored block is split into two disjoint pools: the scored draw is taken with + replacement from one, matching production, and the oracle centroid from the other. + The transferred centroid is subsampled to the same frame count as the oracle's, so + the two arms differ in temporal separation and not in how much MD they saw. + + `n_est_cap` holds that count equal across the *rows* of the ladder as well. Without + it a long-lag row estimates from 501 frames while a short sub-block row estimates + from 50, and the rows differ in estimation precision on top of lag. `equalize` + switches it off for the primary arm, whose estimand is the best correction available + from the whole of `est_block`: matching the oracle's precision there would throw away + half the segment and could manufacture a false negative. + + `est_block=None` is the no-separation control, where the transferred estimate comes + from a third disjoint pool of the scored block. Drawing it from the whole block + instead lets it overlap the scored frames while the oracle cannot, which is not a + control but a handicap on the oracle. + + `full_support` reproduces production's reference sampling: `analyse_bbflow` draws the + reference cloud with replacement from *all* of the segment, so drawing instead from a + disjoint half nearly doubles the duplicate rate, correlates the draws through a + randomly chosen support, and shifts `C` -- which sits inside every square root and so + moves the absolute gain being tested. Under `full_support` the reference is drawn from + the whole block first and the oracle pool is whatever frames the draw did not touch. + `support_cap` does the opposite job for the ladder, holding the support size equal + across rows whose blocks differ in length. + """ + # The generated side first, because it fixes the cloud size the reference must match. + if gen_holdout: + g = rng.permutation(len(gen_p)) + cut = len(gen_p) // 2 + if cut < 2: + return None + pool_gen, mu_apply = gen_p[g[:cut]], gen_p[g[cut:]].mean(0) + else: + pool_gen, mu_apply = gen_p, None + n_use = min(n_score, len(pool_gen)) + gen_score = (pool_gen if n_use == len(pool_gen) + else pool_gen[rng.permutation(len(pool_gen))[:n_use]]) + if mu_apply is None: + mu_apply = gen_score.mean(0) + + if full_support: + ref_idx = rng.integers(0, len(score_block), n_use) + keep = np.ones(len(score_block), bool) + keep[ref_idx] = False + ref_score, pool_oracle, pool_est = score_block[ref_idx], score_block[keep], est_block + else: + idx = rng.permutation(len(score_block)) + if est_block is None: + t = len(score_block) // 3 + if t < 2: + return None + pool_score, pool_oracle, pool_est = (score_block[idx[:t]], + score_block[idx[t:2 * t]], + score_block[idx[2 * t:]]) + else: + half = len(score_block) // 2 + if half < 2: + return None + pool_score, pool_oracle, pool_est = (score_block[idx[:half]], + score_block[idx[half:]], est_block) + if support_cap: + pool_score = pool_score[:support_cap] + ref_score = pool_score[rng.integers(0, len(pool_score), n_use)] + + n_est = (min(len(pool_oracle), len(pool_est), n_est_cap or len(pool_est)) + if equalize else len(pool_est)) + if n_est < 2 or len(pool_oracle) < 2: + return None + mu_oracle = pool_oracle[rng.permutation(len(pool_oracle))[:n_est]].mean(0) + mu_trn = (pool_est.mean(0) if n_est >= len(pool_est) + else pool_est[rng.permutation(len(pool_est))[:n_est]].mean(0)) + return score_pair(gen_score, mu_apply, mu_trn, mu_oracle, ref_score, scale, quad, + n_est, group) + + +def sub_blocks(seg, length, gap): + return [seg[s:s + length] for s in range(0, len(seg) - length + 1, length + gap)] + + +def sampled_pairs(n_blocks, budget, rng): + """All directed pairs, then a uniform sample of `budget` of them. + + Walking the pairs in nested order and stopping at the budget selects only + `block 0 -> everything`, which is one early estimate extrapolated over every lag with + no reverse directions, so a temporal trend reads as a lag effect. + """ + all_pairs = [(p, q) for p in range(n_blocks) for q in range(n_blocks) if p != q] + if len(all_pairs) <= budget: + return all_pairs + sel = rng.permutation(len(all_pairs))[:budget] + return [all_pairs[i] for i in sorted(sel)] + + +ARM_KEYS = ("uncorrected", "oracle", "transferred", "random", + *[f"frac{int(a*100)}" for a in FRACTIONS]) + + +def summarise(row, pairs, tag): + """Average each arm over block pairs, then form gains. + + Averaging then differencing equals differencing then averaging, since every square + root is already taken inside each pair. Retention is a ratio of averaged gains rather + than an average of ratios, so a pair with a near-zero denominator cannot take over. + """ + cols = ("unc", "oracle", "trn", "rnd", "gain_oracle", "gain_trn", "gain_rnd", + "retention", "rms_est_to_ref", "n_pairs", "n_used", "n_est", "gain_trn_mcse", + "gain_trn_alt", "leak", + *[f"gain_frac{int(a*100)}" for a in FRACTIONS]) + if not pairs: + for c in cols: + row[f"{tag}_{c}"] = float("nan") + return + a = {k: float(np.mean([p[k] for p in pairs])) + for k in (*ARM_KEYS, "transferred_alt", "m_trn", "n_used", "n_est")} + row[f"{tag}_unc"] = a["uncorrected"] + row[f"{tag}_oracle"] = a["oracle"] + row[f"{tag}_trn"] = a["transferred"] + row[f"{tag}_rnd"] = a["random"] + row[f"{tag}_gain_oracle"] = a["uncorrected"] - a["oracle"] + row[f"{tag}_gain_trn"] = a["uncorrected"] - a["transferred"] + row[f"{tag}_gain_rnd"] = a["uncorrected"] - a["random"] + for f in FRACTIONS: + row[f"{tag}_gain_frac{int(f*100)}"] = a["uncorrected"] - a[f"frac{int(f*100)}"] + g_o = row[f"{tag}_gain_oracle"] + row[f"{tag}_retention"] = (row[f"{tag}_gain_trn"] / g_o) if g_o > 1e-12 else float("nan") + # Root mean square, not mean: it is the average of the squared terms the identity uses. + row[f"{tag}_rms_est_to_ref"] = a["m_trn"] ** 0.5 + # Paired leak: the same cloud, reference draw and A centroid, corrected once with a + # held-out generated centroid and once with the scored cloud's own mean. Zero unless + # this tag ran with a holdout. + row[f"{tag}_gain_trn_alt"] = a["uncorrected"] - a["transferred_alt"] + row[f"{tag}_leak"] = row[f"{tag}_gain_trn_alt"] - row[f"{tag}_gain_trn"] + # Monte Carlo error of the reference draws only. Pooling the spread over all directed + # pairs instead would fold in real heterogeneity between those pairs, which is signal, + # and would not describe how much a different set of random partitions could move the + # result. + by_group = {} + for p in pairs: + by_group.setdefault(p["group"], []).append(p["uncorrected"] - p["transferred"]) + reps = [np.var(v, ddof=1) for v in by_group.values() if len(v) > 1] + row[f"{tag}_gain_trn_mcse"] = (float(np.mean(reps) / len(pairs)) ** 0.5 + if reps else float("nan")) + row[f"{tag}_n_pairs"] = len(pairs) + row[f"{tag}_n_used"] = a["n_used"] + row[f"{tag}_n_est"] = a["n_est"] + + +def audit_one(name, ctx, gen_flat, k_dim, rng, sub_lens, gap, n_ref_draws, + max_pairs_per_segment, n_boot, n_quad): + n_atoms, bounds, segs = ctx["n_atoms"], ctx["bounds"], ctx["segs"] + md_p, sing, acs = ctx["md_p"], ctx["sing"], ctx["acs"] + n_md, n_gen = ctx["n_md"], gen_flat.shape[0] + scale = 10.0 / n_atoms ** 0.5 # the metric's own units + quad = quadrature_directions(k_dim, n_quad) + gen_p = (gen_flat - ctx["centre"]) @ ctx["basis"].T + seg_len = min(len(s) for s in segs) + + row = {"name": name, "n_res": n_atoms, "n_gen": n_gen, "n_md": n_md, + "n_segments": len(bounds), "seg_len_min": seg_len, + "seg_len_max": max(len(s) for s in segs)} + row["d_gen_to_pool"] = float(np.linalg.norm(gen_p.mean(0) - md_p.mean(0)) * scale) + + # A typical conditional standard error of a 250-sample centroid. Not the realized + # error of this draw, which is unobservable; it gives the typical sampling scale of + # the measured centroid gap, so a gap of the same order is not safely model bias. + boot = np.array([gen_p[rng.integers(0, n_gen, n_gen)].mean(0) for _ in range(n_boot)]) + row["mc_gen_centroid"] = float(np.linalg.norm(boot.std(0, ddof=1)) * scale) + + # Every segment and every projected coordinate, because the mask wants the worst + # finite-length independent content, not the slowest asymptotic one. + tau = max(t for t, _ in acs) + row["tau_segment"] = float(tau) + row["ess_min_segment"] = min(ess_block(r, seg_len) for _, r in acs) + blk = max(1, int(round(tau))) + row["block_len_used"] = blk + row["se_segment_centroid"] = max(moving_block_se(s, blk, rng, n_boot) + for s in segs) * scale + + # The ladder runs at one cloud size and one estimation size, so its rows differ in + # temporal separation and nothing else. The shortest sub-block sets both: it can + # spare only half its frames for the oracle estimate. + ladder_n = max(2, min(n_gen, min(sub_lens) // 2)) if sub_lens else n_gen + ladder_est = max(2, min(sub_lens) // 2) if sub_lens else None + row["ladder_n"], row["ladder_n_est"] = ladder_n, ladder_est or 0 + + def between_pairs(n_score, holdout, cap, equalize=True, full=False, support=None): + out, grp = [], 0 + for i, a in enumerate(segs): + for j, b in enumerate(segs): + if i == j: + continue + grp += 1 + for _ in range(n_ref_draws): + p = block_pair(gen_p, a, b, n_score, scale, rng, holdout, quad, cap, + equalize, support, full, grp) + if p is not None: + out.append(p) + return out + + # Primary: production cloud size drawn production-style from the whole of segment B, + # and the centroid taken from all of segment A, since the estimand is the best + # correction the whole segment affords. Then the same with the generated centroid + # held out, which necessarily halves the cloud. + summarise(row, between_pairs(n_gen, False, None, False, True), "primary") + summarise(row, between_pairs(n_gen, True, None, False, True), "primaryH") + + # Ladder: common cloud size, estimation size, and reference support, so duplicate + # rates and C do not vary with block length alongside the lag. + summarise(row, between_pairs(ladder_n, False, ladder_est, support=ladder_est), + "L_between") + + no_sep = [] + for gi, s in enumerate(segs): + for _ in range(n_ref_draws): + p = block_pair(gen_p, None, s, ladder_n, scale, rng, False, quad, ladder_est, + True, ladder_est, False, gi) + if p is not None: + no_sep.append(p) + summarise(row, no_sep, "L_nosep") + + adj, grp = [], 0 + for s in segs: + h = len(s) // 2 + for est, sc in ((s[:h], s[h:]), (s[h:], s[:h])): # both directions + grp += 1 + for _ in range(n_ref_draws): + p = block_pair(gen_p, est, sc, ladder_n, scale, rng, False, quad, + ladder_est, True, ladder_est, False, grp) + if p is not None: + adj.append(p) + summarise(row, adj, "L_adjacent") + + for L in sub_lens: + pairs = [] + for si, seg in enumerate(segs): + blocks = sub_blocks(seg, L, gap) + sel = sampled_pairs(len(blocks), max_pairs_per_segment, + np.random.default_rng(stable_seed(f"{name}:{L}:{si}", 0))) + for gi, (p_i, q_i) in enumerate(sel): + for _ in range(n_ref_draws): + r = block_pair(gen_p, blocks[p_i], blocks[q_i], ladder_n, + scale, rng, False, quad, ladder_est, True, + ladder_est, False, si * 1000 + gi) + if r is not None: + pairs.append(r) + tag = f"L_within{L}" + summarise(row, pairs, tag) + e = min(ess_block(r, L) for _, r in acs) + row[f"{tag}_ess"] = e + if e < MIN_ESS_CELL: # masked, so it is genuinely not counted anywhere + for c in [c for c in row if c.startswith(f"{tag}_") and not c.endswith("_ess")]: + row[c] = float("nan") + + if len(sing) > k_dim: + l2, l3 = sing[k_dim - 1] ** 2, sing[k_dim] ** 2 + row["pc_relgap"] = float((l2 - l3) / max(l2, 1e-300)) + else: + row["pc_relgap"] = float("nan") + return row + + +def verify_identity(name, ctx, gen_flat, rng): + """Check the closed form against transport actually computed on the shifted cloud.""" + scale = 10.0 / ctx["n_atoms"] ** 0.5 + md_p, bounds = ctx["md_p"], ctx["bounds"] + gen_p = (gen_flat - ctx["centre"]) @ ctx["basis"].T + + a_seg = md_p[bounds[0][0]:bounds[0][1]] + b_seg = md_p[bounds[1][0]:bounds[1][1]] + b = b_seg[rng.integers(0, len(b_seg), gen_p.shape[0])] + mu_a, mu_g, mu_b = a_seg.mean(0), gen_p.mean(0), b.mean(0) + + measured = w2_sq(gen_p + (mu_a - mu_g), b, scale) ** 0.5 + predicted = (float(np.square(mu_a - mu_b).sum()) * scale ** 2 + + w2_sq(gen_p - mu_g, b - mu_b, scale)) ** 0.5 + return {"name": name, "measured": measured, "predicted": predicted} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--md_dir", required=True) + ap.add_argument("--ensemble_dirs", nargs="+", required=True) + ap.add_argument("--names", nargs="*", default=[]) + ap.add_argument("--k", type=int, default=2) + ap.add_argument("--sub_lens", type=int, nargs="*", default=[100, 250, 400]) + ap.add_argument("--gap", type=int, default=50, + help="frames skipped between contiguous sub-blocks") + ap.add_argument("--n_ref_draws", type=int, default=5, + help="scored draws per block pair, so nothing rests on one subset") + ap.add_argument("--max_pairs_per_segment", type=int, default=6) + ap.add_argument("--n_boot", type=int, default=400) + ap.add_argument("--n_quad", type=int, default=64, + help="directions in the random-shift expectation") + ap.add_argument("--verify", type=int, default=3, + help="proteins on which to check the closed form against transport") + ap.add_argument("--min_useful_gain", type=float, default=0.10, + help="Angstrom. 0.10 is the project's prespecified continuation " + "threshold and treats the ceiling as the thing being gated; " + "0.20 corresponds to assuming a predictor captures half of it") + ap.add_argument("--min_attenuation", type=float, default=0.5, + help="fraction of the paired in-sample gain the held-out correction " + "must retain before a pass is allowed to stand") + ap.add_argument("--expect_cohort", type=int, default=82) + ap.add_argument("--expect_n_gen", type=int, default=250) + ap.add_argument("--expect_seg_len", type=int, default=1001) + ap.add_argument("--require_segments", type=int, default=3) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out_csv", default="") + args = ap.parse_args() + + labels = args.names or [os.path.basename(d.rstrip("/")) for d in args.ensemble_dirs] + if len(labels) != len(args.ensemble_dirs): + raise SystemExit("--names must match --ensemble_dirs in length") + if len(set(labels)) != len(labels): + raise SystemExit("run labels must be unique") + + import pandas as pd + guards = [] # any entry suppresses the verdict rather than annotating it + cohort = sorted(set.intersection(*[ + {d for d in os.listdir(e) if os.path.isdir(os.path.join(e, d))} + for e in args.ensemble_dirs])) + print(f"cohort common to all runs: {len(cohort)} proteins", flush=True) + + # Protein-outer, so the pooled SVD and the autocorrelations are paid for once no + # matter how many checkpoints are being compared. + rows, failures, verified = [], {}, 0 + print(f"\ncomparing {len(labels)} runs; the MD projection is computed once per " + f"protein\n", flush=True) + for i, nm in enumerate(cohort): + try: + ctx = md_context(nm, args.md_dir, args.k, args.require_segments) + except Exception as exc: # noqa: BLE001 + for label in labels: + failures.setdefault(label, []).append( + f"{nm}: {type(exc).__name__}: {exc}") + continue + for label, ens in zip(labels, args.ensemble_dirs): + try: + gen_flat = load_generated(nm, ens, ctx["ref"]) + if verified < args.verify and label == labels[0]: + v = verify_identity(nm, ctx, gen_flat, + np.random.default_rng(stable_seed(nm, args.seed))) + rel = abs(v["measured"] - v["predicted"]) / max(abs(v["measured"]), 1e-30) + print(f" identity check {nm}: measured {v['measured']:.6f} " + f"predicted {v['predicted']:.6f} rel {rel:.2e}", flush=True) + if rel > VERIFY_TOL: + raise SystemExit("the closed form does not reproduce transport; " + "the whole design rests on it, so stop here") + verified += 1 + r = audit_one(nm, ctx, gen_flat, args.k, + np.random.default_rng(stable_seed(nm, args.seed)), + args.sub_lens, args.gap, args.n_ref_draws, + args.max_pairs_per_segment, args.n_boot, args.n_quad) + r["run"] = label + r.update({"cfg_seed": args.seed, "cfg_k": args.k, "cfg_gap": args.gap, + "cfg_ref_draws": args.n_ref_draws, "cfg_boot": args.n_boot}) + rows.append(r) + except SystemExit: + raise + except Exception as exc: # noqa: BLE001 + failures.setdefault(label, []).append(f"{nm}: {type(exc).__name__}: {exc}") + if (i + 1) % 10 == 0: + print(f" {i+1}/{len(cohort)} proteins", flush=True) + + if failures: + print("\nfailures:") + for label, msgs in failures.items(): + print(f" [{label}] {len(msgs)}") + for m in msgs[:5]: + print(f" {m}") + + df = pd.DataFrame(rows) + if df.empty: + raise SystemExit("no protein produced a measurement") + counts = df.groupby("name")["run"].nunique() + shared = set(counts[counts == len(labels)].index) + if not shared: + raise SystemExit("no protein succeeded in every run") + df = df[df.name.isin(shared)] + if args.out_csv: + df.to_csv(args.out_csv, index=False) + print(f"\nper-protein values -> {args.out_csv}") + + # Checked after the failures are known, so a cohort that shrank during the run cannot + # slip a verdict through on a selected subset. + if args.expect_cohort and len(shared) != args.expect_cohort: + guards.append(f"analysed {len(shared)} proteins, expected {args.expect_cohort}") + # Both ends, since a minimum of 1001 is also satisfied by [1001, 1002, 1002]. + for field, expect, what in (("n_gen", args.expect_n_gen, "generated samples"), + ("seg_len_min", args.expect_seg_len, "frames in every segment"), + ("seg_len_max", args.expect_seg_len, "frames in every segment")): + if not expect: + continue + bad = int((df[field] != expect).sum()) + if bad: + # A truncated segment changes both the A estimate and B's support, so the + # design is not the one the threshold was set for. + guards.append(f"{bad} rows do not have {expect} {what}") + + def boot_ci(v, n=4000): + v = np.asarray(v, float) + v = v[np.isfinite(v)] + if v.size < 2: + return float("nan"), float("nan") + s = np.random.default_rng(0).choice(v, (n, v.size), replace=True) + return tuple(np.percentile(np.median(s, axis=1), [2.5, 97.5])) + + print(f"\n{'='*78}\n median over {len(shared)} proteins, Angstrom\n{'='*78}") + for label in labels: + d = df[df.run == label] + if d.empty: + continue + print(f"\n--- {label} ---") + + print(f"\n diagnostic ladder, all rows at one cloud size and one estimation size") + print(f" {'lag':<26}{'uncorr':>9}{'oracle':>9}{'transf':>9}{'random':>9}" + f"{'gain_o':>9}{'gain_t':>9}{'keep':>8}{'n':>6}{'n_est':>7}{'prots':>7}") + ladder = [("no separation", "L_nosep"), + *[(f"within segment, {L} fr", f"L_within{L}") for L in args.sub_lens], + ("half segment apart", "L_adjacent"), + ("different segment", "L_between")] + for title, tag in ladder: + if f"{tag}_unc" not in d.columns or d[f"{tag}_unc"].isna().all(): + e = d.get(f"{tag}_ess") + note = (f"UNRESOLVED, {e.median():.1f} effective samples" + if e is not None else "no data") + print(f" {title:<26}{note:>74}") + continue + # Proteins masked out by the ESS floor leave the row, so say how many are + # left: a row over 23 high-autocorrelation proteins must not be compared + # with one over all 82 as though the lag were the only difference. + valid = int(d[f"{tag}_unc"].notna().sum()) + print(f" {title:<26}{d[f'{tag}_unc'].median():>9.4f}" + f"{d[f'{tag}_oracle'].median():>9.4f}{d[f'{tag}_trn'].median():>9.4f}" + f"{d[f'{tag}_rnd'].median():>9.4f}{d[f'{tag}_gain_oracle'].median():>9.4f}" + f"{d[f'{tag}_gain_trn'].median():>9.4f}" + f"{d[f'{tag}_retention'].median():>8.3f}" + f"{int(d[f'{tag}_n_used'].median()):>6}" + f"{int(d[f'{tag}_n_est'].median()):>7}" + f"{valid:>7}") + + g_lo, g_hi = boot_ci(d["primary_gain_trn"]) + g = d["primary_gain_trn"].median() + # A pass on the production arm alone is not enough: that arm subtracts the scored + # cloud's own centroid and so cancels a realized Monte Carlo error a learned + # objective could never know. The check is the paired one inside the held-out run + # -- same cloud, same reference draw, same A centroid, corrected once each way -- + # so it isolates the leak instead of confounding it with the halved cloud size. + # + # A non-inferiority contrast, not a ratio. Two negative gains divide to about one, + # so a ratio can read as perfect retention of an effect that is not there; and + # requiring only the ratio's *upper* end to clear the margin would approve a CI + # like [0.10, 0.60] that mostly indicates collapse. + held = d["primaryH_gain_trn"] + contrast = held - args.min_attenuation * d["primaryH_gain_trn_alt"] + c_lo, c_hi = boot_ci(contrast) + holdout_agrees = bool(held.median() > 0 and c_lo > 0) + if guards: + verdict = "SUPPRESSED" + elif g_hi < args.min_useful_gain: + verdict = "DEAD" + elif g_lo > args.min_useful_gain: + verdict = ("worth the MD-free prediction gate" if holdout_agrees + else "UNRESOLVED: does not clear the held-out margin") + else: + verdict = "UNRESOLVED" + print(f"\n primary: a centroid from all of one segment, applied and scored " + f"against a different\n segment, n={int(d['primary_n_used'].median())} " + f"(the production cloud size), estimated from " + f"{int(d['primary_n_est'].median())} frames") + print(f" transferred gain {g:+.4f} [{g_lo:+.4f}, {g_hi:+.4f}] " + f"against {args.min_useful_gain:.2f} -> {verdict}") + print(f" positive on {(d['primary_gain_trn'] > 0).mean():.2f} of proteins, " + f"beats a matched random shift on " + f"{(d['primary_gain_trn'] > d['primary_gain_rnd']).mean():.2f}" + f" (draw-to-draw SE {d['primary_gain_trn_mcse'].median():.4f})") + print(f" retention is not reported here: this arm deliberately gives the " + f"transferred estimate\n the whole segment while the oracle gets half, " + f"so read 'different segment' in the ladder") + frac = " ".join(f"{int(f*100)}%: {d[f'primary_gain_frac{int(f*100)}'].median():+.4f}" + for f in FRACTIONS) + print(f" gain at a fraction of the shift {frac} 100%: {g:+.4f}") + print(f" (a predictor captures a fraction of the shift, not of the gain; " + f"read the row above\n before choosing a threshold, not after)") + + hg_lo, hg_hi = boot_ci(d["primaryH_gain_trn"]) + print(f"\n same, generated centroid held out, n={int(d['primaryH_n_used'].median())}" + f" -- no verdict, this is not the metric the threshold was set on") + print(f" transferred gain {d['primaryH_gain_trn'].median():+.4f} " + f"[{hg_lo:+.4f}, {hg_hi:+.4f}] " + f"retention {d['primaryH_retention'].median():+.3f}") + print(f" paired against the same cloud corrected with its own mean " + f"({d['primaryH_gain_trn_alt'].median():+.4f}): the leak is worth " + f"{d['primaryH_leak'].median():+.4f}") + print(f" held-out minus {args.min_attenuation:.2f} of in-sample: " + f"{contrast.median():+.4f} [{c_lo:+.4f}, {c_hi:+.4f}] -> " + f"{'holds up' if holdout_agrees else 'does not clear the margin'}") + + print(f"\n generated centroid vs pooled reference {d['d_gen_to_pool'].median():.4f}" + f" typical Monte Carlo SE {d['mc_gen_centroid'].median():.4f}") + print(f" correlation time {d['tau_segment'].median():.1f} frames, so a " + f"{int(d['seg_len_min'].median())}-frame segment holds " + f"{d['ess_min_segment'].median():.1f} effective samples") + print(f" worst-segment centroid SE {d['se_segment_centroid'].median():.4f}, " + f"top-2 eigenvalue gap {d['pc_relgap'].median():.3f}") + + if guards: + print(f"\n{'='*78}\n VERDICT SUPPRESSED\n{'='*78}") + for g in guards: + print(f" {g}") + print(" The numbers above are still printed, but this was set up as a " + "prespecified\n decision experiment and the preconditions did not hold.") + + print(f"\n{'='*78}\n reading\n{'='*78}") + print(" The gate is the absolute transferred gain on the primary row. Retention says") + print(" how much of the achievable correction survives the lag; the gain says whether") + print(" what survives is worth anything. A pass means only that the target is stable") + print(" enough to justify the MD-free prediction test -- the transferred gain is a") + print(" ceiling reached by knowing another segment's centroid, not a prediction.") + print() + print(" The ladder's 'no separation' row is the sensitivity control for the ladder,") + print(" not for the primary row, which has its own denominator at its own cloud size.") + print(" A healthy control there does not by itself establish power at long lag: three") + print(" temporal replicates estimate between-segment variability imprecisely, and a") + print(" randomised draw from a segment averages its whole occupancy while a") + print(" contiguous estimation block does not.") + print() + print(" The ladder is not monotone. Retention high at short lag and collapsing") + print(" between segments is compatible with drift or with differing metastable") + print(" occupancy -- and trapping in distinct basins can equally mean the trajectory") + print(" is too short for the equilibrium quantity being aimed at. The reverse shape,") + print(" short lag poor while whole segments hold up, is compatible with strong") + print(" within-segment autocorrelation or other short-window heterogeneity. Neither") + print(" shape identifies its cause; check the correlation time before reading either.") + print() + print(" A null is attributable to the measurement rather than the target when the") + print(" control row's gain is small, when the Monte Carlo centroid SE is a large part") + print(" of the generated centroid error, when the correlation time leaves few") + print(" effective samples, when the top-2 eigenvalue gap is narrow enough that the") + print(" plane itself is unstable, or when a segment is an equilibration transient") + print(" rather than equilibrium occupancy. Those are not automated: the verdict is") + print(" suppressed only for the cohort and sample-size preconditions.") + print() + print(" Stability is necessary, not sufficient. The shift also has to be predictable") + print(" without the test protein's MD, and these PCA coordinates carry an arbitrary") + print(" sign and rotation, so they are not themselves a cross-protein target.") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/centroid_shrinkage_check.py b/bbflow_base/scripts/centroid_shrinkage_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e9bc268687749079993a528316c2c20a39dff125 --- /dev/null +++ b/bbflow_base/scripts/centroid_shrinkage_check.py @@ -0,0 +1,431 @@ +"""Follow-up to centroid_reliability.py: is negative transfer real drift, or overcorrection? + +`centroid_reliability.py` found that a full-strength centroid correction, estimated on one +whole MD segment and applied to a different segment, made the score *worse* than doing +nothing, on all 82 test proteins and all 7 checkpoints tried. That result stands: raw, +full-strength segment-centroid correction is unusable. It does not by itself distinguish +two explanations, which imply opposite next steps: + + overcorrection each 1001-frame segment carries only a handful of effective + independent samples (measured separately per protein), so a + segment's own centroid is a noisy estimate of a real, stable target. + Applying it at full strength imports that noise; a shrunk correction + could still help, and a denoised/learned centroid could be worth a + separate learnability experiment. + + genuine instability there is no stable target at this timescale -- segments differ + because the underlying occupancy itself drifts or the trajectory + visits different metastable states in different windows. No amount + of shrinkage rescues a moving target, and the line should stop. + +Two checks, both closed-form and CPU-only, reusing the exact production-style primary +construction (all frames of segment A, reference drawn with replacement from all of +segment B, at the production cloud size): + + directed pairs the six ordered segment pairs, reported separately rather than + pooled. Segments are indexed by discovery order (`_R1`, `_R2`, + `_R3`), which is deterministic but is *not* independently verified + here to be simulation chronology -- see the caveat below. If only + pairs touching the first-discovered segment fail, that is + *consistent with* an equilibration transient or a protocol + difference specific to that segment, not proof of one; if the other + two segments fail just as badly against each other, instability is + the more credible reading regardless of what segment order means. + + shrinkage, cross-validated, held-out, at the production gate three curves per + directed pair and alpha, mirroring `centroid_reliability.py`'s + primary/held-out/paired-contrast design exactly, because the same + size mismatch that design was built to handle shows up here too: + + production full 250-sample cloud, anchor = its own mean. This is the only curve + evaluated against the project's 0.10 Angstrom threshold, because that + threshold was set at the production cloud size and the mean term sits + inside a square root -- a correction that clears 0.10 at n=125 is not + shown to clear it at n=250, and one that fails at n=125 is not shown to + fail at n=250 either. + held-out half the cloud (125), anchor = a disjoint half's mean, so the anchor + cannot cancel the realized sampling noise of the half being scored. This + is the *only* curve alpha selection uses: choosing among alphas is a + relative comparison and does not need the production cloud size, but it + does need to be leak-free, or every alpha would look better than it is + by a similar amount and the ranking would not be trustworthy. + held-out, in-sample anchor the same scored half and reference draw as held-out, + anchored to its own mean instead. Paired with held-out at the same size, + this reproduces the primary script's leak/attenuation contrast: how much + of the held-out gain would collapse if the anchor were allowed to see + the batch it corrects. + + For each protein, the fraction is chosen by *median* gain on the held-out curve of the + other 81 proteins (leave-one-protein-out), then that fraction is applied to this + protein's own *production* curve for the 0.10 Angstrom gate, and separately checked + against the paired attenuation contrast at matched size. A pass requires both: the + production gain clears 0.10, and the held-out gain is not mostly attributable to the + in-sample anchor's leak. + +Both reuse `md_context` / `load_generated` from `centroid_reliability.py` unchanged, so +the MD projection, segment definitions and CA/topology handling are exactly what the +reviewed primary result used -- this is not a new measurement of the reference, only a +different way of slicing and aggregating the same closed-form quantity. + +Cohort and shape preconditions mirror the primary script: the verdict is suppressed, +not merely annotated, if the analysed cohort, generated-sample count, or segment length +don't match what was expected, so a run that silently lost proteins or ran on truncated +segments can't produce a headline number. + +A pass here is not proof a sequence-based model can learn the equilibrium centroid -- +only that a segment's own centroid carries transferable information worth a *separate* +learnability experiment. And because the checkpoints compared are trained on the same 82 +proteins, MD and segmentation, seven of them agreeing is not seven independent +confirmations; the summary at the end reports how many give the same read rather than +treating one pass among several as a rescue. +""" + +import argparse +import os +from collections import Counter + +import numpy as np + +from centroid_reliability import (load_generated, md_context, stable_seed, w2_sq) + +ALPHA_GRID = tuple(sorted(set( + [round(x, 3) for x in np.arange(0.0, 0.1001, 0.01)] + # dense near zero + [0.125, 0.15, 0.175, 0.20] + + [round(x, 3) for x in np.arange(0.25, 1.0001, 0.05)]))) +MIN_ATTENUATION = 0.5 + + +def _curve(gen_score, mu_apply, mu_a, ref, scale, alphas): + """Closed-form distance at every alpha for one already-drawn (cloud, reference) pair. + + `mu_apply` is subtracted as the correction anchor; `mu_a` is the segment-A centroid + being partially applied. Passing `mu_apply = gen_score.mean(0)` gives the in-sample + (leaky) curve; passing a disjoint half's mean gives the held-out curve. One transport + call gives every alpha, via the same mean-separation identity the primary script uses. + """ + mu_gs = gen_score.mean(0) + mu_b = ref.mean(0) + c = w2_sq(gen_score - mu_gs, ref - mu_b, scale) + d = mu_gs - mu_b + step = mu_a - mu_apply + s2 = scale ** 2 + return {a: float(np.square(d + a * step).sum() * s2 + c) ** 0.5 for a in alphas} + + +def pair_gains(gen_p, mu_a, seg_b, n_prod, scale, rng, n_ref_draws, alphas): + """Three curves per directed pair: production, held-out, and held-out's in-sample twin. + + All three share `mu_a` and are averaged over `n_ref_draws` draws each, but only `ho` + and `hoalt` share their *specific* scored half and reference draw within every + iteration -- they are the paired pair the attenuation contrast needs. `prod` draws its + own reference independently and scores the full cloud, so it is not paired against the + other two frame-for-frame; only the selected alpha (chosen from `ho` alone, on other + proteins) carries over to it. + """ + n_gen = gen_p.shape[0] + acc_prod = {a: 0.0 for a in alphas} + acc_ho = {a: 0.0 for a in alphas} + acc_hoalt = {a: 0.0 for a in alphas} + for _ in range(n_ref_draws): + ref_prod = seg_b[rng.integers(0, len(seg_b), n_prod)] + c_prod = _curve(gen_p, gen_p.mean(0), mu_a, ref_prod, scale, alphas) + for a in alphas: + acc_prod[a] += c_prod[a] + + g_idx = rng.permutation(n_gen) + cut = n_gen // 2 + scored_half, apply_half = gen_p[g_idx[:cut]], gen_p[g_idx[cut:]] + ref_ho = seg_b[rng.integers(0, len(seg_b), cut)] + c_ho = _curve(scored_half, apply_half.mean(0), mu_a, ref_ho, scale, alphas) + c_hoalt = _curve(scored_half, scored_half.mean(0), mu_a, ref_ho, scale, alphas) + for a in alphas: + acc_ho[a] += c_ho[a] + acc_hoalt[a] += c_hoalt[a] + return ({a: v / n_ref_draws for a, v in acc_prod.items()}, + {a: v / n_ref_draws for a, v in acc_ho.items()}, + {a: v / n_ref_draws for a, v in acc_hoalt.items()}) + + +def audit_one(name, ctx, gen_flat, k_dim, rng, n_ref_draws, alphas): + segs = ctx["segs"] + scale = 10.0 / ctx["n_atoms"] ** 0.5 + gen_p = (gen_flat - ctx["centre"]) @ ctx["basis"].T + n_prod = gen_p.shape[0] + + rows = [] + for i in range(len(segs)): + for j in range(len(segs)): + if i == j: + continue + prod, ho, hoalt = pair_gains(gen_p, segs[i].mean(0), segs[j], n_prod, scale, + rng, n_ref_draws, alphas) + rows.append({"name": name, "src": i, "dst": j, + "touches_seg0": (i == 0 or j == 0), + **{f"prod_a{a}": prod[a] for a in alphas}, + **{f"ho_a{a}": ho[a] for a in alphas}, + **{f"hoalt_a{a}": hoalt[a] for a in alphas}}) + return rows + + +def boot_ci(v, reps=4000): + v = np.asarray(v, float) + s = np.random.default_rng(0).choice(v, (reps, v.size), replace=True) + return tuple(np.percentile(np.median(s, axis=1), [2.5, 97.5])) + + +def select_alpha_lopo(df, alphas, mask=None): + """Leave-one-protein-out fraction, chosen by median held-out gain on every other + protein. Held-out (not production, not its in-sample twin) is the only curve this + reads, because comparing alphas needs to be leak-free but does not need the + production cloud size -- that size only matters once, for the gate itself. + + Returns, per protein: the chosen alpha, and that protein's own production and + held-out-pair gains *at* that alpha, so the gate and the attenuation check are + evaluated at the fraction genuinely selected without seeing this protein. + """ + d = df[mask] if mask is not None else df + ho_cols = [f"ho_a{a}" for a in alphas] + per_protein = d.groupby("name")[[*ho_cols, + *[f"prod_a{a}" for a in alphas], + *[f"hoalt_a{a}" for a in alphas]]].mean() + names = per_protein.index.to_numpy() + ho_unc = per_protein[ho_cols].to_numpy() + ho_gain = ho_unc[:, alphas.index(0.0)][:, None] - ho_unc + n = len(names) + chosen_idx = np.empty(n, dtype=int) + for i in range(n): + med_others = np.median(np.delete(ho_gain, i, axis=0), axis=0) + chosen_idx[i] = int(np.argmax(med_others)) + + prod_unc = per_protein[[f"prod_a{a}" for a in alphas]].to_numpy() + hoalt_unc = per_protein[[f"hoalt_a{a}" for a in alphas]].to_numpy() + prod_base, hoalt_base = prod_unc[:, alphas.index(0.0)], hoalt_unc[:, alphas.index(0.0)] + + out = [] + for i in range(n): + a_idx = chosen_idx[i] + out.append({"name": names[i], "alpha": alphas[a_idx], + "prod_gain": prod_base[i] - prod_unc[i, a_idx], + "ho_gain": ho_gain[i, a_idx], + "hoalt_gain": hoalt_base[i] - hoalt_unc[i, a_idx]}) + import pandas as pd + return pd.DataFrame(out) + + +def report_shrinkage(df, alphas, min_useful_gain, subset_label, mask=None): + sel = select_alpha_lopo(df, alphas, mask) + chosen = sel["alpha"].to_numpy() + top, top_n = Counter(np.round(chosen, 3)).most_common(1)[0] + print(f"\n [{subset_label}] leave-one-protein-out shrinkage, {len(sel)} proteins") + print(f" fraction selected on the held-out curve: median {np.median(chosen):.3f}, " + f"most common {top:.3f} ({top_n}/{len(sel)}), " + f"range [{chosen.min():.3f}, {chosen.max():.3f}]") + + g = sel["prod_gain"].to_numpy() + g_lo, g_hi = boot_ci(g) + gate = ("DEAD" if g_hi < min_useful_gain else + "clears the gate" if g_lo > min_useful_gain else "UNRESOLVED") + print(f" gate: production-size (n=250) gain at the selected fraction, applied to " + f"this protein only\n {np.median(g):+.4f} [{g_lo:+.4f}, {g_hi:+.4f}] " + f"against {min_useful_gain:.2f} -> {gate}") + + ho, hoalt = sel["ho_gain"].to_numpy(), sel["hoalt_gain"].to_numpy() + contrast = ho - MIN_ATTENUATION * hoalt + c_lo, c_hi = boot_ci(contrast) + holds_up = bool(np.median(ho) > 0 and c_lo > 0) + print(f" qualification: held-out gain {np.median(ho):+.4f} vs its in-sample twin " + f"{np.median(hoalt):+.4f} at the same n=125") + print(f" held-out minus {MIN_ATTENUATION:.2f} of the twin: " + f"{np.median(contrast):+.4f} [{c_lo:+.4f}, {c_hi:+.4f}] -> " + f"{'holds up' if holds_up else 'does not clear the margin'}") + + if gate == "DEAD": + verdict = "DEAD" + elif gate == "clears the gate" and holds_up: + verdict = "warrants a separate learnability experiment" + else: + verdict = "UNRESOLVED" + print(f" -> {verdict}") + + # Sensitivity only, not a second chance at a verdict: alpha ranking can differ at + # n=125 (where it was chosen) from n=250 (where the gate is applied), since the shape + # term changes with cloud size. If a DEAD verdict is going to be reported as "no + # shrinkage helps," this shows whether any alpha's production gain clears 0.10 even + # though it wasn't the one the leak-free procedure selected. A large value here is a + # reason to look closer, via the held-out qualification at that specific alpha, not a + # license to report it as if it had been selected honestly. + all_prod = df[mask] if mask is not None else df + prod_curve = all_prod.groupby("name")[[f"prod_a{a}" for a in alphas]].mean() + prod_gain_by_alpha = prod_curve.iloc[:, alphas.index(0.0)].to_numpy()[:, None] \ + - prod_curve.to_numpy() + best_unselected = int(np.argmax(np.median(prod_gain_by_alpha, axis=0))) + print(f" sensitivity only, not selected: best production-gain alpha in hindsight " + f"is {alphas[best_unselected]:.3f}, median gain " + f"{np.median(prod_gain_by_alpha[:, best_unselected]):+.4f} -- report this only " + f"alongside the held-out check at that alpha, never as a standalone pass") + return verdict + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--md_dir", required=True) + ap.add_argument("--ensemble_dirs", nargs="+", required=True) + ap.add_argument("--names", nargs="*", default=[]) + ap.add_argument("--k", type=int, default=2) + ap.add_argument("--n_ref_draws", type=int, default=5) + ap.add_argument("--min_useful_gain", type=float, default=0.10) + ap.add_argument("--require_segments", type=int, default=3) + ap.add_argument("--expect_cohort", type=int, default=82) + ap.add_argument("--expect_n_gen", type=int, default=250) + ap.add_argument("--expect_seg_len", type=int, default=1001) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out_csv", default="") + args = ap.parse_args() + + labels = args.names or [os.path.basename(d.rstrip("/")) for d in args.ensemble_dirs] + if len(labels) != len(args.ensemble_dirs) or len(set(labels)) != len(labels): + raise SystemExit("--names must match --ensemble_dirs, uniquely") + + import pandas as pd + cohort = sorted(set.intersection(*[ + {d for d in os.listdir(e) if os.path.isdir(os.path.join(e, d))} + for e in args.ensemble_dirs])) + print(f"cohort common to all runs: {len(cohort)} proteins", flush=True) + + rows, failures, n_gen_seen, seg_lens = [], {}, set(), set() + for i, nm in enumerate(cohort): + try: + ctx = md_context(nm, args.md_dir, args.k, args.require_segments) + except Exception as exc: # noqa: BLE001 + for label in labels: + failures.setdefault(label, []).append(f"{nm}: {exc}") + continue + seg_lens.update(len(s) for s in ctx["segs"]) + for label, ens in zip(labels, args.ensemble_dirs): + try: + gen_flat = load_generated(nm, ens, ctx["ref"]) + n_gen_seen.add(gen_flat.shape[0]) + r = audit_one(nm, ctx, gen_flat, args.k, + np.random.default_rng(stable_seed(nm, args.seed)), + args.n_ref_draws, ALPHA_GRID) + for row in r: + row["run"] = label + rows.extend(r) + except Exception as exc: # noqa: BLE001 + failures.setdefault(label, []).append(f"{nm}: {exc}") + if (i + 1) % 10 == 0: + print(f" {i+1}/{len(cohort)} proteins", flush=True) + + if failures: + print("\nfailures:") + for label, msgs in failures.items(): + print(f" [{label}] {len(msgs)}") + for m in msgs[:5]: + print(f" {m}") + + df = pd.DataFrame(rows) + if df.empty: + raise SystemExit("no protein produced a measurement") + + counts = df.groupby("name")["run"].nunique() + shared = set(counts[counts == len(labels)].index) + df = df[df.name.isin(shared)] + + guards = [] + if args.expect_cohort and len(shared) != args.expect_cohort: + guards.append(f"analysed {len(shared)} proteins, expected {args.expect_cohort}") + if args.expect_n_gen and n_gen_seen != {args.expect_n_gen}: + guards.append(f"generated sample counts seen {sorted(n_gen_seen)}, " + f"expected {args.expect_n_gen}") + if args.expect_seg_len and seg_lens != {args.expect_seg_len}: + guards.append(f"segment lengths seen {sorted(seg_lens)}, " + f"expected {args.expect_seg_len} in every segment") + + if args.out_csv: + df.to_csv(args.out_csv, index=False) + print(f"\nper-directed-pair values -> {args.out_csv}") + + for label in labels: + d = df[df.run == label] + if d.empty: + continue + print(f"\n{'='*78}\n{label}\n{'='*78}") + + print("\n directed segment pairs (1-indexed to match R1/R2/R3), held-out " + "full-strength gain (Angstrom),\n median over proteins, n=125") + d = d.copy() + d["gain_ho_full"] = d["ho_a0.0"] - d[f"ho_a{ALPHA_GRID[-1]}"] + piv = d.groupby(["src", "dst"])["gain_ho_full"].median().unstack() + print(" src\\dst " + "".join(f"{j+1:>10}" for j in range(3))) + for i in range(3): + cells = "".join(f"{piv.loc[i, j]:>10.4f}" if j in piv.columns and i in piv.index + and not np.isnan(piv.loc[i, j]) else f"{'':>10}" + for j in range(3)) + print(f" {i+1} {cells}") + + seg0 = d[d.touches_seg0].groupby("name")["gain_ho_full"].mean() + seg23 = d[~d.touches_seg0].groupby("name")["gain_ho_full"].mean() + + def summarize(v, tag): + lo, hi = boot_ci(v) + print(f" {tag:<28} median {np.median(v):+.4f} [{lo:+.4f}, {hi:+.4f}] " + f"n={len(v)}") + + print("\n held-out full-strength gain: pairs touching R1 vs R2<->R3 only") + summarize(seg0.to_numpy(), "touches R1") + if len(seg23): + summarize(seg23.to_numpy(), "R2 <-> R3 only") + else: + print(" R2 <-> R3 only no data (need >=3 segments)") + print(" only touching-R1 failing is CONSISTENT WITH an equilibration") + print(" transient or a protocol difference specific to R1 -- it does not by") + print(" itself prove one, and R1/R2/R3 file order is not independently") + print(" verified here as simulation chronology") + + if guards: + print("\n VERDICT SUPPRESSED for this run's shrinkage analysis:") + for g in guards: + print(f" {g}") + continue + + report_shrinkage(d, ALPHA_GRID, args.min_useful_gain, "all six directed pairs") + if len(seg23): + report_shrinkage(d, ALPHA_GRID, args.min_useful_gain, + "R2<->R3 only, excludes any R1-specific artefact", + mask=~d.touches_seg0) + + print(f"\n{'='*78}\n across-checkpoint summary\n{'='*78}") + print(" These checkpoints share the same 82 proteins, MD and segmentation, so") + print(" agreement across them is not independent confirmation the way agreement") + print(" across different held-out data would be. A pass on one checkpoint alone") + print(" is not a rescue; only a consistent pattern across the group is meaningful.") + if guards: + print(f"\n guard tripped, no per-checkpoint verdicts to summarise: " + f"{'; '.join(guards)}") + return + + verdicts = {} + for label in labels: + d = df[df.run == label] + if d.empty: + continue + sel = select_alpha_lopo(d, ALPHA_GRID, mask=~d.touches_seg0) + g_lo, g_hi = boot_ci(sel["prod_gain"].to_numpy()) + c_lo, _ = boot_ci(sel["ho_gain"].to_numpy() + - MIN_ATTENUATION * sel["hoalt_gain"].to_numpy()) + if g_hi < args.min_useful_gain: + verdicts[label] = "DEAD" + elif g_lo > args.min_useful_gain and sel["ho_gain"].median() > 0 and c_lo > 0: + verdicts[label] = "PASS" + else: + verdicts[label] = "UNRESOLVED" + for label, v in verdicts.items(): + print(f" {label:<16} R2<->R3-only, LOPO-selected, held-out-qualified " + f"verdict: {v}") + n_dead = sum(v == "DEAD" for v in verdicts.values()) + print(f"\n {n_dead}/{len(verdicts)} checkpoints DEAD on the qualified, " + f"R1-excluded view") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/check_directional_condition_equivariance.py b/bbflow_base/scripts/check_directional_condition_equivariance.py new file mode 100644 index 0000000000000000000000000000000000000000..056686e45f7601f552a7d215f55c4dc6ad503426 --- /dev/null +++ b/bbflow_base/scripts/check_directional_condition_equivariance.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +"""Known-answer checks for directional node/edge conditions.""" +from pathlib import Path +import sys + +import torch + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from bbflow.models.latent import LatentEncoder + + +class _Cfg: + dim = 16 + num_modes = 2 + motion_hidden_dim = 16 + motion_dist_bins = 4 + motion_dist_width = 4.0 + motion_message_passing_layers = 1 + template_residual_scale = 0.1 + template_remove_rotation = True + + +def main(): + torch.manual_seed(7) + encoder = LatentEncoder(_Cfg()).eval() + trans = torch.tensor([[[0.0, 0.0, 0.0], [1.2, 0.1, 0.0], [0.3, 1.1, 0.2], [1.0, 1.2, 0.5], [0.2, 0.4, 1.3]]]) + rotmats = torch.eye(3).reshape(1, 1, 3, 3).repeat(1, trans.shape[1], 1, 1) + seq = torch.zeros(1, trans.shape[1], 21) + seq[0, torch.arange(trans.shape[1]), torch.arange(trans.shape[1]) % 21] = 1.0 + mask = torch.ones(1, trans.shape[1]) + rotation = torch.tensor([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) + + with torch.no_grad(): + condition, _ = encoder.forward_prior(trans, rotmats, seq, mask) + trans_rot = torch.einsum("ij,bnj->bni", rotation, trans) + rotmats_rot = torch.einsum("ij,bnjk->bnik", rotation, rotmats) + condition_rot, _ = encoder.forward_prior(trans_rot, rotmats_rot, seq, mask) + + disp_local_diff = (condition_rot["disp_node_cond"].float() - condition["disp_node_cond"].float()).abs().max() + disp_edge_diff = (condition_rot["disp_edge_cond"].float() - condition["disp_edge_cond"].float()).abs().max() + expected_u = torch.einsum("ij,bnkj->bnki", rotation, condition["u_global"].float()) + u_global_diff = (condition_rot["u_global"].float() - expected_u).abs().max() + + print("disp_node_cond_shape =", tuple(condition["disp_node_cond"].shape)) + print("disp_edge_cond_shape =", tuple(condition["disp_edge_cond"].shape)) + print("disp_local_equivariance_max_abs_diff =", float(disp_local_diff.item())) + print("disp_edge_invariance_max_abs_diff =", float(disp_edge_diff.item())) + print("u_global_equivariance_max_abs_diff =", float(u_global_diff.item())) + + assert tuple(condition["disp_node_cond"].shape) == (1, trans.shape[1], 3) + assert tuple(condition["disp_edge_cond"].shape) == (1, trans.shape[1], trans.shape[1], 1) + assert disp_local_diff < 1e-4 + assert disp_edge_diff < 1e-4 + assert u_global_diff < 1e-4 + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/check_foundation_compatibility.py b/bbflow_base/scripts/check_foundation_compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..b58fa05de97a5c6a6e7b8dbc327f7965f379fa8b --- /dev/null +++ b/bbflow_base/scripts/check_foundation_compatibility.py @@ -0,0 +1,207 @@ +import argparse +import copy +import json +from pathlib import Path + +import torch +from hydra import compose, initialize_config_dir +from omegaconf import OmegaConf + +from bbflow.data.pdb_dataloader_bbflow import PdbDataModuleBBFlow +from bbflow.models.bbflow_module import BBFlowModule +from bbflow.models.embedder import Embedder +from bbflow.models.bbflow_model import BBFlowModel + + +def _dim_summary(cfg): + e = cfg.model.embed + node_dim = int(e.time_embed_dim) + int(e.length_embed_dim) + if e.embed_aatype: + node_dim += int(e.aatype_embed_dim) + + edge_dim = 2 * int(e.time_embed_dim) + edge_dim += 2 * int(cfg.model.node_embed_size) + edge_dim += int(e.num_bins_distance) + if e.embed_distogram: + edge_dim += int(e.num_bins_distance) + if e.embed_self_conditioning: + edge_dim += int(e.num_bins_distance) + if e.embed_direction: + edge_dim += 3 + index_type = getattr(e, "index_embed_type", None) + if index_type == "full": + node_dim += int(e.index_embed_dim) + edge_dim += int(e.index_embed_dim) + elif index_type == "neighbor": + edge_dim += 1 + return { + "time_embed_dim": int(e.time_embed_dim), + "aatype_embed_dim": int(e.aatype_embed_dim), + "embed_direction": bool(e.embed_direction), + "node_dim": node_dim, + "edge_dim": edge_dim, + } + + +def _load_ckpt_state(ckpt_path): + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=True) + state = ckpt["state_dict"] + return {k.replace("model.", ""): v for k, v in state.items()} + + +def _compatible_report(model, ckpt_state): + current = model.state_dict() + loaded = [] + skipped = [] + for key, value in ckpt_state.items(): + if key in current and current[key].shape == value.shape: + loaded.append(key) + elif key in current: + skipped.append({ + "key": key, + "ckpt_shape": list(value.shape), + "model_shape": list(current[key].shape), + }) + return {"loaded": len(loaded), "skipped": skipped} + + +def _make_embedder_inputs(batch): + node_mask = batch["res_mask"] + trans_t = batch["trans_t"] + trans_sc = batch.get("trans_sc", torch.zeros_like(trans_t)) + bsz, num_res = node_mask.shape[:2] + return { + "B,N": (bsz, num_res), + "device": node_mask.device, + "time": batch["t"], + "CA_pos": { + "trans_t": trans_t, + "trans_sc": trans_sc, + "trans_equilibrium": batch["trans_equilibrium"], + }, + "rotmats_equilibrium": batch["rotmats_equilibrium"], + "seq": batch["seq"], + "z": batch.get("z"), + } + + +def _move_to_device(batch, device): + return {k: v.to(device) if torch.is_tensor(v) else v for k, v in batch.items()} + + +def _adapter_zero_report(model): + report = {} + embedder = model.embedder + for name in ["z_node_adapter", "z_edge_adapter", "disp_node_adapter", "disp_edge_adapter"]: + module = getattr(embedder, name, None) + if module is None: + report[name] = None + continue + last = module[-1] + report[name] = { + "weight_abs_max": float(last.weight.detach().abs().max().cpu().item()), + "bias_abs_max": float(last.bias.detach().abs().max().cpu().item()), + } + film = getattr(model, "film_mlp", None) + if film is not None: + last = film[-1] + report["film_mlp"] = { + "weight_abs_max": float(last.weight.detach().abs().max().cpu().item()), + "bias_abs_max": float(last.bias.detach().abs().max().cpu().item()), + } + else: + report["film_mlp"] = None + return report + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--official_config_path", default=None) + parser.add_argument("--device", default="cpu") + parser.add_argument("--run_batch_checks", action="store_true") + parser.add_argument("--output", default=None) + parser.add_argument("--override", action="append", default=[]) + args = parser.parse_args() + + repo_root = Path(__file__).resolve().parents[1] + with initialize_config_dir(version_base=None, config_dir=str(repo_root / "configs")): + cfg = compose(config_name="train", overrides=args.override) + OmegaConf.set_struct(cfg, False) + cfg.experiment.use_wandb = False + cfg.experiment.num_devices = 1 + cfg.latent.enable = True + cfg.latent.inject_embedder = True + cfg.latent.inject_film = True + cfg.data.loader.num_workers = 0 + + report = { + "current_config_dims": _dim_summary(cfg), + "official_config_dims": None, + "official_config_matches_current": None, + "compatibility": None, + "adapter_zero_init": None, + "initial_equivalence": None, + "prior_scope": { + "prior_uses_model_embed_config": False, + "prior_input_dim": 50, + "note": "LatentEncoder prior features are defined in bbflow.models.latent and do not read cfg.model.embed time/aatype/embed_direction.", + }, + } + + if args.official_config_path is not None and Path(args.official_config_path).exists(): + official_cfg = OmegaConf.load(args.official_config_path) + report["official_config_dims"] = _dim_summary(official_cfg) + report["official_config_matches_current"] = report["official_config_dims"] == report["current_config_dims"] + + module = BBFlowModule(cfg) + ckpt_state = _load_ckpt_state(args.ckpt_path) + report["compatibility"] = _compatible_report(module.model, ckpt_state) + report["adapter_zero_init"] = _adapter_zero_report(module.model) + + baseline_model = BBFlowModel(cfg.model, latent_cfg=None).eval() + latent_model = BBFlowModel(cfg.model, latent_cfg=cfg.latent).eval() + latent_model.load_state_dict(copy.deepcopy(baseline_model.state_dict()), strict=False) + + device = torch.device(args.device if (args.device == "cpu" or torch.cuda.is_available()) else "cpu") + baseline_model.to(device) + latent_model.to(device) + + if args.run_batch_checks: + datamodule = PdbDataModuleBBFlow(cfg.data, training_cfg=cfg.experiment.training, latent_cfg=cfg.latent) + datamodule.setup("fit") + batch = next(iter(datamodule.train_dataloader(rank=0, num_replicas=1))) + batch = _move_to_device(batch, device) + module.interpolant.set_device(device) + noisy = module.interpolant.corrupt_batch(batch) + noisy = _move_to_device(noisy, device) + bsz, num_res = noisy["res_mask"].shape[:2] + num_modes = int(cfg.latent.num_modes) + z = { + "node_cond": torch.randn(bsz, num_res, num_modes, device=device), + "edge_cond": torch.randn(bsz, num_res, num_res, num_modes, device=device), + } + noisy_z = dict(noisy) + noisy_z["z"] = z + with torch.no_grad(): + out_base = baseline_model(noisy) + out_latent = latent_model(noisy_z) + embed_base = baseline_model.embedder(_make_embedder_inputs(noisy)) + embed_latent = latent_model.embedder(_make_embedder_inputs(noisy_z)) + report["initial_equivalence"] = { + "pred_trans_max_abs_diff": float((out_base["pred_trans"] - out_latent["pred_trans"]).abs().max().cpu().item()), + "pred_rotmats_max_abs_diff": float((out_base["pred_rotmats"] - out_latent["pred_rotmats"]).abs().max().cpu().item()), + "node_embed_max_abs_diff": float((embed_base[0] - embed_latent[0]).abs().max().cpu().item()), + "edge_embed_max_abs_diff": float((embed_base[1] - embed_latent[1]).abs().max().cpu().item()), + } + + text = json.dumps(report, indent=2, ensure_ascii=False) + print(text) + if args.output is not None: + out = Path(args.output) + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(text + "\n") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/check_latent_smoke.py b/bbflow_base/scripts/check_latent_smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..0036f8928a6b2fe2a2a0d40e59e77f0a25500a68 --- /dev/null +++ b/bbflow_base/scripts/check_latent_smoke.py @@ -0,0 +1,318 @@ +import argparse +import json +from pathlib import Path + +import pandas as pd +import torch +from hydra import compose, initialize_config_dir +from omegaconf import OmegaConf + +from bbflow.data.pdb_dataloader_bbflow import PdbDataModuleBBFlow +from bbflow.models.bbflow_module import BBFlowModule + + +def grad_norm(parameters): + total = 0.0 + count = 0 + for param in parameters: + if param is None or param.grad is None: + continue + value = param.grad.detach().float().norm().cpu().item() + total += value * value + count += 1 + return total ** 0.5, count + + +def move_to_device(batch, device): + return {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} + + +def load_model_warm_start(module, ckpt_path): + if ckpt_path is None: + return {"loaded": 0, "skipped": 0, "ckpt_path": None, "skipped_keys": []} + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=True) + state_dict = ckpt["state_dict"] + model_state = {k.replace("model.", ""): v for k, v in state_dict.items() if k.startswith("model.")} + current_state = module.model.state_dict() + compatible_state = {} + skipped = [] + for key, value in model_state.items(): + if key in current_state and current_state[key].shape == value.shape: + compatible_state[key] = value + elif key in current_state: + skipped.append({"key": key, "ckpt_shape": list(value.shape), "model_shape": list(current_state[key].shape)}) + module.model.load_state_dict(compatible_state, strict=False) + return { + "loaded": len(compatible_state), + "skipped": len(skipped), + "ckpt_path": str(ckpt_path), + "skipped_keys": skipped[:20], + } + + +def autocast_context(cfg, device): + precision = str(getattr(cfg.experiment.trainer, "precision", "32-true")) + if device.type == "cuda" and precision == "bf16-mixed": + return torch.autocast(device_type="cuda", dtype=torch.bfloat16) + if device.type == "cuda" and precision == "16-mixed": + return torch.autocast(device_type="cuda", dtype=torch.float16) + return torch.autocast(device_type="cpu", enabled=False) + + +def fp32_context(device): + return torch.autocast(device_type=device.type, enabled=False) + + +def summarize_batch(batch): + names = [str(name) for name in batch["pdb_name"]] + return [ + { + "sample": idx, + "pdb_name": name, + "num_res": int(batch["res_mask"][idx].sum().item()), + } + for idx, name in enumerate(names) + ] + + +def injection_parameters(model): + params = [] + if getattr(model.embedder, "z_node_adapter", None) is not None: + params.extend(model.embedder.z_node_adapter.parameters()) + if getattr(model.embedder, "z_edge_adapter", None) is not None: + params.extend(model.embedder.z_edge_adapter.parameters()) + if getattr(model.embedder, "disp_node_adapter", None) is not None: + params.extend(model.embedder.disp_node_adapter.parameters()) + if getattr(model.embedder, "disp_edge_adapter", None) is not None: + params.extend(model.embedder.disp_edge_adapter.parameters()) + if getattr(model, "film_mlp", None) is not None: + params.extend(model.film_mlp.parameters()) + return params + + +def condition_tensor_summary(condition): + out = {} + for key in ["node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond", "energy", "u_local", "u_global", "local_cov_pred", "cross_cov_pred", "rmsf_pred"]: + value = condition.get(key) + if torch.is_tensor(value): + value_f = value.detach().float() + out[f"{key}_shape"] = list(value.shape) + out[f"{key}_abs_mean"] = float(value_f.abs().mean().cpu().item()) + out[f"{key}_std"] = float(value_f.std().cpu().item()) if value_f.numel() > 1 else 0.0 + return out + + + + +def known_rotation(device): + # Fixed +90 degree rotation around z. This gives a deterministic + # equivariance check with a known answer: output_rotated == R @ output. + return torch.tensor( + [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], + device=device, + dtype=torch.float32, + ) + + +def equivariance_diagnostics(module, noisy_batch, condition): + with torch.no_grad(), fp32_context(noisy_batch["res_mask"].device): + rot = known_rotation(noisy_batch["res_mask"].device) + trans_rot = torch.einsum("ij,bnj->bni", rot, noisy_batch["trans_equilibrium"].float()) + rotmats_rot = torch.einsum("ij,bnjk->bnik", rot, noisy_batch["rotmats_equilibrium"].float()) + condition_rot, _ = module.latent_encoder.forward_prior( + trans_rot, + rotmats_rot, + noisy_batch["seq"], + noisy_batch["res_mask"], + ) + expected_u = torch.einsum("ij,bnkj->bnki", rot, condition["u_global"].float()) + expected_center = torch.einsum("ij,bkj->bki", rot, condition["template_center"].float()) + expected_omega = torch.einsum("ij,bkj->bki", rot, condition["template_omega"].float()) + expected_velocity = torch.einsum("ij,bkj->bki", rot, condition["template_velocity"].float()) + return { + "equivariance_rotation": "fixed_z_90deg", + "equivariance_u_global_max_abs_diff": float((condition_rot["u_global"].float() - expected_u).abs().max().detach().cpu().item()), + "equivariance_template_center_max_abs_diff": float((condition_rot["template_center"].float() - expected_center).abs().max().detach().cpu().item()), + "equivariance_template_omega_max_abs_diff": float((condition_rot["template_omega"].float() - expected_omega).abs().max().detach().cpu().item()), + "equivariance_template_velocity_max_abs_diff": float((condition_rot["template_velocity"].float() - expected_velocity).abs().max().detach().cpu().item()), + } + +def zero_condition(condition): + zeroed = {} + for key, value in condition.items(): + if torch.is_tensor(value): + if key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}: + zeroed[key] = torch.zeros_like(value) + else: + zeroed[key] = value.detach() + else: + zeroed[key] = value + return zeroed + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--out_dir", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--ckpt_path", default=None) + parser.add_argument("--override", action="append", default=[]) + args = parser.parse_args() + + repo_root = Path(__file__).resolve().parents[1] + with initialize_config_dir(version_base=None, config_dir=str(repo_root / "configs")): + cfg = compose(config_name="train", overrides=args.override) + OmegaConf.set_struct(cfg, False) + cfg.experiment.use_wandb = False + cfg.experiment.num_devices = 1 + cfg.latent.enable = True + + device = torch.device(args.device if torch.cuda.is_available() or args.device == "cpu" else "cpu") + datamodule = PdbDataModuleBBFlow(cfg.data, training_cfg=cfg.experiment.training, latent_cfg=cfg.latent) + datamodule.setup("fit") + loader = datamodule.train_dataloader(rank=0, num_replicas=1) + batch = move_to_device(next(iter(loader)), device) + batch_rows = summarize_batch(batch) + + module = BBFlowModule(cfg).to(device) + load_info = load_model_warm_start(module, args.ckpt_path) + module.train() + module._set_frozen_foundation_eval() + module.interpolant.set_device(device) + + with fp32_context(device): + noisy_batch = module.interpolant.corrupt_batch(batch) + prior_feature_breakdown = module.latent_encoder.prior_feature_breakdown( + noisy_batch["trans_equilibrium"], + noisy_batch["rotmats_equilibrium"], + noisy_batch["seq"], + noisy_batch["res_mask"], + ) + ( + condition, + group_index, + latent_metrics, + motion_loss, + shape_baseline_error, + ) = module._latent_group_z(noisy_batch) + + for key in ["node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"]: + if torch.is_tensor(condition.get(key)): + condition[key].retain_grad() + noisy_batch["z"] = condition + + with autocast_context(cfg, device): + module.model.embedder.track_condition_debug = True + model_output = module.model(noisy_batch) + model_output["pred_trans"].retain_grad() + + probe_batch = dict(noisy_batch) + probe_batch["z"] = zero_condition(condition) + with torch.no_grad(), autocast_context(cfg, device): + probe_output = module.model(probe_batch) + z_output_delta = torch.mean(torch.abs(probe_output["pred_trans"] - model_output["pred_trans"].detach())) + + with autocast_context(cfg, device): + losses = module.loss_fn(noisy_batch, model_output) + total_losses = {key: torch.mean(value) for key, value in losses.items()} + official_loss = total_losses[module._exp_cfg.training.loss] + total_losses["auxiliary_loss"] + total_loss = official_loss + float(getattr(module._exp_cfg.training, "lambda_shape", 1.0)) * motion_loss + + prior_params = list(module.latent_encoder.parameters()) + inject_params = injection_parameters(module.model) + + module.zero_grad(set_to_none=True) + motion_loss.backward(retain_graph=True) + motion_prior_grad, motion_prior_count = grad_norm(prior_params) + motion_inject_grad, motion_inject_count = grad_norm(inject_params) + + module.zero_grad(set_to_none=True) + for key in ["node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"]: + if torch.is_tensor(condition.get(key)): + condition[key].grad = None + model_output["pred_trans"].grad = None + total_loss.backward() + node_cond_grad, node_cond_grad_count = grad_norm([condition.get("node_cond")]) + edge_cond_grad, edge_cond_grad_count = grad_norm([condition.get("edge_cond")]) + pred_trans_grad, pred_trans_grad_count = grad_norm([model_output["pred_trans"]]) + total_prior_grad, total_prior_count = grad_norm(prior_params) + total_inject_grad, total_inject_count = grad_norm(inject_params) + total_model_grad, total_model_count = grad_norm(module.model.parameters()) + + rigid_metrics = module.latent_encoder.rigid_component_metrics( + condition, + noisy_batch["trans_equilibrium"], + noisy_batch["res_mask"], + ) + equiv_metrics = equivariance_diagnostics(module, noisy_batch, condition) + alignment_metrics = {} + if module.motion_loss_enabled: + motion_targets = module._lookup_motion_targets( + noisy_batch["pdb_name"], + device=device, + dtype=condition["cross_cov_pred"].dtype, + num_res=noisy_batch["res_mask"].shape[1], + ) + with torch.autocast(device_type=device.type, enabled=False): + spatial_dists = torch.cdist( + noisy_batch["trans_equilibrium"].float(), + noisy_batch["trans_equilibrium"].float(), + ) + alignment_metrics = module.latent_encoder.motion_alignment_metrics( + condition, + motion_targets, + noisy_batch["res_mask"], + spatial_dists, + ) + summary = { + "batch_size": int(batch["res_mask"].shape[0]), + "warm_start": load_info, + "seq_len": int(batch["res_mask"].shape[1]), + "num_batch_entries": len(batch_rows), + "batch_entries": batch_rows[:10], + "official_loss": float(official_loss.detach().cpu().item()), + "motion_loss": float(motion_loss.detach().cpu().item()), + "shape_recon_loss": float(motion_loss.detach().cpu().item()), + "shape_baseline_error": float(shape_baseline_error.detach().cpu().item()), + "prior_feature_breakdown": prior_feature_breakdown, + "embedder_z_seen": bool(getattr(module.model.embedder, "_last_z_seen", False)), + "embedder_z_requires_grad": bool(getattr(module.model.embedder, "_last_z_requires_grad", False)), + "embedder_z_shape": getattr(module.model.embedder, "_last_z_shape", None), + "embedder_z_abs_mean": float(getattr(module.model.embedder, "_last_z_abs_mean", 0.0)), + "condition_zero_output_delta_mean_abs": float(z_output_delta.detach().cpu().item()), + "motion_prior_grad_norm": motion_prior_grad, + "motion_prior_grad_count": motion_prior_count, + "motion_injection_grad_norm": motion_inject_grad, + "motion_injection_grad_count": motion_inject_count, + "total_node_cond_grad_norm": node_cond_grad, + "total_node_cond_grad_count": node_cond_grad_count, + "total_edge_cond_grad_norm": edge_cond_grad, + "total_edge_cond_grad_count": edge_cond_grad_count, + "total_pred_trans_grad_norm": pred_trans_grad, + "total_pred_trans_grad_count": pred_trans_grad_count, + "total_prior_grad_norm": total_prior_grad, + "total_prior_grad_count": total_prior_count, + "total_injection_grad_norm": total_inject_grad, + "total_injection_grad_count": total_inject_count, + "total_model_grad_norm": total_model_grad, + "total_model_grad_count": total_model_count, + } + summary.update(condition_tensor_summary(condition)) + for key, value in latent_metrics.items(): + summary[key] = float(value.detach().cpu().item()) if torch.is_tensor(value) else float(value) + for key, value in rigid_metrics.items(): + summary[key] = float(value.detach().cpu().item()) if torch.is_tensor(value) else float(value) + for key, value in alignment_metrics.items(): + summary[key] = float(value.detach().cpu().item()) if torch.is_tensor(value) else float(value) + summary.update(equiv_metrics) + + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + with (out_dir / "latent_smoke_summary.json").open("w") as handle: + json.dump(summary, handle, indent=2) + pd.DataFrame(batch_rows).to_csv(out_dir / "latent_smoke_batch.tsv", sep="\t", index=False) + print(json.dumps(summary, indent=2)) + print(f"Wrote template-mode smoke diagnostics to {out_dir}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/cmd_inference_example.sh b/bbflow_base/scripts/cmd_inference_example.sh new file mode 100644 index 0000000000000000000000000000000000000000..b788c55289d8b85ba992d6f59d2ca01f5cc2d427 --- /dev/null +++ b/bbflow_base/scripts/cmd_inference_example.sh @@ -0,0 +1,11 @@ +# Example usage of the bbflow_sample command (run bbflow_sample -h for help) + +THISDIR=$(dirname "$(readlink -f "$0")") + +TEST_PDB_DIR="${THISDIR}/../test_data/test_pdbs" + +bbflow_sample --input_path "${TEST_PDB_DIR}/equilibrium.pdb" "${TEST_PDB_DIR}/short_equilibrium.pdb" \ + --output_path "${TEST_PDB_DIR}/equilibrium_samples.pdb" "${TEST_PDB_DIR}/short_equilibrium_samples.pdb" \ + --cuda_memory_GB 5 \ + --num_samples 100 \ + --tag bbflow-mini-0.1 # small test model, use --tag latest for more accurate ensembles \ No newline at end of file diff --git a/bbflow_base/scripts/cmfm_replay_failure.py b/bbflow_base/scripts/cmfm_replay_failure.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a46f0d666ed7e0a6215d7f1e04ecdea682e4fa --- /dev/null +++ b/bbflow_base/scripts/cmfm_replay_failure.py @@ -0,0 +1,318 @@ +#!/usr/bin/env python +"""Replay a captured CMFM microbatch and attribute the non-finite gradient. + +This is a localization tool, not a fix. It answers exactly two questions about +a dump written by ``BBFlowModule._dump_cmfm_failure``: + +1. which loss component -- ``official``, ``latent``, or ``collective`` -- is the + first to produce a non-finite parameter gradient on that microbatch; +2. whether the same component still explodes in fp32, i.e. whether the target + is mathematically singular or bf16 merely amplified it. + +Each component is backpropagated on its own with ``torch.autograd.grad`` so the +buffers never mix. Nothing is clipped, skipped, or rescaled. + +Usage:: + + python scripts/cmfm_replay_failure.py \ + --dump outputs/.../cmfm_failure_dumps/rank1_epoch0_step170_micro3.pt \ + --config outputs/ckpt/.../config.yaml \ + --precision both +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch +from omegaconf import OmegaConf + +from bbflow.models.bbflow_module import BBFlowModule + + +COMPONENTS = ("official", "latent", "collective") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--dump", + type=Path, + required=True, + help="Path to the rank*_epoch*_step*_micro*.pt failure dump.", + ) + parser.add_argument( + "--config", + type=Path, + default=None, + help=( + "Training config.yaml. Defaults to the config embedded in the dump, " + "then to config.yaml next to the run checkpoint directory." + ), + ) + parser.add_argument( + "--ckpt", + type=Path, + default=None, + help=( + "Optional checkpoint to load instead of the state_dict embedded in " + "the dump. The embedded weights are the pre-step weights and are " + "what you normally want." + ), + ) + parser.add_argument( + "--precision", + choices=("bf16", "fp32", "both"), + default="both", + help="Replay under bf16 autocast, in pure fp32, or both.", + ) + parser.add_argument("--device", default="cuda") + parser.add_argument( + "--json-out", + type=Path, + default=None, + help="Optional path for the machine-readable report.", + ) + return parser.parse_args() + + +def load_config(args: argparse.Namespace, payload: dict) -> OmegaConf: + if args.config is not None: + return OmegaConf.load(args.config) + embedded = payload.get("config") + if embedded is not None: + return OmegaConf.create(embedded) + checkpoint_dir = payload.get("metadata", {}).get("checkpoint_dir", "") + candidate = Path(checkpoint_dir) / "config.yaml" + if candidate.is_file(): + return OmegaConf.load(candidate) + raise SystemExit( + "No config found: pass --config with the training config.yaml." + ) + + +def build_module(cfg, payload: dict, args: argparse.Namespace) -> BBFlowModule: + module = BBFlowModule(cfg) + if args.ckpt is not None: + checkpoint = torch.load(args.ckpt, map_location="cpu", weights_only=False) + state_dict = checkpoint.get("state_dict", checkpoint) + else: + state_dict = payload.get("state_dict") + if state_dict is None: + raise SystemExit( + "The dump carries no state_dict (experiment.training." + "cmfm_dump_state_dict was false); pass --ckpt instead." + ) + missing, unexpected = module.load_state_dict(state_dict, strict=False) + if missing or unexpected: + print( + f"[replay] load_state_dict: {len(missing)} missing, " + f"{len(unexpected)} unexpected keys" + ) + module.to(args.device) + # Train mode so dropout/checkpointing match the failing step. Dropout draws + # differ from the original step; that changes the sample, not whether a + # component's Jacobian is astronomically large. + module.train() + return module + + +def move_batch(batch: dict, device: str) -> dict: + moved = {} + for key, value in batch.items(): + moved[key] = value.to(device) if torch.is_tensor(value) else value + return moved + + +def grad_report(loss: torch.Tensor, parameters, names) -> dict: + grads = torch.autograd.grad( + loss, + parameters, + retain_graph=True, + allow_unused=True, + ) + total_square = 0.0 + finite_absmax = 0.0 + nonfinite = [] + for name, grad in zip(names, grads): + if grad is None: + continue + grad = grad.detach().float() + finite = torch.isfinite(grad) + if not bool(finite.all()): + nonfinite.append(name) + if bool(finite.any()): + selected = grad[finite] + total_square += float(selected.square().sum().item()) + finite_absmax = max(finite_absmax, float(selected.abs().max().item())) + return { + "loss": float(loss.detach().float().item()), + "grad_norm_finite_part": total_square ** 0.5, + "grad_absmax_finite_part": finite_absmax, + "nonfinite_parameter_count": len(nonfinite), + "nonfinite_parameters": nonfinite[:20], + } + + +def replay_once(module: BBFlowModule, batch: dict, use_bf16: bool) -> dict: + named = [ + (name, param) for name, param in module.named_parameters() + if param.requires_grad + ] + names = [name for name, _ in named] + parameters = [param for _, param in named] + + torch.manual_seed(0) + module.zero_grad(set_to_none=True) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=use_bf16): + outputs = module.cmfm_debug_losses(dict(batch)) + + report = { + "precision": "bf16-mixed" if use_bf16 else "fp32", + "components": {}, + "group_diagnostics": [ + { + key: ( + float(value.detach().float().item()) + if torch.is_tensor(value) else value + ) + for key, value in entry.items() + } + for entry in outputs["group_diagnostics"] + ], + "collective_parts": { + key: float(value.detach().float().item()) + for key, value in outputs["collective_parts"].items() + if torch.is_tensor(value) + }, + } + # "official" is a sum of sub-losses with very different numerics, so the + # module also exposes them individually as "official:". Attributing a + # non-finite backward to "official" alone is not a location. + components = list(COMPONENTS) + sorted( + key for key in outputs + if isinstance(key, str) and key.startswith("official:") + ) + report["component_order"] = components + for component in components: + loss = outputs[component] + if not torch.is_tensor(loss) or not loss.requires_grad: + report["components"][component] = { + "loss": float(loss) if not torch.is_tensor(loss) + else float(loss.detach().float().item()), + "grad_norm_finite_part": 0.0, + "grad_absmax_finite_part": 0.0, + "nonfinite_parameter_count": 0, + "nonfinite_parameters": [], + "note": "component does not require grad", + } + continue + report["components"][component] = grad_report(loss, parameters, names) + return report + + +def print_report(report: dict) -> None: + print(f"\n=== replay precision={report['precision']} ===") + components = report.get("component_order", list(COMPONENTS)) + header = ( + f"{'component':<26}{'loss':>14}{'|grad| norm':>16}" + f"{'|grad| max':>14}{'nonfinite params':>19}" + ) + print(header) + print("-" * len(header)) + for component in components: + entry = report["components"][component] + print( + f"{component:<26}{entry['loss']:>14.6g}" + f"{entry['grad_norm_finite_part']:>16.6g}" + f"{entry['grad_absmax_finite_part']:>14.6g}" + f"{entry['nonfinite_parameter_count']:>19d}" + ) + for component in components: + entry = report["components"][component] + if entry["nonfinite_parameters"]: + print(f" {component} first non-finite: {entry['nonfinite_parameters']}") + print("\n per-group collective diagnostics:") + for entry in report["group_diagnostics"]: + print( + f" group={entry.get('group')} size={entry.get('size')} " + f"obs_var_min={entry.get('observed_target_variance_min'):.6g} " + f"cov_scale_min={entry.get('covariance_scale_min'):.6g} " + f"1/cov_scale_max={entry.get('covariance_inverse_scale_max'):.6g} " + f"target_rate_absmax={entry.get('target_cov_rate_absmax'):.6g} " + f"pred_rate_absmax={entry.get('predicted_cov_rate_absmax'):.6g}" + ) + + +def main() -> None: + args = parse_args() + payload = torch.load(args.dump, map_location="cpu", weights_only=False) + metadata = payload.get("metadata", {}) + batch = payload.get("batch") + if batch is None: + raise SystemExit( + "The dump carries no batch (experiment.training.cmfm_capture_failure " + "was false); the failure cannot be replayed." + ) + + print("[replay] captured microbatch") + for key in ( + "rank", + "epoch", + "global_step", + "microbatch", + "precision", + "accumulate_grad_batches", + "nonfinite_parameter_count", + ): + if key in metadata: + print(f" {key}={metadata[key]}") + if metadata.get("pdb_name"): + print(f" pdb_name={metadata['pdb_name'][0]}") + for key in ("group_index", "trajectory_idx", "conformation_idx", "t"): + if key in metadata: + print(f" {key}={metadata[key]}") + + cfg = load_config(args, payload) + module = build_module(cfg, payload, args) + device_batch = move_batch(batch, args.device) + + precisions = ( + [True, False] if args.precision == "both" + else [args.precision == "bf16"] + ) + reports = [] + for use_bf16 in precisions: + report = replay_once(module, device_batch, use_bf16) + print_report(report) + reports.append(report) + + verdict = [] + for report in reports: + offenders = [ + component for component in report.get("component_order", COMPONENTS) + if report["components"][component]["nonfinite_parameter_count"] > 0 + ] + verdict.append( + f"{report['precision']}: " + + (", ".join(offenders) if offenders else "no non-finite gradient") + ) + print("\n=== verdict ===") + for line in verdict: + print(f" {line}") + + out_path = args.json_out or args.dump.with_suffix(".replay.json") + with out_path.open("w") as handle: + json.dump( + {"metadata": metadata, "reports": reports, "verdict": verdict}, + handle, + indent=2, + default=str, + ) + print(f"\n[replay] report written to {out_path}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/compare_diag_fullcov.py b/bbflow_base/scripts/compare_diag_fullcov.py new file mode 100644 index 0000000000000000000000000000000000000000..da77186573b96433a8a7b81cefa6bd80fb11b2ca --- /dev/null +++ b/bbflow_base/scripts/compare_diag_fullcov.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python +import argparse +import pickle +from pathlib import Path + +import numpy as np +import pandas as pd + + +def load_run(path: Path, tag: str) -> pd.DataFrame: + with path.open("rb") as handle: + payload = pickle.load(handle) + + rows = [] + for name, values in payload.items(): + model_rmsf = np.asarray(values["model_rmsf"], dtype=float) + ref_rmsf = np.asarray(values["ref_rmsf"], dtype=float) + model_pairwise = float(values["model_mean_pairwise_rmsd"]) + ref_pairwise = float(values["ref_mean_pairwise_rmsd"]) + rows.append( + { + "pdb_name": name, + f"{tag}_pca_w2": float(values["md_pca_w2"]), + f"{tag}_joint_pca_w2": float(values["joint_pca_w2"]), + f"{tag}_model_pairwise": model_pairwise, + f"{tag}_ref_pairwise": ref_pairwise, + f"{tag}_pairwise_abs_error": abs(model_pairwise - ref_pairwise), + f"{tag}_model_rmsf_mean": float(model_rmsf.mean()), + f"{tag}_rmsf_mae": float(np.mean(np.abs(model_rmsf - ref_rmsf))), + } + ) + return pd.DataFrame(rows) + + +def bootstrap_ci(values, statistic, samples=10000, seed=20260709): + values = np.asarray(values, dtype=float) + rng = np.random.default_rng(seed) + estimates = np.empty(samples, dtype=float) + for index in range(samples): + draw = values[rng.integers(0, len(values), len(values))] + estimates[index] = statistic(draw) + return np.quantile(estimates, [0.025, 0.975]) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--diag", type=Path, required=True) + parser.add_argument("--fullcov", type=Path, required=True) + parser.add_argument("--output_dir", type=Path, required=True) + args = parser.parse_args() + + diag = load_run(args.diag, "diag") + fullcov = load_run(args.fullcov, "fullcov") + frame = diag.merge(fullcov, on="pdb_name", validate="one_to_one") + + frame["delta_pca_w2"] = frame.fullcov_pca_w2 - frame.diag_pca_w2 + frame["delta_joint_pca_w2"] = ( + frame.fullcov_joint_pca_w2 - frame.diag_joint_pca_w2 + ) + frame["delta_model_pairwise"] = ( + frame.fullcov_model_pairwise - frame.diag_model_pairwise + ) + frame["delta_pairwise_abs_error"] = ( + frame.fullcov_pairwise_abs_error - frame.diag_pairwise_abs_error + ) + frame["delta_model_rmsf_mean"] = ( + frame.fullcov_model_rmsf_mean - frame.diag_model_rmsf_mean + ) + frame["delta_rmsf_mae"] = frame.fullcov_rmsf_mae - frame.diag_rmsf_mae + + x = np.column_stack( + [ + np.ones(len(frame)), + frame.delta_model_pairwise, + frame.delta_model_rmsf_mean, + ] + ) + y = frame.delta_pca_w2.to_numpy() + coefficients, *_ = np.linalg.lstsq(x, y, rcond=None) + prediction = x @ coefficients + total = np.sum((y - y.mean()) ** 2) + r2 = 1.0 - np.sum((y - prediction) ** 2) / total if total > 0 else np.nan + + amplitude_change = np.sqrt( + frame.delta_model_pairwise.to_numpy() ** 2 + + frame.delta_model_rmsf_mean.to_numpy() ** 2 + ) + cutoff = float(np.quantile(amplitude_change, 0.25)) + stable = amplitude_change <= cutoff + + median_ci = bootstrap_ci(y, np.median) + win_ci = bootstrap_ci(y, lambda values: np.mean(values < 0)) + summary = pd.DataFrame( + [ + { + "n": len(frame), + "median_fullcov_minus_diag_pca_w2": np.median(y), + "median_delta_pca_ci_low": median_ci[0], + "median_delta_pca_ci_high": median_ci[1], + "fullcov_pca_win_fraction": np.mean(y < 0), + "pca_win_fraction_ci_low": win_ci[0], + "pca_win_fraction_ci_high": win_ci[1], + "median_delta_pairwise_abs_error": frame.delta_pairwise_abs_error.median(), + "median_delta_rmsf_mae": frame.delta_rmsf_mae.median(), + "pearson_delta_pca_vs_pairwise": frame.delta_pca_w2.corr( + frame.delta_model_pairwise, method="pearson" + ), + "spearman_delta_pca_vs_pairwise": frame.delta_pca_w2.corr( + frame.delta_model_pairwise, method="spearman" + ), + "amplitude_regression_r2": r2, + "stable_amplitude_cutoff": cutoff, + "stable_amplitude_n": int(stable.sum()), + "stable_amplitude_median_delta_pca": np.median(y[stable]), + "stable_amplitude_fullcov_pca_win_fraction": np.mean(y[stable] < 0), + } + ] + ) + + args.output_dir.mkdir(parents=True, exist_ok=True) + frame.sort_values("delta_pca_w2").to_csv( + args.output_dir / "diag_vs_fullcov_per_protein.csv", index=False + ) + summary.to_csv(args.output_dir / "diag_vs_fullcov_summary.csv", index=False) + + print("=== A diagonal vs B full covariance at epoch30 ===") + print(summary.T.to_string(header=False, float_format=lambda value: f"{value:.4f}")) + print("\nNegative delta means full covariance is better.") + print("\n=== strongest fullcov PCA wins ===") + columns = [ + "pdb_name", + "diag_pca_w2", + "fullcov_pca_w2", + "delta_pca_w2", + "delta_model_pairwise", + "delta_pairwise_abs_error", + ] + print(frame.nsmallest(12, "delta_pca_w2")[columns].to_string(index=False)) + print("\n=== strongest fullcov PCA losses ===") + print(frame.nlargest(12, "delta_pca_w2")[columns].to_string(index=False)) + print(f"\nSaved to: {args.output_dir}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/compare_saved_cross_cov.py b/bbflow_base/scripts/compare_saved_cross_cov.py new file mode 100644 index 0000000000000000000000000000000000000000..96a1d2a08de062f5d17ebba4e5c5d0d58ca479d9 --- /dev/null +++ b/bbflow_base/scripts/compare_saved_cross_cov.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python +import argparse +import json +from pathlib import Path +import sys + +import mdtraj +import numpy as np +import pandas as pd +import torch + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from scripts.fit_motion_template_upper_bound import load_motion_targets +from scripts.probe_condition_ensemble_cov import ensemble_motion_stats +from scripts.probe_condition_quality_vs_md import ( + evaluate_against_target, + target_for_pdb, +) + + +def load_ca(path: Path) -> torch.Tensor: + trajectory = mdtraj.load(str(path)) + ca = trajectory.topology.select("name CA") + if len(ca) == 0: + raise ValueError(f"No CA atoms in {path}") + # mdtraj uses nm; BBFlow motion targets use Angstrom. + return torch.from_numpy(trajectory.xyz[:, ca, :] * 10.0).float() + + +def evaluate_ensemble( + ensemble_path: Path, + equilibrium_path: Path, + target, + near_distance: float, +): + generated = load_ca(ensemble_path) + equilibrium = load_ca(equilibrium_path)[0] + if generated.shape[1:] != equilibrium.shape: + raise ValueError( + f"CA shape mismatch: generated={tuple(generated.shape)}, " + f"equilibrium={tuple(equilibrium.shape)}" + ) + mask = torch.ones(generated.shape[1], dtype=torch.float32) + stats = ensemble_motion_stats(generated, equilibrium, mask) + spatial_distances = torch.cdist(equilibrium, equilibrium) + return evaluate_against_target( + stats, target, mask, spatial_distances, near_distance + ) + + +def bootstrap(values, statistic, samples=10000, seed=20260709): + values = np.asarray(values, dtype=float) + rng = np.random.default_rng(seed) + estimates = np.empty(samples) + for index in range(samples): + sample = values[rng.integers(0, len(values), len(values))] + estimates[index] = statistic(sample) + return np.quantile(estimates, [0.025, 0.975]) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--csv_path", type=Path, required=True) + parser.add_argument("--atlas_root", type=Path, required=True) + parser.add_argument("--motion_target_cache_path", type=Path, required=True) + parser.add_argument("--method_a_dir", type=Path, required=True) + parser.add_argument("--method_b_dir", type=Path, required=True) + parser.add_argument("--method_a_name", default="A") + parser.add_argument("--method_b_name", default="Official") + parser.add_argument("--near_distance", type=float, default=12.0) + parser.add_argument("--output_dir", type=Path, required=True) + args = parser.parse_args() + + metadata = pd.read_csv(args.csv_path) + key = "name" if "name" in metadata.columns else metadata.columns[0] + targets = load_motion_targets(args.motion_target_cache_path) + rows = [] + + for pdb_name in metadata[key].astype(str): + equilibrium = args.atlas_root / pdb_name / f"{pdb_name}.pdb" + path_a = args.method_a_dir / pdb_name / "sampled_conformations.pdb" + path_b = args.method_b_dir / pdb_name / "sampled_conformations.pdb" + missing = [path for path in (equilibrium, path_a, path_b) if not path.exists()] + if missing: + raise FileNotFoundError(f"{pdb_name} missing files: {missing}") + + target = target_for_pdb(targets, pdb_name) + metrics_a = evaluate_ensemble( + path_a, equilibrium, target, args.near_distance + ) + metrics_b = evaluate_ensemble( + path_b, equilibrium, target, args.near_distance + ) + row = {"pdb_name": pdb_name} + for metric in ( + "far_cross_cov_corr", + "far_top10_sign_agree", + "far_cross_cov_rel_loss", + "near_cross_cov_corr", + "near_top10_sign_agree", + ): + row[f"{args.method_a_name}_{metric}"] = metrics_a[metric] + row[f"{args.method_b_name}_{metric}"] = metrics_b[metric] + row[f"delta_{metric}"] = metrics_a[metric] - metrics_b[metric] + rows.append(row) + print(f"[cross-cov] {pdb_name} done") + + frame = pd.DataFrame(rows) + summary = {} + for metric in ( + "far_cross_cov_corr", + "far_top10_sign_agree", + "far_cross_cov_rel_loss", + "near_cross_cov_corr", + "near_top10_sign_agree", + ): + delta = frame[f"delta_{metric}"].to_numpy() + lower, upper = bootstrap(delta, np.mean) + higher_is_better = not metric.endswith("_rel_loss") + wins = delta > 0 if higher_is_better else delta < 0 + summary[metric] = { + f"{args.method_a_name}_mean": float( + frame[f"{args.method_a_name}_{metric}"].mean() + ), + f"{args.method_b_name}_mean": float( + frame[f"{args.method_b_name}_{metric}"].mean() + ), + "paired_mean_delta_a_minus_b": float(delta.mean()), + "paired_mean_delta_ci95": [float(lower), float(upper)], + f"{args.method_a_name}_win_fraction": float(wins.mean()), + } + + args.output_dir.mkdir(parents=True, exist_ok=True) + frame.to_csv(args.output_dir / "per_protein_cross_cov.csv", index=False) + (args.output_dir / "summary.json").write_text( + json.dumps(summary, indent=2, sort_keys=True) + "\n" + ) + + print("\n=== paired cross-cov comparison ===") + print(json.dumps(summary, indent=2, sort_keys=True)) + print(f"\nSaved to: {args.output_dir}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/covariance_transport.py b/bbflow_base/scripts/covariance_transport.py new file mode 100644 index 0000000000000000000000000000000000000000..a68e6b407a027f3415c51212782705ba4d98db6d --- /dev/null +++ b/bbflow_base/scripts/covariance_transport.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python +""" +Marginal-preserving low-rank covariance transport (oracle + A30-mode). + +IDEA + Do NOT retrain the generator. Take BBFlow's already-sampled 20-step CA ensemble + and reshape its covariance toward a target CORRELATION structure while KEEPING + BBFlow's per-coordinate variances (the marginals) and the total variance (trace) + fixed. Only cross-correlations / principal directions change => this is + REDISTRIBUTION, not addition. RMSF (per-residue fluctuation) and mean pairwise + spread are preserved by construction; only PCA W2 / cross-cov can move. + +TWO MODES + oracle : target correlation = MD's OWN correlation. This is the UPPER BOUND and + the mechanism/side-effect validator. Run this FIRST. If oracle does not + win PCA W2 cleanly (or breaks structure), the transport idea is dead and + A30 modes are irrelevant. + a30 : target correlation built ONLY from A30's mode subspace U (8 modes), NOT + its unreliable energies. This is the deployable version, upper-bounded by + how well A30's modes generalize to test82 (empirically ~0.4 cos to MD PCs, + so expect at most a small gain). + +WHY per-residue RIGID application (structural validity) + A raw linear map on flattened CA coords can distort geometry. Instead we compute + the CA-level displacement the transport induces per frame per residue, then (for a + full-atom eval) apply that displacement RIGIDLY to every atom of that residue. + Intra-residue geometry is untouched; only inter-residue arrangement is reshaped. + This script does the CA-level transport (enough to test PCA W2 / RMSF / Pairwise + on CA). The rigid full-atom application is `apply_ca_disp_to_full_atoms` below. + +STATUS: written without a local python to test. Verify on the server with the +smoke check at the bottom (--smoke) before trusting any metric. + +Frames of reference + Covariance of a conformational ensemble is only meaningful AFTER removing global + rotation/translation. We (1) superpose every gen frame to the gen mean, (2) align + the gen mean to the ref (MD) mean so gen and MD correlations live in a COMMON + orientation, then (3) transport. Residue correspondence is by index (same protein). +""" +import argparse +import os +import numpy as np + + +# ----------------------------------------------------------------------------- IO +def load_ca_frames(pdb_path): + """Parse a multi-MODEL PDB -> [M, N, 3] of CA coords (Angstrom).""" + models, cur = [], [] + with open(pdb_path) as fh: + for ln in fh: + if ln.startswith("MODEL"): + cur = [] + elif ln.startswith("ENDMDL"): + if cur: + models.append(cur) + cur = [] + elif ln.startswith(("ATOM", "HETATM")) and ln[12:16].strip() == "CA": + cur.append([float(ln[30:38]), float(ln[38:46]), float(ln[46:54])]) + if not models and cur: + models.append(cur) + X = np.asarray(models, dtype=np.float64) # [M, N, 3] + if X.ndim != 3: + raise ValueError(f"parsed shape {X.shape} from {pdb_path}; frames differ in N?") + return X + + +def write_ca_frames(path, coords): + """Write [M, N, 3] CA coords as a minimal multi-MODEL CA-only PDB.""" + with open(path, "w") as fh: + for m, frame in enumerate(coords, 1): + fh.write(f"MODEL {m:>4d}\n") + for i, (x, y, z) in enumerate(frame, 1): + fh.write( + f"ATOM {i:>5d} CA ALA A{i:>4d} " + f"{x:8.3f}{y:8.3f}{z:8.3f} 1.00 0.00 C\n" + ) + fh.write("ENDMDL\n") + + +# ------------------------------------------------------------------ linear algebra +def kabsch(P, Q): + """Rotation R minimizing ||P R - Q|| for centered P, Q ([N,3]).""" + H = P.T @ Q + U, _, Vt = np.linalg.svd(H) + d = np.sign(np.linalg.det(Vt.T @ U.T)) + D = np.diag([1.0, 1.0, d]) + return U @ D @ Vt # apply as P @ R + + +def superpose_to_mean(X, iters=3): + """Iteratively Kabsch-superpose all frames to the running mean. Returns + aligned frames [M,N,3] and the mean [N,3] (both centered at origin).""" + Xc = X - X.mean(axis=1, keepdims=True) # remove per-frame translation + ref = Xc[0] - Xc[0].mean(0) + for _ in range(iters): + aligned = np.stack([(f - f.mean(0)) @ kabsch(f - f.mean(0), ref) for f in Xc]) + ref = aligned.mean(0) + ref = ref - ref.mean(0) + Xc = aligned + return Xc, ref + + +def symm_sqrt(C, inverse=False, eps=1e-6): + """Symmetric (inverse) square root of a PSD matrix via eigh, regularized.""" + w, V = np.linalg.eigh((C + C.T) * 0.5) + w = np.clip(w, 0.0, None) + scale = w.max() if w.size else 1.0 + w = w + eps * max(scale, 1.0) + s = 1.0 / np.sqrt(w) if inverse else np.sqrt(w) + return (V * s) @ V.T + + +def ensemble_cov(Xc_flat): + """Empirical covariance of centered [M, D] samples -> [D, D].""" + M = Xc_flat.shape[0] + return (Xc_flat.T @ Xc_flat) / max(M - 1, 1) + + +def correlation_from_cov(C, eps=1e-8): + d = np.sqrt(np.clip(np.diag(C), eps, None)) + R = C / (d[:, None] * d[None, :]) + return R + + +def target_cov(C_gen, C_ref, lam, mode, U_modes=None): + """Build C* = Dg^{1/2} [ (1-lam) R_gen + lam R_target ] Dg^{1/2}. + Dg = diag(C_gen) is KEPT (marginals preserved).""" + dg = np.clip(np.diag(C_gen), 1e-8, None) + Dg_half = np.sqrt(dg) + R_gen = correlation_from_cov(C_gen) + if mode == "oracle": + R_tgt = correlation_from_cov(C_ref) + elif mode == "a30": + # Correlation implied by the A30 mode subspace ONLY (no energies): build a + # covariance from equal-weight unit modes, then normalize to a correlation. + # U_modes: [D, K] (flattened CA modes, each column a mode over 3N coords). + if U_modes is None: + raise ValueError("mode=a30 requires U_modes [D,K]") + Un = U_modes / (np.linalg.norm(U_modes, axis=0, keepdims=True) + 1e-8) + C_modes = Un @ Un.T + R_tgt = correlation_from_cov(C_modes) + else: + raise ValueError(mode) + R_star = (1.0 - lam) * R_gen + lam * R_tgt + return (Dg_half[:, None] * R_star * Dg_half[None, :]) + + +def transport(Xc_flat, C_gen, C_star, eps=1e-6): + """CORAL / Bures whitening-then-coloring: X' has covariance ~ C_star, + marginals of C_star preserved. Xc_flat: centered [M, D].""" + W = symm_sqrt(C_gen, inverse=True, eps=eps) @ symm_sqrt(C_star, inverse=False, eps=eps) + return Xc_flat @ W # [M, D] + + +# ------------------------------------------------------------------------- driver +def run_one(gen_pdb, ref_pdb, out_pdb, lam=0.5, mode="oracle", modes_npy=None): + Xg = load_ca_frames(gen_pdb) # [Mg, N, 3] + Xr = load_ca_frames(ref_pdb) # [Mr, N, 3] (MD CA frames) + if Xg.shape[1] != Xr.shape[1]: + raise ValueError(f"residue count mismatch: gen {Xg.shape[1]} vs ref {Xr.shape[1]}") + N = Xg.shape[1] + + Xg_al, mean_g = superpose_to_mean(Xg) + Xr_al, mean_r = superpose_to_mean(Xr) + # put gen into MD's mean orientation so R_gen and R_ref are comparable + Rg2r = kabsch(mean_g, mean_r) + Xg_al = Xg_al @ Rg2r + mean_g = mean_g @ Rg2r + + Fg = Xg_al.reshape(Xg_al.shape[0], N * 3) # [Mg, 3N] centered fluct + Fr = Xr_al.reshape(Xr_al.shape[0], N * 3) + C_gen = ensemble_cov(Fg) + C_ref = ensemble_cov(Fr) + + U = None + if mode == "a30": + U = np.load(modes_npy) # expect [3N, K] or [N,3,K] + U = U.reshape(N * 3, -1) + + C_star = target_cov(C_gen, C_ref, lam, mode, U_modes=U) + Fg_t = transport(Fg, C_gen, C_star) # [Mg, 3N] + Xt = Fg_t.reshape(-1, N, 3) + mean_g[None] # re-add gen mean structure + write_ca_frames(out_pdb, Xt) + + # diagnostics (marginal/trace preservation should be ~exact) + C_out = ensemble_cov((Xt - Xt.mean(0)).reshape(len(Xt), N * 3)) + print(f"[transport] {os.path.basename(gen_pdb)} mode={mode} lam={lam}") + print(f" trace gen={np.trace(C_gen):.3f} target={np.trace(C_star):.3f} out={np.trace(C_out):.3f}") + print(f" diag L1 |gen-out| = {np.abs(np.diag(C_gen)-np.diag(C_out)).mean():.3e} (want ~0)") + return out_pdb + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--gen_pdb", required=True, help="BBFlow sampled_conformations.pdb (CA)") + ap.add_argument("--ref_pdb", required=True, help="MD reference frames as multi-MODEL CA PDB") + ap.add_argument("--out_pdb", required=True) + ap.add_argument("--lam", type=float, default=0.5) + ap.add_argument("--mode", choices=["oracle", "a30"], default="oracle") + ap.add_argument("--modes_npy", default=None, help="A30 modes [3N,K] (mode=a30)") + ap.add_argument("--smoke", action="store_true", help="print shapes/invariants only") + args = ap.parse_args() + if args.smoke: + Xg = load_ca_frames(args.gen_pdb) + print("gen frames:", Xg.shape) + Xr = load_ca_frames(args.ref_pdb) + print("ref frames:", Xr.shape) + return + run_one(args.gen_pdb, args.ref_pdb, args.out_pdb, args.lam, args.mode, args.modes_npy) + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/covariance_transport_batch.py b/bbflow_base/scripts/covariance_transport_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..16c1a83af6fd700cf1cae0c9e86bcd40e82459c4 --- /dev/null +++ b/bbflow_base/scripts/covariance_transport_batch.py @@ -0,0 +1,357 @@ +#!/usr/bin/env python +"""Batch endpoint covariance transport for BBFlow ensembles. + +This script implements the low-cost test proposed in the handoff: + +1. Start from an already sampled 20-step BBFlow endpoint ensemble. +2. Preserve that ensemble's per-coordinate variance scale. +3. Replace only part of its correlation structure with either: + - oracle MD correlation, or + - A30 learned mode-subspace correlation. +4. Write a standard ``/sampled_conformations.pdb`` directory that can + be passed directly to ``reproduction/03_evaluate.sh``. + +The output is CA-only. The official RMSF / Pairwise / PCA-W2 path reduces both +reference and model trajectories to CA coordinates, so this is sufficient for +the core table metrics. Backbone geometry side effects must still be checked +separately before making a paper claim. +""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Iterable + +import mdtraj +import numpy as np + + +def read_test_names(csv_path: Path) -> list[str]: + with csv_path.open(newline="") as handle: + reader = csv.DictReader(handle) + if reader.fieldnames is None: + raise ValueError(f"Empty CSV: {csv_path}") + name_key = "pdb_name" if "pdb_name" in reader.fieldnames else reader.fieldnames[0] + names = [str(row[name_key]).strip() for row in reader if str(row[name_key]).strip()] + if not names: + raise ValueError(f"No protein names found in {csv_path}") + return names + + +def pdb_name_variants(name: str) -> Iterable[str]: + yield name + if "_" in name: + yield name.replace("_", "") + elif len(name) == 5: + yield f"{name[:4]}_{name[4]}" + + +def load_ca_pdb_models(pdb_path: Path) -> np.ndarray: + """Load a multi-model PDB and return CA coordinates in Angstrom, [M,N,3].""" + traj = mdtraj.load(str(pdb_path)) + ca = traj.topology.select("name CA") + if ca.size == 0: + raise ValueError(f"No CA atoms in {pdb_path}") + return np.asarray(traj.xyz[:, ca, :] * 10.0, dtype=np.float64) + + +def load_md_ca_frames(atlas_root: Path, pdb_name: str, stride: int, max_frames: int, seed: int) -> np.ndarray: + entry = atlas_root / pdb_name + top_path = entry / f"{pdb_name}.pdb" + if not top_path.exists(): + raise FileNotFoundError(f"Missing MD topology PDB: {top_path}") + top = mdtraj.load(str(top_path)) + ca = top.topology.select("name CA") + if ca.size == 0: + raise ValueError(f"No CA atoms in {top_path}") + + frames = [] + for replica in (1, 2, 3): + xtc_path = entry / f"{pdb_name}_R{replica}.xtc" + if not xtc_path.exists(): + raise FileNotFoundError(f"Missing MD trajectory: {xtc_path}") + traj = mdtraj.load(str(xtc_path), top=str(top_path), atom_indices=ca, stride=max(1, stride)) + frames.append(np.asarray(traj.xyz * 10.0, dtype=np.float64)) + out = np.concatenate(frames, axis=0) + + if max_frames and out.shape[0] > max_frames: + rng = np.random.default_rng(seed) + indices = np.sort(rng.choice(out.shape[0], size=max_frames, replace=False)) + out = out[indices] + return out + + +def write_ca_pdb(path: Path, coords: np.ndarray) -> None: + """Write [M,N,3] Angstrom CA coordinates as multi-model PDB.""" + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w") as handle: + for model_idx, frame in enumerate(coords, start=1): + handle.write(f"MODEL {model_idx:>4d}\n") + for residue_idx, (x, y, z) in enumerate(frame, start=1): + atom_serial = ((residue_idx - 1) % 99999) + 1 + residue_serial = ((residue_idx - 1) % 9999) + 1 + handle.write( + f"ATOM {atom_serial:>5d} CA ALA A{residue_serial:>4d} " + f"{x:8.3f}{y:8.3f}{z:8.3f} 1.00 0.00 C\n" + ) + handle.write("ENDMDL\n") + handle.write("END\n") + + +def kabsch(P: np.ndarray, Q: np.ndarray) -> np.ndarray: + H = P.T @ Q + U, _, Vt = np.linalg.svd(H, full_matrices=False) + det = np.linalg.det(Vt.T @ U.T) + sign = 1.0 if det >= 0.0 else -1.0 + D = np.diag([1.0, 1.0, sign]) + R = U @ D @ Vt + if np.linalg.det(R) < 0.0: + raise ValueError("Kabsch produced a reflection") + return R + + +def superpose_to_mean(X: np.ndarray, iterations: int = 3) -> tuple[np.ndarray, np.ndarray]: + """Remove global translation/rotation and return centered frames and mean.""" + Xc = X - X.mean(axis=1, keepdims=True) + ref = Xc[0] - Xc[0].mean(axis=0, keepdims=True) + aligned = Xc + for _ in range(iterations): + aligned = np.stack( + [ + (frame - frame.mean(axis=0, keepdims=True)) + @ kabsch(frame - frame.mean(axis=0, keepdims=True), ref) + for frame in aligned + ], + axis=0, + ) + ref = aligned.mean(axis=0) + ref = ref - ref.mean(axis=0, keepdims=True) + return aligned, ref + + +def whiten_samples(X: np.ndarray, eps: float) -> np.ndarray: + """Return sample coordinates with empirical covariance approximately I.""" + sample_count = X.shape[0] + U, S, _ = np.linalg.svd(X, full_matrices=False) + rank = int(np.sum(S > eps * max(float(S.max()), 1.0))) + if rank < 1: + raise ValueError("Generated ensemble has zero covariance rank") + return U[:, :rank] * np.sqrt(max(sample_count - 1, 1)) + + +def color_from_factor(white: np.ndarray, target_factor: np.ndarray, eps: float) -> np.ndarray: + """Color whitened samples with covariance encoded by factor L, C=L.T@L.""" + _, S, Vt = np.linalg.svd(target_factor, full_matrices=False) + rank = min(white.shape[1], int(np.sum(S > eps * max(float(S.max()), 1.0)))) + if rank < 1: + raise ValueError("Target covariance factor has zero rank") + return (white[:, :rank] * S[:rank]) @ Vt[:rank, :] + + +def match_marginal_variances(X: np.ndarray, target_diag: np.ndarray, eps: float) -> np.ndarray: + """Rescale each coordinate so the finite-sample diagonal matches target_diag. + + The transport target can have rank above the available generated ensemble + rank. After truncating back to at most M-1 sample directions, the diagonal is + no longer guaranteed to match. This final coordinate-wise calibration restores + the central promise of this diagnostic: preserve BBFlow endpoint marginals and + trace, while only changing correlations as much as the finite ensemble allows. + """ + X = X - X.mean(axis=0, keepdims=True) + current_diag = covariance_diag(X) + scale = np.sqrt(np.clip(target_diag, eps, None) / np.clip(current_diag, eps, None)) + return X * scale[None, :] + + +def covariance_diag(X: np.ndarray) -> np.ndarray: + return np.var(X, axis=0, ddof=1) + + +def oracle_target_factor(Fg: np.ndarray, Fr: np.ndarray, lam: float, eps: float) -> np.ndarray: + """Factor for Dg^1/2 [(1-lam)R_gen + lam R_MD] Dg^1/2.""" + gen_factor = Fg / np.sqrt(max(Fg.shape[0] - 1, 1)) + ref_factor = Fr / np.sqrt(max(Fr.shape[0] - 1, 1)) + dg = np.clip(covariance_diag(Fg), eps, None) + dr = np.clip(covariance_diag(Fr), eps, None) + ref_scaled = ref_factor * np.sqrt(dg / dr)[None, :] + return np.concatenate( + [np.sqrt(max(1.0 - lam, 0.0)) * gen_factor, np.sqrt(max(lam, 0.0)) * ref_scaled], + axis=0, + ) + + +def load_modes(modes_dir: Path, pdb_name: str, num_res: int) -> np.ndarray: + for variant in pdb_name_variants(pdb_name): + path = modes_dir / f"{variant}.npy" + if path.exists(): + modes = np.load(path) + break + else: + raise FileNotFoundError(f"Missing A30 mode file for {pdb_name} in {modes_dir}") + + modes = np.asarray(modes, dtype=np.float64) + if modes.shape[:2] == (num_res, 3): + # [N,3,K] + modes = np.transpose(modes, (0, 2, 1)) + if modes.shape[0] != num_res or modes.ndim != 3: + raise ValueError(f"Expected modes [N,K,3] or [N,3,K] for {pdb_name}, got {modes.shape}") + return np.transpose(modes, (0, 2, 1)).reshape(num_res * 3, modes.shape[1]) + + +def a30_target_factor(Fg: np.ndarray, modes: np.ndarray, lam: float, eps: float) -> np.ndarray: + """Factor for Dg^1/2 [(1-lam)R_gen + lam R_A30] Dg^1/2.""" + gen_factor = Fg / np.sqrt(max(Fg.shape[0] - 1, 1)) + mode_cols = modes / np.linalg.norm(modes, axis=0, keepdims=True).clip(min=eps) + mode_diag = np.sum(mode_cols * mode_cols, axis=1).clip(min=eps) + dg = np.clip(covariance_diag(Fg), eps, None) + mode_factor = (mode_cols * np.sqrt(dg / mode_diag)[:, None]).T + return np.concatenate( + [np.sqrt(max(1.0 - lam, 0.0)) * gen_factor, np.sqrt(max(lam, 0.0)) * mode_factor], + axis=0, + ) + + +def transport_one( + pdb_name: str, + ensemble_dir: Path, + atlas_root: Path, + out_dir: Path, + mode: str, + lam: float, + stride: int, + max_md_frames: int, + seed: int, + modes_dir: Path | None, + eps: float, + overwrite: bool, +) -> dict[str, float | str | int]: + gen_pdb = ensemble_dir / pdb_name / "sampled_conformations.pdb" + out_pdb = out_dir / pdb_name / "sampled_conformations.pdb" + if out_pdb.exists() and not overwrite: + return {"pdb_name": pdb_name, "status": "skipped_exists"} + if not gen_pdb.exists(): + return {"pdb_name": pdb_name, "status": "missing_gen_pdb", "path": str(gen_pdb)} + + Xg = load_ca_pdb_models(gen_pdb) + Xr = load_md_ca_frames(atlas_root, pdb_name, stride=stride, max_frames=max_md_frames, seed=seed) + if Xg.shape[1] != Xr.shape[1]: + raise ValueError(f"{pdb_name}: residue mismatch gen={Xg.shape[1]} md={Xr.shape[1]}") + + Xg_aligned, mean_g = superpose_to_mean(Xg) + Xr_aligned, mean_r = superpose_to_mean(Xr) + Rg2r = kabsch(mean_g, mean_r) + Xg_aligned = Xg_aligned @ Rg2r + mean_g = mean_g @ Rg2r + + num_res = Xg.shape[1] + Fg = Xg_aligned.reshape(Xg_aligned.shape[0], num_res * 3) + Fr = Xr_aligned.reshape(Xr_aligned.shape[0], num_res * 3) + white = whiten_samples(Fg, eps=eps) + + if mode == "oracle": + target_factor = oracle_target_factor(Fg, Fr, lam=lam, eps=eps) + elif mode == "a30": + if modes_dir is None: + raise ValueError("--modes_dir is required for --mode a30") + modes = load_modes(modes_dir, pdb_name, num_res=num_res) + target_factor = a30_target_factor(Fg, modes, lam=lam, eps=eps) + else: + raise ValueError(mode) + + Ft = color_from_factor(white, target_factor, eps=eps) + Ft = match_marginal_variances(Ft, covariance_diag(Fg), eps=eps) + Xt = Ft.reshape(Fg.shape[0], num_res, 3) + mean_g[None, :, :] + write_ca_pdb(out_pdb, Xt) + + diag_gen = covariance_diag(Fg) + diag_out = covariance_diag(Ft) + return { + "pdb_name": pdb_name, + "status": "ok", + "num_res": int(num_res), + "num_gen_frames": int(Xg.shape[0]), + "num_md_frames": int(Xr.shape[0]), + "trace_gen": float(np.sum(diag_gen)), + "trace_out": float(np.sum(diag_out)), + "diag_l1_gen_out": float(np.mean(np.abs(diag_gen - diag_out))), + "diag_rel_l1_gen_out": float(np.mean(np.abs(diag_gen - diag_out)) / max(np.mean(diag_gen), eps)), + } + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--ensemble_dir", required=True, type=Path) + parser.add_argument("--atlas_root", required=True, type=Path) + parser.add_argument("--test_csv", required=True, type=Path) + parser.add_argument("--out_dir", required=True, type=Path) + parser.add_argument("--mode", choices=["oracle", "a30"], default="oracle") + parser.add_argument("--lam", type=float, default=0.5) + parser.add_argument("--modes_dir", type=Path, default=None) + parser.add_argument("--md_stride", type=int, default=1) + parser.add_argument("--max_md_frames", type=int, default=0, help="0 means all MD frames after stride") + parser.add_argument("--seed", type=int, default=123) + parser.add_argument("--eps", type=float, default=1e-8) + parser.add_argument("--overwrite", action="store_true") + parser.add_argument("--limit", type=int, default=0, help="0 means all proteins") + return parser.parse_args() + + +def main() -> None: + args = parse_args() + if not args.ensemble_dir.exists(): + raise FileNotFoundError(args.ensemble_dir) + if not args.atlas_root.exists(): + raise FileNotFoundError(args.atlas_root) + if not args.test_csv.exists(): + raise FileNotFoundError(args.test_csv) + if args.mode == "a30" and (args.modes_dir is None or not args.modes_dir.exists()): + raise FileNotFoundError(f"--mode a30 requires existing --modes_dir, got {args.modes_dir}") + + names = read_test_names(args.test_csv) + if args.limit > 0: + names = names[: args.limit] + + args.out_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for idx, name in enumerate(names, start=1): + print(f"[{idx}/{len(names)}] {name} mode={args.mode} lambda={args.lam}") + row = transport_one( + pdb_name=name, + ensemble_dir=args.ensemble_dir, + atlas_root=args.atlas_root, + out_dir=args.out_dir, + mode=args.mode, + lam=args.lam, + stride=args.md_stride, + max_md_frames=args.max_md_frames, + seed=args.seed + idx, + modes_dir=args.modes_dir, + eps=args.eps, + overwrite=args.overwrite, + ) + rows.append(row) + print(json.dumps(row, sort_keys=True)) + + summary_path = args.out_dir / "transport_summary.json" + with summary_path.open("w") as handle: + json.dump( + { + "mode": args.mode, + "lambda": args.lam, + "ensemble_dir": str(args.ensemble_dir), + "atlas_root": str(args.atlas_root), + "test_csv": str(args.test_csv), + "rows": rows, + }, + handle, + indent=2, + sort_keys=True, + ) + print(f"Saved: {summary_path}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/diagnose_condition_interface.py b/bbflow_base/scripts/diagnose_condition_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..b1e604b4fe8716be07ba5be1cd55c851919e16c0 --- /dev/null +++ b/bbflow_base/scripts/diagnose_condition_interface.py @@ -0,0 +1,645 @@ +#!/usr/bin/env python +"""Diagnose the interface between projected MD coefficients and sampled q. + +This is a diagnostic script only. It does not train, select checkpoints, or use +MD-derived quantities as an inference-time method. The MD frames are used here +only as held-out measurement labels to answer three questions: + +1. controllability: if we feed clean frame-projected c*, does the generator move + toward the matching MD frame? +2. robustness: if clean c* is perturbed toward q-like noise, how quickly does + the generator lose the target? +3. qdist: does q(c|x_eq) match the empirical distribution of frame-projected c*? +""" +import argparse +import json +from pathlib import Path +import sys + +import mdtraj +import numpy as np +import pandas as pd +import torch +from omegaconf import OmegaConf + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from bbflow.data.interpolant_bbflow import InterpolantBBFlow +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow +from bbflow.models.bbflow_module import BBFlowModule + + +def load_module(ckpt_path, device, num_timesteps): + ckpt_path = Path(ckpt_path) + cfg_path = ckpt_path.with_name("config.yaml") + if not cfg_path.exists(): + raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}") + + infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(cfg_path) + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.inference.interpolant.use_tqdm = False + cfg.inference.interpolant.rots.sample_schedule = ckpt_cfg.interpolant.rots.sample_schedule + cfg.inference.interpolant.trans.sample_schedule = ckpt_cfg.interpolant.trans.sample_schedule + cfg.model.embed = ckpt_cfg.model.embed + if num_timesteps is not None: + cfg.inference.interpolant.rots.num_timesteps = int(num_timesteps) + cfg.inference.interpolant.trans.num_timesteps = int(num_timesteps) + + module = BBFlowModule(cfg) + checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False) + current = module.state_dict() + compatible = { + key: value + for key, value in checkpoint["state_dict"].items() + if key in current and current[key].shape == value.shape + } + missing, unexpected = module.load_state_dict(compatible, strict=False) + module.to(device) + module.eval() + + interpolant = InterpolantBBFlow(cfg.inference.interpolant) + interpolant.set_device(device) + return module, interpolant, { + "loaded": len(compatible), + "missing": len(missing), + "unexpected": len(unexpected), + } + + +def move_item_to_device(item, device): + out = {} + for key, value in item.items(): + if torch.is_tensor(value): + out[key] = value[None].to(device) + else: + out[key] = value + return out + + +def select_protein_indices(df, dataset, pdb_names, num_proteins, max_len): + if pdb_names: + wanted = [name.strip() for name in pdb_names.split(",") if name.strip()] + by_name = {str(name): idx for idx, name in enumerate(dataset.pdb_names)} + missing = [name for name in wanted if name not in by_name] + if missing: + raise ValueError(f"pdb_names not found in csv: {missing}") + return [by_name[name] for name in wanted] + + candidates = list(range(len(df))) + if "modeled_seq_len" in df.columns: + candidates = [ + idx for idx in candidates + if int(df.iloc[idx]["modeled_seq_len"]) <= int(max_len) + ] + candidates = sorted(candidates, key=lambda idx: int(df.iloc[idx]["modeled_seq_len"])) + return candidates[: int(num_proteins)] + + +def infer_num_conformations(row): + for key in [ + "num_conformations", + "n_conformations", + "num_frames", + "n_frames", + "traj_num_frames", + ]: + if key in row and pd.notna(row[key]): + return int(row[key]) + + if "folder" in row and pd.notna(row["folder"]): + folder = Path(str(row["folder"])) + elif "pdb_path" in row and pd.notna(row["pdb_path"]): + folder = Path(str(row["pdb_path"])).parent + else: + folder = None + name = str(row["name"]) if "name" in row else str(row.get("pdb_name", "")) + if folder is not None and name: + traj_path = folder / f"{name}_R1.xtc" + if traj_path.exists(): + try: + with mdtraj.open(str(traj_path)) as handle: + if hasattr(handle, "n_frames"): + return int(handle.n_frames) + return int(len(handle)) + except Exception: + pass + return None + + +def frame_indices_for_row(row, num_frames): + total = infer_num_conformations(row) + if total is None: + name = str(row["name"]) if "name" in row else str(row.get("pdb_name", "")) + if "folder" in row and pd.notna(row["folder"]): + folder = str(row["folder"]) + elif "pdb_path" in row and pd.notna(row["pdb_path"]): + folder = str(Path(str(row["pdb_path"])).parent) + else: + folder = "" + raise RuntimeError( + "Cannot determine the number of MD frames for " + f"{name}. CSV has no frame-count column and {folder}/{name}_R1.xtc " + "could not be opened. Refusing to use guessed frame indices." + ) + if total <= 1: + return [0] + # Avoid frame 0 only; spread across the trajectory. + return sorted(set(np.linspace(0, total - 1, int(num_frames), dtype=int).tolist())) + + +def ca_from_trans(trans): + return trans.detach().float() + + +def rmsd_to_target(ca, target): + target = target.to(device=ca.device, dtype=ca.dtype) + diff = ca.float() - target.float()[None] + return torch.sqrt(diff.square().mean(dim=(1, 2)).clamp_min(0.0)) + + +def pairwise_target_rmsd(a, b): + b = b.to(device=a.device, dtype=a.dtype) + return float(torch.sqrt((a.float() - b.float()).square().mean()).detach().cpu().item()) + + +def flattened_cosine(a, b): + a = a.detach().float().reshape(-1) + b = b.detach().float().reshape(-1).to(device=a.device) + denom = a.norm().clamp_min(1e-8) * b.norm().clamp_min(1e-8) + return float((a * b).sum().div(denom).detach().cpu().item()) + + +def norm_ratio(a, b): + a = a.detach().float().reshape(-1) + b = b.detach().float().reshape(-1).to(device=a.device) + return float((a.norm() / b.norm().clamp_min(1e-8)).detach().cpu().item()) + + +def repeat_condition(module, condition, batch_size): + return module.latent_encoder.repeat_condition(condition, batch_size) + + +def clone_condition(condition): + return { + key: value.clone() if torch.is_tensor(value) else value + for key, value in condition.items() + } + + +def q_marginal_stats(module, prior_condition): + second = module.latent_encoder.mixture_second_moment(prior_condition).float() + logits = prior_condition["mixture_logits"].float() + probs = torch.softmax(logits, dim=-1) + mu = prior_condition["mixture_mu"].float() + mean = torch.einsum("bm,bmk->bk", probs, mu) + var = torch.diagonal(second, dim1=-2, dim2=-1) - mean.square() + return mean, var.clamp_min(1e-8), second + + +def build_cstar_condition(module, item, prior_condition, mean_disp=None): + return module.latent_encoder.frame_condition_from_projection( + item["trans_1"], + item["trans_equilibrium"], + item["rotmats_equilibrium"], + torch.ones_like(item["trans_equilibrium"][..., 0]), + prior_condition, + mean_disp=mean_disp, + ) + + +def mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device): + disps = [] + for frame_id in frame_ids: + row = dataset.csv.iloc[protein_idx] + item = move_item_to_device(dataset[(protein_idx, 0, int(frame_id))], device) + disp = module.latent_encoder.relative_displacement( + item["trans_1"].float(), + item["trans_equilibrium"].float(), + torch.ones_like(item["trans_equilibrium"][..., 0]), + ) + disps.append(disp) + return torch.cat(disps, dim=0).mean(dim=0, keepdim=True) + + +def sample_final_ca(module, interpolant, item, condition, num_samples, seed, final_only=True): + device = item["trans_equilibrium"].device + _, num_res = item["trans_equilibrium"].shape[:2] + torch.manual_seed(int(seed)) + np.random.seed(int(seed) % (2**32 - 1)) + z = repeat_condition(module, condition, int(num_samples)) + with torch.no_grad(): + atom37_traj, _, _ = interpolant.sample( + int(num_samples), + int(num_res), + module.model, + item["trans_equilibrium"].repeat(int(num_samples), 1, 1), + item["rotmats_equilibrium"].repeat(int(num_samples), 1, 1, 1), + item["seq"].repeat(int(num_samples), 1, 1), + z=z, + return_trajectory=not final_only, + cache_static_features=True, + ) + final_atom37 = torch.stack(atom37_traj, dim=1)[:, -1] + return final_atom37[:, :, 1, :].detach().float() + + +def run_qdist(args, module, dataset, indices, device): + rows = [] + for protein_idx in indices: + row = dataset.csv.iloc[protein_idx] + frame_ids = frame_indices_for_row(row, args.num_frames) + eq_item = move_item_to_device(dataset[(protein_idx, 0, frame_ids[0])], device) + res_mask = torch.ones_like(eq_item["trans_equilibrium"][..., 0]) + with torch.no_grad(): + prior, _ = module.latent_encoder.forward_prior( + eq_item["trans_equilibrium"], + eq_item["rotmats_equilibrium"], + eq_item["seq"], + res_mask, + ) + mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device) + cstars = [] + for frame_id in frame_ids: + item = move_item_to_device(dataset[(protein_idx, 0, int(frame_id))], device) + _, coeff = build_cstar_condition(module, item, prior, mean_disp=mean_disp) + cstars.append(coeff.detach().float()) + cstar = torch.cat(cstars, dim=0) + q_mean, q_var, _ = q_marginal_stats(module, prior) + q_condition = repeat_condition(module, prior, max(args.num_q_samples, 2)) + q_coeff, _ = module.latent_encoder.sample_coefficients_from_q(q_condition) + q_coeff = q_coeff.detach().float() + + cstar_mean = cstar.mean(dim=0) + cstar_var = cstar.var(dim=0, unbiased=False).clamp_min(1e-8) + rows.append({ + "pdb_name": str(row["name"]), + "num_res": int(eq_item["trans_equilibrium"].shape[1]), + "num_frames": int(cstar.shape[0]), + "cstar_norm_mean": float(cstar.norm(dim=-1).mean().cpu()), + "q_norm_mean": float(q_coeff.norm(dim=-1).mean().cpu()), + "q_over_cstar_norm_mean": float((q_coeff.norm(dim=-1).mean() / cstar.norm(dim=-1).mean().clamp_min(1e-8)).cpu()), + "diag_var_rel_l1": float(((q_var[0] - cstar_var).abs().mean() / cstar_var.abs().mean().clamp_min(1e-8)).cpu()), + "mean_rel_l2": float(((q_mean[0] - cstar_mean).norm() / cstar_mean.norm().clamp_min(1e-8)).cpu()), + "q_nll_on_cstar": float(module.latent_encoder.mixture_nll(repeat_condition(module, prior, cstar.shape[0]), cstar).detach().cpu()), + }) + return pd.DataFrame(rows) + + +def run_controllability(args, module, interpolant, dataset, indices, device): + rows = [] + for protein_idx in indices: + row = dataset.csv.iloc[protein_idx] + frame_ids = frame_indices_for_row(row, max(args.num_frames, 2)) + if len(frame_ids) < 2: + continue + a_id, b_id = int(frame_ids[0]), int(frame_ids[-1]) + a_item = move_item_to_device(dataset[(protein_idx, 0, a_id)], device) + b_item = move_item_to_device(dataset[(protein_idx, 0, b_id)], device) + res_mask = torch.ones_like(a_item["trans_equilibrium"][..., 0]) + with torch.no_grad(): + prior, _ = module.latent_encoder.forward_prior( + a_item["trans_equilibrium"], + a_item["rotmats_equilibrium"], + a_item["seq"], + res_mask, + ) + mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device) + cond_a, coeff_a = build_cstar_condition(module, a_item, prior, mean_disp=mean_disp) + cond_b, coeff_b = build_cstar_condition(module, b_item, prior, mean_disp=mean_disp) + ca_a = ca_from_trans(a_item["trans_1"][0]) + ca_b = ca_from_trans(b_item["trans_1"][0]) + gen_a = sample_final_ca(module, interpolant, a_item, cond_a, args.samples_per_condition, args.seed, args.final_only) + gen_b = sample_final_ca(module, interpolant, a_item, cond_b, args.samples_per_condition, args.seed, args.final_only) + a_to_a = rmsd_to_target(gen_a, ca_a) + a_to_b = rmsd_to_target(gen_a, ca_b) + b_to_a = rmsd_to_target(gen_b, ca_a) + b_to_b = rmsd_to_target(gen_b, ca_b) + rows.append({ + "pdb_name": str(row["name"]), + "num_res": int(a_item["trans_equilibrium"].shape[1]), + "frame_a": a_id, + "frame_b": b_id, + "target_pair_rmsd": pairwise_target_rmsd(ca_a, ca_b), + "coeff_pair_l2": float((coeff_a - coeff_b).norm().detach().cpu()), + "a_condition_correct_fraction": float((a_to_a < a_to_b).float().mean().cpu()), + "b_condition_correct_fraction": float((b_to_b < b_to_a).float().mean().cpu()), + "mean_correct_fraction": float(torch.cat([(a_to_a < a_to_b).float(), (b_to_b < b_to_a).float()]).mean().cpu()), + "a_margin_rmsd_b_minus_a": float((a_to_b - a_to_a).mean().cpu()), + "b_margin_rmsd_a_minus_b": float((b_to_a - b_to_b).mean().cpu()), + "gen_centroid_pair_rmsd": pairwise_target_rmsd(gen_a.mean(dim=0), gen_b.mean(dim=0)), + }) + return pd.DataFrame(rows) + + +def project_generated_coefficients(module, trans_gen, item, prior, mean_disp): + device = trans_gen.device + trans_eq = item["trans_equilibrium"].to(device=device, dtype=trans_gen.dtype) + res_mask = torch.ones_like(trans_eq[..., 0], device=device) + u_global = prior["u_global"].to(device=device, dtype=trans_gen.dtype) + disp = module.latent_encoder.relative_displacement( + trans_gen.float(), + trans_eq.float(), + res_mask, + ) + disp = (disp - mean_disp.to(device=disp.device, dtype=disp.dtype)) * res_mask.float()[:, :, None] + return module.latent_encoder.project_displacement_lstsq( + disp, + u_global, + res_mask, + ridge=module.latent_encoder.q_lstsq_ridge, + detach_modes=True, + ) + + +def choose_matched_distance_pair(candidates): + """Pick frames with similar ||x-x_eq|| but large c*/target separation.""" + best = None + for i in range(len(candidates)): + for j in range(i + 1, len(candidates)): + a, b = candidates[i], candidates[j] + dist_gap = abs(a["eq_rmsd"] - b["eq_rmsd"]) + dist_scale = max(a["eq_rmsd"], b["eq_rmsd"], 1e-8) + dist_rel_gap = dist_gap / dist_scale + if dist_rel_gap > 0.15: + continue + coeff_gap = float((a["coeff"] - b["coeff"]).norm().detach().cpu().item()) + target_gap = pairwise_target_rmsd(a["trans_1"], b["trans_1"]) + score = coeff_gap * target_gap / (1.0 + 10.0 * dist_rel_gap) + row = { + "i": i, + "j": j, + "score": score, + "eq_rmsd_gap": dist_gap, + "eq_rmsd_rel_gap": dist_rel_gap, + "coeff_pair_l2": coeff_gap, + "target_pair_rmsd": target_gap, + } + if best is None or score > best["score"]: + best = row + if best is not None: + return best + + # If no pair passes the strict 15% distance match, still return the least + # biased high-separation pair and record the larger rel gap in the output. + for i in range(len(candidates)): + for j in range(i + 1, len(candidates)): + a, b = candidates[i], candidates[j] + dist_gap = abs(a["eq_rmsd"] - b["eq_rmsd"]) + dist_scale = max(a["eq_rmsd"], b["eq_rmsd"], 1e-8) + dist_rel_gap = dist_gap / dist_scale + coeff_gap = float((a["coeff"] - b["coeff"]).norm().detach().cpu().item()) + target_gap = pairwise_target_rmsd(a["trans_1"], b["trans_1"]) + score = coeff_gap * target_gap / (1.0 + 10.0 * dist_rel_gap) + row = { + "i": i, + "j": j, + "score": score, + "eq_rmsd_gap": dist_gap, + "eq_rmsd_rel_gap": dist_rel_gap, + "coeff_pair_l2": coeff_gap, + "target_pair_rmsd": target_gap, + } + if best is None or score > best["score"]: + best = row + return best + + +def run_matched_controllability(args, module, interpolant, dataset, indices, device): + rows = [] + for protein_idx in indices: + row = dataset.csv.iloc[protein_idx] + frame_ids = frame_indices_for_row(row, args.num_frames) + if len(frame_ids) < 2: + continue + eq_item = move_item_to_device(dataset[(protein_idx, 0, int(frame_ids[0]))], device) + res_mask = torch.ones_like(eq_item["trans_equilibrium"][..., 0]) + with torch.no_grad(): + prior, _ = module.latent_encoder.forward_prior( + eq_item["trans_equilibrium"], + eq_item["rotmats_equilibrium"], + eq_item["seq"], + res_mask, + ) + mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device) + candidates = [] + for frame_id in frame_ids: + item = move_item_to_device(dataset[(protein_idx, 0, int(frame_id))], device) + cond, coeff = build_cstar_condition(module, item, prior, mean_disp=mean_disp) + trans_1 = item["trans_1"][0].detach().float() + trans_eq = item["trans_equilibrium"][0].detach().float() + candidates.append({ + "frame_id": int(frame_id), + "item": item, + "condition": cond, + "coeff": coeff.detach().float(), + "trans_1": trans_1, + "eq_rmsd": pairwise_target_rmsd(trans_1, trans_eq), + }) + pair = choose_matched_distance_pair(candidates) + if pair is None: + continue + a = candidates[pair["i"]] + b = candidates[pair["j"]] + gen_a = sample_final_ca( + module, interpolant, a["item"], a["condition"], + args.samples_per_condition, args.seed, args.final_only, + ) + gen_b = sample_final_ca( + module, interpolant, b["item"], b["condition"], + args.samples_per_condition, args.seed, args.final_only, + ) + mean_gen_a = gen_a.mean(dim=0, keepdim=True) + mean_gen_b = gen_b.mean(dim=0, keepdim=True) + generated_delta = mean_gen_b[0] - mean_gen_a[0] + target_delta = b["trans_1"].to(generated_delta.device) - a["trans_1"].to(generated_delta.device) + + coeff_gen_a = project_generated_coefficients( + module, mean_gen_a, a["item"], prior, mean_disp + ) + coeff_gen_b = project_generated_coefficients( + module, mean_gen_b, b["item"], prior, mean_disp + ) + a_coeff = a["coeff"].to(device=coeff_gen_a.device, dtype=coeff_gen_a.dtype) + b_coeff = b["coeff"].to(device=coeff_gen_b.device, dtype=coeff_gen_b.dtype) + coeff_gen_delta = coeff_gen_b - coeff_gen_a + coeff_delta = b_coeff - a_coeff + + cycle_a = float(((coeff_gen_a - a_coeff).norm() / a_coeff.norm().clamp_min(1e-8)).detach().cpu().item()) + cycle_b = float(((coeff_gen_b - b_coeff).norm() / b_coeff.norm().clamp_min(1e-8)).detach().cpu().item()) + rows.append({ + "pdb_name": str(row["name"]), + "num_res": int(eq_item["trans_equilibrium"].shape[1]), + "frame_a": int(a["frame_id"]), + "frame_b": int(b["frame_id"]), + "eq_rmsd_a": float(a["eq_rmsd"]), + "eq_rmsd_b": float(b["eq_rmsd"]), + "eq_rmsd_rel_gap": float(pair["eq_rmsd_rel_gap"]), + "target_pair_rmsd": float(pair["target_pair_rmsd"]), + "coeff_pair_l2": float(pair["coeff_pair_l2"]), + "generated_pair_rmsd": pairwise_target_rmsd(mean_gen_a[0], mean_gen_b[0]), + "direction_score": flattened_cosine(generated_delta, target_delta), + "gain_score": norm_ratio(generated_delta, target_delta), + "coeff_direction_score": flattened_cosine(coeff_gen_delta, coeff_delta), + "coeff_gain_score": norm_ratio(coeff_gen_delta, coeff_delta), + "cycle_error_a": cycle_a, + "cycle_error_b": cycle_b, + "cycle_error_mean": 0.5 * (cycle_a + cycle_b), + }) + return pd.DataFrame(rows) + + +def perturb_condition_coefficients(module, prior, base_coeff, q_var, rotmats_eq, res_mask, sigma, seed): + gen = torch.Generator(device=base_coeff.device) + gen.manual_seed(int(seed)) + noise = torch.randn(base_coeff.shape, generator=gen, device=base_coeff.device) + coeff = base_coeff.float() + float(sigma) * torch.sqrt(q_var).to(base_coeff.device) * noise + return module.latent_encoder.condition_from_mode_coefficients( + prior["u_global"], + coeff, + rotmats_eq, + res_mask, + extra={ + key: prior[key] + for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"] + if key in prior + }, + ) + + +def run_robustness(args, module, interpolant, dataset, indices, device): + rows = [] + sigmas = [float(x) for x in args.sigmas.split(",") if x.strip()] + for protein_idx in indices: + row = dataset.csv.iloc[protein_idx] + frame_ids = frame_indices_for_row(row, args.num_frames) + target_id = int(frame_ids[len(frame_ids) // 2]) + item = move_item_to_device(dataset[(protein_idx, 0, target_id)], device) + res_mask = torch.ones_like(item["trans_equilibrium"][..., 0]) + with torch.no_grad(): + prior, _ = module.latent_encoder.forward_prior( + item["trans_equilibrium"], + item["rotmats_equilibrium"], + item["seq"], + res_mask, + ) + mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device) + clean_cond, coeff = build_cstar_condition(module, item, prior, mean_disp=mean_disp) + _, q_var, _ = q_marginal_stats(module, prior) + target = ca_from_trans(item["trans_1"][0]) + clean_gen = sample_final_ca(module, interpolant, item, clean_cond, args.samples_per_condition, args.seed, args.final_only) + clean_rmsd = rmsd_to_target(clean_gen, target).mean() + for sigma in sigmas: + if sigma == 0.0: + cond = clean_cond + else: + cond = perturb_condition_coefficients( + module, + prior, + coeff, + q_var, + item["rotmats_equilibrium"], + res_mask, + sigma, + args.seed + int(1000 * sigma) + protein_idx, + ) + gen = sample_final_ca(module, interpolant, item, cond, args.samples_per_condition, args.seed, args.final_only) + rows.append({ + "pdb_name": str(row["name"]), + "num_res": int(item["trans_equilibrium"].shape[1]), + "frame": target_id, + "sigma": sigma, + "target_rmsd": float(rmsd_to_target(gen, target).mean().cpu()), + "target_rmsd_delta_vs_clean": float((rmsd_to_target(gen, target).mean() - clean_rmsd).cpu()), + "centroid_drift_from_clean": pairwise_target_rmsd(gen.mean(dim=0), clean_gen.mean(dim=0)), + }) + return pd.DataFrame(rows) + + +def summarize(df, task): + numeric = df.select_dtypes(include=[np.number]) + out = {"task": task, "n_rows": int(len(df))} + for col in numeric.columns: + out[f"{col}_mean"] = float(numeric[col].mean()) + out[f"{col}_median"] = float(numeric[col].median()) + return out + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--task", + choices=["controllability", "matched_controllability", "robustness", "qdist"], + required=True, + ) + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--csv_path", required=True) + parser.add_argument("--out_dir", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--pdb_names", default="") + parser.add_argument("--num_proteins", type=int, default=12) + parser.add_argument("--max_len", type=int, default=450) + parser.add_argument("--num_frames", type=int, default=6) + parser.add_argument("--num_q_samples", type=int, default=256) + parser.add_argument("--samples_per_condition", type=int, default=4) + parser.add_argument("--num_timesteps", type=int, default=20) + parser.add_argument("--sigmas", default="0,0.25,0.5,1.0") + parser.add_argument("--seed", type=int, default=20260710) + parser.add_argument("--final_only", action="store_true", default=True) + args = parser.parse_args() + + torch.manual_seed(args.seed) + np.random.seed(args.seed % (2**32 - 1)) + device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu") + module, interpolant, load_info = load_module(args.ckpt_path, device, args.num_timesteps) + + df = pd.read_csv(args.csv_path) + if "folder" not in df.columns: + if "pdb_path" not in df.columns: + raise RuntimeError( + "CSV must contain either a folder column or a pdb_path column " + "so MD trajectory paths can be resolved scientifically." + ) + df = df.copy() + df["folder"] = df["pdb_path"].map(lambda path: str(Path(str(path)).parent)) + dataset = PDBDatasetBBFlow(df) + indices = select_protein_indices(df, dataset, args.pdb_names, args.num_proteins, args.max_len) + if not indices: + raise RuntimeError("No proteins selected") + + if args.task == "controllability": + result = run_controllability(args, module, interpolant, dataset, indices, device) + elif args.task == "matched_controllability": + result = run_matched_controllability(args, module, interpolant, dataset, indices, device) + elif args.task == "robustness": + result = run_robustness(args, module, interpolant, dataset, indices, device) + else: + result = run_qdist(args, module, dataset, indices, device) + + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + csv_path = out_dir / f"{args.task}.csv" + json_path = out_dir / f"{args.task}_summary.json" + result.to_csv(csv_path, index=False) + summary = { + "ckpt_path": str(args.ckpt_path), + "csv_path": str(args.csv_path), + "load_info": load_info, + "selected_pdb_names": [str(dataset.pdb_names[idx]) for idx in indices], + "summary": summarize(result, args.task), + } + json_path.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n") + print(json.dumps(summary, indent=2, sort_keys=True)) + print(f"[saved] {csv_path}") + print(f"[saved] {json_path}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/diagnose_condition_snr.py b/bbflow_base/scripts/diagnose_condition_snr.py new file mode 100644 index 0000000000000000000000000000000000000000..36b4802681fbcd00fbee61f5eb9469a8c07969ef --- /dev/null +++ b/bbflow_base/scripts/diagnose_condition_snr.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python +import argparse +import json +from pathlib import Path + +import numpy as np +import pandas as pd +import torch + +from diagnose_condition_interface import ( + load_module, + move_item_to_device, + select_protein_indices, + frame_indices_for_row, + mean_disp_from_frames, + build_cstar_condition, + choose_matched_distance_pair, + sample_final_ca, + pairwise_target_rmsd, + flattened_cosine, + norm_ratio, +) +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow + + +def centroid_dispersion(samples): + # samples: [N, L, 3] + center = samples.mean(dim=0, keepdim=True) + return torch.sqrt((samples.float() - center.float()).square().mean(dim=(1, 2)).clamp_min(0)).mean() + + +def pairwise_sample_rmsd_mean(samples): + n = samples.shape[0] + if n < 2: + return torch.tensor(float("nan"), device=samples.device) + vals = [] + for i in range(n): + for j in range(i + 1, n): + vals.append(torch.sqrt((samples[i].float() - samples[j].float()).square().mean().clamp_min(0))) + return torch.stack(vals).mean() + + +def run_snr(args): + torch.manual_seed(args.seed) + np.random.seed(args.seed % (2**32 - 1)) + + device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu") + module, interpolant, load_info = load_module(args.ckpt_path, device, args.num_timesteps) + + df = pd.read_csv(args.csv_path) + if "folder" not in df.columns: + if "pdb_path" not in df.columns: + raise RuntimeError("CSV must contain either folder or pdb_path") + df = df.copy() + df["folder"] = df["pdb_path"].map(lambda path: str(Path(str(path)).parent)) + + dataset = PDBDatasetBBFlow(df) + indices = select_protein_indices(df, dataset, args.pdb_names, args.num_proteins, args.max_len) + if not indices: + raise RuntimeError("No proteins selected") + + rows = [] + selected = [] + for protein_idx in indices: + row = dataset.csv.iloc[protein_idx] + pdb_name = str(row["name"]) + selected.append(pdb_name) + + frame_ids = frame_indices_for_row(row, args.num_frames) + if len(frame_ids) < 2: + continue + + eq_item = move_item_to_device(dataset[(protein_idx, 0, int(frame_ids[0]))], device) + res_mask = torch.ones_like(eq_item["trans_equilibrium"][..., 0]) + + with torch.no_grad(): + prior, _ = module.latent_encoder.forward_prior( + eq_item["trans_equilibrium"], + eq_item["rotmats_equilibrium"], + eq_item["seq"], + res_mask, + ) + mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device) + + candidates = [] + for frame_id in frame_ids: + item = move_item_to_device(dataset[(protein_idx, 0, int(frame_id))], device) + cond, coeff = build_cstar_condition(module, item, prior, mean_disp=mean_disp) + trans_1 = item["trans_1"][0].detach().float() + trans_eq = item["trans_equilibrium"][0].detach().float() + candidates.append({ + "frame_id": int(frame_id), + "item": item, + "condition": cond, + "coeff": coeff.detach().float(), + "trans_1": trans_1, + "eq_rmsd": pairwise_target_rmsd(trans_1, trans_eq), + }) + + pair = choose_matched_distance_pair(candidates) + if pair is None: + continue + + a = candidates[pair["i"]] + b = candidates[pair["j"]] + + gen_a = sample_final_ca( + module, interpolant, a["item"], a["condition"], + args.samples_per_condition, args.seed + 101 * protein_idx + 1, True, + ) + gen_b = sample_final_ca( + module, interpolant, b["item"], b["condition"], + args.samples_per_condition, args.seed + 101 * protein_idx + 2, True, + ) + + mean_a = gen_a.mean(dim=0) + mean_b = gen_b.mean(dim=0) + + within_a = centroid_dispersion(gen_a) + within_b = centroid_dispersion(gen_b) + within = 0.5 * (within_a + within_b) + + same_pair_a = pairwise_sample_rmsd_mean(gen_a) + same_pair_b = pairwise_sample_rmsd_mean(gen_b) + same_pair = 0.5 * (same_pair_a + same_pair_b) + + cross_centroid = torch.sqrt((mean_a.float() - mean_b.float()).square().mean().clamp_min(0)) + target_delta = b["trans_1"].to(mean_a.device) - a["trans_1"].to(mean_a.device) + generated_delta = mean_b - mean_a + target_pair = float(pair["target_pair_rmsd"]) + + rows.append({ + "pdb_name": pdb_name, + "num_res": int(eq_item["trans_equilibrium"].shape[1]), + "frame_a": int(a["frame_id"]), + "frame_b": int(b["frame_id"]), + "target_pair_rmsd": target_pair, + "cross_centroid_rmsd": float(cross_centroid.detach().cpu()), + "within_centroid_rmsd": float(within.detach().cpu()), + "same_c_pairwise_rmsd": float(same_pair.detach().cpu()), + "snr_centroid": float((cross_centroid / within.clamp_min(1e-8)).detach().cpu()), + "snr_pairwise": float((cross_centroid / same_pair.clamp_min(1e-8)).detach().cpu()), + "amp_ratio_cross_to_target": float((cross_centroid / max(target_pair, 1e-8)).detach().cpu()), + "direction_score": flattened_cosine(generated_delta, target_delta), + "gain_score": norm_ratio(generated_delta, target_delta), + "eq_rmsd_rel_gap": float(pair["eq_rmsd_rel_gap"]), + "coeff_pair_l2": float(pair["coeff_pair_l2"]), + }) + + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + result = pd.DataFrame(rows) + result.to_csv(out_dir / "condition_snr.csv", index=False) + + summary = { + "run_name": args.run_name, + "ckpt_path": args.ckpt_path, + "selected_pdb_names": selected, + "n_rows": int(len(result)), + } + for col in result.select_dtypes(include=[np.number]).columns: + summary[col + "_mean"] = float(result[col].mean()) + summary[col + "_median"] = float(result[col].median()) + + (out_dir / "condition_snr_summary.json").write_text(json.dumps(summary, indent=2)) + print(json.dumps(summary, indent=2)) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--run_name", required=True) + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--csv_path", required=True) + parser.add_argument("--out_dir", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--pdb_names", default="") + parser.add_argument("--num_proteins", type=int, default=12) + parser.add_argument("--max_len", type=int, default=450) + parser.add_argument("--num_frames", type=int, default=6) + parser.add_argument("--samples_per_condition", type=int, default=8) + parser.add_argument("--num_timesteps", type=int, default=20) + parser.add_argument("--seed", type=int, default=20260711) + args = parser.parse_args() + run_snr(args) + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/diagnose_enm_baseline.py b/bbflow_base/scripts/diagnose_enm_baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..ebefa57840a24317252cf577b2a5dec4b8f7c15d --- /dev/null +++ b/bbflow_base/scripts/diagnose_enm_baseline.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python +"""Diagnose how well pure ENM/ANM modes explain MD motion targets.""" + +import argparse +import json +import sys +from pathlib import Path + +SCRIPT_DIR = Path(__file__).resolve().parent +REPO_ROOT = SCRIPT_DIR.parent +for path in [str(REPO_ROOT), str(SCRIPT_DIR)]: + if path not in sys.path: + sys.path.insert(0, path) + +import numpy as np +import pandas as pd +import torch + +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb +from fit_motion_template_upper_bound import load_motion_targets, pdb_name_variants, corr_and_sign, relative_losses + + +def select_dataset_indices(dataset, names, num_proteins): + if names: + wanted = [x.strip() for x in names.split(",") if x.strip()] + out = [] + for name in wanted: + matches = [i for i, pdb in enumerate(dataset.pdb_names) if str(pdb) == name] + if not matches: + raise ValueError(f"pdb_name not found in csv: {name}") + out.append(matches[0]) + return out + return list(range(min(num_proteins, len(dataset)))) + + +def anm_modes(coords, mask, num_modes, cutoff, eps): + valid = mask.bool() + coords_valid = coords[valid].float() + n_valid = coords_valid.shape[0] + n_total = coords.shape[0] + modes = coords.new_zeros(n_total, num_modes, 3, dtype=torch.float32) + evals_out = coords.new_zeros(num_modes, dtype=torch.float32) + if n_valid < 3: + return modes, evals_out + + diff = coords_valid[:, None, :] - coords_valid[None, :, :] + dist = torch.linalg.norm(diff, dim=-1).clamp_min(eps) + contact = (dist < cutoff) & (~torch.eye(n_valid, device=coords.device, dtype=torch.bool)) + if not contact.any(): + return modes, evals_out + + unit = diff / dist[..., None] + outer = unit[..., :, None] * unit[..., None, :] + off_diag = -outer * contact[..., None, None].float() + h_blocks = off_diag.clone() + diag_blocks = -off_diag.sum(dim=1) + idx = torch.arange(n_valid, device=coords.device) + h_blocks[idx, idx] = diag_blocks + hessian = h_blocks.permute(0, 2, 1, 3).reshape(3 * n_valid, 3 * n_valid) + hessian = 0.5 * (hessian + hessian.transpose(0, 1)) + + evals, evecs = torch.linalg.eigh(hessian) + start = min(6, evecs.shape[1]) + stop = min(start + num_modes, evecs.shape[1]) + if stop <= start: + return modes, evals_out + raw = evecs[:, start:stop].reshape(n_valid, 3, stop - start).permute(0, 2, 1).contiguous() + modes[valid, : raw.shape[1], :] = raw + evals_out[: raw.shape[1]] = evals[start:stop].clamp_min(eps) + return modes, evals_out + + +def covariance_from_enm(modes, evals, mask, weighted): + if weighted: + energy = 1.0 / evals.clamp_min(1e-8) + energy = energy / energy.mean().clamp_min(1e-8) + else: + energy = torch.ones_like(evals) + modes = modes * mask[:, None, None] + local_cov = torch.einsum("k,nki,nkj->nij", energy, modes, modes) + cross_cov = torch.einsum("k,nkd,mkd->nm", energy, modes, modes) + rmsf = torch.sqrt(torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)) + return local_cov, cross_cov, rmsf + + +def diagnose_one(name, coords, target, args, device): + coords = coords.to(device=device, dtype=torch.float32) + mask = target["res_mask"].to(device=device, dtype=torch.float32) + target = {k: v.to(device=device, dtype=torch.float32) for k, v in target.items() if k in ["local_cov", "cross_cov", "rmsf"]} + spatial_dists = torch.cdist(coords[None], coords[None])[0] + modes, evals = anm_modes(coords, mask, args.num_modes, args.cutoff, args.eps) + + rows = [] + pair_mask = mask[:, None] * mask[None, :] + offdiag = pair_mask.bool() & ~torch.eye(coords.shape[0], device=device, dtype=torch.bool) + near = offdiag & (spatial_dists <= args.near_distance) + far = offdiag & (spatial_dists > args.near_distance) + for weighted in [False, True]: + local_pred, cross_pred, rmsf_pred = covariance_from_enm(modes, evals, mask, weighted=weighted) + losses = relative_losses((local_pred, cross_pred, rmsf_pred), target, mask, spatial_dists, args.near_distance) + near_corr, near_sign = corr_and_sign(cross_pred, target["cross_cov"], near) + far_corr, far_sign = corr_and_sign(cross_pred, target["cross_cov"], far) + rows.append({ + "pdb_name": name, + "num_res": int(coords.shape[0]), + "num_modes": int(args.num_modes), + "cutoff": float(args.cutoff), + "weighted": "inv_eigenvalue" if weighted else "unweighted", + "eval_min": float(evals[evals > 0].min().detach().cpu()) if (evals > 0).any() else 0.0, + "eval_max": float(evals.max().detach().cpu()), + **{k: float(v.detach().cpu()) for k, v in losses.items()}, + "near_corr_all": near_corr, + "near_top10_sign_agree": near_sign, + "far_corr_all": far_corr, + "far_top10_sign_agree": far_sign, + "pred_abs_mean_near": float(cross_pred[near].abs().mean().detach().cpu()) if near.any() else 0.0, + "true_abs_mean_near": float(target["cross_cov"][near].abs().mean().detach().cpu()) if near.any() else 0.0, + "pred_abs_mean_far": float(cross_pred[far].abs().mean().detach().cpu()) if far.any() else 0.0, + "true_abs_mean_far": float(target["cross_cov"][far].abs().mean().detach().cpu()) if far.any() else 0.0, + }) + return rows + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--motion_target_cache_path", required=True) + parser.add_argument("--csv_path", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--pdb_names", default="") + parser.add_argument("--num_proteins", type=int, default=10) + parser.add_argument("--num_modes", type=int, default=8) + parser.add_argument("--cutoff", type=float, default=12.0) + parser.add_argument("--eps", type=float, default=1e-6) + parser.add_argument("--near_distance", type=float, default=12.0) + parser.add_argument("--device", default="cuda") + args = parser.parse_args() + + device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu") + out_dir = Path(args.output_dir) + out_dir.mkdir(parents=True, exist_ok=True) + targets = load_motion_targets(args.motion_target_cache_path) + df = pd.read_csv(args.csv_path) + df = df.drop(columns=["modeled_seq_len"], errors="ignore") + dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) + + rows = [] + for idx in select_dataset_indices(dataset, args.pdb_names, args.num_proteins): + item = dataset[idx] + name = str(item["pdb_name"]) + target = None + for variant in pdb_name_variants(name): + target = targets.get(variant) + if target is not None: + break + if target is None: + raise KeyError(f"Missing motion target for {name}") + print(f"[enm-baseline] {name} N={item['trans_equilibrium'].shape[0]}", flush=True) + rows.extend(diagnose_one(name, item["trans_equilibrium"].float(), target, args, device)) + + table = pd.DataFrame(rows) + table.to_csv(out_dir / "enm_baseline_summary.csv", index=False) + aggregate = table.groupby("weighted").mean(numeric_only=True).reset_index() + aggregate.to_csv(out_dir / "enm_baseline_aggregate.csv", index=False) + (out_dir / "enm_baseline_aggregate.json").write_text(json.dumps(aggregate.to_dict(orient="records"), indent=2)) + print("\n[enm-baseline] aggregate") + print(aggregate.to_string(index=False)) + print(f"[enm-baseline] wrote {out_dir}") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/diagnose_film.py b/bbflow_base/scripts/diagnose_film.py new file mode 100644 index 0000000000000000000000000000000000000000..b95f2e14f2b84e20c232ab9fd17be3034ac1d576 --- /dev/null +++ b/bbflow_base/scripts/diagnose_film.py @@ -0,0 +1,171 @@ +import argparse +import json +from pathlib import Path + +import torch +from hydra import compose, initialize_config_dir +from omegaconf import OmegaConf + +from bbflow.data.pdb_dataloader_bbflow import PdbDataModuleBBFlow +from bbflow.models.bbflow_module import BBFlowModule + + +def move_to_device(batch, device): + return {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} + + +def load_cfg(repo_root, ckpt_path, overrides): + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + cfg_path = Path(ckpt_path).with_name("config.yaml") + if cfg_path.exists(): + cfg = OmegaConf.load(cfg_path) + else: + with initialize_config_dir(version_base=None, config_dir=str(repo_root / "configs")): + cfg = compose(config_name="train", overrides=[]) + cfg = OmegaConf.create(OmegaConf.to_container(cfg, resolve=False)) + if overrides: + with initialize_config_dir(version_base=None, config_dir=str(repo_root / "configs")): + override_cfg = compose(config_name="train", overrides=overrides) + cfg = OmegaConf.merge(cfg, override_cfg) + OmegaConf.set_struct(cfg, False) + cfg.experiment.use_wandb = False + cfg.experiment.num_devices = 1 + cfg.latent.enable = True + return cfg, ckpt + + +def load_checkpoint(module, ckpt): + missing, unexpected = module.load_state_dict(ckpt["state_dict"], strict=False) + return { + "missing": len(missing), + "unexpected": len(unexpected), + "missing_keys": list(missing)[:20], + "unexpected_keys": list(unexpected)[:20], + } + + +def tensor_stats(x): + x = x.detach().float() + return { + "mean": float(x.mean().cpu().item()), + "abs_mean": float(x.abs().mean().cpu().item()), + "std": float(x.std(unbiased=False).cpu().item()) if x.numel() > 1 else 0.0, + "min": float(x.min().cpu().item()), + "max": float(x.max().cpu().item()), + } + + +def final_layer_stats(module): + if module is None: + return None + last = module[-1] + return { + "weight_abs_mean": float(last.weight.detach().float().abs().mean().cpu().item()), + "weight_abs_max": float(last.weight.detach().float().abs().max().cpu().item()), + "bias_abs_mean": float(last.bias.detach().float().abs().mean().cpu().item()), + "bias_abs_max": float(last.bias.detach().float().abs().max().cpu().item()), + } + + +def zero_condition(condition): + out = {} + for key, value in condition.items(): + if torch.is_tensor(value): + out[key] = torch.zeros_like(value) if key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"} else value.detach() + else: + out[key] = value + return out + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--out_path", default="") + parser.add_argument("--device", default="cuda") + parser.add_argument("--num_batches", type=int, default=4) + parser.add_argument("--override", action="append", default=[]) + args = parser.parse_args() + + repo_root = Path(__file__).resolve().parents[1] + cfg, ckpt = load_cfg(repo_root, args.ckpt_path, args.override) + device = torch.device(args.device if torch.cuda.is_available() or args.device == "cpu" else "cpu") + + module = BBFlowModule(cfg).to(device) + load_info = load_checkpoint(module, ckpt) + module.eval() + module.interpolant.set_device(device) + + datamodule = PdbDataModuleBBFlow(cfg.data, training_cfg=cfg.experiment.training, latent_cfg=cfg.latent) + datamodule.setup("fit") + loader = datamodule.train_dataloader(rank=0, num_replicas=1) + + all_node, all_edge, all_energy = [], [], [] + all_gamma, all_beta = [], [] + output_deltas = [] + names = [] + with torch.no_grad(), torch.autocast(device_type=device.type, enabled=False): + for batch_idx, batch in enumerate(loader): + if batch_idx >= args.num_batches: + break + batch = move_to_device(batch, device) + condition = module.latent_encoder.sample_prior_z( + batch["trans_equilibrium"].float(), + batch["rotmats_equilibrium"].float(), + batch["seq"].float(), + batch["res_mask"].float(), + ) + all_node.append(condition["node_cond"].detach().float().cpu()) + all_edge.append(condition["edge_cond"].detach().float().cpu()) + all_energy.append(condition["energy"].detach().float().cpu()) + if getattr(module.model, "inject_film", False) and module.model.film_mlp is not None: + gamma_beta = module.model.film_mlp(condition["node_cond"].float()) + gamma, beta = torch.chunk(gamma_beta, 2, dim=-1) + all_gamma.append(gamma.detach().float().cpu()) + all_beta.append(beta.detach().float().cpu()) + noisy = module.interpolant.corrupt_batch(batch) + noisy["z"] = condition + noisy_zero = dict(noisy) + noisy_zero["z"] = zero_condition(condition) + out = module.model(noisy) + out_zero = module.model(noisy_zero) + output_deltas.append((out["pred_trans"] - out_zero["pred_trans"]).detach().float().abs().mean().cpu()) + names.extend([str(name) for name in batch["pdb_name"]]) + + node = torch.cat(all_node, dim=0) + edge = torch.cat(all_edge, dim=0) + energy = torch.cat(all_energy, dim=0) + summary = { + "ckpt_path": str(args.ckpt_path), + "num_batches": int(len(all_node)), + "num_samples": int(node.shape[0]), + "num_unique_pdb": int(len(set(names))), + "load_info": load_info, + "node_cond": tensor_stats(node), + "edge_cond": tensor_stats(edge), + "energy": tensor_stats(energy), + "zero_condition_pred_trans_delta": tensor_stats(torch.stack(output_deltas)), + "z_node_adapter_final": final_layer_stats(getattr(module.model.embedder, "z_node_adapter", None)), + "z_edge_adapter_final": final_layer_stats(getattr(module.model.embedder, "z_edge_adapter", None)), + "disp_node_adapter_final": final_layer_stats(getattr(module.model.embedder, "disp_node_adapter", None)), + "disp_edge_adapter_final": final_layer_stats(getattr(module.model.embedder, "disp_edge_adapter", None)), + "film_mlp_final": final_layer_stats(getattr(module.model, "film_mlp", None)), + } + if all_gamma: + gamma = torch.cat(all_gamma, dim=0) + beta = torch.cat(all_beta, dim=0) + summary["one_plus_gamma"] = tensor_stats(1.0 + gamma) + summary["gamma"] = tensor_stats(gamma) + summary["beta"] = tensor_stats(beta) + summary["gamma_across_samples_std"] = tensor_stats(gamma.flatten(1).std(dim=0, unbiased=False)) + summary["beta_across_samples_std"] = tensor_stats(beta.flatten(1).std(dim=0, unbiased=False)) + + text = json.dumps(summary, indent=2, sort_keys=True) + print(text) + if args.out_path: + out_path = Path(args.out_path) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text(text + "\n") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/diagnose_final_condition_sensitivity.py b/bbflow_base/scripts/diagnose_final_condition_sensitivity.py new file mode 100644 index 0000000000000000000000000000000000000000..c7a5d5ae1bd8bc029698ab2df99a07a4dce124bd --- /dev/null +++ b/bbflow_base/scripts/diagnose_final_condition_sensitivity.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python +"""Measure condition sensitivity at the final BBFlow coordinate-update input. + +This script is diagnostic-only. It does not modify model source files, checkpoint +weights, or training configuration. It compares three counterfactual conditions +at the sampler's initial noisy state: + +1. directional_all_zero: zero disp_node_cond and disp_edge_cond; +2. node_cond_zero_all_paths: zero node_cond everywhere; +3. node_cond_zero_film_only: keep initial node injection but zero node_cond only + inside the final-block FiLM call. +""" +import argparse +import copy +import json +from pathlib import Path +import sys + +import numpy as np +import pandas as pd +import torch +from omegaconf import OmegaConf + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb +from bbflow.models.bbflow_module import BBFlowModule + + +def load_module(ckpt_path, device): + ckpt_path = Path(ckpt_path) + cfg_path = ckpt_path.with_name("config.yaml") + if not cfg_path.exists(): + raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}") + + infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(cfg_path) + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.inference.interpolant.use_tqdm = False + cfg.model.embed = ckpt_cfg.model.embed + + module = BBFlowModule(cfg) + checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False) + current_state = module.state_dict() + compatible_state = { + key: value + for key, value in checkpoint["state_dict"].items() + if key in current_state and current_state[key].shape == value.shape + } + missing, unexpected = module.load_state_dict(compatible_state, strict=False) + module.to(device) + module.eval() + return module, { + "loaded": len(compatible_state), + "missing": len(missing), + "unexpected": len(unexpected), + } + + +def select_item(dataset, pdb_name): + for idx, name in enumerate(dataset.pdb_names): + if str(name) == pdb_name: + return dataset[idx] + raise ValueError(f"pdb_name not found in csv: {pdb_name}") + + +def clone_condition(condition): + return { + key: value.clone() if torch.is_tensor(value) else copy.deepcopy(value) + for key, value in condition.items() + } + + +def zero_condition_keys(condition, keys): + out = clone_condition(condition) + for key in keys: + if key in out and torch.is_tensor(out[key]): + out[key] = torch.zeros_like(out[key]) + return out + + +def relative_mean_abs_delta(reference, changed): + denominator = reference.detach().float().abs().mean().clamp_min(1e-8) + return float( + ( + (reference.detach().float() - changed.detach().float()).abs().mean() + / denominator + ) + .cpu() + .item() + ) + + +def run_model_and_capture_final_update(model, batch, condition, zero_node_cond_in_film=False): + """Return final bb_update input and pred_trans for one counterfactual forward.""" + captured = {} + last_block_index = model._gfa_conf.num_blocks - 1 + last_bb_update = model.trunk[f"bb_update_{last_block_index}"] + + def capture_final_update(_module, args): + captured["final_update_node_embed"] = args[0].detach().clone() + + handle = last_bb_update.register_forward_pre_hook(capture_final_update) + original_apply_film = model._apply_latent_film + + if zero_node_cond_in_film: + def apply_film_with_zero_node_cond(node_embed, z): + if isinstance(z, dict): + z = dict(z) + z["node_cond"] = torch.zeros_like(z["node_cond"]) + elif torch.is_tensor(z): + z = torch.zeros_like(z) + return original_apply_film(node_embed, z) + + model._apply_latent_film = apply_film_with_zero_node_cond + + try: + call_batch = dict(batch) + call_batch["z"] = condition + with torch.no_grad(): + output = model(call_batch) + finally: + model._apply_latent_film = original_apply_film + handle.remove() + + return { + "final_update_node_embed": captured["final_update_node_embed"], + "pred_trans": output["pred_trans"].detach().clone(), + } + + +def measure_protein(module, dataset, pdb_name, device): + item = select_item(dataset, pdb_name) + trans_eq = item["trans_equilibrium"][None].to(device) + rotmats_eq = item["rotmats_equilibrium"][None].to(device) + seq = item["seq"][None].to(device) + num_res = trans_eq.shape[1] + res_mask = torch.ones(1, num_res, device=device) + + trans_t, rotmats_t = module.interpolant.sample_from_prior( + 1, num_res, trans_eq, rotmats_eq + ) + batch = { + "res_mask": res_mask, + "trans_equilibrium": trans_eq, + "rotmats_equilibrium": rotmats_eq, + "seq": seq, + "trans_t": trans_t, + "rotmats_t": rotmats_t, + "t": torch.full( + (1, 1), + module.interpolant._cfg.min_t, + device=device, + dtype=trans_eq.dtype, + ), + } + + with torch.no_grad(): + condition = module.latent_encoder.sample_prior_z( + trans_eq, rotmats_eq, seq, res_mask + ) + + reference = run_model_and_capture_final_update(module.model, batch, condition) + variants = { + "directional_all_zero": ( + zero_condition_keys(condition, ["disp_node_cond", "disp_edge_cond"]), + False, + ), + "node_cond_zero_all_paths": ( + zero_condition_keys(condition, ["node_cond"]), + False, + ), + "node_cond_zero_film_only": (condition, True), + } + + result = { + "pdb_name": str(item["pdb_name"]), + "num_res": int(num_res), + "t": float(module.interpolant._cfg.min_t), + } + for label, (variant_condition, film_only) in variants.items(): + changed = run_model_and_capture_final_update( + module.model, + batch, + variant_condition, + zero_node_cond_in_film=film_only, + ) + result[f"{label}_final_update_rel_delta"] = relative_mean_abs_delta( + reference["final_update_node_embed"], + changed["final_update_node_embed"], + ) + result[f"{label}_pred_trans_rel_delta"] = relative_mean_abs_delta( + reference["pred_trans"], + changed["pred_trans"], + ) + return result + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--csv_path", required=True) + parser.add_argument("--pdb_names", default="6o2vA,7eadA,6uofA") + parser.add_argument("--device", default="cuda") + parser.add_argument("--seed", type=int, default=20260626) + parser.add_argument("--out_path", default="") + args = parser.parse_args() + + torch.manual_seed(args.seed) + device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu") + module, load_info = load_module(args.ckpt_path, device) + module.interpolant.set_device(device) + + df = pd.read_csv(args.csv_path) + dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) + pdb_names = [name.strip() for name in args.pdb_names.split(",") if name.strip()] + per_protein = [measure_protein(module, dataset, name, device) for name in pdb_names] + + metric_keys = [key for key in per_protein[0] if key.endswith("_rel_delta")] + summary = { + "ckpt_path": str(args.ckpt_path), + "load_info": load_info, + "measurement": ( + "Relative mean-absolute counterfactual change at the sampler initial " + "noise state. final_update is captured by a pre-hook immediately before " + "the final bb_update module." + ), + "per_protein": per_protein, + "mean_over_proteins": { + key: float(np.mean([row[key] for row in per_protein])) + for key in metric_keys + }, + } + text = json.dumps(summary, indent=2, sort_keys=True) + print(text) + if args.out_path: + out_path = Path(args.out_path) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text(text + "\n") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/diagnose_injection_amplitude.py b/bbflow_base/scripts/diagnose_injection_amplitude.py new file mode 100644 index 0000000000000000000000000000000000000000..33f6611d54d5368bc9f55b60eb49e2f5c361c349 --- /dev/null +++ b/bbflow_base/scripts/diagnose_injection_amplitude.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python +"""Diagnose whether latent condition adapters grew and inject nontrivial amplitude.""" +import argparse +import json +from pathlib import Path +import sys + +import numpy as np +import pandas as pd +import torch +from omegaconf import OmegaConf + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb +from bbflow.models.bbflow_module import BBFlowModule + + +def load_module(ckpt_path, device): + ckpt_path = Path(ckpt_path) + cfg_path = ckpt_path.with_name("config.yaml") + if not cfg_path.exists(): + raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}") + infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(cfg_path) + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.inference.interpolant.use_tqdm = False + cfg.model.embed = ckpt_cfg.model.embed + module = BBFlowModule(cfg) + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + current_state = module.state_dict() + compatible_state = { + key: value for key, value in ckpt["state_dict"].items() + if key in current_state and current_state[key].shape == value.shape + } + missing, unexpected = module.load_state_dict(compatible_state, strict=False) + module.to(device) + module.eval() + return module, cfg, {"loaded": len(compatible_state), "missing": len(missing), "unexpected": len(unexpected)} + + +def select_item(dataset, pdb_name): + if pdb_name: + for idx, name in enumerate(dataset.pdb_names): + if str(name) == pdb_name: + return dataset[idx] + raise ValueError(f"pdb_name not found: {pdb_name}") + return dataset[0] + + +def last_linear_stats(module): + if module is None: + return None + last = module[-1] + return { + "weight_norm": float(last.weight.detach().float().norm().cpu().item()), + "weight_abs_mean": float(last.weight.detach().float().abs().mean().cpu().item()), + "weight_abs_max": float(last.weight.detach().float().abs().max().cpu().item()), + "bias_norm": float(last.bias.detach().float().norm().cpu().item()) if last.bias is not None else 0.0, + "bias_abs_mean": float(last.bias.detach().float().abs().mean().cpu().item()) if last.bias is not None else 0.0, + "bias_abs_max": float(last.bias.detach().float().abs().max().cpu().item()) if last.bias is not None else 0.0, + } + + +def mean_abs(tensor): + return float(tensor.detach().float().abs().mean().cpu().item()) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--csv_path", required=True) + parser.add_argument("--pdb_name", default="") + parser.add_argument("--device", default="cuda") + parser.add_argument("--out_path", default="") + args = parser.parse_args() + + device = torch.device(args.device if (args.device == "cpu" or torch.cuda.is_available()) else "cpu") + module, cfg, load_info = load_module(args.ckpt_path, device) + module.interpolant.set_device(device) + + df = pd.read_csv(args.csv_path) + dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) + item = select_item(dataset, args.pdb_name) + trans_eq = item["trans_equilibrium"][None].to(device) + rotmats_eq = item["rotmats_equilibrium"][None].to(device) + seq = item["seq"][None].to(device) + num_res = trans_eq.shape[1] + batch = { + "trans_equilibrium": trans_eq, + "rotmats_equilibrium": rotmats_eq, + "seq": seq, + "res_mask": torch.ones(1, num_res, device=device), + "pdb_name": [str(item["pdb_name"])], + } + + # This is an injection-site diagnostic, not a training-loss diagnostic. + # PDBDatasetBBFlowFromPdb only provides the equilibrium structure, not MD + # targets (trans_1/rotmats_1), so build a minimal model-forward batch by + # using the equilibrium frame as the current frame. The embedder injection + # amplitudes are measured at the exact node/edge embedding site. + noisy_batch = dict(batch) + noisy_batch["trans_t"] = trans_eq.clone() + noisy_batch["rotmats_t"] = rotmats_eq.clone() + noisy_batch["t"] = torch.full((1, 1), 0.5, device=device, dtype=trans_eq.dtype) + with torch.no_grad(): + condition = module.latent_encoder.sample_prior_z( + noisy_batch["trans_equilibrium"], + noisy_batch["rotmats_equilibrium"], + noisy_batch["seq"], + noisy_batch["res_mask"], + ) + noisy_batch["z"] = condition + + captures = {} + handles = [] + + def capture(name): + def hook(_mod, _inp, out): + captures[name] = out.detach() + return hook + + embedder = module.model.embedder + for name, submodule in [ + ("node_base", embedder.node_embedding), + ("edge_base_flat", embedder.edge_embedding), + ("z_node_adapter", embedder.z_node_adapter), + ("z_edge_adapter", embedder.z_edge_adapter), + ("disp_node_adapter", embedder.disp_node_adapter), + ("disp_edge_adapter", embedder.disp_edge_adapter), + ]: + if submodule is not None: + handles.append(submodule.register_forward_hook(capture(name))) + + with torch.no_grad(): + _ = module.model(noisy_batch) + + for handle in handles: + handle.remove() + + node_base = captures.get("node_base") + edge_base_flat = captures.get("edge_base_flat") + out = { + "ckpt_path": str(args.ckpt_path), + "pdb_name": str(item["pdb_name"]), + "num_res": int(num_res), + "load_info": load_info, + "condition_shapes": { + key: list(value.shape) for key, value in condition.items() if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"} + }, + "last_layer_stats": { + "z_node_adapter": last_linear_stats(embedder.z_node_adapter), + "z_edge_adapter": last_linear_stats(embedder.z_edge_adapter), + "disp_node_adapter": last_linear_stats(embedder.disp_node_adapter), + "disp_edge_adapter": last_linear_stats(embedder.disp_edge_adapter), + }, + "injection_amplitude": {}, + } + + if node_base is not None: + node_base_abs = mean_abs(node_base) + out["injection_amplitude"]["node_base_abs_mean"] = node_base_abs + for key in ["z_node_adapter", "disp_node_adapter"]: + if key in captures: + amp = mean_abs(captures[key]) + out["injection_amplitude"][f"{key}_out_abs_mean"] = amp + out["injection_amplitude"][f"{key}_out_over_node_base"] = amp / max(node_base_abs, 1e-12) + + if edge_base_flat is not None: + edge_base_abs = mean_abs(edge_base_flat) + out["injection_amplitude"]["edge_base_abs_mean"] = edge_base_abs + for key in ["z_edge_adapter", "disp_edge_adapter"]: + if key in captures: + amp = mean_abs(captures[key]) + out["injection_amplitude"][f"{key}_out_abs_mean"] = amp + out["injection_amplitude"][f"{key}_out_over_edge_base"] = amp / max(edge_base_abs, 1e-12) + + text = json.dumps(out, indent=2, sort_keys=True) + print(text) + if args.out_path: + Path(args.out_path).parent.mkdir(parents=True, exist_ok=True) + Path(args.out_path).write_text(text + "\n") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/diagnose_mode_pca_alignment.py b/bbflow_base/scripts/diagnose_mode_pca_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1872c6abee58aa71ff144dfaebcf4f7f0abc9d --- /dev/null +++ b/bbflow_base/scripts/diagnose_mode_pca_alignment.py @@ -0,0 +1,287 @@ +#!/usr/bin/env python +"""Compare learned latent modes with MD PCA/oracle modes. + +The goal is to test whether the model's highest-energy learned modes align +with the MD top principal components that drive PCA-W2. +""" +import argparse +import json +from pathlib import Path +import sys + +import numpy as np +import pandas as pd +import mdtraj +import torch +from omegaconf import OmegaConf + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb +from bbflow.data.utils import frames_from_pdb +from bbflow.models.latent import LatentEncoder +from bbflow.models.bbflow_module import BBFlowModule +from scripts.fit_motion_template_upper_bound import load_motion_targets, pdb_name_variants + + +def load_module(ckpt_path, device): + ckpt_path = Path(ckpt_path) + cfg_path = ckpt_path.with_name("config.yaml") + if not cfg_path.exists(): + raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}") + infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(cfg_path) + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.model.embed = ckpt_cfg.model.embed + + module = BBFlowModule(cfg) + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + current_state = module.state_dict() + compatible_state = { + key: value for key, value in ckpt["state_dict"].items() + if key in current_state and current_state[key].shape == value.shape + } + missing, unexpected = module.load_state_dict(compatible_state, strict=False) + module.to(device) + module.eval() + return module, {"loaded": len(compatible_state), "missing": len(missing), "unexpected": len(unexpected)} + + +def target_for_pdb(targets, pdb_name): + for name in pdb_name_variants(str(pdb_name)): + if name in targets: + return targets[name] + raise KeyError(f"No motion target for {pdb_name}") + + +def load_ca_md_frames(atlas_root, pdb_name): + entry_dir = Path(atlas_root) / str(pdb_name) + eq_path = entry_dir / f"{pdb_name}.pdb" + if not eq_path.exists(): + raise FileNotFoundError(f"Missing equilibrium PDB: {eq_path}") + top = mdtraj.load(str(eq_path)) + ca_indices = top.top.select("name CA") + if ca_indices.size == 0: + raise ValueError(f"No CA atoms found in {eq_path}") + + frames = [] + for traj_idx in range(1, 4): + xtc_path = entry_dir / f"{pdb_name}_R{traj_idx}.xtc" + if not xtc_path.exists(): + raise FileNotFoundError(f"Missing trajectory: {xtc_path}") + traj = mdtraj.load(str(xtc_path), top=str(eq_path), atom_indices=ca_indices) + frames.append(torch.as_tensor(traj.xyz, dtype=torch.float32) * 10.0) + return torch.cat(frames, dim=0) + + +def oracle_modes_from_target_or_md(target, atlas_root, pdb_name, num_md_pcs, device): + if "oracle_modes" in target and "oracle_energy" in target: + return ( + torch.as_tensor(target["oracle_modes"], device=device, dtype=torch.float32), + torch.as_tensor(target["oracle_energy"], device=device, dtype=torch.float32), + "cache", + ) + if atlas_root is None: + raise KeyError( + f"{pdb_name} target lacks oracle_modes/oracle_energy; pass --atlas_root to compute them from MD" + ) + eq_path = Path(atlas_root) / str(pdb_name) / f"{pdb_name}.pdb" + trans_eq, _, _, _ = frames_from_pdb(eq_path) + frames = load_ca_md_frames(atlas_root, pdb_name) + mask = torch.ones(trans_eq.shape[0], dtype=torch.float32) + disp = LatentEncoder.relative_displacement(frames, trans_eq.float(), mask) + disp_centered = disp - disp.mean(dim=0, keepdim=True) + modes, energy = LatentEncoder.pca_modes_from_centered_displacement( + disp_centered, + mask, + num_modes=num_md_pcs, + ) + return modes.to(device), energy.to(device), "md_xtc" + + +def flatten_modes(modes, mask): + """Return [K, 3N] masked, L2-normalized mode vectors.""" + if modes.ndim == 4: + modes = modes[0] + # [N,K,3] -> [K,N,3] -> [K,3N] + mask = mask.float() + flat = (modes.float() * mask[:, None, None]).permute(1, 0, 2).reshape(modes.shape[1], -1) + return flat / flat.norm(dim=-1, keepdim=True).clamp_min(1e-8) + + +def cosine_matrix(learned_modes, md_modes, mask): + learned = flatten_modes(learned_modes, mask) + md = flatten_modes(md_modes, mask) + return learned @ md.T + + +def orthonormal_basis(mode_flat): + # mode_flat: [K, D], row vectors. + q, _ = torch.linalg.qr(mode_flat.T, mode="reduced") + return q + + +def subspace_overlap(learned_modes, md_modes, mask, learned_indices, md_indices): + learned = flatten_modes(learned_modes, mask)[learned_indices] + md = flatten_modes(md_modes, mask)[md_indices] + q_l = orthonormal_basis(learned) + q_m = orthonormal_basis(md) + s = torch.linalg.svdvals(q_l.T @ q_m) + return { + "mean_sq_cos": float((s.square().mean()).detach().cpu().item()), + "min_sq_cos": float((s.square().min()).detach().cpu().item()), + "singular_values": [float(x) for x in s.detach().cpu().tolist()], + } + + +def numeric_mean(rows): + out = {} + if not rows: + return out + keys = sorted({key for row in rows for key in row}) + for key in keys: + vals = [row[key] for row in rows if isinstance(row.get(key), (int, float))] + if vals: + out[key] = float(np.mean(vals)) + return out + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--csv_path", required=True) + parser.add_argument("--motion_target_cache_path", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--atlas_root", default=None, help="ATLAS root with PDB/XTC files; used if cache lacks oracle_modes.") + parser.add_argument("--num_md_pcs", type=int, default=5) + parser.add_argument("--num_proteins", type=int, default=0, help="0 means all proteins") + parser.add_argument("--pdb_name", default="") + parser.add_argument("--device", default="cuda") + return parser.parse_args() + + +def select_indices(dataset, pdb_name, num_proteins): + if pdb_name: + wanted = [x.strip() for x in pdb_name.split(",") if x.strip()] + indices = [] + for name in wanted: + matches = [idx for idx, pdb in enumerate(dataset.pdb_names) if pdb == name] + if not matches: + raise ValueError(f"pdb_name not found in csv: {name}") + indices.append(matches[0]) + return indices + limit = len(dataset) if int(num_proteins) <= 0 else min(int(num_proteins), len(dataset)) + return list(range(limit)) + + +def main(): + args = parse_args() + device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu") + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + module, load_info = load_module(args.ckpt_path, device) + targets = load_motion_targets(args.motion_target_cache_path) + df = pd.read_csv(args.csv_path) + dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) + indices = select_indices(dataset, args.pdb_name, args.num_proteins) + + rows = [] + with torch.no_grad(): + for idx in indices: + pdb_name = dataset.pdb_names[idx] + item = dataset[idx] + trans_eq = item["trans_equilibrium"][None].to(device) + rotmats_eq = item["rotmats_equilibrium"][None].to(device) + seq = item["seq"][None].to(device) + _, num_res = trans_eq.shape[:2] + mask = torch.ones(num_res, device=device) + res_mask = mask[None] + + condition, _ = module.latent_encoder.forward_prior(trans_eq, rotmats_eq, seq, res_mask) + learned_modes = condition["u_global"].detach().float() + learned_energy = condition["energy"][0].detach().float() + + target = target_for_pdb(targets, pdb_name) + md_modes, md_energy, md_mode_source = oracle_modes_from_target_or_md( + target, + args.atlas_root, + pdb_name, + args.num_md_pcs, + device, + ) + if md_modes.shape[1] < args.num_md_pcs: + raise ValueError(f"{pdb_name} has only {md_modes.shape[1]} oracle modes") + + cos = cosine_matrix(learned_modes, md_modes[:, : args.num_md_pcs], mask) + abs_cos = cos.abs() + learned_order = torch.argsort(learned_energy, descending=True) + md_order = torch.arange(args.num_md_pcs, device=device) + + row = { + "pdb_name": pdb_name, + "num_res": int(num_res), + "md_mode_source": md_mode_source, + "learned_energy_top0": float(learned_energy[learned_order[0]].cpu().item()), + "learned_energy_top1": float(learned_energy[learned_order[1]].cpu().item()) if learned_order.numel() > 1 else float("nan"), + "md_energy_pc1": float(md_energy[0].cpu().item()), + "md_energy_pc2": float(md_energy[1].cpu().item()) if md_energy.numel() > 1 else float("nan"), + } + + for pc_idx in range(min(args.num_md_pcs, abs_cos.shape[1])): + best = torch.max(abs_cos[:, pc_idx]) + best_idx = int(torch.argmax(abs_cos[:, pc_idx]).cpu().item()) + top0 = int(learned_order[0].cpu().item()) + row[f"best_abs_cos_to_md_pc{pc_idx + 1}"] = float(best.cpu().item()) + row[f"best_learned_mode_for_md_pc{pc_idx + 1}"] = best_idx + row[f"top_energy_abs_cos_to_md_pc{pc_idx + 1}"] = float(abs_cos[top0, pc_idx].cpu().item()) + + for rank in range(min(learned_order.numel(), 5)): + learned_idx = int(learned_order[rank].cpu().item()) + best_pc = torch.max(abs_cos[learned_idx, :]) + best_pc_idx = int(torch.argmax(abs_cos[learned_idx, :]).cpu().item()) + row[f"top{rank + 1}_energy_mode_index"] = learned_idx + row[f"top{rank + 1}_energy_best_abs_cos_to_any_md_pc"] = float(best_pc.cpu().item()) + row[f"top{rank + 1}_energy_best_md_pc"] = best_pc_idx + 1 + + top2_learned = learned_order[: min(2, learned_order.numel())] + top2_md = md_order[: min(2, md_order.numel())] + top2 = subspace_overlap(learned_modes, md_modes, mask, top2_learned, top2_md) + row["top2_energy_vs_md_top2_subspace_mean_sq_cos"] = top2["mean_sq_cos"] + row["top2_energy_vs_md_top2_subspace_min_sq_cos"] = top2["min_sq_cos"] + + all_learned = torch.arange(learned_modes.shape[2], device=device) + best2 = subspace_overlap(learned_modes, md_modes, mask, all_learned, top2_md) + row["all_learned_vs_md_top2_subspace_mean_sq_cos"] = best2["mean_sq_cos"] + row["all_learned_vs_md_top2_subspace_min_sq_cos"] = best2["min_sq_cos"] + rows.append(row) + + matrix_path = output_dir / f"{pdb_name}_abs_cosine.npy" + np.save(matrix_path, abs_cos.detach().cpu().numpy()) + + out_csv = output_dir / "per_protein_mode_pca_alignment.csv" + pd.DataFrame(rows).to_csv(out_csv, index=False) + summary = { + "ckpt_path": str(args.ckpt_path), + "csv_path": str(args.csv_path), + "motion_target_cache_path": str(args.motion_target_cache_path), + "atlas_root": str(args.atlas_root) if args.atlas_root is not None else None, + "load_info": load_info, + "num_proteins": len(rows), + "mean": numeric_mean(rows), + } + with (output_dir / "summary.json").open("w") as handle: + json.dump(summary, handle, indent=2) + print(json.dumps(summary, indent=2)) + print(f"Wrote {out_csv}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/diagnose_pca_projection_ceiling.py b/bbflow_base/scripts/diagnose_pca_projection_ceiling.py new file mode 100644 index 0000000000000000000000000000000000000000..683a4c349169d8094e08d889fc52a808ce8e844d --- /dev/null +++ b/bbflow_base/scripts/diagnose_pca_projection_ceiling.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python +"""Report the centered MD-PCA projection ceiling stored in a motion-target cache.""" + +import argparse +import csv +import json +import math +import statistics +from pathlib import Path + +import torch + +from bbflow.data.alignment import require_alignment_version + + +def target_pca_metrics(target, num_modes): + mask = torch.as_tensor(target["res_mask"], dtype=torch.float64) + local_cov = torch.as_tensor(target["local_cov"], dtype=torch.float64) + energy = torch.as_tensor(target["oracle_energy"], dtype=torch.float64) + mean_disp = torch.as_tensor(target["oracle_mean_disp"], dtype=torch.float64) + if int(num_modes) > int(energy.numel()): + raise ValueError( + f"Requested K={num_modes}, but cache contains only {energy.numel()} PCA modes" + ) + + fluctuation_energy = ( + torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1) * mask + ).sum() + pca_energy = energy[: int(num_modes)].clamp_min(0.0).sum() + explained = (pca_energy / fluctuation_energy.clamp_min(1e-12)).clamp(0.0, 1.0) + mean_offset_energy = (mean_disp.square().sum(dim=-1) * mask).sum() + total_energy = mean_offset_energy + fluctuation_energy + + return { + "num_res": int(mask.sum().item()), + "num_modes": int(num_modes), + "pca_energy": float(pca_energy.item()), + "fluctuation_energy": float(fluctuation_energy.item()), + "pca_explained_fraction": float(explained.item()), + "pca_optimal_relative_rmse": math.sqrt(max(0.0, 1.0 - float(explained.item()))), + "mean_offset_energy": float(mean_offset_energy.item()), + "mean_to_fluctuation_energy_ratio": float( + (mean_offset_energy / fluctuation_energy.clamp_min(1e-12)).item() + ), + "mean_fraction_of_total_energy": float( + (mean_offset_energy / total_energy.clamp_min(1e-12)).item() + ), + } + + +def canonical_targets(payload): + if not isinstance(payload, dict) or "motion_targets" not in payload: + raise ValueError("Expected a motion-target cache with a motion_targets mapping") + targets = payload["motion_targets"] + for name, target in targets.items(): + if "_" in name and name.replace("_", "") in targets: + continue + yield str(name), target + + +def aggregate(rows): + metric_names = [ + "pca_explained_fraction", + "pca_optimal_relative_rmse", + "mean_to_fluctuation_energy_ratio", + "mean_fraction_of_total_energy", + ] + result = {"num_proteins": len(rows)} + for name in metric_names: + values = [float(row[name]) for row in rows] + result[f"{name}_mean"] = statistics.fmean(values) + result[f"{name}_median"] = statistics.median(values) + + total_pca = sum(float(row["pca_energy"]) for row in rows) + total_fluctuation = sum(float(row["fluctuation_energy"]) for row in rows) + result["pca_explained_fraction_energy_weighted"] = total_pca / max(total_fluctuation, 1e-12) + return result + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--motion_target_cache_path", required=True) + parser.add_argument("--num_modes", type=int, nargs="+", default=[8, 16]) + parser.add_argument("--output_dir", required=True) + return parser.parse_args() + + +def main(): + args = parse_args() + cache_path = Path(args.motion_target_cache_path) + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + payload = torch.load(cache_path, map_location="cpu", weights_only=False) + require_alignment_version(payload, source=str(cache_path)) + targets = list(canonical_targets(payload)) + + all_results = {} + for num_modes in args.num_modes: + rows = [] + for name, target in targets: + row = {"name": name, **target_pca_metrics(target, num_modes)} + rows.append(row) + + summary = aggregate(rows) + all_results[str(num_modes)] = summary + csv_path = output_dir / f"pca_ceiling_k{num_modes}.csv" + with csv_path.open("w", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + print(f"\n[PCA ceiling K={num_modes}]") + for key, value in summary.items(): + print(f"{key}: {value:.6f}" if isinstance(value, float) else f"{key}: {value}") + + json_path = output_dir / "pca_ceiling_summary.json" + json_path.write_text(json.dumps(all_results, indent=2, sort_keys=True) + "\n") + print(f"\nWrote {json_path}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/diagnose_q_calibration_pit.py b/bbflow_base/scripts/diagnose_q_calibration_pit.py new file mode 100644 index 0000000000000000000000000000000000000000..dccbfee5b353d015b4ff4c2ea901df88a2994280 --- /dev/null +++ b/bbflow_base/scripts/diagnose_q_calibration_pit.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python +import argparse +import json +import math +import sys +from pathlib import Path + +import mdtraj +import numpy as np +import pandas as pd +import torch +from omegaconf import OmegaConf + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow +from bbflow.models.bbflow_module import BBFlowModule + + +def normalize_csv(csv_path): + df = pd.read_csv(csv_path) + if "folder" not in df.columns: + if "pdb_path" not in df.columns: + raise RuntimeError(f"{csv_path} has no folder or pdb_path column") + df = df.copy() + df["folder"] = df["pdb_path"].map(lambda x: str(Path(str(x)).parent)) + if "name" not in df.columns: + raise RuntimeError(f"{csv_path} has no name column") + return df + + +def load_module(ckpt_path, device): + ckpt_path = Path(ckpt_path) + cfg_path = ckpt_path.with_name("config.yaml") + infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(cfg_path) + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.inference.interpolant.use_tqdm = False + cfg.model.embed = ckpt_cfg.model.embed + + module = BBFlowModule(cfg) + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + current = module.state_dict() + compatible = { + k: v for k, v in ckpt["state_dict"].items() + if k in current and current[k].shape == v.shape + } + module.load_state_dict(compatible, strict=False) + module.to(device) + module.eval() + return module + + +def infer_num_frames(row): + for key in ["num_conformations", "num_frames", "n_frames", "traj_num_frames"]: + if key in row and pd.notna(row[key]): + return int(row[key]) + name = str(row["name"]) + folder = Path(str(row["folder"])) + xtc = folder / f"{name}_R1.xtc" + if not xtc.exists(): + raise FileNotFoundError(f"Missing trajectory: {xtc}") + with mdtraj.open(str(xtc)) as handle: + return int(handle.n_frames if hasattr(handle, "n_frames") else len(handle)) + + +def move_item(item, device): + out = {} + for k, v in item.items(): + out[k] = v[None].to(device) if torch.is_tensor(v) else v + return out + + +def selected_indices(df, limit, max_len): + idxs = list(range(len(df))) + if "modeled_seq_len" in df.columns: + idxs = [i for i in idxs if int(df.iloc[i]["modeled_seq_len"]) <= int(max_len)] + idxs = sorted(idxs, key=lambda i: int(df.iloc[i]["modeled_seq_len"])) + return idxs[: int(limit)] + + +def mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device): + disps = [] + for fid in frame_ids: + item = move_item(dataset[(protein_idx, 0, int(fid))], device) + mask = torch.ones_like(item["trans_equilibrium"][..., 0]) + disp = module.latent_encoder.relative_displacement( + item["trans_1"].float(), + item["trans_equilibrium"].float(), + mask, + ) + disps.append(disp) + return torch.cat(disps, dim=0).mean(dim=0, keepdim=True) + + +def q_marginal_pit(prior, coeff): + logits = prior["mixture_logits"].float() + probs = torch.softmax(logits, dim=-1)[0] + mu = prior["mixture_mu"].float()[0] + tril = prior["mixture_scale_tril"].float()[0] + sigma = torch.diagonal(tril, dim1=-2, dim2=-1).clamp_min(1e-8) + + x = coeff.float() + z = (x[:, None, :] - mu[None, :, :]) / sigma[None, :, :] + cdf = 0.5 * (1.0 + torch.erf(z / math.sqrt(2.0))) + return (cdf * probs[None, :, None]).sum(dim=1).clamp(0.0, 1.0) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt_path", required=True) + ap.add_argument("--csv_path", required=True) + ap.add_argument("--out_dir", required=True) + ap.add_argument("--split_name", required=True) + ap.add_argument("--device", default="cuda") + ap.add_argument("--num_proteins", type=int, default=128) + ap.add_argument("--num_frames", type=int, default=16) + ap.add_argument("--max_len", type=int, default=600) + args = ap.parse_args() + + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + device = torch.device(args.device if torch.cuda.is_available() and args.device.startswith("cuda") else "cpu") + module = load_module(args.ckpt_path, device) + + df = normalize_csv(args.csv_path) + dataset = PDBDatasetBBFlow(csv=df) + + rows = [] + all_pit = [] + + with torch.no_grad(): + for protein_idx in selected_indices(df, args.num_proteins, args.max_len): + row = dataset.csv.iloc[protein_idx] + name = str(row["name"]) + total = infer_num_frames(row) + frame_ids = sorted(set(np.linspace(0, total - 1, args.num_frames, dtype=int).tolist())) + if len(frame_ids) < 2: + continue + + eq_item = move_item(dataset[(protein_idx, 0, int(frame_ids[0]))], device) + mask = torch.ones_like(eq_item["trans_equilibrium"][..., 0]) + prior, _ = module.latent_encoder.forward_prior( + eq_item["trans_equilibrium"], + eq_item["rotmats_equilibrium"], + eq_item["seq"], + mask, + ) + + mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device) + + coeffs = [] + for fid in frame_ids: + item = move_item(dataset[(protein_idx, 0, int(fid))], device) + _, coeff = module.latent_encoder.frame_condition_from_projection( + item["trans_1"], + item["trans_equilibrium"], + item["rotmats_equilibrium"], + torch.ones_like(item["trans_equilibrium"][..., 0]), + prior, + mean_disp=mean_disp, + ) + coeffs.append(coeff.detach().float()) + + cstar = torch.cat(coeffs, dim=0) + pit = q_marginal_pit(prior, cstar) + all_pit.append(pit.detach().cpu()) + + second = module.latent_encoder.mixture_second_moment(prior).float() + probs = torch.softmax(prior["mixture_logits"].float(), dim=-1) + mu = prior["mixture_mu"].float() + q_mean = torch.einsum("bm,bmk->bk", probs, mu) + q_var = torch.diagonal(second, dim1=-2, dim2=-1) - q_mean.square() + q_var = q_var[0].clamp_min(1e-8) + + c_mean = cstar.mean(dim=0) + c_var = cstar.var(dim=0, unbiased=False).clamp_min(1e-8) + + prior_rep = module.latent_encoder.repeat_condition(prior, cstar.shape[0]) + q_nll = module.latent_encoder.mixture_nll(prior_rep, cstar) + + rows.append({ + "split": args.split_name, + "pdb_name": name, + "num_frames": int(cstar.shape[0]), + "num_res": int(eq_item["trans_equilibrium"].shape[1]), + "q_nll_on_cstar": float(q_nll.detach().cpu()), + "q_over_cstar_norm": float((q_mean.norm() / c_mean.norm().clamp_min(1e-8)).detach().cpu()), + "q_var_over_cstar_var_mean": float((q_var / c_var).mean().detach().cpu()), + "q_var_over_cstar_var_median": float((q_var / c_var).median().detach().cpu()), + "diag_var_rel_l1": float(((q_var - c_var).abs().mean() / c_var.abs().mean().clamp_min(1e-8)).detach().cpu()), + "mean_rel_l2": float(((q_mean - c_mean).norm() / c_mean.norm().clamp_min(1e-8)).detach().cpu()), + "pit_edge_frac": float(((pit < 0.1) | (pit > 0.9)).float().mean().detach().cpu()), + "pit_mid_frac": float(((pit > 0.4) & (pit < 0.6)).float().mean().detach().cpu()), + }) + print(f"[q-calib] {args.split_name} {name} done", flush=True) + + frame = pd.DataFrame(rows) + frame.to_csv(out_dir / f"q_calibration_{args.split_name}.csv", index=False) + + pit_all = torch.cat(all_pit, dim=0).numpy() if all_pit else np.empty((0, 0)) + summary = { + "split": args.split_name, + "n_proteins": int(len(frame)), + "n_pit_values": int(pit_all.size), + "mean_q_nll_on_cstar": float(frame["q_nll_on_cstar"].mean()) if len(frame) else float("nan"), + "median_q_nll_on_cstar": float(frame["q_nll_on_cstar"].median()) if len(frame) else float("nan"), + "mean_q_var_over_cstar_var": float(frame["q_var_over_cstar_var_mean"].mean()) if len(frame) else float("nan"), + "median_q_var_over_cstar_var": float(frame["q_var_over_cstar_var_median"].median()) if len(frame) else float("nan"), + "mean_pit_edge_frac": float(frame["pit_edge_frac"].mean()) if len(frame) else float("nan"), + "mean_pit_mid_frac": float(frame["pit_mid_frac"].mean()) if len(frame) else float("nan"), + "uniform_expected_edge_frac": 0.2, + "uniform_expected_mid_frac": 0.2, + } + + (out_dir / f"q_calibration_summary_{args.split_name}.json").write_text( + json.dumps(summary, indent=2, sort_keys=True) + "\n" + ) + print(json.dumps(summary, indent=2, sort_keys=True), flush=True) + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/diagnose_training_contraction.py b/bbflow_base/scripts/diagnose_training_contraction.py new file mode 100644 index 0000000000000000000000000000000000000000..e8f78577b938b31a97158ce2037997145dc85f56 --- /dev/null +++ b/bbflow_base/scripts/diagnose_training_contraction.py @@ -0,0 +1,384 @@ +#!/usr/bin/env python +"""Diagnose whether training improvements shrink generated ensembles. + +This script is intentionally post-hoc: it does not sample new conformations. +It reads existing epoch metrics and saved ``sampled_conformations.pdb`` files, +then compares generated CA displacement magnitude and MD-PC projections against +ATLAS MD trajectories. +""" +import argparse +import json +from pathlib import Path +import sys + +import numpy as np +import pandas as pd +import torch + +try: + from omegaconf import OmegaConf +except ModuleNotFoundError: + OmegaConf = None + +try: + import mdtraj +except ModuleNotFoundError: # Allow metrics-only mode without trajectory deps. + mdtraj = None + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +PDBDatasetBBFlowFromPdb = None +frames_from_pdb = None +LatentEncoder = None + + +def ensure_bbflow_imports(): + global PDBDatasetBBFlowFromPdb, frames_from_pdb, LatentEncoder + if PDBDatasetBBFlowFromPdb is not None: + return + from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb as _Dataset + from bbflow.data.utils import frames_from_pdb as _frames_from_pdb + from bbflow.models.latent import LatentEncoder as _LatentEncoder + PDBDatasetBBFlowFromPdb = _Dataset + frames_from_pdb = _frames_from_pdb + LatentEncoder = _LatentEncoder + + +def quantiles(x, prefix): + x = np.asarray(x, dtype=np.float64) + if x.size == 0: + return {} + return { + f"{prefix}_mean": float(np.mean(x)), + f"{prefix}_std": float(np.std(x)), + f"{prefix}_q05": float(np.quantile(x, 0.05)), + f"{prefix}_q10": float(np.quantile(x, 0.10)), + f"{prefix}_q25": float(np.quantile(x, 0.25)), + f"{prefix}_median": float(np.quantile(x, 0.50)), + f"{prefix}_q75": float(np.quantile(x, 0.75)), + f"{prefix}_q90": float(np.quantile(x, 0.90)), + f"{prefix}_q95": float(np.quantile(x, 0.95)), + } + + +def numeric_mean(rows): + out = {} + if not rows: + return out + keys = sorted({key for row in rows for key in row}) + for key in keys: + vals = [row[key] for row in rows if isinstance(row.get(key), (int, float, np.number))] + if vals: + out[key] = float(np.mean(vals)) + return out + + +def load_ca_pdb(path): + if mdtraj is None: + raise ModuleNotFoundError("mdtraj is required for ensemble/PDB diagnostics") + traj = mdtraj.load(str(path)) + ca_idx = traj.top.select("name CA") + if ca_idx.size == 0: + raise ValueError(f"No CA atoms found in {path}") + return torch.as_tensor(traj.xyz[:, ca_idx, :] * 10.0, dtype=torch.float32) + + +def load_ca_md_frames(atlas_root, pdb_name): + if mdtraj is None: + raise ModuleNotFoundError("mdtraj is required for ensemble/PDB diagnostics") + entry_dir = Path(atlas_root) / str(pdb_name) + eq_path = entry_dir / f"{pdb_name}.pdb" + if not eq_path.exists(): + raise FileNotFoundError(f"Missing equilibrium PDB: {eq_path}") + top = mdtraj.load(str(eq_path)) + ca_indices = top.top.select("name CA") + if ca_indices.size == 0: + raise ValueError(f"No CA atoms found in {eq_path}") + + frames = [] + for traj_idx in range(1, 4): + xtc_path = entry_dir / f"{pdb_name}_R{traj_idx}.xtc" + if not xtc_path.exists(): + raise FileNotFoundError(f"Missing trajectory: {xtc_path}") + traj = mdtraj.load(str(xtc_path), top=str(eq_path), atom_indices=ca_indices) + frames.append(torch.as_tensor(traj.xyz, dtype=torch.float32) * 10.0) + return torch.cat(frames, dim=0) + + +def flatten_disp(disp, mask): + return (disp * mask[None, :, None]).reshape(disp.shape[0], -1) + + +def per_frame_rms_disp(disp, mask): + denom = mask.sum().clamp_min(1.0) + return torch.sqrt((disp.square().sum(dim=-1) * mask[None]).sum(dim=-1) / denom) + + +def per_residue_rms_disp(disp): + return torch.sqrt(disp.square().sum(dim=-1).mean(dim=0)) + + +def pca_basis_from_md(md_disp, mask, num_pcs): + md_mean = md_disp.mean(dim=0, keepdim=True) + centered = md_disp - md_mean + modes, energy = LatentEncoder.pca_modes_from_centered_displacement( + centered, + mask, + num_modes=num_pcs, + ) + basis = flatten_disp(modes.permute(1, 0, 2), mask) + basis = basis / basis.norm(dim=-1, keepdim=True).clamp_min(1e-8) + return md_mean, basis, energy + + +def projection_stats(disp, md_mean, basis, mask, prefix): + centered = disp - md_mean + flat = flatten_disp(centered, mask) + coeff = flat @ basis.T + total_sq = flat.square().sum(dim=-1).clamp_min(1e-8) + proj_sq = coeff.square().sum(dim=-1) + residual_sq = (flat - coeff @ basis).square().sum(dim=-1) + out = {} + out.update(quantiles(torch.sqrt(total_sq).cpu().numpy(), f"{prefix}_centered_norm")) + out.update(quantiles(torch.sqrt(proj_sq).cpu().numpy(), f"{prefix}_md_pc_proj_norm")) + out.update(quantiles((proj_sq / total_sq).cpu().numpy(), f"{prefix}_md_pc_energy_frac")) + out.update(quantiles(torch.sqrt(residual_sq / total_sq).cpu().numpy(), f"{prefix}_md_pc_residual_rel")) + for idx in range(coeff.shape[1]): + out.update(quantiles(coeff[:, idx].cpu().numpy(), f"{prefix}_md_pc{idx + 1}_coord")) + out[f"{prefix}_md_pc{idx + 1}_var"] = float(coeff[:, idx].var(unbiased=False).cpu().item()) + return out + + +def ensemble_rows(csv_path, atlas_root, ensembles, num_md_pcs, num_proteins=None): + ensure_bbflow_imports() + df = pd.read_csv(csv_path) + if num_proteins is not None: + df = df.head(int(num_proteins)).copy() + dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) + rows = [] + skipped = [] + for idx, pdb_name in enumerate(dataset.pdb_names): + eq_path = Path(atlas_root) / str(pdb_name) / f"{pdb_name}.pdb" + trans_eq, _, _, _ = frames_from_pdb(eq_path) + trans_eq = trans_eq.float() + mask = torch.ones(trans_eq.shape[0], dtype=torch.float32) + md = load_ca_md_frames(atlas_root, pdb_name) + if md.shape[1] != trans_eq.shape[0]: + raise ValueError(f"{pdb_name}: MD CA {md.shape[1]} vs eq {trans_eq.shape[0]}") + + md_disp = LatentEncoder.relative_displacement(md, trans_eq, mask) + md_amp = per_frame_rms_disp(md_disp, mask) + md_res_amp = per_residue_rms_disp(md_disp) + md_mean, basis, md_energy = pca_basis_from_md(md_disp, mask, num_md_pcs) + md_proj = projection_stats(md_disp, md_mean, basis, mask, "md") + + for name, root in ensembles: + pdb_path = Path(root) / str(pdb_name) / "sampled_conformations.pdb" + if not pdb_path.exists(): + skipped.append({"ensemble": name, "pdb_name": str(pdb_name), "path": str(pdb_path)}) + continue + gen = load_ca_pdb(pdb_path) + if gen.shape[1] != trans_eq.shape[0]: + raise ValueError(f"{pdb_name} {name}: generated CA {gen.shape[1]} vs eq {trans_eq.shape[0]}") + gen_disp = LatentEncoder.relative_displacement(gen, trans_eq, mask) + gen_amp = per_frame_rms_disp(gen_disp, mask) + gen_res_amp = per_residue_rms_disp(gen_disp) + gen_proj = projection_stats(gen_disp, md_mean, basis, mask, "gen") + + amp_ratio = gen_amp / md_amp.median().clamp_min(1e-8) + residue_ratio = gen_res_amp / md_res_amp.clamp_min(1e-8) + row = { + "ensemble": name, + "pdb_name": str(pdb_name), + "num_res": int(trans_eq.shape[0]), + "num_md_frames": int(md.shape[0]), + "num_gen_frames": int(gen.shape[0]), + "md_pc1_energy": float(md_energy[0].cpu().item()) if md_energy.numel() > 0 else np.nan, + "md_pc2_energy": float(md_energy[1].cpu().item()) if md_energy.numel() > 1 else np.nan, + "gen_amp_mean_div_md_mean": float(gen_amp.mean().cpu().item() / md_amp.mean().clamp_min(1e-8).cpu().item()), + "gen_amp_median_div_md_median": float(gen_amp.median().cpu().item() / md_amp.median().clamp_min(1e-8).cpu().item()), + "gen_amp_q90_div_md_q90": float( + np.quantile(gen_amp.cpu().numpy(), 0.90) + / max(np.quantile(md_amp.cpu().numpy(), 0.90), 1e-8) + ), + "gen_frac_below_md_q10": float((gen_amp < torch.quantile(md_amp, 0.10)).float().mean().cpu().item()), + "gen_frac_below_half_md_median": float((gen_amp < 0.5 * md_amp.median()).float().mean().cpu().item()), + "residue_rms_ratio_mean": float(residue_ratio.mean().cpu().item()), + "residue_rms_ratio_median": float(residue_ratio.median().cpu().item()), + "residue_frac_below_half_md": float((residue_ratio < 0.5).float().mean().cpu().item()), + **quantiles(md_amp.cpu().numpy(), "md_amp"), + **quantiles(gen_amp.cpu().numpy(), "gen_amp"), + **quantiles(amp_ratio.cpu().numpy(), "gen_amp_div_md_median"), + **md_proj, + **gen_proj, + } + for pc_idx in range(num_md_pcs): + md_var = row.get(f"md_md_pc{pc_idx + 1}_var", np.nan) + gen_var = row.get(f"gen_md_pc{pc_idx + 1}_var", np.nan) + row[f"gen_md_pc{pc_idx + 1}_var_div_md"] = float(gen_var / md_var) if md_var > 1e-8 else np.nan + rows.append(row) + return rows, skipped + + +def epoch_metric_diagnostics(metrics_csv, config_path=None): + df = pd.read_csv(metrics_csv) + rows = [] + if df.empty or "epoch" not in df: + return {"error": "missing epoch column"}, pd.DataFrame() + metric_cols = [ + "train_loss", + "motion_loss", + "local_cov_loss", + "cross_cov_loss", + "cross_cov_far_corr", + "cross_cov_far_loss", + "rmsf_loss", + "pca_align_loss", + "pca_align_weighted_overlap", + "pca_align_top_energy_overlap", + "pca_align_top_energy_subspace_overlap", + "mode_coeff_abs", + "mode_coeff_std", + "mode_max_cosine_abs", + "mode_gram_condition", + "q_nll_loss", + "q_nll_per_dim", + "latent_effective_modes", + ] + metric_cols = [col for col in metric_cols if col in df.columns] + first = df.iloc[0] + last = df.iloc[-1] + epoch29 = df[df["epoch"] == 29] + anchor = epoch29.iloc[0] if not epoch29.empty else first + for col in metric_cols: + rows.append({ + "metric": col, + "first": float(first[col]), + "epoch29_or_first": float(anchor[col]), + "last": float(last[col]), + "change_first_to_last": float(last[col] - first[col]), + "change_epoch29_to_last": float(last[col] - anchor[col]), + "last5_change": float(df[col].tail(5).iloc[-1] - df[col].tail(5).iloc[0]) if len(df) >= 5 else np.nan, + }) + config_summary = {} + if config_path is not None and Path(config_path).exists(): + if OmegaConf is None: + config_summary["warning"] = "omegaconf is not installed; config was not parsed" + return { + "metrics_csv": str(metrics_csv), + "num_epochs": int(len(df)), + "first_epoch": int(first["epoch"]), + "last_epoch": int(last["epoch"]), + "anchor_epoch": int(anchor["epoch"]), + "config_summary": config_summary, + }, pd.DataFrame(rows) + cfg = OmegaConf.load(config_path) + for dotted in [ + "experiment.training.enm_warmup_epochs", + "experiment.training.lambda_enm_warmup", + "experiment.training.lambda_motion", + "experiment.training.lambda_q", + "experiment.training.lambda_mode_orth", + "experiment.training.lambda_mode_recon", + "experiment.training.lambda_pca_align", + "experiment.scheduler.enabled", + "experiment.warmup_lr", + "experiment.warmup_lr_factor", + ]: + cur = cfg + ok = True + for part in dotted.split("."): + if part not in cur: + ok = False + break + cur = cur[part] + if ok: + config_summary[dotted] = cur + return { + "metrics_csv": str(metrics_csv), + "num_epochs": int(len(df)), + "first_epoch": int(first["epoch"]), + "last_epoch": int(last["epoch"]), + "anchor_epoch": int(anchor["epoch"]), + "config_summary": config_summary, + }, pd.DataFrame(rows) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--metrics_csv") + parser.add_argument("--config_path") + parser.add_argument("--csv_path") + parser.add_argument("--atlas_root") + parser.add_argument("--output_dir", required=True) + parser.add_argument("--num_md_pcs", type=int, default=2) + parser.add_argument("--num_proteins", type=int, default=None) + parser.add_argument( + "--ensemble", + action="append", + nargs=2, + metavar=("NAME", "DIR"), + help="Name and directory containing protein/sample_conformations.pdb. Repeatable.", + ) + args = parser.parse_args() + + out_dir = Path(args.output_dir) + out_dir.mkdir(parents=True, exist_ok=True) + summary = { + "metrics_csv": args.metrics_csv, + "config_path": args.config_path, + "csv_path": args.csv_path, + "atlas_root": args.atlas_root, + "num_md_pcs": args.num_md_pcs, + "num_proteins": args.num_proteins, + "ensembles": {name: path for name, path in (args.ensemble or [])}, + } + + if args.metrics_csv: + metric_summary, metric_df = epoch_metric_diagnostics(args.metrics_csv, args.config_path) + metric_df.to_csv(out_dir / "epoch_metric_diagnostics.csv", index=False) + summary["epoch_metrics"] = metric_summary + summary["epoch_metric_meaning"] = { + "mode_coeff_abs/std": "Existing training-time coefficient magnitude; if it falls, c sampling/targets are contracting.", + "local/cross/rmsf/pca losses": "Proxy losses; compare their improvement against downstream degradation.", + "config_summary": "Checks whether warmup/scheduler/loss weights can change after epoch 30.", + } + + if args.ensemble: + if not args.csv_path or not args.atlas_root: + raise ValueError("--csv_path and --atlas_root are required when --ensemble is used") + rows, skipped = ensemble_rows( + args.csv_path, + args.atlas_root, + args.ensemble, + args.num_md_pcs, + args.num_proteins, + ) + per = pd.DataFrame(rows) + per.to_csv(out_dir / "per_protein_contraction.csv", index=False) + aggregate = { + name: numeric_mean([row for row in rows if row["ensemble"] == name]) + for name, _ in args.ensemble + } + summary["ensemble_aggregate"] = aggregate + summary["num_ensemble_rows"] = len(rows) + summary["num_skipped"] = len(skipped) + summary["skipped"] = skipped[:50] + summary["ensemble_metric_meaning"] = { + "gen_amp_*": "Frame-wise Kabsch-aligned CA displacement RMS from x_eq.", + "gen_amp_*_div_md_*": "Generated amplitude divided by MD amplitude at matching summary statistic.", + "gen_frac_below_md_q10": "Fraction of generated frames smaller than the low-amplitude MD tail.", + "gen_md_pc_energy_frac": "How much generated displacement energy lies in the MD top-PC subspace.", + "gen_md_pc*_var_div_md": "Variance along MD PC k relative to MD; values below 1 mean under-dispersed along that PC.", + "residue_rms_ratio_*": "Per-residue generated RMS displacement divided by MD RMS displacement.", + } + + with (out_dir / "contraction_summary.json").open("w") as handle: + json.dump(summary, handle, indent=2) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/diagnose_z.py b/bbflow_base/scripts/diagnose_z.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3c42ae7c4f235069960fd76e4f14e72864d4a0 --- /dev/null +++ b/bbflow_base/scripts/diagnose_z.py @@ -0,0 +1,300 @@ +import argparse +import os +from pathlib import Path + +import numpy as np +import pandas as pd +import torch +from omegaconf import OmegaConf + +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb +from bbflow.models.bbflow_module import BBFlowModule +from bbflow.data.interpolant_bbflow import InterpolantBBFlow + + +def load_module(ckpt_path, device): + ckpt_path = Path(ckpt_path) + cfg_path = ckpt_path.parent / "config.yaml" + if not cfg_path.exists(): + raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}") + repo_root = Path(__file__).resolve().parents[1] + infer_cfg = OmegaConf.load(repo_root / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(cfg_path) + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.inference.interpolant.use_tqdm = False + cfg.model.embed = ckpt_cfg.model.embed + module = BBFlowModule(cfg) + ckpt = torch.load(ckpt_path, map_location="cpu") + current_state = module.state_dict() + compatible_state = { + key: value for key, value in ckpt["state_dict"].items() + if key in current_state and current_state[key].shape == value.shape + } + module.load_state_dict(compatible_state, strict=False) + module.to(device) + module.eval() + return module, cfg + + +def pairwise_ca_rmsd(ca_coords): + flat = ca_coords.reshape(ca_coords.shape[0], -1) + diff = flat[:, None, :] - flat[None, :, :] + return np.sqrt(np.mean(diff ** 2, axis=-1)) + + +def summarize_rmsd(ca_coords, num_z, samples_per_z): + rmsd = pairwise_ca_rmsd(ca_coords) + msd = rmsd ** 2 + within, between, within_msd, between_msd = [], [], [], [] + for i in range(num_z * samples_per_z): + zi = i // samples_per_z + for j in range(i + 1, num_z * samples_per_z): + zj = j // samples_per_z + if zi == zj: + within.append(float(rmsd[i, j])) + within_msd.append(float(msd[i, j])) + else: + between.append(float(rmsd[i, j])) + between_msd.append(float(msd[i, j])) + within_mean = float(np.mean(within)) if within else 0.0 + between_mean = float(np.mean(between)) if between else 0.0 + + grouped = ca_coords.reshape(num_z, samples_per_z, *ca_coords.shape[1:]) + centroids = grouped.mean(axis=1) + centroid_rmsd = pairwise_ca_rmsd(centroids) + centroid_between = [ + float(centroid_rmsd[i, j]) + for i in range(num_z) + for j in range(i + 1, num_z) + ] + centroid_between_mean = float(np.mean(centroid_between)) if centroid_between else 0.0 + + within_msd_mean = float(np.mean(within_msd)) if within_msd else 0.0 + between_msd_mean = float(np.mean(between_msd)) if between_msd else 0.0 + z_signal_msd = max(0.0, between_msd_mean - within_msd_mean) + z_signal_rmsd = float(np.sqrt(z_signal_msd)) + + return { + "within_z_mean": within_mean, + "between_z_mean": between_mean, + "between_over_within": between_mean / max(within_mean, 1e-8), + "within_z_msd_mean": within_msd_mean, + "between_z_msd_mean": between_msd_mean, + "z_signal_msd": z_signal_msd, + "z_signal_rmsd": z_signal_rmsd, + "z_signal_over_within": z_signal_rmsd / max(within_mean, 1e-8), + "centroid_between_z_mean": centroid_between_mean, + "centroid_between_over_within": centroid_between_mean / max(within_mean, 1e-8), + } + + +def select_indices(dataset, pdb_name, num_proteins): + if pdb_name is not None: + names = [name.strip() for name in pdb_name.split(",") if name.strip()] + indices = [] + for name in names: + matches = [i for i, pdb in enumerate(dataset.pdb_names) if pdb == name] + if not matches: + raise ValueError(f"pdb_name not found in csv: {name}") + indices.append(matches[0]) + return indices + return list(range(min(num_proteins, len(dataset)))) + + +def clone_condition(condition): + return { + key: value.clone() if torch.is_tensor(value) else value + for key, value in condition.items() + } + + +def scale_condition(condition, factor): + out = clone_condition(condition) + for key in ["node_cond", "edge_cond"]: + if key in out: + out[key] = out[key] * factor + return out + + +def perturb_mode_channel(condition, mode_idx, factor): + out = clone_condition(condition) + if "node_cond" in out: + out["node_cond"][..., mode_idx] = out["node_cond"][..., mode_idx] * factor + if "edge_cond" in out: + out["edge_cond"][..., mode_idx] = out["edge_cond"][..., mode_idx] * factor + return out + + +def repeat_condition(module, condition, batch_size): + return module.latent_encoder.repeat_condition(condition, batch_size) + + +def condition_abs_std(condition): + values = [] + for key in ["node_cond", "edge_cond"]: + if key in condition: + values.append(condition[key].detach().float().reshape(-1)) + merged = torch.cat(values) if values else torch.zeros(1) + return float(merged.abs().mean().cpu().item()), float(merged.std().cpu().item()) + + +def make_z_variants(module, trans_eq, rotmats_eq, seq, res_mask, num_z, z_delta, mode): + base_condition = module.latent_encoder.sample_prior_z(trans_eq, rotmats_eq, seq, res_mask) + variants = [] + with torch.no_grad(): + center = (num_z - 1) / 2.0 + if mode == "scale": + for z_idx in range(num_z): + factor = 1.0 + (z_idx - center) * z_delta + variants.append(scale_condition(base_condition, factor)) + else: + num_modes = int(base_condition["node_cond"].shape[-1]) + for z_idx in range(num_z): + mode_idx = z_idx % num_modes + factor = 1.0 + (z_idx - center) * z_delta + variants.append(perturb_mode_channel(base_condition, mode_idx, factor)) + return base_condition, variants + + +def diagnose_one(module, cfg, interpolant, dataset, idx, args, device): + item = dataset[idx] + pdb_name = item["pdb_name"] + trans_eq = item["trans_equilibrium"][None].to(device) + rotmats_eq = item["rotmats_equilibrium"][None].to(device) + seq = item["seq"][None].to(device) + _, num_res = trans_eq.shape[:2] + res_mask = torch.ones(1, num_res, device=device) + + all_ca = [] + labels = [] + with torch.no_grad(): + base_condition, z_variants = make_z_variants( + module, trans_eq, rotmats_eq, seq, res_mask, + args.num_z, args.z_delta, args.z_mode, + ) + for z_idx, z_one in enumerate(z_variants): + z = repeat_condition(module, z_one, args.samples_per_z) + atom37_traj, _, _ = interpolant.sample( + args.samples_per_z, + num_res, + module.model, + trans_eq.repeat(args.samples_per_z, 1, 1), + rotmats_eq.repeat(args.samples_per_z, 1, 1, 1), + seq.repeat(args.samples_per_z, 1, 1), + z=z, + ) + final_atom37 = torch.stack(atom37_traj, dim=1)[:, -1] + ca = final_atom37[:, :, 1, :].detach().cpu().numpy() + all_ca.append(ca) + labels.extend([f"z{z_idx}_sample{i}" for i in range(args.samples_per_z)]) + + all_ca = np.concatenate(all_ca, axis=0) + rmsd = pairwise_ca_rmsd(all_ca) + summary = summarize_rmsd(all_ca, args.num_z, args.samples_per_z) + base_abs, base_std = condition_abs_std(base_condition) + summary.update({ + "pdb_name": pdb_name, + "num_res": int(num_res), + "num_z": args.num_z, + "samples_per_z": args.samples_per_z, + "z_delta": args.z_delta, + "z_mode": args.z_mode, + "base_condition_abs_mean": base_abs, + "base_condition_std": base_std, + "base_energy_mean": float(base_condition["energy"].detach().float().mean().cpu().item()), + "base_effective_modes": float(module.latent_encoder.motion_metrics(base_condition, res_mask)["latent_effective_modes"].detach().cpu().item()), + }) + + out_dir = Path(args.output_dir) / pdb_name + os.makedirs(out_dir, exist_ok=True) + np.save(out_dir / "ca_coords.npy", all_ca) + np.save(out_dir / "ca_rmsd_matrix.npy", rmsd) + pd.DataFrame(rmsd, index=labels, columns=labels).to_csv(out_dir / "ca_rmsd_matrix.csv") + pd.Series(summary).to_json(out_dir / "summary.json", indent=2) + return summary + + +def aggregate(rows): + df = pd.DataFrame(rows) + ratio = df["between_over_within"] + centroid_ratio = df["centroid_between_over_within"] + signal_ratio = df["z_signal_over_within"] + return { + "num_proteins": int(len(df)), + "within_z_mean_mean": float(df["within_z_mean"].mean()), + "between_z_mean_mean": float(df["between_z_mean"].mean()), + "between_over_within_mean": float(ratio.mean()), + "between_over_within_std": float(ratio.std(ddof=0)), + "between_over_within_min": float(ratio.min()), + "between_over_within_max": float(ratio.max()), + "fraction_gt_1.0": float((ratio > 1.0).mean()), + "fraction_gt_1.2": float((ratio > 1.2).mean()), + "centroid_between_z_mean_mean": float(df["centroid_between_z_mean"].mean()), + "centroid_between_over_within_mean": float(centroid_ratio.mean()), + "centroid_between_over_within_std": float(centroid_ratio.std(ddof=0)), + "centroid_between_over_within_min": float(centroid_ratio.min()), + "centroid_between_over_within_max": float(centroid_ratio.max()), + "z_signal_rmsd_mean": float(df["z_signal_rmsd"].mean()), + "z_signal_over_within_mean": float(signal_ratio.mean()), + "z_signal_over_within_std": float(signal_ratio.std(ddof=0)), + "z_signal_over_within_min": float(signal_ratio.min()), + "z_signal_over_within_max": float(signal_ratio.max()), + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--csv_path", required=True) + parser.add_argument("--pdb_name", default=None) + parser.add_argument("--num_proteins", type=int, default=10) + parser.add_argument("--output_dir", default="outputs/diagnose_z") + parser.add_argument("--num_z", type=int, default=8) + parser.add_argument("--samples_per_z", type=int, default=8) + parser.add_argument("--z_delta", type=float, default=0.25) + parser.add_argument("--z_mode", choices=["dimension", "scale"], default="dimension") + parser.add_argument("--device", default="cuda") + args = parser.parse_args() + + device = torch.device(args.device if torch.cuda.is_available() or args.device == "cpu" else "cpu") + module, cfg = load_module(args.ckpt_path, device) + if not getattr(module, "latent_enabled", False): + raise ValueError("Checkpoint/config has latent.enable=false; diagnose_z requires latent model.") + + csv = pd.read_csv(args.csv_path) + dataset = PDBDatasetBBFlowFromPdb(csv, sort=False) + indices = select_indices(dataset, args.pdb_name, args.num_proteins) + + interpolant = InterpolantBBFlow(cfg.inference.interpolant) + interpolant.set_device(device) + + os.makedirs(args.output_dir, exist_ok=True) + rows = [] + for n, idx in enumerate(indices, start=1): + row = diagnose_one(module, cfg, interpolant, dataset, idx, args, device) + rows.append(row) + print( + f"[{n}/{len(indices)}] {row['pdb_name']} " + f"raw_between/within={row['between_over_within']:.4f} " + f"centroid_between/within={row['centroid_between_over_within']:.4f} " + f"z_signal_rmsd={row['z_signal_rmsd']:.4f} " + f"within={row['within_z_mean']:.4f}" + ) + + df = pd.DataFrame(rows) + agg = aggregate(rows) + out_dir = Path(args.output_dir) + df.to_csv(out_dir / "summary_by_protein.csv", index=False) + pd.Series(agg).to_json(out_dir / "summary_aggregate.json", indent=2) + print("\nAggregate") + print(pd.Series(agg).to_string()) + print(f"Wrote z diagnostics to {out_dir}") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/diagnose_z.py.bak.20260621_155301 b/bbflow_base/scripts/diagnose_z.py.bak.20260621_155301 new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/bbflow_base/scripts/download_atlas.py b/bbflow_base/scripts/download_atlas.py new file mode 100644 index 0000000000000000000000000000000000000000..fa1d58cb04770574a27d799c7ef5fadedf623c0f --- /dev/null +++ b/bbflow_base/scripts/download_atlas.py @@ -0,0 +1,225 @@ + +import os +import argparse +import shutil +import subprocess +import time +import zipfile +import pandas as pd +from tqdm import tqdm +import mdtraj + + +def expected_entry_paths(out_root, pdb_name): + pdb_out_dir = os.path.join(out_root, pdb_name) + return [ + os.path.join(pdb_out_dir, f"{pdb_name}.pdb"), + os.path.join(pdb_out_dir, f"{pdb_name}_R1.xtc"), + os.path.join(pdb_out_dir, f"{pdb_name}_R2.xtc"), + os.path.join(pdb_out_dir, f"{pdb_name}_R3.xtc"), + ] + + +def entry_is_complete(out_root, pdb_name): + return all(os.path.isfile(path) and os.path.getsize(path) > 0 + for path in expected_entry_paths(out_root, pdb_name)) + + +def download_entry(out_root, name, chain, max_retries, retry_delay): + pdb_name = name + chain + pdb_out_dir = os.path.join(out_root, pdb_name) + results_link = ( + f"https://www.dsimb.inserm.fr/ATLAS/api/ATLAS/analysis/{name}_{chain}" + ) + + if entry_is_complete(out_root, pdb_name): + return + + last_error = None + for attempt in range(1, max_retries + 1): + if os.path.isdir(pdb_out_dir): + shutil.rmtree(pdb_out_dir) + os.makedirs(pdb_out_dir, exist_ok=True) + zip_path = os.path.join(pdb_out_dir, f"{pdb_name}_analysis.zip") + + try: + subprocess.run( + ["wget", "-q", results_link, "-O", zip_path], + check=True, + ) + with zipfile.ZipFile(zip_path, "r") as zip_ref: + all_files = zip_ref.namelist() + source_prefix = f"{name}_{chain}" + archive_files = [ + path for path in all_files + if path.endswith(".pdb") or path.endswith(".xtc") + ] + for archive_path in archive_files: + zip_ref.extract(archive_path, pdb_out_dir) + source_path = os.path.join(pdb_out_dir, archive_path) + output_name = os.path.basename(archive_path).replace( + source_prefix, pdb_name + ) + os.replace( + source_path, + os.path.join(pdb_out_dir, output_name), + ) + + if os.path.isfile(zip_path): + os.remove(zip_path) + if not entry_is_complete(out_root, pdb_name): + raise RuntimeError( + f"Downloaded archive for {pdb_name} did not contain " + "the expected PDB and three XTC files" + ) + return + except KeyboardInterrupt: + if os.path.isdir(pdb_out_dir): + shutil.rmtree(pdb_out_dir) + raise + except (OSError, subprocess.CalledProcessError, zipfile.BadZipFile, + RuntimeError) as exc: + last_error = exc + print( + f"[download] {pdb_name} attempt {attempt}/{max_retries} " + f"failed: {exc}" + ) + if attempt < max_retries: + time.sleep(retry_delay) + + if os.path.isdir(pdb_out_dir): + shutil.rmtree(pdb_out_dir) + raise RuntimeError( + f"Failed to download {pdb_name} after {max_retries} attempts" + ) from last_error + + +def download_data( + out_root: str, + train_csv: str=None, + validation_csv: str=None, + test_csv: str=None, + out_csv_folder: str="./dataset_csv", + max_entries_per_csv: int=None, + max_retries: int=5, + retry_delay: float=10.0, +): + csv_files = [train_csv, validation_csv, test_csv] + out_names = ['train', 'validation', 'test'] + + for csv_file, out_name in zip(csv_files, out_names): + if csv_file is None: + continue + print(f"Processing CSV file: {csv_file}") + df_metadata = pd.read_csv(csv_file) + + names = [] + modeled_seq_lens = [] + folders = [] + num_conformations = [] + pdb_paths = [] + + pbar = tqdm( + enumerate(df_metadata.iterrows()), + total=len(df_metadata) if max_entries_per_csv is None else min(len(df_metadata), max_entries_per_csv), + ) + for i, (index, row) in pbar: + pdb_name = row['pdb_name'] if 'pdb_name' in row else row['name'] + if "_" in pdb_name: + name = pdb_name.split("_")[0] + chain = pdb_name.split("_")[1] + else: + name = pdb_name[:4] + chain = pdb_name[4] + pdb_name = name + chain + if entry_is_complete(out_root, pdb_name): + pbar.set_description(f"Using cached {pdb_name}") + else: + pbar.set_description(f"Downloading {pdb_name}") + + pdb_out_dir = os.path.join(out_root, pdb_name) + download_entry( + out_root, + name, + chain, + max_retries=max_retries, + retry_delay=retry_delay, + ) + + # Collect metadata + names.append(pdb_name) + pdb_paths.append(os.path.abspath(os.path.join(pdb_out_dir, f"{pdb_name}.pdb"))) + if out_name == 'train': + folders.append(os.path.abspath(pdb_out_dir)) + if 'modeled_seq_len' in row and 'num_conformations' in row: + modeled_seq_lens.append(row['modeled_seq_len']) + num_conformations.append(row['num_conformations']) + else: + traj = mdtraj.load( + os.path.join(pdb_out_dir, f"{pdb_name}_R1.xtc"), + top=os.path.join(pdb_out_dir, f"{pdb_name}.pdb") + ) + modeled_seq_lens.append(traj.n_residues) + num_conformations.append(traj.n_frames) + + + if max_entries_per_csv is not None and i + 1 >= max_entries_per_csv: + break + + out_metadata = { + 'name': names, + } + if out_name == 'train': + out_metadata['modeled_seq_len'] = modeled_seq_lens + out_metadata['pdb_path'] = pdb_paths + out_metadata['folder'] = folders + out_metadata['num_conformations'] = num_conformations + else: + out_metadata['pdb_path'] = pdb_paths + + out_df = pd.DataFrame(out_metadata) + if out_name == 'train': + out_df = out_df.sort_values(by='modeled_seq_len').reset_index(drop=True) + + out_csv_folder_ = os.path.join(out_csv_folder, out_name) + if not os.path.exists(out_csv_folder_): + os.makedirs(out_csv_folder_) + out_csv_path = os.path.join(out_csv_folder_, f"ATLAS_{out_name}.csv") + out_df.to_csv(out_csv_path, index=False) + print(f"Saved metadata to {out_csv_path}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description='Download ATLAS dataset') + parser.add_argument('--out_folder', type=str, default='./datasets/ATLAS', help='Path to the download folder') + parser.add_argument('--train_csv', type=str, default='dataset_csv/ATLAS_split/ATLAS_train.csv', help='Path to the training CSV file with PDB entries to download') + parser.add_argument('--validation_csv', type=str, default='dataset_csv/ATLAS_split/ATLAS_validation.csv', help='Path to the validation CSV file with PDB entries to download') + parser.add_argument('--test_csv', type=str, default='dataset_csv/ATLAS_split/ATLAS_test.csv', help='Path to the test CSV file with PDB entries to download') + parser.add_argument('--out_csv_folder', type=str, default="./dataset_csv", help='Folder to save the output CSV files') + parser.add_argument('--max_entries_per_split', type=int, default=None, help='Maximum number of entries to download per CSV file') + parser.add_argument('--max_retries', type=int, default=5, help='Retries per ATLAS entry') + parser.add_argument('--retry_delay', type=float, default=10.0, help='Seconds between retries') + args = parser.parse_args() + + # Example usage: + # python scripts/download_atlas.py + # --out_folder=./datasets/ATLAS + # --train_csv=./dataset_csv/ATLAS_split/ATLAS_train.csv + # --validation_csv=./dataset_csv/ATLAS_split/ATLAS_validation.csv + # --test_csv=./dataset_csv/ATLAS_split/ATLAS_test.csv + # --out_csv_folder=./dataset_csv/ + + + download_data( + out_root=args.out_folder, + train_csv=args.train_csv, + validation_csv=args.validation_csv, + test_csv=args.test_csv, + out_csv_folder=args.out_csv_folder, + max_entries_per_csv=args.max_entries_per_split, + max_retries=args.max_retries, + retry_delay=args.retry_delay, + ) + + + diff --git a/bbflow_base/scripts/download_models.py b/bbflow_base/scripts/download_models.py new file mode 100644 index 0000000000000000000000000000000000000000..4ca4b97eab07c1e76548477d7def638a99a8499e --- /dev/null +++ b/bbflow_base/scripts/download_models.py @@ -0,0 +1,5 @@ +from bbflow.deployment.bbflow import BBFlow + +BBFlow.from_tag('bbflow-mini-0.1') +BBFlow.from_tag('bbflow-multimer-0.2') +BBFlow.from_tag('latest') \ No newline at end of file diff --git a/bbflow_base/scripts/eval_held_out_mode_recon.py b/bbflow_base/scripts/eval_held_out_mode_recon.py new file mode 100644 index 0000000000000000000000000000000000000000..f7ba8c9b9af4a91902c7a708cde228b74d098198 --- /dev/null +++ b/bbflow_base/scripts/eval_held_out_mode_recon.py @@ -0,0 +1,344 @@ +#!/usr/bin/env python +""" +Stage-1 GATE metric: held-out displacement-reconstruction error of the predicted +motion subspace U = f(X_eq), with the full diagnostic protocol needed before +concluding anything from a single number: + + 1. SAME-GATE train-split eval (apples-to-apples vs the held-out number; the + live training loop's mode_recon_rel_error uses different batching/masking + and is NOT directly comparable to this script's per-protein full-MD-frame + eval -- see HANDOFF discussion). + 2. ALL-EPOCH sweep on held-out (checks for overfitting-with-training / picks + the best checkpoint by validation instead of just reading the last one). + 3. random / untrained U baselines, so a bare rel_error number has a floor to + compare against: random = a random orthonormal K-dim subspace (no network, + no X_eq dependence at all); untrained = a freshly-initialized LatentEncoder + (same architecture/K, never trained) run on the real X_eq. + + 1 - r^2 (r = rel_error) is the fraction of MD displacement ENERGY explained by + the K-dim subspace (Pythagorean identity for an orthogonal/ridge-lstsq + projection). Report r AND 1-r^2 -- r alone overstates how bad/good a number is. + +NO-LEAKAGE CONTRACT + --csv_path is REQUIRED (no default). This script never reads any other split's + CSV and never touches the training dataloader. + +USAGE + # single checkpoint, trained U, one split: + python scripts/eval_held_out_mode_recon.py --run_dir RUN --csv_path CSV \ + --cache_path CACHE --frames_per_protein 20 + + # all epochs, held-out, to see over/under-fitting across training: + python scripts/eval_held_out_mode_recon.py --run_dir RUN --csv_path VAL_CSV \ + --cache_path CACHE --all_epochs + + # random / untrained baselines (checkpoint choice is irrelevant for these + # except --run_dir's config.yaml is used to build a same-K fresh encoder): + python scripts/eval_held_out_mode_recon.py --run_dir RUN --csv_path VAL_CSV \ + --cache_path CACHE --baseline random + python scripts/eval_held_out_mode_recon.py --run_dir RUN --csv_path VAL_CSV \ + --cache_path CACHE --baseline untrained +""" +import argparse +import glob +import os +import sys + +import numpy as np +import torch +import mdtraj +import pandas as pd +from omegaconf import OmegaConf + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from bbflow.data.utils import frames_from_pdb, backbone_to_frames +from bbflow.models.bbflow_module import BBFlowModule +from bbflow.models.latent import LatentEncoder + + +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 load_mean_disp_cache(cache_path): + cache = torch.load(cache_path, map_location="cpu", weights_only=False) + targets = cache["motion_targets"] if isinstance(cache, dict) and "motion_targets" in cache else cache + out = {} + for key, value in targets.items(): + if "oracle_mean_disp" not in value: + continue + md = torch.as_tensor(value["oracle_mean_disp"], dtype=torch.float32) + for name in pdb_name_variants(str(key)): + out[name] = md + return out + + +def list_epoch_checkpoints(run_dir): + return sorted(glob.glob(os.path.join(run_dir, "epoch:*.ckpt"))) + + +def pick_checkpoint(run_dir, ckpt_name=None): + if ckpt_name: + return os.path.join(run_dir, ckpt_name) + candidates = list_epoch_checkpoints(run_dir) + if candidates: + return candidates[-1] + last = os.path.join(run_dir, "last.ckpt") + if os.path.exists(last): + return last + raise FileNotFoundError(f"No epoch:*.ckpt or last.ckpt found in {run_dir}") + + +def build_module(run_dir, device, ckpt_path=None): + """Build BBFlowModule from run_dir's config.yaml. If ckpt_path is given, load + its weights (the 'trained' condition). If None, leave the module at its + from-scratch random init (the 'untrained' baseline: same architecture/K, + never saw a gradient step).""" + cfg_path = os.path.join(run_dir, "config.yaml") + cfg = OmegaConf.load(cfg_path) + module = BBFlowModule(cfg) + if ckpt_path is not None: + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + state_dict = ckpt["state_dict"] if "state_dict" in ckpt else ckpt + current_state = module.state_dict() + compatible = { + k: v for k, v in state_dict.items() + if k in current_state and current_state[k].shape == v.shape + } + missing = len(current_state) - len(compatible) + print(f"[load] {os.path.basename(ckpt_path)}: matched {len(compatible)}/{len(current_state)} " + f"tensors ({missing} unmatched -- should be ~0 for a same-config checkpoint)") + module.load_state_dict(compatible, strict=False) + module.eval() + module.to(device) + return module + + +def reload_checkpoint_(module, ckpt_path): + """In-place weight swap for the all-epoch sweep -- avoids rebuilding the + module (and re-reading config.yaml) 15 times.""" + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + state_dict = ckpt["state_dict"] if "state_dict" in ckpt else ckpt + current_state = module.state_dict() + compatible = { + k: v for k, v in state_dict.items() + if k in current_state and current_state[k].shape == v.shape + } + module.load_state_dict(compatible, strict=False) + module.eval() + + +def random_orthonormal_modes(N, K, device): + """A random K-dim linear subspace of the full 3N-dim displacement space, via + QR on a Gaussian matrix. Independent of X_eq and of any network -- the floor + baseline: if trained-U barely beats this, U carries ~no learned information.""" + g = torch.randn(N * 3, K, device=device) + q, _ = torch.linalg.qr(g) # [3N, K], orthonormal columns + return q.reshape(N, 3, K).permute(0, 2, 1) # -> [N, K, 3], matches u_global layout + + +def sample_frame_indices(traj_path, n_frames): + with mdtraj.open(traj_path) as f: + total = len(f) + if total <= 0: + return [] + n = min(n_frames, total) + return np.linspace(0, total - 1, n, dtype=int).tolist() + + +def load_md_frame_trans(traj_path, eq_path, frame_idx, seq_letters): + conf = mdtraj.load_frame(traj_path, frame_idx, top=eq_path) + N_atoms = conf.xyz[0, conf.top.select("name N"), :] * 10 + CA_atoms = conf.xyz[0, conf.top.select("name CA"), :] * 10 + C_atoms = conf.xyz[0, conf.top.select("name C"), :] * 10 + data = backbone_to_frames(N_atoms, CA_atoms, C_atoms, seq_letters) + return data["trans"] # [N, 3] + + +def load_protein_cache(csv_path, mean_disp_cache, frames_per_protein, max_proteins, device, random_seed=None): + """Load MD frames / eq structure / mean_disp ONCE per protein. Reused across + every checkpoint/epoch/baseline evaluated against this CSV -- an all-epoch + sweep does NOT re-read MD trajectories per epoch.""" + csv = pd.read_csv(csv_path) + if max_proteins: + # NOTE: .iloc[:max_proteins] takes the CSV's first N rows, not a random + # sample. If the CSV has any ordering (by length, difficulty, source...) + # that subsets non-representatively. Pass random_seed to draw a real + # random sample instead when comparing against a held-out split. + if random_seed is not None: + csv = csv.sample(n=min(max_proteins, len(csv)), random_state=random_seed) + else: + csv = csv.iloc[:max_proteins] + + proteins, skipped = [], [] + for _, row in csv.iterrows(): + name = row["name"] + # Two CSV schemas exist: train (name, folder, pdb_path, ...) and + # validation/test (name, pdb_path only). dirname(pdb_path) == folder in + # both (verified against a train-CSV row). + if "pdb_path" in row and pd.notna(row.get("pdb_path")): + eq_path = row["pdb_path"] + folder = os.path.dirname(eq_path) + else: + folder = row["folder"] + eq_path = os.path.join(folder, f"{name}.pdb") + traj_path = os.path.join(folder, f"{name}_R1.xtc") + if not os.path.exists(traj_path): + skipped.append((name, f"missing trajectory: {traj_path}")) + continue + + mean_disp = None + for variant in pdb_name_variants(name): + if variant in mean_disp_cache: + mean_disp = mean_disp_cache[variant] + break + if mean_disp is None: + skipped.append((name, "no oracle_mean_disp in cache")) + continue + + frame_idxs = sample_frame_indices(traj_path, frames_per_protein) + if not frame_idxs: + skipped.append((name, f"empty trajectory: {traj_path}")) + continue + + trans_eq, rotmats_eq, seq_onehot, _ = frames_from_pdb(eq_path) + seq_letters = list(mdtraj.load(eq_path).top.to_fasta()[0]) + trans_1 = torch.stack( + [load_md_frame_trans(traj_path, eq_path, i, seq_letters) for i in frame_idxs], dim=0 + ).to(device) # [B, N, 3] + + proteins.append({ + "name": name, + "N": trans_eq.shape[0], + "trans_eq": trans_eq.to(device), + "rotmats_eq": rotmats_eq.to(device), + "seq_onehot": seq_onehot.to(device), + "trans_1": trans_1, + "mean_disp": mean_disp.to(device), + }) + return proteins, skipped + + +def eval_cache(host_encoder, proteins, device, baseline, source_module=None, num_modes=None): + """host_encoder: a LatentEncoder instance used for the projection math + (frame_condition_from_projection) -- its ridge/detach hyperparameters, NOT + necessarily the source of u_global. + baseline: 'trained' (u_global from source_module.latent_encoder, i.e. the + loaded checkpoint), 'untrained' (u_global from host_encoder itself, freshly + initialized, never loaded any checkpoint), 'random' (u_global = random + orthonormal subspace, no network at all).""" + per_protein = [] + for p in proteins: + B = p["trans_1"].shape[0] + N = p["N"] + res_mask_1 = torch.ones(1, N, device=device) + with torch.no_grad(): + if baseline == "random": + u1 = random_orthonormal_modes(N, num_modes, device)[None] # [1,N,K,3] + else: + src = source_module.latent_encoder if baseline == "trained" else host_encoder + prior_condition_1, _ = src.forward_prior( + p["trans_eq"][None], p["rotmats_eq"][None], p["seq_onehot"][None], res_mask_1 + ) + u1 = prior_condition_1["u_global"] + u_b = LatentEncoder.repeat_condition({"u_global": u1}, B)["u_global"] + trans_eq_b = p["trans_eq"][None].expand(B, -1, -1) + rotmats_eq_b = p["rotmats_eq"][None].expand(B, -1, -1, -1) + res_mask_b = torch.ones(B, N, device=device) + condition, _ = host_encoder.frame_condition_from_projection( + p["trans_1"], trans_eq_b, rotmats_eq_b, res_mask_b, {"u_global": u_b}, + mean_disp=p["mean_disp"], + ) + rel_error = condition["projection_recon_rel_error"].detach().cpu().numpy() + per_protein.append((p["name"], float(np.mean(rel_error)))) + return per_protein + + +def report(per_protein, label): + if not per_protein: + print(f"[gate] {label}: NO proteins evaluated.") + return + values = np.array([v for _, v in per_protein]) + energy = 1.0 - values ** 2 + print(f"[gate] {label}") + print(f" rel_error mean={values.mean():.4f} median={np.median(values):.4f}") + print(f" energy(1-r^2) mean={energy.mean():.4f} median={np.median(energy):.4f} " + f"(fraction of MD displacement variance explained)") + worst = sorted(per_protein, key=lambda x: -x[1])[:5] + print(f" worst5 = {worst}") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--run_dir", required=True) + ap.add_argument("--ckpt_name", default=None, help="single-checkpoint mode: default latest epoch:*.ckpt") + ap.add_argument("--all_epochs", action="store_true", help="sweep every epoch:*.ckpt in run_dir") + ap.add_argument("--baseline", choices=["trained", "untrained", "random"], default="trained") + ap.add_argument("--csv_path", required=True, + help="EXACT split to evaluate. Never pass a mix of splits.") + ap.add_argument("--cache_path", required=True, help="motion-target cache with oracle_mean_disp") + ap.add_argument("--frames_per_protein", type=int, default=20) + ap.add_argument("--max_proteins", type=int, default=None) + ap.add_argument("--random_seed", type=int, default=None, + help="if set with --max_proteins, draw a RANDOM sample of that many " + "rows instead of the CSV's first N (default .iloc[:N] is order-biased)") + ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") + args = ap.parse_args() + + split_name = os.path.basename(args.csv_path) + print(f"[gate] split file: {args.csv_path} baseline={args.baseline}") + + mean_disp_cache = load_mean_disp_cache(args.cache_path) + proteins, skipped = load_protein_cache( + args.csv_path, mean_disp_cache, args.frames_per_protein, args.max_proteins, args.device, + random_seed=args.random_seed, + ) + print(f"[gate] loaded {len(proteins)} proteins, skipped {len(skipped)}") + for name, err in skipped: + print(f" SKIP {name}: {err}") + if not proteins: + print("[gate] nothing to evaluate.") + return + + cfg = OmegaConf.load(os.path.join(args.run_dir, "config.yaml")) + num_modes = int(cfg.latent.num_modes) + + if args.baseline == "random": + host = LatentEncoder(cfg.latent).to(args.device).eval() + per_protein = eval_cache(host, proteins, args.device, "random", num_modes=num_modes) + report(per_protein, f"{split_name} K={num_modes} baseline=random") + return + + if args.baseline == "untrained": + host = LatentEncoder(cfg.latent).to(args.device).eval() + per_protein = eval_cache(host, proteins, args.device, "untrained") + report(per_protein, f"{split_name} K={num_modes} baseline=untrained") + return + + # baseline == "trained" + if args.all_epochs: + ckpts = list_epoch_checkpoints(args.run_dir) + if not ckpts: + print(f"[gate] no epoch:*.ckpt found in {args.run_dir}") + return + module = build_module(args.run_dir, args.device, ckpt_path=ckpts[0]) + for ckpt_path in ckpts: + reload_checkpoint_(module, ckpt_path) + per_protein = eval_cache(module.latent_encoder, proteins, args.device, "trained", source_module=module) + epoch_tag = os.path.basename(ckpt_path) + report(per_protein, f"{split_name} {epoch_tag}") + else: + ckpt_path = pick_checkpoint(args.run_dir, args.ckpt_name) + module = build_module(args.run_dir, args.device, ckpt_path=ckpt_path) + per_protein = eval_cache(module.latent_encoder, proteins, args.device, "trained", source_module=module) + report(per_protein, f"{split_name} {os.path.basename(ckpt_path)}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/evaluate_saved_condition_covariances.py b/bbflow_base/scripts/evaluate_saved_condition_covariances.py new file mode 100644 index 0000000000000000000000000000000000000000..d30d98943cbca52c57ad5d228518da893989acb6 --- /dev/null +++ b/bbflow_base/scripts/evaluate_saved_condition_covariances.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python +"""Evaluate saved sampled_conformations.pdb ensembles against MD motion targets. + +This script does not sample. It reads existing standard downstream PDBs and +computes the same RMSF/local/cross-covariance diagnostics used by the probe. +""" +import argparse +import json +from pathlib import Path +import sys + +import mdtraj +import numpy as np +import pandas as pd +import torch + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb +from scripts.fit_motion_template_upper_bound import load_motion_targets, pdb_name_variants +from scripts.probe_condition_ensemble_cov import ensemble_motion_stats +from scripts.probe_condition_quality_vs_md import evaluate_against_target + + +def target_for_pdb(targets, pdb_name): + for name in pdb_name_variants(str(pdb_name)): + if name in targets: + return targets[name] + raise KeyError(f"No motion target for {pdb_name}") + + +def load_saved_ca(path, device): + traj = mdtraj.load(str(path)) + ca_idx = traj.top.select("name CA") + if ca_idx.size == 0: + raise ValueError(f"No CA atoms found in {path}") + return torch.as_tensor(traj.xyz[:, ca_idx, :] * 10.0, dtype=torch.float32, device=device) + + +def numeric_mean(rows): + out = {} + if not rows: + return out + keys = sorted({key for row in rows for key in row.keys()}) + for key in keys: + vals = [row[key] for row in rows if isinstance(row.get(key), (int, float))] + if vals: + out[key] = float(np.mean(vals)) + return out + + +def improvement_vs(metrics, baseline, prefix): + out = {} + for key, value in metrics.items(): + if not isinstance(value, (int, float)) or key not in baseline: + continue + if key.endswith("_rel_loss"): + out[f"{prefix}_{key}_delta"] = float(value - baseline[key]) + out[f"{prefix}_{key}_improvement"] = float(baseline[key] - value) + elif key.endswith("_corr") or key.endswith("sign_agree"): + out[f"{prefix}_{key}_delta"] = float(value - baseline[key]) + return out + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--csv_path", required=True) + parser.add_argument("--motion_target_cache_path", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--near_distance", type=float, default=12.0) + parser.add_argument("--device", default="cpu") + parser.add_argument( + "--ensemble", + action="append", + nargs=2, + metavar=("NAME", "DIR"), + required=True, + help="Condition name and directory containing protein/sample_conformations.pdb. Repeatable.", + ) + args = parser.parse_args() + + device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu") + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + df = pd.read_csv(args.csv_path) + dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) + targets = load_motion_targets(args.motion_target_cache_path) + ensembles = [(name, Path(path)) for name, path in args.ensemble] + + rows = [] + skipped = [] + for idx, pdb_name in enumerate(dataset.pdb_names): + item = dataset[idx] + trans_eq = item["trans_equilibrium"].to(device=device, dtype=torch.float32) + mask = torch.ones(trans_eq.shape[0], device=device) + spatial_dists = torch.cdist(trans_eq, trans_eq) + target = target_for_pdb(targets, pdb_name) + + for condition, ensemble_dir in ensembles: + pdb_path = ensemble_dir / str(pdb_name) / "sampled_conformations.pdb" + if not pdb_path.is_file(): + skipped.append({"pdb_name": pdb_name, "condition": condition, "path": str(pdb_path)}) + continue + ca = load_saved_ca(pdb_path, device) + if ca.shape[1] != trans_eq.shape[0]: + raise ValueError( + f"Length mismatch for {pdb_name} {condition}: " + f"PDB CA {ca.shape[1]} vs equilibrium {trans_eq.shape[0]}" + ) + stats = ensemble_motion_stats(ca, trans_eq, mask) + metrics = evaluate_against_target(stats, target, mask, spatial_dists, args.near_distance) + rows.append({ + "pdb_name": pdb_name, + "condition": condition, + "num_res": int(trans_eq.shape[0]), + "num_samples": int(ca.shape[0]), + **metrics, + }) + + per_protein = pd.DataFrame(rows) + per_protein.to_csv(output_dir / "per_protein_metrics.csv", index=False) + + aggregate = { + condition: numeric_mean([row for row in rows if row["condition"] == condition]) + for condition, _ in ensembles + } + + deltas = [] + condition_names = [name for name, _ in ensembles] + if "real" in condition_names: + by_protein = {} + for row in rows: + by_protein.setdefault(row["pdb_name"], {})[row["condition"]] = row + for pdb_name, condition_rows in by_protein.items(): + real = condition_rows.get("real") + if real is None: + continue + out = {"pdb_name": pdb_name, "num_res": real["num_res"], "num_samples": real["num_samples"]} + for baseline_name in condition_names: + if baseline_name == "real" or baseline_name not in condition_rows: + continue + out.update(improvement_vs(real, condition_rows[baseline_name], f"real_minus_{baseline_name}")) + deltas.append(out) + + delta_df = pd.DataFrame(deltas) + if not delta_df.empty: + delta_df.to_csv(output_dir / "real_vs_baseline_deltas.csv", index=False) + + summary = { + "ensembles": {name: str(path) for name, path in ensembles}, + "csv_path": str(args.csv_path), + "motion_target_cache_path": str(args.motion_target_cache_path), + "near_distance": args.near_distance, + "num_rows": len(rows), + "num_skipped": len(skipped), + "skipped": skipped[:20], + "aggregate_by_condition": aggregate, + "delta_means": numeric_mean(deltas), + } + with (output_dir / "summary.json").open("w") as handle: + json.dump(summary, handle, indent=2) + + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/export_condition_modes.py b/bbflow_base/scripts/export_condition_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..4e67313fc77ed7c4ed66f1bf32f98ecc1c1caf70 --- /dev/null +++ b/bbflow_base/scripts/export_condition_modes.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +"""Export learned condition modes from a BBFlow/A30 checkpoint. + +The covariance transport script consumes one ``.npy`` file per +protein, with shape [N, K, 3]. This helper runs the latent prior on equilibrium +structures and writes those mode tensors. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys + +import numpy as np +import pandas as pd +import torch +from omegaconf import OmegaConf + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb +from bbflow.models.bbflow_module import BBFlowModule + + +def load_module(ckpt_path: Path, device: torch.device) -> tuple[BBFlowModule, dict[str, int]]: + cfg_path = ckpt_path.with_name("config.yaml") + if not cfg_path.exists(): + raise FileNotFoundError(f"Missing checkpoint config next to checkpoint: {cfg_path}") + + infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(cfg_path) + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.model.embed = ckpt_cfg.model.embed + + module = BBFlowModule(cfg) + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + current_state = module.state_dict() + compatible_state = { + key: value + for key, value in ckpt["state_dict"].items() + if key in current_state and current_state[key].shape == value.shape + } + missing, unexpected = module.load_state_dict(compatible_state, strict=False) + module.to(device) + module.eval() + return module, {"loaded": len(compatible_state), "missing": len(missing), "unexpected": len(unexpected)} + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt_path", required=True, type=Path) + parser.add_argument("--csv_path", required=True, type=Path) + parser.add_argument("--output_dir", required=True, type=Path) + parser.add_argument("--device", default="cuda") + parser.add_argument("--limit", type=int, default=0, help="0 means all proteins") + parser.add_argument("--pdb_name", default="", help="Optional comma-separated protein names") + parser.add_argument("--overwrite", action="store_true") + return parser.parse_args() + + +def select_indices(dataset: PDBDatasetBBFlowFromPdb, pdb_name: str, limit: int) -> list[int]: + if pdb_name: + wanted = [item.strip() for item in pdb_name.split(",") if item.strip()] + indices = [] + for name in wanted: + matches = [idx for idx, candidate in enumerate(dataset.pdb_names) if candidate == name] + if not matches: + raise ValueError(f"Protein not found in csv: {name}") + indices.append(matches[0]) + return indices + count = len(dataset) if limit <= 0 else min(limit, len(dataset)) + return list(range(count)) + + +def main() -> None: + args = parse_args() + if not args.ckpt_path.exists(): + raise FileNotFoundError(args.ckpt_path) + if not args.csv_path.exists(): + raise FileNotFoundError(args.csv_path) + + device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu") + args.output_dir.mkdir(parents=True, exist_ok=True) + + module, load_info = load_module(args.ckpt_path, device) + df = pd.read_csv(args.csv_path) + dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) + indices = select_indices(dataset, args.pdb_name, args.limit) + + rows = [] + with torch.no_grad(): + for idx in indices: + pdb_name = dataset.pdb_names[idx] + out_path = args.output_dir / f"{pdb_name}.npy" + if out_path.exists() and not args.overwrite: + rows.append({"pdb_name": pdb_name, "status": "skipped_exists", "path": str(out_path)}) + continue + + item = dataset[idx] + trans_eq = item["trans_equilibrium"][None].to(device) + rotmats_eq = item["rotmats_equilibrium"][None].to(device) + seq = item["seq"][None].to(device) + _, num_res = trans_eq.shape[:2] + res_mask = torch.ones(1, num_res, device=device) + + condition, _ = module.latent_encoder.forward_prior(trans_eq, rotmats_eq, seq, res_mask) + modes = condition["u_global"][0].detach().float().cpu().numpy() + if modes.ndim != 3: + raise ValueError(f"{pdb_name}: expected u_global [N,K,3], got {modes.shape}") + np.save(out_path, modes) + row = { + "pdb_name": pdb_name, + "status": "ok", + "num_res": int(num_res), + "num_modes": int(modes.shape[1]), + "path": str(out_path), + } + rows.append(row) + print(json.dumps(row, sort_keys=True)) + + summary_path = args.output_dir / "export_condition_modes_summary.json" + with summary_path.open("w") as handle: + json.dump({"ckpt_path": str(args.ckpt_path), "load_info": load_info, "rows": rows}, handle, indent=2) + print(f"Saved: {summary_path}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/extract_shape_fingerprints.py b/bbflow_base/scripts/extract_shape_fingerprints.py new file mode 100644 index 0000000000000000000000000000000000000000..250414f77444a6da5e1570b8fb1250db39b04129 --- /dev/null +++ b/bbflow_base/scripts/extract_shape_fingerprints.py @@ -0,0 +1,131 @@ +import argparse +from pathlib import Path +from types import SimpleNamespace + +import mdtraj +import pandas as pd +import torch +from tqdm.auto import tqdm + +from bbflow.data.alignment import ALIGNMENT_VERSION +from bbflow.data.utils import frames_from_pdb +from bbflow.models.latent import LatentEncoder + + +def pdb_name_from_row(row): + if "name" in row and pd.notna(row["name"]): + return str(row["name"]) + if "pdb_name" in row and pd.notna(row["pdb_name"]): + return str(row["pdb_name"]) + raise KeyError("CSV row has neither 'name' nor 'pdb_name'") + + +def entry_dir_from_row(row, atlas_root, name): + if "folder" in row and pd.notna(row["folder"]): + folder = Path(str(row["folder"])) + if folder.exists(): + return folder + return atlas_root / name + + +def load_ca_md_frames(entry_dir, name): + eq_path = entry_dir / f"{name}.pdb" + if not eq_path.exists(): + raise FileNotFoundError(f"Missing equilibrium PDB: {eq_path}") + top = mdtraj.load(str(eq_path)) + ca_indices = top.top.select("name CA") + if ca_indices.size == 0: + raise ValueError(f"No CA atoms found in {eq_path}") + + frames = [] + frame_counts = [] + for traj_idx in range(1, 4): + xtc_path = entry_dir / f"{name}_R{traj_idx}.xtc" + if not xtc_path.exists(): + raise FileNotFoundError(f"Missing trajectory: {xtc_path}") + traj = mdtraj.load(str(xtc_path), top=str(eq_path), atom_indices=ca_indices) + ca = torch.tensor(traj.xyz, dtype=torch.float32) * 10.0 + ca = ca - ca.mean(dim=1, keepdim=True) + frames.append(ca) + frame_counts.append(int(ca.shape[0])) + return torch.cat(frames, dim=0), frame_counts + + +def summarize_target(label): + rmsf = label["rmsf"] + local_cov = label["local_cov"] + cross_cov = label["cross_cov"] + offdiag = cross_cov[~torch.eye(cross_cov.shape[0], dtype=torch.bool)] + return { + "rmsf_mean": float(rmsf.mean().item()), + "rmsf_std": float(rmsf.std().item()), + "local_cov_abs_mean": float(local_cov.abs().mean().item()), + "cross_cov_offdiag_abs_mean": float(offdiag.abs().mean().item()) if offdiag.numel() else 0.0, + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--atlas_root", required=True) + parser.add_argument("--csv", action="append", required=True) + parser.add_argument("--out_path", required=True) + parser.add_argument("--shape_k", type=int, default=5, help="Kept for old bash compatibility; unused by motion targets.") + parser.add_argument("--num_modes", type=int, default=8, help="Number of oracle PCA modes to store for oracle c* training.") + parser.add_argument("--max_entries", type=int, default=None) + args = parser.parse_args() + + atlas_root = Path(args.atlas_root) + out_path = Path(args.out_path) + out_path.parent.mkdir(parents=True, exist_ok=True) + + dfs = [] + for csv_path in args.csv: + df = pd.read_csv(csv_path) + df["_source_csv"] = str(csv_path) + dfs.append(df) + table = pd.concat(dfs, ignore_index=True) + table["_name"] = table.apply(pdb_name_from_row, axis=1) + table = table.drop_duplicates("_name").reset_index(drop=True) + if args.max_entries is not None: + table = table.iloc[:args.max_entries].copy() + + latent = LatentEncoder(SimpleNamespace(dim=16, num_modes=args.num_modes, z_stochastic=False)) + motion_targets = {} + rows = [] + for _, row in tqdm(table.iterrows(), total=len(table), desc="motion targets"): + name = row["_name"] + entry_dir = entry_dir_from_row(row, atlas_root, name) + trans_eq, _, _, _ = frames_from_pdb(entry_dir / f"{name}.pdb") + frames, frame_counts = load_ca_md_frames(entry_dir, name) + if frames.shape[1] != trans_eq.shape[0]: + raise ValueError( + f"Length mismatch for {name}: MD CA {frames.shape[1]} vs equilibrium {trans_eq.shape[0]}" + ) + res_mask = torch.ones(trans_eq.shape[0], dtype=torch.float32) + label = latent.compute_motion_targets(frames, trans_eq, res_mask, num_modes=latent.num_modes) + motion_targets[name] = label + if len(name) == 5: + motion_targets[f"{name[:4]}_{name[4]}"] = label + rows.append({ + "name": name, + "entry_dir": str(entry_dir), + "num_frames": int(frames.shape[0]), + "traj_frame_counts": ",".join(map(str, frame_counts)), + "num_res": int(trans_eq.shape[0]), + **summarize_target(label), + }) + + payload = { + "motion_targets": motion_targets, + "target_type": "centered_local_and_cross_covariance", + "alignment_version": ALIGNMENT_VERSION, + "num_entries": len(rows), + } + torch.save(payload, out_path) + pd.DataFrame(rows).to_csv(out_path.with_suffix(".tsv"), sep="\t", index=False) + print(f"Wrote {len(rows)} motion targets to {out_path}") + print(f"Wrote summary to {out_path.with_suffix('.tsv')}") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/bbflow_base/scripts/fit_motion_template_upper_bound.py b/bbflow_base/scripts/fit_motion_template_upper_bound.py new file mode 100644 index 0000000000000000000000000000000000000000..31b79c241421e9b81199c66fb02982dfd7bc3563 --- /dev/null +++ b/bbflow_base/scripts/fit_motion_template_upper_bound.py @@ -0,0 +1,339 @@ +#!/usr/bin/env python +"""Fit directional template modes directly to MD motion targets. + +This is an upper-bound diagnostic for the v2 representation. It bypasses the +prior network and optimizes the mode template parameters per protein. If this +cannot fit cross-covariance, the representation is too weak; if it can, the next +problem is teaching a prior to predict those parameters from x_eq. +""" + +import argparse +import json +import math +import os +from pathlib import Path + +import numpy as np +import pandas as pd +import torch +import torch.nn.functional as F + +from bbflow.data.alignment import require_alignment_version +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb + + +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 load_motion_targets(cache_path): + cache = torch.load(cache_path, map_location="cpu", weights_only=False) + require_alignment_version(cache, source=str(cache_path)) + if not isinstance(cache, dict) or "motion_targets" not in cache: + raise ValueError(f"Unsupported motion target cache: {cache_path}") + out = {} + for key, value in cache["motion_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), + "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 variant in pdb_name_variants(str(key)): + out[variant] = target + return out + + +def cross_matrix_for_w_cross_r(r): + """Return A where A @ w = cross(w, r), for r shape [N, 3].""" + zeros = torch.zeros_like(r[..., 0]) + x, y, z = r[..., 0], r[..., 1], r[..., 2] + return torch.stack( + [ + torch.stack([zeros, z, -y], dim=-1), + torch.stack([-z, zeros, x], dim=-1), + torch.stack([y, -x, zeros], dim=-1), + ], + dim=-2, + ) + + +def remove_rigid_component(u, coords, mask, remove_rotation=True, ridge=1e-5): + """Remove global translation and, optionally, best-fit global rotation. + + Args: + u: [N, K, 3] vector fields. + coords: [N, 3] equilibrium coordinates. + mask: [N] residue mask. + """ + mask = mask.float() + valid = mask > 0.5 + denom = mask.sum().clamp_min(1.0) + u = u * mask[:, None, None] + u = u - (u * mask[:, None, None]).sum(dim=0, keepdim=True) / denom + u = u * mask[:, None, None] + if not remove_rotation or valid.sum() < 3: + return u + + centered = coords - (coords * mask[:, None]).sum(dim=0, keepdim=True) / denom + a = cross_matrix_for_w_cross_r(centered[valid]).reshape(-1, 3) + normal = a.T @ a + ridge * torch.eye(3, device=coords.device, dtype=coords.dtype) + rhs_base = a.T + corrected = [] + for mode_idx in range(u.shape[1]): + y = u[valid, mode_idx, :].reshape(-1) + omega = torch.linalg.solve(normal, rhs_base @ y) + rigid = (cross_matrix_for_w_cross_r(centered) @ omega).reshape(coords.shape[0], 3) + corrected.append(u[:, mode_idx, :] - rigid) + out = torch.stack(corrected, dim=1) + return out * mask[:, None, None] + + +def covariance_from_modes(u, energy): + local_cov = torch.einsum("k,nki,nkj->nij", energy, u, u) + cross_cov = torch.einsum("k,nkd,mkd->nm", energy, u, u) + rmsf = torch.sqrt(torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)) + return local_cov, cross_cov, rmsf + + +def make_template_field(coords, mask, params, residual_scale, remove_rotation): + num_res = coords.shape[0] + num_modes = params["omega"].shape[0] + mask = mask.float() + centered_coords = coords - (coords * mask[:, None]).sum(dim=0, keepdim=True) / mask.sum().clamp_min(1.0) + + logits = params["center_logits"].masked_fill(mask[None, :] <= 0.5, -1e9) + center_weights = torch.softmax(logits, dim=-1) + centers = center_weights @ centered_coords + + base = torch.cross( + params["omega"][None, :, :].expand(num_res, -1, -1), + centered_coords[:, None, :] - centers[None, :, :], + dim=-1, + ) + params["velocity"][None, :, :] + residual = residual_scale * torch.tanh(params["residual"]) + u = params["participation"][:, :, None] * base + residual + u = remove_rigid_component(u, centered_coords, mask, remove_rotation=remove_rotation) + energy = F.softplus(params["energy_logit"]) + 1e-6 + return u, energy, center_weights + + +def relative_losses(pred, target, mask, spatial_dists, near_distance): + local_pred, cross_pred, rmsf_pred = pred + local_target = target["local_cov"].to(local_pred.device) + cross_target = target["cross_cov"].to(local_pred.device) + rmsf_target = target["rmsf"].to(local_pred.device) + mask = mask.to(local_pred.device).float() + pair_mask = mask[:, None] * mask[None, :] + offdiag = pair_mask * (1.0 - torch.eye(mask.shape[0], device=mask.device)) + local_mask = mask[:, None, None] + + local_denom = ((local_target * local_mask).square().sum() / local_mask.sum().clamp_min(1.0)).clamp_min(1e-6) + local_loss = (((local_pred - local_target) * local_mask).square().sum() / local_mask.sum().clamp_min(1.0)) / local_denom + + cross_denom = ((cross_target * offdiag).square().sum() / offdiag.sum().clamp_min(1.0)).clamp_min(1e-6) + cross_loss = (((cross_pred - cross_target) * offdiag).square().sum() / offdiag.sum().clamp_min(1.0)) / cross_denom + + near_mask = offdiag * (spatial_dists <= near_distance).float() + far_mask = offdiag * (spatial_dists > near_distance).float() + near_denom = ((cross_target * near_mask).square().sum() / near_mask.sum().clamp_min(1.0)).clamp_min(1e-6) + far_denom = ((cross_target * far_mask).square().sum() / far_mask.sum().clamp_min(1.0)).clamp_min(1e-6) + near_loss = (((cross_pred - cross_target) * near_mask).square().sum() / near_mask.sum().clamp_min(1.0)) / near_denom + far_loss = (((cross_pred - cross_target) * far_mask).square().sum() / far_mask.sum().clamp_min(1.0)) / far_denom + + rmsf_denom = ((rmsf_target * mask).square().sum() / mask.sum().clamp_min(1.0)).clamp_min(1e-6) + rmsf_loss = (((rmsf_pred - rmsf_target) * mask).square().sum() / mask.sum().clamp_min(1.0)) / rmsf_denom + return { + "local_cov_loss": local_loss, + "cross_cov_loss": cross_loss, + "cross_cov_near_loss": near_loss, + "cross_cov_far_loss": far_loss, + "rmsf_loss": rmsf_loss, + } + + +def corr_and_sign(pred, true, mask): + p = pred[mask].float() + t = true[mask].float() + if p.numel() < 2: + return 0.0, 0.0 + pc = p - p.mean() + tc = t - t.mean() + corr = (pc * tc).mean() / (pc.std().clamp_min(1e-8) * tc.std().clamp_min(1e-8)) + top = t.abs() >= torch.quantile(t.abs(), 0.90) + sign = ((p[top] * t[top]) > 0).float().mean() if top.any() else torch.zeros((), device=p.device) + return float(corr.detach().cpu()), float(sign.detach().cpu()) + + +def mode_spread(u, mask): + amp2 = u.detach().float().square().sum(dim=-1) * mask[:, None] + prob = amp2 / amp2.sum(dim=0, keepdim=True).clamp_min(1e-8) + entropy = -(prob * prob.clamp_min(1e-8).log()).sum(dim=0) + effective_res = entropy.exp() + return { + "mode_effective_res_mean": float(effective_res.mean().cpu()), + "mode_effective_res_min": float(effective_res.min().cpu()), + "mode_max_res_frac_mean": float(prob.max(dim=0).values.mean().cpu()), + } + + +def fit_one(name, coords, target, args, device): + coords = coords.to(device=device, dtype=torch.float32) + mask = target["res_mask"].to(device=device, dtype=torch.float32) + target = {k: v.to(device=device, dtype=torch.float32) for k, v in target.items() if k in ["local_cov", "cross_cov", "rmsf"]} + num_res = coords.shape[0] + spatial_dists = torch.cdist(coords[None], coords[None])[0] + + torch.manual_seed(args.seed) + params = { + "center_logits": torch.zeros(args.num_modes, num_res, device=device, requires_grad=True), + "omega": (0.01 * torch.randn(args.num_modes, 3, device=device)).requires_grad_(), + "velocity": (0.01 * torch.randn(args.num_modes, 3, device=device)).requires_grad_(), + "participation": (0.1 * torch.randn(num_res, args.num_modes, device=device)).requires_grad_(), + "residual": torch.zeros(num_res, args.num_modes, 3, device=device, requires_grad=True), + "energy_logit": torch.zeros(args.num_modes, device=device, requires_grad=True), + } + optimizer = torch.optim.Adam(params.values(), lr=args.lr) + + best = None + for step in range(args.steps): + optimizer.zero_grad(set_to_none=True) + u, energy, _ = make_template_field(coords, mask, params, args.residual_scale, args.remove_rotation) + pred = covariance_from_modes(u, energy) + losses = relative_losses(pred, target, mask, spatial_dists, args.near_distance) + residual_penalty = (torch.tanh(params["residual"]).square().mean()) * args.lambda_residual + participation_penalty = (params["participation"].square().mean()) * args.lambda_participation + total = ( + args.lambda_local * losses["local_cov_loss"] + + args.lambda_cross * losses["cross_cov_loss"] + + args.lambda_rmsf * losses["rmsf_loss"] + + residual_penalty + + participation_penalty + ) + total.backward() + optimizer.step() + + if best is None or float(total.detach().cpu()) < best["total_loss"]: + best = {"total_loss": float(total.detach().cpu()), "step": step} + best.update({k: float(v.detach().cpu()) for k, v in losses.items()}) + if args.log_every > 0 and (step + 1) % args.log_every == 0: + print(f"{name} step={step+1} total={float(total.detach().cpu()):.4f} cross={float(losses['cross_cov_loss'].detach().cpu()):.4f} far={float(losses['cross_cov_far_loss'].detach().cpu()):.4f}") + + with torch.no_grad(): + u, energy, center_weights = make_template_field(coords, mask, params, args.residual_scale, args.remove_rotation) + local_pred, cross_pred, rmsf_pred = covariance_from_modes(u, energy) + losses = relative_losses((local_pred, cross_pred, rmsf_pred), target, mask, spatial_dists, args.near_distance) + pair_mask = mask[:, None] * mask[None, :] + offdiag = pair_mask.bool() & ~torch.eye(num_res, device=device, dtype=torch.bool) + near = offdiag & (spatial_dists <= args.near_distance) + far = offdiag & (spatial_dists > args.near_distance) + near_corr, near_sign = corr_and_sign(cross_pred, target["cross_cov"], near) + far_corr, far_sign = corr_and_sign(cross_pred, target["cross_cov"], far) + row = { + "pdb_name": name, + "num_res": int(num_res), + "num_modes": int(args.num_modes), + "steps": int(args.steps), + "residual_scale": float(args.residual_scale), + "remove_rotation": bool(args.remove_rotation), + "best_step": int(best["step"]), + "best_total_loss": float(best["total_loss"]), + **{k: float(v.detach().cpu()) for k, v in losses.items()}, + "near_corr_all": near_corr, + "near_top10_sign_agree": near_sign, + "far_corr_all": far_corr, + "far_top10_sign_agree": far_sign, + "energy_mean": float(energy.mean().detach().cpu()), + "energy_std": float(energy.std().detach().cpu()), + } + row.update(mode_spread(u, mask)) + state = { + "energy": energy.detach().cpu(), + "center_weights": center_weights.detach().cpu(), + "u_global": u.detach().cpu(), + "cross_cov_pred": cross_pred.detach().cpu(), + } + return row, state + + +def select_dataset_indices(dataset, names, num_proteins): + if names: + wanted = [x.strip() for x in names.split(",") if x.strip()] + out = [] + for name in wanted: + matches = [i for i, pdb in enumerate(dataset.pdb_names) if pdb == name] + if not matches: + raise ValueError(f"pdb_name not found in csv: {name}") + out.append(matches[0]) + return out + return list(range(min(num_proteins, len(dataset)))) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--motion_target_cache_path", required=True) + parser.add_argument("--csv_path", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--pdb_names", default="") + parser.add_argument("--num_proteins", type=int, default=2) + parser.add_argument("--num_modes", type=int, default=8) + parser.add_argument("--steps", type=int, default=1000) + parser.add_argument("--lr", type=float, default=3e-2) + parser.add_argument("--near_distance", type=float, default=12.0) + parser.add_argument("--residual_scale", type=float, default=0.1) + parser.add_argument("--lambda_local", type=float, default=1.0) + parser.add_argument("--lambda_cross", type=float, default=1.0) + parser.add_argument("--lambda_rmsf", type=float, default=0.25) + parser.add_argument("--lambda_residual", type=float, default=1e-3) + parser.add_argument("--lambda_participation", type=float, default=1e-5) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--device", default="cuda") + parser.add_argument("--log_every", type=int, default=100) + parser.add_argument("--keep_rotation", action="store_true") + args = parser.parse_args() + args.remove_rotation = not args.keep_rotation + + device = torch.device(args.device if args.device == "cpu" or torch.cuda.is_available() else "cpu") + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + targets = load_motion_targets(args.motion_target_cache_path) + df = pd.read_csv(args.csv_path) + df = df.drop(columns=["modeled_seq_len"], errors="ignore") + dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) + + rows = [] + for idx in select_dataset_indices(dataset, args.pdb_names, args.num_proteins): + item = dataset[idx] + name = str(item["pdb_name"]) + target = None + for variant in pdb_name_variants(name): + target = targets.get(variant) + if target is not None: + break + if target is None: + raise KeyError(f"Missing motion target for {name}") + coords = item["trans_equilibrium"].float() + print(f"[template-upper-bound] fitting {name} N={coords.shape[0]}") + row, state = fit_one(name, coords, target, args, device) + rows.append(row) + torch.save(state, output_dir / f"{name}_template_fit.pt") + pd.Series(row).to_json(output_dir / f"{name}_summary.json", indent=2) + print(pd.Series(row).to_string()) + + summary = pd.DataFrame(rows) + summary.to_csv(output_dir / "template_upper_bound_summary.csv", index=False) + aggregate = summary.mean(numeric_only=True).to_dict() + aggregate["num_proteins"] = int(len(summary)) + (output_dir / "template_upper_bound_aggregate.json").write_text(json.dumps(aggregate, indent=2)) + print("\n[template-upper-bound] aggregate") + print(pd.Series(aggregate).to_string()) + print(f"[template-upper-bound] wrote {output_dir}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/inference_example.py b/bbflow_base/scripts/inference_example.py new file mode 100644 index 0000000000000000000000000000000000000000..d2549ea79561620834553fd126dc5f1d1019c842 --- /dev/null +++ b/bbflow_base/scripts/inference_example.py @@ -0,0 +1,56 @@ +# THIS SCRIPT USES A LIGHTWEIGHT EXAMPLE MODEL FOR DEMONSTRATION. TO OBTAIN GOOD ENSEMBLES, CHANGE THE MODEL TAG TO 'LATEST' BELOW. + +#%% + +from bbflow.deployment.bbflow import BBFlow +from pathlib import Path + +rootdir = Path(__file__).parent.parent + +# Download a small test model into ./models/bbflow-mini-0.1, +bbflow_sampler = BBFlow.from_tag('bbflow-mini-0.1') # use 'latest' to download a heavier, more accurate model + +# Alternatively, you can specify a ckpt path directly +# ckpt_path = './ckpt/bbflow.ckpt' +# bbflow_sampler = BBFlow(ckpt_path) + +# %% +# Sample conformations from the protein specified +# by the PDB file of the equilibrium structure +pdb_path = rootdir/'test_data/test_pdbs/equilibrium.pdb' + +#%% +# Sample 50 conformations and save them to the output path +# with a fixed batch size of 10 +bbflow_sampler.sample( + input_path=pdb_path, output_path=rootdir/'test_data/test_pdbs/ensemble.pdb', + num_samples=50, batch_size=10 +) + +#%% +# Sample 50 conformations and save them to the output path where +# the batch size is estimated based on the VRAM of the GPU +bbflow_sampler.sample( + input_path=pdb_path, output_path=rootdir/'test_data/test_pdbs/ensemble.pdb', + num_samples=50, cuda_memory_GB=6 +) + + +# %% +# Analyze the generated ensemble against the reference MD trajectory +from scripts.analysis_script import calc_metrics + +calc_metrics( + paths=[ + ( + "test_data/test_pdbs/ensemble.pdb", + "test_data/test_pdbs/equilibrium.pdb", + "test_data/test_pdbs/MD_trajectory.xtc", + ) + ], + print_metrics=True, + analysis_data_path="test_data/test_pdbs/analysis_data.pkl", + analysis_metrics_path="test_data/test_pdbs/metrics_summary.csv", + num_workers=1, +) + diff --git a/bbflow_base/scripts/inference_example.sh b/bbflow_base/scripts/inference_example.sh new file mode 100644 index 0000000000000000000000000000000000000000..67ddcf3714c811ab1c3c36e353fb2494c9a6904b --- /dev/null +++ b/bbflow_base/scripts/inference_example.sh @@ -0,0 +1,32 @@ +# THIS SCRIPT USES A LIGHTWEIGHT EXAMPLE MODEL FOR DEMONSTRATION. TO OBTAIN GOOD ENSEMBLES, CHANGE THE MODEL TAG TO 'LATEST' BELOW. + +# Example usage of the bbflow_sample command (run bbflow_sample -h for help) + +# define path to test data +THISDIR=$(dirname "$(readlink -f "$0")") +TEST_PDB_DIR="${THISDIR}/../test_data/test_pdbs" +set -e + + +# EXAMPLE 1 +# specify (several) input and output path for each equilibrium structure and ensemble +# the output_path may also end on .xtc, in this case, the ensemble will be saved in compressed format +bbflow_sample --input_path "${TEST_PDB_DIR}/equilibrium.pdb" "${TEST_PDB_DIR}/short_equilibrium.pdb" \ + --output_path "${TEST_PDB_DIR}/equilibrium_samples.pdb" "${TEST_PDB_DIR}/short_equilibrium_samples.pdb" \ + --cuda_memory_GB 5 \ + --num_samples 100 \ + --tag bbflow-mini-0.1 # small test model, use --tag latest for more accurate ensembles + + +# EXAMPLE 2 +# you can also pass an input and output directory to generate ensembles for all pdb files in that directory +# to demonstrate this, we create a seperate directory with example inputs: +mkdir -p "${TEST_PDB_DIR}/example_inputs" +cp "${TEST_PDB_DIR}/equilibrium.pdb" "${TEST_PDB_DIR}/example_inputs/equilibrium.pdb" +cp "${TEST_PDB_DIR}/short_equilibrium.pdb" "${TEST_PDB_DIR}/example_inputs/short_equilibrium.pdb" + +bbflow_sample --input_dir "${TEST_PDB_DIR}/example_inputs" \ + --output_dir "${TEST_PDB_DIR}/example_outputs" \ + --cuda_memory_GB 5 \ + --num_samples 100 \ + --tag bbflow-mini-0.1 # small test model, use --tag latest for more accurate ensembles \ No newline at end of file diff --git a/bbflow_base/scripts/multimer_inference.sh b/bbflow_base/scripts/multimer_inference.sh new file mode 100644 index 0000000000000000000000000000000000000000..45becdf12ff12ce8f06f827624770b3471f5eb02 --- /dev/null +++ b/bbflow_base/scripts/multimer_inference.sh @@ -0,0 +1,10 @@ +# define path to test data +THISDIR=$(dirname "$(readlink -f "$0")") +TEST_PDB_DIR="${THISDIR}/../test_data/test_pdbs" +set -e + +bbflow_sample --input_path "${TEST_PDB_DIR}/multimer.pdb"\ + --output_path "${TEST_PDB_DIR}/multimer_samples.pdb"\ + --cuda_memory_GB 5 \ + --num_samples 10 \ + --tag bbflow-multimer-0.2 diff --git a/bbflow_base/scripts/per_protein_scale_ceiling.py b/bbflow_base/scripts/per_protein_scale_ceiling.py new file mode 100644 index 0000000000000000000000000000000000000000..57c6973f62fd768e896281f447ad5fea0ca91238 --- /dev/null +++ b/bbflow_base/scripts/per_protein_scale_ceiling.py @@ -0,0 +1,227 @@ +"""Could a per-protein conditioning scale beat one global scale? Upper bound, existing files. + +Every one of the conditioned configurations buys PCA-W2 at the cost of dispersion, and +lowering `condition_scale` shrinks the gain and the cost together. One reading is that a +single global scale must compromise between proteins that are badly over-dispersed and +proteins that are nearly right, so a per-protein scale could do better. Before spending a +generation run on any rule for choosing it, this measures the **ceiling**: give every +protein its own best scale, chosen with full knowledge of the answer, and see whether that +oracle even beats the best global scale. If the oracle gain is small, no rule for +predicting the scale can do better, and the idea is dead without generating anything. + +Three questions, in order: + + 1. heterogeneity do different proteins actually want different scales, or does almost + everyone want the same one? If the optimum is homogeneous, a global + scale is already doing the job and there is nothing to recover. + 2. ceiling median PCA-W2 under the per-protein oracle versus under the single + best global scale. This is the most any per-protein rule can buy. + 3. compatibility does the scale that minimises PCA-W2 for a protein also move its + dispersion toward the MD target, or are they minimised at opposite + ends? If they fight, a scalar cannot fix both no matter how it is + chosen, and the trade is structural rather than a compromise. + +The scorer's noise is handled without departing from its definition. The official +implementation draws its reference subsample unseeded, and repeated runs on identical +files gave 1.18 / 1.24 / 1.27 -- SD about 0.046, which swamps every difference in the +sweep. Here the **same reference indices are used for every configuration** within a +protein and draw, so configurations are compared on identical references and that noise +cancels in the comparison instead of being averaged down at 1/sqrt(n). The metric itself +is the project's own `_pca_w2` on the project's own `_get_pca`, unmodified. + +RMSF and pairwise summaries here are this script's own definitions, used only to answer +question 3 in relative terms. They are not the official columns and must not be compared +with the published table. +""" + +import argparse +import os + +import numpy as np + + +def fit_reference_pca(ref_xyz): + from bbflow.analysis.analyse_bbflow import _get_pca + return _get_pca(ref_xyz) + + +def pca_w2_shared(ref_coords, model_coords, n_atoms, idx): + """The project's metric on a caller-supplied reference draw, so arms are paired.""" + from bbflow.analysis.analyse_bbflow import _pca_w2 + return float(_pca_w2(ref_coords[idx], model_coords, n_atoms, K=2)["pca_w2"]) + + +def _kabsch_rmsd_batch(a, b): + ac, bc = a - a.mean(1, keepdims=True), b - b.mean(1, keepdims=True) + h = np.einsum("fij,fik->fjk", ac, bc) + u, s, vt = np.linalg.svd(h) + sign = np.sign(np.linalg.det(np.einsum("fij,fjk->fik", u, vt))) + s = s.copy() + s[:, -1] *= sign + n = a.shape[1] + return np.sqrt(np.maximum( + (np.square(ac).sum((1, 2)) + np.square(bc).sum((1, 2)) - 2 * s.sum(1)) / n, 0.0)) + + +def dispersion(xyz, rng, n_pairs=800): + """Internal dispersion summaries, in Angstrom. Not the official definitions.""" + x = xyz * 10.0 + rmsf = np.sqrt(np.square(x - x.mean(0)).sum(-1).mean(0)) + i, j = rng.integers(0, len(x), n_pairs), rng.integers(0, len(x), n_pairs) + ok = i != j + return float(np.median(rmsf)), float(np.median(_kabsch_rmsd_batch(x[i[ok]], x[j[ok]]))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--md_dir", required=True) + ap.add_argument("--ensemble_dirs", nargs="+", required=True) + ap.add_argument("--scales", nargs="+", type=float, required=True, + help="the condition_scale each ensemble dir was generated at") + ap.add_argument("--baseline_dir", default="", + help="optional unconditioned run, scored on the same references") + ap.add_argument("--n_draws", type=int, default=15) + ap.add_argument("--require_segments", type=int, default=3) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out_csv", default="") + args = ap.parse_args() + + if len(args.scales) != len(args.ensemble_dirs): + raise SystemExit("--scales must match --ensemble_dirs in length") + order = np.argsort(args.scales) + scales = [args.scales[i] for i in order] + dirs = [args.ensemble_dirs[i] for i in order] + print("scales: " + " ".join(f"{s:g}" for s in scales), flush=True) + + from centroid_reliability import load_generated, load_reference, stable_seed + import pandas as pd + + pools = [dirs] + ([[args.baseline_dir]] if args.baseline_dir else []) + cohort = sorted(set.intersection(*[ + {d for d in os.listdir(e) if os.path.isdir(os.path.join(e, d))} + for grp in pools for e in grp])) + print(f"cohort: {len(cohort)} proteins", flush=True) + + rows, failures = [], [] + for pi, prot in enumerate(cohort): + try: + ref, md_flat, n_atoms, _ = load_reference(prot, args.md_dir, + args.require_segments) + ref_pca, ref_coords = fit_reference_pca(md_flat.reshape(len(md_flat), n_atoms, 3)) + except Exception as exc: # noqa: BLE001 + failures.append(f"{prot}: {exc}") + continue + + try: + gens = [load_generated(prot, d, ref) for d in dirs] + base = load_generated(prot, args.baseline_dir, ref) if args.baseline_dir else None + except Exception as exc: # noqa: BLE001 + failures.append(f"{prot}: {exc}") + continue + + n_gen = len(gens[0]) + rng = np.random.default_rng(stable_seed(prot, args.seed)) + # One set of reference draws, shared by every configuration for this protein. + draws = [rng.integers(0, ref_coords.shape[0], n_gen) for _ in range(args.n_draws)] + + projected = [ref_pca.transform(g.reshape(len(g), -1)) for g in gens] + base_proj = ref_pca.transform(base.reshape(len(base), -1)) if base is not None else None + + drng = np.random.default_rng(stable_seed(prot, args.seed + 1)) + for k, (s, g, mp) in enumerate(zip(scales, gens, projected)): + w2 = float(np.mean([pca_w2_shared(ref_coords, mp, n_atoms, d) for d in draws])) + rm, pw = dispersion(g.reshape(len(g), n_atoms, 3), + np.random.default_rng(stable_seed(prot, 99))) + rows.append({"name": prot, "arm": f"s{s:g}", "scale": s, "pca_w2": w2, + "rmsf_med": rm, "pw_med": pw}) + if base_proj is not None: + w2 = float(np.mean([pca_w2_shared(ref_coords, base_proj, n_atoms, d) + for d in draws])) + rm, pw = dispersion(base.reshape(len(base), n_atoms, 3), + np.random.default_rng(stable_seed(prot, 99))) + rows.append({"name": prot, "arm": "baseline", "scale": np.nan, "pca_w2": w2, + "rmsf_med": rm, "pw_med": pw}) + # MD's own dispersion, for question 3's target + rm, pw = dispersion(md_flat.reshape(len(md_flat), n_atoms, 3)[ + np.random.default_rng(stable_seed(prot, 5)).integers(0, len(md_flat), n_gen)], + np.random.default_rng(stable_seed(prot, 99))) + rows.append({"name": prot, "arm": "MD", "scale": np.nan, "pca_w2": np.nan, + "rmsf_med": rm, "pw_med": pw}) + if (pi + 1) % 10 == 0: + print(f" {pi+1}/{len(cohort)}", flush=True) + + if failures: + print(f"\n{len(failures)} failures; first: {failures[0]}") + df = pd.DataFrame(rows) + if df.empty: + raise SystemExit("nothing measured") + if args.out_csv: + df.to_csv(args.out_csv, index=False) + print(f"per-protein values -> {args.out_csv}") + + cond = df[df.arm.str.startswith("s")] + piv = cond.pivot(index="name", columns="scale", values="pca_w2").dropna() + md = df[df.arm == "MD"].set_index("name") + n = len(piv) + + print(f"\n{'='*74}\n per-scale medians, paired references ({args.n_draws} shared " + f"draws)\n{'='*74}") + print(f" {'scale':>8}{'PCA-W2':>10}{'rmsf_med':>11}{'pw_med':>10}") + for s in piv.columns: + c = cond[cond.scale == s] + print(f" {s:>8g}{piv[s].median():>10.4f}{c.rmsf_med.median():>11.4f}" + f"{c.pw_med.median():>10.4f}") + if args.baseline_dir: + b = df[df.arm == "baseline"] + print(f" {'baseline':>8}{b.pca_w2.median():>10.4f}{b.rmsf_med.median():>11.4f}" + f"{b.pw_med.median():>10.4f}") + print(f" {'MD':>8}{'-':>10}{md.rmsf_med.median():>11.4f}{md.pw_med.median():>10.4f}") + + print(f"\n{'='*74}\n 1. heterogeneity: does each protein want a different scale?" + f"\n{'='*74}") + best = piv.idxmin(axis=1) + counts = best.value_counts().sort_index() + for s, c in counts.items(): + print(f" scale {s:<6g} is best for {c:>3}/{n} proteins ({c/n:.2f})") + print(f"\n If one scale is best for nearly everyone there is no heterogeneity to") + print(f" exploit and a per-protein rule has nothing to recover.") + + print(f"\n{'='*74}\n 2. CEILING: per-protein oracle versus the best global scale" + f"\n{'='*74}") + global_best_s = piv.median().idxmin() + glob = piv[global_best_s] + oracle = piv.min(axis=1) + gap = float(glob.median() - oracle.median()) + rng = np.random.default_rng(0) + idx = rng.integers(0, n, (4000, n)) + g_arr, o_arr = glob.to_numpy(), oracle.to_numpy() + boot = np.median(g_arr[idx], axis=1) - np.median(o_arr[idx], axis=1) + lo, hi = np.percentile(boot, [2.5, 97.5]) + print(f" best global scale {global_best_s:g}") + print(f" its median PCA-W2 {glob.median():.4f}") + print(f" per-protein oracle median {oracle.median():.4f}") + print(f" CEILING (what any rule could buy) {gap:+.4f} [{lo:+.4f}, {hi:+.4f}]") + print(f"\n This oracle is chosen with the answer in hand, so it is an upper bound no") + print(f" predictor can exceed. Against the scorer's ~0.046 single-run SD and the") + print(f" project's 0.06-0.08 selection band, a ceiling below roughly 0.05 means a") + print(f" per-protein rule cannot matter even if it worked perfectly.") + + print(f"\n{'='*74}\n 3. compatibility: does the PCA-W2 optimum also fix dispersion?" + f"\n{'='*74}") + rm_piv = cond.pivot(index="name", columns="scale", values="rmsf_med").loc[piv.index] + pw_piv = cond.pivot(index="name", columns="scale", values="pw_med").loc[piv.index] + rm_best = (rm_piv - md.rmsf_med.loc[piv.index].to_numpy()[:, None]).abs().idxmin(axis=1) + pw_best = (pw_piv - md.pw_med.loc[piv.index].to_numpy()[:, None]).abs().idxmin(axis=1) + agree_rm = float((best == rm_best).mean()) + agree_pw = float((best == pw_best).mean()) + print(f" scale minimising PCA-W2 also closest on rmsf_med: {agree_rm:.2f} of proteins") + print(f" scale minimising PCA-W2 also closest on pw_med: {agree_pw:.2f} of proteins") + print(f" median scale wanted by PCA-W2 {best.median():g}, " + f"by rmsf_med {rm_best.median():g}, by pw_med {pw_best.median():g}") + print(f"\n If PCA-W2 and dispersion want opposite ends of the range, no scalar fixes") + print(f" both, however it is chosen, and the trade is structural rather than a") + print(f" compromise a per-protein rule could resolve.") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/phase_a_oracle_ceiling.py b/bbflow_base/scripts/phase_a_oracle_ceiling.py new file mode 100644 index 0000000000000000000000000000000000000000..942b641e7af67cd39b2631e99ddec00b2fba572b --- /dev/null +++ b/bbflow_base/scripts/phase_a_oracle_ceiling.py @@ -0,0 +1,854 @@ +"""Phase A: how much PCA-W2 is recoverable by fixing the first two moments? + +The reported metric projects both ensembles onto the reference trajectory's leading two +principal components and takes an empirical optimal-transport distance between the two +2-D clouds. Several objectives have been built to match second moments; none has improved +the metric. Before designing another, this measures the ceiling: if the generated cloud's +mean and covariance in that plane were corrected *exactly*, how much of the gap closes? + +A small answer means post-hoc calibration of the first two moments has little to offer on +these ensembles, which is strong practical evidence against continuing down that line. It +is not a proof that a covariance-based training objective is useless -- training can also +move modality and tails -- but it removes the mechanism those objectives were meant to +exploit. + +Method +------ +The correction is the canonical Gaussian optimal-transport (Brenier) map, not an affine +map fitted against the empirical distance: + + T(x) = m_ref + A (x - m_gen) + A = C_gen^{-1/2} ( C_gen^{1/2} C_ref C_gen^{1/2} )^{1/2} C_gen^{-1/2} + +`A` is the unique symmetric positive-definite matrix carrying `C_gen` to `C_ref`, and is +the minimum mean-squared affine displacement under a Gaussian approximation. An +unrestricted affine map fitted against the empirical W2 is deliberately NOT implemented: +it would let rotations and reflections chase higher-order structure, and fitted and scored +on the same cloud it would absorb transport noise, answering a different question. + +Every corrected distance is reported twice: + + in-sample the map is estimated on the same cloud it is applied to. Removes that + cloud's own sampling fluctuation as though it were model error, so it + overstates what is recoverable. Optimistic bound. + cross-fitted repeated K-fold. Each fold's points are transformed by a map estimated on + the other folds, and the transformed folds are reassembled into a full + out-of-fold cloud of the original size. That cloud is scored against the + same fixed reference subset the uncorrected number uses, so the decision + statistic stays at the sample size the metric is defined at. + +The reference moments used to build the map come from frames disjoint from the frames the +distance is evaluated against, so the correction is never fitted to its own target sample. + +Reading the output +------------------ +`floor` is the distance between two clouds of the same size resampled from the reference +trajectory itself. It is what a perfect model would score; the gap worth discussing is +measured against it, not against zero. A replica-versus-replica floor is reported +alongside, which additionally absorbs slow drift between the three trajectory segments. + +The decision rule is in DECISION below, fixed before any association was examined, and +stated in absolute Angstrom because the practical hurdle is an existing 1.27 against a +1.34 reference rather than a fraction of an arbitrary total. + +Caveats that belong with any use of these numbers: + + * Squared W2 separates the mean exactly: + `W2^2(P,Q) = ||mu_P - mu_Q||^2 + W2^2(P - mu_P, Q - mu_Q)`. The exact mean component + of the scored distance is `mean_err_eval`. The mean-only *column* corrects toward + `m_ref` from the independent moment pool rather than toward the empirical mean of the + scored cloud, so it is the honest cross-fitted version of that correction, not the + identity term itself. The covariance term separates in no such way: Bures is a lower + bound (Gelbrich), tight only for compatible elliptical families. The residual after + correction is an operational remainder, not a formal "higher-order share". + * CA atoms only, so absolute values sit a few percent from the all-atom pipeline. A + paired within-protein difference is expected to be less sensitive to that than the + absolute value is, but a preprocessing change can move paired gains too, not merely + add a constant. Confirm against the official per-protein score on one checkpoint + before relying on the magnitude. + * When the eigenvalue floor activates, the map no longer carries the empirical `C_gen` + exactly to `C_ref`. The transport residual is measured for every fitted map and + surfaced; a run in which it is not negligible is a *regularized* correction, not an + exact one. +""" + +import argparse +import hashlib +import os +import warnings + +import numpy as np +from scipy.optimize import linear_sum_assignment + +# Fixed before any association was examined. See module docstring. +DECISION = """ + median cross-fitted paired improvement, in Angstrom: + < 0.07 stop; less than the margin that would have to be beaten + 0.07 - 0.10 probably stop, unless the effect is unusually consistent + >= 0.10 - 0.15 enough upside to continue, if the lower bound sits near 0.07 + and in every case: require improvement on a clear majority of proteins, not a median + carried by a subset. +""" + +INV_FLOOR_REL = 1e-6 # floor for the inverse square root, relative to the trace +# An unfloored map in float64 should carry Cg to Cr to ~1e-13. A 1e-6 residual is a +# failure, not an "exact" map; the legacy value would have passed the float32 pipeline +# this run exists to replace. Floored maps are regularized by construction and are +# tracked separately rather than judged against this. +TRANSPORT_TOL = 1e-9 + + +def emp_cov(x): + """Empirical covariance, denominator n. + + `np.cov` defaults to n-1. The reference and generated sample sizes differ by an order + of magnitude here, so those factors do not cancel between the two sides of the map, + and the Gelbrich bound is defined for the empirical measure. + """ + xc = x - x.mean(0, keepdims=True) + return (xc.T @ xc) / xc.shape[0] + + +def _sym(a): + return 0.5 * (a + a.T) + + +def _psd_sqrt(c): + """PSD square root. Only negative roundoff is clipped, so the Bures quantity is not + perturbed by a positive floor.""" + w, v = np.linalg.eigh(_sym(c)) + w = np.clip(w, 0.0, None) + return _sym((v * np.sqrt(w)) @ v.T) + + +def _inv_sqrt(c): + """Inverse square root with a positive relative floor. Returns whether it activated.""" + w, v = np.linalg.eigh(_sym(c)) + floor = max(INV_FLOOR_REL * max(w.sum(), 1e-30), 1e-30) + activated = bool((w < floor).any()) + w = np.clip(w, floor, None) + return _sym((v * (1.0 / np.sqrt(w))) @ v.T), activated + + +def bures_map(c_gen, c_ref): + """Gaussian Brenier map from `c_gen` to `c_ref`, with transport diagnostics.""" + g_half = _psd_sqrt(c_gen) + g_inv_half, floored = _inv_sqrt(c_gen) + middle = _psd_sqrt(_sym(g_half @ c_ref @ g_half)) + a = _sym(g_inv_half @ middle @ g_inv_half) + denom = max(np.linalg.norm(c_ref, "fro"), 1e-30) + residual = float(np.linalg.norm(a @ c_gen @ a.T - c_ref, "fro") / denom) + return a, floored, residual + + +def w2(a, b, n_atoms): + """Empirical 2-Wasserstein between equal-size clouds, in the reported units. + + Mirrors `analyse_bbflow._pca_w2` composed with `_get_wasserstein`. + """ + d = np.square(a[:, None] - b[None]).sum(-1) ** 0.5 / n_atoms ** 0.5 * 10.0 + d = d ** 2 + r, c = linear_sum_assignment(d) + return float(d[r, c].mean() ** 0.5) + + +def w2_sq_decomposition(a, b, n_atoms): + """Split squared W2 into its mean and centred parts. + + For any two measures with finite second moments, writing `X = mu_P + X'`, + + E||X - Y||^2 = ||mu_P - mu_Q||^2 + E||X' - Y'||^2 + + because the cross term vanishes. The first term does not depend on the coupling, so + the same coupling minimises both sides and + + W2^2(P, Q) = ||mu_P - mu_Q||^2 + W2^2(P_centred, Q_centred) + + holds exactly, empirical measures included. That makes it a hard invariant: any + residual is a defect in the pipeline, not a property of the data. It is what the + interaction between correction arms must satisfy, so a non-zero squared-scale + interaction localises an inconsistency between how the arms are built. + """ + scale = 10.0 / n_atoms ** 0.5 + dm = (a.mean(0) - b.mean(0)) * scale + mean_term = float(dm @ dm) + centred = w2(a - a.mean(0), b - b.mean(0), n_atoms) ** 2 + total = w2(a, b, n_atoms) ** 2 + return total, mean_term, centred + + +def check_invariants(name, md_dir, ensemble_dir, k_dim, rng, n_folds, expect_gen): + """Localise the squared-scale interaction between the correction arms. + + The mean/centred split of squared W2 is exact for every cloud on its own, but that + alone does not force the interaction `G_affine - G_mean - G_cov` to vanish. Zero + interaction additionally needs the arms to be a genuine factorial: mean-only must + leave the centred cloud untouched, covariance-only must leave the mean untouched, and + affine must be exactly covariance-only composed with the same mean shift. + + Two constructions here break that, and the diagnostic separates them: + + * the mean arm applies a *fold-specific* translation `m_ref - m_f`, so the + reassembled cloud is not the raw cloud moved by one vector and its centred shape + changes; + * the covariance arm is globally recentred after reassembly while the affine arm is + not. + + So the reported three arms are three separate interventions, not a factorial, and the + interaction between them is not a distributional quantity. An explicit factorial is + built alongside — raw, raw plus one global shift, the mean-preserving covariance + cloud, and that cloud plus the same global shift — whose interaction must vanish to + numerical error. It is a different estimator from the cross-fitted arms and is + reported as such, never substituted for them. + """ + md_flat, gen_flat, n_atoms, _ = _load(name, md_dir, ensemble_dir) + n_gen, n_md = gen_flat.shape[0], md_flat.shape[0] + if expect_gen and n_gen != expect_gen: + raise ValueError(f"{name}: {n_gen} generated samples, expected {expect_gen}") + for arr, tag in ((md_flat, "reference"), (gen_flat, "generated")): + if arr.dtype != np.float64: + raise TypeError(f"{name}: {tag} coordinates are {arr.dtype}, expected float64") + + md_mean_all = md_flat.mean(0, keepdims=True) + _, sing, vh = np.linalg.svd(md_flat - md_mean_all, full_matrices=False) + basis = vh[:k_dim] + md_p = (md_flat - md_mean_all) @ basis.T + gen_p = (gen_flat - md_mean_all) @ basis.T + + perm = rng.permutation(n_md) + md_eval = md_p[perm[:n_gen]] + m_ref, c_ref = md_p[perm[n_gen:]].mean(0), emp_cov(md_p[perm[n_gen:]]) + + mean_arm = np.empty_like(gen_p) + cov_pre = np.empty_like(gen_p) + affine_arm = np.empty_like(gen_p) + for fold in _fold_indices(n_gen, n_folds, rng): + train = np.setdiff1d(np.arange(n_gen), fold) + m_f, c_f = gen_p[train].mean(0), emp_cov(gen_p[train]) + a, _, _ = bures_map(c_f, c_ref) + held = gen_p[fold] + mean_arm[fold] = held + (m_ref - m_f) + cov_pre[fold] = (held - m_f) @ a.T + m_f + affine_arm[fold] = (held - m_f) @ a.T + m_ref + cov_arm = cov_pre + (gen_p.mean(0) - cov_pre.mean(0)) + + # Explicit factorial, defined after reassembly. Its interaction must vanish. + shift = m_ref - gen_p.mean(0) + fac = {"raw": gen_p, "mean": gen_p + shift, + "cov": cov_arm, "affine": cov_arm + shift} + + scale = 10.0 / n_atoms ** 0.5 + dec = {} + for label, cloud in [("raw", gen_p), ("mean", mean_arm), ("cov_pre", cov_pre), + ("cov", cov_arm), ("affine", affine_arm)]: + dec[label] = w2_sq_decomposition(cloud, md_eval, n_atoms) + + def interaction(d): + tot = {k: v[0] for k, v in d.items()} + mt = {k: v[1] for k, v in d.items()} + ct = {k: v[2] for k, v in d.items()} + i_mean = mt["mean"] + mt["cov"] - mt["raw"] - mt["affine"] + i_centred = ct["mean"] + ct["cov"] - ct["raw"] - ct["affine"] + i_total = ((tot["raw"] - tot["affine"]) - (tot["raw"] - tot["mean"]) + - (tot["raw"] - tot["cov"])) + return i_total, i_mean, i_centred + + fac_dec = {k: w2_sq_decomposition(v, md_eval, n_atoms) for k, v in fac.items()} + + # Hard invariants: each must hold to numerical precision or the pipeline is wrong. + hard = { + "decomposition residual, max over clouds": + max(abs(t - m - c) + for t, m, c in list(dec.values()) + list(fac_dec.values())), + # If these fail the defect is in the arm bookkeeping, not in the transport + # solver; separating them tells you which layer to look at. + "factorial mean arm != raw + shift": + float(np.abs(fac["mean"] - (gen_p + shift)).max() * scale), + "factorial affine arm != cov + shift": + float(np.abs(fac["affine"] - (cov_arm + shift)).max() * scale), + "covariance arm moves the mean": + float(np.linalg.norm(cov_arm.mean(0) - gen_p.mean(0)) * scale), + "recentring changes the centred cloud": + float(np.abs((cov_arm - cov_arm.mean(0)) - (cov_pre - cov_pre.mean(0))).max() * scale), + "explicit factorial interaction": + abs(interaction(fac_dec)[0]), + } + + # Soft diagnostics: expected to be non-zero, and the size is the finding. + i_tot, i_mean, i_centred = interaction(dec) + soft = { + "mean arm alters the centred cloud (vs raw)": + abs(dec["mean"][2] - dec["raw"][2]), + "fold-specific mean arm vs one global shift, pointwise": + float(np.abs(mean_arm - (gen_p + shift)).max() * scale), + "affine arm vs cov_pre + global shift, pointwise": + float(np.abs(affine_arm - (cov_pre + shift)).max() * scale), + "affine arm mean minus m_ref": + float(np.linalg.norm(affine_arm.mean(0) - m_ref) * scale), + } + + means = { + "raw -> reference": float(np.linalg.norm(gen_p.mean(0) - m_ref) * scale), + "mean arm -> reference": float(np.linalg.norm(mean_arm.mean(0) - m_ref) * scale), + "cov_pre -> raw": float(np.linalg.norm(cov_pre.mean(0) - gen_p.mean(0)) * scale), + "cov -> raw": float(np.linalg.norm(cov_arm.mean(0) - gen_p.mean(0)) * scale), + "affine -> reference": float(np.linalg.norm(affine_arm.mean(0) - m_ref) * scale), + } + + c_g = emp_cov(gen_p) + ev = np.linalg.eigvalsh(c_g) + cond = float(ev.max() / max(ev.min(), 1e-300)) + if len(sing) > k_dim: + l2, l3 = sing[k_dim - 1] ** 2, sing[k_dim] ** 2 + eigengap = float((l2 - l3) / max(l2, 1e-300)) + else: + eigengap = float("nan") + + return {"name": name, "dec": dec, "fac_dec": fac_dec, "hard": hard, "soft": soft, + "means": means, "i_total": i_tot, "i_mean": i_mean, "i_centred": i_centred, + "fac_i": interaction(fac_dec), "cov_eigs": ev, "cov_cond": cond, + "pc_relgap": eigengap} + +def stable_seed(name, base): + """Reproducible across processes; Python string hashing is randomised per run.""" + h = hashlib.sha256(name.encode()).digest() + return (base + int.from_bytes(h[:4], "big")) % (2 ** 32) + + +def _ca_signature(traj): + """Residue identity of the CA atoms, so a matching count with a different ordering + cannot pass silently.""" + return tuple(f"{a.residue.name}{a.residue.resSeq}{a.residue.chain.index}" + for a in traj.top.atoms) + + +def _load(name, md_dir, ensemble_dir): + import mdtraj # imported here so the numeric path can be exercised without it + + top = os.path.join(md_dir, name, f"{name}.pdb") + gen = os.path.join(ensemble_dir, name, "sampled_conformations.pdb") + if not (os.path.exists(top) and os.path.exists(gen)): + raise FileNotFoundError(f"{name}: missing reference or generated file") + + ref = mdtraj.load(top) + ca = ref.top.select("name CA") + if ca.size < 4: + raise ValueError(f"{name}: {ca.size} CA atoms") + ref = ref.atom_slice(ca) + + md, bounds = None, [] + for i in (1, 2, 3): + p = os.path.join(md_dir, name, f"{name}_R{i}.xtc") + if not os.path.exists(p): + continue + part = mdtraj.load(p, top=top).atom_slice(ca) + bounds.append((0 if md is None else md.n_frames, + part.n_frames if md is None else md.n_frames + part.n_frames)) + md = part if md is None else md + part + if md is None: + raise FileNotFoundError(f"{name}: no reference trajectory") + + g = mdtraj.load(gen) + g = g.atom_slice(g.top.select("name CA")) + if _ca_signature(g) != _ca_signature(ref): + raise ValueError(f"{name}: CA residue identity differs between reference and generated") + + md.superpose(ref) + g.superpose(ref) + # mdtraj hands back float32. Casting here does not recover precision already lost in + # the coordinates, but it keeps covariance estimation, the eigendecompositions, the + # matrix square roots and the transport residual in float64 -- the residual was + # sitting at 1e-6, which is float32 accumulation, not float64 machine precision. + return (md.xyz.reshape(md.n_frames, -1).astype(np.float64), + g.xyz.reshape(g.n_frames, -1).astype(np.float64), ca.size, bounds) + + +def _fold_indices(n, k, rng): + order = rng.permutation(n) + return np.array_split(order, k) + + +def audit_one(name, md_dir, ensemble_dir, k_dim, rng, n_folds, n_reps, expect_gen): + md_flat, gen_flat, n_atoms, bounds = _load(name, md_dir, ensemble_dir) + n_gen, n_md = gen_flat.shape[0], md_flat.shape[0] + if expect_gen and n_gen != expect_gen: + raise ValueError(f"{name}: {n_gen} generated samples, expected {expect_gen}") + if n_folds > n_gen: + raise ValueError(f"{name}: {n_folds} folds requested for {n_gen} samples") + if n_md < 2 * n_gen: + raise ValueError(f"{name}: {n_md} reference frames, need at least {2 * n_gen}") + + # Axes from the full trajectory, matching the metric's own definition. + md_mean_all = md_flat.mean(0, keepdims=True) + _, sing, vh = np.linalg.svd(md_flat - md_mean_all, full_matrices=False) + basis = vh[:k_dim] + + def proj(x): + return (x - md_mean_all) @ basis.T + + md_p, gen_p = proj(md_flat), proj(gen_flat) + + # Disjoint reference pools: one supplies the scored cloud, the other the target + # moments. Fitting the correction to the frames it is scored against would + # manufacture agreement. + perm = rng.permutation(n_md) + eval_idx, moment_idx = perm[:n_gen], perm[n_gen:] + md_eval = md_p[eval_idx] + m_ref, c_ref = md_p[moment_idx].mean(0), emp_cov(md_p[moment_idx]) + + row = {"name": name, "n_res": n_atoms, "n_gen": n_gen, "n_md": n_md} + row["w2_raw"] = w2(md_eval, gen_p, n_atoms) + + # Finite-sample floor: two clouds resampled with replacement from the empirical + # reference distribution. This is the OT sampling floor conditional on the observed + # trajectory, which is the quantity the metric is subject to. + row["floor"] = float(np.mean([ + w2(md_p[rng.integers(0, n_md, n_gen)], md_p[rng.integers(0, n_md, n_gen)], n_atoms) + for _ in range(n_reps) + ])) + # Sensitivity: distinct trajectory segments, which additionally absorb slow drift. + seg = [w2(md_p[rng.choice(np.arange(*a), n_gen, replace=len(range(*a)) < n_gen)], + md_p[rng.choice(np.arange(*b), n_gen, replace=len(range(*b)) < n_gen)], n_atoms) + for i, a in enumerate(bounds) for b in bounds[i + 1:]] + row["floor_replica"] = float(np.mean(seg)) if seg else float("nan") + + flooring_hits, transport_max, transport_max_unfloored = 0, 0.0, 0.0 + + # In-sample: map estimated on the very cloud it corrects. + m_g, c_g = gen_p.mean(0), emp_cov(gen_p) + a_in, fl, res = bures_map(c_g, c_ref) + flooring_hits += int(fl) + transport_max = max(transport_max, res) + if not fl: + transport_max_unfloored = max(transport_max_unfloored, res) + row["w2_mean_insample"] = w2(md_eval, gen_p + (m_ref - m_g), n_atoms) + row["w2_cov_insample"] = w2(md_eval, (gen_p - m_g) @ a_in.T + m_g, n_atoms) + # In sample there is one global map, which already leaves `m_g` in place, so the + # arm before recentring and the arm after it are the same cloud. Stated rather than + # left to be inferred, since every mode in `per_rep` needs an in-sample counterpart. + row["w2_cov_pre_insample"] = row["w2_cov_insample"] + row["w2_affine_insample"] = w2(md_eval, (gen_p - m_g) @ a_in.T + m_ref, n_atoms) + + # Cross-fitted: reassemble a full out-of-fold cloud so the scored sample size matches + # the metric's, then average over repeated partitions. Per-repetition values are kept + # so split instability is visible rather than averaged away. + # `cov_pre` is the covariance arm before its global recentring. It is carried as a + # supplementary arm so the effect of the recentring is visible in the reported table, + # not only under --invariants. + per_rep = {m: [] for m in ("mean", "cov", "cov_pre", "affine")} + fold_conds, fold_min_eigs = [], [] + for _ in range(n_reps): + out = {m: np.empty_like(gen_p) for m in per_rep} + for fold in _fold_indices(n_gen, n_folds, rng): + train = np.setdiff1d(np.arange(n_gen), fold, assume_unique=False) + m_f, c_f = gen_p[train].mean(0), emp_cov(gen_p[train]) + a, fl, res = bures_map(c_f, c_ref) + flooring_hits += int(fl) + transport_max = max(transport_max, res) + if not fl: + transport_max_unfloored = max(transport_max_unfloored, res) + # The maps are fitted per fold, so the conditioning that matters is the + # per-fold covariance's, not the whole cloud's. + ev_f = np.linalg.eigvalsh(_sym(c_f)) + fold_conds.append(float(ev_f.max() / max(ev_f.min(), 1e-300))) + fold_min_eigs.append(float(ev_f.min())) + held = gen_p[fold] + out["mean"][fold] = held + (m_ref - m_f) + # Every fold is centred on its *training* mean, so the reassembled cloud is + # what applying the estimated maps to the population would give. Recentring + # each fold on its own mean instead would leave between-fold mean variation + # untransformed and make the result depend on the arbitrary partition. + out["cov_pre"][fold] = (held - m_f) @ a.T + m_f + out["cov"][fold] = out["cov_pre"][fold] + out["affine"][fold] = (held - m_f) @ a.T + m_ref + # One global translation restores the original mean exactly, which a rigid shift + # does without touching the transformed covariance. Covariance-only therefore + # contributes no mean correction at all. + out["cov"] = out["cov_pre"] + (gen_p.mean(0) - out["cov_pre"].mean(0)) + for m in per_rep: + per_rep[m].append(w2(md_eval, out[m], n_atoms)) + + for m, vals in per_rep.items(): + row[f"w2_{m}_cv"] = float(np.mean(vals)) + row[f"w2_{m}_cv_sd"] = float(np.std(vals, ddof=1)) if len(vals) > 1 else 0.0 + row[f"gain_{m}_cv"] = row["w2_raw"] - row[f"w2_{m}_cv"] + row[f"gain_{m}_insample"] = row["w2_raw"] - row[f"w2_{m}_insample"] + # Repetition-level values are retained, not averaged away: the Monte Carlo + # uncertainty that matters is that of the across-protein median, which cannot be + # reconstructed from per-protein summaries alone. + for r, v in enumerate(vals): + row[f"w2_{m}_rep{r}"] = float(v) + + row["floored_maps"] = flooring_hits + row["transport_residual_max"] = transport_max + # Judged separately: a floored map is regularized by construction and its residual + # says nothing about arithmetic, whereas an unfloored map in float64 must be exact. + row["transport_residual_max_unfloored"] = transport_max_unfloored + row["fold_cond_max"] = float(np.max(fold_conds)) + row["fold_min_eig"] = float(np.min(fold_min_eigs)) + ev_ref = np.linalg.eigvalsh(_sym(c_ref)) + row["ref_cond"] = float(ev_ref.max() / max(ev_ref.min(), 1e-300)) + # Relative gap at the projection cut. An absolute singular-value difference scales + # with trajectory length and coordinate units and is not comparable across proteins. + if len(sing) > k_dim: + l2, l3 = sing[k_dim - 1] ** 2, sing[k_dim] ** 2 + row["pc_relgap"] = float((l2 - l3) / max(l2, 1e-300)) + else: + row["pc_relgap"] = float("nan") + + # Moment errors. `mean_err_eval` is the quantity that enters the exact squared-W2 + # mean decomposition against the scored cloud; `mean_err_target` is the error against + # the population target the map actually corrects toward. + scale = 10.0 / n_atoms ** 0.5 + row["mean_err_target"] = float(np.linalg.norm(gen_p.mean(0) - m_ref) * scale) + row["mean_err_eval"] = float(np.linalg.norm(gen_p.mean(0) - md_eval.mean(0)) * scale) + cross = _psd_sqrt(_psd_sqrt(c_ref) @ c_g @ _psd_sqrt(c_ref)) + row["bures_err"] = float( + np.sqrt(max(np.trace(c_g) + np.trace(c_ref) - 2 * np.trace(cross), 0.0)) * scale) + row["trace_ratio"] = float(np.trace(c_g) / max(np.trace(c_ref), 1e-30)) + return row + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--md_dir", required=True) + ap.add_argument("--ensemble_dirs", nargs="+", required=True) + ap.add_argument("--names", nargs="*", default=[]) + ap.add_argument("--k", type=int, default=2, + help="projected dimensions; the metric uses 2 and the decision run must") + ap.add_argument("--n_folds", type=int, default=5) + ap.add_argument("--n_reps", type=int, default=10) + ap.add_argument("--expect_gen", type=int, default=250, + help="required generated ensemble size; 0 disables the check") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out_csv", default="") + ap.add_argument("--invariants", type=int, default=0, + help="arm-consistency checks on this many proteins then exit; -1 = all") + ap.add_argument("--compare_csv", default="", + help="previous per-protein CSV; report the paired change against it") + ap.add_argument("--equiv_tol", type=float, default=0.001, + help="tolerance for calling --compare_csv equivalent, in Angstrom") + ap.add_argument("--ratio_tol", type=float, default=0.002, + help="separate tolerance for the dimensionless trace_ratio") + args = ap.parse_args() + + if args.k != 2: + warnings.warn(f"--k {args.k}: the decision thresholds are calibrated for k=2") + if args.n_reps < 2: + raise SystemExit("--n_reps must be at least 2; the Monte Carlo spread is the point") + if args.n_folds < 2 or (args.expect_gen and args.n_folds > args.expect_gen): + raise SystemExit(f"--n_folds must lie in [2, {args.expect_gen or 'n_gen'}]") + + labels = args.names or [os.path.basename(d.rstrip("/")) for d in args.ensemble_dirs] + if len(labels) != len(args.ensemble_dirs): + raise SystemExit("--names must match --ensemble_dirs in length") + if len(set(labels)) != len(labels): + raise SystemExit("run labels must be unique; otherwise the summary silently merges runs") + + import pandas as pd + + # One cohort for every checkpoint. Independent per-directory listings would let a + # failure in one run silently shift its median relative to the others. + per_dir = [set(d for d in os.listdir(e) if os.path.isdir(os.path.join(e, d))) + for e in args.ensemble_dirs] + cohort = sorted(set.intersection(*per_dir)) + for label, s in zip(labels, per_dir): + missing = sorted(set().union(*per_dir) - s) + if missing: + print(f" [{label}] absent: {len(missing)} -> {missing[:6]}") + print(f"cohort common to all runs: {len(cohort)} proteins\n") + + if args.invariants: + n_check = len(cohort) if args.invariants < 0 else min(args.invariants, len(cohort)) + print(f"{'='*78}\n arm-consistency invariants, {n_check} proteins\n{'='*78}") + print(" HARD invariants must hold to numerical precision; a violation is a defect.") + print(" SOFT diagnostics are expected to be non-zero: the reported three arms are") + print(" three separate interventions, not a factorial, because the mean arm uses") + print(" fold-specific translations and the covariance arm is globally recentred.") + print(" The explicit factorial built alongside must show zero interaction.\n") + HARD_TOL = 1e-9 + violations = [] + agg = {} + # Conditioning is data dependent, so every checkpoint is checked, not only the + # first: a map can be well conditioned on one ensemble and not on another. + for label, ens in zip(labels, args.ensemble_dirs): + print(f" [{label}]") + for nm in cohort[:n_check]: + rng = np.random.default_rng(stable_seed(nm, args.seed)) + r = check_invariants(nm, args.md_dir, ens, args.k, + rng, args.n_folds, args.expect_gen) + for k, v in r["hard"].items(): + agg.setdefault(("HARD", k), []).append(v) + if v > HARD_TOL: + violations.append((f"{label}/{nm}", k, v)) + for k, v in r["soft"].items(): + agg.setdefault(("SOFT", k), []).append(v) + for k, v in r["means"].items(): + agg.setdefault(("mean distance", k), []).append(v) + for k, v in (("I(W2^2) total", r["i_total"]), (" mean part", r["i_mean"]), + (" centred part", r["i_centred"]), + ("I(W2^2) explicit factorial", r["fac_i"][0]), + ("covariance condition number", r["cov_cond"]), + ("PC relative gap at the cut", r["pc_relgap"])): + agg.setdefault(("interaction", k), []).append(v) + if n_check <= 3: + print(f" {r['name']}") + print(f" {'cloud':<10}{'W2^2':>11}{'mean term':>12}{'centred':>11}{'resid':>11}") + for label, (tot, mt, ct) in r["dec"].items(): + print(f" {label:<10}{tot:>11.5f}{mt:>12.5f}{ct:>11.5f}{abs(tot-mt-ct):>11.2e}") + print() + + for section in ("HARD", "SOFT", "mean distance", "interaction"): + keys = [k for (sec, k) in agg if sec == section] + if not keys: + continue + print(f" --- {section} (median over {n_check} proteins x {len(labels)} runs) ---") + for k in keys: + v = np.median(agg[(section, k)]) + mx = np.max(np.abs(agg[(section, k)])) + flag = "" + if section == "HARD": + flag = " <-- VIOLATED" if mx > HARD_TOL else " ok" + print(f" {k:<52}{v:>12.3e} max {mx:>10.3e}{flag}") + print() + + if violations: + print(f" {len(violations)} hard-invariant violations, first five:") + for nm, k, v in violations[:5]: + print(f" {nm} {k} {v:.3e}") + raise SystemExit(1) + print(" all hard invariants hold") + return + + rows, failures = [], {} + for label, ens in zip(labels, args.ensemble_dirs): + print(f"[{label}]", flush=True) + for i, nm in enumerate(cohort): + rng = np.random.default_rng(stable_seed(nm, args.seed)) + try: + r = audit_one(nm, args.md_dir, ens, args.k, rng, + args.n_folds, args.n_reps, args.expect_gen) + r["run"] = label + # Matching on (run, name) does not prove like was compared with like. + r.update({"cfg_seed": args.seed, "cfg_folds": args.n_folds, + "cfg_reps": args.n_reps, "cfg_k": args.k, + "cfg_expect_gen": args.expect_gen}) + rows.append(r) + except Exception as exc: # noqa: BLE001 + failures.setdefault(label, []).append(f"{nm}: {type(exc).__name__}: {exc}") + if (i + 1) % 20 == 0: + print(f" {i+1}/{len(cohort)}", flush=True) + + if failures: + print("\nfailures:") + for label, msgs in failures.items(): + print(f" [{label}] {len(msgs)}") + for m in msgs[:5]: + print(f" {m}") + + df = pd.DataFrame(rows) + if df.empty: + raise SystemExit("no protein produced a measurement") + + # Summarise only proteins that succeeded everywhere, so the medians are paired. + counts = df.groupby("name")["run"].nunique() + shared = set(counts[counts == len(labels)].index) + dropped = len(cohort) - len(shared) + if dropped: + print(f"\n{dropped} proteins failed in at least one run and are excluded") + if not shared: + raise SystemExit("no protein succeeded in every run; nothing is comparable") + df = df[df.name.isin(shared)] + + if args.out_csv: + df.to_csv(args.out_csv, index=False) + print(f"per-protein values -> {args.out_csv}") + + if args.compare_csv: + old = pd.read_csv(args.compare_csv) + key = ["run", "name"] + for tag, frame in (("new", df), ("previous", old)): + if frame.duplicated(key).any(): + raise SystemExit(f"{tag} table has duplicate (run, name) keys") + + # Required columns are validated up front. A conditionally built column list can + # otherwise report "equivalent" while silently having compared nothing. + # The schema splits three ways. Imposing the new columns on the previous table + # would reject the very pre-change CSV this comparison exists to check against. + REQUIRED_BOTH = ["w2_raw", "w2_mean_cv", "w2_cov_cv", "w2_affine_cv", + "bures_err", "mean_err_eval", "trace_ratio"] + REQUIRED_NEW = ["transport_residual_max_unfloored", "floored_maps", + "fold_cond_max", "fold_min_eig", "ref_cond", "pc_relgap"] + NEW_ONLY = ["w2_cov_pre_cv"] # no counterpart to compare against + missing = [c for c in REQUIRED_BOTH if c not in df.columns] + missing += [c for c in REQUIRED_NEW + NEW_ONLY if c not in df.columns] + if missing: + raise SystemExit(f"new table is missing required columns: {missing}") + missing_old = [c for c in REQUIRED_BOTH if c not in old.columns] + if missing_old: + raise SystemExit(f"previous table is missing required columns: {missing_old}") + absent_old = [c for c in REQUIRED_NEW + NEW_ONLY if c not in old.columns] + if absent_old: + print(f" new outputs with no counterpart in the previous table, judged" + f" absolutely rather than paired: {absent_old}") + # A provenance comparison run under a different configuration cannot conclude + # equivalence, so a mismatch is fatal rather than a warning. + for c in ("cfg_seed", "cfg_folds", "cfg_reps", "cfg_k", "cfg_expect_gen"): + if c not in df.columns or c not in old.columns: + warnings.warn(f"{c} absent from one table; provenance unverified " + "(expected when comparing against a pre-change CSV)") + continue + a, b = sorted(df[c].unique().tolist()), sorted(old[c].unique().tolist()) + if a != b: + raise SystemExit(f"{c} differs between tables: {a} vs {b}; " + "the two runs are not comparable") + + j = df.merge(old, on=key, suffixes=("_new", "_old")) + if len(j) != len(df) or len(j) != len(old): + raise SystemExit( + f"row counts disagree: new {len(df)}, previous {len(old)}, " + f"matched {len(j)}. A dropped row would make this meaningless.") + + contrasts = {"gain_affine": ("w2_raw", "w2_affine_cv"), + "gain_mean": ("w2_raw", "w2_mean_cv"), + "gain_cov": ("w2_raw", "w2_cov_cv"), + "cov_after_mean": ("w2_mean_cv", "w2_affine_cv")} + + print(f"\n{'='*78}\n equivalence against {args.compare_csv}\n{'='*78}") + print(f" Paired within (run, protein). {len(j)} rows, all matched.\n") + worst, worst_ratio = 0.0, 0.0 + print(f" {'quantity':<26}{'median |d|':>14}{'max |d|':>12}{'at':>14}{'verdict':>10}") + + def line(label, d_, tol, bucket="angstrom"): + nonlocal worst, worst_ratio + if not np.isfinite(d_).all(): + raise SystemExit(f"non-finite change in {label}") + if tol is not None: + if bucket == "angstrom": + worst = max(worst, float(d_.max())) + else: + worst_ratio = max(worst_ratio, float(d_.max())) + at = j.loc[d_.idxmax(), "name"] + v = "-" if tol is None else ("ok" if d_.max() < tol else "EXCEEDS") + print(f" {label:<26}{d_.median():>14.6f}{d_.max():>12.6f}{at:>14}{v:>10}") + + for c in [c for c in df.columns + if c in old.columns + and c.startswith(("w2_", "mean_err", "bures", "floor")) + and not c.endswith("_sd") and "_rep" not in c + and c not in NEW_ONLY]: + line(c, (j[f"{c}_new"] - j[f"{c}_old"]).abs(), args.equiv_tol) + print() + # The contrasts are what the decision reads. Each column can move under + # tolerance while their difference moves over it. + for label, (a, b) in contrasts.items(): + d_ = ((j[f"{a}_new"] - j[f"{b}_new"]) - (j[f"{a}_old"] - j[f"{b}_old"])).abs() + line(label, d_, args.equiv_tol) + print() + # Dimensionless but scientifically meaningful, so it gets its own bound rather + # than being waved through as a numerical diagnostic. + line("trace_ratio", (j["trace_ratio_new"] - j["trace_ratio_old"]).abs(), + args.ratio_tol, bucket="ratio") + + # The transport residual is judged against an absolute float64 correctness bound, + # not against the previous run -- the previous run is what is being replaced. + rescol = ("transport_residual_max_unfloored_new" + if "transport_residual_max_unfloored_new" in j + else "transport_residual_max_unfloored") + floorcol = "floored_maps_new" if "floored_maps_new" in j else "floored_maps" + res_new = j[rescol] + if not np.isfinite(res_new).all(): + raise SystemExit("non-finite transport residual in the new table") + bad = int((res_new > TRANSPORT_TOL).sum()) + floored_rows = int((j[floorcol] > 0).sum()) + print(f"\n unfloored transport residual: median {res_new.median():.3e}" + f" max {res_new.max():.3e} " + + ("ok" if bad == 0 else f"{bad} rows above {TRANSPORT_TOL:.0e}")) + print(f" rows with at least one floored map: {floored_rows}" + + ("" if floored_rows == 0 else " <-- those are regularized estimators")) + + # Column equivalence is not the claim; the reported table is. + print(f"\n {'run':<16}" + "".join(f"{c + ' (change)':>26}" for c in contrasts)) + for r in sorted(j.run.unique()): + g = j[j.run == r] + cells = "" + for a, b in contrasts.values(): + gn = float((g[f"{a}_new"] - g[f"{b}_new"]).median()) + go = float((g[f"{a}_old"] - g[f"{b}_old"]).median()) + cells += f"{gn:>17.4f}{gn - go:>+9.4f}" + print(f" {r:<16}{cells}") + + ok = worst < args.equiv_tol and worst_ratio < args.ratio_tol and bad == 0 + verdict = ("equivalent; the previous table may be replaced" if ok + else "NOT equivalent -- investigate before replacing anything") + print(f"\n worst Angstrom change {worst:.6f} vs {args.equiv_tol}" + f" worst ratio change {worst_ratio:.6f} vs {args.ratio_tol}" + f" residual violations {bad}\n {verdict}") + + def boot(v, n=4000): + v = np.asarray(v, float) + s = np.random.default_rng(0).choice(v, (n, v.size), replace=True) + return np.percentile(np.median(s, axis=1), [2.5, 97.5]) + + print(f"\n{'='*78}\n Phase A: recoverable by exact first- and second-moment correction\n{'='*78}") + print(f" cohort {len(shared)} proteins {args.n_folds}-fold x {args.n_reps} repetitions") + for label in labels: + d = df[df.run == label] + if d.empty: + continue + print(f"\n--- {label} ---") + print(f" uncorrected {d['w2_raw'].median():.4f}") + print(f" resampled reference floor {d['floor'].median():.4f}" + f" (distinct segments: {d['floor_replica'].median():.4f})") + print(f" projected mean error vs target {d['mean_err_target'].median():.4f}" + f" (vs scored cloud: {d['mean_err_eval'].median():.4f})") + print(f" projected Bures covariance error {d['bures_err'].median():.4f}") + print(f" covariance trace ratio {d['trace_ratio'].median():.4f}") + fl = int(d['floored_maps'].sum()) + print(f" eigenvalue floor activations {fl}" + f" max transport residual {d['transport_residual_max'].max():.2e}" + f"{' <-- REGULARIZED, not exact' if fl or d['transport_residual_max'].max() > TRANSPORT_TOL else ''}") + print(f"\n {'correction':<10}{'in-sample':>20}{'cross-fitted':>30}") + print(f" {'':10}{'W2':>10}{'gain':>10}{'W2':>10}{'gain':>10}" + f"{'95% CI of gain':>22}{'win':>7}{'~MC SE':>9}{'p90 prot':>10}") + for m in ("mean", "cov", "cov_pre", "affine"): + g = d[f"gain_{m}_cv"] + lo, hi = boot(g) + # Monte Carlo uncertainty of the *reported median gain*: recompute the + # across-protein median separately for each repetition, then take the spread + # of those. The median of the per-protein SDs answers a different question. + per_rep_median = [ + float((d["w2_raw"] - d[f"w2_{m}_rep{r}"]).median()) + for r in range(args.n_reps) + ] + mc = float(np.std(per_rep_median, ddof=1) / np.sqrt(args.n_reps)) + p90 = float((d[f"w2_{m}_cv_sd"] / np.sqrt(args.n_reps)).quantile(0.90)) + print(f" {m:<10}{d[f'w2_{m}_insample'].median():>10.4f}" + f"{d[f'gain_{m}_insample'].median():>10.4f}" + f"{d[f'w2_{m}_cv'].median():>10.4f}{g.median():>10.4f}" + f" [{lo:+.4f}, {hi:+.4f}]{(g > 0).mean():>7.2f}{mc:>9.4f}{p90:>10.4f}") + + # The contrast being adjudicated for the covariance line needs its own interval, + # not only the standalone arms. + inc = d["w2_mean_cv"] - d["w2_affine_cv"] + lo, hi = boot(inc) + # Not a factorial conditional: the mean and affine arms can have different + # reassembled means, so this is the contrast between those two arms, no more. + print(f"\n affine arm minus mean arm (covariance contrast)" + f" {inc.median():>+8.4f} [{lo:+.4f}, {hi:+.4f}]" + f" win {(inc > 0).mean():.2f}") + + print(f"\n{'='*78}\n prespecified decision rule\n{'='*78}{DECISION}") + print(" Decide on the cross-fitted `affine` gain; in-sample is the optimistic bound.") + print(" ~MC SE is an approximation (the median is nonlinear) and should sit well") + print(" below 0.005; if not, raise --n_reps. A rerun under a different --seed is the") + print(" decisive stability check when the gain lands near a threshold.") + print(" A small gain says post-hoc moment calibration has little to offer on these") + print(" ensembles -- strong practical evidence against another covariance objective,") + print(" though not a proof, since training can also move modality and tails. The") + print(" residual after correction is an operational remainder, not a formal") + print(" higher-order share: only the mean term separates exactly in squared W2.") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/plot_epoch_metrics.py b/bbflow_base/scripts/plot_epoch_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..6cc80c9b7ce7e23febc8a19719408bbd798f75ec --- /dev/null +++ b/bbflow_base/scripts/plot_epoch_metrics.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python +import argparse +import csv +import re +from pathlib import Path + +import matplotlib.pyplot as plt + + +EPOCH_RE = re.compile(r"\[epoch\s+(\d+)\s+md\]\s+(.*)") + + +def _parse_value(raw): + raw = raw.strip().rstrip(",") + try: + return float(raw) + except ValueError: + return None + + +def parse_epoch_log(path): + rows = [] + for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines(): + match = EPOCH_RE.search(line) + if not match: + continue + row = {"epoch": int(match.group(1))} + for item in match.group(2).split(","): + if "=" not in item: + continue + key, value = item.split("=", 1) + parsed = _parse_value(value) + if parsed is not None: + row[key.strip()] = parsed + rows.append(row) + return rows + + +def parse_csv(path): + rows = [] + with Path(path).open("r", encoding="utf-8", errors="replace", newline="") as handle: + for raw in csv.DictReader(handle): + row = {} + for key, value in raw.items(): + if key is None: + continue + if key == "epoch": + row[key] = int(float(value)) + else: + parsed = _parse_value(value) + if parsed is not None: + row[key] = parsed + if "epoch" in row: + rows.append(row) + return rows + + +def plot_group(rows, metrics, title, output_path): + epochs = [row["epoch"] for row in rows] + fig, axes = plt.subplots(len(metrics), 1, figsize=(10, 2.4 * len(metrics)), sharex=True) + if len(metrics) == 1: + axes = [axes] + for axis, metric in zip(axes, metrics): + values = [row.get(metric) for row in rows] + valid = [(epoch, value) for epoch, value in zip(epochs, values) if value is not None] + if valid: + axis.plot([x for x, _ in valid], [y for _, y in valid], marker="o", linewidth=1.5) + axis.set_ylabel(metric) + axis.grid(True, alpha=0.25) + axes[-1].set_xlabel("epoch") + fig.suptitle(title) + fig.tight_layout() + fig.savefig(output_path, dpi=180) + plt.close(fig) + + +def main(): + parser = argparse.ArgumentParser(description="Plot BBFlow per-epoch latent/training metrics.") + parser.add_argument("input", help="train.log or latent_train_epoch_metrics.csv") + parser.add_argument("--out-dir", default="metric_plots") + args = parser.parse_args() + + input_path = Path(args.input) + rows = parse_csv(input_path) if input_path.suffix.lower() == ".csv" else parse_epoch_log(input_path) + if not rows: + raise SystemExit(f"No epoch metric rows found in {input_path}") + rows = sorted(rows, key=lambda row: row["epoch"]) + + out_dir = Path(args.out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + groups = { + "losses": [ + "train_loss", + "official_loss", + "motion_loss", + "q_nll_per_dim", + "mode_orth_loss", + ], + "mode_health": [ + "mode_coeff_abs", + "mode_coeff_std", + "mode_recon_centered_rel_error", + "mode_gram_condition", + "mode_max_cosine_abs", + "latent_effective_modes", + ], + "covariance": [ + "local_cov_loss", + "cross_cov_loss", + "cross_cov_far_loss", + "cross_cov_far_corr", + "cross_cov_far_top10_sign_agree", + "rmsf_loss", + ], + "condition": [ + "condition_scaled_pred_trans_delta_rel", + "condition_pred_trans_delta_rel", + "condition_delta_rel", + "cross_cov_far_corr", + "q_nll_per_dim", + ], + } + + written = [] + available = set().union(*(row.keys() for row in rows)) + for name, metrics in groups.items(): + present = [metric for metric in metrics if metric in available] + if not present: + continue + output_path = out_dir / f"{name}.png" + plot_group(rows, present, f"{name} ({input_path.name})", output_path) + written.append(output_path) + + print(f"Parsed {len(rows)} epoch rows: {rows[0]['epoch']}..{rows[-1]['epoch']}") + for path in written: + print(path) + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/probe_condition_ensemble_cov.py b/bbflow_base/scripts/probe_condition_ensemble_cov.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f13ce88ed58fcb0e825471e7f29ba79caeaefb --- /dev/null +++ b/bbflow_base/scripts/probe_condition_ensemble_cov.py @@ -0,0 +1,327 @@ +import argparse +import json +from pathlib import Path + +import numpy as np +import torch +from omegaconf import OmegaConf + +from bbflow.data.alignment import kabsch_align +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb +from bbflow.models.bbflow_module import BBFlowModule + + +def load_module(ckpt_path, device): + ckpt_path = Path(ckpt_path) + cfg_path = ckpt_path.with_name("config.yaml") + if not cfg_path.exists(): + raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}") + repo_root = Path(__file__).resolve().parents[1] + infer_cfg = OmegaConf.load(repo_root / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(cfg_path) + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.inference.interpolant.use_tqdm = False + cfg.model.embed = ckpt_cfg.model.embed + module = BBFlowModule(cfg) + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + current_state = module.state_dict() + compatible_state = { + key: value for key, value in ckpt["state_dict"].items() + if key in current_state and current_state[key].shape == value.shape + } + missing, unexpected = module.load_state_dict(compatible_state, strict=False) + module.to(device) + module.eval() + return module, cfg, {"missing": len(missing), "unexpected": len(unexpected)} + + +def zero_condition(condition): + out = {} + for key, value in condition.items(): + if torch.is_tensor(value): + out[key] = torch.zeros_like(value) if key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"} else value + else: + out[key] = value + return out + + +def repeat_condition(module, condition, batch_size): + return module.latent_encoder.repeat_condition(condition, batch_size) + + +def align_to_reference(coords, ref, mask): + return kabsch_align(coords, ref, mask) + + +def ensemble_motion_stats(ca_coords, ref_coords, mask): + ref_coords = ref_coords.to(device=ca_coords.device).float() + mask = mask.to(device=ca_coords.device).float() + aligned = align_to_reference(ca_coords, ref_coords, mask) + disp = (aligned - ref_coords[None]) * mask[None, :, None].float() + disp = disp - disp.mean(dim=0, keepdim=True) + denom = max(int(ca_coords.shape[0]) - 1, 1) + cross_cov = torch.einsum("sik,sjk->ij", disp, disp) / denom + local_cov = torch.einsum("sni,snj->nij", disp, disp) / denom + rmsf = torch.sqrt(torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)) + pair_mask = mask[:, None] * mask[None, :] + cross_cov = cross_cov * pair_mask + local_cov = local_cov * mask[:, None, None] + rmsf = rmsf * mask + return { + "cross_cov": cross_cov, + "local_cov": local_cov, + "rmsf": rmsf, + "pair_mask": pair_mask, + } + + +def top_abs_sign_agree(a, b, mask, fraction=0.1): + a = a.float()[mask.bool()] + b = b.float()[mask.bool()] + if a.numel() == 0: + return 0.0 + k = max(1, min(a.numel(), int(round(float(a.numel()) * fraction)))) + idx = torch.topk(b.abs(), k=k, largest=True).indices + return float((torch.sign(a[idx]) == torch.sign(b[idx])).float().mean().cpu().item()) + + +def masked_corr(a, b, mask): + a = a.float()[mask.bool()] + b = b.float()[mask.bool()] + if a.numel() == 0: + return 0.0 + a = a - a.mean() + b = b - b.mean() + denom = a.norm() * b.norm() + if denom <= 1e-8: + return 0.0 + return float(((a * b).sum() / denom).cpu().item()) + + +def compare_rmsf(a, b, mask): + b = b.to(device=a.device) + mask = mask.to(device=a.device).bool() + diff = (a - b).float() + denom = (b.float().square()[mask].sum()).clamp_min(1e-8).sqrt() + return { + "rmsf_fro_rel": float((diff.square()[mask].sum().sqrt() / denom).cpu().item()) if mask.any() else 0.0, + "rmsf_corr": masked_corr(a, b, mask), + "rmsf_abs_diff_mean": float(diff.abs()[mask].mean().cpu().item()) if mask.any() else 0.0, + "static_rmsf_abs_mean": float(a.float().abs()[mask].mean().cpu().item()) if mask.any() else 0.0, + "zero_rmsf_abs_mean": float(b.float().abs()[mask].mean().cpu().item()) if mask.any() else 0.0, + } + + +def compare_local_cov(a, b, mask): + b = b.to(device=a.device) + mask = mask.to(device=a.device).float() + local_mask = mask[:, None, None] + diff = (a - b).float() + denom = (b.float().square() * local_mask).sum().clamp_min(1e-8).sqrt() + return { + "local_cov_fro_rel": float(((diff.square() * local_mask).sum().sqrt() / denom).cpu().item()), + "local_cov_corr": masked_corr(a, b, local_mask.expand_as(a)), + } + + +def compare_covariances(a, b, pair_mask, spatial_dists, near_distance): + b = b.to(device=a.device) + pair_mask = pair_mask.to(device=a.device) + spatial_dists = spatial_dists.to(device=a.device) + eye = torch.eye(pair_mask.shape[0], device=pair_mask.device, dtype=pair_mask.dtype) + offdiag = pair_mask * (1.0 - eye) + near = offdiag * (spatial_dists <= near_distance).to(dtype=offdiag.dtype) + far = offdiag * (spatial_dists > near_distance).to(dtype=offdiag.dtype) + diff = (a - b).float() + denom = (b.float().square() * offdiag).sum().clamp_min(1e-8).sqrt() + near_denom = (b.float().square() * near).sum().clamp_min(1e-8).sqrt() + far_denom = (b.float().square() * far).sum().clamp_min(1e-8).sqrt() + return { + "cross_cov_fro_rel": float(((diff.square() * offdiag).sum().sqrt() / denom).cpu().item()), + "near_cross_cov_fro_rel": float(((diff.square() * near).sum().sqrt() / near_denom).cpu().item()), + "far_cross_cov_fro_rel": float(((diff.square() * far).sum().sqrt() / far_denom).cpu().item()), + "cross_cov_corr": masked_corr(a, b, offdiag), + "near_cross_cov_corr": masked_corr(a, b, near), + "far_cross_cov_corr": masked_corr(a, b, far), + "near_top10_sign_agree_between_settings": top_abs_sign_agree(a, b, near), + "far_top10_sign_agree_between_settings": top_abs_sign_agree(a, b, far), + } + + +def sample_ensemble(module, interpolant, trans_eq, rotmats_eq, seq, condition, num_samples, batch_size): + _, num_res = trans_eq.shape[:2] + chunks = torch.split(torch.arange(num_samples, device=trans_eq.device), batch_size) + ca_samples = [] + with torch.no_grad(): + for chunk in chunks: + bsz = int(chunk.numel()) + z = repeat_condition(module, condition, bsz) + atom37_traj, _, _ = interpolant.sample( + bsz, + num_res, + module.model, + trans_eq.repeat(bsz, 1, 1), + rotmats_eq.repeat(bsz, 1, 1, 1), + seq.repeat(bsz, 1, 1), + z=z, + ) + final_atom37 = torch.stack(atom37_traj, dim=1)[:, -1] + ca_samples.append(final_atom37[:, :, 1, :].detach().float()) + return torch.cat(ca_samples, dim=0) + + +def select_indices(dataset, pdb_name, num_proteins): + if pdb_name: + wanted = [name.strip() for name in pdb_name.split(",") if name.strip()] + out = [] + for name in wanted: + matches = [idx for idx, pdb in enumerate(dataset.pdb_names) if pdb == name] + if not matches: + raise ValueError(f"pdb_name not found in csv: {name}") + out.append(matches[0]) + return out + return list(range(min(num_proteins, len(dataset)))) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--csv_path", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--pdb_name", default="") + parser.add_argument("--num_proteins", type=int, default=3) + parser.add_argument("--num_samples", type=int, default=50) + parser.add_argument("--batch_size", type=int, default=10) + parser.add_argument("--near_distance", type=float, default=12.0) + parser.add_argument("--device", default="cuda") + args = parser.parse_args() + + device = torch.device(args.device if (args.device == "cpu" or torch.cuda.is_available()) else "cpu") + module, cfg, load_info = load_module(args.ckpt_path, device) + interpolant = module.interpolant + interpolant.set_device(device) + # This diagnostic runs as a single process. The sampler's tqdm description + # calls torch.distributed.get_rank(), so force tqdm off here. + interpolant._cfg.use_tqdm = False + + import pandas as pd + + df = pd.read_csv(args.csv_path) + dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) + indices = select_indices(dataset, args.pdb_name, args.num_proteins) + + layer0 = { + "node_cond_shape": "[B,N,K]", + "edge_cond_shape": "[B,N,N,K]", + "disp_node_cond_shape": "[B,N,3]", + "disp_edge_cond_shape": "[B,N,N,1]", + "adapter_accepts_directional_displacement_B_N_3": True, + "finding": "Current generator has a directional node/edge adapters that accepts local-frame per-residue displacement fields disp_node_cond[b,i,3] and disp_edge_cond[b,i,j,1]. Layer 1 compares static directional condition vs zero condition.", + } + results = [] + out_dir = Path(args.output_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + for idx in indices: + item = dataset[idx] + pdb_name = str(item["pdb_name"]) + trans_eq = item["trans_equilibrium"][None].to(device) + rotmats_eq = item["rotmats_equilibrium"][None].to(device) + seq = item["seq"][None].to(device) + _, num_res = trans_eq.shape[:2] + res_mask = torch.ones(1, num_res, device=device) + mask = res_mask[0] + + with torch.no_grad(): + condition = module.latent_encoder.sample_prior_z(trans_eq, rotmats_eq, seq, res_mask) + zero = zero_condition(condition) + static_ca = sample_ensemble(module, interpolant, trans_eq, rotmats_eq, seq, condition, args.num_samples, args.batch_size) + zero_ca = sample_ensemble(module, interpolant, trans_eq, rotmats_eq, seq, zero, args.num_samples, args.batch_size) + + static_stats = ensemble_motion_stats(static_ca, trans_eq[0], mask) + zero_stats = ensemble_motion_stats(zero_ca, trans_eq[0], mask) + static_cov = static_stats["cross_cov"] + zero_cov = zero_stats["cross_cov"] + pair_mask = static_stats["pair_mask"] + spatial_dists = torch.cdist(trans_eq[0].float(), trans_eq[0].float()) + comp = {} + comp.update(compare_covariances(static_cov, zero_cov, pair_mask, spatial_dists, args.near_distance)) + comp.update(compare_local_cov(static_stats["local_cov"], zero_stats["local_cov"], mask)) + comp.update(compare_rmsf(static_stats["rmsf"], zero_stats["rmsf"], mask)) + row = { + "pdb_name": pdb_name, + "num_res": int(num_res), + "num_samples": int(args.num_samples), + **comp, + } + results.append(row) + protein_dir = out_dir / pdb_name + protein_dir.mkdir(parents=True, exist_ok=True) + torch.save({ + "static_cross_cov": static_cov.cpu(), + "zero_cross_cov": zero_cov.cpu(), + "static_local_cov": static_stats["local_cov"].cpu(), + "zero_local_cov": zero_stats["local_cov"].cpu(), + "static_rmsf": static_stats["rmsf"].cpu(), + "zero_rmsf": zero_stats["rmsf"].cpu(), + "pair_mask": pair_mask.cpu(), + "spatial_dists": spatial_dists.cpu(), + "summary": row, + }, protein_dir / "covariances.pt") + (protein_dir / "summary.json").write_text(json.dumps(row, indent=2, sort_keys=True) + "\n") + + numeric_keys = [key for key, value in results[0].items() if isinstance(value, (int, float))] + aggregate = { + key: float(torch.tensor([row[key] for row in results], dtype=torch.float32).mean().item()) + for key in numeric_keys + } + summary = { + "ckpt_path": str(args.ckpt_path), + "load_info": load_info, + "layer0_interface": layer0, + "layer1_static_directional_vs_zero": { + "description": "Full sampling ensembles compared by Kabsch-aligned CA displacement cross-covariance. Static condition includes K-channel scalar conditions and local-frame directional disp_node_cond[b,i,3] plus signed pairwise disp_edge_cond[b,i,j,1].", + "aggregate": aggregate, + "proteins": results, + }, + "layer2_per_sample_directional": { + "status": "not_run", + "reason": "Layer 1 must first show that static directional injection can rearrange long-range co-motion structure.", + }, + } + text = json.dumps(summary, indent=2, sort_keys=True) + (out_dir / "summary.json").write_text(text + "\n") + + aggregate = summary["layer1_static_directional_vs_zero"]["aggregate"] + print("=== Layer 0 interface ===") + print(json.dumps(layer0, indent=2, sort_keys=True)) + print() + print("=== Layer 1 aggregate: static directional vs zero ===") + for key in [ + "rmsf_fro_rel", + "rmsf_corr", + "rmsf_abs_diff_mean", + "local_cov_fro_rel", + "local_cov_corr", + "cross_cov_fro_rel", + "near_cross_cov_fro_rel", + "far_cross_cov_fro_rel", + "cross_cov_corr", + "near_cross_cov_corr", + "far_cross_cov_corr", + "near_top10_sign_agree_between_settings", + "far_top10_sign_agree_between_settings", + ]: + if key in aggregate: + print(f"{key}: {aggregate[key]:.6f}") + print() + print(f"=== Per protein summary written to {out_dir / 'summary.json'} ===") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/probe_condition_quality_vs_md.py b/bbflow_base/scripts/probe_condition_quality_vs_md.py new file mode 100644 index 0000000000000000000000000000000000000000..9dd2bfad2cd3561122f61cf95b0b55dc399f820e --- /dev/null +++ b/bbflow_base/scripts/probe_condition_quality_vs_md.py @@ -0,0 +1,434 @@ +#!/usr/bin/env python +"""Compare per-sample q conditions and matched controls against MD targets. + +Every generated conformation receives an independent c sample. Real, zero, +shuffled, and static conditions reuse matched diffusion-noise seeds. +""" +import argparse +import json +from pathlib import Path +import sys + +import numpy as np +import pandas as pd +import torch +from omegaconf import OmegaConf + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb +from bbflow.models.bbflow_module import BBFlowModule +from scripts.fit_motion_template_upper_bound import load_motion_targets, pdb_name_variants +from scripts.probe_condition_ensemble_cov import ( + align_to_reference, + ensemble_motion_stats, + masked_corr, + select_indices, + top_abs_sign_agree, + zero_condition, +) + +CONDITION_KEYS = {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"} + + +def load_module(ckpt_path, device): + ckpt_path = Path(ckpt_path) + cfg_path = ckpt_path.with_name("config.yaml") + if not cfg_path.exists(): + raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}") + infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml") + ckpt_cfg = OmegaConf.load(cfg_path) + OmegaConf.set_struct(infer_cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(infer_cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.inference.interpolant.use_tqdm = False + cfg.model.embed = ckpt_cfg.model.embed + module = BBFlowModule(cfg) + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + current_state = module.state_dict() + compatible_state = { + key: value for key, value in ckpt["state_dict"].items() + if key in current_state and current_state[key].shape == value.shape + } + missing, unexpected = module.load_state_dict(compatible_state, strict=False) + module.to(device) + module.eval() + return module, cfg, {"loaded": len(compatible_state), "missing": len(missing), "unexpected": len(unexpected)} + + +def clone_condition(condition): + out = {} + for key, value in condition.items(): + out[key] = value.clone() if torch.is_tensor(value) else value + return out + + +def shuffled_condition(condition, res_mask, seed=0): + """Residue-shuffle control preserving values but breaking residue-condition assignment.""" + out = clone_condition(condition) + device = res_mask.device + valid = torch.where(res_mask[0] > 0.5)[0] + gen = torch.Generator(device=device) + gen.manual_seed(int(seed)) + perm_valid = valid[torch.randperm(valid.numel(), generator=gen, device=device)] + perm = torch.arange(res_mask.shape[1], device=device) + perm[valid] = perm_valid + for key in ["node_cond", "disp_node_cond"]: + value = condition.get(key) + if torch.is_tensor(value): + out[key] = value[:, perm, ...] + for key in ["edge_cond", "disp_edge_cond"]: + value = condition.get(key) + if torch.is_tensor(value): + out[key] = value[:, perm, ...][:, :, perm, ...] + return out + + +def condition_seed_for_chunk(seed, batch_index, condition_name): + if condition_name == "static": + return int(seed) + return int(seed + batch_index * 1009) + + +def build_condition_batch( + module, + trans_eq, + rotmats_eq, + seq, + res_mask, + batch_size, + condition_name, + condition_seed, +): + """Build B independent q samples, then derive a matched control condition.""" + torch.manual_seed(int(condition_seed)) + + if condition_name == "static": + single = module.latent_encoder.sample_prior_z( + trans_eq, rotmats_eq, seq, res_mask + ) + if "mode_coefficients" not in single: + raise RuntimeError( + "static control requires latent.sample_coefficients=true" + ) + return module.latent_encoder.repeat_condition(single, batch_size) + + 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) + real = module.latent_encoder.sample_prior_z( + trans_in, rot_in, seq_in, mask_in + ) + if condition_name == "real": + return real + if condition_name == "zero": + return zero_condition(real) + if condition_name == "shuffled": + return shuffled_condition(real, res_mask, seed=condition_seed + 17) + raise ValueError(f"Unknown condition: {condition_name}") + + +def sample_ensemble_for_condition( + module, + interpolant, + trans_eq, + rotmats_eq, + seq, + res_mask, + condition_name, + num_samples, + batch_size, + seed, +): + """Full sampling with independent c per conformation and matched diffusion noise.""" + _, num_res = trans_eq.shape[:2] + chunks = torch.split(torch.arange(num_samples, device=trans_eq.device), batch_size) + ca_samples = [] + with torch.no_grad(): + for batch_index, chunk in enumerate(chunks): + bsz = int(chunk.numel()) + condition_seed = condition_seed_for_chunk( + seed, batch_index, condition_name + ) + diffusion_seed = int(seed + 1_000_000 + batch_index * 1013) + z = build_condition_batch( + module, + trans_eq, + rotmats_eq, + seq, + res_mask, + bsz, + condition_name, + condition_seed, + ) + torch.manual_seed(diffusion_seed) + np.random.seed(diffusion_seed % (2**32 - 1)) + atom37_traj, _, _ = interpolant.sample( + bsz, + num_res, + module.model, + trans_eq.repeat(bsz, 1, 1), + rotmats_eq.repeat(bsz, 1, 1, 1), + seq.repeat(bsz, 1, 1), + z=z, + ) + final_atom37 = torch.stack(atom37_traj, dim=1)[:, -1] + ca_samples.append(final_atom37[:, :, 1, :].detach().float()) + return torch.cat(ca_samples, dim=0) + + +def relative_scalar_loss(pred, target, mask): + pred = pred.float() + target = target.to(device=pred.device, dtype=pred.dtype) + mask = mask.to(device=pred.device).bool() + denom = target[mask].square().sum().clamp_min(1e-8).sqrt() + return float(((pred - target)[mask].square().sum().sqrt() / denom).detach().cpu().item()) if mask.any() else 0.0 + + +def relative_local_cov_loss(pred, target, mask): + pred = pred.float() + target = target.to(device=pred.device, dtype=pred.dtype) + local_mask = mask.to(device=pred.device, dtype=pred.dtype)[:, None, None] + denom = (target.square() * local_mask).sum().clamp_min(1e-8).sqrt() + return float((((pred - target).square() * local_mask).sum().sqrt() / denom).detach().cpu().item()) + + +def relative_cross_cov_loss(pred, target, pair_mask): + pred = pred.float() + target = target.to(device=pred.device, dtype=pred.dtype) + pair_mask = pair_mask.to(device=pred.device, dtype=pred.dtype) + denom = (target.square() * pair_mask).sum().clamp_min(1e-8).sqrt() + return float((((pred - target).square() * pair_mask).sum().sqrt() / denom).detach().cpu().item()) + + +def evaluate_against_target(stats, target, mask, spatial_dists, near_distance): + mask = mask.to(device=stats["rmsf"].device).float() + pair_mask = mask[:, None] * mask[None, :] + eye = torch.eye(pair_mask.shape[0], device=pair_mask.device, dtype=pair_mask.dtype) + offdiag = pair_mask * (1.0 - eye) + near = offdiag * (spatial_dists.to(pair_mask.device) <= near_distance).to(dtype=pair_mask.dtype) + far = offdiag * (spatial_dists.to(pair_mask.device) > near_distance).to(dtype=pair_mask.dtype) + target = {key: value.to(device=mask.device, dtype=torch.float32) for key, value in target.items() if key in {"rmsf", "local_cov", "cross_cov"}} + return { + "rmsf_rel_loss": relative_scalar_loss(stats["rmsf"], target["rmsf"], mask), + "rmsf_corr": masked_corr(stats["rmsf"], target["rmsf"], mask.bool()), + "local_cov_rel_loss": relative_local_cov_loss(stats["local_cov"], target["local_cov"], mask), + "local_cov_corr": masked_corr(stats["local_cov"], target["local_cov"], mask[:, None, None].expand_as(stats["local_cov"])), + "cross_cov_rel_loss": relative_cross_cov_loss(stats["cross_cov"], target["cross_cov"], offdiag), + "cross_cov_corr": masked_corr(stats["cross_cov"], target["cross_cov"], offdiag), + "near_cross_cov_rel_loss": relative_cross_cov_loss(stats["cross_cov"], target["cross_cov"], near), + "near_cross_cov_corr": masked_corr(stats["cross_cov"], target["cross_cov"], near), + "near_top10_sign_agree": top_abs_sign_agree(stats["cross_cov"], target["cross_cov"], near), + "far_cross_cov_rel_loss": relative_cross_cov_loss(stats["cross_cov"], target["cross_cov"], far), + "far_cross_cov_corr": masked_corr(stats["cross_cov"], target["cross_cov"], far), + "far_top10_sign_agree": top_abs_sign_agree(stats["cross_cov"], target["cross_cov"], far), + } + + +def target_for_pdb(targets, pdb_name): + for name in pdb_name_variants(str(pdb_name)): + if name in targets: + return targets[name] + raise KeyError(f"No motion target for {pdb_name}") + + +def improvement_vs(metrics, baseline, prefix): + out = {} + for key, value in metrics.items(): + if not isinstance(value, (int, float)) or key not in baseline: + continue + if key.endswith("_rel_loss"): + out[f"{prefix}_{key}_delta_vs_baseline"] = float(value - baseline[key]) + out[f"{prefix}_{key}_improvement_vs_baseline"] = float(baseline[key] - value) + elif key.endswith("_corr") or key.endswith("sign_agree"): + out[f"{prefix}_{key}_delta_vs_baseline"] = float(value - baseline[key]) + return out + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--csv_path", required=True) + parser.add_argument("--motion_target_cache_path", required=True) + parser.add_argument("--output_dir", required=True) + parser.add_argument("--pdb_name", default="") + parser.add_argument("--num_proteins", type=int, default=10) + parser.add_argument("--num_samples", type=int, default=50) + parser.add_argument("--batch_size", type=int, default=5) + parser.add_argument("--near_distance", type=float, default=12.0) + parser.add_argument("--seed", type=int, default=2026) + parser.add_argument("--progress_dir", default="") + parser.add_argument("--device", default="cuda") + parser.add_argument( + "--resume_existing", + action="store_true", + help="Reuse per-protein summary.json files already present in output_dir.", + ) + parser.add_argument( + "--conditions", + nargs="+", + default=["real", "zero", "shuffled", "static"], + choices=["real", "zero", "shuffled", "static"], + help="Condition variants to evaluate.", + ) + args = parser.parse_args() + + torch.manual_seed(args.seed) + device = torch.device(args.device if (args.device == "cpu" or torch.cuda.is_available()) else "cpu") + module, cfg, load_info = load_module(args.ckpt_path, device) + interpolant = module.interpolant + interpolant.set_device(device) + interpolant._cfg.use_tqdm = False + + targets = load_motion_targets(args.motion_target_cache_path) + df = pd.read_csv(args.csv_path) + dataset = PDBDatasetBBFlowFromPdb(df, sort=False, min_length=0, max_length=np.inf) + indices = select_indices(dataset, args.pdb_name, args.num_proteins) + out_dir = Path(args.output_dir) + out_dir.mkdir(parents=True, exist_ok=True) + progress_dir = Path(args.progress_dir) if args.progress_dir else None + if progress_dir is not None: + progress_dir.mkdir(parents=True, exist_ok=True) + + all_rows = [] + condition_names = list(dict.fromkeys(args.conditions)) + + for idx in indices: + item = dataset[idx] + pdb_name = str(item["pdb_name"]) + protein_dir = out_dir / pdb_name + protein_summary_path = protein_dir / "summary.json" + if args.resume_existing and protein_summary_path.exists(): + existing_rows = json.loads(protein_summary_path.read_text()) + existing_conditions = {row.get("condition") for row in existing_rows} + if set(condition_names).issubset(existing_conditions): + all_rows.extend( + row for row in existing_rows + if row.get("condition") in condition_names + ) + if progress_dir is not None: + (progress_dir / f"{pdb_name}.done").write_text("\n") + print(f"[quality-vs-md] {pdb_name} skipped existing") + continue + + trans_eq = item["trans_equilibrium"][None].to(device) + rotmats_eq = item["rotmats_equilibrium"][None].to(device) + seq = item["seq"][None].to(device) + _, num_res = trans_eq.shape[:2] + res_mask = torch.ones(1, num_res, device=device) + mask = res_mask[0] + target = target_for_pdb(targets, pdb_name) + spatial_dists = torch.cdist(trans_eq[0].float(), trans_eq[0].float()) + + protein_rows = [] + saved = {"target": {k: v.cpu() for k, v in target.items() if torch.is_tensor(v)}} + protein_seed = int(args.seed + idx * 100_003) + for name in condition_names: + ca = sample_ensemble_for_condition( + module, + interpolant, + trans_eq, + rotmats_eq, + seq, + res_mask, + name, + args.num_samples, + args.batch_size, + protein_seed, + ) + stats = ensemble_motion_stats(ca, trans_eq[0], mask) + metrics = evaluate_against_target(stats, target, mask, spatial_dists, args.near_distance) + row = { + "pdb_name": pdb_name, + "condition": name, + "num_res": int(num_res), + "num_samples": int(args.num_samples), + **metrics, + } + protein_rows.append(row) + all_rows.append(row) + saved[name] = {k: v.detach().cpu() for k, v in stats.items()} + + by_name = {row["condition"]: row for row in protein_rows} + for row in protein_rows: + if row["condition"] == "real": + if "zero" in by_name: + row.update(improvement_vs(row, by_name["zero"], "real_minus_zero")) + if "shuffled" in by_name: + row.update(improvement_vs(row, by_name["shuffled"], "real_minus_shuffled")) + if "static" in by_name: + row.update(improvement_vs(row, by_name["static"], "real_minus_static")) + + protein_dir.mkdir(parents=True, exist_ok=True) + torch.save(saved, protein_dir / "motion_stats.pt") + (protein_dir / "summary.json").write_text(json.dumps(protein_rows, indent=2, sort_keys=True) + "\n") + if progress_dir is not None: + (progress_dir / f"{pdb_name}.done").write_text("\n") + print(f"[quality-vs-md] {pdb_name} done") + + aggregate = {} + for condition in condition_names: + rows = [row for row in all_rows if row["condition"] == condition] + numeric_keys = [key for key, value in rows[0].items() if isinstance(value, (int, float))] + aggregate[condition] = { + key: float(torch.tensor([row[key] for row in rows], dtype=torch.float32).mean().item()) + for key in numeric_keys + } + real_rows = [row for row in all_rows if row["condition"] == "real"] + real_deltas = {} + if real_rows: + real_delta_keys = [ + key for key, value in real_rows[0].items() + if isinstance(value, (int, float)) and ("delta_vs_baseline" in key or "improvement_vs_baseline" in key) + ] + real_deltas = { + key: float(torch.tensor([row[key] for row in real_rows if key in row], dtype=torch.float32).mean().item()) + for key in real_delta_keys + } + summary = { + "ckpt_path": str(args.ckpt_path), + "motion_target_cache_path": str(args.motion_target_cache_path), + "load_info": load_info, + "num_proteins": len({row["pdb_name"] for row in all_rows}), + "conditions": { + "real": "independent c~q(c|x_eq) for every generated conformation", + "zero": "matched sampled conditions with node/edge/disp tensors set to zero", + "shuffled": "matched sampled conditions with residue assignments shuffled", + "static": "one c~q(c|x_eq) sampled per protein and fixed across its generated ensemble", + }, + "aggregate_by_condition": aggregate, + "real_condition_deltas": real_deltas, + "proteins": all_rows, + } + text = json.dumps(summary, indent=2, sort_keys=True) + (out_dir / "summary.json").write_text(text + "\n") + + print("=== Quality vs MD aggregate ===") + for condition in condition_names: + print(f"\n== {condition} ==") + for key in [ + "rmsf_rel_loss", + "rmsf_corr", + "local_cov_rel_loss", + "near_cross_cov_rel_loss", + "near_cross_cov_corr", + "near_top10_sign_agree", + "far_cross_cov_rel_loss", + "far_cross_cov_corr", + "far_top10_sign_agree", + ]: + print(f"{key}: {aggregate[condition].get(key, float('nan')):.6f}") + print("\n== real deltas; negative loss delta / positive improvement is good ==") + for key in sorted(real_deltas): + print(f"{key}: {real_deltas[key]:.6f}") + print(f"\n[quality-vs-md] wrote {out_dir / 'summary.json'}") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/probe_sample_condition.py b/bbflow_base/scripts/probe_sample_condition.py new file mode 100644 index 0000000000000000000000000000000000000000..43e21441b2181aa6a0b47e3067fe45b1306a61c2 --- /dev/null +++ b/bbflow_base/scripts/probe_sample_condition.py @@ -0,0 +1,258 @@ +import argparse +import json +from pathlib import Path + +import torch +from omegaconf import OmegaConf + +from bbflow.data.pdb_dataloader_bbflow import PdbDataModuleBBFlow +from bbflow.models.bbflow_module import BBFlowModule + + +def move_to_device(batch, device): + return {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} + + +def load_cfg(repo_root, ckpt_path, overrides): + ckpt_path = Path(ckpt_path) + cfg_path = ckpt_path.with_name("config.yaml") + if not cfg_path.exists(): + raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}") + cfg = OmegaConf.load(cfg_path) + if overrides: + from hydra import compose, initialize_config_dir + + with initialize_config_dir(version_base=None, config_dir=str(repo_root / "configs")): + override_cfg = compose(config_name="train", overrides=overrides) + cfg = OmegaConf.merge(cfg, override_cfg) + OmegaConf.set_struct(cfg, False) + cfg.experiment.use_wandb = False + cfg.experiment.num_devices = 1 + cfg.latent.enable = True + cfg.data.loader.num_workers = 0 + ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False) + return cfg, ckpt + + +def load_checkpoint(module, ckpt): + missing, unexpected = module.load_state_dict(ckpt["state_dict"], strict=False) + return { + "missing": len(missing), + "unexpected": len(unexpected), + "missing_keys": list(missing)[:20], + "unexpected_keys": list(unexpected)[:20], + } + + +def clone_condition(condition): + return { + key: value.clone() if torch.is_tensor(value) else value + for key, value in condition.items() + } + + +def zero_condition(condition): + out = clone_condition(condition) + for key in ("node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"): + if key in out: + out[key] = torch.zeros_like(out[key]) + return out + + +def scale_condition(condition, scale): + out = clone_condition(condition) + for key in ("node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"): + if key in out: + out[key] = out[key] * scale + return out + + +def sample_coefficient_condition(condition, eps, coefficient_scale=1.0): + """Convert static mode blueprint into per-sample mode-coefficient condition. + + The current adapters expect K-channel node/edge conditions, so this probe + keeps the same shapes: + node_cond_sample[b,i,k] = eps[b,k] * node_cond[b,i,k] + edge_cond_sample[b,i,j,k] = eps[b,k]^2 * edge_cond[b,i,j,k] + + Static node_cond already contains sqrt(energy_k) * |U_k[i]|, and static + edge_cond already contains energy_k * . Multiplying by eps + and eps^2 is the compatible K-channel version of sampling + c_k = sqrt(energy_k) * eps_k per generated sample. + """ + out = clone_condition(condition) + coeff = eps.to(device=condition["node_cond"].device, dtype=condition["node_cond"].dtype) * float(coefficient_scale) + out["mode_eps"] = coeff + out["node_cond"] = condition["node_cond"] * coeff[:, None, :] + out["edge_cond"] = condition["edge_cond"] * coeff[:, None, None, :].square() + return out + + +def pred_delta(reference, other): + ref = reference.detach().float() + diff = (other.detach().float() - ref).abs().mean() + denom = ref.abs().mean().clamp_min(1e-8) + return diff, diff / denom + + +def tensor_stats(x): + x = x.detach().float() + return { + "mean": float(x.mean().cpu().item()), + "abs_mean": float(x.abs().mean().cpu().item()), + "std": float(x.std(unbiased=False).cpu().item()) if x.numel() > 1 else 0.0, + "min": float(x.min().cpu().item()), + "max": float(x.max().cpu().item()), + } + + +def condition_stats(prefix, condition): + stats = {} + for key in ("node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"): + if key in condition: + stats[f"{prefix}_{key}"] = tensor_stats(condition[key]) + if "mode_eps" in condition: + stats[f"{prefix}_mode_eps"] = tensor_stats(condition["mode_eps"]) + return stats + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt_path", required=True) + parser.add_argument("--out_path", default="") + parser.add_argument("--device", default="cuda") + parser.add_argument("--num_batches", type=int, default=1) + parser.add_argument("--num_trials", type=int, default=8) + parser.add_argument("--coefficient_scale", type=float, default=1.0) + parser.add_argument("--static_scale", type=float, default=2.0) + parser.add_argument("--seed", type=int, default=7) + parser.add_argument("--override", action="append", default=[]) + args = parser.parse_args() + + repo_root = Path(__file__).resolve().parents[1] + cfg, ckpt = load_cfg(repo_root, args.ckpt_path, args.override) + device = torch.device(args.device if (args.device == "cpu" or torch.cuda.is_available()) else "cpu") + + module = BBFlowModule(cfg).to(device) + load_info = load_checkpoint(module, ckpt) + module.eval() + module.interpolant.set_device(device) + + datamodule = PdbDataModuleBBFlow(cfg.data, training_cfg=cfg.experiment.training, latent_cfg=cfg.latent) + datamodule.setup("fit") + loader = datamodule.train_dataloader(rank=0, num_replicas=1) + generator = torch.Generator(device=device) + generator.manual_seed(int(args.seed)) + + batch_summaries = [] + with torch.no_grad(), torch.autocast(device_type=device.type, enabled=False): + for batch_idx, batch in enumerate(loader): + if batch_idx >= args.num_batches: + break + batch = move_to_device(batch, device) + noisy = module.interpolant.corrupt_batch(batch) + condition = module.latent_encoder.sample_prior_z( + noisy["trans_equilibrium"].float(), + noisy["rotmats_equilibrium"].float(), + noisy["seq"].float(), + noisy["res_mask"].float(), + ) + + noisy_static = dict(noisy) + noisy_static["z"] = condition + pred_static = module.model(noisy_static)["pred_trans"] + + noisy_zero = dict(noisy) + noisy_zero["z"] = zero_condition(condition) + pred_zero = module.model(noisy_zero)["pred_trans"] + + noisy_scaled = dict(noisy) + noisy_scaled["z"] = scale_condition(condition, args.static_scale) + pred_scaled = module.model(noisy_scaled)["pred_trans"] + + zero_abs, zero_rel = pred_delta(pred_static, pred_zero) + scaled_abs, scaled_rel = pred_delta(pred_static, pred_scaled) + + sampled_abs = [] + sampled_rel = [] + sampled_pair_abs = [] + sampled_pair_rel = [] + prev_pred = None + first_sampled_condition = None + batch_size = condition["node_cond"].shape[0] + num_modes = condition["node_cond"].shape[-1] + for trial_idx in range(args.num_trials): + eps = torch.randn(batch_size, num_modes, device=device, generator=generator) + sampled_condition = sample_coefficient_condition( + condition, + eps, + coefficient_scale=args.coefficient_scale, + ) + if first_sampled_condition is None: + first_sampled_condition = sampled_condition + noisy_sampled = dict(noisy) + noisy_sampled["z"] = sampled_condition + pred_sampled = module.model(noisy_sampled)["pred_trans"] + abs_delta, rel_delta = pred_delta(pred_static, pred_sampled) + sampled_abs.append(abs_delta.detach()) + sampled_rel.append(rel_delta.detach()) + if prev_pred is not None: + pair_abs, pair_rel = pred_delta(prev_pred, pred_sampled) + sampled_pair_abs.append(pair_abs.detach()) + sampled_pair_rel.append(pair_rel.detach()) + prev_pred = pred_sampled + + batch_summary = { + "batch_idx": int(batch_idx), + "pdb_names": [str(name) for name in batch["pdb_name"]], + "batch_size": int(batch_size), + "num_res": int(condition["node_cond"].shape[1]), + "num_modes": int(num_modes), + "static_vs_zero_pred_trans_delta": float(zero_abs.cpu().item()), + "static_vs_zero_pred_trans_delta_rel": float(zero_rel.cpu().item()), + "static_vs_scaled_pred_trans_delta": float(scaled_abs.cpu().item()), + "static_vs_scaled_pred_trans_delta_rel": float(scaled_rel.cpu().item()), + "static_vs_sampled_pred_trans_delta": float(torch.stack(sampled_abs).mean().cpu().item()), + "static_vs_sampled_pred_trans_delta_rel": float(torch.stack(sampled_rel).mean().cpu().item()), + } + if sampled_pair_abs: + batch_summary.update({ + "sampled_vs_sampled_pred_trans_delta": float(torch.stack(sampled_pair_abs).mean().cpu().item()), + "sampled_vs_sampled_pred_trans_delta_rel": float(torch.stack(sampled_pair_rel).mean().cpu().item()), + }) + batch_summary.update(condition_stats("static", condition)) + if first_sampled_condition is not None: + batch_summary.update(condition_stats("sampled", first_sampled_condition)) + batch_summaries.append(batch_summary) + + if not batch_summaries: + raise RuntimeError("No batches were processed") + + numeric_keys = [ + key for key, value in batch_summaries[0].items() + if isinstance(value, (int, float)) + ] + aggregate = { + key: float(torch.tensor([row[key] for row in batch_summaries], dtype=torch.float32).mean().item()) + for key in numeric_keys + } + summary = { + "ckpt_path": str(args.ckpt_path), + "num_batches": int(len(batch_summaries)), + "num_trials": int(args.num_trials), + "coefficient_scale": float(args.coefficient_scale), + "static_scale": float(args.static_scale), + "load_info": load_info, + "aggregate": aggregate, + "batches": batch_summaries, + } + text = json.dumps(summary, indent=2, sort_keys=True) + print(text) + if args.out_path: + out_path = Path(args.out_path) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text(text + "\n") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/reachability_audit.py b/bbflow_base/scripts/reachability_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..6eec6063ce08340f564a0a1fd4475e3d66da5d8a --- /dev/null +++ b/bbflow_base/scripts/reachability_audit.py @@ -0,0 +1,147 @@ +"""What is the ceiling on in-plane variance for ANY rescaling of the model's own axes? + +`spectral_calibration.py`'s Phase A reported an enrichment ratio, `r_H / r_T`, where + + r_H = P_H / S_H in-plane variance per unit variance in the head + r_T = P_T / S_T the same for the tail + +and read values of 5 to 117 as "the head is well aligned". That was wrong. The ratio can +be enormous simply because `r_T` is near zero, while `r_H` itself is still below what MD +requires. Under a fixed total variance the attainable in-plane fraction lies between `r_T` +and `r_H`, so **if `r_H` is below MD's in-plane fraction, no amount of tail shrinkage +reaches the target** -- and the ratio never reveals it. + +This computes the ceilings directly, on ensembles already on disk, CPU only: + + two-bin ceiling `r_H` at each cutoff `p`: the best a head/tail transform can do, + reached by putting every unit of variance in the head. + diagonal ceiling `max_k q_k`, where `q_k = ||V_2^T w_k||^2`. Any rescaling of the + model's own principal axes -- two-bin, smooth, per-component, + anything diagonal in that basis -- is a convex combination of the + `q_k` weighted by where it puts variance. So the single best axis + bounds every such method. This is the strongest statement available + without changing the basis. + target MD's own in-plane fraction for that protein. + +Reading it: + + diagonal ceiling below the target no diagonal rescaling of the model's axes can + reach MD's allocation. The post-hoc line is capped + by geometry, not by tuning, and the only way out is + a transform that mixes axes or a model that puts + variance somewhere else to begin with. + two-bin below but diagonal above the head/tail parameterisation is the limitation; + a finer per-component profile could do better. + both above the target the ceiling is not the obstacle and the earlier + infeasibility was about the second constraint + (matching total variance), not about reach. + +Nothing here is tuned or selected: these are properties of the generated ensemble and the +MD reference, computed once. It uses test MD and is a diagnostic, not a method. +""" + +import argparse +import os + +import numpy as np + +from spectral_calibration import prepare + + +def ceilings(pd_, p_grid): + lam, q = pd_["g_lam"], pd_["q"] + total = lam.sum() + target = pd_["md_inplane"] / pd_["md_total"] + actual = float((lam * q).sum() / total) + row = {"name": pd_["name"], "target": float(target), "actual": actual, + "diag_ceiling": float(q.max()), + "var_ratio": float(total / pd_["md_total"])} + # Best single axis is the ceiling for any diagonal rescaling; the top-few average + # shows how fast it decays, i.e. whether the ceiling depends on one lucky direction. + order = np.argsort(q)[::-1] + row["diag_ceiling_top5_mean"] = float(q[order[:5]].mean()) + for p in p_grid: + if p >= len(lam): + continue + s_h, s_t = lam[:p].sum(), lam[p:].sum() + p_h, p_t = (lam[:p] * q[:p]).sum(), (lam[p:] * q[p:]).sum() + row[f"rH_p{p}"] = float(p_h / s_h) if s_h > 0 else np.nan + row[f"rT_p{p}"] = float(p_t / s_t) if s_t > 0 else np.nan + return row + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--md_dir", required=True) + ap.add_argument("--ensemble_dir", required=True) + ap.add_argument("--p_grid", type=int, nargs="*", default=[2, 3, 5, 8, 12, 20, 40]) + ap.add_argument("--require_segments", type=int, default=3) + ap.add_argument("--out_csv", default="") + args = ap.parse_args() + + names = sorted(x for x in os.listdir(args.ensemble_dir) + if os.path.isdir(os.path.join(args.ensemble_dir, x))) + print(f"{len(names)} proteins in {args.ensemble_dir}", flush=True) + + rows, failures = [], [] + for i, nm in enumerate(names): + try: + rows.append(ceilings(prepare(nm, args.md_dir, args.ensemble_dir, + args.require_segments), args.p_grid)) + except Exception as exc: # noqa: BLE001 + failures.append(f"{nm}: {type(exc).__name__}: {exc}") + if (i + 1) % 20 == 0: + print(f" {i+1}/{len(names)}", flush=True) + if failures: + print(f"{len(failures)} failures; first: {failures[0]}") + + import pandas as pd + df = pd.DataFrame(rows) + if args.out_csv: + df.to_csv(args.out_csv, index=False) + print(f"per-protein values -> {args.out_csv}") + + print(f"\n{'='*74}\n in-plane variance fraction, median over {len(df)} proteins" + f"\n{'='*74}") + print(f" MD's fraction (the target) {df.target.median():.4f}") + print(f" model's fraction now {df.actual.median():.4f}") + print(f" model total variance / MD's {df.var_ratio.median():.4f}") + print(f"\n CEILING for any diagonal rescaling of the model's own axes:") + print(f" best single axis max_k q_k {df.diag_ceiling.median():.4f}") + print(f" mean of its top 5 axes " + f"{df.diag_ceiling_top5_mean.median():.4f}") + above = float((df.diag_ceiling > df.target).mean()) + print(f" exceeds the target on {above:.2f} of proteins") + + print(f"\n two-bin (head/tail) ceiling r_H, and the tail r_T it is compared against:") + print(f" {'p':>5}{'r_H':>10}{'r_T':>10}{'enrich = r_H/r_T':>20}" + f"{'r_H > target':>15}") + for p in args.p_grid: + c = f"rH_p{p}" + if c not in df.columns or df[c].isna().all(): + continue + rh, rt = df[c].median(), df[f"rT_p{p}"].median() + frac = float((df[c] > df.target).mean()) + print(f" {p:>5}{rh:>10.4f}{rt:>10.4f}{rh / max(rt, 1e-12):>20.1f}{frac:>15.2f}") + + print(f"\n{'='*74}\n reading\n{'='*74}") + print(" The enrichment column is the number the earlier diagnostic reported. Compare") + print(" it with r_H beside it: a large ratio driven by a near-zero tail says nothing") + print(" about whether the head can reach the target.") + print() + print(" If the diagonal ceiling is below the target, no rescaling of the model's own") + print(" principal axes -- of any shape, however finely tuned -- reaches MD's") + print(" allocation, because every such transform only reweights the q_k it already") + print(" has. That would cap the post-hoc line by geometry rather than by tuning.") + print() + print(" If the diagonal ceiling clears the target but r_H does not, the head/tail") + print(" split is what is limiting, and a per-component profile is worth trying.") + print() + print(" These ceilings ignore the second constraint, matching total variance, and") + print(" ignore that W2 depends on the shape and mean of the cloud rather than on") + print(" in-plane variance alone. They are upper bounds: clearing them is necessary,") + print(" not sufficient.") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/rescore_pca_w2.py b/bbflow_base/scripts/rescore_pca_w2.py new file mode 100644 index 0000000000000000000000000000000000000000..f98b6b6d9148f97b453d546d02e397948fe25064 --- /dev/null +++ b/bbflow_base/scripts/rescore_pca_w2.py @@ -0,0 +1,193 @@ +"""Re-score generated ensembles at a chosen number of principal components, per protein. + +Two problems with the reported number this addresses. + +1. ``analyse_bbflow.py`` calls ``_pca_w2(..., K=2)``: the score sees two directions out of + ``3N``. Anything the model does in the remaining directions is invisible. ``--k`` + here is configurable; run it at 2 and 10 together and compare. + +2. The reported value is a median over 82 proteins, and runs are compared on that + aggregate. Between-protein spread dominates it, so the comparison is far less + sensitive than it could be. This script writes the per-protein values so runs can be + compared *paired*, which removes the protein effect entirely. + +Self-check: the K=2 column should land near the published figure for a run whose reported +score is known. If it does not, the atom selection here differs from the analysis +pipeline and the absolute numbers should not be compared across scripts -- the paired +differences remain valid either way, since the selection is held fixed. + +No GPU. Uses only files already on disk. +""" + +import argparse +import os +import warnings + +import mdtraj +import numpy as np +from scipy.optimize import linear_sum_assignment + + +def _wasserstein(a, b, n_atoms): + """Exact 2-Wasserstein between two equal-size point clouds, in Angstrom. + + Mirrors ``analyse_bbflow._get_wasserstein`` composed with the ``_pca_w2`` scaling. + """ + distmat = np.square(a[:, None] - b[None]).sum(-1) + distmat = distmat ** 0.5 / n_atoms ** 0.5 * 10.0 + distmat = distmat ** 2 + row, col = linear_sum_assignment(distmat) + return float(distmat[row, col].mean() ** 0.5) + + +def _load(name, md_dir, ensemble_dir, rng): + top_path = os.path.join(md_dir, name, f"{name}.pdb") + gen_path = os.path.join(ensemble_dir, name, "sampled_conformations.pdb") + if not (os.path.exists(top_path) and os.path.exists(gen_path)): + return None, None, 0 + + ref = mdtraj.load(top_path) + ca = ref.top.select("name CA") + ref = ref.atom_slice(ca) + + md = None + for i in (1, 2, 3): + path = os.path.join(md_dir, name, f"{name}_R{i}.xtc") + if not os.path.exists(path): + continue + part = mdtraj.load(path, top=top_path).atom_slice(ca) + md = part if md is None else md + part + if md is None: + return None, None, 0 + + gen = mdtraj.load(gen_path) + gen_ca = gen.top.select("name CA") + if gen_ca.size != ca.size: + warnings.warn(f"{name}: CA mismatch; skipping") + return None, None, 0 + gen = gen.atom_slice(gen_ca) + + md.superpose(ref) + gen.superpose(ref) + return md.xyz, gen.xyz, ca.size + + +def score_one(name, md_dir, ensemble_dir, k_list, rng, max_md_frames=3000): + md_xyz, gen_xyz, n_atoms = _load(name, md_dir, ensemble_dir, rng) + if md_xyz is None: + return None + + md_flat = md_xyz.reshape(md_xyz.shape[0], -1) + gen_flat = gen_xyz.reshape(gen_xyz.shape[0], -1) + + md_mean = md_flat.mean(0, keepdims=True) + # The SVD dominates both runtime and peak memory: at ~10^4 frames and 3N ~ 10^3 the + # dense decomposition is several GB, which is enough to get the process killed when + # anything else on the node wants memory. A few thousand frames determine the leading + # ten directions to far better precision than the metric can resolve. + svd_src = md_flat - md_mean + if max_md_frames and svd_src.shape[0] > max_md_frames: + step = svd_src.shape[0] // max_md_frames + svd_src = svd_src[::step][:max_md_frames] + _, _, vh = np.linalg.svd(svd_src, full_matrices=False) + + # Subsample MD to the generated frame count so the assignment problem is square, + # matching the reference implementation's RAND1 step. + idx = rng.integers(0, md_flat.shape[0], gen_flat.shape[0]) + md_sub = md_flat[idx] + + row = {"name": name, "n_res": n_atoms, "gen_frames": gen_flat.shape[0]} + for k in k_list: + basis = vh[:k] + row[f"pca_w2_k{k}"] = _wasserstein( + (md_sub - md_mean) @ basis.T, + (gen_flat - md_mean) @ basis.T, + n_atoms, + ) + return row + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--md_dir", required=True) + ap.add_argument("--ensemble_dirs", nargs="+", required=True) + ap.add_argument("--names", nargs="*", default=[], + help="Labels for the ensemble dirs; defaults to basenames.") + ap.add_argument("--k", type=int, nargs="*", default=[2, 10]) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--max_md_frames", type=int, default=3000, + help="Subsample MD frames before the SVD; 0 disables.") + ap.add_argument("--out_csv", default="") + args = ap.parse_args() + + labels = args.names if args.names else [os.path.basename(d.rstrip("/")) for d in args.ensemble_dirs] + if len(labels) != len(args.ensemble_dirs): + raise SystemExit("--names must match --ensemble_dirs in length") + + import pandas as pd + frames = [] + for label, ens in zip(labels, args.ensemble_dirs): + names = sorted(d for d in os.listdir(ens) if os.path.isdir(os.path.join(ens, d))) + print(f"[{label}] {len(names)} proteins", flush=True) + rng = np.random.default_rng(args.seed) # same subsample across runs -> paired + rows = [] + for i, name in enumerate(names): + try: + row = score_one(name, args.md_dir, ens, args.k, rng, args.max_md_frames) + except Exception as exc: # noqa: BLE001 + warnings.warn(f"{label}/{name}: {type(exc).__name__}: {exc}") + row = None + if row is not None: + row["run"] = label + rows.append(row) + if (i + 1) % 20 == 0: + print(f" {i+1}/{len(names)}", flush=True) + frames.append(pd.DataFrame(rows)) + + df = pd.concat(frames, ignore_index=True) + if args.out_csv: + df.to_csv(args.out_csv, index=False) + print(f"\nper-protein values -> {args.out_csv}") + + print("\n=== aggregate (median over proteins, as reported) ===") + for k in args.k: + line = " ".join( + f"{lab}={df[df.run == lab][f'pca_w2_k{k}'].median():.4f}" for lab in labels + ) + print(f" K={k:<3} {line}") + + if len(labels) < 2: + print("\n(only one run given; pass several --ensemble_dirs for the paired test)") + return + + print("\n=== paired comparison, per protein ===") + from scipy import stats + base = labels[0] + for k in args.k: + col = f"pca_w2_k{k}" + print(f"\n K={k}, baseline = {base}") + b = df[df.run == base].set_index("name")[col] + for lab in labels[1:]: + o = df[df.run == lab].set_index("name")[col] + common = b.index.intersection(o.index) + if len(common) < 3: + print(f" {lab}: too few shared proteins") + continue + d = (o.loc[common] - b.loc[common]).to_numpy() + t, p = stats.ttest_rel(o.loc[common], b.loc[common]) + rho = float(np.corrcoef(o.loc[common], b.loc[common])[0, 1]) + unpaired_se = float(np.sqrt(o.loc[common].var(ddof=1) / len(common) + + b.loc[common].var(ddof=1) / len(common))) + print(f" {lab:<28} mean diff={d.mean():+.4f} " + f"paired SE={d.std(ddof=1)/np.sqrt(len(common)):.4f} " + f"unpaired SE={unpaired_se:.4f} rho={rho:.3f} p={p:.2g} " + f"n={len(common)} wins={int((d < 0).sum())}") + + print("\nReading: 'paired SE' vs 'unpaired SE' is how much resolution the paired") + print("comparison buys. A difference smaller than ~2.8x the SE is not resolvable.") + print("rho is the across-protein correlation between the two runs; the higher it is,") + print("the more the pairing helps.") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/response_jacobian_audit.py b/bbflow_base/scripts/response_jacobian_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..50b4abeb387940baa69dc6a25a9337755b892c42 --- /dev/null +++ b/bbflow_base/scripts/response_jacobian_audit.py @@ -0,0 +1,192 @@ +"""Measure the operator that actually carries the conditioning to the output. + +The objective constrains ``U``, the linear decoder inside the model. What reaches the +sampled structure is ``J = E[d Phi / d c]``, the Jacobian of the 20-step flow map with +respect to the mixture coefficients. Nothing ties the two: between them sit a nonlinear +velocity field and twenty integration steps. + +Every alignment number reported so far -- span_overlap, the reachable floor -- was +computed on ``U``. If ``span(J)`` and ``span(U)`` differ, those numbers describe an +object the evaluation never sees, which would explain why they have tracked the +evaluation badly. + +``J`` is estimated by antithetic central differences: perturb one coefficient by ++/- one standard deviation of ``q``, re-integrate with the initial noise held fixed, and +difference the endpoints. Cost is ``2K`` sampler calls per protein. + +What the numbers mean: + * ``overlap(J, V_2)`` near zero -- the conditioning cannot reach the two directions the + score is computed on, so no reweighting of the objective and no choice of Gamma can + move the score. Only the flow map itself can. + * ``overlap(J, V_2)`` clearly above ``overlap(U, V_2)`` -- the objective has been + aligning the wrong operator, and should be rewritten around ``J``. + * the two roughly equal -- ``U`` is a fair proxy after all, and the failure lies + elsewhere. + +No training. A handful of proteins is enough; the quantity is a property of the map. +""" + +import argparse +import os + +import numpy as np +import torch +from omegaconf import OmegaConf + +from bbflow.models.bbflow_module import BBFlowModule +from bbflow.data.interpolant_bbflow import InterpolantBBFlow +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb +from bbflow.models.collective import mixture_mean_and_covariance + + +def subspace_overlap(columns, reference, top_p): + """Mean squared cosine of the principal angles between span(columns) and the + leading ``top_p`` reference directions. Scale free: both sides are orthonormalised. + + ``columns`` [D, m] arbitrary basis of the subspace under test + ``reference`` [D, R] orthonormal reference directions, leading first + """ + q, _ = np.linalg.qr(columns) + v = reference[:, :top_p] + v, _ = np.linalg.qr(v) + return float(np.square(v.T @ q).sum() / min(top_p, q.shape[1])) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt", required=True) + ap.add_argument("--csv", required=True) + ap.add_argument("--cache", required=True, help="motion-target cache with oracle_modes") + ap.add_argument("--num_proteins", type=int, default=6) + ap.add_argument("--batch", type=int, default=4, help="initial-noise draws averaged over") + ap.add_argument("--timesteps", type=int, default=20) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--device", default="cuda:0") + args = ap.parse_args() + + # Config exactly as inference.py assembles it: the checkpoint's own config supplies + # the model and the prior, the repo default supplies the inference block. + ckpt_cfg = OmegaConf.load(os.path.join(os.path.dirname(args.ckpt), "config.yaml")) + cfg = OmegaConf.load("configs/inference.yaml") + OmegaConf.set_struct(cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.inference.interpolant.sampling.num_timesteps = args.timesteps + cfg.model.embed = ckpt_cfg.model.embed + + print(f"loading {args.ckpt}") + module = BBFlowModule(cfg) + state = torch.load(args.ckpt, map_location="cpu")["state_dict"] + current = module.state_dict() + compatible = {k: v for k, v in state.items() + if k in current and current[k].shape == v.shape} + missing, unexpected = module.load_state_dict(compatible, strict=False) + print(f" loaded {len(compatible)} tensors, missing={len(missing)}, unexpected={len(unexpected)}") + + device = torch.device(args.device) + module = module.to(device).eval() + interpolant = InterpolantBBFlow(cfg.inference.interpolant) + interpolant.set_device(device) + + cache = torch.load(args.cache, map_location="cpu", weights_only=False) + if isinstance(cache, dict) and "motion_targets" in cache: + cache = cache["motion_targets"] + + import pandas as pd + csv = pd.read_csv(args.csv).head(args.num_proteins) + dataset = PDBDatasetBBFlowFromPdb(csv, sort=False, min_length=0, max_length=np.inf) + + rows = [] + for idx in range(len(dataset.pdb_names)): + name = dataset.pdb_names[idx] + entry = cache.get(name) or cache.get(name.replace("_", "")) + if entry is None or "oracle_modes" not in entry: + print(f" {name}: no oracle_modes in cache, skipping") + continue + + trans_eq = dataset.trans[idx][None].to(device).float() + rotmats_eq = dataset.rotmats[idx][None].to(device).float() + seq = dataset.seqs[idx][None].to(device).float() + n_res = trans_eq.shape[1] + res_mask = torch.ones(1, n_res, device=device) + + with torch.no_grad(): + prior, _ = module.latent_encoder.forward_prior(trans_eq, rotmats_eq, seq, res_mask) + u_global = prior["u_global"].float() # [1, N, K, 3] + num_modes = u_global.shape[2] + _, coeff_cov = mixture_mean_and_covariance( + prior["mixture_logits"], prior["mixture_mu"], prior["mixture_scale_tril"] + ) + sigma = torch.diagonal(coeff_cov[0]).clamp_min(1e-12).sqrt() # [K] + + b = args.batch + responses = [] + for k in range(num_modes): + endpoints = {} + for sign in (+1.0, -1.0): + coeff = torch.zeros(b, num_modes, device=device) + coeff[:, k] = sign * sigma[k] + z = module.latent_encoder.condition_from_mode_coefficients( + u_global.expand(b, -1, -1, -1), + coeff, + rotmats_eq.expand(b, -1, -1, -1), + torch.ones(b, n_res, device=device), + include_statistics=False, + ) + # Identical initial noise on both sides: the difference is then the + # response to c alone, not to a fresh draw of x0. + torch.manual_seed(args.seed + 1000 * idx) + atom37, _, _ = interpolant.sample( + b, n_res, module.model, + trans_eq.expand(b, -1, -1), + rotmats_eq.expand(b, -1, -1, -1), + seq.expand(b, -1, -1), + z=z, return_trajectory=False, cache_static_features=True, + ) + last = atom37[-1] if isinstance(atom37, (list, tuple)) else atom37 + if not torch.is_tensor(last): + last = torch.as_tensor(np.asarray(last)) + # sample() hands back host tensors; sigma lives on the device. + ca = last[:, :, 1, :].float().to(device) # [b, N, 3] CA + endpoints[sign] = ca + d = (endpoints[+1.0] - endpoints[-1.0]) / (2.0 * sigma[k]) + responses.append(d.mean(dim=0).reshape(-1)) # [N*3] + + jac = torch.stack(responses, dim=1).cpu().numpy() # [N*3, K] + + modes = entry["oracle_modes"].float() # [N, R, 3] + v = modes.permute(0, 2, 1).reshape(-1, modes.shape[1]).numpy() # [N*3, R] + u = u_global[0].permute(0, 2, 1).reshape(-1, num_modes).cpu().numpy() + + row = {"name": name, "n_res": n_res} + for p in (2, min(10, v.shape[1])): + row[f"J_vs_V{p}"] = subspace_overlap(jac, v, p) + row[f"U_vs_V{p}"] = subspace_overlap(u, v, p) + row["J_vs_U"] = subspace_overlap(jac, np.linalg.qr(u)[0], num_modes) + row["J_norm"] = float(np.linalg.norm(jac)) + row["U_norm"] = float(np.linalg.norm(u)) + rows.append(row) + print(f" {name:8s} N={n_res:4d} " + f"J·V2={row['J_vs_V2']:.4f} U·V2={row['U_vs_V2']:.4f} " + f"J·U={row['J_vs_U']:.4f}") + + if not rows: + raise SystemExit("no proteins produced a measurement") + + df = pd.DataFrame(rows) + print(f"\n{len(df)} proteins, medians:\n") + for c in [c for c in df.columns if c.startswith(("J_vs", "U_vs"))]: + print(f" {c:12s} {df[c].median():.4f}") + + print("\nReading:") + print(" J_vs_V2 near 0 the conditioning does not reach the scored directions;") + print(" no objective written in Gamma can move the score.") + print(" J_vs_V2 >> U_vs_V2 the objective has been aligning the wrong operator.") + print(" J_vs_U near 1 U is a fair proxy for the response after all.") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/scale_calibration_sweep.py b/bbflow_base/scripts/scale_calibration_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..0545e8978c43a900ff57e8dc2f3637b830b9d359 --- /dev/null +++ b/bbflow_base/scripts/scale_calibration_sweep.py @@ -0,0 +1,528 @@ +#!/usr/bin/env python +"""How much of the ensemble error is a pure scale miscalibration? + +`cross_cov_far_corr` is a Pearson correlation between covariance entries, so it +is exactly invariant when every displacement is multiplied by a constant. The +evaluation metric is not. If the model's error is largely a mis-scaled ensemble, +the surrogate cannot see it and a post-hoc calibration fixes it without touching +the model. + +This measures that directly on samples that already exist. For each system it +computes the exact optimal scale in closed form and the metric before and after. + +For zero-mean Gaussians with covariances `s^2 A` and `B`, the squared Bures +distance is + + W2(s)^2 = s^2 tr(A) + tr(B) - 2 s T, T = tr( (B^{1/2} A B^{1/2})^{1/2} ) + +which is a parabola in `s`, minimised at `s* = T / tr(A)` with value +`tr(B) - T^2/tr(A)`. No grid search is needed and the optimum is exact. + +Everything prints to stdout as it goes. +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +import numpy as np + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +import mdtraj +from scipy.stats import pearsonr + +from scripts.surrogate_validation import ( + load_ca, + reference_ensemble, + displacement_matrix, + residue_block_covariance, +) + + +def parse_args(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--ensemble_dir", required=True) + parser.add_argument("--md_dir", required=True) + parser.add_argument("--max_systems", type=int, default=0) + parser.add_argument("--ref_frames", type=int, default=1000) + parser.add_argument("--far_distance", type=float, default=12.0) + parser.add_argument("--top_k", type=int, default=10) + parser.add_argument("--out_csv", default="") + parser.add_argument( + "--write_rescaled", default="", + help="Optional output directory. Writes /sampled_conformations.pdb " + "with displacements rescaled, so the official analysis can be re-run " + "on a comparable footing.", + ) + parser.add_argument( + "--rescale_mode", choices=("per_system", "global"), default="global", + help="per_system uses each system's own optimal scale, which needs the " + "reference ensemble at test time and is therefore not a deployable " + "method -- it is the upper bound. global uses one constant.", + ) + parser.add_argument( + "--group_size", type=int, default=8, + help="Group size the objective is computed from. Only used to report the " + "information ceiling on eigenvector recovery at that group size.", + ) + parser.add_argument( + "--collective_rank", type=int, default=4, + help="Rank of the self-referential basis, for the water-level test.", + ) + return parser.parse_args() + + +def psd_sqrt(matrix): + evals, evecs = np.linalg.eigh(matrix) + evals = np.clip(evals, 0.0, None) + return evecs @ np.diag(np.sqrt(evals)) @ evecs.T + + +def aligned_metric(cov_a, cov_b, top_k): + """Bures error after the best possible orthogonal alignment of `cov_a`. + + `min over Q in O(k)` of `W2(Q A Q^T, B)` equals `sum_i (sqrt(a_i)-sqrt(b_i))^2` + on the independently sorted spectra, so this is basis free: it never touches + an estimated eigenvector and therefore cannot pick up the spurious term that + a direction-paired accounting would suffer near a degenerate spectral tail. + + It is not zero for a model that is a pure rotation of the reference, because + the projection onto the reference's top-k does not commute with that rotation + and truncates energy the rotation moved outside. Verified: at full rank the + rotated case reads 4e-16, at k=10 of 12 it reads 9e-2. That truncation floor + is exactly what the reference-against-itself null measures, which is why the + null is the control that makes this number readable at all. + """ + evals_r, evecs_r = np.linalg.eigh(cov_b) + order = np.argsort(evals_r)[::-1] + basis = evecs_r[:, order[:top_k]] + a = basis.T @ cov_a @ basis + b = basis.T @ cov_b @ basis + tr_b = float(np.trace(b)) + if tr_b <= 0: + return float("nan") + alpha = np.sort(np.clip(np.linalg.eigvalsh(a), 0.0, None))[::-1] + beta = np.sort(np.clip(np.linalg.eigvalsh(b), 0.0, None))[::-1] + return float(np.sqrt(np.sum((np.sqrt(alpha) - np.sqrt(beta)) ** 2)) / np.sqrt(tr_b)) + + +def eigenvector_ceiling(cov_ref, ambient_dim, group_size): + """Best achievable squared overlap with the leading eigenvector from `G` samples. + + Under the spiked model `Sigma = lambda_b (I + beta v v^T)` the attainable + `E^2` is `beta / (beta + gamma)` with `gamma = d / G`, and this is + tight -- it is both the projection-onto-sample-span rate and the Fano upper + bound, so it caps every statistic of the sample, not just the sample + eigenvector. + + Everything turns on the bulk level `lambda_b`: a weak bulk makes eight + samples informative about direction, a heavy one makes them useless no + matter what functional is placed on top. + """ + evals = np.sort(np.clip(np.linalg.eigvalsh(cov_ref), 0.0, None))[::-1] + positive = evals[evals > 1e-12] + if positive.size < 4: + return None + lambda_top = float(positive[0]) + lambda_bulk = float(np.median(positive)) + if lambda_bulk <= 0: + return None + beta = max(lambda_top / lambda_bulk - 1.0, 0.0) + gamma = ambient_dim / float(group_size) + return { + "lambda_top": lambda_top, + "lambda_bulk": lambda_bulk, + "spike_beta": beta, + "overlap_ceiling": beta / (beta + gamma) if (beta + gamma) > 0 else 0.0, + } + + +def water_level(cov_model, cov_ref, top_k, collective_rank): + """Test the sliding-mode prediction for the self-referential basis. + + If the basis tracks the model's own leading eigenvectors, a direction can + only inflate until its variance reaches the model's R-th eigenvalue, at which + point it enters the basis and is pushed back. The prediction is therefore + specific: over-inflated directions should sit just below `lambda_R(model)`, + not spread arbitrarily. + """ + evals_r, evecs_r = np.linalg.eigh(cov_ref) + order = np.argsort(evals_r)[::-1] + basis = evecs_r[:, order[:top_k]] + a_diag = np.clip(np.diag(basis.T @ cov_model @ basis), 1e-12, None) + b_diag = np.clip(np.diag(basis.T @ cov_ref @ basis), 1e-12, None) + + model_evals = np.sort(np.clip(np.linalg.eigvalsh(cov_model), 0.0, None))[::-1] + if model_evals.size < collective_rank: + return None + lambda_r = float(model_evals[collective_rank - 1]) + if lambda_r <= 0: + return None + + inflated = a_diag / b_diag > 2.0 + if not inflated.any(): + return {"n_inflated": 0, "median_log10_vs_lambda_r": float("nan")} + return { + "n_inflated": int(inflated.sum()), + "median_log10_vs_lambda_r": float( + np.median(np.log10(a_diag[inflated] / lambda_r)) + ), + } + + +def scale_analysis(cov_model, cov_ref, top_k): + """Exact optimal isotropic rescaling in the reference principal subspace.""" + evals_r, evecs_r = np.linalg.eigh(cov_ref) + order = np.argsort(evals_r)[::-1] + basis = evecs_r[:, order[:top_k]] + + a = basis.T @ cov_model @ basis + b = basis.T @ cov_ref @ basis + tr_a = float(np.trace(a)) + tr_b = float(np.trace(b)) + if tr_a <= 0 or tr_b <= 0: + return None + + sqrt_b = psd_sqrt(b) + middle = sqrt_b @ a @ sqrt_b + cross = float(np.sqrt(np.clip(np.linalg.eigvalsh(middle), 0.0, None)).sum()) + + w2_sq_at_one = max(tr_a + tr_b - 2.0 * cross, 0.0) + best_scale = cross / tr_a + w2_sq_best = max(tr_b - cross * cross / tr_a, 0.0) + + # Split the error into "wrong eigenvalues" and "wrong eigenvectors". + # + # Over all orthogonal Q, the Bures distance between Q A Q^T and B is + # minimised when the two share eigenvectors with eigenvalues sorted the same + # way, giving sum_i (sqrt(alpha_i) - sqrt(beta_i))^2 on the sorted spectra. + # That floor is reachable by rotating the model's covariance alone, so it is + # exactly the part of the error the spectrum is responsible for; whatever + # sits above it is the cost of the model's principal directions being wrong. + # + # The two call for completely different fixes, which is the whole point of + # computing this: a spectrum error is an allocation problem (how variance is + # divided among the modes), a direction error is a representation problem. + alpha = np.sort(np.clip(np.linalg.eigvalsh(a), 0.0, None))[::-1] + beta = np.sort(np.clip(np.linalg.eigvalsh(b), 0.0, None))[::-1] + w2_sq_aligned = float(np.sum((np.sqrt(alpha) - np.sqrt(beta)) ** 2)) + # Numerical floor only: the aligned value is a mathematical lower bound. + w2_sq_aligned = min(w2_sq_aligned, w2_sq_at_one) + + # Reported in the same normalisation as the surrogate study: a dimensionless + # error relative to the reference's own scale in this subspace. + norm = np.sqrt(tr_b) + spectrum_share = ( + w2_sq_aligned / w2_sq_at_one if w2_sq_at_one > 1e-12 else float("nan") + ) + # How compressed the generated spectrum is: slope of log(alpha) on + # log(beta). Below 1 means variance is spread too evenly across directions. + finite = (alpha > 1e-10) & (beta > 1e-10) + if finite.sum() >= 3: + log_slope = float( + np.polyfit(np.log(beta[finite]), np.log(alpha[finite]), 1)[0] + ) + else: + log_slope = float("nan") + + return { + "scale_opt": best_scale, + "metric_at_1": np.sqrt(w2_sq_at_one) / norm, + "metric_at_opt": np.sqrt(w2_sq_best) / norm, + "metric_aligned": np.sqrt(w2_sq_aligned) / norm, + "spectrum_share": spectrum_share, + "log_spectrum_slope": log_slope, + "trace_ratio": tr_a / tr_b, + # The three scalars that determine the metric at every scale. Caching + # these rather than the covariances is what makes the sweep free: the + # eigendecomposition of cov_ref is up to 2000x2000 and does not depend + # on the scale. + "_tr_a": tr_a, + "_tr_b": tr_b, + "_cross": cross, + } + + +def metric_for_scale(tr_a, tr_b, cross, scale): + """Metric after multiplying every displacement by `scale`, in closed form.""" + value = max(scale * scale * tr_a + tr_b - 2.0 * scale * cross, 0.0) + return np.sqrt(value) / np.sqrt(tr_b) + + +def write_rescaled(ensemble_dir, out_dir, name, scale): + source = Path(ensemble_dir) / name / "sampled_conformations.pdb" + traj = mdtraj.load(str(source)) + xyz = np.asarray(traj.xyz, dtype=np.float64) + mean = xyz.mean(axis=0, keepdims=True) + traj.xyz = (mean + scale * (xyz - mean)).astype(np.float32) + target = Path(out_dir) / name + target.mkdir(parents=True, exist_ok=True) + traj.save_pdb(str(target / "sampled_conformations.pdb")) + + +def main(): + args = parse_args() + ensemble_dir = Path(args.ensemble_dir) + names = sorted( + d.name for d in ensemble_dir.iterdir() + if d.is_dir() and (d / "sampled_conformations.pdb").exists() + ) + if args.max_systems > 0: + names = names[: args.max_systems] + print(f"[scale] {len(names)} systems", flush=True) + + rows = [] + cached = {} + for index, name in enumerate(names, start=1): + try: + ref_struct, ref_traj = reference_ensemble(args.md_dir, name, args.ref_frames) + if ref_struct is None: + print(f"[{index:3d}/{len(names)}] {name}: no reference, skipped", flush=True) + continue + model_traj = load_ca(str(ensemble_dir / name / "sampled_conformations.pdb")) + num_res = ref_struct.n_atoms + if model_traj.n_atoms != num_res: + print(f"[{index:3d}/{len(names)}] {name}: atom mismatch, skipped", flush=True) + continue + + disp_m = displacement_matrix(model_traj, ref_struct) + disp_r = displacement_matrix(ref_traj, ref_struct) + cov_m = (disp_m.T @ disp_m) / max(disp_m.shape[0] - 1, 1) + cov_r = (disp_r.T @ disp_r) / max(disp_r.shape[0] - 1, 1) + + result = scale_analysis(cov_m, cov_r, args.top_k) + if result is None: + print(f"[{index:3d}/{len(names)}] {name}: degenerate covariance, skipped", + flush=True) + continue + + # The invariance claim, checked numerically rather than asserted. + eq = np.asarray(ref_struct.xyz[0], dtype=np.float64) * 10.0 + pair = np.linalg.norm(eq[:, None, :] - eq[None, :, :], axis=-1) + far = pair > args.far_distance + block_m = residue_block_covariance(disp_m, num_res) + block_r = residue_block_covariance(disp_r, num_res) + rho_1 = float(pearsonr(block_m[far], block_r[far])[0]) + block_m_scaled = residue_block_covariance(disp_m * 2.0, num_res) + rho_2 = float(pearsonr(block_m_scaled[far], block_r[far])[0]) + + cached[name] = (result.pop("_tr_a"), result.pop("_tr_b"), + result.pop("_cross")) + + ceiling = eigenvector_ceiling(cov_r, disp_r.shape[1], args.group_size) + level = water_level(cov_m, cov_r, args.top_k, args.collective_rank) + + # Null reading: two disjoint halves of the *same* reference ensemble, + # sized to match the real comparison. Whatever this reads is pure + # finite-sample artefact -- there is no model in it at all. + n_model = disp_m.shape[0] + null_metric = float("nan") + if disp_r.shape[0] >= 2 * n_model: + order_r = np.random.default_rng(0).permutation(disp_r.shape[0]) + part_a = disp_r[order_r[:n_model]] + part_b = disp_r[order_r[n_model:]] + cov_a = (part_a.T @ part_a) / max(part_a.shape[0] - 1, 1) + cov_b = (part_b.T @ part_b) / max(part_b.shape[0] - 1, 1) + null_metric = aligned_metric(cov_a, cov_b, args.top_k) + + row = {"name": name, "num_res": num_res, "rho_at_1": rho_1, + "rho_at_2x": rho_2, "null_aligned": null_metric, **result} + if ceiling: + row.update(ceiling) + if level: + row.update(level) + rows.append(row) + print(f"[{index:3d}/{len(names)}] {name}: N={num_res} " + f"s*={result['scale_opt']:.3f} " + f"metric {result['metric_at_1']:.4f} -> {result['metric_at_opt']:.4f} " + f"| aligned {result['metric_aligned']:.4f} " + f"(spectrum {100*result['spectrum_share']:.0f}%) " + f"slope {result['log_spectrum_slope']:.2f} " + f"| rho {rho_1:.4f} -> {rho_2:.4f} at 2x", flush=True) + except Exception as exc: # noqa: BLE001 + print(f"[{index:3d}/{len(names)}] {name}: FAILED ({exc})", flush=True) + + if len(rows) < 5: + print("[scale] too few systems succeeded", flush=True) + return + + import pandas as pd + frame = pd.DataFrame(rows) + # Written before the sweep: the per-system pass is the expensive part and its + # results should survive anything that happens after it. + if args.out_csv: + frame.to_csv(args.out_csv, index=False) + print(f"\n[scale] per-system table written to {args.out_csv}", flush=True) + + grid = np.linspace(0.3, 3.0, 271) + totals = np.asarray([ + float(np.mean([metric_for_scale(*cached[n], scale) for n in frame["name"]])) + for scale in grid + ]) + best_index = int(np.argmin(totals)) + global_scale = float(grid[best_index]) + + mean_at_one = float(frame["metric_at_1"].mean()) + mean_at_opt = float(frame["metric_at_opt"].mean()) + mean_at_global = float(totals[best_index]) + + frame["metric_at_global"] = [ + metric_for_scale(*cached[n], global_scale) for n in frame["name"] + ] + if args.out_csv: + frame.to_csv(args.out_csv, index=False) + + max_rho_drift = float((frame["rho_at_2x"] - frame["rho_at_1"]).abs().max()) + + print(f"\n{'=' * 74}") + print(f"Scale calibration over {len(frame)} systems") + print("=" * 74) + print(f" surrogate invariance check: max |rho(2x) - rho(1x)| = {max_rho_drift:.2e}") + print(f" (doubling every displacement leaves the surrogate unchanged;") + print(f" any metric change below is invisible to it by construction)") + print() + print(f" mean metric, as generated {mean_at_one:.4f}") + print(f" mean metric, one global scale={global_scale:.3f} {mean_at_global:.4f}" + f" ({100*(1-mean_at_global/mean_at_one):+.1f}%)") + print(f" mean metric, per-system optimal {mean_at_opt:.4f}" + f" ({100*(1-mean_at_opt/mean_at_one):+.1f}%) [upper bound, not deployable]") + print() + print(f" optimal scale: median {frame['scale_opt'].median():.3f}, " + f"IQR [{frame['scale_opt'].quantile(0.25):.3f}, " + f"{frame['scale_opt'].quantile(0.75):.3f}], " + f"range [{frame['scale_opt'].min():.3f}, {frame['scale_opt'].max():.3f}]") + print(f" systems needing to shrink (s*<1): " + f"{int((frame['scale_opt'] < 1).sum())} / {len(frame)}") + print("=" * 74, flush=True) + + mean_aligned = float(frame["metric_aligned"].mean()) + median_share = float(frame["spectrum_share"].median()) + median_slope = float(frame["log_spectrum_slope"].median()) + + print() + print(f" mean metric, eigenvectors made perfect {mean_aligned:.4f}" + f" ({100*(1-mean_aligned/mean_at_one):+.1f}%)") + print(f" of the squared error, the spectrum accounts for a median of " + f"{100*median_share:.0f}%") + print(f" log-spectrum slope, generated vs reference: median " + f"{median_slope:.2f} (1.0 = correct shape, <1 = too flat)") + print("=" * 74, flush=True) + + print("\nReading this:") + if mean_at_global < 0.9 * mean_at_one: + print(" A single constant recovers a large part of the error. The model is") + print(" mis-scaled, not mis-shaped, and the surrogate was blind to exactly") + print(" that. Re-run the official analysis on rescaled samples before") + print(" changing any loss.") + elif mean_at_opt < 0.8 * mean_at_one: + print(" Per-system scaling helps a lot but a single constant does not, so") + print(" the miscalibration is system-dependent. A deployable fix has to") + print(" predict the scale, which is what the amplitude head is for.") + else: + print(" Scale is not the dominant error. The ensembles are wrong in shape,") + print(" and a calibration will not rescue them.") + print() + if median_share > 0.6: + print(" The error lives in the eigenvalues: the principal directions are") + print(" substantially right and the variance is allocated among them") + print(" wrongly. That is an allocation problem, and the head that decides") + print(" the allocation is the thing to fix. Check the slope above -- a") + print(" slope well below 1 means the generated spectrum is too flat,") + print(" which is what a near-uniform amplitude head produces.") + elif median_share < 0.3: + print(" The error lives in the eigenvectors: even with a perfect spectrum") + print(" the ensembles would be nearly as wrong, because they move in the") + print(" wrong directions. No amplitude fix reaches this. The subspace") + print(" itself is the problem.") + else: + print(" The error is split between eigenvalues and eigenvectors, so") + print(" neither fix alone is decisive. Fixing only the allocation caps") + print(" out at the spectrum share reported above.") + print(flush=True) + + # ---- the three decisive measurements ----------------------------------- + print(f"{'=' * 74}") + print("Three measurements that decide where to go next") + print("=" * 74) + + if "null_aligned" in frame and frame["null_aligned"].notna().sum() >= 5: + null_median = float(frame["null_aligned"].median()) + share = null_median / mean_aligned if mean_aligned > 0 else float("nan") + print(f"\n1. NULL. Reference split against itself, matched sample sizes.") + print(f" aligned metric on the null {null_median:.4f}") + print(f" aligned metric against the model {mean_aligned:.4f}") + print(f" the null accounts for {100*share:.0f}%") + if share > 0.7: + print(" -> the eigenvalue residual is a finite-sample artefact. The") + print(" error is essentially all in the directions.") + elif share < 0.3: + print(" -> the eigenvalue residual is real. Both terms need fixing.") + else: + print(" -> the eigenvalue residual is part artefact, part real.") + else: + print("\n1. NULL: not enough reference frames to split; rerun with a") + print(" larger --ref_frames.") + + if "overlap_ceiling" in frame and frame["overlap_ceiling"].notna().sum() >= 5: + ceil_median = float(frame["overlap_ceiling"].median()) + bulk_median = float(frame["lambda_bulk"].median()) + top_median = float(frame["lambda_top"].median()) + print(f"\n2. CEILING at G={args.group_size}. Best squared overlap with the") + print(f" leading eigenvector any statistic of one group can reach.") + print(f" median lambda_top {top_median:.4g}") + print(f" median lambda_bulk {bulk_median:.4g}") + print(f" median ceiling {ceil_median:.3f}" + f" (IQR [{frame['overlap_ceiling'].quantile(0.25):.3f}, " + f"{frame['overlap_ceiling'].quantile(0.75):.3f}])") + if ceil_median > 0.5: + print(" -> a group of this size does carry usable direction") + print(" information. The barrier is not the group size: it is that") + print(" the gradient of a sliced objective has rank-R support and") + print(" cannot push outside its own basis. Anchor the basis to the") + print(" data and accumulate across batches.") + elif ceil_median < 0.2: + print(" -> a group of this size cannot carry direction information.") + print(" No objective on 8-tuples reaches the dominant error term;") + print(" the group size is the binding constraint.") + else: + print(" -> marginal. Direction information exists but is weak; expect") + print(" to need cross-batch accumulation to use any of it.") + + if "median_log10_vs_lambda_r" in frame: + valid = frame["median_log10_vs_lambda_r"].dropna() + if valid.size >= 5: + level_median = float(valid.median()) + print(f"\n3. WATER LEVEL. Over-inflated directions, variance relative to") + print(f" the model's own rank-{args.collective_rank} eigenvalue (log10).") + print(f" median {level_median:+.2f} " + f"(0.00 = exactly at the level)") + print(f" systems with any inflated direction: " + f"{int((frame['n_inflated'] > 0).sum())} / {len(frame)}") + if abs(level_median) < 0.35: + print(" -> consistent with the sliding-mode picture: inflation stops") + print(" where a direction would enter the basis and be pushed") + print(" back. The self-referential basis is the mechanism.") + else: + print(" -> not clustered at the level; the inflation is not being") + print(" set by basis entry and needs another explanation.") + print("=" * 74, flush=True) + + if args.write_rescaled: + out_dir = Path(args.write_rescaled) + out_dir.mkdir(parents=True, exist_ok=True) + print(f"[scale] writing rescaled ensembles to {out_dir} " + f"(mode={args.rescale_mode})", flush=True) + for _, row in frame.iterrows(): + scale = float(row["scale_opt"]) if args.rescale_mode == "per_system" else global_scale + write_rescaled(ensemble_dir, out_dir, row["name"], scale) + print(f"[scale] done. Re-run scripts/analysis_script.py with " + f"--ensemble_dirs {out_dir}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/smoke_md_subspace_loss.py b/bbflow_base/scripts/smoke_md_subspace_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b09539ae5a8123e23d346419329c6be68412a2 --- /dev/null +++ b/bbflow_base/scripts/smoke_md_subspace_loss.py @@ -0,0 +1,141 @@ +"""CPU smoke test for md_subspace_shape_loss against the real cache. Seconds, no GPU. + +Checks, in order: + 1. the cache carries oracle_modes / oracle_energy and their shapes are what the loss + assumes ([N, R, 3] and [R] per protein); + 2. the loss runs on a batch stacked the way _lookup_motion_targets stacks it; + 3. gradients reach both the modes and the mixture parameters; + 4. the loss is zero when the model's implied covariance equals the target, and grows + when it does not -- i.e. the target is actually the minimiser. + +Usage: + python scripts/smoke_md_subspace_loss.py --cache +""" + +import argparse + +import torch + +from bbflow.models.latent import LatentEncoder + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--batch", type=int, default=2) + args = ap.parse_args() + + print(f"loading {args.cache}") + cache = torch.load(args.cache, map_location="cpu", weights_only=False) + # Same unwrapping as bbflow_module._get_motion_target_cache: the rows live under + # "motion_targets", alongside alignment-version metadata. + if isinstance(cache, dict) and "motion_targets" in cache: + print(f" top-level keys: {sorted(cache.keys())}") + cache = cache["motion_targets"] + print(f" {len(cache)} entries") + + entries = [(k, v) for k, v in cache.items() + if isinstance(v, dict) and "oracle_modes" in v and "oracle_energy" in v] + if not entries: + keys = list(cache.keys())[:3] + sample = cache[keys[0]] if keys else {} + raise SystemExit( + "FAIL (1): no entry has oracle_modes/oracle_energy.\n" + f" fields present on {keys[0] if keys else '?'}: " + f"{sorted(sample.keys()) if isinstance(sample, dict) else type(sample)}\n" + " regenerate: python scripts/extract_shape_fingerprints.py --num_modes 8 ..." + ) + print(f" {len(entries)} entries carry oracle_modes/oracle_energy") + + name, row = entries[0] + modes, energy = row["oracle_modes"], row["oracle_energy"] + print(f"\n--- 1. shapes on disk, entry '{name}' ---") + print(f" oracle_modes {tuple(modes.shape)} expected (N, R, 3)") + print(f" oracle_energy {tuple(energy.shape)} expected (R,)") + print(f" rmsf {tuple(row['rmsf'].shape)} expected (N,)") + if modes.dim() != 3 or modes.shape[-1] != 3: + raise SystemExit(f"FAIL (1): oracle_modes is {tuple(modes.shape)}, loss assumes (N, R, 3)") + if energy.dim() != 1 or energy.shape[0] != modes.shape[1]: + raise SystemExit(f"FAIL (1): oracle_energy {tuple(energy.shape)} vs R={modes.shape[1]}") + n_res, rank = modes.shape[0], modes.shape[1] + print(" OK") + + # Stack same-length entries exactly as _lookup_motion_targets does. + same = [r for _, r in entries if r["oracle_modes"].shape[0] == n_res][: args.batch] + while len(same) < args.batch: + same.append(same[0]) + targets = { + "oracle_modes": torch.stack([r["oracle_modes"] for r in same]).float(), + "oracle_energy": torch.stack([r["oracle_energy"] for r in same]).float(), + } + b = targets["oracle_modes"].shape[0] + res_mask = torch.ones(b, n_res) + print(f"\n--- 2. batched: oracle_modes {tuple(targets['oracle_modes'].shape)}, " + f"oracle_energy {tuple(targets['oracle_energy'].shape)} ---") + + num_modes = rank + torch.manual_seed(0) + u_global = (targets["oracle_modes"].clone() * 0.5).requires_grad_(True) + logits = torch.zeros(b, 2, requires_grad=True) + # Not zeros: the mixture means enter the covariance only through the spread of the + # components about their own weighted mean, which is quadratic in (mu_m - mu_bar). + # Identical means sit exactly at a stationary point of that term, so a zero gradient + # there is correct behaviour rather than a broken path, and would make this check + # vacuous. Distinct means exercise the between-component route. + mu = (0.1 * torch.randn(b, 2, num_modes)).requires_grad_(True) + tril = torch.eye(num_modes).repeat(b, 2, 1, 1).clone().requires_grad_(True) + condition = { + "u_global": u_global, + "mixture_logits": logits, + "mixture_mu": mu, + "mixture_scale_tril": tril, + } + + enc = LatentEncoder.__new__(LatentEncoder) # only the static algebra is exercised + out = LatentEncoder.md_subspace_shape_loss(enc, condition, targets, res_mask) + for k, v in out.items(): + print(f" {k:<34} {float(v):.6g}") + if not torch.isfinite(out["md_subspace_shape_loss"]): + raise SystemExit("FAIL (2): loss is not finite") + print(" OK") + + print("\n--- 3. gradient flow ---") + (out["md_subspace_shape_loss"] + out["md_subspace_trace_loss"]).backward() + for nm, t in (("u_global", u_global), ("mixture_mu", mu), ("mixture_scale_tril", tril)): + g = t.grad + ok = g is not None and torch.isfinite(g).all() and g.abs().sum() > 0 + print(f" {nm:<20} grad {'OK' if ok else 'MISSING/ZERO'}" + f" |g|={0.0 if g is None else float(g.abs().max()):.4g}") + if not ok: + raise SystemExit(f"FAIL (3): no usable gradient into {nm}") + + print("\n--- 4. is the reference the minimiser? ---") + # Modes equal to the reference basis and Cov[c] = diag(beta) reproduces the target + # exactly, so the shape loss should sit at ~0 there and rise on either side. + with torch.no_grad(): + beta = targets["oracle_energy"].clamp_min(1e-8) + exact = { + "u_global": targets["oracle_modes"].clone(), + "mixture_logits": torch.zeros(b, 1), + "mixture_mu": torch.zeros(b, 1, num_modes), + "mixture_scale_tril": torch.diag_embed(beta.sqrt()).unsqueeze(1), + } + base = float(LatentEncoder.md_subspace_shape_loss( + enc, exact, targets, res_mask)["md_subspace_shape_loss"]) + print(f" at the reference {base:.6g}") + for s in (0.5, 2.0): + scaled = dict(exact) + scaled["mixture_scale_tril"] = exact["mixture_scale_tril"] * s + v = float(LatentEncoder.md_subspace_shape_loss( + enc, scaled, targets, res_mask)["md_subspace_shape_loss"]) + print(f" Cov[c] scaled by {s:<4} {v:.6g} {'OK' if v > base else 'FAIL'}") + if v <= base: + raise SystemExit( + "FAIL (4): dilating the model does not increase the loss -- the " + "statistic would carry the scale invariance this loss exists to avoid" + ) + print("\nall checks passed") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/spectral_calibration.py b/bbflow_base/scripts/spectral_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..50bd43a93e17d57026fdae5f980d0c59eb97d0e7 --- /dev/null +++ b/bbflow_base/scripts/spectral_calibration.py @@ -0,0 +1,701 @@ +"""Inference-time spectral calibration of generated conformational ensembles. + +The measured defect +------------------- +A subspace variance audit found the generated ensembles are not uniformly over-dispersed, +they are *misallocated*: + + total variance 1.62x MD's + outside MD's top 10 directions 3.6x MD's + inside MD's top 2 directions 0.73x MD's (27% LOW -- and this is what is scored) + +The model under-fills the directions PCA-W2 looks at and over-fills the ones it does not. +Three training objectives failed because they acted on `U`, the internal decoder +(overlap 0.205 with the scored plane), rather than on the flow's actual response `J` +(overlap 0.576). Both inference knobs are structurally unable to reach the defect: +`condition_scale` scales the conditioning variable, so it moves only the steerable +variance component; `gamma_trans` sets the prior width, which is measurably forgotten +after 20 integration steps. + +This acts on the output samples, where the tail is reachable: rescale the ensemble along +its *own* principal directions, amplifying the head and shrinking the tail, + + x -> mu + sum_k s_k w_k, s_k = gamma (k <= p), beta (k > p) + +then re-superpose, because the official scorer superposes every frame it loads and a +linear recombination of individually-aligned structures is not itself aligned. + +Whether it can work at all (Phase A) +------------------------------------ +PCA-W2 projects onto *MD's* top-2 plane `V_2`, not the model's. With + + q_k = ||V_2^T w_k||^2 model PC k's share of the plane + S_H = sum_{k<=p} lam_k, S_T = sum_{k>p} lam_k head / tail variance + P_H = sum_{k<=p} lam_k q_k, P_T = sum_{k>p} lam_k q_k head / tail variance in-plane + +amplifying the head can cut total variance and raise in-plane variance simultaneously only +if `P_H/S_H > P_T/S_T`. That inequality is exact for the raw linear rescale, but the +implemented transform re-superposes afterwards and a per-frame Kabsch rotation is +nonlinear, so it is a necessary-mechanism diagnostic rather than a verdict -- Phase A also +applies the real transform at a predeclared probe and reports what actually happens to +both variances. Phase A reports the inequality, the per-protein `(gamma, beta)` implied by + + gamma^2 S_H + beta^2 S_T = S_target gamma^2 P_H + beta^2 P_T = P_target + +and -- because per-protein feasibility does not imply one global setting serves them all -- +the dispersion of those solutions and how well the single best global pair does. + +**Phase A uses MD and is a diagnostic. It selects nothing that Phase B uses.** The control +arms' cutoff is the predeclared constant `CONTROL_P`, not an MD-derived optimum. + +Honest selection (Phase B) +-------------------------- +Two modes, and only the first should ever be reported as a headline number: + + frozen `--select_on_dir` / `--select_on_md_dir` name a disjoint cohort (e.g. the 39 + validation proteins, never touched by any prior comparison). One global + setting is chosen there by median delta, frozen, and applied unchanged to + every protein of the evaluation cohort. + exploratory no selection cohort: repeated K-fold cross-fitting inside the evaluation + cohort. Each protein's delta comes from a setting chosen on folds that + exclude it, and the confidence interval re-runs the selection inside every + bootstrap resample, so it reflects selection instability rather than + conditioning on one lucky choice. + +Neither erases that this cohort has already informed 15-30 comparisons and the conception +of this method. A change smaller than the 0.06-0.08 selection band is not evidence. + +What this is and is not +----------------------- +It is calibration of CA-coordinate ensembles, not generation of physical backbones. +Rescaled principal components are linear combinations the model never produced, whose +geometry need not be valid -- and every reported metric is CA geometry, so none of them can +see that. Geometry diagnostics are reported for each arm, and a `reweight` arm in which +every output conformation is one the model really generated is included as the +validity-preserving control. If a gain survives only under coordinate rescaling and not +under reweighting, that is a finding about the metric. + +The transform is not novel: it is eigenvalue shrinkage / spectral filtering / covariance +inflation, long established in ensemble data assimilation and essential dynamics. What is +specific here is the diagnosis and the held-out test. + +Only `pca_w2` is comparable to the project's own numbers; its kernel is a verbatim copy of +the project's code and is checked against the original at startup given projected +coordinates -- the PCA fit, centering, sampling and superposition around it are this +script's own, and the metric is averaged over `N_MD_DRAWS` reference draws rather than the +official scorer's single realisation, so the official rescoring of `--write_best_pdb` is +what should be reported. Every +other column here is a differently-defined internal diagnostic, is prefixed `diag_`, and +must not be compared with the published table -- use `--write_best_pdb` and score those +files with the official `analysis_script.py`. +""" + +import argparse +import os +from collections import Counter + +import numpy as np +from scipy.optimize import linear_sum_assignment + +PRIMARY = "pca_w2" +CONTROL_P = 5 # predeclared cutoff for the control arms; never MD-derived +CA_BOND = 3.8 # Angstrom +BREAK_TOL = 0.5 # |CA-CA - 3.8| above this counts as a broken bond +CLASH = 4.0 # Angstrom, for |i-j| >= 3 pairs only +N_REWEIGHT_DRAWS = 5 +N_MD_DRAWS = 3 # metric averaged over this many reference draws, per protein + + +# --------------------------------------------------------------------------- metric + +def _wasserstein(distmat, p=2): + """Verbatim copy of `analyse_bbflow._get_wasserstein`.""" + assert distmat.shape[0] == distmat.shape[1] + distmat = distmat ** p + row_ind, col_ind = linear_sum_assignment(distmat) + return distmat[row_ind, col_ind].mean() ** (1 / p) + + +def pca_w2(ref_proj, model_proj, n_atoms): + """Verbatim copy of the `analyse_bbflow._pca_w2` body, for already-projected input.""" + d = np.square(ref_proj[:, None] - model_proj[None]).sum(-1) ** 0.5 / n_atoms ** 0.5 * 10 + return float(_wasserstein(d)) + + +def verify_metric(): + """Check the whole PCA-W2 path against the project's, not just the assignment kernel. + + Returns True if verified, False if the project module could not be imported. Only + import errors are swallowed: a genuine failure inside the project's own code must not + be reported as a missing optional dependency. + """ + try: + from bbflow.analysis.analyse_bbflow import _pca_w2 as ref_impl + except (ImportError, ModuleNotFoundError): + return False + rng = np.random.default_rng(0) + for n, n_atoms in ((5, 12), (40, 97), (120, 300)): + a = rng.normal(size=(n, 2)) + b = rng.normal(size=(n, 2)) + mine = pca_w2(a, b, n_atoms) + theirs = float(ref_impl(a.copy(), b.copy(), n_atoms, K=2)["pca_w2"]) + assert abs(mine - theirs) < 1e-12, f"metric drifted: {mine} vs {theirs}" + return True + + +# --------------------------------------------------------------------------- geometry + +def superpose_to(coords, target, n_atoms): + """Kabsch-align every frame to `target`, batched. + + The official scorer superposes every frame it loads. A rescaled principal-component + reconstruction is a linear recombination of individually-aligned structures and is not + itself aligned, so scoring it without this step measures something the official path + never sees, and can pick a different winner. + """ + x = coords.reshape(len(coords), n_atoms, 3) + t_mu = target.mean(0) + tc = target - t_mu + xc = x - x.mean(1, keepdims=True) + h = np.einsum("fij,ik->fjk", xc, tc) + u, _, vt = np.linalg.svd(h) + sign = np.sign(np.linalg.det(np.einsum("fij,fjk->fik", u, vt))) + u = u.copy() + u[:, :, -1] *= sign[:, None] + r = np.einsum("fij,fjk->fik", u, vt) + return (np.einsum("fij,fjk->fik", xc, r) + t_mu).reshape(len(coords), -1) + + +def geometry(coords, n_atoms): + x = coords.reshape(len(coords), n_atoms, 3) * 10.0 # nm -> Angstrom + bond = np.linalg.norm(np.diff(x, axis=1), axis=-1) + dev = np.abs(bond - CA_BOND) + d = np.linalg.norm(x[:, :, None] - x[:, None, :], axis=-1) + iu = np.triu_indices(n_atoms, k=3) # |i-j| >= 3 only + return {"diag_bond_dev": float(dev.mean()), + "diag_bond_break_frac": float((dev > BREAK_TOL).mean()), + "diag_bond_dev_max": float(dev.max()), + "diag_clash_frac": float((d[:, iu[0], iu[1]] < CLASH).mean())} + + +def _kabsch_rmsd_batch(a, b): + ac = a - a.mean(1, keepdims=True) + bc = b - b.mean(1, keepdims=True) + h = np.einsum("fij,fik->fjk", ac, bc) + u, s, vt = np.linalg.svd(h) + sign = np.sign(np.linalg.det(np.einsum("fij,fjk->fik", u, vt))) + s = s.copy() + s[:, -1] *= sign + n = a.shape[1] + sq = (np.square(ac).sum((1, 2)) + np.square(bc).sum((1, 2)) - 2 * s.sum(1)) / n + return np.sqrt(np.maximum(sq, 0.0)) + + +def diagnostics(coords, md_sample, n_atoms, rng, n_pairs=1500): + """Internal spread diagnostics. NOT the project's definitions -- see the docstring.""" + out = geometry(coords, n_atoms) + x = coords.reshape(len(coords), n_atoms, 3) * 10.0 + m = md_sample.reshape(len(md_sample), n_atoms, 3) * 10.0 + rmsf_g = np.sqrt(np.square(x - x.mean(0)).sum(-1).mean(0)) + rmsf_m = np.sqrt(np.square(m - m.mean(0)).sum(-1).mean(0)) + out["diag_rmsf_r"] = float(np.corrcoef(rmsf_g, rmsf_m)[0, 1]) + out["diag_rmsf_mae"] = float(np.abs(rmsf_g - rmsf_m).mean()) + out["diag_rmsf_med"] = float(np.median(rmsf_g)) + out["diag_md_rmsf_med"] = float(np.median(rmsf_m)) + i = rng.integers(0, len(x), n_pairs) + j = rng.integers(0, len(x), n_pairs) + ok = i != j + out["diag_pw_kabsch_med"] = float(np.median(_kabsch_rmsd_batch(x[i[ok]], x[j[ok]]))) + i = rng.integers(0, len(m), n_pairs) + j = rng.integers(0, len(m), n_pairs) + ok = i != j + out["diag_md_pw_kabsch_med"] = float(np.median(_kabsch_rmsd_batch(m[i[ok]], m[j[ok]]))) + return out + + +# --------------------------------------------------------------------------- per protein + +def prepare(name, md_dir, ensemble_dir, require_segments): + from centroid_reliability import load_generated, load_reference, stable_seed + ref, md_flat, n_atoms, _ = load_reference(name, md_dir, require_segments) + gen = load_generated(name, ensemble_dir, ref) + ref_xyz = np.asarray(ref.xyz[0], dtype=np.float64) if ref is not None else \ + gen[0].reshape(n_atoms, 3) + + md_mu = md_flat.mean(0, keepdims=True) + _, md_sv, md_vt = np.linalg.svd(md_flat - md_mu, full_matrices=False) + md_lam = md_sv ** 2 / len(md_flat) + + gen_mu = gen.mean(0, keepdims=True) + u, sv, vt = np.linalg.svd(gen - gen_mu, full_matrices=False) + g_lam = sv ** 2 / len(gen) + v2 = md_vt[:2] + + # One MD comparison draw per protein, shared by every arm, so arms are paired and no + # arm carries extra MD Monte Carlo noise. The size is the generated cloud's, not a + # free parameter: production draws `model_traj.n_frames` reference frames with + # replacement, and the assignment the metric uses requires a square matrix. + r = np.random.default_rng(stable_seed(name, 12345)) + md_samples = [md_flat[r.integers(0, len(md_flat), len(gen))] for _ in range(N_MD_DRAWS)] + + return {"name": name, "n_atoms": n_atoms, "gen": gen, "ref_xyz": ref_xyz, + "md_flat": md_flat, "md_mu": md_mu, "v2": v2, "md_samples": md_samples, + "md_total": float(md_lam.sum()), "md_inplane": float(md_lam[:2].sum()), + "u": u, "sv": sv, "vt": vt, "gen_mu": gen_mu, "g_lam": g_lam, + "q": np.square(v2 @ vt.T).sum(0)} + + +def reshape(pd_, p, gamma, beta): + """Rescale along the ensemble's own directions, then re-superpose. SVD is cached.""" + s = np.where(np.arange(len(pd_["sv"])) < p, gamma, beta) + out = (pd_["u"] * (pd_["sv"] * s)) @ pd_["vt"] + pd_["gen_mu"] + return superpose_to(out, pd_["ref_xyz"], pd_["n_atoms"]) + + +def reweight(pd_, p, gamma, beta, rng): + """Validity-preserving control: resample real conformations, never build new ones.""" + c = (pd_["gen"] - pd_["gen_mu"]) @ pd_["vt"].T + head = np.square(c[:, :p]).sum(1) + tail = np.square(c[:, p:]).sum(1) + head = head / max(head.mean(), 1e-12) + tail = tail / max(tail.mean(), 1e-12) + logw = np.log(max(gamma, 1e-6)) * head + np.log(max(beta, 1e-6)) * tail + logw -= logw.max() + w = np.exp(logw) + w /= w.sum() + ess = float(1.0 / np.square(w).sum()) + draws = [pd_["gen"][rng.choice(len(pd_["gen"]), len(pd_["gen"]), replace=True, p=w)] + for _ in range(N_REWEIGHT_DRAWS)] + mean_shift = float(np.linalg.norm((pd_["gen"] * w[:, None]).sum(0) + - pd_["gen"].mean(0)) / np.sqrt(pd_["n_atoms"])) + return draws, ess, mean_shift + + +def score_primary(pd_, coords): + """Averaged over the protein's fixed reference draws. + + A single draw lets a grid winner exploit that one Monte Carlo realisation, which + matters most in the small selection cohort where the frozen setting is picked. + """ + mod_proj = (coords - pd_["md_mu"]) @ pd_["v2"].T + return float(np.mean([pca_w2((m - pd_["md_mu"]) @ pd_["v2"].T, mod_proj, + pd_["n_atoms"]) for m in pd_["md_samples"]])) + + +# --------------------------------------------------------------------------- phase A + +def phase_a(pd_, p_grid): + lam, q = pd_["g_lam"], pd_["q"] + out = [] + for p in p_grid: + if p >= len(lam): + continue + s_h, s_t = lam[:p].sum(), lam[p:].sum() + p_h, p_t = (lam[:p] * q[:p]).sum(), (lam[p:] * q[p:]).sum() + if s_h <= 0 or s_t <= 0: + continue + det = s_h * p_t - s_t * p_h + g2 = b2 = np.nan + if abs(det) > 1e-30: + g2 = (pd_["md_total"] * p_t - s_t * pd_["md_inplane"]) / det + b2 = (s_h * pd_["md_inplane"] - pd_["md_total"] * p_h) / det + ok = g2 == g2 and b2 == b2 and g2 > 1.0 and 0 < b2 < 1.0 + out.append({"name": pd_["name"], "p": p, + "enrich": float((p_h / s_h) / max(p_t / s_t, 1e-30)), + "inplane_frac_model": float((lam * q).sum() / lam.sum()), + "inplane_frac_md": float(pd_["md_inplane"] / pd_["md_total"]), + "var_ratio": float(lam.sum() / pd_["md_total"]), + "gamma": float(np.sqrt(g2)) if g2 == g2 and g2 > 0 else np.nan, + "beta": float(np.sqrt(b2)) if b2 == b2 and b2 > 0 else np.nan, + "has_solution": bool(g2 == g2 and b2 == b2 and g2 > 0 and b2 > 0), + "feasible": bool(ok)}) + return out + + +PROBE = (1.2, 0.8) # predeclared small perturbation for the post-Kabsch sign check + + +def post_kabsch_check(pd_, p_grid): + """Does the transform ACTUALLY cut total variance and raise in-plane variance? + + Phase A's algebra is exact for the raw linear rescale, but `reshape` re-superposes + afterwards, and a per-frame Kabsch rotation is nonlinear -- it changes both variances. + So the inequality is a necessary-mechanism diagnostic, not a theorem about the + implemented method. This measures the two quantities on the real output, at one + predeclared perturbation, and is the check that actually decides the sign. + """ + base = superpose_to(pd_["gen"], pd_["ref_xyz"], pd_["n_atoms"]) + def moments(c): + cc = c - c.mean(0, keepdims=True) + total = float(np.square(cc).sum() / len(cc)) + inpl = float(np.square(cc @ pd_["v2"].T).sum() / len(cc)) + return total, inpl + t0, i0 = moments(base) + out = [] + for p in p_grid: + if p >= len(pd_["sv"]): + continue + t1, i1 = moments(reshape(pd_, p, *PROBE)) + out.append({"name": pd_["name"], "p": p, + "total_falls": bool(t1 < t0), "inplane_rises": bool(i1 > i0), + "both": bool(t1 < t0 and i1 > i0), + "d_total": float(t1 / max(t0, 1e-30)), + "d_inplane": float(i1 / max(i0, 1e-30))}) + return out + + +def subspace_stability(gen, p, rng, reps=6): + n = len(gen) + vals = [] + for _ in range(reps): + idx = rng.permutation(n) + a, b = gen[idx[:n // 2]], gen[idx[n // 2:]] + va = np.linalg.svd(a - a.mean(0), full_matrices=False)[2][:p] + vb = np.linalg.svd(b - b.mean(0), full_matrices=False)[2][:p] + vals.append(np.square(va @ vb.T).sum() / p) + return float(np.mean(vals)) + + +# --------------------------------------------------------------------------- main + +NOOP = (0, 1.0, 1.0) # p=0 -> every component scaled by beta=1.0 -> identity + + +def build_grid(p_grid, gamma_grid, beta_grid): + """The identity is a candidate on purpose. + + Without it the selector must return some transform even when every one of them loses + on the selection cohort, so `chosen` would mean "least bad reshape" rather than + "calibration was worth applying". If NOOP wins, the honest answer is that it is not. + """ + return [NOOP] + [(p, g, b) for p in p_grid for g in gamma_grid for b in beta_grid + if not (g == 1.0 and b == 1.0)] + + +def delta_matrix(data, settings): + """[n_proteins, n_settings] change in the primary metric against no correction.""" + base = np.array([score_primary(d, superpose_to(d["gen"], d["ref_xyz"], d["n_atoms"])) + for d in data]) + m = np.empty((len(data), len(settings))) + for j, (p, g, b) in enumerate(settings): + for i, d in enumerate(data): + m[i, j] = score_primary(d, reshape(d, p, g, b)) + return m - base[:, None], base + + +def load_cohort(md_dir, ensemble_dir, require_segments, label): + names = sorted(x for x in os.listdir(ensemble_dir) + if os.path.isdir(os.path.join(ensemble_dir, x))) + print(f"[{label}] {len(names)} proteins in {ensemble_dir}", flush=True) + data, failures = [], [] + for i, nm in enumerate(names): + try: + data.append(prepare(nm, md_dir, ensemble_dir, require_segments)) + except Exception as exc: # noqa: BLE001 + failures.append(f"{nm}: {type(exc).__name__}: {exc}") + if (i + 1) % 20 == 0: + print(f" loaded {i+1}/{len(names)}", flush=True) + if failures: + print(f" {len(failures)} failures:") + for f in failures[:5]: + print(f" {f}") + return data, failures + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--md_dir", required=True) + ap.add_argument("--ensemble_dir", required=True) + ap.add_argument("--select_on_dir", default="") + ap.add_argument("--select_on_md_dir", default="") + ap.add_argument("--p_grid", type=int, nargs="*", default=[2, 3, 5, 8, 12, 20]) + ap.add_argument("--gamma_grid", type=float, nargs="*", + default=[1.0, 1.1, 1.2, 1.35, 1.5, 1.75, 2.0]) + ap.add_argument("--beta_grid", type=float, nargs="*", + default=[1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4]) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--repeats", type=int, default=10) + ap.add_argument("--require_segments", type=int, default=3) + ap.add_argument("--expect_select_cohort", type=int, default=0, + help="frozen mode: required size of the selection cohort") + ap.add_argument("--expect_cohort", type=int, default=0, + help="fail rather than silently evaluate a favourable subset") + ap.add_argument("--allow_unverified_metric", action="store_true") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out_csv", default="") + ap.add_argument("--write_best_pdb", default="") + args = ap.parse_args() + + if bool(args.select_on_dir) != bool(args.select_on_md_dir): + raise SystemExit("--select_on_dir and --select_on_md_dir must be given together") + if args.repeats < 1: + raise SystemExit("--repeats must be >= 1") + if args.folds < 2: + raise SystemExit("--folds must be >= 2 (one fold leaves no training set)") + _fold_cap_checked = False + + verified = verify_metric() + if verified: + print("PCA-W2 kernel verified identical to analyse_bbflow's given projected " + "coordinates\n(the PCA fit, centering, sampling and superposition around it " + "are this script's own)", flush=True) + elif args.allow_unverified_metric: + print("WARNING: analyse_bbflow not importable; PCA-W2 copy is UNVERIFIED. " + "Exploratory only.", flush=True) + else: + raise SystemExit("cannot import analyse_bbflow to verify the metric. Run where " + "the project imports work, or pass --allow_unverified_metric " + "and treat the result as exploratory.") + + import pandas as pd + data, failures = load_cohort(args.md_dir, args.ensemble_dir, args.require_segments, + "evaluate") + if not data: + raise SystemExit("no protein loaded") + if args.expect_cohort and len(data) != args.expect_cohort: + raise SystemExit(f"loaded {len(data)} proteins, expected {args.expect_cohort}; " + f"refusing to report on a subset ({len(failures)} failures)") + + # ------------------------------- Phase A + print(f"\n{'='*78}\n PHASE A -- feasibility (uses MD; selects nothing Phase B uses)" + f"\n{'='*78}") + fa = pd.DataFrame([r for d in data for r in phase_a(d, args.p_grid)]) + d0 = fa[fa.p == fa.p.min()] + print(f"\n model variance / MD variance {d0.var_ratio.median():.2f}x") + print(f" model variance fraction in-plane {d0.inplane_frac_model.median():.3f}" + f" MD's {d0.inplane_frac_md.median():.3f}") + print(f"\n {'p':>4}{'enrich':>9}{'>1 frac':>9}{'has soln':>10}{'feasible':>10}" + f"{'gamma p25/50/75':>22}{'beta p25/50/75':>22}") + for p in sorted(fa.p.unique()): + s = fa[fa.p == p] + gq = np.nanpercentile(s.gamma, [25, 50, 75]) + bq = np.nanpercentile(s.beta, [25, 50, 75]) + print(f" {p:>4}{s.enrich.median():>9.2f}{(s.enrich > 1).mean():>9.2f}" + f"{s.has_solution.mean():>10.2f}{s.feasible.mean():>10.2f}" + f"{f'{gq[0]:.2f}/{gq[1]:.2f}/{gq[2]:.2f}':>22}" + f"{f'{bq[0]:.2f}/{bq[1]:.2f}/{bq[2]:.2f}':>22}") + print("\n enrich must exceed 1 for head amplification to raise in-plane variance while") + print(" total variance falls. 'has soln' is the fraction with any positive root at") + print(" all; quartiles are over those only, so a low 'has soln' makes them") + print(" unrepresentative. Wide quartiles mean no single global pair serves the") + print(" cohort -- per-protein feasibility does not imply a global setting exists,") + print(" which is what Phase B actually tests.") + print("\n These are computed BEFORE re-superposition. The implemented transform") + print(" re-superposes, and a per-frame Kabsch rotation is nonlinear, so the algebra") + print(" above is a necessary-mechanism diagnostic, not a theorem about the method.") + print(f" The check below applies the real transform at the predeclared probe") + print(f" gamma={PROBE[0]}, beta={PROBE[1]} and measures what actually happens:") + pk = pd.DataFrame([r for d in data for r in post_kabsch_check(d, args.p_grid)]) + print(f"\n {'p':>4}{'total falls':>14}{'in-plane rises':>17}{'both':>8}" + f"{'total ratio':>14}{'in-plane ratio':>16}") + for p in sorted(pk.p.unique()): + t = pk[pk.p == p] + print(f" {p:>4}{t.total_falls.mean():>14.2f}{t.inplane_rises.mean():>17.2f}" + f"{t.both.mean():>8.2f}{t.d_total.median():>14.3f}" + f"{t.d_inplane.median():>16.3f}") + print(" 'both' is the fraction of proteins where the real transform moves both the") + print(" right way at this one probe. A low fraction weakens the mechanism but does") + print(" not rule the method out: a different amplification/shrinkage balance may") + print(" still work after the nonlinear alignment. Phase B is what settles it.") + rng = np.random.default_rng(args.seed) + stab = [subspace_stability(d["gen"], CONTROL_P, rng) for d in data] + print(f"\n split-half stability of the top-{CONTROL_P} model subspace over all " + f"{len(data)} proteins: {np.median(stab):.3f}" + f" (1.0 reproducible; low means head amplification amplifies sampling noise)") + + # ------------------------------- Phase B + print(f"\n{'='*78}\n PHASE B -- apply and score\n{'='*78}", flush=True) + settings = build_grid(args.p_grid, args.gamma_grid, args.beta_grid) + print(f" {len(settings)} settings x {len(data)} proteins", flush=True) + dm, base = delta_matrix(data, settings) + print(f" uncorrected {PRIMARY}: median {np.median(base):.4f}", flush=True) + + # Best setting picked directly on this cohort. This is what the number would be with + # no protection at all, and it is printed so it can be compared with the honest one + # below rather than guessed at. The gap between them IS the selection optimism, paid + # for by nothing -- both come from the same grid that was already computed. + med_all = np.median(dm, axis=0) + j_naive = int(np.argmin(med_all)) + naive = settings[j_naive] + print(f"\n [selected directly on these {len(data)} proteins, for reference]") + print(f" best of {len(settings)} settings: p={naive[0]} gamma={naive[1]} " + f"beta={naive[2]} median change {med_all[j_naive]:+.4f}") + print(f" this is the most optimistic number available and cannot distinguish a") + print(f" real effect from the best of {len(settings)} draws; compare it with the") + print(f" held-out number below -- if they agree the effect is real, if only this") + print(f" one is good then the improvement does not exist outside this cohort") + + if args.select_on_dir: + sel_data, sel_failures = load_cohort(args.select_on_md_dir, args.select_on_dir, + args.require_segments, "select") + if not sel_data: + raise SystemExit("selection cohort is empty") + # Failures here silently change which setting gets frozen, while the output still + # describes a legitimate disjoint cohort. Same hazard as a favourable evaluation + # subset, so it gets the same treatment. + if sel_failures: + raise SystemExit(f"{len(sel_failures)} selection proteins failed to load; " + f"the frozen setting would be chosen on a subset. First: " + f"{sel_failures[0]}") + if args.expect_select_cohort and len(sel_data) != args.expect_select_cohort: + raise SystemExit(f"selection cohort has {len(sel_data)} proteins, expected " + f"{args.expect_select_cohort}") + overlap = {d["name"] for d in sel_data} & {d["name"] for d in data} + if overlap: + raise SystemExit(f"selection and evaluation cohorts share {len(overlap)} " + f"proteins; they must be disjoint") + sel_dm, _ = delta_matrix(sel_data, settings) + j = int(np.argmin(np.median(sel_dm, axis=0))) + frozen = settings[j] + honest = dm[:, j] + mode = (f"FROZEN: one global setting chosen on {len(sel_data)} disjoint " + f"proteins, applied unchanged") + print(f"\n {mode}") + print(f" setting p={frozen[0]} gamma={frozen[1]} beta={frozen[2]}" + f" (its median delta on the selection cohort: " + f"{np.median(sel_dm[:, j]):+.4f})") + + def boot(reps=4000): + r = np.random.default_rng(0) + idx = r.integers(0, len(honest), (reps, len(honest))) + return np.percentile(np.median(honest[idx], axis=1), [2.5, 97.5]) + per_protein_setting = [frozen] * len(data) + else: + # Repeated K-fold: each protein's delta comes from folds excluding it. + if args.folds > len(data): + raise SystemExit(f"--folds {args.folds} exceeds {len(data)} proteins") + r = np.random.default_rng(args.seed) + acc = np.zeros(len(data)) + cnt = np.zeros(len(data)) + picks = [] + for _ in range(args.repeats): + order = r.permutation(len(data)) + folds = np.array_split(order, args.folds) + for f in folds: + tr = np.setdiff1d(order, f) + j = int(np.argmin(np.median(dm[tr], axis=0))) + picks.append(settings[j]) + acc[f] += dm[f, j] + cnt[f] += 1 + honest = acc / np.maximum(cnt, 1) + top, top_n = Counter(picks).most_common(1)[0] + mode = (f"EXPLORATORY: {args.repeats}x{args.folds}-fold cross-fitted inside the " + f"evaluation cohort") + print(f"\n {mode}") + print(f" most-selected setting p={top[0]} gamma={top[1]} beta={top[2]} " + f"({top_n}/{len(picks)} folds) -- selection varies across folds, which is " + f"why the CI below re-runs it") + + def boot(reps=1000): + rb = np.random.default_rng(0) + meds = np.empty(reps) + for t in range(reps): + bs = rb.integers(0, len(data), len(data)) + oob = np.setdiff1d(np.arange(len(data)), bs) + if len(oob) < 3: + meds[t] = np.nan + continue + jj = int(np.argmin(np.median(dm[bs], axis=0))) + meds[t] = np.median(dm[oob, jj]) + return np.nanpercentile(meds, [2.5, 97.5]) + per_protein_setting = [top] * len(data) + frozen = top + print(f" NOTE: the arms table below and any PDB export use this modal setting") + print(f" scored IN SAMPLE on the evaluation cohort. That is not the " + f"cross-fitted number.") + print(f" The only trustworthy exploratory result is the paired change above.") + + lo, hi = boot() + interval = ("protein bootstrap of the frozen setting" if args.select_on_dir + else "OOB selection-instability spread, NOT a CI for the cross-fitted " + "estimate") + print(f" paired change in {PRIMARY}: {np.median(honest):+.4f} " + f"[{lo:+.4f}, {hi:+.4f}] (negative = better)") + print(f" interval = {interval}") + print(f" improved on {(honest < 0).mean():.2f} of proteins, " + f"worsened on {(honest > 0).mean():.2f}") + print(f" the selection band from prior reuse of this cohort is 0.06-0.08; a change") + print(f" smaller than that is not evidence, whatever the interval says") + + # ------------------------------- arms + recs = [] + for i, d in enumerate(data): + r = np.random.default_rng(2024) + aligned = superpose_to(d["gen"], d["ref_xyz"], d["n_atoms"]) + chosen_label = "frozen_setting" if args.select_on_dir else "dev_modal_in_sample" + arms = {"uncorrected": aligned, + chosen_label: reshape(d, *per_protein_setting[i]), + "tail_only": reshape(d, CONTROL_P, 1.0, 0.6), + "head_only": reshape(d, CONTROL_P, 1.5, 1.0), + "uniform": reshape(d, len(d["sv"]), 0.8, 0.8)} + for arm, co in arms.items(): + recs.append({"name": d["name"], "arm": arm, PRIMARY: score_primary(d, co), + **diagnostics(co, d["md_samples"][0], d["n_atoms"], + np.random.default_rng(7))}) + draws, ess, shift = reweight(d, CONTROL_P, 1.5, 0.6, r) + for k, co in enumerate(draws): + co = superpose_to(co, d["ref_xyz"], d["n_atoms"]) + recs.append({"name": d["name"], "arm": "reweight", "draw": k, + PRIMARY: score_primary(d, co), "ess": ess, "mean_shift": shift, + **diagnostics(co, d["md_samples"][0], d["n_atoms"], + np.random.default_rng(7))}) + if (i + 1) % 20 == 0: + print(f" arms {i+1}/{len(data)}", flush=True) + + df = pd.DataFrame(recs) + if args.out_csv: + df.to_csv(args.out_csv, index=False) + print(f"\nper-protein values -> {args.out_csv}") + + cols = [PRIMARY, "diag_rmsf_r", "diag_rmsf_mae", "diag_rmsf_med", + "diag_pw_kabsch_med", "diag_bond_dev", "diag_bond_break_frac", "diag_clash_frac"] + print(f"\n arms, median over proteins. ONLY {PRIMARY} is comparable to the published") + print(f" table; every diag_* column is an internal definition of this script's own.") + print(" " + f"{'arm':<20}" + "".join(f"{c.replace('diag_',''):>16}" for c in cols)) + chosen_label = "frozen_setting" if args.select_on_dir else "dev_modal_in_sample" + for arm in ("uncorrected", chosen_label, "tail_only", "head_only", "uniform", + "reweight"): + s = df[df.arm == arm] + if s.empty: + continue + print(f" {arm:<20}" + "".join(f"{s[c].median():>16.4f}" for c in cols)) + print(f" {'MD ref':<20}{'-':>16}{'-':>16}{'-':>16}" + f"{df.diag_md_rmsf_med.median():>16.4f}" + f"{df.diag_md_pw_kabsch_med.median():>16.4f}" + f"{'-':>16}" * 3) + rw = df[df.arm == "reweight"] + if not rw.empty: + print(f"\n reweight effective sample size {rw.ess.median():.0f} of " + f"{len(data[0]['gen'])}, weighted-mean displacement " + f"{rw.mean_shift.median():.4f} nm over {N_REWEIGHT_DRAWS} draws") + print(f" (a large mean displacement means this arm is partly correcting the " + f"centroid,\n which is a different effect from covariance calibration)") + print(f"\n bond_break_frac is the fraction of CA-CA bonds off 3.8 A by more than " + f"{BREAK_TOL} A;\n clash_frac counts |i-j|>=3 CA pairs under {CLASH} A. If " + f"'chosen' moves these against\n 'uncorrected', the gain is bought with " + f"geometry no reported metric can see, and only\n the reweight arm -- whose " + f"every conformation the model really produced -- is trustworthy.") + + if args.write_best_pdb and not args.select_on_dir: + print(f"\n NOT writing PDBs: in exploratory mode the setting is test-informed " + f"and its\n in-sample score is not the cross-fitted estimate. Re-run with " + f"--select_on_dir\n to produce ensembles worth scoring officially.") + elif args.write_best_pdb: + import mdtraj + from centroid_reliability import load_reference + os.makedirs(args.write_best_pdb, exist_ok=True) + for i, d in enumerate(data): + ref, _, n_atoms, _ = load_reference(d["name"], args.md_dir, + args.require_segments) + co = reshape(d, *per_protein_setting[i]) + t = mdtraj.Trajectory(co.reshape(len(co), n_atoms, 3), ref.top) + od = os.path.join(args.write_best_pdb, d["name"]) + os.makedirs(od, exist_ok=True) + t.save_pdb(os.path.join(od, "sampled_conformations.pdb")) + print(f"\n ensembles ({mode.split(':')[0]}) -> {args.write_best_pdb}") + print(" score these with the official analysis_script.py. The numbers above are " + "internal;\n only the official ones belong in any comparison with the " + "published table.") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/subspace_variance_audit.py b/bbflow_base/scripts/subspace_variance_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..b2691309b7560897e47520de25e054e66b21da55 --- /dev/null +++ b/bbflow_base/scripts/subspace_variance_audit.py @@ -0,0 +1,160 @@ +"""Where does the generated ensemble put its variance? + +Motivation +---------- +The reported ``MD PCA W2`` projects onto the top ``K=2`` principal components of the +reference trajectory (``analyse_bbflow.py``: ``_pca_w2(..., K=2)``). A model is therefore +free to place arbitrary variance in the remaining ``3N-2`` directions without the metric +responding. The observed pattern -- the most over-dispersed run scoring best -- is what +that blindness would look like. + +This script measures it directly. For each protein it builds the reference eigenbasis +``V`` from the full MD trajectory and reports, for both MD and the generated ensemble, the +fraction of total displacement variance captured by the leading ``K`` directions. + +If the generated fraction is materially lower than MD's at ``K=2``, variance is sitting +where the metric does not look, and every comparison made with that metric is confounded. + +CA atoms only, superposed to the reference structure. No GPU, no model, no training. +""" + +import argparse +import os +import warnings + +import mdtraj +import numpy as np + + +def _load_pair(name, md_dir, ensemble_dir): + """Return (md_disp, gen_disp) as [T, N, 3] displacement arrays in the same frame.""" + top_path = os.path.join(md_dir, name, f"{name}.pdb") + gen_path = os.path.join(ensemble_dir, name, "sampled_conformations.pdb") + if not os.path.exists(top_path) or not os.path.exists(gen_path): + return None, None + + ref = mdtraj.load(top_path) + ca = ref.top.select("name CA") + if ca.size < 4: + return None, None + ref = ref.atom_slice(ca) + + traj_paths = [os.path.join(md_dir, name, f"{name}_R{i}.xtc") for i in (1, 2, 3)] + traj_paths = [p for p in traj_paths if os.path.exists(p)] + if not traj_paths: + return None, None + md = None + for path in traj_paths: + part = mdtraj.load(path, top=top_path).atom_slice(ca) + md = part if md is None else md + part + + gen = mdtraj.load(gen_path) + gen_ca = gen.top.select("name CA") + if gen_ca.size != ca.size: + warnings.warn(f"{name}: CA count mismatch md={ca.size} gen={gen_ca.size}; skipping") + return None, None + gen = gen.atom_slice(gen_ca) + + # Remove rigid motion against a common reference before measuring covariance. + md.superpose(ref) + gen.superpose(ref) + + md_xyz = md.xyz * 10.0 # nm -> Angstrom + gen_xyz = gen.xyz * 10.0 + return md_xyz - md_xyz.mean(0, keepdims=True), gen_xyz - gen_xyz.mean(0, keepdims=True) + + +def _captured_fraction(disp, basis): + """Fraction of total variance of ``disp`` lying in span(basis). + + ``disp`` [T, N, 3] already mean-centred + ``basis`` [K, N*3] orthonormal rows + """ + flat = disp.reshape(disp.shape[0], -1) + total = float(np.square(flat).sum() / max(flat.shape[0] - 1, 1)) + if total <= 0.0: + return float("nan"), 0.0 + coeff = flat @ basis.T # [T, K] + inside = float(np.square(coeff).sum() / max(flat.shape[0] - 1, 1)) + return inside / total, total + + +def audit_one(name, md_dir, ensemble_dir, k_list): + md_disp, gen_disp = _load_pair(name, md_dir, ensemble_dir) + if md_disp is None: + return None + + flat = md_disp.reshape(md_disp.shape[0], -1) + # Right singular vectors of the centred MD displacement are the PCA modes. + _, sing, vh = np.linalg.svd(flat, full_matrices=False) + row = {"name": name, "n_res": md_disp.shape[1], + "md_frames": md_disp.shape[0], "gen_frames": gen_disp.shape[0]} + + for k in k_list: + basis = vh[:k] + md_frac, md_total = _captured_fraction(md_disp, basis) + gen_frac, gen_total = _captured_fraction(gen_disp, basis) + row[f"md_frac_k{k}"] = md_frac + row[f"gen_frac_k{k}"] = gen_frac + row[f"blind_ratio_k{k}"] = (1.0 - gen_frac) / max(1.0 - md_frac, 1e-9) + row["md_total_var"] = md_total + row["gen_total_var"] = gen_total + row["var_ratio"] = gen_total / max(md_total, 1e-9) + return row + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--md_dir", required=True) + ap.add_argument("--ensemble_dir", required=True) + ap.add_argument("--k", type=int, nargs="*", default=[2, 10]) + ap.add_argument("--out_csv", default="") + args = ap.parse_args() + + names = sorted( + d for d in os.listdir(args.ensemble_dir) + if os.path.isdir(os.path.join(args.ensemble_dir, d)) + ) + print(f"auditing {len(names)} proteins at K={args.k}", flush=True) + + rows = [] + for i, name in enumerate(names): + try: + row = audit_one(name, args.md_dir, args.ensemble_dir, args.k) + except Exception as exc: # noqa: BLE001 - report and continue + warnings.warn(f"{name}: {type(exc).__name__}: {exc}") + row = None + if row is None: + continue + rows.append(row) + if (i + 1) % 10 == 0: + print(f" {i+1}/{len(names)}", flush=True) + + if not rows: + raise SystemExit("no proteins could be audited -- check --md_dir and --ensemble_dir") + + import pandas as pd + df = pd.DataFrame(rows) + if args.out_csv: + df.to_csv(args.out_csv, index=False) + print(f"\nper-protein values -> {args.out_csv}") + + print(f"\n{len(df)} proteins\n") + print("Fraction of total displacement variance inside the leading MD directions") + print("(median over proteins; MD is the reference, generated is the model)\n") + print(f" {'K':>4} {'MD':>8} {'generated':>10} {'outside-variance ratio':>22}") + for k in args.k: + print(f" {k:>4} {df[f'md_frac_k{k}'].median():>8.4f}" + f" {df[f'gen_frac_k{k}'].median():>10.4f}" + f" {df[f'blind_ratio_k{k}'].median():>22.3f}") + + print(f"\n total variance ratio (generated / MD), median: {df['var_ratio'].median():.3f}") + print("\nReading:") + print(" outside-variance ratio > 1 means the model puts proportionally more of its") + print(" motion outside the measured subspace than MD does -- i.e. the K=2 metric is") + print(" blind to it. Combined with a total variance ratio > 1 (over-dispersion),") + print(" that is the mechanism by which an over-dispersed run can score best.") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/surrogate_validation.py b/bbflow_base/scripts/surrogate_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..5a3b0cb7ee9f9b3713f5021a0f8c32674aa57038 --- /dev/null +++ b/bbflow_base/scripts/surrogate_validation.py @@ -0,0 +1,348 @@ +#!/usr/bin/env python +"""Rank candidate covariance statistics against the real evaluation metric. + +A surrogate is only worth optimising if it moves with the thing it stands for. +`cross_cov_far_corr` did not: it is a Pearson correlation between covariance +entries, so it is invariant under a global rescaling of the ensemble, while the +evaluation metric is not. A model can inflate every variance by 100x and leave +the correlation untouched. That is what happened, and it took 26 epochs of +training to find out. + +This script answers the question offline, on samples that already exist, with no +GPU and no training: across the held-out systems, which candidate statistics +actually rank-correlate with the evaluation metric? + +Only candidates that survive here are worth putting in a loss. If none survive, +second-moment regularisation cannot work for this metric and that is the result. + +Everything is printed to stdout as it goes. +""" + +from __future__ import annotations + +import argparse +import os +import pickle +import sys +from pathlib import Path + +import numpy as np + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +import mdtraj +from scipy.stats import spearmanr, pearsonr + + +def parse_args(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--ensemble_dir", required=True, + help="Directory of /sampled_conformations.pdb") + parser.add_argument("--md_dir", required=True, + help="Directory of /.pdb and _R{1,2,3}.xtc") + parser.add_argument("--metrics_pkl", default="", + help="Optional analysis_metrics_path pickle for the " + "pipeline's own per-system metrics.") + parser.add_argument("--max_systems", type=int, default=0, + help="0 means all.") + parser.add_argument("--ref_frames", type=int, default=1000, + help="Reference frames after striding, per system.") + parser.add_argument("--far_distance", type=float, default=12.0, + help="Residue pairs farther apart than this (Angstrom, " + "in the reference structure) count as long range.") + parser.add_argument("--top_k", type=int, default=10, + help="Principal subspace size for the spectral candidates.") + parser.add_argument("--out_csv", default="", + help="Optional per-system table.") + return parser.parse_args() + + +def load_ca(path, top=None, stride=1): + traj = mdtraj.load(path, top=top, stride=stride) if top else mdtraj.load(path) + ca = traj.top.select("name CA") + if ca.size == 0: + raise ValueError(f"no CA atoms in {path}") + return traj.atom_slice(ca) + + +def reference_ensemble(md_dir, name, ref_frames): + entry = Path(md_dir) / name + top_path = entry / f"{name}.pdb" + if not top_path.exists(): + return None, None + ref = load_ca(str(top_path)) + chunks = [] + for i in (1, 2, 3): + xtc = entry / f"{name}_R{i}.xtc" + if not xtc.exists(): + continue + traj = mdtraj.load(str(xtc), top=str(top_path)) + ca = traj.top.select("name CA") + chunks.append(traj.atom_slice(ca)) + if not chunks: + return None, None + full = chunks[0] + for chunk in chunks[1:]: + full += chunk + if full.n_frames > ref_frames: + full = full[:: max(1, full.n_frames // ref_frames)][:ref_frames] + return ref, full + + +def displacement_matrix(traj, reference): + """Superpose onto the reference and return [M, 3N] mean-centred displacements.""" + traj = traj.superpose(reference) + xyz = np.asarray(traj.xyz, dtype=np.float64) * 10.0 # nm -> Angstrom + flat = xyz.reshape(xyz.shape[0], -1) + return flat - flat.mean(axis=0, keepdims=True) + + +def residue_block_covariance(disp, num_res): + """[N, N] matrix whose (i,j) entry is sum_d Cov(x_i^d, x_j^d).""" + cov = (disp.T @ disp) / max(disp.shape[0] - 1, 1) + blocks = cov.reshape(num_res, 3, num_res, 3) + return np.einsum("idjd->ij", blocks) + + +def gaussian_w2_sq(cov_a, cov_b): + """Squared Bures-Wasserstein distance between zero-mean Gaussians.""" + evals_b, evecs_b = np.linalg.eigh(cov_b) + evals_b = np.clip(evals_b, 0.0, None) + sqrt_b = evecs_b @ np.diag(np.sqrt(evals_b)) @ evecs_b.T + middle = sqrt_b @ cov_a @ sqrt_b + evals_m = np.clip(np.linalg.eigvalsh(middle), 0.0, None) + return float(np.trace(cov_a) + np.trace(cov_b) - 2.0 * np.sqrt(evals_m).sum()) + + +def candidates(disp_model, disp_ref, num_res, far_mask, top_k): + """Every statistic a loss could plausibly target, plus the metric itself.""" + out = {} + + cov_m = (disp_model.T @ disp_model) / max(disp_model.shape[0] - 1, 1) + cov_r = (disp_ref.T @ disp_ref) / max(disp_ref.shape[0] - 1, 1) + + # --- the evaluation metric, recomputed here so the study is self-contained. + # Reference top-k principal subspace, both ensembles projected onto it, + # Bures distance between the projected second moments, made dimensionless + # by the reference's own scale. + evals_r, evecs_r = np.linalg.eigh(cov_r) + order = np.argsort(evals_r)[::-1] + basis = evecs_r[:, order[:top_k]] + proj_m = basis.T @ cov_m @ basis + proj_r = basis.T @ cov_r @ basis + ref_scale = float(np.trace(proj_r)) + 1e-12 + out["METRIC_pca_w2"] = np.sqrt(max(gaussian_w2_sq(proj_m, proj_r), 0.0)) / np.sqrt(ref_scale) + + # --- candidate 1: the surrogate that was actually used. + # Pearson correlation of long-range residue-block covariance entries. + # Scale invariant by construction; included as the control. + block_m = residue_block_covariance(disp_model, num_res) + block_r = residue_block_covariance(disp_ref, num_res) + far_m, far_r = block_m[far_mask], block_r[far_mask] + if far_m.size >= 2 and far_m.std() > 0 and far_r.std() > 0: + out["cross_cov_far_corr"] = float(pearsonr(far_m, far_r)[0]) + else: + out["cross_cov_far_corr"] = np.nan + + # --- candidate 2: pure scale. No pattern information at all. + tr_m, tr_r = float(np.trace(cov_m)), float(np.trace(cov_r)) + out["abs_log_trace_ratio"] = abs(np.log((tr_m + 1e-12) / (tr_r + 1e-12))) + + # --- candidate 3: relative Frobenius error of the full covariance. + out["cov_fro_rel"] = float( + np.linalg.norm(cov_m - cov_r) / (np.linalg.norm(cov_r) + 1e-12) + ) + + # --- candidate 4: long-range block error, scale sensitive. + out["far_block_rel_err"] = float( + np.linalg.norm(far_m - far_r) / (np.linalg.norm(far_r) + 1e-12) + ) + + # --- candidate 5: spectrum only, in the reference basis. + eig_m = np.clip(np.diag(proj_m), 0.0, None) + eig_r = np.clip(np.diag(proj_r), 0.0, None) + out["abs_log_spectrum_err"] = float( + np.mean(np.abs(np.log((eig_m + 1e-8) / (eig_r + 1e-8)))) + ) + + # --- candidate 6: directions only, scale blind by construction. + evals_m, evecs_m = np.linalg.eigh(cov_m) + order_m = np.argsort(evals_m)[::-1] + top_m = evecs_m[:, order_m[:2]] + top_r = evecs_r[:, order[:2]] + out["top2_subspace_overlap"] = float(np.mean((top_m.T @ top_r) ** 2)) + + # --- candidate 7/8: per-residue amplitude, pattern and scale separately. + rmsf_m = np.sqrt(np.clip(np.diag(block_m), 0.0, None)) + rmsf_r = np.sqrt(np.clip(np.diag(block_r), 0.0, None)) + if rmsf_m.std() > 0 and rmsf_r.std() > 0: + out["rmsf_corr"] = float(pearsonr(rmsf_m, rmsf_r)[0]) + else: + out["rmsf_corr"] = np.nan + out["abs_log_rmsf_ratio"] = abs( + np.log((rmsf_m.mean() + 1e-12) / (rmsf_r.mean() + 1e-12)) + ) + + return out + + +def main(): + args = parse_args() + ensemble_dir = Path(args.ensemble_dir) + names = sorted( + d.name for d in ensemble_dir.iterdir() + if d.is_dir() and (d / "sampled_conformations.pdb").exists() + ) + if args.max_systems > 0: + names = names[: args.max_systems] + print(f"[surrogate] {len(names)} systems with generated ensembles", flush=True) + + # The pipeline's own per-system metrics are optional context. The file may be + # a pickle or a CSV regardless of its suffix, and a bad one must not stop the + # study -- the script computes its own metric either way. + pipeline_metrics = {} + if args.metrics_pkl and os.path.exists(args.metrics_pkl): + payload = None + try: + with open(args.metrics_pkl, "rb") as handle: + payload = pickle.load(handle) + print(f"[surrogate] loaded {args.metrics_pkl} as pickle: top-level " + f"type {type(payload).__name__}", flush=True) + except Exception: + try: + import pandas as pd + table = pd.read_csv(args.metrics_pkl) + name_column = next( + (c for c in table.columns + if c.lower() in ("name", "pdb", "pdb_name", "system")), + table.columns[0], + ) + payload = { + str(row[name_column]): { + k: v for k, v in row.items() + if k != name_column and np.isscalar(v) + } + for _, row in table.iterrows() + } + print(f"[surrogate] loaded {args.metrics_pkl} as CSV: " + f"{len(payload)} rows, key column {name_column!r}", + flush=True) + except Exception as exc: # noqa: BLE001 + print(f"[surrogate] could not read {args.metrics_pkl} ({exc}); " + f"continuing with the self-computed metric only", flush=True) + payload = None + if isinstance(payload, dict) and payload: + sample_key = next(iter(payload), None) + print(f"[surrogate] example key={sample_key!r} value type=" + f"{type(payload.get(sample_key)).__name__}", flush=True) + if isinstance(payload.get(sample_key), dict): + print(f"[surrogate] metric names: " + f"{sorted(payload[sample_key])[:12]}", flush=True) + pipeline_metrics = payload + + rows = [] + for index, name in enumerate(names, start=1): + try: + ref_struct, ref_traj = reference_ensemble( + args.md_dir, name, args.ref_frames + ) + if ref_struct is None: + print(f"[{index:3d}/{len(names)}] {name}: no reference, skipped", + flush=True) + continue + model_traj = load_ca( + str(ensemble_dir / name / "sampled_conformations.pdb") + ) + num_res = ref_struct.n_atoms + if model_traj.n_atoms != num_res: + print(f"[{index:3d}/{len(names)}] {name}: residue count " + f"{model_traj.n_atoms} vs {num_res}, skipped", flush=True) + continue + + disp_m = displacement_matrix(model_traj, ref_struct) + disp_r = displacement_matrix(ref_traj, ref_struct) + + eq = np.asarray(ref_struct.xyz[0], dtype=np.float64) * 10.0 + pair = np.linalg.norm(eq[:, None, :] - eq[None, :, :], axis=-1) + far_mask = pair > args.far_distance + if far_mask.sum() < 10: + print(f"[{index:3d}/{len(names)}] {name}: too few long-range " + f"pairs, skipped", flush=True) + continue + + row = {"name": name, "num_res": num_res, + "n_ref_frames": disp_r.shape[0], + "n_model_frames": disp_m.shape[0]} + row.update(candidates(disp_m, disp_r, num_res, far_mask, args.top_k)) + if name in pipeline_metrics: + for key, value in pipeline_metrics[name].items(): + if np.isscalar(value): + row[f"pipeline_{key}"] = float(value) + rows.append(row) + print(f"[{index:3d}/{len(names)}] {name}: N={num_res} " + f"metric={row['METRIC_pca_w2']:.4f} " + f"rho={row['cross_cov_far_corr']:.4f} " + f"log_trace={row['abs_log_trace_ratio']:.4f}", flush=True) + except Exception as exc: # noqa: BLE001 - a bad system must not stop the study + print(f"[{index:3d}/{len(names)}] {name}: FAILED ({exc})", flush=True) + + if len(rows) < 5: + print("[surrogate] too few systems succeeded to correlate anything", + flush=True) + return + + import pandas as pd + frame = pd.DataFrame(rows) + if args.out_csv: + frame.to_csv(args.out_csv, index=False) + print(f"\n[surrogate] per-system table written to {args.out_csv}", + flush=True) + + metric_columns = [c for c in frame.columns + if c.startswith("METRIC_") or c.startswith("pipeline_")] + candidate_columns = [ + c for c in frame.columns + if c not in metric_columns + and c not in ("name", "num_res", "n_ref_frames", "n_model_frames") + ] + + print(f"\n{'=' * 78}") + print(f"Spearman rank correlation across {len(frame)} systems") + print("A usable surrogate needs |rho| well above 0.5 AND the right sign.") + print("Sign convention: METRIC_pca_w2 is an error, so lower is better.") + print(" - an error-like candidate should correlate POSITIVELY") + print(" - a similarity-like candidate (corr, overlap) should correlate NEGATIVELY") + print("=" * 78, flush=True) + + for metric in metric_columns: + target = frame[metric].to_numpy(dtype=float) + if not np.isfinite(target).sum() >= 5: + continue + print(f"\nagainst {metric}:") + scored = [] + for candidate in candidate_columns: + values = frame[candidate].to_numpy(dtype=float) + mask = np.isfinite(values) & np.isfinite(target) + if mask.sum() < 5: + continue + rho, pval = spearmanr(values[mask], target[mask]) + scored.append((abs(rho), rho, pval, int(mask.sum()), candidate)) + scored.sort(reverse=True) + print(f" {'candidate':<26}{'spearman':>10}{'p':>12}{'n':>6}") + print(f" {'-' * 54}") + for _, rho, pval, count, candidate in scored: + print(f" {candidate:<26}{rho:>10.3f}{pval:>12.2e}{count:>6d}", + flush=True) + + print(f"\n{'=' * 78}") + print("Reading this:") + print(" cross_cov_far_corr near zero confirms it was never a surrogate.") + print(" If no candidate exceeds |rho| ~ 0.5, the metric is not determined") + print(" by second moments and no second-moment penalty can control it.") + print("=" * 78, flush=True) + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/tilt_gate.py b/bbflow_base/scripts/tilt_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..ea9c4aa71741f0bd02dbf1d76802a8f22298936f --- /dev/null +++ b/bbflow_base/scripts/tilt_gate.py @@ -0,0 +1,396 @@ +"""Does per-mode conditioning energy have anywhere useful to go? Gate before any sweep. + +`condition_scale` is exhausted: a per-protein oracle over four scales bought +0.0053 +against a scorer SD of 0.046, and the scale minimising PCA-W2 was also best for dispersion +on 0.27 of proteins against 0.25 by chance. One number cannot serve both, so the remaining +freedom is *which* modes carry the conditioning. This decides whether that freedom leads +anywhere, before a single production ensemble is generated. + +What is measured, per protein +----------------------------- + Sigma_0 the empirical covariance of the model's own output under the full generative + process: `c ~ q` and a fresh initial noise for every replica. Anchoring on + this is what makes the surrogate honest -- the output covariance is + `N + J Gamma J^T + D`, and building it from the steerable term alone omits + both the variance the conditioning cannot reach and the nonlinear residual, + either of which can dominate the denominator of the fraction being chased. + J the response of the output to each mode coefficient, by antithetic central + differences about the mixture mean with the initial noise held fixed. + Gamma the coefficient covariance under `q`, full matrix, off-diagonals included. + +Every endpoint is Kabsch-aligned to the equilibrium structure first. The MD modes are +built from aligned frames and the official scorer superposes everything it loads, so +without this both `J` and `Sigma_0` carry rigid-body motion that the 0.268-versus-0.552 +comparison excludes. + +The surrogate +------------- + Sigma_alpha = Sigma_0 + J (Gamma_alpha - Gamma_0) J^T, Gamma_alpha = G Gamma G + +`alpha = 0` reproduces `Sigma_0` exactly, so the baseline is the measured ensemble rather +than a reconstruction. `G` is the gain the sampler will actually apply -- ranked by each +protein's marginal coefficient variance, fixed across its samples, renormalised so +`tr(G Gamma G) == tr(Gamma)` -- so the gate evaluates the same transform the experiment +would run. It assumes only that `N` and `D` do not move with alpha, which is explicit and +true only approximately; that is why a pass licenses a small pilot, not a result. + +Reported: the in-plane fraction `tr(V2^T Sigma_alpha V2) / tr(Sigma_alpha)` against MD's +0.552, and the whole-ensemble trace ratio, which is the check that alpha has not merely +become another amplitude knob after `condition_scale` was exhausted. + +The per-mode efficiency `||V2^T J_k||^2 / ||J_k||^2` is a mechanism diagnostic only. It +ignores response magnitude, cross-terms between the `J_k`, and the off-diagonal structure +of `Gamma`, so it is neither necessary nor sufficient for the tilt to work; the paired +surrogate decides. +""" + +import argparse +import os + +import numpy as np +import torch +from omegaconf import OmegaConf + +from bbflow.data.interpolant_bbflow import InterpolantBBFlow +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb +from bbflow.models.bbflow_module import BBFlowModule +from bbflow.models.collective import mixture_mean_and_covariance + +ALPHAS = (-0.5, -0.25, 0.0, 0.25, 0.5, 1.0) +MD_INPLANE_TARGET = 0.552 + + +def kabsch_align(x, target): + """Align every frame to `target`, matching the scorer and the MD mode construction.""" + t_mu = target.mean(0) + tc = target - t_mu + xc = x - x.mean(1, keepdims=True) + h = np.einsum("fij,ik->fjk", xc, tc) + u, _, vt = np.linalg.svd(h) + sign = np.sign(np.linalg.det(np.einsum("fij,fjk->fik", u, vt))) + u = u.copy() + u[:, :, -1] *= sign[:, None] + r = np.einsum("fij,fjk->fik", u, vt) + return (np.einsum("fij,fjk->fik", xc, r) + t_mu).reshape(len(x), -1) + + +def tilt_gamma(gamma, alpha): + """`G Gamma G` with `tr` preserved -- the exact transform `latent.set_tilt` applies.""" + if alpha == 0.0: + return gamma.copy(), np.ones(gamma.shape[0]) + k = gamma.shape[0] + rank = np.empty(k) + rank[np.argsort(-np.diag(gamma))] = np.arange(1, k + 1) + g = rank ** (-alpha) + t = g[:, None] * gamma * g[None, :] + g = g * np.sqrt(np.trace(gamma) / max(np.trace(t), 1e-30)) + return g[:, None] * gamma * g[None, :], g + + +def _ca(atom37): + last = atom37[-1] if isinstance(atom37, (list, tuple)) else atom37 + if not torch.is_tensor(last): + last = torch.as_tensor(np.asarray(last)) + return last[:, :, 1, :].float().cpu().numpy() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt", required=True) + ap.add_argument("--csv", required=True) + ap.add_argument("--cache", required=True) + ap.add_argument("--num_proteins", type=int, default=12) + ap.add_argument("--batch", type=int, default=4, + help="noise replicas averaged inside each central difference") + ap.add_argument("--baseline_batch", type=int, default=120, + help="full draws for Sigma_0. The in-plane trace has effective rank 2, " + "so its relative error is about sqrt(2/(m-1)): 24 replicas is over " + "20 percent and cannot support a gate") + ap.add_argument("--repeat_seed", action="store_true", + help="recompute J on an independent set of noise draws and report the " + "seed-to-seed spread of the predicted deltas. The two step sizes " + "share their noise, so their agreement tests the step, not the " + "convergence of the noise-averaged response, and J enters the " + "surrogate quadratically") + ap.add_argument("--fd_step", type=float, default=1.0) + ap.add_argument("--fd_check_step", type=float, default=0.5, + help="second, smaller step. A one-sigma difference is a secant, not a " + "derivative; the two must agree or J does not describe the response") + ap.add_argument("--timesteps", type=int, default=20) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--device", default="cuda:0") + ap.add_argument("--out_csv", default="") + args = ap.parse_args() + + ckpt_cfg = OmegaConf.load(os.path.join(os.path.dirname(args.ckpt), "config.yaml")) + cfg = OmegaConf.load("configs/inference.yaml") + OmegaConf.set_struct(cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(cfg, ckpt_cfg) + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.inference.interpolant.sampling.num_timesteps = args.timesteps + cfg.model.embed = ckpt_cfg.model.embed + + print(f"loading {args.ckpt}", flush=True) + module = BBFlowModule(cfg) + state = torch.load(args.ckpt, map_location="cpu")["state_dict"] + cur = module.state_dict() + module.load_state_dict({k: v for k, v in state.items() + if k in cur and cur[k].shape == v.shape}, strict=False) + device = torch.device(args.device) + module = module.to(device).eval() + module.latent_encoder._tilt_gain = None # J is the untilted response + interpolant = InterpolantBBFlow(cfg.inference.interpolant) + interpolant.set_device(device) + + cache = torch.load(args.cache, map_location="cpu", weights_only=False) + if isinstance(cache, dict) and "motion_targets" in cache: + cache = cache["motion_targets"] + + import pandas as pd + csv = pd.read_csv(args.csv).head(args.num_proteins) + dataset = PDBDatasetBBFlowFromPdb(csv, sort=False, min_length=0, max_length=np.inf) + + rows, per_mode = [], [] + for idx in range(len(dataset.pdb_names)): + name = dataset.pdb_names[idx] + entry = cache.get(name) or cache.get(name.replace("_", "")) + if entry is None or "oracle_modes" not in entry: + print(f" {name}: no oracle_modes, skipping", flush=True) + continue + + trans_eq = dataset.trans[idx][None].to(device).float() + rotmats_eq = dataset.rotmats[idx][None].to(device).float() + seq = dataset.seqs[idx][None].to(device).float() + n_res = trans_eq.shape[1] + res_mask = torch.ones(1, n_res, device=device) + eq_ca = trans_eq[0].cpu().numpy() + + with torch.no_grad(): + prior, _ = module.latent_encoder.forward_prior( + trans_eq, rotmats_eq, seq, res_mask) + u_global = prior["u_global"].float() + K = u_global.shape[2] + mu_c, coeff_cov = mixture_mean_and_covariance( + prior["mixture_logits"], prior["mixture_mu"], prior["mixture_scale_tril"]) + gamma = coeff_cov[0].cpu().numpy().astype(float) + mu = mu_c[0] + sigma = torch.diagonal(coeff_cov[0]).clamp_min(1e-12).sqrt() + + def run(coeff, n, seed): + z = module.latent_encoder.condition_from_mode_coefficients( + u_global.expand(n, -1, -1, -1), coeff, + rotmats_eq.expand(n, -1, -1, -1), + torch.ones(n, n_res, device=device), include_statistics=False) + torch.manual_seed(seed) + atom37, _, _ = interpolant.sample( + n, n_res, module.model, trans_eq.expand(n, -1, -1), + rotmats_eq.expand(n, -1, -1, -1), seq.expand(n, -1, -1), + z=z, return_trajectory=False, cache_static_features=True) + return kabsch_align(_ca(atom37), eq_ca) + + # Draw from the ACTUAL mixture, the same way production does: pick a + # component, then that component's Gaussian. A moment-matched single + # Gaussian shares the mean and covariance but not the higher moments, and a + # nonlinear generator can respond differently to them -- the anchor would + # then not be production's baseline at all. + nb = args.baseline_batch + torch.manual_seed(args.seed + 31 * idx) + rep = {k: v.expand(nb, *v.shape[1:]) if torch.is_tensor(v) and v.shape[0] == 1 + else v for k, v in prior.items()} + c_draws, _ = module.latent_encoder.sample_coefficients_from_q(rep) + c_draws = c_draws.to(device).float() + base_pts = run(c_draws, nb, args.seed + 555 + idx) + sig0 = np.cov(base_pts, rowvar=False) + + def jacobian(step, noise_seed): + cols = [] + for k in range(K): + ends = {} + for sgn in (+1.0, -1.0): + c = mu[None].expand(args.batch, -1).clone() + c[:, k] = c[:, k] + sgn * step * sigma[k] + ends[sgn] = run(c, args.batch, noise_seed) + cols.append((ends[+1.0] - ends[-1.0]).mean(0) + / (2.0 * step * sigma[k].item())) + return np.stack(cols, axis=1) + + jacs = {step: jacobian(step, args.seed + 1000 * idx) + for step in (args.fd_step, args.fd_check_step)} + jac = jacs[args.fd_step] + jac_half = jacs[args.fd_check_step] + jac_alt = (jacobian(args.fd_step, args.seed + 90000 + idx) + if args.repeat_seed else None) + + modes = entry["oracle_modes"].float() + v2 = np.linalg.qr( + modes.permute(0, 2, 1).reshape(-1, modes.shape[1]).numpy()[:, :2])[0] + + num = np.square(v2.T @ jac).sum(0) + den = np.square(jac).sum(0).clip(1e-30) + rank = np.empty(K) + rank[np.argsort(-np.diag(gamma))] = np.arange(1, K + 1) + for k in range(K): + per_mode.append({"name": name, "mode": k, "rank": float(rank[k]), + "efficiency": float(num[k] / den[k]), + "sigma2": float(gamma[k, k])}) + + a, b = jacs[args.fd_step], jacs[args.fd_check_step] + cos = float(np.mean([abs(a[:, k] @ b[:, k]) + / max(np.linalg.norm(a[:, k]) * np.linalg.norm(b[:, k]), 1e-30) + for k in range(K)])) + + mu_np = mu.cpu().numpy().astype(float) + sig_np = np.sqrt(np.diag(gamma)).clip(1e-30) + row = {"name": name, "n_res": n_res, "fd_cosine": cos, + "steer_share": float(np.trace(jac @ gamma @ jac.T) + / max(np.trace(sig0), 1e-30))} + for al in ALPHAS: + gam_a, g_a = tilt_gamma(gamma, al) + # The sampler applies c -> G c, so the mean moves to G mu as well. The + # surrogate only models the covariance change; if this displacement is not + # small against the coefficient scale, J and the residual move too and the + # linearisation does not describe the transform. + # Worst standardized mode, not the RMS: one badly displaced mode invalidates + # the linearisation even when the average looks small. + row[f"mushift_a{al}"] = float(np.max(np.abs((g_a - 1.0) * mu_np / sig_np))) + sig = sig0 + jac @ (gam_a - gamma) @ jac.T + tot = float(np.trace(sig)) + row[f"frac_a{al}"] = float(np.trace(v2.T @ sig @ v2) / max(tot, 1e-30)) + row[f"trace_a{al}"] = tot + # Cosine can read 1.0 while the magnitudes differ twofold, and J enters + # quadratically, so compare the predicted deltas themselves. + sh = sig0 + jac_half @ (gam_a - gamma) @ jac_half.T + row[f"frac_half_a{al}"] = float( + np.trace(v2.T @ sh @ v2) / max(np.trace(sh), 1e-30)) + if jac_alt is not None: + s2 = sig0 + jac_alt @ (gam_a - gamma) @ jac_alt.T + row[f"frac_alt_a{al}"] = float( + np.trace(v2.T @ s2 @ v2) / max(np.trace(s2), 1e-30)) + rows.append(row) + print(f" {name:8s} N={n_res:4d} in-plane {row['frac_a0.0']:.4f} " + f"steerable share {row['steer_share']:.3f} fd cos {cos:.3f}", flush=True) + + if not rows: + raise SystemExit("no protein produced a measurement") + df, pm = pd.DataFrame(rows), pd.DataFrame(per_mode) + if args.out_csv: + pm.to_csv(args.out_csv, index=False) + df.to_csv(args.out_csv.replace(".csv", "_proteins.csv"), index=False) + print(f"\nper-mode -> {args.out_csv}", flush=True) + + n = len(df) + rng = np.random.default_rng(0) + bidx = rng.integers(0, n, (4000, n)) + + print(f"\n{'='*72}\n validity of the measurement\n{'='*72}") + print(f" finite-difference cosine, {args.fd_step} vs {args.fd_check_step} sigma: " + f"{df.fd_cosine.median():.3f}") + print(f" below about 0.9 means the step crosses curvature and J is a secant, not") + print(f" the local response the surrogate assumes") + print(f" in-plane fraction at alpha=0: {df['frac_a0.0'].median():.4f}" + f" (production ensembles measure 0.268; MD is {MD_INPLANE_TARGET})") + print(f" steerable share of total variance: {df.steer_share.median():.3f}") + print(f" small means the denominator is dominated by variance no tilt can reach,") + print(f" and that is itself the answer") + + print(f"\n{'='*72}\n surrogate: whole-ensemble in-plane fraction under the tilt" + f"\n{'='*72}") + base = df["frac_a0.0"].to_numpy() + print(f" {'alpha':>7}{'in-plane':>11}{'paired delta':>15}{'95% CI':>22}" + f"{'trace ratio':>13}{'better on':>11}{'mu shift':>10}{'seed spread':>13}" + f"{'step spread':>12}") + nz = [a for a in ALPHAS if a != 0.0] + boots = {} + for al in ALPHAS: + cur_a = df[f"frac_a{al}"].to_numpy() + d = cur_a - base + boots[al] = np.median(d[bidx], axis=1) + lo, hi = np.percentile(boots[al], [2.5, 97.5]) + tr = (df[f"trace_a{al}"] / df["trace_a0.0"]).median() + ms = df[f"mushift_a{al}"].median() if f"mushift_a{al}" in df else float("nan") + sp = (abs(df[f"frac_alt_a{al}"] - df[f"frac_a{al}"]).median() + if f"frac_alt_a{al}" in df else float("nan")) + print(f" {al:>7}{np.median(cur_a):>11.4f}{np.median(d):>+15.4f}" + f"{f'[{lo:+.4f}, {hi:+.4f}]':>22}{tr:>13.3f}{(d > 0).mean():>11.2f}" + f"{ms:>10.3f}{sp:>13.4f}" + f"{abs(df[f'frac_half_a{al}'] - df[f'frac_a{al}']).median():>12.4f}") + # Searching five alphas needs a simultaneous bound, not five marginal ones. + obs = {a: float(np.median(df[f"frac_a{a}"].to_numpy() - base)) for a in nz} + best = max(nz, key=obs.get) + # One-sided simultaneous bound: the max over alphas of the DOWNWARD centered + # deviation. Using upward deviations gives a bound looser than the marginal one, + # which is the opposite of what a search correction must do. + err = np.max(np.stack([obs[a] - boots[a] for a in nz]), axis=0) + slo = obs[best] - np.percentile(err, 97.5) + print(f"\n selected alpha {best}, observed delta {obs[best]:+.4f}") + print(f" simultaneous lower bound over all {len(nz)} non-zero alphas: {slo:+.4f}") + print(f" this is what the search justifies; the per-row CIs above are marginal") + print(f" and are optimistic because the best of five was chosen") + print(f" mu shift is ||(G-1)mu/sigma||/sqrt(K): the tilt moves the mixture mean as") + print(f" well as its covariance, and the surrogate models only the covariance, so") + print(f" a large value means J and the residual move too and the linearisation") + print(f" does not describe the transform") + if any(f"frac_alt_a{a}" in df for a in ALPHAS): + print(f" seed spread is |delta from an independent noise draw for J|; J enters") + print(f" the surrogate quadratically, so this must be small against the deltas") + else: + print(f" seed spread not measured -- pass --repeat_seed before treating any") + print(f" delta as a verdict rather than a smoke test") + + print(f"\n{'='*72}\n mechanism diagnostic, not the gate\n{'='*72}") + from scipy.stats import spearmanr + per = [spearmanr(g["rank"], g["efficiency"]).statistic for _, g in pm.groupby("name")] + per = np.asarray([x for x in per if x == x]) + plo, phi = np.percentile( + np.median(per[rng.integers(0, len(per), (4000, len(per)))], axis=1), [2.5, 97.5]) + print(f" Spearman(variance rank, response efficiency), per protein then bootstrapped") + print(f" median {np.median(per):+.3f} [{plo:+.3f}, {phi:+.3f}]" + f" negative means high-variance modes are the efficient ones") + print(f" clustered by protein rather than pooled over modes, because the mode rows") + print(f" within a protein are not independent observations") + + ms_sel = df[f"mushift_a{best}"].median() + tr_sel = (df[f"trace_a{best}"] / df["trace_a0.0"]).median() + win_sel = float((df[f"frac_a{best}"].to_numpy() - base > 0).mean()) + step_sel = float(abs(df[f"frac_half_a{best}"] - df[f"frac_a{best}"]).median()) + seed_sel = (float(abs(df[f"frac_alt_a{best}"] - df[f"frac_a{best}"]).median()) + if f"frac_alt_a{best}" in df else None) + + print(f"\n{'='*72}\n decision, criteria fixed before the run\n{'='*72}") + checks = [ + ("surrogate valid: worst standardized mean shift below the " + f"{args.fd_step} sigma step", ms_sel < args.fd_step, f"{ms_sel:.3f}"), + ("J is a local response: step spread small against the delta", + step_sel < 0.3 * abs(obs[best]), f"{step_sel:.4f} vs {0.3*abs(obs[best]):.4f}"), + ("J converged: seed spread small against the delta", + (seed_sel is not None and seed_sel < 0.3 * abs(obs[best])), + "not measured, pass --repeat_seed" if seed_sel is None else + f"{seed_sel:.4f} vs {0.3*abs(obs[best]):.4f}"), + ("effect survives the search: simultaneous lower bound above zero", + slo > 0, f"{slo:+.4f}"), + ("effect is material: at least 0.03 (an externally set absolute threshold, " + "not a gap measured here)", obs[best] >= 0.03, f"{obs[best]:+.4f}"), + ("broad: improves a clear majority", win_sel >= 0.6, f"{win_sel:.2f}"), + ("not an amplitude knob: whole-ensemble trace ratio near 1", + 0.95 <= tr_sel <= 1.05, f"{tr_sel:.3f}"), + ] + for label, ok, val in checks: + print(f" [{'PASS' if ok else 'FAIL'}] {label}\n {val}") + if not (ms_sel < args.fd_step): + print(f"\n VERDICT: SURROGATE INVALID at alpha {best} -- the tilt moves the") + print(f" coefficient mean beyond where J was measured, so this is neither a") + print(f" pass nor a fail, it is out of the linearisation's range.") + elif all(ok for _, ok, _ in checks): + print(f"\n VERDICT: proceed to a pilot at alpha {best}.") + else: + print(f"\n VERDICT: do not spend GPU on a pilot.") + print(f"\n These {n} proteins are SELECTION data. Alpha is locked here. The pilot") + print(f" evaluates that locked alpha on untouched proteins with no further alpha") + print(f" choice -- re-selecting there would make those proteins selection data too.") + + +if __name__ == "__main__": + main() diff --git a/bbflow_base/scripts/validate_motion_target_cache.py b/bbflow_base/scripts/validate_motion_target_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..71803d7db9d5600cf076b6fc78ecb2c23a0ada83 --- /dev/null +++ b/bbflow_base/scripts/validate_motion_target_cache.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +"""Validate required fields before launching an expensive training run.""" + +import argparse + +import torch + +from bbflow.data.alignment import ALIGNMENT_VERSION, require_alignment_version + + +def canonical_targets(payload): + if not isinstance(payload, dict) or "motion_targets" not in payload: + raise ValueError("cache must contain a motion_targets mapping") + targets = payload["motion_targets"] + return { + name: target + for name, target in targets.items() + if not ("_" in name and name.replace("_", "") in targets) + } + + +def validate_cache( + path, required_fields, required_alignment_version=ALIGNMENT_VERSION +): + payload = torch.load(path, map_location="cpu", weights_only=False) + if required_alignment_version == ALIGNMENT_VERSION: + require_alignment_version(payload) + elif payload.get("alignment_version") != required_alignment_version: + raise ValueError( + "motion-target cache alignment_version mismatch: " + f"expected {required_alignment_version!r}, " + f"got {payload.get('alignment_version')!r}" + ) + targets = canonical_targets(payload) + if not targets: + raise ValueError("motion-target cache is empty") + + missing = { + name: [field for field in required_fields if field not in target] + for name, target in targets.items() + } + missing = {name: fields for name, fields in missing.items() if fields} + if missing: + preview = ", ".join( + f"{name}: {','.join(fields)}" for name, fields in list(missing.items())[:5] + ) + raise ValueError( + f"motion-target cache is missing required fields for {len(missing)}/{len(targets)} " + f"proteins ({preview})" + ) + return len(targets) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--path", required=True) + parser.add_argument("--require", nargs="+", required=True) + args = parser.parse_args() + count = validate_cache(args.path, args.require) + print(f"[cache-check] OK: {count} proteins contain {', '.join(args.require)}") + + +if __name__ == "__main__": + main()