Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- bbflow_base/code_exports/a30_redesign_source_20260719/base_stages/00_train_final_mog_ddp.sh +228 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/data/interpolant_bbflow.py +312 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/bbflow_model.py +266 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/bbflow_module.py +1923 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/embedder.py +463 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/latent.py +1317 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/configs/experiment/default.yaml +116 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/configs/inference.yaml +93 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/configs/train.yaml +34 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/docs/HANDOFF_2026-07-17.txt +924 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/docs/experiment_trace_2026-07-05.md +1367 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/docs/protein_project_conversation_record_2026-07-13.txt +71 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/experiments/inference.py +171 -0
- bbflow_base/code_exports/a30_redesign_source_20260719/experiments/train.py +180 -0
- bbflow_base/reproduction/00_prepare_data.sh +28 -0
- bbflow_base/reproduction/00_reproduce_official_pretrained.sh +254 -0
- bbflow_base/reproduction/01_download_official.sh +14 -0
- bbflow_base/reproduction/01_train.sh +76 -0
- bbflow_base/reproduction/02_sample_test.sh +55 -0
- bbflow_base/reproduction/03_evaluate.sh +58 -0
- bbflow_base/reproduction/10h_sweep_then_resume.sh +133 -0
- bbflow_base/reproduction/README.md +25 -0
- bbflow_base/reproduction/__pycache__/prepare_atlas_view.cpython-39.pyc +0 -0
- bbflow_base/reproduction/outputs/metrics/compact_metrics.csv +9 -0
- bbflow_base/reproduction/outputs/metrics/summary_metrics.csv +28 -0
- bbflow_base/reproduction/prepare_atlas_view.py +162 -0
- bbflow_base/reproduction/watch_train_then_infer.sh +84 -0
- bbflow_base/scripts/__init__.py +1 -0
- bbflow_base/scripts/__pycache__/__init__.cpython-310.pyc +0 -0
- bbflow_base/scripts/__pycache__/check_directional_condition_equivariance.cpython-39.pyc +0 -0
- bbflow_base/scripts/__pycache__/diagnose_film.cpython-39.pyc +0 -0
- bbflow_base/scripts/__pycache__/diagnose_pca_projection_ceiling.cpython-39.pyc +0 -0
- bbflow_base/scripts/__pycache__/diagnose_z.cpython-311.pyc +0 -0
- bbflow_base/scripts/__pycache__/fit_motion_template_upper_bound.cpython-311.pyc +0 -0
- bbflow_base/scripts/__pycache__/fit_motion_template_upper_bound.cpython-39.pyc +0 -0
- bbflow_base/scripts/__pycache__/probe_condition_ensemble_cov.cpython-39.pyc +0 -0
- bbflow_base/scripts/__pycache__/probe_sample_condition.cpython-39.pyc +0 -0
- bbflow_base/scripts/__pycache__/rescore_pca_w2.cpython-311.pyc +0 -0
- bbflow_base/scripts/__pycache__/spectral_calibration.cpython-310.pyc +0 -0
- bbflow_base/scripts/analysis_script.py +327 -0
- bbflow_base/scripts/analyze_fullcov_pca_contraction.py +150 -0
- bbflow_base/scripts/audit_condition_branch_weights.py +70 -0
- bbflow_base/scripts/audit_condition_forward_paths.py +427 -0
- bbflow_base/scripts/audit_condition_sign_loss.py +295 -0
- bbflow_base/scripts/audit_condition_sign_loss_min.py +377 -0
- bbflow_base/scripts/audit_condition_source_paths.py +265 -0
- bbflow_base/scripts/audit_covariance_transport.py +427 -0
- bbflow_base/scripts/audit_frame_gap_confound.py +160 -0
- bbflow_base/scripts/audit_sign_loss_confound.py +244 -0
- bbflow_base/scripts/audit_sign_loss_vs_response.py +125 -0
bbflow_base/code_exports/a30_redesign_source_20260719/base_stages/00_train_final_mog_ddp.sh
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 5 |
+
BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
| 6 |
+
PROJECT_ROOT="$(cd "${BBFLOW_ROOT}/.." && pwd)"
|
| 7 |
+
cd "${BBFLOW_ROOT}"
|
| 8 |
+
|
| 9 |
+
ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}"
|
| 10 |
+
RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_final_mog_k8_m2_30ep_ddp}"
|
| 11 |
+
GPU_IDS="${GPU_IDS:-0,1,2}"
|
| 12 |
+
NUM_DEVICES="${NUM_DEVICES:-3}"
|
| 13 |
+
|
| 14 |
+
DEFAULT_BASE_CKPT="${BBFLOW_ROOT}/models/bbflow-0.1/bbflow-0.1.ckpt"
|
| 15 |
+
if [[ ! -f "${DEFAULT_BASE_CKPT}" && -f "${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" ]]; then
|
| 16 |
+
DEFAULT_BASE_CKPT="${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt"
|
| 17 |
+
fi
|
| 18 |
+
BASE_CKPT="${BASE_CKPT:-${DEFAULT_BASE_CKPT}}"
|
| 19 |
+
LATENT_DIM="${LATENT_DIM:-16}"
|
| 20 |
+
NUM_MODES="${NUM_MODES:-8}"
|
| 21 |
+
MIXTURE_COMPONENTS="${MIXTURE_COMPONENTS:-2}"
|
| 22 |
+
Q_LSTSQ_RIDGE="${Q_LSTSQ_RIDGE:-1e-4}"
|
| 23 |
+
Q_CHOLESKY_JITTER="${Q_CHOLESKY_JITTER:-1e-4}"
|
| 24 |
+
Q_DETACH_PROJECTION="${Q_DETACH_PROJECTION:-true}"
|
| 25 |
+
Q_DETACH_SHARED_ENCODER="${Q_DETACH_SHARED_ENCODER:-false}"
|
| 26 |
+
ENERGY_FROM_Q="${ENERGY_FROM_Q:-false}"
|
| 27 |
+
ENERGY_FROM_Q_FULL_COV="${ENERGY_FROM_Q_FULL_COV:-false}"
|
| 28 |
+
LAMBDA_MOTION="${LAMBDA_MOTION:-1.0}"
|
| 29 |
+
LAMBDA_Q="${LAMBDA_Q:-1.0}"
|
| 30 |
+
LAMBDA_MODE_ORTH="${LAMBDA_MODE_ORTH:-0.0}"
|
| 31 |
+
LAMBDA_MODE_RECON="${LAMBDA_MODE_RECON:-0.0}"
|
| 32 |
+
LAMBDA_PCA_ALIGN="${LAMBDA_PCA_ALIGN:-0.0}"
|
| 33 |
+
LAMBDA_CONDITION_CYCLE="${LAMBDA_CONDITION_CYCLE:-0.0}"
|
| 34 |
+
PCA_ALIGN_TOP_M="${PCA_ALIGN_TOP_M:-2}"
|
| 35 |
+
MOTION_MESSAGE_PASSING_LAYERS="${MOTION_MESSAGE_PASSING_LAYERS:-4}"
|
| 36 |
+
CROSS_COV_NEAR_DISTANCE="${CROSS_COV_NEAR_DISTANCE:-12.0}"
|
| 37 |
+
TEMPLATE_RESIDUAL_SCALE="${TEMPLATE_RESIDUAL_SCALE:-0.1}"
|
| 38 |
+
TEMPLATE_REMOVE_ROTATION="${TEMPLATE_REMOVE_ROTATION:-true}"
|
| 39 |
+
MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-400000}"
|
| 40 |
+
MAX_BATCH_SIZE="${MAX_BATCH_SIZE:-32}"
|
| 41 |
+
ENSEMBLE_GROUP_SIZE="${ENSEMBLE_GROUP_SIZE:-0}"
|
| 42 |
+
if [[ "${ENSEMBLE_GROUP_SIZE}" -gt 1 ]]; then
|
| 43 |
+
FORCE_GROUPED_BATCH=true
|
| 44 |
+
else
|
| 45 |
+
FORCE_GROUPED_BATCH=false
|
| 46 |
+
fi
|
| 47 |
+
PRECISION="${PRECISION:-bf16-mixed}"
|
| 48 |
+
ACTIVATION_CHECKPOINT="${ACTIVATION_CHECKPOINT:-true}"
|
| 49 |
+
MAX_EPOCHS="${MAX_EPOCHS:-30}"
|
| 50 |
+
MIN_EPOCHS="${MIN_EPOCHS:-1}"
|
| 51 |
+
MAX_STEPS="${MAX_STEPS:--1}"
|
| 52 |
+
TRAINER_PROFILER="${TRAINER_PROFILER:-null}"
|
| 53 |
+
SELF_CONDITION="${SELF_CONDITION:-true}"
|
| 54 |
+
EMBED_SELF_CONDITIONING="${EMBED_SELF_CONDITIONING:-true}"
|
| 55 |
+
if [[ "${EMBED_SELF_CONDITIONING}" != "true" ]]; then
|
| 56 |
+
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
|
| 57 |
+
return 2 2>/dev/null || exit 2
|
| 58 |
+
fi
|
| 59 |
+
DIAGNOSTIC_INTERVAL_STEPS="${DIAGNOSTIC_INTERVAL_STEPS:-50}"
|
| 60 |
+
TRACK_CONDITION_DEBUG="${TRACK_CONDITION_DEBUG:-false}"
|
| 61 |
+
EPOCH_CONDITION_PROBE="${EPOCH_CONDITION_PROBE:-false}"
|
| 62 |
+
LOG_EVERY_N_STEPS="${LOG_EVERY_N_STEPS:-50}"
|
| 63 |
+
VALID_SAMPLES_PER_PROTEIN="${VALID_SAMPLES_PER_PROTEIN:-6}"
|
| 64 |
+
CHECKPOINT_EVERY_N_EPOCHS="${CHECKPOINT_EVERY_N_EPOCHS:-1}"
|
| 65 |
+
CHECKPOINT_SAVE_LAST="${CHECKPOINT_SAVE_LAST:-true}"
|
| 66 |
+
CHECKPOINT_SAVE_TOP_K="${CHECKPOINT_SAVE_TOP_K:--1}"
|
| 67 |
+
RESET_EPOCH="${RESET_EPOCH:-false}"
|
| 68 |
+
RESET_OPTIMIZER_ON_LOAD="${RESET_OPTIMIZER_ON_LOAD:-false}"
|
| 69 |
+
LAMBDA_GENERATOR_COV="${LAMBDA_GENERATOR_COV:-0.0}"
|
| 70 |
+
GENERATOR_COV_USE_CROSS="${GENERATOR_COV_USE_CROSS:-false}"
|
| 71 |
+
FREEZE_FOUNDATION="${FREEZE_FOUNDATION:-false}"
|
| 72 |
+
GENERATOR_COV_T_MIN="${GENERATOR_COV_T_MIN:-0.1}"
|
| 73 |
+
GENERATOR_COV_T_MAX="${GENERATOR_COV_T_MAX:-0.6}"
|
| 74 |
+
GENERATOR_COV_DELTA_SCALE="${GENERATOR_COV_DELTA_SCALE:-1.0}"
|
| 75 |
+
GENERATOR_COV_NUM_DELTAS="${GENERATOR_COV_NUM_DELTAS:-2}"
|
| 76 |
+
GENERATOR_COV_STUDENT_CHUNK_DELTAS="${GENERATOR_COV_STUDENT_CHUNK_DELTAS:-1}"
|
| 77 |
+
GENERATOR_COV_TEACHER_NUM_DELTAS="${GENERATOR_COV_TEACHER_NUM_DELTAS:-1}"
|
| 78 |
+
GENERATOR_COV_TEACHER_REUSE_STUDENT_DELTA="${GENERATOR_COV_TEACHER_REUSE_STUDENT_DELTA:-true}"
|
| 79 |
+
GENERATOR_COV_TEACHER_TRACE_DENOMINATOR="${GENERATOR_COV_TEACHER_TRACE_DENOMINATOR:-teacher}"
|
| 80 |
+
GENERATOR_COV_CHECKPOINT="${GENERATOR_COV_CHECKPOINT:-false}"
|
| 81 |
+
GENERATOR_COV_INITIAL_TRACE_ANCHOR="${GENERATOR_COV_INITIAL_TRACE_ANCHOR:-true}"
|
| 82 |
+
GENERATOR_COV_AMPLITUDE_ANCHOR="${GENERATOR_COV_AMPLITUDE_ANCHOR:-md_trace}"
|
| 83 |
+
GENERATOR_COV_ROLLOUT_CALIBRATION="${GENERATOR_COV_ROLLOUT_CALIBRATION:-false}"
|
| 84 |
+
GENERATOR_COV_ROLLOUT_STEPS="${GENERATOR_COV_ROLLOUT_STEPS:-2}"
|
| 85 |
+
GENERATOR_COV_ROLLOUT_NUM_DELTAS="${GENERATOR_COV_ROLLOUT_NUM_DELTAS:-1}"
|
| 86 |
+
GENERATOR_COV_ROLLOUT_MAX_EXAMPLES="${GENERATOR_COV_ROLLOUT_MAX_EXAMPLES:-4}"
|
| 87 |
+
GENERATOR_COV_ROLLOUT_INTERVAL_STEPS="${GENERATOR_COV_ROLLOUT_INTERVAL_STEPS:-200}"
|
| 88 |
+
GENERATOR_COV_ROLLOUT_EMA_DECAY="${GENERATOR_COV_ROLLOUT_EMA_DECAY:-0.9}"
|
| 89 |
+
LAMBDA_GEN_LOCAL_SHAPE="${LAMBDA_GEN_LOCAL_SHAPE:-1.0}"
|
| 90 |
+
LAMBDA_GEN_CROSS_SHAPE="${LAMBDA_GEN_CROSS_SHAPE:-1.0}"
|
| 91 |
+
LAMBDA_GEN_TRACE_ANCHOR="${LAMBDA_GEN_TRACE_ANCHOR:-0.05}"
|
| 92 |
+
FINGERPRINT_CACHE="${FINGERPRINT_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k${NUM_MODES}.pt}"
|
| 93 |
+
EXTRA_HYDRA_ARGS="${EXTRA_HYDRA_ARGS:-}"
|
| 94 |
+
|
| 95 |
+
TRAIN_CSV="${TRAIN_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/train/ATLAS_train.csv}"
|
| 96 |
+
VAL_CSV="${VAL_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/validation/ATLAS_validation.csv}"
|
| 97 |
+
TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}"
|
| 98 |
+
ATLAS_DATASET_DIR="${ATLAS_DATASET_DIR:-${ATLAS_REPRO_ROOT}/datasets/ATLAS}"
|
| 99 |
+
|
| 100 |
+
mkdir -p "${RUN_DIR}"
|
| 101 |
+
|
| 102 |
+
CACHE_REQUIRE_FIELDS=(local_cov cross_cov rmsf oracle_mean_disp)
|
| 103 |
+
if [[ "${LAMBDA_PCA_ALIGN}" != "0" && "${LAMBDA_PCA_ALIGN}" != "0.0" ]]; then
|
| 104 |
+
CACHE_REQUIRE_FIELDS+=(oracle_modes oracle_energy)
|
| 105 |
+
fi
|
| 106 |
+
|
| 107 |
+
python scripts/validate_motion_target_cache.py \
|
| 108 |
+
--path "${FINGERPRINT_CACHE}" \
|
| 109 |
+
--require "${CACHE_REQUIRE_FIELDS[@]}"
|
| 110 |
+
|
| 111 |
+
echo "[base:00] Train final MoG per-conformation BBFlow"
|
| 112 |
+
echo " RUN_DIR=${RUN_DIR}"
|
| 113 |
+
echo " GPU_IDS=${GPU_IDS} NUM_DEVICES=${NUM_DEVICES} MAX_EPOCHS=${MAX_EPOCHS} VALID_SAMPLES_PER_PROTEIN=${VALID_SAMPLES_PER_PROTEIN}"
|
| 114 |
+
echo " BASE_CKPT=${BASE_CKPT}"
|
| 115 |
+
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}"
|
| 116 |
+
echo " ENERGY_FROM_Q=${ENERGY_FROM_Q} ENERGY_FROM_Q_FULL_COV=${ENERGY_FROM_Q_FULL_COV}"
|
| 117 |
+
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}"
|
| 118 |
+
echo " GROUPED_BATCH=${FORCE_GROUPED_BATCH} ENSEMBLE_GROUP_SIZE=${ENSEMBLE_GROUP_SIZE}"
|
| 119 |
+
echo " CHECKPOINT_EVERY_N_EPOCHS=${CHECKPOINT_EVERY_N_EPOCHS} CHECKPOINT_SAVE_LAST=${CHECKPOINT_SAVE_LAST} CHECKPOINT_SAVE_TOP_K=${CHECKPOINT_SAVE_TOP_K}"
|
| 120 |
+
echo " RESET_EPOCH=${RESET_EPOCH} RESET_OPTIMIZER_ON_LOAD=${RESET_OPTIMIZER_ON_LOAD}"
|
| 121 |
+
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}"
|
| 122 |
+
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}"
|
| 123 |
+
echo " TRAIN: c*=lstsq(U, Kabsch(x_t,x_eq)-x_eq); INFER: c~q(c|x_eq)"
|
| 124 |
+
echo " INJECT_EMBEDDER=true INJECT_FILM=true SAMPLE_COEFFICIENTS=true FREEZE_FOUNDATION=${FREEZE_FOUNDATION}"
|
| 125 |
+
|
| 126 |
+
CUDA_VISIBLE_DEVICES="${GPU_IDS}" python experiments/train.py \
|
| 127 |
+
latent.enable=true \
|
| 128 |
+
latent.dim="${LATENT_DIM}" \
|
| 129 |
+
latent.num_modes="${NUM_MODES}" \
|
| 130 |
+
+latent.mixture_components="${MIXTURE_COMPONENTS}" \
|
| 131 |
+
+latent.q_lstsq_ridge="${Q_LSTSQ_RIDGE}" \
|
| 132 |
+
+latent.q_cholesky_jitter="${Q_CHOLESKY_JITTER}" \
|
| 133 |
+
+latent.q_detach_projection="${Q_DETACH_PROJECTION}" \
|
| 134 |
+
+latent.q_detach_shared_encoder="${Q_DETACH_SHARED_ENCODER}" \
|
| 135 |
+
+latent.energy_from_q="${ENERGY_FROM_Q}" \
|
| 136 |
+
+latent.energy_from_q_full_cov="${ENERGY_FROM_Q_FULL_COV}" \
|
| 137 |
+
+latent.sample_coefficients=true \
|
| 138 |
+
latent.motion_message_passing_layers="${MOTION_MESSAGE_PASSING_LAYERS}" \
|
| 139 |
+
latent.cross_cov_near_distance="${CROSS_COV_NEAR_DISTANCE}" \
|
| 140 |
+
+latent.pca_align_top_m="${PCA_ALIGN_TOP_M}" \
|
| 141 |
+
latent.template_residual_scale="${TEMPLATE_RESIDUAL_SCALE}" \
|
| 142 |
+
latent.template_remove_rotation="${TEMPLATE_REMOVE_ROTATION}" \
|
| 143 |
+
latent.node_cond_dim="${NUM_MODES}" \
|
| 144 |
+
latent.edge_cond_dim="${NUM_MODES}" \
|
| 145 |
+
latent.freeze_foundation="${FREEZE_FOUNDATION}" \
|
| 146 |
+
latent.inject_embedder=true \
|
| 147 |
+
latent.inject_film=true \
|
| 148 |
+
latent.activation_checkpoint="${ACTIVATION_CHECKPOINT}" \
|
| 149 |
+
latent.track_condition_debug="${TRACK_CONDITION_DEBUG}" \
|
| 150 |
+
model.embed.embed_self_conditioning="${EMBED_SELF_CONDITIONING}" \
|
| 151 |
+
interpolant.self_condition="${SELF_CONDITION}" \
|
| 152 |
+
latent.shape_fingerprint_k=5 \
|
| 153 |
+
latent.shape_fingerprint_cache_path="${FINGERPRINT_CACHE}" \
|
| 154 |
+
latent.motion_target_cache_path="${FINGERPRINT_CACHE}" \
|
| 155 |
+
latent.z_stochastic=false \
|
| 156 |
+
experiment.num_devices="${NUM_DEVICES}" \
|
| 157 |
+
experiment.training.force_grouped_batch="${FORCE_GROUPED_BATCH}" \
|
| 158 |
+
experiment.training.ensemble_group_size="${ENSEMBLE_GROUP_SIZE}" \
|
| 159 |
+
+experiment.training.per_frame_coeff_condition=true \
|
| 160 |
+
experiment.training.lambda_shape=1.0 \
|
| 161 |
+
+experiment.training.lambda_motion="${LAMBDA_MOTION}" \
|
| 162 |
+
+experiment.training.lambda_q="${LAMBDA_Q}" \
|
| 163 |
+
+experiment.training.lambda_mode_orth="${LAMBDA_MODE_ORTH}" \
|
| 164 |
+
experiment.training.lambda_mode_recon="${LAMBDA_MODE_RECON}" \
|
| 165 |
+
+experiment.training.lambda_pca_align="${LAMBDA_PCA_ALIGN}" \
|
| 166 |
+
+experiment.training.lambda_condition_cycle="${LAMBDA_CONDITION_CYCLE}" \
|
| 167 |
+
experiment.training.lambda_local_cov=1.0 \
|
| 168 |
+
experiment.training.lambda_cross_cov=1.0 \
|
| 169 |
+
experiment.training.lambda_rmsf=0.25 \
|
| 170 |
+
experiment.training.enm_warmup_epochs=0 \
|
| 171 |
+
+experiment.training.oracle_condition=false \
|
| 172 |
+
+experiment.training.grad_flow_check=true \
|
| 173 |
+
+experiment.training.log_optimizer_coverage=true \
|
| 174 |
+
experiment.training.epoch_condition_probe="${EPOCH_CONDITION_PROBE}" \
|
| 175 |
+
experiment.training.lambda_generator_cov="${LAMBDA_GENERATOR_COV}" \
|
| 176 |
+
experiment.training.generator_cov_use_cross="${GENERATOR_COV_USE_CROSS}" \
|
| 177 |
+
experiment.training.generator_cov_t_min="${GENERATOR_COV_T_MIN}" \
|
| 178 |
+
experiment.training.generator_cov_t_max="${GENERATOR_COV_T_MAX}" \
|
| 179 |
+
experiment.training.generator_cov_delta_scale="${GENERATOR_COV_DELTA_SCALE}" \
|
| 180 |
+
experiment.training.generator_cov_num_deltas="${GENERATOR_COV_NUM_DELTAS}" \
|
| 181 |
+
experiment.training.generator_cov_student_chunk_deltas="${GENERATOR_COV_STUDENT_CHUNK_DELTAS}" \
|
| 182 |
+
experiment.training.generator_cov_teacher_num_deltas="${GENERATOR_COV_TEACHER_NUM_DELTAS}" \
|
| 183 |
+
experiment.training.generator_cov_teacher_reuse_student_delta="${GENERATOR_COV_TEACHER_REUSE_STUDENT_DELTA}" \
|
| 184 |
+
experiment.training.generator_cov_teacher_trace_denominator="${GENERATOR_COV_TEACHER_TRACE_DENOMINATOR}" \
|
| 185 |
+
experiment.training.generator_cov_checkpoint="${GENERATOR_COV_CHECKPOINT}" \
|
| 186 |
+
experiment.training.generator_cov_initial_trace_anchor="${GENERATOR_COV_INITIAL_TRACE_ANCHOR}" \
|
| 187 |
+
experiment.training.generator_cov_amplitude_anchor="${GENERATOR_COV_AMPLITUDE_ANCHOR}" \
|
| 188 |
+
experiment.training.generator_cov_rollout_calibration="${GENERATOR_COV_ROLLOUT_CALIBRATION}" \
|
| 189 |
+
experiment.training.generator_cov_rollout_steps="${GENERATOR_COV_ROLLOUT_STEPS}" \
|
| 190 |
+
experiment.training.generator_cov_rollout_num_deltas="${GENERATOR_COV_ROLLOUT_NUM_DELTAS}" \
|
| 191 |
+
experiment.training.generator_cov_rollout_max_examples="${GENERATOR_COV_ROLLOUT_MAX_EXAMPLES}" \
|
| 192 |
+
experiment.training.generator_cov_rollout_interval_steps="${GENERATOR_COV_ROLLOUT_INTERVAL_STEPS}" \
|
| 193 |
+
experiment.training.generator_cov_rollout_ema_decay="${GENERATOR_COV_ROLLOUT_EMA_DECAY}" \
|
| 194 |
+
experiment.training.lambda_gen_local_shape="${LAMBDA_GEN_LOCAL_SHAPE}" \
|
| 195 |
+
experiment.training.lambda_gen_cross_shape="${LAMBDA_GEN_CROSS_SHAPE}" \
|
| 196 |
+
experiment.training.lambda_gen_trace_anchor="${LAMBDA_GEN_TRACE_ANCHOR}" \
|
| 197 |
+
data.sampler.max_num_res_squared="${MAX_NUM_RES_SQUARED}" \
|
| 198 |
+
data.sampler.max_batch_size="${MAX_BATCH_SIZE}" \
|
| 199 |
+
experiment.trainer.precision="${PRECISION}" \
|
| 200 |
+
experiment.trainer.default_root_dir="${RUN_DIR}" \
|
| 201 |
+
experiment.trainer.log_every_n_steps="${LOG_EVERY_N_STEPS}" \
|
| 202 |
+
experiment.use_wandb=false \
|
| 203 |
+
experiment.warm_start="${BASE_CKPT}" \
|
| 204 |
+
experiment.warm_start_cfg_override=false \
|
| 205 |
+
experiment.reset_epoch="${RESET_EPOCH}" \
|
| 206 |
+
experiment.reset_optimizer_on_load="${RESET_OPTIMIZER_ON_LOAD}" \
|
| 207 |
+
experiment.wandb.name="$(basename "${RUN_DIR}")" \
|
| 208 |
+
experiment.trainer.max_epochs="${MAX_EPOCHS}" \
|
| 209 |
+
experiment.trainer.min_epochs="${MIN_EPOCHS}" \
|
| 210 |
+
+experiment.trainer.max_steps="${MAX_STEPS}" \
|
| 211 |
+
+experiment.trainer.profiler="${TRAINER_PROFILER}" \
|
| 212 |
+
experiment.training.diagnostic_interval_steps="${DIAGNOSTIC_INTERVAL_STEPS}" \
|
| 213 |
+
data.validation.samples_per_valid_protein="${VALID_SAMPLES_PER_PROTEIN}" \
|
| 214 |
+
+experiment.trainer.num_sanity_val_steps=0 \
|
| 215 |
+
experiment.first_val_epoch=inf \
|
| 216 |
+
experiment.checkpointer.dirpath="${RUN_DIR}" \
|
| 217 |
+
experiment.checkpointer.every_n_epochs="${CHECKPOINT_EVERY_N_EPOCHS}" \
|
| 218 |
+
experiment.checkpointer.save_last="${CHECKPOINT_SAVE_LAST}" \
|
| 219 |
+
experiment.checkpointer.save_top_k="${CHECKPOINT_SAVE_TOP_K}" \
|
| 220 |
+
data.dataset.train_csv_path="${TRAIN_CSV}" \
|
| 221 |
+
"data.dataset.valid_csv_paths=[${VAL_CSV}]" \
|
| 222 |
+
"data.dataset.valid_dataset_names=[ATLAS_validation]" \
|
| 223 |
+
data.dataset.test_csv_path="${TEST_CSV}" \
|
| 224 |
+
data.dataset.split_path="${RUN_DIR}" \
|
| 225 |
+
"data.validation.valid_xtc_paths=[${ATLAS_DATASET_DIR}]" \
|
| 226 |
+
${EXTRA_HYDRA_ARGS}
|
| 227 |
+
|
| 228 |
+
echo "[base:00] Latent metrics: ${RUN_DIR}/latent_train_epoch_metrics.csv"
|
bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/data/interpolant_bbflow.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 Max Planck Institute for Polymer Research
|
| 2 |
+
# Copyright (c) 2024 HITS gGmbH
|
| 3 |
+
# Copyright (c) Microsoft Corporation.
|
| 4 |
+
# Licensed under the MIT license.
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import numpy as np
|
| 8 |
+
from scipy.spatial.transform import Rotation
|
| 9 |
+
import os
|
| 10 |
+
import contextlib
|
| 11 |
+
from scipy.optimize import linear_sum_assignment
|
| 12 |
+
from sklearn.metrics import pairwise_distances
|
| 13 |
+
from tqdm.auto import tqdm
|
| 14 |
+
import pandas as pd
|
| 15 |
+
import logging
|
| 16 |
+
from torch.utils.data.distributed import dist
|
| 17 |
+
|
| 18 |
+
from gafl.data import so3_utils
|
| 19 |
+
from gafl.data import utils as du
|
| 20 |
+
from gafl.data import all_atom
|
| 21 |
+
from gafl.data.interpolant import (
|
| 22 |
+
Interpolant,
|
| 23 |
+
_centered_gaussian,
|
| 24 |
+
_uniform_so3,
|
| 25 |
+
_trans_diffuse_mask,
|
| 26 |
+
_rots_diffuse_mask
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class InterpolantBBFlow(Interpolant):
|
| 31 |
+
|
| 32 |
+
def __init__(self, cfg):
|
| 33 |
+
self._cfg = cfg
|
| 34 |
+
self._rots_cfg = cfg.rots
|
| 35 |
+
self._trans_cfg = cfg.trans
|
| 36 |
+
self._sample_cfg = cfg.sampling
|
| 37 |
+
self._rot_distribution = self._rots_cfg.distribution
|
| 38 |
+
self._igso3 = None
|
| 39 |
+
self._log = logging.getLogger(__name__)
|
| 40 |
+
|
| 41 |
+
super().__init__(cfg)
|
| 42 |
+
|
| 43 |
+
def _fp32_linalg_context(self):
|
| 44 |
+
device_type = getattr(getattr(self, "_device", None), "type", None)
|
| 45 |
+
if device_type == "cuda":
|
| 46 |
+
return torch.autocast(device_type="cuda", enabled=False)
|
| 47 |
+
return contextlib.nullcontext()
|
| 48 |
+
|
| 49 |
+
def _intra_batch_ot(self, trans_1, trans_0, t, res_mask):
|
| 50 |
+
B, N = trans_0.shape[:2]
|
| 51 |
+
|
| 52 |
+
if self._cfg.batch_ot == "intra_permute":
|
| 53 |
+
|
| 54 |
+
trans_0_ordered = torch.zeros_like(trans_0)
|
| 55 |
+
for b in range(B):
|
| 56 |
+
cost_matrix_x = pairwise_distances(
|
| 57 |
+
trans_1[b].numpy(force=True),
|
| 58 |
+
trans_0[b].numpy(force=True)
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
cost_matrix = cost_matrix_x #+ cost_matrix_r
|
| 62 |
+
_, col_ind = linear_sum_assignment(cost_matrix)
|
| 63 |
+
|
| 64 |
+
aligned_0, _, _ = du.batch_align_structures(
|
| 65 |
+
trans_0[b].clone()[col_ind].unsqueeze(0),
|
| 66 |
+
trans_1[b].unsqueeze(0)
|
| 67 |
+
)
|
| 68 |
+
trans_0_ordered[b] = aligned_0[0]
|
| 69 |
+
|
| 70 |
+
return trans_0_ordered
|
| 71 |
+
else:
|
| 72 |
+
trans_0, trans_1, _ = du.batch_align_structures(
|
| 73 |
+
trans_0, trans_1, mask=res_mask
|
| 74 |
+
)
|
| 75 |
+
return trans_0
|
| 76 |
+
|
| 77 |
+
def _corrupt_trans(self, trans_1, trans_0, t, res_mask):
|
| 78 |
+
|
| 79 |
+
if self._cfg.batch_ot == "inter":
|
| 80 |
+
trans_0 = self._batch_ot(trans_0, trans_1, res_mask)
|
| 81 |
+
elif self._cfg.batch_ot in ["intra", "intra_permute"]:
|
| 82 |
+
trans_0 = self._intra_batch_ot(trans_1, trans_0, t, res_mask)
|
| 83 |
+
elif self._cfg.batch_ot == "none":
|
| 84 |
+
pass
|
| 85 |
+
else:
|
| 86 |
+
raise ValueError(f'Unknown batch ot type {self._cfg.batch_ot}')
|
| 87 |
+
trans_t = (1 - t[..., None]) * trans_0 + t[..., None] * trans_1
|
| 88 |
+
trans_t = _trans_diffuse_mask(trans_t, trans_1, res_mask)
|
| 89 |
+
|
| 90 |
+
return trans_t * res_mask[..., None]
|
| 91 |
+
|
| 92 |
+
def _corrupt_rotmats(self, rotmats_1, rotmats_0, t, res_mask):
|
| 93 |
+
rotmats_t = so3_utils.geodesic_t(t[..., None], rotmats_1, rotmats_0)
|
| 94 |
+
identity = torch.eye(3, device=self._device)
|
| 95 |
+
rotmats_t = (
|
| 96 |
+
rotmats_t * res_mask[..., None, None]
|
| 97 |
+
+ identity[None, None] * (1 - res_mask[..., None, None])
|
| 98 |
+
)
|
| 99 |
+
return _rots_diffuse_mask(rotmats_t, rotmats_1, res_mask)
|
| 100 |
+
|
| 101 |
+
def corrupt_batch(self, batch, t=None):
|
| 102 |
+
noisy_batch = dict(batch)
|
| 103 |
+
|
| 104 |
+
trans_equilibrium = batch["trans_equilibrium"].float()
|
| 105 |
+
rotmats_equilibrium = batch["rotmats_equilibrium"].float()
|
| 106 |
+
B, N = trans_equilibrium.shape[:2]
|
| 107 |
+
with self._fp32_linalg_context():
|
| 108 |
+
trans_0, rotmats_0 = self.sample_from_prior(
|
| 109 |
+
B, N,
|
| 110 |
+
trans_equilibrium,
|
| 111 |
+
rotmats_equilibrium,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
if t is None:
|
| 115 |
+
# [B, 1]
|
| 116 |
+
t = self.sample_t(B)[:, None]
|
| 117 |
+
t = t.float()
|
| 118 |
+
|
| 119 |
+
# [B, N, 3]
|
| 120 |
+
trans_1 = batch['trans_1'].float() # Angstrom
|
| 121 |
+
|
| 122 |
+
# [B, N, 3, 3]
|
| 123 |
+
rotmats_1 = batch['rotmats_1'].float()
|
| 124 |
+
|
| 125 |
+
# [B, N]
|
| 126 |
+
res_mask = batch['res_mask'].float()
|
| 127 |
+
|
| 128 |
+
# Apply corruptions
|
| 129 |
+
trans_t = self._corrupt_trans(trans_1, trans_0, t, res_mask)
|
| 130 |
+
rotmats_t = self._corrupt_rotmats(rotmats_1, rotmats_0, t, res_mask)
|
| 131 |
+
|
| 132 |
+
noisy_batch['t'] = t
|
| 133 |
+
noisy_batch['trans_t'] = trans_t
|
| 134 |
+
noisy_batch['rotmats_t'] = rotmats_t
|
| 135 |
+
return noisy_batch
|
| 136 |
+
|
| 137 |
+
def _pure_noise_prior(self, num_batch, num_res, rotmats_1):
|
| 138 |
+
trans_nm_0 = _centered_gaussian(num_batch, num_res, self._device)
|
| 139 |
+
trans_0 = trans_nm_0 * du.NM_TO_ANG_SCALE
|
| 140 |
+
trans_0 *= self.noise_scale
|
| 141 |
+
|
| 142 |
+
# make the noise blob larger the longer the protein is:
|
| 143 |
+
if self.noise_res_scaling_power > 0:
|
| 144 |
+
trans_0 *= (trans_0.shape[1] / 128.)**self.noise_res_scaling_power
|
| 145 |
+
|
| 146 |
+
if self._rot_distribution == 'uniform':
|
| 147 |
+
rotmats_0 = _uniform_so3(num_batch, num_res, self._device)
|
| 148 |
+
elif self._rot_distribution == 'igso3':
|
| 149 |
+
noisy_rotmats = self.igso3.sample(
|
| 150 |
+
torch.tensor([1.5]),
|
| 151 |
+
num_batch*num_res
|
| 152 |
+
).to(self._device)
|
| 153 |
+
noisy_rotmats = noisy_rotmats.reshape(num_batch, num_res, 3, 3)
|
| 154 |
+
rotmats_0 = torch.einsum("...ij,...jk->...ik", rotmats_1, noisy_rotmats)
|
| 155 |
+
else:
|
| 156 |
+
raise ValueError(f'Unknown SO(3) distribution {self._rot_distribution}')
|
| 157 |
+
|
| 158 |
+
return trans_0, rotmats_0
|
| 159 |
+
|
| 160 |
+
def _conditional_prior(self, num_batch, num_res, trans_equilibrium, rotmats_equilibrium):
|
| 161 |
+
res_mask = torch.ones(num_batch, num_res, device=self._device)
|
| 162 |
+
trans_equilibrium = trans_equilibrium.float()
|
| 163 |
+
rotmats_equilibrium = rotmats_equilibrium.float()
|
| 164 |
+
trans_0, rotmats_0 = self._pure_noise_prior(num_batch, num_res, rotmats_equilibrium)
|
| 165 |
+
|
| 166 |
+
trans_0 = self._corrupt_trans(
|
| 167 |
+
trans_equilibrium,
|
| 168 |
+
trans_0,
|
| 169 |
+
self._cfg.prior_conditional.gamma_trans * torch.ones(num_batch, 1, device=self._device, dtype=torch.float32),
|
| 170 |
+
res_mask
|
| 171 |
+
)
|
| 172 |
+
rotmats_0 = self._corrupt_rotmats(
|
| 173 |
+
rotmats_equilibrium,
|
| 174 |
+
rotmats_0,
|
| 175 |
+
self._cfg.prior_conditional.gamma_rots * torch.ones(num_batch, 1, device=self._device, dtype=torch.float32),
|
| 176 |
+
res_mask
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
return trans_0, rotmats_0
|
| 180 |
+
|
| 181 |
+
def sample_from_prior(
|
| 182 |
+
self,
|
| 183 |
+
num_batch,
|
| 184 |
+
num_res,
|
| 185 |
+
trans_equilibrium,
|
| 186 |
+
rotmats_equilibrium,
|
| 187 |
+
):
|
| 188 |
+
|
| 189 |
+
prior_type = self._cfg.prior
|
| 190 |
+
|
| 191 |
+
if prior_type == 'conditional':
|
| 192 |
+
with self._fp32_linalg_context():
|
| 193 |
+
return self._conditional_prior(
|
| 194 |
+
num_batch, num_res, trans_equilibrium, rotmats_equilibrium
|
| 195 |
+
)
|
| 196 |
+
elif prior_type == 'pure_noise':
|
| 197 |
+
return self._pure_noise_prior(num_batch, num_res, rotmats_equilibrium)
|
| 198 |
+
|
| 199 |
+
else:
|
| 200 |
+
raise ValueError(f'Unknown prior type {prior_type}')
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def sample(
|
| 204 |
+
self,
|
| 205 |
+
num_batch,
|
| 206 |
+
num_res,
|
| 207 |
+
model,
|
| 208 |
+
trans_equilibrium,
|
| 209 |
+
rotmats_equilibrium,
|
| 210 |
+
seq,
|
| 211 |
+
z=None,
|
| 212 |
+
return_trajectory=True,
|
| 213 |
+
cache_static_features=True,
|
| 214 |
+
):
|
| 215 |
+
|
| 216 |
+
res_mask = torch.ones(num_batch, num_res, device=self._device)
|
| 217 |
+
|
| 218 |
+
# Set-up initial prior samples
|
| 219 |
+
trans_0, rotmats_0 = self.sample_from_prior(
|
| 220 |
+
num_batch, num_res, trans_equilibrium, rotmats_equilibrium
|
| 221 |
+
)
|
| 222 |
+
batch = {
|
| 223 |
+
"res_mask": res_mask,
|
| 224 |
+
"trans_equilibrium": trans_equilibrium,
|
| 225 |
+
"rotmats_equilibrium": rotmats_equilibrium,
|
| 226 |
+
"seq": seq,
|
| 227 |
+
}
|
| 228 |
+
if z is not None:
|
| 229 |
+
batch["z"] = z
|
| 230 |
+
if cache_static_features and hasattr(model, "prepare_inference_static"):
|
| 231 |
+
batch["_embedder_static"] = model.prepare_inference_static(batch)
|
| 232 |
+
|
| 233 |
+
# Set-up time
|
| 234 |
+
ts = torch.linspace(
|
| 235 |
+
self._cfg.min_t, 1.0, self._sample_cfg.num_timesteps)
|
| 236 |
+
t_1 = ts[0]
|
| 237 |
+
|
| 238 |
+
prot_traj = [(trans_0, rotmats_0)] if return_trajectory else None
|
| 239 |
+
clean_traj = []
|
| 240 |
+
trans_current, rotmats_current = trans_0, rotmats_0
|
| 241 |
+
if self._cfg.use_tqdm:
|
| 242 |
+
iterator = tqdm(
|
| 243 |
+
ts[1:],
|
| 244 |
+
leave=False,
|
| 245 |
+
desc=f'Sampl. {num_batch} states, len {num_res}, rank {dist.get_rank()} - timesteps'
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
else:
|
| 249 |
+
iterator = ts[1:]
|
| 250 |
+
for t_2 in iterator:
|
| 251 |
+
|
| 252 |
+
# Run model.
|
| 253 |
+
trans_t_1, rotmats_t_1 = trans_current, rotmats_current
|
| 254 |
+
t = torch.ones((num_batch, 1), device=self._device) * t_1
|
| 255 |
+
batch['trans_t'] = trans_t_1
|
| 256 |
+
batch['rotmats_t'] = rotmats_t_1
|
| 257 |
+
batch['t'] = t
|
| 258 |
+
with torch.no_grad():
|
| 259 |
+
model_out = model(batch)
|
| 260 |
+
# Process model output.
|
| 261 |
+
pred_trans_1 = model_out['pred_trans']
|
| 262 |
+
pred_rotmats_1 = model_out['pred_rotmats']
|
| 263 |
+
if return_trajectory:
|
| 264 |
+
clean_traj.append(
|
| 265 |
+
(pred_trans_1.detach().cpu(), pred_rotmats_1.detach().cpu())
|
| 266 |
+
)
|
| 267 |
+
if self._cfg.self_condition:
|
| 268 |
+
batch['trans_sc'] = pred_trans_1
|
| 269 |
+
|
| 270 |
+
d_t = t_2 - t_1
|
| 271 |
+
# Take reverse step
|
| 272 |
+
trans_t_2 = self._trans_euler_step(
|
| 273 |
+
d_t, t_1, pred_trans_1, trans_t_1)
|
| 274 |
+
rotmats_t_2 = self._rots_euler_step(
|
| 275 |
+
d_t, t_1, pred_rotmats_1, rotmats_t_1)
|
| 276 |
+
|
| 277 |
+
trans_current, rotmats_current = trans_t_2, rotmats_t_2
|
| 278 |
+
if return_trajectory:
|
| 279 |
+
prot_traj.append((trans_t_2, rotmats_t_2))
|
| 280 |
+
t_1 = t_2
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
t_1 = ts[-1]
|
| 285 |
+
trans_t_1, rotmats_t_1 = trans_current, rotmats_current
|
| 286 |
+
t = torch.ones((num_batch, 1), device=self._device) * t_1
|
| 287 |
+
batch['trans_t'] = trans_t_1
|
| 288 |
+
batch['rotmats_t'] = rotmats_t_1
|
| 289 |
+
batch['t'] = t
|
| 290 |
+
|
| 291 |
+
with torch.no_grad():
|
| 292 |
+
model_out = model(batch)
|
| 293 |
+
# Process model output.
|
| 294 |
+
pred_trans_1 = model_out['pred_trans']
|
| 295 |
+
pred_rotmats_1 = model_out['pred_rotmats']
|
| 296 |
+
if return_trajectory:
|
| 297 |
+
clean_traj.append(
|
| 298 |
+
(pred_trans_1.detach().cpu(), pred_rotmats_1.detach().cpu())
|
| 299 |
+
)
|
| 300 |
+
prot_traj.append((pred_trans_1, pred_rotmats_1))
|
| 301 |
+
else:
|
| 302 |
+
# Keep the historical return structure, but materialize only the
|
| 303 |
+
# final state that inference actually writes.
|
| 304 |
+
prot_traj = [(pred_trans_1, pred_rotmats_1)]
|
| 305 |
+
clean_traj = [(pred_trans_1, pred_rotmats_1)]
|
| 306 |
+
|
| 307 |
+
# Convert trajectories to atom37.
|
| 308 |
+
atom37_traj = all_atom.transrot_to_atom37(prot_traj, res_mask)
|
| 309 |
+
clean_atom37_traj = all_atom.transrot_to_atom37(clean_traj, res_mask)
|
| 310 |
+
|
| 311 |
+
return atom37_traj, clean_atom37_traj, clean_traj
|
| 312 |
+
|
bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/bbflow_model.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 Max Planck Institute for Polymer Research
|
| 2 |
+
# Copyright (c) 2024 HITS gGmbH
|
| 3 |
+
# Copyright (c) Microsoft Corporation.
|
| 4 |
+
# Licensed under the MIT license.
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
from torch.utils.checkpoint import checkpoint
|
| 10 |
+
|
| 11 |
+
from gafl.models import ipa_pytorch
|
| 12 |
+
from gafl.data import utils as du
|
| 13 |
+
from gafl.models.gafl.pga_utils import embed_frames, EquiLayerNorm
|
| 14 |
+
from gafl.models.gafl.cfa import GeometricFrameAttention, Linear, BackboneUpdate
|
| 15 |
+
|
| 16 |
+
from bbflow.models.embedder import Embedder
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
from omegaconf import DictConfig, OmegaConf
|
| 20 |
+
from omegaconf.base import ContainerMetadata
|
| 21 |
+
# depending on the torch version (higher than 2.6), we need to add the DictConfig and ContainerMetadata to the safe globals:
|
| 22 |
+
import torch
|
| 23 |
+
import builtins
|
| 24 |
+
from typing import Any
|
| 25 |
+
from collections import defaultdict
|
| 26 |
+
from omegaconf import DictConfig, OmegaConf, ListConfig
|
| 27 |
+
from omegaconf.nodes import AnyNode
|
| 28 |
+
from omegaconf.base import ContainerMetadata, Metadata
|
| 29 |
+
|
| 30 |
+
# depending on the torch version (>=2.6), we need to add all types the checkpoint asked for
|
| 31 |
+
if hasattr(torch.serialization, "add_safe_globals"):
|
| 32 |
+
torch.serialization.add_safe_globals([
|
| 33 |
+
(Any, "typing.Any"),
|
| 34 |
+
(defaultdict, "collections.defaultdict"),
|
| 35 |
+
(DictConfig, "omegaconf.dictconfig.DictConfig"),
|
| 36 |
+
(ListConfig, "omegaconf.listconfig.ListConfig"),
|
| 37 |
+
(AnyNode, "omegaconf.nodes.AnyNode"),
|
| 38 |
+
(ContainerMetadata, "omegaconf.base.ContainerMetadata"),
|
| 39 |
+
(Metadata, "omegaconf.base.Metadata"),
|
| 40 |
+
(builtins.dict, "builtins.dict"),
|
| 41 |
+
(builtins.int, "builtins.int"),
|
| 42 |
+
(builtins.list, "builtins.list"),
|
| 43 |
+
])
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class BBFlowModel(nn.Module):
|
| 47 |
+
|
| 48 |
+
def __init__(self, model_conf, latent_cfg=None):
|
| 49 |
+
super(BBFlowModel, self).__init__()
|
| 50 |
+
|
| 51 |
+
self._model_conf = model_conf
|
| 52 |
+
self._gfa_conf = model_conf.gfa
|
| 53 |
+
self.rigids_ang_to_nm = lambda x: x.apply_trans_fn(lambda x: x * du.ANG_TO_NM_SCALE)
|
| 54 |
+
self.rigids_nm_to_ang = lambda x: x.apply_trans_fn(lambda x: x * du.NM_TO_ANG_SCALE)
|
| 55 |
+
self.embedder = Embedder(model_conf, latent_cfg=latent_cfg)
|
| 56 |
+
self.latent_enabled = bool(latent_cfg is not None and getattr(latent_cfg, "enable", False))
|
| 57 |
+
self.inject_film = bool(
|
| 58 |
+
self.latent_enabled and getattr(latent_cfg, "inject_film", True)
|
| 59 |
+
)
|
| 60 |
+
self.activation_checkpoint = bool(
|
| 61 |
+
latent_cfg is not None and getattr(latent_cfg, "activation_checkpoint", False)
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
# Attention trunk
|
| 65 |
+
self.trunk = nn.ModuleDict()
|
| 66 |
+
for b in range(self._gfa_conf.num_blocks):
|
| 67 |
+
self.trunk[f'gfa_{b}'] = GeometricFrameAttention(self._gfa_conf, geometric_input=bool(b), geometric_output=True)
|
| 68 |
+
self.trunk[f'gfa_ln_{b}'] = nn.LayerNorm(self._gfa_conf.c_s)
|
| 69 |
+
self.trunk[f'g_ln_{b}'] = EquiLayerNorm()
|
| 70 |
+
tfmr_in = self._gfa_conf.c_s
|
| 71 |
+
tfmr_layer = nn.TransformerEncoderLayer(
|
| 72 |
+
d_model=tfmr_in,
|
| 73 |
+
nhead=self._gfa_conf.seq_tfmr_num_heads,
|
| 74 |
+
dim_feedforward=tfmr_in,
|
| 75 |
+
batch_first=True,
|
| 76 |
+
dropout=0.0,
|
| 77 |
+
norm_first=False
|
| 78 |
+
)
|
| 79 |
+
self.trunk[f'seq_tfmr_{b}'] = nn.TransformerEncoder(
|
| 80 |
+
tfmr_layer, self._gfa_conf.seq_tfmr_num_layers, enable_nested_tensor=False)
|
| 81 |
+
self.trunk[f'post_tfmr_{b}'] = Linear(
|
| 82 |
+
tfmr_in, self._gfa_conf.c_s, init="final")
|
| 83 |
+
self.trunk[f'node_transition_{b}'] = ipa_pytorch.StructureModuleTransition(
|
| 84 |
+
c=self._gfa_conf.c_s)
|
| 85 |
+
self.trunk[f'bb_update_{b}'] = BackboneUpdate(
|
| 86 |
+
self._gfa_conf.c_s,
|
| 87 |
+
self._gfa_conf.no_v_points,
|
| 88 |
+
self._gfa_conf.no_heads,)
|
| 89 |
+
|
| 90 |
+
if b < self._gfa_conf.num_blocks-1:
|
| 91 |
+
# No edge update on the last block.
|
| 92 |
+
edge_in = self._model_conf.edge_embed_size
|
| 93 |
+
self.trunk[f'edge_transition_{b}'] = ipa_pytorch.EdgeTransition(
|
| 94 |
+
node_embed_size=self._gfa_conf.c_s,
|
| 95 |
+
edge_embed_in=edge_in,
|
| 96 |
+
edge_embed_out=self._model_conf.edge_embed_size,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
if self.inject_film:
|
| 100 |
+
self.latent_dim = int(getattr(latent_cfg, "dim", 16))
|
| 101 |
+
self.film_cond_dim = int(getattr(latent_cfg, "node_cond_dim", getattr(latent_cfg, "num_modes", self.latent_dim)))
|
| 102 |
+
self.film_mlp = nn.Sequential(
|
| 103 |
+
nn.Linear(self.film_cond_dim, self._gfa_conf.c_s),
|
| 104 |
+
nn.ReLU(),
|
| 105 |
+
nn.Linear(self._gfa_conf.c_s, 2 * self._gfa_conf.c_s),
|
| 106 |
+
)
|
| 107 |
+
nn.init.zeros_(self.film_mlp[-1].weight)
|
| 108 |
+
nn.init.zeros_(self.film_mlp[-1].bias)
|
| 109 |
+
else:
|
| 110 |
+
self.latent_dim = 0
|
| 111 |
+
self.film_cond_dim = 0
|
| 112 |
+
self.film_mlp = None
|
| 113 |
+
|
| 114 |
+
def _apply_latent_film(self, node_embed, z):
|
| 115 |
+
if not self.inject_film:
|
| 116 |
+
return node_embed
|
| 117 |
+
if isinstance(z, dict):
|
| 118 |
+
cond = z.get("node_cond")
|
| 119 |
+
else:
|
| 120 |
+
cond = z
|
| 121 |
+
if cond is None:
|
| 122 |
+
cond = torch.zeros(
|
| 123 |
+
node_embed.shape[0],
|
| 124 |
+
node_embed.shape[1],
|
| 125 |
+
self.film_cond_dim,
|
| 126 |
+
device=node_embed.device,
|
| 127 |
+
dtype=node_embed.dtype,
|
| 128 |
+
)
|
| 129 |
+
if cond.dim() == 2:
|
| 130 |
+
cond = cond[:, None, :].expand(node_embed.shape[0], node_embed.shape[1], -1)
|
| 131 |
+
gamma_beta = self.film_mlp(cond.to(dtype=node_embed.dtype))
|
| 132 |
+
gamma, beta = torch.chunk(gamma_beta, 2, dim=-1)
|
| 133 |
+
return node_embed * (1.0 + gamma) + beta
|
| 134 |
+
|
| 135 |
+
def prepare_inference_static(self, batch):
|
| 136 |
+
B, N = batch["res_mask"].shape[:2]
|
| 137 |
+
return self.embedder.prepare_inference_static({
|
| 138 |
+
"B,N": (B, N),
|
| 139 |
+
"device": batch["res_mask"].device,
|
| 140 |
+
"CA_pos": {
|
| 141 |
+
"trans_equilibrium": batch["trans_equilibrium"],
|
| 142 |
+
},
|
| 143 |
+
"rotmats_equilibrium": batch["rotmats_equilibrium"],
|
| 144 |
+
"seq": batch["seq"],
|
| 145 |
+
"z": batch.get("z"),
|
| 146 |
+
})
|
| 147 |
+
|
| 148 |
+
def _run_gfa(self, block_idx, node_embed, g, edge_embed, curr_frames, node_mask):
|
| 149 |
+
gfa = self.trunk[f'gfa_{block_idx}']
|
| 150 |
+
if not (self.training and self.activation_checkpoint and torch.is_grad_enabled()):
|
| 151 |
+
return gfa(node_embed, g, edge_embed, curr_frames, node_mask)
|
| 152 |
+
if g is None:
|
| 153 |
+
return gfa(node_embed, g, edge_embed, curr_frames, node_mask)
|
| 154 |
+
|
| 155 |
+
def gfa_forward(node_embed_, g_, edge_embed_, curr_frames_, node_mask_):
|
| 156 |
+
return gfa(node_embed_, g_, edge_embed_, curr_frames_, node_mask_)
|
| 157 |
+
|
| 158 |
+
return checkpoint(
|
| 159 |
+
gfa_forward,
|
| 160 |
+
node_embed,
|
| 161 |
+
g,
|
| 162 |
+
edge_embed,
|
| 163 |
+
curr_frames,
|
| 164 |
+
node_mask,
|
| 165 |
+
use_reentrant=False,
|
| 166 |
+
preserve_rng_state=False,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def forward(self, input_feats):
|
| 171 |
+
node_mask = input_feats['res_mask']
|
| 172 |
+
edge_mask = node_mask[:, None] * node_mask[:, :, None]
|
| 173 |
+
continuous_t = input_feats['t']
|
| 174 |
+
trans_t = input_feats['trans_t']
|
| 175 |
+
rotmats_t = input_feats['rotmats_t']
|
| 176 |
+
|
| 177 |
+
# Initialize node and edge embeddings
|
| 178 |
+
if 'trans_sc' not in input_feats:
|
| 179 |
+
trans_sc = torch.zeros_like(trans_t)
|
| 180 |
+
else:
|
| 181 |
+
trans_sc = input_feats['trans_sc']
|
| 182 |
+
|
| 183 |
+
B, N = node_mask.shape[:2]
|
| 184 |
+
CA_pos = {
|
| 185 |
+
"trans_t": trans_t,
|
| 186 |
+
"trans_sc": trans_sc,
|
| 187 |
+
"trans_equilibrium": input_feats["trans_equilibrium"]
|
| 188 |
+
}
|
| 189 |
+
embedder_input_feats = {
|
| 190 |
+
"B,N": (B, N),
|
| 191 |
+
"device": node_mask.device,
|
| 192 |
+
"time": continuous_t,
|
| 193 |
+
"CA_pos": CA_pos,
|
| 194 |
+
"rotmats_equilibrium": input_feats["rotmats_equilibrium"],
|
| 195 |
+
"seq": input_feats["seq"],
|
| 196 |
+
}
|
| 197 |
+
if "dataset_type_onehot" in input_feats:
|
| 198 |
+
embedder_input_feats["dataset_type_onehot"] = input_feats["dataset_type_onehot"]
|
| 199 |
+
if "z" in input_feats:
|
| 200 |
+
embedder_input_feats["z"] = input_feats["z"]
|
| 201 |
+
if "_embedder_static" in input_feats:
|
| 202 |
+
embedder_input_feats["inference_static"] = input_feats["_embedder_static"]
|
| 203 |
+
init_node_embed, init_edge_embed = self.embedder(embedder_input_feats)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# Initial rigids
|
| 207 |
+
# curr_frames = embed_frames(rotmats_t, trans_t * du.ANG_TO_NM_SCALE)
|
| 208 |
+
curr_rigids = du.create_rigid(rotmats_t, trans_t,)
|
| 209 |
+
curr_rigids = self.rigids_ang_to_nm(curr_rigids)
|
| 210 |
+
curr_frames = embed_frames(rotmats_t, trans_t * du.ANG_TO_NM_SCALE)
|
| 211 |
+
|
| 212 |
+
# Main trunk
|
| 213 |
+
init_node_embed = init_node_embed * node_mask[..., None]
|
| 214 |
+
node_embed = init_node_embed * node_mask[..., None]
|
| 215 |
+
edge_embed = init_edge_embed * edge_mask[..., None]
|
| 216 |
+
g = None
|
| 217 |
+
for b in range(self._gfa_conf.num_blocks):
|
| 218 |
+
gfa_embed, g_gfa, gfa_rel = self._run_gfa(
|
| 219 |
+
b,
|
| 220 |
+
node_embed,
|
| 221 |
+
g,
|
| 222 |
+
edge_embed,
|
| 223 |
+
curr_frames,
|
| 224 |
+
node_mask)
|
| 225 |
+
gfa_embed *= node_mask[..., None]
|
| 226 |
+
gfa_rel = gfa_rel * node_mask[..., None, None]
|
| 227 |
+
node_embed = self.trunk[f'gfa_ln_{b}'](node_embed + gfa_embed)
|
| 228 |
+
|
| 229 |
+
if g is not None:
|
| 230 |
+
g = self.trunk[f'g_ln_{b}'](g + g_gfa)
|
| 231 |
+
else:
|
| 232 |
+
g = self.trunk[f'g_ln_{b}'](g_gfa)
|
| 233 |
+
g = g * node_mask[..., None, None]
|
| 234 |
+
|
| 235 |
+
seq_tfmr_out = self.trunk[f'seq_tfmr_{b}'](
|
| 236 |
+
node_embed, src_key_padding_mask=(1 - node_mask).bool())
|
| 237 |
+
node_embed = node_embed + self.trunk[f'post_tfmr_{b}'](seq_tfmr_out)
|
| 238 |
+
node_embed = self.trunk[f'node_transition_{b}'](node_embed)
|
| 239 |
+
node_embed = node_embed * node_mask[..., None]
|
| 240 |
+
update_node_embed = node_embed
|
| 241 |
+
if b == self._gfa_conf.num_blocks - 1:
|
| 242 |
+
update_node_embed = self._apply_latent_film(
|
| 243 |
+
node_embed,
|
| 244 |
+
input_feats.get("z", None),
|
| 245 |
+
)
|
| 246 |
+
curr_frames, curr_rigids = self.trunk[f'bb_update_{b}'](
|
| 247 |
+
update_node_embed,
|
| 248 |
+
g,
|
| 249 |
+
gfa_rel,
|
| 250 |
+
curr_frames,
|
| 251 |
+
curr_rigids,
|
| 252 |
+
node_mask[..., None],)
|
| 253 |
+
|
| 254 |
+
if b < self._gfa_conf.num_blocks-1:
|
| 255 |
+
edge_embed = self.trunk[f'edge_transition_{b}'](
|
| 256 |
+
node_embed, edge_embed)
|
| 257 |
+
edge_embed *= edge_mask[..., None]
|
| 258 |
+
|
| 259 |
+
curr_rigids = self.rigids_nm_to_ang(curr_rigids)
|
| 260 |
+
pred_trans = curr_rigids.get_trans()
|
| 261 |
+
pred_rotmats = curr_rigids.get_rots().get_rot_mats()
|
| 262 |
+
|
| 263 |
+
return {
|
| 264 |
+
'pred_trans': pred_trans,
|
| 265 |
+
'pred_rotmats': pred_rotmats,
|
| 266 |
+
}
|
bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/bbflow_module.py
ADDED
|
@@ -0,0 +1,1923 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 Max Planck Institute for Polymer Research
|
| 2 |
+
# Copyright (c) 2024 HITS gGmbH
|
| 3 |
+
# Copyright (c) Microsoft Corporation.
|
| 4 |
+
# Licensed under the MIT license.
|
| 5 |
+
|
| 6 |
+
from typing import Any
|
| 7 |
+
import copy
|
| 8 |
+
import torch
|
| 9 |
+
import torch.utils.checkpoint
|
| 10 |
+
import time
|
| 11 |
+
import os
|
| 12 |
+
import random
|
| 13 |
+
import logging
|
| 14 |
+
import wandb
|
| 15 |
+
import numpy as np
|
| 16 |
+
import pandas as pd
|
| 17 |
+
import shutil
|
| 18 |
+
import json
|
| 19 |
+
from datetime import datetime
|
| 20 |
+
from pytorch_lightning.utilities import rank_zero_only
|
| 21 |
+
import torch.distributed as dist
|
| 22 |
+
import matplotlib
|
| 23 |
+
import mdtraj
|
| 24 |
+
import warnings
|
| 25 |
+
|
| 26 |
+
from gafl.analysis import metrics
|
| 27 |
+
from gafl.models.flow_module import FlowModule
|
| 28 |
+
from gafl.data import utils as du
|
| 29 |
+
from gafl.models import utils as mu
|
| 30 |
+
import gafl.experiment_utils as eu
|
| 31 |
+
|
| 32 |
+
from bbflow.data.alignment import require_alignment_version
|
| 33 |
+
from bbflow.models.bbflow_model import BBFlowModel
|
| 34 |
+
from bbflow.models.latent import LatentEncoder
|
| 35 |
+
from bbflow.analysis import utils as au
|
| 36 |
+
from bbflow.analysis.analyse_bbflow import calc_metrics
|
| 37 |
+
from bbflow.data.interpolant_bbflow import InterpolantBBFlow
|
| 38 |
+
|
| 39 |
+
# depending on the torch version (higher than 2.6), we need to add the DictConfig and ContainerMetadata to the safe globals:
|
| 40 |
+
from omegaconf import DictConfig, OmegaConf
|
| 41 |
+
from omegaconf.base import ContainerMetadata
|
| 42 |
+
if hasattr(torch.serialization, 'add_safe_globals'):
|
| 43 |
+
torch.serialization.add_safe_globals([DictConfig, ContainerMetadata]) # needed for loading the checkpoint with weights_only=True
|
| 44 |
+
|
| 45 |
+
WARMUP_EPOCH_SUMMARY_KEYS = [
|
| 46 |
+
"train_loss",
|
| 47 |
+
"official_loss",
|
| 48 |
+
"enm_warmup_loss",
|
| 49 |
+
"enm_warmup_subspace_overlap",
|
| 50 |
+
"enm_warmup_cross_cov_far_top10_sign_agree",
|
| 51 |
+
"enm_warmup_cross_cov_far_corr",
|
| 52 |
+
"enm_warmup_active",
|
| 53 |
+
"latent_effective_modes",
|
| 54 |
+
"condition_scaled_pred_trans_delta_rel",
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
MD_EPOCH_SUMMARY_KEYS = [
|
| 58 |
+
"train_loss",
|
| 59 |
+
"official_loss",
|
| 60 |
+
"motion_loss",
|
| 61 |
+
"mode_orth_loss",
|
| 62 |
+
"mode_recon_loss",
|
| 63 |
+
"q_nll_loss",
|
| 64 |
+
"q_nll_per_dim",
|
| 65 |
+
"mode_coeff_abs",
|
| 66 |
+
"mode_coeff_std",
|
| 67 |
+
"mode_recon_centered_rel_error",
|
| 68 |
+
"mode_recon_uncentered_rel_error",
|
| 69 |
+
"mode_gram_min_eig",
|
| 70 |
+
"mode_gram_condition",
|
| 71 |
+
"mode_max_cosine_abs",
|
| 72 |
+
"local_cov_loss",
|
| 73 |
+
"cross_cov_loss",
|
| 74 |
+
"cross_cov_near_loss",
|
| 75 |
+
"cross_cov_far_loss",
|
| 76 |
+
"cross_cov_far_corr",
|
| 77 |
+
"cross_cov_far_top10_sign_agree",
|
| 78 |
+
"cross_cov_near_top10_sign_agree",
|
| 79 |
+
"rmsf_loss",
|
| 80 |
+
"gen_cov_loss",
|
| 81 |
+
"gen_local_shape_loss",
|
| 82 |
+
"gen_cross_shape_loss",
|
| 83 |
+
"gen_trace_anchor_loss",
|
| 84 |
+
"gen_response_abs_mean",
|
| 85 |
+
"gen_response_trace_mean",
|
| 86 |
+
"gen_trace_ratio_to_teacher",
|
| 87 |
+
"gen_trace_ratio_to_anchor",
|
| 88 |
+
"gen_trace_anchor_mean",
|
| 89 |
+
"gen_rollout_trace_ratio",
|
| 90 |
+
"gen_rollout_trace_ratio_ema",
|
| 91 |
+
"gen_rollout_trace_target_scale",
|
| 92 |
+
"gen_rollout_trace_measured",
|
| 93 |
+
"gen_rollout_trace_steps",
|
| 94 |
+
"gen_rollout_batch",
|
| 95 |
+
"gen_rollout_num_res",
|
| 96 |
+
"gen_response_active_frac",
|
| 97 |
+
"pca_align_loss",
|
| 98 |
+
"pca_align_weighted_overlap",
|
| 99 |
+
"pca_align_best_overlap",
|
| 100 |
+
"pca_align_top_energy_overlap",
|
| 101 |
+
"pca_align_top_energy_subspace_overlap",
|
| 102 |
+
"condition_cycle_loss",
|
| 103 |
+
"condition_cycle_rel_error",
|
| 104 |
+
"condition_cycle_cosine",
|
| 105 |
+
"enm_warmup_active",
|
| 106 |
+
"latent_effective_modes",
|
| 107 |
+
"condition_scaled_pred_trans_delta_rel",
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def epoch_summary_stage(metrics):
|
| 112 |
+
warmup_active = float(metrics.get("enm_warmup_active", 0.0) or 0.0) > 0.5
|
| 113 |
+
return "enm-init" if warmup_active else "md"
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def epoch_summary_keys(metrics):
|
| 117 |
+
"""Return the concise console summary for the current training stage."""
|
| 118 |
+
return WARMUP_EPOCH_SUMMARY_KEYS if epoch_summary_stage(metrics) == "enm-init" else MD_EPOCH_SUMMARY_KEYS
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class BBFlowModule(FlowModule):
|
| 122 |
+
|
| 123 |
+
def __init__(self, cfg, folding_cfg=None):
|
| 124 |
+
self._latent_cfg_raw = cfg.latent if hasattr(cfg, "latent") else None
|
| 125 |
+
super().__init__(cfg, folding_cfg)
|
| 126 |
+
self._print_logger = eu.get_pylogger(__name__)
|
| 127 |
+
if hasattr(self._exp_cfg, 'reset_epoch'):
|
| 128 |
+
self.reset_epoch = self._exp_cfg.reset_epoch
|
| 129 |
+
else:
|
| 130 |
+
self.reset_epoch = False
|
| 131 |
+
if hasattr(self._exp_cfg, 'reset_optimizer_on_load'):
|
| 132 |
+
self.reset_optimizer_on_load = self._exp_cfg.reset_optimizer_on_load
|
| 133 |
+
else:
|
| 134 |
+
self.reset_optimizer_on_load = False
|
| 135 |
+
|
| 136 |
+
# set samples per valid protein:
|
| 137 |
+
num_ranks = cfg.experiment.num_devices
|
| 138 |
+
total_samples_per_valid_prot = self._data_cfg.validation.samples_per_valid_protein
|
| 139 |
+
self.samples_per_valid_protein_per_rank = total_samples_per_valid_prot // num_ranks
|
| 140 |
+
|
| 141 |
+
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."
|
| 142 |
+
assert self.samples_per_valid_protein_per_rank > 0
|
| 143 |
+
|
| 144 |
+
def create_model(self):
|
| 145 |
+
latent_enabled = bool(self._latent_cfg_raw is not None and getattr(self._latent_cfg_raw, "enable", False))
|
| 146 |
+
self.model = BBFlowModel(self._model_cfg, latent_cfg=self._latent_cfg_raw)
|
| 147 |
+
self.interpolant = InterpolantBBFlow(self._interpolant_cfg)
|
| 148 |
+
self.latent_enabled = latent_enabled
|
| 149 |
+
training_cfg = self._exp_cfg.training
|
| 150 |
+
self.motion_loss_enabled = bool(
|
| 151 |
+
latent_enabled and float(getattr(training_cfg, "lambda_shape", 1.0)) != 0.0
|
| 152 |
+
)
|
| 153 |
+
self.condition_enabled = bool(
|
| 154 |
+
latent_enabled and (
|
| 155 |
+
getattr(self._latent_cfg_raw, "inject_embedder", True)
|
| 156 |
+
or getattr(self._latent_cfg_raw, "inject_film", True)
|
| 157 |
+
)
|
| 158 |
+
)
|
| 159 |
+
self.training_epoch_metrics = []
|
| 160 |
+
self._grad_flow_reported = False
|
| 161 |
+
self._condition_probe_epoch = None
|
| 162 |
+
self._gen_cov_rollout_trace_ratio_ema = None
|
| 163 |
+
self.freeze_foundation = bool(
|
| 164 |
+
latent_enabled and getattr(self._latent_cfg_raw, "freeze_foundation", True)
|
| 165 |
+
)
|
| 166 |
+
if latent_enabled:
|
| 167 |
+
self.latent_encoder = LatentEncoder(self._latent_cfg_raw)
|
| 168 |
+
self.motion_target_cache = None
|
| 169 |
+
self.motion_target_device_cache = {}
|
| 170 |
+
self.equilibrium_distance_cache = {}
|
| 171 |
+
self.motion_target_cache_path = getattr(
|
| 172 |
+
self._latent_cfg_raw,
|
| 173 |
+
"motion_target_cache_path",
|
| 174 |
+
getattr(self._latent_cfg_raw, "shape_fingerprint_cache_path", None),
|
| 175 |
+
)
|
| 176 |
+
if not self.motion_loss_enabled and not self.condition_enabled:
|
| 177 |
+
for param in self.latent_encoder.parameters():
|
| 178 |
+
param.requires_grad = False
|
| 179 |
+
if self.freeze_foundation:
|
| 180 |
+
self._freeze_foundation_model()
|
| 181 |
+
def _freeze_foundation_model(self):
|
| 182 |
+
for param in self.model.parameters():
|
| 183 |
+
param.requires_grad = False
|
| 184 |
+
trainable_modules = [
|
| 185 |
+
self.model.embedder.z_node_adapter,
|
| 186 |
+
self.model.embedder.z_edge_adapter,
|
| 187 |
+
self.model.embedder.disp_node_adapter,
|
| 188 |
+
self.model.embedder.disp_edge_adapter,
|
| 189 |
+
self.model.film_mlp,
|
| 190 |
+
]
|
| 191 |
+
for module in trainable_modules:
|
| 192 |
+
if module is not None:
|
| 193 |
+
for param in module.parameters():
|
| 194 |
+
param.requires_grad = True
|
| 195 |
+
|
| 196 |
+
def _set_frozen_foundation_eval(self):
|
| 197 |
+
if not getattr(self, "freeze_foundation", False):
|
| 198 |
+
return
|
| 199 |
+
self.model.eval()
|
| 200 |
+
for module in [
|
| 201 |
+
self.model.embedder.z_node_adapter,
|
| 202 |
+
self.model.embedder.z_edge_adapter,
|
| 203 |
+
self.model.embedder.disp_node_adapter,
|
| 204 |
+
self.model.embedder.disp_edge_adapter,
|
| 205 |
+
self.model.film_mlp,
|
| 206 |
+
]:
|
| 207 |
+
if module is not None:
|
| 208 |
+
module.train()
|
| 209 |
+
|
| 210 |
+
def on_train_epoch_start(self):
|
| 211 |
+
self._set_frozen_foundation_eval()
|
| 212 |
+
parent_hook = getattr(super(), "on_train_epoch_start", None)
|
| 213 |
+
if parent_hook is not None:
|
| 214 |
+
return parent_hook()
|
| 215 |
+
return None
|
| 216 |
+
|
| 217 |
+
def _get_motion_target_cache(self):
|
| 218 |
+
if self.motion_target_cache is not None:
|
| 219 |
+
return self.motion_target_cache
|
| 220 |
+
cache_path = self.motion_target_cache_path
|
| 221 |
+
if cache_path in (None, "null", ""):
|
| 222 |
+
return None
|
| 223 |
+
cache_path = os.path.expanduser(str(cache_path))
|
| 224 |
+
if not os.path.exists(cache_path):
|
| 225 |
+
raise FileNotFoundError(f"Missing motion target cache: {cache_path}")
|
| 226 |
+
cache = torch.load(cache_path, map_location="cpu", weights_only=False)
|
| 227 |
+
require_alignment_version(cache, source=str(cache_path))
|
| 228 |
+
if isinstance(cache, dict) and "motion_targets" in cache:
|
| 229 |
+
targets = cache["motion_targets"]
|
| 230 |
+
else:
|
| 231 |
+
raise ValueError(
|
| 232 |
+
f"Unsupported motion target cache format: {cache_path}. "
|
| 233 |
+
"Run scripts/extract_shape_fingerprints.py again to create motion_targets."
|
| 234 |
+
)
|
| 235 |
+
out = {}
|
| 236 |
+
for key, value in targets.items():
|
| 237 |
+
target = {
|
| 238 |
+
"local_cov": torch.as_tensor(value["local_cov"], dtype=torch.float32),
|
| 239 |
+
"cross_cov": torch.as_tensor(value["cross_cov"], dtype=torch.float32),
|
| 240 |
+
"dccm": torch.as_tensor(value.get("dccm", value["cross_cov"]), dtype=torch.float32),
|
| 241 |
+
"rmsf": torch.as_tensor(value["rmsf"], dtype=torch.float32),
|
| 242 |
+
"res_mask": torch.as_tensor(value.get("res_mask", torch.ones_like(torch.as_tensor(value["rmsf"]))), dtype=torch.float32),
|
| 243 |
+
}
|
| 244 |
+
for optional_field in [
|
| 245 |
+
"oracle_modes",
|
| 246 |
+
"oracle_energy",
|
| 247 |
+
"oracle_mean_disp",
|
| 248 |
+
"gen_response_trace_anchor",
|
| 249 |
+
]:
|
| 250 |
+
if optional_field in value:
|
| 251 |
+
target[optional_field] = torch.as_tensor(value[optional_field], dtype=torch.float32)
|
| 252 |
+
for name in self._pdb_name_variants(str(key)):
|
| 253 |
+
out[name] = target
|
| 254 |
+
if len(out) == 0:
|
| 255 |
+
raise ValueError(f"Motion target cache is empty: {cache_path}")
|
| 256 |
+
self.motion_target_cache = out
|
| 257 |
+
return self.motion_target_cache
|
| 258 |
+
|
| 259 |
+
@staticmethod
|
| 260 |
+
def _pdb_name_variants(name):
|
| 261 |
+
variants = {name}
|
| 262 |
+
if "_" in name:
|
| 263 |
+
variants.add(name.replace("_", ""))
|
| 264 |
+
elif len(name) == 5:
|
| 265 |
+
variants.add(f"{name[:4]}_{name[4]}")
|
| 266 |
+
return variants
|
| 267 |
+
|
| 268 |
+
def _lookup_motion_targets(self, pdb_names, device, dtype, num_res):
|
| 269 |
+
cache = self._get_motion_target_cache()
|
| 270 |
+
if cache is None:
|
| 271 |
+
raise ValueError(
|
| 272 |
+
"latent.motion_target_cache_path is required for motion-prior training; "
|
| 273 |
+
"run base_stages/00_extract_shape_fingerprints.sh first."
|
| 274 |
+
)
|
| 275 |
+
rows = []
|
| 276 |
+
missing = []
|
| 277 |
+
required_fields = ["local_cov", "cross_cov", "rmsf"]
|
| 278 |
+
optional_fields = ["oracle_mean_disp", "gen_response_trace_anchor"]
|
| 279 |
+
needs_oracle_modes = bool(getattr(self._exp_cfg.training, "oracle_condition", False)) or (
|
| 280 |
+
float(getattr(self._exp_cfg.training, "lambda_pca_align", 0.0)) > 0.0
|
| 281 |
+
)
|
| 282 |
+
if needs_oracle_modes:
|
| 283 |
+
optional_fields = ["oracle_modes", "oracle_energy", "oracle_mean_disp"]
|
| 284 |
+
for name in pdb_names:
|
| 285 |
+
key = str(name)
|
| 286 |
+
value = None
|
| 287 |
+
resolved_name = None
|
| 288 |
+
for variant in self._pdb_name_variants(key):
|
| 289 |
+
value = cache.get(variant)
|
| 290 |
+
if value is not None:
|
| 291 |
+
resolved_name = variant
|
| 292 |
+
break
|
| 293 |
+
if value is None:
|
| 294 |
+
missing.append(key)
|
| 295 |
+
continue
|
| 296 |
+
if needs_oracle_modes:
|
| 297 |
+
missing_oracle = [field for field in ["oracle_modes", "oracle_energy"] if field not in value]
|
| 298 |
+
if missing_oracle:
|
| 299 |
+
raise ValueError(
|
| 300 |
+
f"Motion target cache entry {key} lacks {missing_oracle}; "
|
| 301 |
+
"regenerate it with scripts/extract_shape_fingerprints.py before using lambda_pca_align."
|
| 302 |
+
)
|
| 303 |
+
if int(value["rmsf"].shape[0]) != int(num_res):
|
| 304 |
+
raise ValueError(
|
| 305 |
+
f"Motion target length mismatch for {key}: cache {value['rmsf'].shape[0]} vs batch {num_res}"
|
| 306 |
+
)
|
| 307 |
+
device_key = (resolved_name, str(device), str(dtype))
|
| 308 |
+
device_value = self.motion_target_device_cache.get(device_key)
|
| 309 |
+
if device_value is None:
|
| 310 |
+
fields = required_fields + [
|
| 311 |
+
field for field in optional_fields if field in value
|
| 312 |
+
]
|
| 313 |
+
device_value = {
|
| 314 |
+
field: value[field].to(device=device, dtype=dtype)
|
| 315 |
+
for field in fields
|
| 316 |
+
}
|
| 317 |
+
self.motion_target_device_cache[device_key] = device_value
|
| 318 |
+
rows.append(device_value)
|
| 319 |
+
if missing:
|
| 320 |
+
preview = ", ".join(missing[:10])
|
| 321 |
+
raise KeyError(f"Missing motion targets for {len(missing)} proteins: {preview}")
|
| 322 |
+
out = {
|
| 323 |
+
field: torch.stack([row[field] for row in rows], dim=0)
|
| 324 |
+
for field in required_fields
|
| 325 |
+
}
|
| 326 |
+
for field in optional_fields:
|
| 327 |
+
if all(field in row for row in rows):
|
| 328 |
+
out[field] = torch.stack([row[field] for row in rows], dim=0)
|
| 329 |
+
return out
|
| 330 |
+
|
| 331 |
+
def _equilibrium_spatial_dists(self, pdb_names, trans_equilibrium):
|
| 332 |
+
rows = []
|
| 333 |
+
num_res = int(trans_equilibrium.shape[1])
|
| 334 |
+
for name, coords in zip(pdb_names, trans_equilibrium):
|
| 335 |
+
key = (
|
| 336 |
+
str(name),
|
| 337 |
+
num_res,
|
| 338 |
+
str(coords.device),
|
| 339 |
+
str(coords.dtype),
|
| 340 |
+
)
|
| 341 |
+
distances = self.equilibrium_distance_cache.get(key)
|
| 342 |
+
if distances is None:
|
| 343 |
+
distances = torch.cdist(
|
| 344 |
+
coords.detach().float()[None], coords.detach().float()[None]
|
| 345 |
+
)[0]
|
| 346 |
+
self.equilibrium_distance_cache[key] = distances
|
| 347 |
+
rows.append(distances)
|
| 348 |
+
return torch.stack(rows, dim=0)
|
| 349 |
+
|
| 350 |
+
def validation_step(self, batch: Any, batch_idx: int, dataloader_idx: int=0):
|
| 351 |
+
pdb_name = batch["pdb_name"][0]
|
| 352 |
+
|
| 353 |
+
epoch_dir = os.path.join(self._sample_write_dir, f'epoch_{self.current_epoch}')
|
| 354 |
+
os.makedirs(epoch_dir, exist_ok=True)
|
| 355 |
+
pdb_dir = os.path.join(epoch_dir, pdb_name)
|
| 356 |
+
os.makedirs(pdb_dir, exist_ok=True)
|
| 357 |
+
|
| 358 |
+
N = batch['seq'].shape[1]
|
| 359 |
+
batch_size = self._data_cfg.validation.max_valid_num_res_squared / N**2
|
| 360 |
+
batch_size = max(
|
| 361 |
+
1,
|
| 362 |
+
min(
|
| 363 |
+
self._data_cfg.validation.max_valid_batch_size,
|
| 364 |
+
int(batch_size/5)*5
|
| 365 |
+
)
|
| 366 |
+
)
|
| 367 |
+
self.interpolant.set_device(batch["trans_equilibrium"].device)
|
| 368 |
+
# print(self.interpolant._cfg)
|
| 369 |
+
sampled_conformations = self._sample_multiple(
|
| 370 |
+
batch["trans_equilibrium"],
|
| 371 |
+
batch["rotmats_equilibrium"],
|
| 372 |
+
batch["seq"],
|
| 373 |
+
self.samples_per_valid_protein_per_rank,
|
| 374 |
+
batch_size,
|
| 375 |
+
self.interpolant,
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
rank = dist.get_rank()
|
| 380 |
+
if dist.get_world_size() > 1:
|
| 381 |
+
# if multi-gpu, only save npy files and combine in on_validation_epoch_end
|
| 382 |
+
# into one pdb file.
|
| 383 |
+
samples_path = os.path.join(pdb_dir, f'rank_{rank}_sampled_conformations.npy')
|
| 384 |
+
np.save(samples_path, sampled_conformations)
|
| 385 |
+
else:
|
| 386 |
+
# if single-gpu, save pdb file directly
|
| 387 |
+
samples_path = os.path.join(pdb_dir, f'sampled_conformations.pdb')
|
| 388 |
+
au.write_prot_to_pdb(
|
| 389 |
+
sampled_conformations,
|
| 390 |
+
samples_path,
|
| 391 |
+
no_indexing=True
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def on_validation_epoch_end(self):
|
| 396 |
+
# wait until all ranks finished validation_step
|
| 397 |
+
if dist.is_initialized() and dist.get_world_size() > 1:
|
| 398 |
+
dist.barrier() # wait until all ranks wrote their .npy
|
| 399 |
+
|
| 400 |
+
if dist.is_initialized() and dist.get_rank() != 0:
|
| 401 |
+
return # only rank 0 continues
|
| 402 |
+
|
| 403 |
+
# make image saving faster:
|
| 404 |
+
matplotlib.use("Agg") # non-interactive, fast, no GUI needed
|
| 405 |
+
import matplotlib.pyplot as plt
|
| 406 |
+
|
| 407 |
+
folder = os.path.join(
|
| 408 |
+
self._sample_write_dir,
|
| 409 |
+
f'epoch_{self.current_epoch}',
|
| 410 |
+
)
|
| 411 |
+
valid_csv_path = os.path.join(self._sample_write_dir, 'valid.csv')
|
| 412 |
+
valid_csv = pd.read_csv(valid_csv_path)
|
| 413 |
+
all_pdb_names = valid_csv['name'].values if 'name' in valid_csv else valid_csv['pdb_name'].values
|
| 414 |
+
pdb_names = []
|
| 415 |
+
if dist.get_world_size() > 1:
|
| 416 |
+
# combine samples that are saved in npy files into one pdb file
|
| 417 |
+
for pdb_name in all_pdb_names:
|
| 418 |
+
pdb_folder = os.path.join(folder, pdb_name)
|
| 419 |
+
if self.trainer.sanity_checking and not os.path.exists(pdb_folder):
|
| 420 |
+
continue
|
| 421 |
+
pdb_names.append(pdb_name)
|
| 422 |
+
|
| 423 |
+
coords = []
|
| 424 |
+
for rank in range(dist.get_world_size()):
|
| 425 |
+
samples_path = os.path.join(pdb_folder, f'rank_{rank}_sampled_conformations.npy')
|
| 426 |
+
coords.append(np.load(samples_path))
|
| 427 |
+
os.remove(samples_path)
|
| 428 |
+
coords = np.concatenate(coords, axis=0)
|
| 429 |
+
|
| 430 |
+
samples_path = os.path.join(pdb_folder, f'sampled_conformations.pdb')
|
| 431 |
+
au.write_prot_to_pdb(
|
| 432 |
+
coords,
|
| 433 |
+
samples_path,
|
| 434 |
+
no_indexing=True
|
| 435 |
+
)
|
| 436 |
+
else:
|
| 437 |
+
for pdb_name in all_pdb_names:
|
| 438 |
+
pdb_folder = os.path.join(folder, pdb_name)
|
| 439 |
+
if self.trainer.sanity_checking and not os.path.exists(pdb_folder):
|
| 440 |
+
continue
|
| 441 |
+
pdb_names.append(pdb_name)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
if self.trainer.sanity_checking or not self._exp_cfg.use_wandb:
|
| 446 |
+
return
|
| 447 |
+
|
| 448 |
+
metrics_subset = self._data_cfg.validation.metrics_subset
|
| 449 |
+
with warnings.catch_warnings():
|
| 450 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
| 451 |
+
data, metrics_dict, _ = calc_metrics(
|
| 452 |
+
pdb_names,
|
| 453 |
+
self._data_cfg.validation.valid_xtc_paths,
|
| 454 |
+
folder,
|
| 455 |
+
137,
|
| 456 |
+
self._data_cfg.loader.num_workers,
|
| 457 |
+
metrics_subset=metrics_subset,
|
| 458 |
+
use_tqdm=self._exp_cfg.use_tqdm
|
| 459 |
+
)
|
| 460 |
+
for key, value in metrics_dict.items():
|
| 461 |
+
self._log_scalar(
|
| 462 |
+
f'valid_bbf_metrics/{key}', value,
|
| 463 |
+
on_step=False, on_epoch=True, prog_bar=False,
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
af_rmsfs = None
|
| 468 |
+
if self._data_cfg.validation.alphaflow_valid_rmsf_path is not None and os.path.exists(self._data_cfg.validation.alphaflow_valid_rmsf_path):
|
| 469 |
+
with open(self._data_cfg.validation.alphaflow_valid_rmsf_path, 'r') as f:
|
| 470 |
+
af_rmsfs = json.load(f)
|
| 471 |
+
else:
|
| 472 |
+
af_rmsfs = None
|
| 473 |
+
|
| 474 |
+
def _plot_rmsf(pdb_name, ax, md, bbf, af=None, rmsf_type="RMSF"):
|
| 475 |
+
rmse = np.sqrt(np.mean((bbf[0] - md[0])**2))
|
| 476 |
+
xs = np.arange(len(md[0]))
|
| 477 |
+
ax.plot(xs, md[0], label="MD", c="C0")
|
| 478 |
+
ax.fill_between(xs, md[1], md[2], color="C0", alpha=0.5)
|
| 479 |
+
ax.plot(xs, bbf[0], label="BBFlow", c="C1")
|
| 480 |
+
ax.fill_between(xs, bbf[1], bbf[2], color="C1", alpha=0.5)
|
| 481 |
+
if af is not None:
|
| 482 |
+
ax.plot(xs, af["rmsf"], label="AlphaFlow", c="C2")
|
| 483 |
+
ax.fill_between(xs, af["low"], af["high"], color="C2", alpha=0.5)
|
| 484 |
+
ax.set_xlabel("Residue")
|
| 485 |
+
ax.set_ylabel(f"{rmsf_type} "+r"[$\AA$]")
|
| 486 |
+
ax.legend()
|
| 487 |
+
ax.set_title(f"{rmsf_type} {pdb_name}, Epoch {self.current_epoch}, RMSE={rmse:.3f}")
|
| 488 |
+
|
| 489 |
+
if self._exp_cfg.use_wandb and "RMSF" in metrics_subset:
|
| 490 |
+
SMALL_SIZE = 20
|
| 491 |
+
MEDIUM_SIZE = 24
|
| 492 |
+
BIGGER_SIZE = 28
|
| 493 |
+
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
|
| 494 |
+
plt.rc('axes', titlesize=BIGGER_SIZE) # fontsize of the axes title
|
| 495 |
+
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
|
| 496 |
+
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
|
| 497 |
+
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
|
| 498 |
+
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
|
| 499 |
+
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
|
| 500 |
+
|
| 501 |
+
for pdb_name in pdb_names:
|
| 502 |
+
fig = plt.figure(figsize=(10, 5))
|
| 503 |
+
_plot_rmsf(
|
| 504 |
+
pdb_name, plt.gca(),
|
| 505 |
+
(data[pdb_name]["CA_ref_rmsf"], data[pdb_name]["CA_ref_rmsf_low"], data[pdb_name]["CA_ref_rmsf_high"]),
|
| 506 |
+
(data[pdb_name]["CA_model_rmsf"], data[pdb_name]["CA_model_rmsf_low"], data[pdb_name]["CA_model_rmsf_high"]),
|
| 507 |
+
af_rmsfs[pdb_name] if af_rmsfs is not None else None,
|
| 508 |
+
"RMSF"
|
| 509 |
+
)
|
| 510 |
+
wandb.log({f"rmsf_plots/{pdb_name}": wandb.Image(fig)})
|
| 511 |
+
plt.close(fig)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
if "RMSF" in metrics_subset:
|
| 515 |
+
rmses = []
|
| 516 |
+
for pdb_name in pdb_names:
|
| 517 |
+
rmse = np.sqrt(np.mean((data[pdb_name]["model_rmsf"] - data[pdb_name]["ref_rmsf"])**2))
|
| 518 |
+
rmses.append(rmse)
|
| 519 |
+
self._log_scalar(
|
| 520 |
+
f'valid_all/{pdb_name}_rmsf_rmse', rmse,
|
| 521 |
+
on_step=False, on_epoch=True, prog_bar=False,
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
rmses = np.array(rmses)
|
| 525 |
+
self._log_scalar(
|
| 526 |
+
f'valid/rmsf_rmse', np.mean(rmses),
|
| 527 |
+
on_step=False, on_epoch=True, prog_bar=False,
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def _sample_multiple(self,
|
| 533 |
+
trans_eq, rotmats_eq, seq,
|
| 534 |
+
num_samples, batch_size,
|
| 535 |
+
interpolant,
|
| 536 |
+
pdb_dir=None
|
| 537 |
+
):
|
| 538 |
+
_, N = trans_eq.shape[:2]
|
| 539 |
+
diffuse_mask = torch.ones(1, N)
|
| 540 |
+
|
| 541 |
+
sample_ids_batches = np.split(
|
| 542 |
+
np.arange(num_samples),
|
| 543 |
+
np.arange(batch_size, num_samples, batch_size)
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
sampled_conformations = []
|
| 547 |
+
|
| 548 |
+
for sample_ids in sample_ids_batches:
|
| 549 |
+
B = len(sample_ids)
|
| 550 |
+
z = self._sample_prior_z(trans_eq, rotmats_eq, seq, B)
|
| 551 |
+
atom37_traj, pred_traj, _ = interpolant.sample(
|
| 552 |
+
B,
|
| 553 |
+
N,
|
| 554 |
+
self.model,
|
| 555 |
+
trans_eq.repeat(B, 1, 1),
|
| 556 |
+
rotmats_eq.repeat(B, 1, 1, 1),
|
| 557 |
+
seq.repeat(B, 1, 1),
|
| 558 |
+
z=z,
|
| 559 |
+
return_trajectory=not bool(
|
| 560 |
+
getattr(self._infer_cfg, "final_only", True)
|
| 561 |
+
) or pdb_dir is not None,
|
| 562 |
+
cache_static_features=bool(
|
| 563 |
+
getattr(self._infer_cfg, "cache_static_features", True)
|
| 564 |
+
),
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
atom37_traj = du.to_numpy(torch.stack(atom37_traj, dim=1))
|
| 568 |
+
pred_traj = du.to_numpy(torch.stack(pred_traj, dim=1))
|
| 569 |
+
# B, T, N, 37, 3
|
| 570 |
+
|
| 571 |
+
# remove the c betas. they are not predicted by the network but rule based and have no real meaning
|
| 572 |
+
# Masking CB atoms
|
| 573 |
+
# atom37 bb order = ['N', 'CA', 'C', 'CB', 'O']
|
| 574 |
+
atom37_traj[..., 3, :] = 0
|
| 575 |
+
pred_traj[..., 3, :] = 0
|
| 576 |
+
|
| 577 |
+
for i, sample_id in enumerate(sample_ids):
|
| 578 |
+
sampled_conformations.append(atom37_traj[i, -1])
|
| 579 |
+
|
| 580 |
+
if pdb_dir is not None:
|
| 581 |
+
sample_dir = os.path.join(pdb_dir, f'conf_{sample_id}')
|
| 582 |
+
os.makedirs(sample_dir, exist_ok=True)
|
| 583 |
+
eu.save_traj(
|
| 584 |
+
atom37_traj[i, -1],
|
| 585 |
+
np.flip(atom37_traj[i], axis=0),
|
| 586 |
+
np.flip(pred_traj[i], axis=0),
|
| 587 |
+
du.to_numpy(diffuse_mask)[0],
|
| 588 |
+
output_dir=sample_dir,
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
sampled_conformations = np.stack(sampled_conformations, axis=0)
|
| 592 |
+
return sampled_conformations
|
| 593 |
+
|
| 594 |
+
def _zero_condition(self, condition):
|
| 595 |
+
if condition is None:
|
| 596 |
+
return None
|
| 597 |
+
out = {}
|
| 598 |
+
for key, value in condition.items():
|
| 599 |
+
if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}:
|
| 600 |
+
out[key] = torch.zeros_like(value)
|
| 601 |
+
else:
|
| 602 |
+
out[key] = value
|
| 603 |
+
return out
|
| 604 |
+
|
| 605 |
+
def _scale_condition(self, condition, scale):
|
| 606 |
+
if condition is None or float(scale) == 1.0:
|
| 607 |
+
return condition
|
| 608 |
+
out = {}
|
| 609 |
+
for key, value in condition.items():
|
| 610 |
+
if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}:
|
| 611 |
+
out[key] = value * float(scale)
|
| 612 |
+
else:
|
| 613 |
+
out[key] = value
|
| 614 |
+
return out
|
| 615 |
+
|
| 616 |
+
def _shuffle_condition(self, condition, num_res):
|
| 617 |
+
if condition is None:
|
| 618 |
+
return None
|
| 619 |
+
device = next(
|
| 620 |
+
(value.device for value in condition.values() if torch.is_tensor(value)),
|
| 621 |
+
torch.device("cpu"),
|
| 622 |
+
)
|
| 623 |
+
perm = torch.randperm(int(num_res), device=device)
|
| 624 |
+
out = {}
|
| 625 |
+
for key, value in condition.items():
|
| 626 |
+
if not torch.is_tensor(value):
|
| 627 |
+
out[key] = value
|
| 628 |
+
elif key in {"node_cond", "disp_node_cond"} and value.ndim >= 3 and value.shape[1] == num_res:
|
| 629 |
+
out[key] = value[:, perm, ...]
|
| 630 |
+
elif key in {"edge_cond", "disp_edge_cond"} and value.ndim >= 4 and value.shape[1] == num_res and value.shape[2] == num_res:
|
| 631 |
+
out[key] = value[:, perm, ...][:, :, perm, ...]
|
| 632 |
+
else:
|
| 633 |
+
out[key] = value
|
| 634 |
+
return out
|
| 635 |
+
|
| 636 |
+
def _sample_prior_z(self, trans_eq, rotmats_eq, seq, batch_size):
|
| 637 |
+
if not getattr(self, "latent_enabled", False):
|
| 638 |
+
return None
|
| 639 |
+
device = trans_eq.device
|
| 640 |
+
_, num_res = trans_eq.shape[:2]
|
| 641 |
+
res_mask = torch.ones(1, num_res, device=device)
|
| 642 |
+
infer_cfg = getattr(self, "_infer_cfg", None)
|
| 643 |
+
z_per_sample = bool(getattr(infer_cfg, "z_per_sample", False)) if infer_cfg is not None else False
|
| 644 |
+
z_per_sample = z_per_sample or bool(getattr(self.latent_encoder, "sample_coefficients", False))
|
| 645 |
+
condition_mode = str(getattr(infer_cfg, "condition_mode", "real")) if infer_cfg is not None else "real"
|
| 646 |
+
condition_scale = float(getattr(infer_cfg, "condition_scale", 1.0)) if infer_cfg is not None else 1.0
|
| 647 |
+
with torch.no_grad():
|
| 648 |
+
if z_per_sample:
|
| 649 |
+
trans_in = trans_eq.repeat(batch_size, 1, 1)
|
| 650 |
+
rot_in = rotmats_eq.repeat(batch_size, 1, 1, 1)
|
| 651 |
+
seq_in = seq.repeat(batch_size, 1, 1)
|
| 652 |
+
mask_in = res_mask.repeat(batch_size, 1)
|
| 653 |
+
z = self.latent_encoder.sample_prior_z(trans_in, rot_in, seq_in, mask_in)
|
| 654 |
+
else:
|
| 655 |
+
z = self.latent_encoder.sample_prior_z(trans_eq, rotmats_eq, seq, res_mask)
|
| 656 |
+
z = self.latent_encoder.repeat_condition(z, batch_size)
|
| 657 |
+
if condition_mode == "real":
|
| 658 |
+
pass
|
| 659 |
+
elif condition_mode == "zero":
|
| 660 |
+
z = self._zero_condition(z)
|
| 661 |
+
elif condition_mode == "shuffled":
|
| 662 |
+
z = self._shuffle_condition(z, num_res)
|
| 663 |
+
else:
|
| 664 |
+
raise ValueError(f"Unknown inference.condition_mode={condition_mode}")
|
| 665 |
+
return self._scale_condition(z, condition_scale)
|
| 666 |
+
|
| 667 |
+
def on_load_checkpoint(self, checkpoint):
|
| 668 |
+
super().on_load_checkpoint(checkpoint)
|
| 669 |
+
# If using a Gafl checkpoint, don't use weights of node_embedder and edge_embedder
|
| 670 |
+
new_state_dict = {}
|
| 671 |
+
current_state = self.state_dict()
|
| 672 |
+
for k,v in checkpoint["state_dict"].items():
|
| 673 |
+
if 'node_embedder' in k:
|
| 674 |
+
continue
|
| 675 |
+
if 'edge_embedder' in k:
|
| 676 |
+
continue
|
| 677 |
+
if k not in current_state:
|
| 678 |
+
continue
|
| 679 |
+
if current_state[k].shape != v.shape:
|
| 680 |
+
continue
|
| 681 |
+
new_state_dict[k] = v
|
| 682 |
+
for k,v in self.model.state_dict().items():
|
| 683 |
+
if f"model.{k}" not in new_state_dict:
|
| 684 |
+
new_state_dict[f"model.{k}"] = v
|
| 685 |
+
for k, v in current_state.items():
|
| 686 |
+
if k not in new_state_dict:
|
| 687 |
+
new_state_dict[k] = v
|
| 688 |
+
checkpoint['state_dict'] = new_state_dict
|
| 689 |
+
|
| 690 |
+
if self.reset_optimizer_on_load:
|
| 691 |
+
optimizers = self.configure_optimizers()
|
| 692 |
+
if isinstance(optimizers, tuple):
|
| 693 |
+
optimizers = optimizers[0]
|
| 694 |
+
lr_schedulers = optimizers[1]
|
| 695 |
+
checkpoint['optimizer_states'] = [o.state_dict() for o in optimizers]
|
| 696 |
+
checkpoint['lr_schedulers'] = [s.state_dict() for s in lr_schedulers]
|
| 697 |
+
else:
|
| 698 |
+
checkpoint['optimizer_states'] = [optimizers.state_dict()]
|
| 699 |
+
|
| 700 |
+
if self.reset_epoch:
|
| 701 |
+
checkpoint["epoch"] = 0
|
| 702 |
+
checkpoint["global_step"] = 0
|
| 703 |
+
del checkpoint["loops"]
|
| 704 |
+
|
| 705 |
+
def _oracle_group_z(self, noisy_batch):
|
| 706 |
+
device = noisy_batch["res_mask"].device
|
| 707 |
+
num_batch, num_res = noisy_batch["res_mask"].shape[:2]
|
| 708 |
+
oracle_targets = self._lookup_motion_targets(
|
| 709 |
+
noisy_batch["pdb_name"],
|
| 710 |
+
device=device,
|
| 711 |
+
dtype=torch.float32,
|
| 712 |
+
num_res=num_res,
|
| 713 |
+
)
|
| 714 |
+
missing = [field for field in ["oracle_modes", "oracle_energy", "oracle_mean_disp"] if field not in oracle_targets]
|
| 715 |
+
if missing:
|
| 716 |
+
raise ValueError(
|
| 717 |
+
f"Oracle condition training requires {missing} in latent.motion_target_cache_path; "
|
| 718 |
+
"rerun base_stages/00_extract_shape_fingerprints.sh with the updated code."
|
| 719 |
+
)
|
| 720 |
+
condition = self.latent_encoder.oracle_condition_from_targets(
|
| 721 |
+
noisy_batch["trans_1"],
|
| 722 |
+
noisy_batch["trans_equilibrium"],
|
| 723 |
+
noisy_batch["rotmats_equilibrium"],
|
| 724 |
+
noisy_batch["res_mask"],
|
| 725 |
+
oracle_targets,
|
| 726 |
+
)
|
| 727 |
+
latent_metrics = {}
|
| 728 |
+
if self._diagnostic_step():
|
| 729 |
+
latent_metrics.update(self.latent_encoder.motion_metrics(condition, noisy_batch["res_mask"]))
|
| 730 |
+
coeff = condition["mode_coefficients"].detach().float()
|
| 731 |
+
centered = condition["oracle_centered_disp"].detach().float()
|
| 732 |
+
recon = condition["oracle_recon_disp"].detach().float()
|
| 733 |
+
mask = noisy_batch["res_mask"].float()[:, :, None]
|
| 734 |
+
recon_error = ((centered - recon).square() * mask).sum().sqrt()
|
| 735 |
+
recon_denom = (centered.square() * mask).sum().sqrt().clamp_min(1e-8)
|
| 736 |
+
latent_metrics.update({
|
| 737 |
+
"oracle_condition_active": noisy_batch["res_mask"].new_ones(()),
|
| 738 |
+
"oracle_coeff_abs": coeff.abs().mean(),
|
| 739 |
+
"oracle_coeff_std": coeff.std(),
|
| 740 |
+
"oracle_recon_rel_error": (recon_error / recon_denom).detach(),
|
| 741 |
+
"enm_warmup_active": noisy_batch["res_mask"].new_zeros(()),
|
| 742 |
+
})
|
| 743 |
+
motion_loss = noisy_batch["res_mask"].new_zeros(())
|
| 744 |
+
shape_baseline_error = noisy_batch["res_mask"].new_zeros(())
|
| 745 |
+
return (
|
| 746 |
+
condition,
|
| 747 |
+
torch.arange(num_batch, device=device, dtype=torch.long),
|
| 748 |
+
latent_metrics,
|
| 749 |
+
motion_loss,
|
| 750 |
+
shape_baseline_error,
|
| 751 |
+
)
|
| 752 |
+
|
| 753 |
+
def _motion_loss_weights(self):
|
| 754 |
+
training_cfg = self._exp_cfg.training
|
| 755 |
+
weights = {
|
| 756 |
+
"local_cov_loss": float(getattr(training_cfg, "lambda_local_cov", 1.0)),
|
| 757 |
+
"cross_cov_loss": float(getattr(training_cfg, "lambda_cross_cov", 1.0)),
|
| 758 |
+
"rmsf_loss": float(getattr(training_cfg, "lambda_rmsf", 0.25)),
|
| 759 |
+
}
|
| 760 |
+
lambda_pca_align = float(getattr(training_cfg, "lambda_pca_align", 0.0))
|
| 761 |
+
if lambda_pca_align > 0.0:
|
| 762 |
+
weights["pca_align_loss"] = lambda_pca_align
|
| 763 |
+
return weights
|
| 764 |
+
|
| 765 |
+
def _diagnostic_step(self):
|
| 766 |
+
interval = int(getattr(
|
| 767 |
+
self._exp_cfg.training, "diagnostic_interval_steps", 1
|
| 768 |
+
))
|
| 769 |
+
return interval > 0 and int(self.global_step) % interval == 0
|
| 770 |
+
|
| 771 |
+
def _latent_group_z(self, noisy_batch):
|
| 772 |
+
self._gen_cov_targets = None
|
| 773 |
+
if bool(getattr(self._exp_cfg.training, "oracle_condition", False)):
|
| 774 |
+
return self._oracle_group_z(noisy_batch)
|
| 775 |
+
device = noisy_batch["res_mask"].device
|
| 776 |
+
num_batch, num_res = noisy_batch["res_mask"].shape[:2]
|
| 777 |
+
prior_condition, _ = self.latent_encoder.forward_prior(
|
| 778 |
+
noisy_batch["trans_equilibrium"],
|
| 779 |
+
noisy_batch["rotmats_equilibrium"],
|
| 780 |
+
noisy_batch["seq"],
|
| 781 |
+
noisy_batch["res_mask"],
|
| 782 |
+
)
|
| 783 |
+
condition = prior_condition
|
| 784 |
+
latent_metrics = {}
|
| 785 |
+
if self._diagnostic_step():
|
| 786 |
+
latent_metrics.update(self.latent_encoder.motion_metrics(prior_condition, noisy_batch["res_mask"]))
|
| 787 |
+
shape_baseline_error = noisy_batch["res_mask"].new_zeros(())
|
| 788 |
+
motion_loss = noisy_batch["res_mask"].new_zeros(())
|
| 789 |
+
q_fit_loss = noisy_batch["res_mask"].new_zeros(())
|
| 790 |
+
mode_recon_loss = noisy_batch["res_mask"].new_zeros(())
|
| 791 |
+
mode_orth_loss = self.latent_encoder.mode_orthogonality_loss(
|
| 792 |
+
prior_condition["u_global"], noisy_batch["res_mask"]
|
| 793 |
+
)
|
| 794 |
+
motion_targets = None
|
| 795 |
+
|
| 796 |
+
enm_warmup_epochs = int(getattr(self._exp_cfg.training, "enm_warmup_epochs", 0))
|
| 797 |
+
in_enm_warmup = bool(self.motion_loss_enabled and int(self.current_epoch) < enm_warmup_epochs)
|
| 798 |
+
if in_enm_warmup:
|
| 799 |
+
loss_parts = self.latent_encoder.enm_initialization_loss(
|
| 800 |
+
prior_condition,
|
| 801 |
+
noisy_batch["trans_equilibrium"],
|
| 802 |
+
noisy_batch["res_mask"],
|
| 803 |
+
)
|
| 804 |
+
warmup_weight = float(getattr(self._exp_cfg.training, "lambda_enm_warmup", 1.0))
|
| 805 |
+
motion_loss = warmup_weight * loss_parts["enm_warmup_loss"]
|
| 806 |
+
latent_metrics.update(loss_parts)
|
| 807 |
+
latent_metrics["enm_warmup_active"] = noisy_batch["res_mask"].new_ones(())
|
| 808 |
+
else:
|
| 809 |
+
if self.motion_loss_enabled:
|
| 810 |
+
motion_targets = self._lookup_motion_targets(
|
| 811 |
+
noisy_batch["pdb_name"],
|
| 812 |
+
device=device,
|
| 813 |
+
dtype=prior_condition["local_cov_pred"].dtype,
|
| 814 |
+
num_res=num_res,
|
| 815 |
+
)
|
| 816 |
+
self._gen_cov_targets = motion_targets
|
| 817 |
+
with torch.autocast(device_type=device.type, enabled=False):
|
| 818 |
+
spatial_dists = self._equilibrium_spatial_dists(
|
| 819 |
+
noisy_batch["pdb_name"],
|
| 820 |
+
noisy_batch["trans_equilibrium"].float(),
|
| 821 |
+
)
|
| 822 |
+
loss_parts = self.latent_encoder.motion_recon_loss(
|
| 823 |
+
prior_condition,
|
| 824 |
+
motion_targets,
|
| 825 |
+
noisy_batch["res_mask"],
|
| 826 |
+
spatial_dists=spatial_dists,
|
| 827 |
+
)
|
| 828 |
+
weights = self._motion_loss_weights()
|
| 829 |
+
motion_loss = sum(weight * loss_parts[name] for name, weight in weights.items())
|
| 830 |
+
latent_metrics.update(loss_parts)
|
| 831 |
+
if self._diagnostic_step():
|
| 832 |
+
latent_metrics.update(self.latent_encoder.motion_alignment_metrics(
|
| 833 |
+
prior_condition,
|
| 834 |
+
motion_targets,
|
| 835 |
+
noisy_batch["res_mask"],
|
| 836 |
+
spatial_dists,
|
| 837 |
+
))
|
| 838 |
+
latent_metrics["enm_warmup_active"] = noisy_batch["res_mask"].new_zeros(())
|
| 839 |
+
|
| 840 |
+
if bool(getattr(self._exp_cfg.training, "per_frame_coeff_condition", False)):
|
| 841 |
+
mean_disp = None if motion_targets is None else motion_targets.get("oracle_mean_disp")
|
| 842 |
+
condition, coeff_target = self.latent_encoder.frame_condition_from_projection(
|
| 843 |
+
noisy_batch["trans_1"],
|
| 844 |
+
noisy_batch["trans_equilibrium"],
|
| 845 |
+
noisy_batch["rotmats_equilibrium"],
|
| 846 |
+
noisy_batch["res_mask"],
|
| 847 |
+
prior_condition,
|
| 848 |
+
mean_disp=mean_disp,
|
| 849 |
+
)
|
| 850 |
+
q_fit_loss = self.latent_encoder.mixture_nll(prior_condition, coeff_target.detach())
|
| 851 |
+
mode_recon_loss = condition["projection_recon_loss"].float().mean()
|
| 852 |
+
centered_recon = condition["projection_recon_rel_error"].detach().float().mean()
|
| 853 |
+
latent_metrics.update({
|
| 854 |
+
"mode_recon_loss": mode_recon_loss.detach(),
|
| 855 |
+
"q_nll_loss": q_fit_loss.detach(),
|
| 856 |
+
"q_nll_per_dim": q_fit_loss.detach() / float(self.latent_encoder.num_modes),
|
| 857 |
+
"mode_coeff_abs": coeff_target.detach().float().abs().mean(),
|
| 858 |
+
"mode_coeff_std": coeff_target.detach().float().std(),
|
| 859 |
+
"mode_recon_rel_error": centered_recon,
|
| 860 |
+
"mode_recon_centered_rel_error": centered_recon,
|
| 861 |
+
"mode_recon_uncentered_rel_error": condition[
|
| 862 |
+
"projection_uncentered_recon_rel_error"
|
| 863 |
+
].detach().float().mean(),
|
| 864 |
+
})
|
| 865 |
+
if self._diagnostic_step():
|
| 866 |
+
gram_metrics = self.latent_encoder.mode_gram_diagnostics(
|
| 867 |
+
prior_condition["u_global"], noisy_batch["res_mask"]
|
| 868 |
+
)
|
| 869 |
+
latent_metrics.update({
|
| 870 |
+
"mode_gram_min_eig": gram_metrics["mode_gram_min_eig"].detach().float().mean(),
|
| 871 |
+
"mode_gram_condition": gram_metrics["mode_gram_condition"].detach().float().mean(),
|
| 872 |
+
"mode_max_cosine_abs": gram_metrics["mode_max_cosine_abs"].detach().float().mean(),
|
| 873 |
+
})
|
| 874 |
+
|
| 875 |
+
lambda_motion = float(getattr(self._exp_cfg.training, "lambda_motion", 1.0))
|
| 876 |
+
lambda_q = float(getattr(self._exp_cfg.training, "lambda_q", 1.0))
|
| 877 |
+
lambda_mode_orth = float(getattr(self._exp_cfg.training, "lambda_mode_orth", 0.0))
|
| 878 |
+
lambda_mode_recon = float(getattr(self._exp_cfg.training, "lambda_mode_recon", 0.0))
|
| 879 |
+
latent_regularizer = (
|
| 880 |
+
lambda_motion * motion_loss
|
| 881 |
+
+ lambda_q * q_fit_loss
|
| 882 |
+
+ lambda_mode_orth * mode_orth_loss
|
| 883 |
+
+ lambda_mode_recon * mode_recon_loss
|
| 884 |
+
)
|
| 885 |
+
latent_metrics["motion_loss"] = motion_loss.detach()
|
| 886 |
+
latent_metrics["mode_orth_loss"] = mode_orth_loss.detach()
|
| 887 |
+
latent_metrics["mode_recon_loss"] = mode_recon_loss.detach()
|
| 888 |
+
latent_metrics["latent_regularizer_loss"] = latent_regularizer.detach()
|
| 889 |
+
return (
|
| 890 |
+
condition,
|
| 891 |
+
torch.arange(num_batch, device=device, dtype=torch.long),
|
| 892 |
+
latent_metrics,
|
| 893 |
+
latent_regularizer,
|
| 894 |
+
shape_baseline_error,
|
| 895 |
+
)
|
| 896 |
+
|
| 897 |
+
@staticmethod
|
| 898 |
+
def _condition_with_scale(condition, scale):
|
| 899 |
+
if not isinstance(condition, dict):
|
| 900 |
+
return condition * scale
|
| 901 |
+
out = {}
|
| 902 |
+
for key, value in condition.items():
|
| 903 |
+
if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}:
|
| 904 |
+
out[key] = value * scale
|
| 905 |
+
else:
|
| 906 |
+
out[key] = value
|
| 907 |
+
return out
|
| 908 |
+
|
| 909 |
+
def _condition_cycle_loss(self, noisy_batch, model_output, condition):
|
| 910 |
+
lambda_cycle = float(getattr(self._exp_cfg.training, "lambda_condition_cycle", 0.0))
|
| 911 |
+
zero = model_output["pred_trans"].new_zeros(())
|
| 912 |
+
if lambda_cycle == 0.0 or condition is None or not isinstance(condition, dict):
|
| 913 |
+
return zero, {}
|
| 914 |
+
required = {"mode_coefficients", "u_global", "projection_mean_disp"}
|
| 915 |
+
if any(key not in condition for key in required):
|
| 916 |
+
return zero, {}
|
| 917 |
+
|
| 918 |
+
device = model_output["pred_trans"].device
|
| 919 |
+
with torch.autocast(device_type=device.type, enabled=False):
|
| 920 |
+
pred_trans = model_output["pred_trans"].float()
|
| 921 |
+
trans_eq = noisy_batch["trans_equilibrium"].to(device=device, dtype=torch.float32)
|
| 922 |
+
res_mask = noisy_batch["res_mask"].to(device=device, dtype=torch.float32)
|
| 923 |
+
mean_disp = condition["projection_mean_disp"].to(device=device, dtype=torch.float32).detach()
|
| 924 |
+
modes = condition["u_global"].to(device=device, dtype=torch.float32).detach()
|
| 925 |
+
target_coeff = condition["mode_coefficients"].to(device=device, dtype=torch.float32).detach()
|
| 926 |
+
|
| 927 |
+
pred_disp = self.latent_encoder.relative_displacement(
|
| 928 |
+
pred_trans,
|
| 929 |
+
trans_eq,
|
| 930 |
+
res_mask,
|
| 931 |
+
)
|
| 932 |
+
pred_centered = pred_disp - mean_disp
|
| 933 |
+
pred_coeff = self.latent_encoder.project_displacement_lstsq(
|
| 934 |
+
pred_centered,
|
| 935 |
+
modes,
|
| 936 |
+
res_mask,
|
| 937 |
+
ridge=float(getattr(self.latent_encoder, "q_lstsq_ridge", 1e-4)),
|
| 938 |
+
detach_modes=True,
|
| 939 |
+
)
|
| 940 |
+
diff = pred_coeff - target_coeff
|
| 941 |
+
denom = target_coeff.norm(dim=-1).clamp_min(1e-8)
|
| 942 |
+
rel_error = diff.norm(dim=-1) / denom
|
| 943 |
+
raw_loss = rel_error.mean()
|
| 944 |
+
cosine = torch.nn.functional.cosine_similarity(
|
| 945 |
+
pred_coeff,
|
| 946 |
+
target_coeff,
|
| 947 |
+
dim=-1,
|
| 948 |
+
eps=1e-8,
|
| 949 |
+
).mean()
|
| 950 |
+
|
| 951 |
+
weighted_loss = lambda_cycle * raw_loss
|
| 952 |
+
metrics = {
|
| 953 |
+
"condition_cycle_loss": raw_loss.detach(),
|
| 954 |
+
"condition_cycle_weighted_loss": weighted_loss.detach(),
|
| 955 |
+
"condition_cycle_rel_error": rel_error.detach().mean(),
|
| 956 |
+
"condition_cycle_cosine": cosine.detach(),
|
| 957 |
+
}
|
| 958 |
+
return weighted_loss, metrics
|
| 959 |
+
|
| 960 |
+
def _initial_generator_response_teacher(self):
|
| 961 |
+
if not hasattr(self, "_gen_response_teacher_model"):
|
| 962 |
+
self._gen_response_teacher_model = None
|
| 963 |
+
if self._gen_response_teacher_model is None:
|
| 964 |
+
teacher = copy.deepcopy(self.model)
|
| 965 |
+
teacher.eval()
|
| 966 |
+
for param in teacher.parameters():
|
| 967 |
+
param.requires_grad_(False)
|
| 968 |
+
self._gen_response_teacher_model = teacher
|
| 969 |
+
return self._gen_response_teacher_model
|
| 970 |
+
|
| 971 |
+
def _generator_response_cov_loss(self, noisy_batch, condition):
|
| 972 |
+
"""Train generator response shape without rewarding global expansion.
|
| 973 |
+
|
| 974 |
+
v2 samples multiple antithetic coefficient perturbations, computes the
|
| 975 |
+
generator's central-difference responses, and matches only the
|
| 976 |
+
trace-normalized response covariance shape to MD targets. A weak optional
|
| 977 |
+
frozen-initial teacher trace anchor keeps response amplitude near the
|
| 978 |
+
A30/start checkpoint under the same ``t`` and coefficient perturbations.
|
| 979 |
+
"""
|
| 980 |
+
lambda_gen = float(getattr(self._exp_cfg.training, "lambda_generator_cov", 0.0))
|
| 981 |
+
zero = noisy_batch["res_mask"].new_zeros(())
|
| 982 |
+
if lambda_gen == 0.0 or condition is None or not isinstance(condition, dict):
|
| 983 |
+
return zero, {}
|
| 984 |
+
targets = getattr(self, "_gen_cov_targets", None)
|
| 985 |
+
if targets is None or "local_cov" not in targets or "rmsf" not in targets:
|
| 986 |
+
return zero, {}
|
| 987 |
+
required = ("u_global", "mixture_logits", "mixture_mu", "mixture_scale_tril")
|
| 988 |
+
if any(key not in condition for key in required):
|
| 989 |
+
return zero, {}
|
| 990 |
+
use_cross = bool(getattr(self._exp_cfg.training, "generator_cov_use_cross", False))
|
| 991 |
+
if use_cross and "cross_cov" not in targets:
|
| 992 |
+
use_cross = False
|
| 993 |
+
|
| 994 |
+
# t = 1 is clean, t = 0 is pure noise; mid-high noise is low-to-mid t.
|
| 995 |
+
t_min = float(getattr(self._exp_cfg.training, "generator_cov_t_min", 0.1))
|
| 996 |
+
t_max = float(getattr(self._exp_cfg.training, "generator_cov_t_max", 0.6))
|
| 997 |
+
t_vec = torch.squeeze(noisy_batch["t"]).reshape(-1).float()
|
| 998 |
+
sample_weight = ((t_vec >= t_min) & (t_vec <= t_max)).to(dtype=t_vec.dtype)
|
| 999 |
+
|
| 1000 |
+
scale = float(getattr(self._exp_cfg.training, "generator_cov_delta_scale", 1.0))
|
| 1001 |
+
num_deltas = int(getattr(self._exp_cfg.training, "generator_cov_num_deltas", 2))
|
| 1002 |
+
num_deltas = max(num_deltas, 2)
|
| 1003 |
+
student_chunk_deltas = int(
|
| 1004 |
+
getattr(self._exp_cfg.training, "generator_cov_student_chunk_deltas", 1)
|
| 1005 |
+
)
|
| 1006 |
+
student_chunk_deltas = max(1, min(student_chunk_deltas, num_deltas))
|
| 1007 |
+
teacher_anchor = bool(getattr(self._exp_cfg.training, "generator_cov_initial_trace_anchor", True))
|
| 1008 |
+
teacher_num_deltas = int(getattr(self._exp_cfg.training, "generator_cov_teacher_num_deltas", 1))
|
| 1009 |
+
teacher_num_deltas = max(1, min(teacher_num_deltas, num_deltas))
|
| 1010 |
+
teacher_reuse_student_delta = bool(
|
| 1011 |
+
getattr(self._exp_cfg.training, "generator_cov_teacher_reuse_student_delta", True)
|
| 1012 |
+
)
|
| 1013 |
+
teacher_trace_denominator = str(
|
| 1014 |
+
getattr(self._exp_cfg.training, "generator_cov_teacher_trace_denominator", "teacher")
|
| 1015 |
+
)
|
| 1016 |
+
# "md_trace" (default) anchors the response magnitude to the cached MD trace.
|
| 1017 |
+
# "teacher_trace" is retained only for reproducing the old runs: the frozen teacher
|
| 1018 |
+
# is copied at step 0 with zero-initialized condition adapters, so its response to c
|
| 1019 |
+
# is identically zero and the anchor collapses the student's response to zero.
|
| 1020 |
+
amplitude_anchor = str(
|
| 1021 |
+
getattr(self._exp_cfg.training, "generator_cov_amplitude_anchor", "md_trace")
|
| 1022 |
+
)
|
| 1023 |
+
rollout_enabled = bool(
|
| 1024 |
+
getattr(self._exp_cfg.training, "generator_cov_rollout_calibration", False)
|
| 1025 |
+
)
|
| 1026 |
+
if rollout_enabled and amplitude_anchor == "md_trace":
|
| 1027 |
+
amplitude_anchor = "rollout_trace"
|
| 1028 |
+
if not teacher_anchor:
|
| 1029 |
+
amplitude_anchor = "none"
|
| 1030 |
+
use_teacher = amplitude_anchor == "teacher_trace"
|
| 1031 |
+
cached_teacher_trace = targets.get("gen_response_trace_anchor") if use_teacher else None
|
| 1032 |
+
teacher_model = (
|
| 1033 |
+
self._initial_generator_response_teacher()
|
| 1034 |
+
if use_teacher and cached_teacher_trace is None
|
| 1035 |
+
else None
|
| 1036 |
+
)
|
| 1037 |
+
with torch.autocast(device_type=noisy_batch["res_mask"].device.type, enabled=False):
|
| 1038 |
+
logits = condition["mixture_logits"].detach().float()
|
| 1039 |
+
mu = condition["mixture_mu"].detach().float()
|
| 1040 |
+
probs = torch.softmax(logits, dim=-1)
|
| 1041 |
+
mu_bar = torch.einsum("bm,bmk->bk", probs, mu)
|
| 1042 |
+
|
| 1043 |
+
u_global = condition["u_global"].detach()
|
| 1044 |
+
rotmats_eq = noisy_batch["rotmats_equilibrium"]
|
| 1045 |
+
res_mask = noisy_batch["res_mask"]
|
| 1046 |
+
def _concat_conditions(conditions):
|
| 1047 |
+
out = {}
|
| 1048 |
+
keys = conditions[0].keys()
|
| 1049 |
+
local_batch_size = None
|
| 1050 |
+
for value in conditions[0].values():
|
| 1051 |
+
if torch.is_tensor(value) and value.dim() > 0:
|
| 1052 |
+
local_batch_size = value.shape[0]
|
| 1053 |
+
break
|
| 1054 |
+
for key in keys:
|
| 1055 |
+
value = conditions[0][key]
|
| 1056 |
+
if (
|
| 1057 |
+
local_batch_size is not None
|
| 1058 |
+
and torch.is_tensor(value)
|
| 1059 |
+
and value.shape[:1] == (local_batch_size,)
|
| 1060 |
+
):
|
| 1061 |
+
out[key] = torch.cat([cond[key] for cond in conditions], dim=0)
|
| 1062 |
+
else:
|
| 1063 |
+
out[key] = value
|
| 1064 |
+
return out
|
| 1065 |
+
|
| 1066 |
+
def _expand_batch(batch, repeats):
|
| 1067 |
+
out = {}
|
| 1068 |
+
local_batch_size = batch["res_mask"].shape[0]
|
| 1069 |
+
for key, value in batch.items():
|
| 1070 |
+
if key == "z":
|
| 1071 |
+
continue
|
| 1072 |
+
if torch.is_tensor(value) and value.shape[:1] == (local_batch_size,):
|
| 1073 |
+
out[key] = torch.cat([value for _ in range(repeats)], dim=0)
|
| 1074 |
+
elif isinstance(value, (list, tuple)) and len(value) == local_batch_size:
|
| 1075 |
+
out[key] = list(value) * repeats
|
| 1076 |
+
else:
|
| 1077 |
+
out[key] = value
|
| 1078 |
+
return out
|
| 1079 |
+
|
| 1080 |
+
use_checkpoint = bool(getattr(self._exp_cfg.training, "generator_cov_checkpoint", True))
|
| 1081 |
+
trans_eq = noisy_batch["trans_equilibrium"]
|
| 1082 |
+
conditions = []
|
| 1083 |
+
for _ in range(num_deltas):
|
| 1084 |
+
c_sample, _ = self.latent_encoder.sample_coefficients_from_q(condition)
|
| 1085 |
+
c_sample = c_sample.detach().float()
|
| 1086 |
+
delta = (c_sample - mu_bar) * scale
|
| 1087 |
+
c_plus = mu_bar + delta
|
| 1088 |
+
c_minus = mu_bar - delta
|
| 1089 |
+
cond_plus = self.latent_encoder.condition_from_mode_coefficients(
|
| 1090 |
+
u_global, c_plus, rotmats_eq, res_mask, include_statistics=False
|
| 1091 |
+
)
|
| 1092 |
+
cond_minus = self.latent_encoder.condition_from_mode_coefficients(
|
| 1093 |
+
u_global, c_minus, rotmats_eq, res_mask, include_statistics=False
|
| 1094 |
+
)
|
| 1095 |
+
conditions.extend([cond_plus, cond_minus])
|
| 1096 |
+
|
| 1097 |
+
batch_size = res_mask.shape[0]
|
| 1098 |
+
response_chunks = []
|
| 1099 |
+
for start_delta in range(0, num_deltas, student_chunk_deltas):
|
| 1100 |
+
end_delta = min(num_deltas, start_delta + student_chunk_deltas)
|
| 1101 |
+
chunk_conditions = conditions[2 * start_delta : 2 * end_delta]
|
| 1102 |
+
chunk_num_deltas = end_delta - start_delta
|
| 1103 |
+
merged_condition = _concat_conditions(chunk_conditions)
|
| 1104 |
+
merged_batch = _expand_batch(noisy_batch, repeats=len(chunk_conditions))
|
| 1105 |
+
merged_batch["z"] = merged_condition
|
| 1106 |
+
|
| 1107 |
+
def _pred_trans_merged(z_cond):
|
| 1108 |
+
probe_batch = dict(merged_batch)
|
| 1109 |
+
probe_batch["z"] = z_cond
|
| 1110 |
+
return self.model(probe_batch)["pred_trans"]
|
| 1111 |
+
|
| 1112 |
+
if use_checkpoint:
|
| 1113 |
+
pred_merged = torch.utils.checkpoint.checkpoint(
|
| 1114 |
+
_pred_trans_merged, merged_condition, use_reentrant=False
|
| 1115 |
+
)
|
| 1116 |
+
else:
|
| 1117 |
+
pred_merged = _pred_trans_merged(merged_condition)
|
| 1118 |
+
|
| 1119 |
+
pred_merged = pred_merged.reshape(
|
| 1120 |
+
chunk_num_deltas, 2, batch_size, *pred_merged.shape[1:]
|
| 1121 |
+
)
|
| 1122 |
+
pred_plus = pred_merged[:, 0].reshape(
|
| 1123 |
+
chunk_num_deltas * batch_size, *pred_merged.shape[3:]
|
| 1124 |
+
)
|
| 1125 |
+
pred_minus = pred_merged[:, 1].reshape(
|
| 1126 |
+
chunk_num_deltas * batch_size, *pred_merged.shape[3:]
|
| 1127 |
+
)
|
| 1128 |
+
trans_eq_rep = trans_eq[None].expand(
|
| 1129 |
+
chunk_num_deltas, -1, -1, -1
|
| 1130 |
+
).reshape(chunk_num_deltas * batch_size, *trans_eq.shape[1:])
|
| 1131 |
+
res_mask_rep = res_mask[None].expand(
|
| 1132 |
+
chunk_num_deltas, -1, -1
|
| 1133 |
+
).reshape(chunk_num_deltas * batch_size, *res_mask.shape[1:])
|
| 1134 |
+
disp_plus = self.latent_encoder.relative_displacement(
|
| 1135 |
+
pred_plus.float(), trans_eq_rep.float(), res_mask_rep
|
| 1136 |
+
)
|
| 1137 |
+
disp_minus = self.latent_encoder.relative_displacement(
|
| 1138 |
+
pred_minus.float(), trans_eq_rep.float(), res_mask_rep
|
| 1139 |
+
)
|
| 1140 |
+
chunk_response = 0.5 * (disp_plus - disp_minus)
|
| 1141 |
+
chunk_response = chunk_response.reshape(
|
| 1142 |
+
chunk_num_deltas, batch_size, *chunk_response.shape[1:]
|
| 1143 |
+
)
|
| 1144 |
+
response_chunks.append(chunk_response)
|
| 1145 |
+
response_deltas = torch.cat(response_chunks, dim=0)
|
| 1146 |
+
|
| 1147 |
+
def _response_trace(response, mask_value):
|
| 1148 |
+
resp = response.float()
|
| 1149 |
+
if resp.dim() == 3:
|
| 1150 |
+
resp = resp[None]
|
| 1151 |
+
resp = resp * mask_value[None, :, :, None].float()
|
| 1152 |
+
local = torch.einsum("sbni,sbnj->bnij", resp, resp) / float(resp.shape[0])
|
| 1153 |
+
return (
|
| 1154 |
+
torch.diagonal(local, dim1=-2, dim2=-1).sum(dim=-1)
|
| 1155 |
+
* mask_value.float()
|
| 1156 |
+
).sum(dim=-1).clamp_min(1e-8)
|
| 1157 |
+
|
| 1158 |
+
def _trim_residue_dims(value, max_res):
|
| 1159 |
+
if not torch.is_tensor(value):
|
| 1160 |
+
return value
|
| 1161 |
+
if value.dim() >= 2 and value.shape[1] == res_mask.shape[1]:
|
| 1162 |
+
value = value[:, :max_res, ...]
|
| 1163 |
+
if value.dim() >= 3 and value.shape[2] == res_mask.shape[1]:
|
| 1164 |
+
value = value[:, :, :max_res, ...]
|
| 1165 |
+
return value
|
| 1166 |
+
|
| 1167 |
+
def _index_first_dim(value, example_idx, max_res=None):
|
| 1168 |
+
if torch.is_tensor(value) and value.shape[:1] == (batch_size,):
|
| 1169 |
+
value = value.index_select(0, example_idx)
|
| 1170 |
+
if max_res is not None:
|
| 1171 |
+
value = _trim_residue_dims(value, max_res)
|
| 1172 |
+
return value
|
| 1173 |
+
if isinstance(value, (list, tuple)) and len(value) == batch_size:
|
| 1174 |
+
return [value[int(i)] for i in example_idx.detach().cpu().tolist()]
|
| 1175 |
+
return value
|
| 1176 |
+
|
| 1177 |
+
def _slice_condition(cond, example_idx, max_res=None):
|
| 1178 |
+
out = {}
|
| 1179 |
+
for key, value in cond.items():
|
| 1180 |
+
out[key] = _index_first_dim(value, example_idx, max_res=max_res)
|
| 1181 |
+
return out
|
| 1182 |
+
|
| 1183 |
+
def _slice_batch(batch, example_idx, max_res=None):
|
| 1184 |
+
out = {}
|
| 1185 |
+
for key, value in batch.items():
|
| 1186 |
+
if key == "z":
|
| 1187 |
+
continue
|
| 1188 |
+
out[key] = _index_first_dim(value, example_idx, max_res=max_res)
|
| 1189 |
+
return out
|
| 1190 |
+
|
| 1191 |
+
def _rollout_final_pred_trans(probe_batch, steps):
|
| 1192 |
+
# Faithful mirror of the real inference sampler (interpolant_bbflow.sample):
|
| 1193 |
+
# the caller has already placed the SHARED prior-noise x0 into
|
| 1194 |
+
# trans_t/rotmats_t. Integrate the full linspace(min_t, 1, steps+1) grid
|
| 1195 |
+
# with the exact euler steps inference uses (scalar t_1/d_t), then return
|
| 1196 |
+
# the final clean pred_trans. This is what makes T_full the real-sampler
|
| 1197 |
+
# c-response instead of a coarse t->1 continuation of the training state.
|
| 1198 |
+
rollout_batch = dict(probe_batch)
|
| 1199 |
+
rollout_batch.pop("trans_sc", None)
|
| 1200 |
+
rollout_batch["_embedder_static"] = self.model.prepare_inference_static(rollout_batch)
|
| 1201 |
+
trans_current = rollout_batch["trans_t"]
|
| 1202 |
+
rotmats_current = rollout_batch["rotmats_t"]
|
| 1203 |
+
n = trans_current.shape[0]
|
| 1204 |
+
device = trans_current.device
|
| 1205 |
+
min_t = float(getattr(self._interpolant_cfg, "min_t", 1e-2))
|
| 1206 |
+
ts = torch.linspace(min_t, 1.0, int(steps) + 1, device=device)
|
| 1207 |
+
was_training = self.model.training
|
| 1208 |
+
self.model.eval()
|
| 1209 |
+
try:
|
| 1210 |
+
t_1 = ts[0]
|
| 1211 |
+
for t_2 in ts[1:]:
|
| 1212 |
+
rollout_batch["trans_t"] = trans_current
|
| 1213 |
+
rollout_batch["rotmats_t"] = rotmats_current
|
| 1214 |
+
rollout_batch["t"] = torch.ones((n, 1), device=device) * t_1
|
| 1215 |
+
model_out = self.model(rollout_batch)
|
| 1216 |
+
pred_trans_1 = model_out["pred_trans"]
|
| 1217 |
+
pred_rotmats_1 = model_out["pred_rotmats"]
|
| 1218 |
+
if self._interpolant_cfg.self_condition:
|
| 1219 |
+
rollout_batch["trans_sc"] = pred_trans_1.detach()
|
| 1220 |
+
d_t = t_2 - t_1
|
| 1221 |
+
trans_current = self.interpolant._trans_euler_step(
|
| 1222 |
+
d_t, t_1, pred_trans_1, trans_current
|
| 1223 |
+
)
|
| 1224 |
+
rotmats_current = self.interpolant._rots_euler_step(
|
| 1225 |
+
d_t, t_1, pred_rotmats_1, rotmats_current
|
| 1226 |
+
)
|
| 1227 |
+
t_1 = t_2
|
| 1228 |
+
rollout_batch["trans_t"] = trans_current
|
| 1229 |
+
rollout_batch["rotmats_t"] = rotmats_current
|
| 1230 |
+
rollout_batch["t"] = torch.ones((n, 1), device=device) * ts[-1]
|
| 1231 |
+
model_out = self.model(rollout_batch)
|
| 1232 |
+
return model_out["pred_trans"]
|
| 1233 |
+
finally:
|
| 1234 |
+
self.model.train(was_training)
|
| 1235 |
+
|
| 1236 |
+
rollout_metrics = {}
|
| 1237 |
+
trace_target_scale = None
|
| 1238 |
+
if rollout_enabled:
|
| 1239 |
+
rollout_interval = int(
|
| 1240 |
+
getattr(self._exp_cfg.training, "generator_cov_rollout_interval_steps", 200)
|
| 1241 |
+
)
|
| 1242 |
+
rollout_interval = max(1, rollout_interval)
|
| 1243 |
+
should_measure = (
|
| 1244 |
+
self._gen_cov_rollout_trace_ratio_ema is None
|
| 1245 |
+
or int(getattr(self, "global_step", 0)) % rollout_interval == 0
|
| 1246 |
+
)
|
| 1247 |
+
if should_measure:
|
| 1248 |
+
# Default matches inference resolution (num_timesteps=20). This is a
|
| 1249 |
+
# no_grad forward-only measurement on a few proteins once per interval,
|
| 1250 |
+
# so there is no reason to under-resolve it; a coarse 2-step rollout
|
| 1251 |
+
# gives a systematically wrong amplification G.
|
| 1252 |
+
rollout_steps = int(
|
| 1253 |
+
getattr(self._exp_cfg.training, "generator_cov_rollout_steps", 20)
|
| 1254 |
+
)
|
| 1255 |
+
rollout_steps = max(1, rollout_steps)
|
| 1256 |
+
rollout_num_deltas = int(
|
| 1257 |
+
getattr(self._exp_cfg.training, "generator_cov_rollout_num_deltas", 1)
|
| 1258 |
+
)
|
| 1259 |
+
rollout_num_deltas = max(1, min(rollout_num_deltas, num_deltas))
|
| 1260 |
+
rollout_max_examples = int(
|
| 1261 |
+
getattr(self._exp_cfg.training, "generator_cov_rollout_max_examples", 4)
|
| 1262 |
+
)
|
| 1263 |
+
rollout_max_examples = max(1, min(rollout_max_examples, batch_size))
|
| 1264 |
+
example_idx = torch.arange(
|
| 1265 |
+
rollout_max_examples,
|
| 1266 |
+
device=res_mask.device,
|
| 1267 |
+
dtype=torch.long,
|
| 1268 |
+
)
|
| 1269 |
+
selected_mask = res_mask.index_select(0, example_idx)
|
| 1270 |
+
selected_lengths = selected_mask.float().sum(dim=-1)
|
| 1271 |
+
rollout_max_res = int(selected_lengths.max().detach().cpu().item())
|
| 1272 |
+
rollout_max_res = max(1, min(rollout_max_res, res_mask.shape[1]))
|
| 1273 |
+
with torch.inference_mode():
|
| 1274 |
+
rollout_conditions = [
|
| 1275 |
+
_slice_condition(cond, example_idx, max_res=rollout_max_res)
|
| 1276 |
+
for cond in conditions[: 2 * rollout_num_deltas]
|
| 1277 |
+
]
|
| 1278 |
+
rollout_condition = _concat_conditions(rollout_conditions)
|
| 1279 |
+
rollout_base_batch = _slice_batch(
|
| 1280 |
+
noisy_batch,
|
| 1281 |
+
example_idx,
|
| 1282 |
+
max_res=rollout_max_res,
|
| 1283 |
+
)
|
| 1284 |
+
# Start T_full from SHARED prior noise x0 (the real inference
|
| 1285 |
+
# start), NOT from the training-time trans_t. trans_t is anchored
|
| 1286 |
+
# to the ground-truth frame (corrupt_batch interpolates noise<->x_1),
|
| 1287 |
+
# so rolling from it measures the c-response near the true frame,
|
| 1288 |
+
# not the free-sampling response inference actually produces.
|
| 1289 |
+
# Sampling x0 on the sliced base (before expand) makes +delta and
|
| 1290 |
+
# -delta of the same example share the same x0 (supplement 1).
|
| 1291 |
+
r_trans0, r_rotmats0 = self.interpolant.sample_from_prior(
|
| 1292 |
+
rollout_max_examples,
|
| 1293 |
+
rollout_max_res,
|
| 1294 |
+
rollout_base_batch["trans_equilibrium"],
|
| 1295 |
+
rollout_base_batch["rotmats_equilibrium"],
|
| 1296 |
+
)
|
| 1297 |
+
rollout_base_batch = dict(rollout_base_batch)
|
| 1298 |
+
rollout_base_batch["trans_t"] = r_trans0
|
| 1299 |
+
rollout_base_batch["rotmats_t"] = r_rotmats0
|
| 1300 |
+
rollout_batch = _expand_batch(
|
| 1301 |
+
rollout_base_batch,
|
| 1302 |
+
repeats=len(rollout_conditions),
|
| 1303 |
+
)
|
| 1304 |
+
rollout_batch["z"] = rollout_condition
|
| 1305 |
+
rollout_pred = _rollout_final_pred_trans(rollout_batch, rollout_steps)
|
| 1306 |
+
rollout_pred = rollout_pred.reshape(
|
| 1307 |
+
rollout_num_deltas, 2, rollout_max_examples, *rollout_pred.shape[1:]
|
| 1308 |
+
)
|
| 1309 |
+
rollout_plus = rollout_pred[:, 0].reshape(
|
| 1310 |
+
rollout_num_deltas * rollout_max_examples,
|
| 1311 |
+
*rollout_pred.shape[3:],
|
| 1312 |
+
)
|
| 1313 |
+
rollout_minus = rollout_pred[:, 1].reshape(
|
| 1314 |
+
rollout_num_deltas * rollout_max_examples,
|
| 1315 |
+
*rollout_pred.shape[3:],
|
| 1316 |
+
)
|
| 1317 |
+
rollout_trans_eq = trans_eq.index_select(0, example_idx)
|
| 1318 |
+
rollout_trans_eq = rollout_trans_eq[:, :rollout_max_res, :]
|
| 1319 |
+
rollout_res_mask = res_mask.index_select(0, example_idx)[:, :rollout_max_res]
|
| 1320 |
+
rollout_trans_eq_rep = rollout_trans_eq[None].expand(
|
| 1321 |
+
rollout_num_deltas, -1, -1, -1
|
| 1322 |
+
).reshape(
|
| 1323 |
+
rollout_num_deltas * rollout_max_examples,
|
| 1324 |
+
*rollout_trans_eq.shape[1:],
|
| 1325 |
+
)
|
| 1326 |
+
rollout_res_mask_rep = rollout_res_mask[None].expand(
|
| 1327 |
+
rollout_num_deltas, -1, -1
|
| 1328 |
+
).reshape(
|
| 1329 |
+
rollout_num_deltas * rollout_max_examples,
|
| 1330 |
+
*rollout_res_mask.shape[1:],
|
| 1331 |
+
)
|
| 1332 |
+
rollout_disp_plus = self.latent_encoder.relative_displacement(
|
| 1333 |
+
rollout_plus.float(),
|
| 1334 |
+
rollout_trans_eq_rep.float(),
|
| 1335 |
+
rollout_res_mask_rep,
|
| 1336 |
+
)
|
| 1337 |
+
rollout_disp_minus = self.latent_encoder.relative_displacement(
|
| 1338 |
+
rollout_minus.float(),
|
| 1339 |
+
rollout_trans_eq_rep.float(),
|
| 1340 |
+
rollout_res_mask_rep,
|
| 1341 |
+
)
|
| 1342 |
+
rollout_response = 0.5 * (rollout_disp_plus - rollout_disp_minus)
|
| 1343 |
+
rollout_response = rollout_response.reshape(
|
| 1344 |
+
rollout_num_deltas,
|
| 1345 |
+
rollout_max_examples,
|
| 1346 |
+
*rollout_response.shape[1:],
|
| 1347 |
+
)
|
| 1348 |
+
rollout_weight = sample_weight.index_select(0, example_idx)
|
| 1349 |
+
rollout_mask = rollout_res_mask.float() * rollout_weight[:, None].float()
|
| 1350 |
+
one_step_trace = _response_trace(
|
| 1351 |
+
response_deltas[:rollout_num_deltas].index_select(1, example_idx),
|
| 1352 |
+
rollout_mask,
|
| 1353 |
+
)
|
| 1354 |
+
rollout_trace = _response_trace(rollout_response, rollout_mask)
|
| 1355 |
+
valid = (rollout_mask.sum(dim=-1) > 0).float()
|
| 1356 |
+
trace_ratio = (rollout_trace / one_step_trace).clamp_min(1e-8)
|
| 1357 |
+
ratio_num = (trace_ratio * valid).sum()
|
| 1358 |
+
ratio_den = valid.sum()
|
| 1359 |
+
if dist.is_available() and dist.is_initialized():
|
| 1360 |
+
ratio_num = ratio_num.detach().clone()
|
| 1361 |
+
ratio_den = ratio_den.detach().clone()
|
| 1362 |
+
dist.all_reduce(ratio_num, op=dist.ReduceOp.SUM)
|
| 1363 |
+
dist.all_reduce(ratio_den, op=dist.ReduceOp.SUM)
|
| 1364 |
+
if ratio_den.detach().item() > 0:
|
| 1365 |
+
ratio_value = ratio_num / ratio_den.clamp_min(1.0)
|
| 1366 |
+
ema_decay = float(
|
| 1367 |
+
getattr(self._exp_cfg.training, "generator_cov_rollout_ema_decay", 0.9)
|
| 1368 |
+
)
|
| 1369 |
+
ema_decay = min(max(ema_decay, 0.0), 0.999)
|
| 1370 |
+
if self._gen_cov_rollout_trace_ratio_ema is None:
|
| 1371 |
+
self._gen_cov_rollout_trace_ratio_ema = ratio_value.detach()
|
| 1372 |
+
else:
|
| 1373 |
+
self._gen_cov_rollout_trace_ratio_ema = (
|
| 1374 |
+
ema_decay * self._gen_cov_rollout_trace_ratio_ema.to(ratio_value.device)
|
| 1375 |
+
+ (1.0 - ema_decay) * ratio_value.detach()
|
| 1376 |
+
)
|
| 1377 |
+
rollout_metrics["gen_rollout_trace_ratio"] = ratio_value.detach()
|
| 1378 |
+
rollout_metrics["gen_rollout_trace_measured"] = ratio_value.new_tensor(1.0)
|
| 1379 |
+
rollout_metrics["gen_rollout_trace_steps"] = ratio_value.new_tensor(
|
| 1380 |
+
float(rollout_steps)
|
| 1381 |
+
)
|
| 1382 |
+
rollout_metrics["gen_rollout_batch"] = ratio_value.new_tensor(
|
| 1383 |
+
float(2 * rollout_num_deltas * rollout_max_examples)
|
| 1384 |
+
)
|
| 1385 |
+
rollout_metrics["gen_rollout_num_res"] = ratio_value.new_tensor(
|
| 1386 |
+
float(rollout_max_res)
|
| 1387 |
+
)
|
| 1388 |
+
if self._gen_cov_rollout_trace_ratio_ema is not None:
|
| 1389 |
+
ema_ratio = self._gen_cov_rollout_trace_ratio_ema.to(res_mask.device).clamp_min(1e-8)
|
| 1390 |
+
trace_target_scale = (1.0 / ema_ratio).detach().reshape(1)
|
| 1391 |
+
rollout_metrics["gen_rollout_trace_ratio_ema"] = ema_ratio.detach()
|
| 1392 |
+
rollout_metrics["gen_rollout_trace_target_scale"] = trace_target_scale.detach()[0]
|
| 1393 |
+
else:
|
| 1394 |
+
trace_target_scale = res_mask.new_tensor([1.0])
|
| 1395 |
+
rollout_metrics["gen_rollout_trace_ratio_ema"] = res_mask.new_tensor(1.0)
|
| 1396 |
+
rollout_metrics["gen_rollout_trace_target_scale"] = res_mask.new_tensor(1.0)
|
| 1397 |
+
if "gen_rollout_trace_measured" not in rollout_metrics:
|
| 1398 |
+
rollout_metrics["gen_rollout_trace_measured"] = res_mask.new_tensor(0.0)
|
| 1399 |
+
|
| 1400 |
+
teacher_response_deltas = None
|
| 1401 |
+
if teacher_model is not None:
|
| 1402 |
+
with torch.no_grad():
|
| 1403 |
+
if teacher_reuse_student_delta:
|
| 1404 |
+
teacher_conditions = conditions[: 2 * teacher_num_deltas]
|
| 1405 |
+
else:
|
| 1406 |
+
teacher_conditions = []
|
| 1407 |
+
for _ in range(teacher_num_deltas):
|
| 1408 |
+
c_sample, _ = self.latent_encoder.sample_coefficients_from_q(condition)
|
| 1409 |
+
c_sample = c_sample.detach().float()
|
| 1410 |
+
delta = (c_sample - mu_bar) * scale
|
| 1411 |
+
c_plus = mu_bar + delta
|
| 1412 |
+
c_minus = mu_bar - delta
|
| 1413 |
+
teacher_conditions.append(
|
| 1414 |
+
self.latent_encoder.condition_from_mode_coefficients(
|
| 1415 |
+
u_global, c_plus, rotmats_eq, res_mask, include_statistics=False
|
| 1416 |
+
)
|
| 1417 |
+
)
|
| 1418 |
+
teacher_conditions.append(
|
| 1419 |
+
self.latent_encoder.condition_from_mode_coefficients(
|
| 1420 |
+
u_global, c_minus, rotmats_eq, res_mask, include_statistics=False
|
| 1421 |
+
)
|
| 1422 |
+
)
|
| 1423 |
+
teacher_condition = _concat_conditions(teacher_conditions)
|
| 1424 |
+
teacher_batch = _expand_batch(noisy_batch, repeats=len(teacher_conditions))
|
| 1425 |
+
teacher_batch["z"] = teacher_condition
|
| 1426 |
+
teacher_pred = teacher_model(teacher_batch)["pred_trans"]
|
| 1427 |
+
teacher_pred = teacher_pred.reshape(
|
| 1428 |
+
teacher_num_deltas, 2, batch_size, *teacher_pred.shape[1:]
|
| 1429 |
+
)
|
| 1430 |
+
teacher_plus = teacher_pred[:, 0].reshape(
|
| 1431 |
+
teacher_num_deltas * batch_size, *teacher_pred.shape[3:]
|
| 1432 |
+
)
|
| 1433 |
+
teacher_minus = teacher_pred[:, 1].reshape(
|
| 1434 |
+
teacher_num_deltas * batch_size, *teacher_pred.shape[3:]
|
| 1435 |
+
)
|
| 1436 |
+
teacher_trans_eq_rep = trans_eq[None].expand(
|
| 1437 |
+
teacher_num_deltas, -1, -1, -1
|
| 1438 |
+
).reshape(teacher_num_deltas * batch_size, *trans_eq.shape[1:])
|
| 1439 |
+
teacher_res_mask_rep = res_mask[None].expand(
|
| 1440 |
+
teacher_num_deltas, -1, -1
|
| 1441 |
+
).reshape(teacher_num_deltas * batch_size, *res_mask.shape[1:])
|
| 1442 |
+
teacher_disp_plus = self.latent_encoder.relative_displacement(
|
| 1443 |
+
teacher_plus.float(), teacher_trans_eq_rep.float(), teacher_res_mask_rep
|
| 1444 |
+
)
|
| 1445 |
+
teacher_disp_minus = self.latent_encoder.relative_displacement(
|
| 1446 |
+
teacher_minus.float(), teacher_trans_eq_rep.float(), teacher_res_mask_rep
|
| 1447 |
+
)
|
| 1448 |
+
teacher_response_deltas = 0.5 * (teacher_disp_plus - teacher_disp_minus)
|
| 1449 |
+
teacher_response_deltas = teacher_response_deltas.reshape(
|
| 1450 |
+
teacher_num_deltas, batch_size, *teacher_response_deltas.shape[1:]
|
| 1451 |
+
)
|
| 1452 |
+
|
| 1453 |
+
losses, metrics = self.latent_encoder.generator_response_cov_loss(
|
| 1454 |
+
response_deltas,
|
| 1455 |
+
res_mask=res_mask,
|
| 1456 |
+
targets=targets,
|
| 1457 |
+
use_cross=use_cross,
|
| 1458 |
+
sample_weight=sample_weight,
|
| 1459 |
+
teacher_response_deltas=teacher_response_deltas,
|
| 1460 |
+
teacher_trace_anchor=cached_teacher_trace,
|
| 1461 |
+
teacher_trace_denominator=teacher_trace_denominator,
|
| 1462 |
+
amplitude_anchor=amplitude_anchor,
|
| 1463 |
+
trace_target_scale=trace_target_scale,
|
| 1464 |
+
)
|
| 1465 |
+
w_local = float(getattr(self._exp_cfg.training, "lambda_gen_local_shape", 1.0))
|
| 1466 |
+
w_cross = float(getattr(self._exp_cfg.training, "lambda_gen_cross_shape", 1.0))
|
| 1467 |
+
w_anchor = float(getattr(self._exp_cfg.training, "lambda_gen_trace_anchor", 0.05))
|
| 1468 |
+
# Anchor warmup: ramp the amplitude-anchor weight 0 -> full over N epochs.
|
| 1469 |
+
# Slamming the calibrated anchor to full on epoch 0 drove the condition to MD
|
| 1470 |
+
# amplitude too fast and collapsed the latent mode geometry (max_cos -> 0.99,
|
| 1471 |
+
# gram_condition -> 1e13) into a NaN q-head by epoch 3. Ramping lets the latent
|
| 1472 |
+
# settle before the amplitude drive reaches full. 0 disables the ramp.
|
| 1473 |
+
anchor_warmup = int(getattr(self._exp_cfg.training, "gen_trace_anchor_warmup_epochs", 0))
|
| 1474 |
+
if anchor_warmup > 0:
|
| 1475 |
+
w_anchor = w_anchor * min(
|
| 1476 |
+
1.0, float(getattr(self, "current_epoch", 0)) / float(anchor_warmup)
|
| 1477 |
+
)
|
| 1478 |
+
total = w_local * losses["gen_local_shape_loss"]
|
| 1479 |
+
if use_cross and "gen_cross_shape_loss" in losses:
|
| 1480 |
+
total = total + w_cross * losses["gen_cross_shape_loss"]
|
| 1481 |
+
if "gen_trace_anchor_loss" in losses:
|
| 1482 |
+
total = total + w_anchor * losses["gen_trace_anchor_loss"]
|
| 1483 |
+
weighted = lambda_gen * total
|
| 1484 |
+
out_metrics = {key: value.detach() for key, value in losses.items()}
|
| 1485 |
+
out_metrics.update(metrics)
|
| 1486 |
+
out_metrics.update(rollout_metrics)
|
| 1487 |
+
out_metrics["gen_cov_loss"] = weighted.detach()
|
| 1488 |
+
return weighted, out_metrics
|
| 1489 |
+
|
| 1490 |
+
def _condition_probe_metrics(self, noisy_batch, model_output, condition):
|
| 1491 |
+
if condition is None or not isinstance(condition, dict):
|
| 1492 |
+
return {}
|
| 1493 |
+
enabled = bool(getattr(self._exp_cfg.training, "epoch_condition_probe", True))
|
| 1494 |
+
if not enabled or self._condition_probe_epoch == int(self.current_epoch):
|
| 1495 |
+
return {}
|
| 1496 |
+
self._condition_probe_epoch = int(self.current_epoch)
|
| 1497 |
+
scale = float(getattr(self._exp_cfg.training, "condition_probe_scale", 2.0))
|
| 1498 |
+
with torch.no_grad():
|
| 1499 |
+
zero_batch = dict(noisy_batch)
|
| 1500 |
+
zero_batch["z"] = self._condition_with_scale(condition, 0.0)
|
| 1501 |
+
zero_output = self.model(zero_batch)
|
| 1502 |
+
scaled_batch = dict(noisy_batch)
|
| 1503 |
+
scaled_batch["z"] = self._condition_with_scale(condition, scale)
|
| 1504 |
+
scaled_output = self.model(scaled_batch)
|
| 1505 |
+
pred = model_output["pred_trans"].detach().float()
|
| 1506 |
+
denom = pred.abs().mean().clamp_min(1e-8)
|
| 1507 |
+
zero_delta = (pred - zero_output["pred_trans"].detach().float()).abs().mean()
|
| 1508 |
+
scaled_delta = (scaled_output["pred_trans"].detach().float() - pred).abs().mean()
|
| 1509 |
+
return {
|
| 1510 |
+
"condition_zero_pred_trans_delta": zero_delta.detach(),
|
| 1511 |
+
"condition_zero_pred_trans_delta_rel": (zero_delta / denom).detach(),
|
| 1512 |
+
"condition_scaled_pred_trans_delta": scaled_delta.detach(),
|
| 1513 |
+
"condition_scaled_pred_trans_delta_rel": (scaled_delta / denom).detach(),
|
| 1514 |
+
}
|
| 1515 |
+
|
| 1516 |
+
def _z_separability(self, z_sample, group_index, groups):
|
| 1517 |
+
with torch.no_grad():
|
| 1518 |
+
z_group, _ = self.latent_encoder._group_mean(z_sample, group_index)
|
| 1519 |
+
if z_group.shape[0] < 2:
|
| 1520 |
+
return None
|
| 1521 |
+
between = torch.pdist(z_group.float(), p=2)
|
| 1522 |
+
if between.numel() == 0:
|
| 1523 |
+
return None
|
| 1524 |
+
within = []
|
| 1525 |
+
for group in groups:
|
| 1526 |
+
members = z_sample[group_index == group]
|
| 1527 |
+
if members.shape[0] > 1:
|
| 1528 |
+
within.append(torch.pdist(members.float(), p=2).mean())
|
| 1529 |
+
if not within:
|
| 1530 |
+
return None
|
| 1531 |
+
within_mean = torch.stack(within).mean().clamp_min(1e-8)
|
| 1532 |
+
return between.mean() / within_mean
|
| 1533 |
+
|
| 1534 |
+
def on_train_epoch_end(self):
|
| 1535 |
+
if (
|
| 1536 |
+
getattr(self, "latent_enabled", False)
|
| 1537 |
+
and self.training_epoch_metrics
|
| 1538 |
+
and getattr(self, "global_rank", 0) == 0
|
| 1539 |
+
):
|
| 1540 |
+
metric_names = sorted({
|
| 1541 |
+
key
|
| 1542 |
+
for batch_metrics in self.training_epoch_metrics
|
| 1543 |
+
for key in batch_metrics
|
| 1544 |
+
})
|
| 1545 |
+
train_epoch_dict = {}
|
| 1546 |
+
for key in metric_names:
|
| 1547 |
+
values = [
|
| 1548 |
+
batch_metrics[key]
|
| 1549 |
+
for batch_metrics in self.training_epoch_metrics
|
| 1550 |
+
if key in batch_metrics
|
| 1551 |
+
]
|
| 1552 |
+
train_epoch_dict[key] = float(
|
| 1553 |
+
torch.stack(values).mean().detach().cpu().item()
|
| 1554 |
+
)
|
| 1555 |
+
train_epoch_dict["epoch"] = int(self.current_epoch)
|
| 1556 |
+
train_epoch_dict["global_step"] = int(self.global_step)
|
| 1557 |
+
train_epoch_dict["rank"] = int(self.global_rank)
|
| 1558 |
+
out_path = os.path.join(self._exp_cfg.checkpointer.dirpath, "latent_train_epoch_metrics.csv")
|
| 1559 |
+
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
| 1560 |
+
pd.DataFrame([train_epoch_dict]).to_csv(
|
| 1561 |
+
out_path,
|
| 1562 |
+
mode="a",
|
| 1563 |
+
header=not os.path.exists(out_path),
|
| 1564 |
+
index=False,
|
| 1565 |
+
)
|
| 1566 |
+
stage_name = epoch_summary_stage(train_epoch_dict)
|
| 1567 |
+
# Curated console watch-list: loss + <=5 decision-driving metrics, one per
|
| 1568 |
+
# line, each tagged with the wanted trend/range. The FULL metric set is
|
| 1569 |
+
# still written to latent_train_epoch_metrics.csv above; this only trims
|
| 1570 |
+
# the console noise so the few numbers that decide the run are readable.
|
| 1571 |
+
_watch = [
|
| 1572 |
+
("official_loss", "want ~0.85 stable; rising = backbone degrading"),
|
| 1573 |
+
("mode_max_cosine_abs", "want down <0.9; nearing 1 = about to diverge"),
|
| 1574 |
+
("gen_response_abs_mean", "want 0.1~0.5; ->0 = inert / blow-up = over-disperse"),
|
| 1575 |
+
("gen_trace_ratio_to_anchor", "want ->1; response amplitude calibrating to MD"),
|
| 1576 |
+
("cross_cov_far_corr", "want up 0.1->0.2; PCA-W2 proxy"),
|
| 1577 |
+
]
|
| 1578 |
+
_loss = train_epoch_dict.get("train_loss", float("nan"))
|
| 1579 |
+
_lines = [f"[epoch {int(self.current_epoch):03d} {stage_name}] loss={_loss:.4g}"]
|
| 1580 |
+
for _k, _hint in _watch:
|
| 1581 |
+
if _k in train_epoch_dict and pd.notna(train_epoch_dict[_k]):
|
| 1582 |
+
_lines.append(f" {_k}={train_epoch_dict[_k]:.4g} [{_hint}]")
|
| 1583 |
+
print("\n".join(_lines), flush=True)
|
| 1584 |
+
self.training_epoch_metrics = []
|
| 1585 |
+
self._grad_flow_reported = False
|
| 1586 |
+
return super().on_train_epoch_end()
|
| 1587 |
+
|
| 1588 |
+
def _grad_norm_for_prefixes(self, prefixes):
|
| 1589 |
+
total = 0.0
|
| 1590 |
+
count = 0
|
| 1591 |
+
for name, param in self.named_parameters():
|
| 1592 |
+
if not any(name.startswith(prefix) or prefix in name for prefix in prefixes):
|
| 1593 |
+
continue
|
| 1594 |
+
if param.grad is None:
|
| 1595 |
+
continue
|
| 1596 |
+
total += float(param.grad.detach().float().norm().cpu().item())
|
| 1597 |
+
count += 1
|
| 1598 |
+
return total, count
|
| 1599 |
+
|
| 1600 |
+
def on_after_backward(self):
|
| 1601 |
+
parent_hook = getattr(super(), "on_after_backward", None)
|
| 1602 |
+
if parent_hook is not None:
|
| 1603 |
+
parent_hook()
|
| 1604 |
+
if not getattr(self, "latent_enabled", False):
|
| 1605 |
+
return
|
| 1606 |
+
if self._grad_flow_reported:
|
| 1607 |
+
return
|
| 1608 |
+
if int(getattr(self, "global_step", 0)) != 0 or getattr(self, "global_rank", 0) != 0:
|
| 1609 |
+
return
|
| 1610 |
+
if not bool(getattr(self._exp_cfg.training, "grad_flow_check", False)):
|
| 1611 |
+
return
|
| 1612 |
+
groups = {
|
| 1613 |
+
"bbflow_backbone": ["model."],
|
| 1614 |
+
"prior_template_head": ["latent_encoder.template_"],
|
| 1615 |
+
"prior_energy_head": ["latent_encoder.energy_out"],
|
| 1616 |
+
"prior_mixture_head": ["latent_encoder.mixture_"],
|
| 1617 |
+
"condition_adapters_film": [
|
| 1618 |
+
"model.embedder.z_node_adapter",
|
| 1619 |
+
"model.embedder.z_edge_adapter",
|
| 1620 |
+
"model.embedder.disp_node_adapter",
|
| 1621 |
+
"model.embedder.disp_edge_adapter",
|
| 1622 |
+
"model.film_mlp",
|
| 1623 |
+
],
|
| 1624 |
+
}
|
| 1625 |
+
rows = []
|
| 1626 |
+
for group_name, prefixes in groups.items():
|
| 1627 |
+
norm, count = self._grad_norm_for_prefixes(prefixes)
|
| 1628 |
+
rows.append(f"{group_name}:grad_norm={norm:.4g}:params_with_grad={count}")
|
| 1629 |
+
print("[grad-flow-check] " + ", ".join(rows), flush=True)
|
| 1630 |
+
self._grad_flow_reported = True
|
| 1631 |
+
def training_step(self, batch: Any, stage: int):
|
| 1632 |
+
step_start_time = time.time()
|
| 1633 |
+
self.interpolant.set_device(batch['res_mask'].device)
|
| 1634 |
+
# Lightning bf16 autocast wraps training_step; OT/Kabsch/SVD/linalg.det need fp32.
|
| 1635 |
+
with torch.autocast(device_type="cuda", enabled=False):
|
| 1636 |
+
noisy_batch = self.interpolant.corrupt_batch(batch)
|
| 1637 |
+
if getattr(self, "latent_enabled", False):
|
| 1638 |
+
(
|
| 1639 |
+
z,
|
| 1640 |
+
group_index,
|
| 1641 |
+
latent_metrics,
|
| 1642 |
+
shape_recon_loss,
|
| 1643 |
+
shape_baseline_error,
|
| 1644 |
+
) = self._latent_group_z(noisy_batch)
|
| 1645 |
+
else:
|
| 1646 |
+
z = None
|
| 1647 |
+
group_index = torch.arange(
|
| 1648 |
+
noisy_batch["res_mask"].shape[0],
|
| 1649 |
+
device=noisy_batch["res_mask"].device,
|
| 1650 |
+
dtype=torch.long,
|
| 1651 |
+
)
|
| 1652 |
+
latent_metrics = {}
|
| 1653 |
+
shape_recon_loss = noisy_batch["res_mask"].new_zeros(())
|
| 1654 |
+
shape_baseline_error = noisy_batch["res_mask"].new_zeros(())
|
| 1655 |
+
if z is not None:
|
| 1656 |
+
noisy_batch["z"] = z
|
| 1657 |
+
|
| 1658 |
+
if (
|
| 1659 |
+
z is not None
|
| 1660 |
+
and isinstance(z, dict)
|
| 1661 |
+
and "u_global" in z
|
| 1662 |
+
and int(self.global_step) % 100 == 0
|
| 1663 |
+
):
|
| 1664 |
+
# DDP-safe mode-collapse watch. Every rank computes its worst mode
|
| 1665 |
+
# norm -- the exact quantity whose 1/norm^2 gradient explodes in
|
| 1666 |
+
# mode_orthogonality_loss -- then all-reduces to the GLOBAL min/max
|
| 1667 |
+
# so a collapse on any rank is caught, and prints on rank 0 only.
|
| 1668 |
+
# Gated purely on the synced global_step + config-level z structure,
|
| 1669 |
+
# so every rank enters the collective together (no deadlock).
|
| 1670 |
+
with torch.no_grad():
|
| 1671 |
+
_basis = z["u_global"].detach().float() * noisy_batch["res_mask"].float()[:, :, None, None]
|
| 1672 |
+
_gram = torch.einsum("bnkd,bnld->bkl", _basis, _basis)
|
| 1673 |
+
_mode_norms = torch.diagonal(_gram, dim1=-2, dim2=-1).clamp_min(0.0).sqrt()
|
| 1674 |
+
_min_norm = _mode_norms.min().detach().clone()
|
| 1675 |
+
_max_norm = _mode_norms.max().detach().clone()
|
| 1676 |
+
if self.trainer.world_size > 1 and dist.is_initialized():
|
| 1677 |
+
dist.all_reduce(_min_norm, op=dist.ReduceOp.MIN)
|
| 1678 |
+
dist.all_reduce(_max_norm, op=dist.ReduceOp.MAX)
|
| 1679 |
+
if int(getattr(self, "global_rank", 0)) == 0:
|
| 1680 |
+
logging.info(
|
| 1681 |
+
"[mode-watch] step=%d min_mode_norm=%.3e max_mode_norm=%.3e",
|
| 1682 |
+
int(self.global_step),
|
| 1683 |
+
float(_min_norm),
|
| 1684 |
+
float(_max_norm),
|
| 1685 |
+
)
|
| 1686 |
+
|
| 1687 |
+
log_latent_batch_debug = bool(
|
| 1688 |
+
getattr(self._exp_cfg.training, "log_latent_batch_debug", False)
|
| 1689 |
+
)
|
| 1690 |
+
if log_latent_batch_debug and (self.global_step < 20 or self.global_step % 500 == 0):
|
| 1691 |
+
groups_unique, group_counts = torch.unique(group_index.detach().cpu(), sorted=True, return_counts=True)
|
| 1692 |
+
logging.info(
|
| 1693 |
+
"latent batch before forward | rank=%s step=%s B=%s N=%s groups=%s group_sizes=%s precision=%s",
|
| 1694 |
+
getattr(self, "global_rank", 0),
|
| 1695 |
+
int(self.global_step),
|
| 1696 |
+
int(noisy_batch["res_mask"].shape[0]),
|
| 1697 |
+
int(noisy_batch["res_mask"].shape[1]),
|
| 1698 |
+
int(groups_unique.numel()),
|
| 1699 |
+
group_counts.tolist(),
|
| 1700 |
+
str(getattr(self._exp_cfg.trainer, "precision", "32-true")),
|
| 1701 |
+
)
|
| 1702 |
+
|
| 1703 |
+
if self._interpolant_cfg.self_condition and random.random() > 0.5:
|
| 1704 |
+
with torch.no_grad():
|
| 1705 |
+
model_sc = self.model(noisy_batch)
|
| 1706 |
+
noisy_batch['trans_sc'] = model_sc['pred_trans']
|
| 1707 |
+
|
| 1708 |
+
model_output = self.model(noisy_batch)
|
| 1709 |
+
if z is not None:
|
| 1710 |
+
latent_metrics.update(self._condition_probe_metrics(noisy_batch, model_output, z))
|
| 1711 |
+
condition_cycle_loss, condition_cycle_metrics = self._condition_cycle_loss(
|
| 1712 |
+
noisy_batch,
|
| 1713 |
+
model_output,
|
| 1714 |
+
z,
|
| 1715 |
+
)
|
| 1716 |
+
latent_metrics.update(condition_cycle_metrics)
|
| 1717 |
+
gen_cov_loss, gen_cov_metrics = self._generator_response_cov_loss(noisy_batch, z)
|
| 1718 |
+
latent_metrics.update(gen_cov_metrics)
|
| 1719 |
+
batch_losses = self.loss_fn(noisy_batch, model_output)
|
| 1720 |
+
num_batch = batch_losses['bb_atom_loss'].shape[0]
|
| 1721 |
+
total_losses = {
|
| 1722 |
+
k: torch.mean(v) for k,v in batch_losses.items()
|
| 1723 |
+
}
|
| 1724 |
+
|
| 1725 |
+
official_loss = (
|
| 1726 |
+
total_losses[self._exp_cfg.training.loss]
|
| 1727 |
+
+ total_losses['auxiliary_loss']
|
| 1728 |
+
)
|
| 1729 |
+
train_loss = (
|
| 1730 |
+
official_loss
|
| 1731 |
+
+ float(getattr(self._exp_cfg.training, "lambda_shape", 1.0)) * shape_recon_loss
|
| 1732 |
+
+ condition_cycle_loss
|
| 1733 |
+
+ gen_cov_loss
|
| 1734 |
+
)
|
| 1735 |
+
|
| 1736 |
+
nan_detected = torch.isnan(train_loss).float()
|
| 1737 |
+
if self.trainer.world_size > 1:
|
| 1738 |
+
dist.all_reduce(nan_detected, op=dist.ReduceOp.SUM)
|
| 1739 |
+
|
| 1740 |
+
if nan_detected > 0:
|
| 1741 |
+
self.nan_steps += 1
|
| 1742 |
+
if self.nan_steps > 5:
|
| 1743 |
+
raise ValueError('NaN loss encountered too many times in a row')
|
| 1744 |
+
if self.global_rank == 0:
|
| 1745 |
+
logging.info(f"NaN detected in loss (epoch {self.current_epoch}). Skipping this step.")
|
| 1746 |
+
return None
|
| 1747 |
+
else:
|
| 1748 |
+
self.nan_steps = 0
|
| 1749 |
+
|
| 1750 |
+
for k,v in total_losses.items():
|
| 1751 |
+
self._log_scalar(
|
| 1752 |
+
f"train/{k}", v, prog_bar=False, batch_size=num_batch)
|
| 1753 |
+
|
| 1754 |
+
self._log_scalar("train/official_loss", official_loss, prog_bar=False, batch_size=num_batch)
|
| 1755 |
+
self._log_scalar("train/shape_recon_loss", shape_recon_loss, prog_bar=False, batch_size=num_batch)
|
| 1756 |
+
self._log_scalar("train/shape_baseline_error", shape_baseline_error, prog_bar=False, batch_size=num_batch)
|
| 1757 |
+
for metric_name, metric_value in latent_metrics.items():
|
| 1758 |
+
self._log_scalar(f"train/{metric_name}", metric_value, prog_bar=False, batch_size=num_batch)
|
| 1759 |
+
|
| 1760 |
+
def detached_scalar(value):
|
| 1761 |
+
if torch.is_tensor(value):
|
| 1762 |
+
return value.detach().float().mean()
|
| 1763 |
+
return train_loss.detach().new_tensor(float(value), dtype=torch.float32)
|
| 1764 |
+
|
| 1765 |
+
batch_metrics = {
|
| 1766 |
+
k: detached_scalar(v) for k, v in total_losses.items()
|
| 1767 |
+
}
|
| 1768 |
+
batch_metrics.update({
|
| 1769 |
+
"official_loss": detached_scalar(official_loss),
|
| 1770 |
+
"shape_recon_loss": detached_scalar(shape_recon_loss),
|
| 1771 |
+
"shape_baseline_error": detached_scalar(shape_baseline_error),
|
| 1772 |
+
"train_loss": detached_scalar(train_loss),
|
| 1773 |
+
})
|
| 1774 |
+
batch_metrics.update({
|
| 1775 |
+
k: detached_scalar(v) for k, v in latent_metrics.items()
|
| 1776 |
+
})
|
| 1777 |
+
|
| 1778 |
+
t = torch.squeeze(noisy_batch['t'])
|
| 1779 |
+
self._log_scalar(
|
| 1780 |
+
"train/t", t.detach().float().mean(),
|
| 1781 |
+
prog_bar=False, batch_size=num_batch)
|
| 1782 |
+
|
| 1783 |
+
if self._exp_cfg.training.t_bins > 1 and self._diagnostic_step():
|
| 1784 |
+
for loss_name, loss_dict in batch_losses.items():
|
| 1785 |
+
stratified_losses = mu.t_stratified_loss(
|
| 1786 |
+
t, loss_dict, num_bins=self._exp_cfg.training.t_bins, t_interval=self._interpolant_cfg.t_interval, loss_name=loss_name)
|
| 1787 |
+
batch_metrics.update({
|
| 1788 |
+
k: detached_scalar(v) for k, v in stratified_losses.items()
|
| 1789 |
+
})
|
| 1790 |
+
|
| 1791 |
+
for k,v in stratified_losses.items():
|
| 1792 |
+
self._log_scalar(
|
| 1793 |
+
f"train/{k}", v, prog_bar=False, batch_size=num_batch)
|
| 1794 |
+
|
| 1795 |
+
self.training_epoch_metrics.append(batch_metrics)
|
| 1796 |
+
|
| 1797 |
+
self._log_scalar(
|
| 1798 |
+
"train/length", float(batch['res_mask'].shape[1]), prog_bar=False, batch_size=num_batch)
|
| 1799 |
+
self._log_scalar(
|
| 1800 |
+
"train/batch_size", float(num_batch), prog_bar=False)
|
| 1801 |
+
step_time = time.time() - step_start_time
|
| 1802 |
+
self._log_scalar(
|
| 1803 |
+
"train/examples_per_second", num_batch / step_time)
|
| 1804 |
+
self._log_scalar(
|
| 1805 |
+
"train/loss", train_loss, batch_size=num_batch)
|
| 1806 |
+
|
| 1807 |
+
if self._exp_cfg.use_wandb:
|
| 1808 |
+
wandb_logs = {}
|
| 1809 |
+
time_indices = torch.bucketize(noisy_batch["t"].detach().cpu(), self._time_bins)
|
| 1810 |
+
time_indices_unique, counts = torch.unique(time_indices-1, return_counts=True)
|
| 1811 |
+
time_indices_unique[time_indices_unique < 0] = 0
|
| 1812 |
+
self._time_histogram[time_indices_unique] += counts
|
| 1813 |
+
wandb_logs["sampled_time_cumulative"] = wandb.Histogram(
|
| 1814 |
+
np_histogram=((
|
| 1815 |
+
(self._time_histogram/self._time_histogram.sum()).numpy(),
|
| 1816 |
+
self._time_bins.numpy()
|
| 1817 |
+
))
|
| 1818 |
+
)
|
| 1819 |
+
time_histogram_step = torch.zeros(self._time_histogram.shape)
|
| 1820 |
+
time_histogram_step[time_indices_unique] += counts
|
| 1821 |
+
wandb_logs["sampled_time_per_step"] = wandb.Histogram(
|
| 1822 |
+
np_histogram=((
|
| 1823 |
+
(time_histogram_step/time_histogram_step.sum()).numpy(),
|
| 1824 |
+
self._time_bins.numpy()
|
| 1825 |
+
))
|
| 1826 |
+
)
|
| 1827 |
+
self.logger.experiment.log(wandb_logs)
|
| 1828 |
+
|
| 1829 |
+
return train_loss
|
| 1830 |
+
|
| 1831 |
+
def configure_optimizers(self):
|
| 1832 |
+
if not getattr(self, "latent_enabled", False):
|
| 1833 |
+
return super().configure_optimizers()
|
| 1834 |
+
|
| 1835 |
+
params = [p for p in list(self.model.parameters()) + list(self.latent_encoder.parameters()) if p.requires_grad]
|
| 1836 |
+
if getattr(self, "global_rank", 0) == 0 and bool(getattr(self._exp_cfg.training, "log_optimizer_coverage", True)):
|
| 1837 |
+
num_params = sum(p.numel() for p in params)
|
| 1838 |
+
print(f"[optimizer-coverage] trainable_tensors={len(params)} trainable_params={num_params}", flush=True)
|
| 1839 |
+
if not self._exp_cfg.scheduler.enabled:
|
| 1840 |
+
return torch.optim.AdamW(
|
| 1841 |
+
params=params,
|
| 1842 |
+
**self._exp_cfg.optimizer,
|
| 1843 |
+
)
|
| 1844 |
+
optimizer = torch.optim.AdamW(
|
| 1845 |
+
params=params,
|
| 1846 |
+
**self._exp_cfg.optimizer,
|
| 1847 |
+
)
|
| 1848 |
+
scheduler = torch.optim.lr_scheduler.LambdaLR(
|
| 1849 |
+
optimizer,
|
| 1850 |
+
lr_lambda=self.lr_lambda
|
| 1851 |
+
)
|
| 1852 |
+
return [optimizer], [scheduler]
|
| 1853 |
+
|
| 1854 |
+
|
| 1855 |
+
def predict_step(self, batch, batch_idx):
|
| 1856 |
+
device = f'cuda:{torch.cuda.current_device()}'
|
| 1857 |
+
interpolant = InterpolantBBFlow(self._infer_cfg.interpolant)
|
| 1858 |
+
interpolant.set_device(device)
|
| 1859 |
+
|
| 1860 |
+
pdb_dir = os.path.join(self._output_dir, batch["pdb_name"][0])
|
| 1861 |
+
if os.path.exists(os.path.join(pdb_dir, "sampled_conformations.pdb")):
|
| 1862 |
+
print(f"Skipping {batch['pdb_name']} as it already exists")
|
| 1863 |
+
return
|
| 1864 |
+
os.makedirs(pdb_dir, exist_ok=True)
|
| 1865 |
+
|
| 1866 |
+
sample_time_start = datetime.now()
|
| 1867 |
+
|
| 1868 |
+
N = batch["trans_equilibrium"].shape[1]
|
| 1869 |
+
batch_size = self._infer_cfg.samples.num_res_squared / N**2
|
| 1870 |
+
batch_size = max(
|
| 1871 |
+
1,
|
| 1872 |
+
min(
|
| 1873 |
+
self._infer_cfg.samples.batch_size,
|
| 1874 |
+
int(batch_size/5)*5
|
| 1875 |
+
)
|
| 1876 |
+
)
|
| 1877 |
+
|
| 1878 |
+
sampled_conformations = self._sample_multiple(
|
| 1879 |
+
batch["trans_equilibrium"],
|
| 1880 |
+
batch["rotmats_equilibrium"],
|
| 1881 |
+
batch["seq"],
|
| 1882 |
+
self._infer_cfg.samples.samples_per_protein,
|
| 1883 |
+
batch_size,
|
| 1884 |
+
interpolant,
|
| 1885 |
+
pdb_dir=pdb_dir if self._infer_cfg.save_traj else None
|
| 1886 |
+
)
|
| 1887 |
+
|
| 1888 |
+
sample_time = (datetime.now()-sample_time_start).total_seconds()
|
| 1889 |
+
|
| 1890 |
+
aatype = batch["seq"][0].argmax(-1).cpu().numpy()
|
| 1891 |
+
|
| 1892 |
+
samples_path = os.path.join(pdb_dir, f'sampled_conformations.pdb')
|
| 1893 |
+
au.write_prot_to_pdb(
|
| 1894 |
+
sampled_conformations,
|
| 1895 |
+
samples_path,
|
| 1896 |
+
aatype=aatype,
|
| 1897 |
+
no_indexing=True
|
| 1898 |
+
)
|
| 1899 |
+
|
| 1900 |
+
if bool(getattr(self._infer_cfg, "postprocess_bfactors", True)):
|
| 1901 |
+
confs = mdtraj.load(samples_path)
|
| 1902 |
+
avg = np.mean(confs.xyz, axis=0)
|
| 1903 |
+
avg -= np.mean(avg[confs.top.select("name CA")], axis=0, keepdims=True)
|
| 1904 |
+
avg = mdtraj.Trajectory(avg[None, :, :], confs.top)
|
| 1905 |
+
confs = confs.superpose(avg)
|
| 1906 |
+
rmsf = mdtraj.rmsf(confs, avg)
|
| 1907 |
+
confs.save_pdb(samples_path, bfactors=rmsf)
|
| 1908 |
+
|
| 1909 |
+
|
| 1910 |
+
if not self._infer_cfg.single_file:
|
| 1911 |
+
os.makedirs(os.path.join(pdb_dir, "samples"))
|
| 1912 |
+
confs = mdtraj.load(samples_path)
|
| 1913 |
+
for i in range(len(confs)):
|
| 1914 |
+
single_sample_path = os.path.join(pdb_dir, "samples", f"sample_{i}.pdb")
|
| 1915 |
+
confs[i].save(single_sample_path)
|
| 1916 |
+
|
| 1917 |
+
os.remove(samples_path)
|
| 1918 |
+
|
| 1919 |
+
|
| 1920 |
+
if self._infer_cfg.log_times:
|
| 1921 |
+
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")
|
| 1922 |
+
sample_time = (datetime.now()-sample_time_start).total_seconds()
|
| 1923 |
+
self._print_logger.info(f"Time with pdb saving and plotting: {sample_time}s")
|
bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/embedder.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 Max Planck Institute for Polymer Research
|
| 2 |
+
# Copyright (c) 2024 HITS gGmbH
|
| 3 |
+
# Copyright (c) Microsoft Corporation.
|
| 4 |
+
# Licensed under the MIT license.
|
| 5 |
+
|
| 6 |
+
import functools as fn
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from torch.nn import functional as F
|
| 11 |
+
|
| 12 |
+
import gafl.models.utils as mu
|
| 13 |
+
from gafl.data import utils as du
|
| 14 |
+
|
| 15 |
+
from gafl.models.ipa_pytorch import Linear
|
| 16 |
+
from gafl.models.utils import get_index_embedding, get_time_embedding, get_length_embedding
|
| 17 |
+
|
| 18 |
+
class MLP(nn.Module):
|
| 19 |
+
def __init__(self, c1, c2, num_layers=2, use_layer_norm=True, dropout=0) -> None:
|
| 20 |
+
super(MLP, self).__init__()
|
| 21 |
+
|
| 22 |
+
self.layers = []
|
| 23 |
+
for _ in range(num_layers-1):
|
| 24 |
+
self.layers.append(Linear(c1, c1, init="relu"))
|
| 25 |
+
self.layers.append(nn.ReLU())
|
| 26 |
+
self.layers.append(nn.Dropout(dropout))
|
| 27 |
+
self.layers.append(Linear(c1, c1, init="final"))
|
| 28 |
+
self.layers = nn.Sequential(*self.layers)
|
| 29 |
+
|
| 30 |
+
if c1 != c2:
|
| 31 |
+
self.final_layer = nn.Linear(c1, c2)
|
| 32 |
+
else:
|
| 33 |
+
self.final_layer = nn.Identity()
|
| 34 |
+
|
| 35 |
+
self.use_layer_norm = use_layer_norm
|
| 36 |
+
if use_layer_norm:
|
| 37 |
+
self.layer_norm = nn.LayerNorm(c2)
|
| 38 |
+
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
x = self.layers(x) + x
|
| 41 |
+
x = self.final_layer(x)
|
| 42 |
+
if self.use_layer_norm:
|
| 43 |
+
x = self.layer_norm(x)
|
| 44 |
+
return x
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def embed_direction(trans, rots, dist_cutoff=np.inf):
|
| 48 |
+
"""
|
| 49 |
+
Compute the position of the other residues from the
|
| 50 |
+
perspective of each residue.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
trans: [B, N, 3] translation vectors
|
| 54 |
+
rots: [B, N, 3, 3] rotation matrices
|
| 55 |
+
Returns:
|
| 56 |
+
[B, N, N, 3] relative positions from each residue to each other residue
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
B, N, _ = trans.shape
|
| 60 |
+
device = trans.device
|
| 61 |
+
|
| 62 |
+
frames = du.create_rigid(rots, trans)
|
| 63 |
+
rel_pos = frames[:,:,None].invert_apply(trans[:,None,:])
|
| 64 |
+
# rel_pos.shape = [B, N, N, 3]
|
| 65 |
+
distances = torch.linalg.norm(rel_pos, dim=-1)
|
| 66 |
+
rel_pos = rel_pos / (distances[...,None] + 1e-6)
|
| 67 |
+
indices = torch.arange(N, device=device)
|
| 68 |
+
rel_pos[:, indices, indices, :] = torch.zeros(3, device=device)
|
| 69 |
+
if dist_cutoff < np.inf:
|
| 70 |
+
# Set all direction vectors to zero if the distance is greater than dist_cutoff
|
| 71 |
+
mask = distances > dist_cutoff
|
| 72 |
+
rel_pos[mask,:] = 0
|
| 73 |
+
|
| 74 |
+
return rel_pos
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class Embedder(nn.Module):
|
| 80 |
+
def __init__(self, model_conf, latent_cfg=None):
|
| 81 |
+
super(Embedder, self).__init__()
|
| 82 |
+
self.model_conf = model_conf
|
| 83 |
+
self.embed_aatype = model_conf.embed.embed_aatype
|
| 84 |
+
self.latent_enabled = bool(latent_cfg is not None and getattr(latent_cfg, "enable", False))
|
| 85 |
+
self.inject_embedder = bool(
|
| 86 |
+
self.latent_enabled and getattr(latent_cfg, "inject_embedder", True)
|
| 87 |
+
)
|
| 88 |
+
self.track_condition_debug = bool(
|
| 89 |
+
self.latent_enabled and getattr(latent_cfg, "track_condition_debug", False)
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
if "time_embed_dim" in model_conf.embed:
|
| 93 |
+
self.time_embed_dim = model_conf.embed.time_embed_dim
|
| 94 |
+
else:
|
| 95 |
+
self.time_embed_dim = 0
|
| 96 |
+
|
| 97 |
+
if "embed_distogram" in model_conf.embed:
|
| 98 |
+
self.embed_distogram = model_conf.embed.embed_distogram
|
| 99 |
+
else:
|
| 100 |
+
self.embed_distogram = True
|
| 101 |
+
|
| 102 |
+
if "embed_self_conditioning" in model_conf.embed:
|
| 103 |
+
self.embed_self_conditioning = model_conf.embed.embed_self_conditioning
|
| 104 |
+
else:
|
| 105 |
+
self.embed_self_conditioning = True
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
length_embed_dim = model_conf.embed.length_embed_dim
|
| 109 |
+
|
| 110 |
+
node_dim_in = self.time_embed_dim + length_embed_dim
|
| 111 |
+
|
| 112 |
+
edge_dim_in = 2 * self.time_embed_dim
|
| 113 |
+
edge_dim_in += 2 * model_conf.node_embed_size
|
| 114 |
+
edge_dim_in += self.model_conf.embed.num_bins_distance
|
| 115 |
+
if self.embed_distogram:
|
| 116 |
+
edge_dim_in += self.model_conf.embed.num_bins_distance
|
| 117 |
+
if self.embed_self_conditioning:
|
| 118 |
+
edge_dim_in += self.model_conf.embed.num_bins_distance
|
| 119 |
+
|
| 120 |
+
self.embed_direction = model_conf.embed.embed_direction
|
| 121 |
+
if self.embed_direction:
|
| 122 |
+
if hasattr(model_conf.embed, "embed_direction_cutoff") and model_conf.embed.embed_direction_cutoff is not None:
|
| 123 |
+
self.embed_direction_cutoff = model_conf.embed.embed_direction_cutoff
|
| 124 |
+
else:
|
| 125 |
+
self.embed_direction_cutoff = np.inf
|
| 126 |
+
edge_dim_in += 3
|
| 127 |
+
|
| 128 |
+
# positional encoding
|
| 129 |
+
# if model_conf.embed.index_embed_dim > 0:
|
| 130 |
+
if hasattr(model_conf.embed, "index_embed_type"):
|
| 131 |
+
self.index_embed_type = model_conf.embed.index_embed_type
|
| 132 |
+
self.index_embed_dim = model_conf.embed.index_embed_dim
|
| 133 |
+
else:
|
| 134 |
+
self.index_embed_dim = model_conf.embed.index_embed_dim
|
| 135 |
+
self.index_embed_type = None if self.index_embed_dim == 0 else "full"
|
| 136 |
+
|
| 137 |
+
if self.index_embed_type is None or self.index_embed_type == "none":
|
| 138 |
+
self.index_embed_type = None
|
| 139 |
+
elif self.index_embed_type == "full":
|
| 140 |
+
assert self.index_embed_dim > 0, "index_embed_dim must be > 0 if index_embed_type is 'full'."
|
| 141 |
+
node_dim_in += self.index_embed_dim
|
| 142 |
+
edge_dim_in += self.index_embed_dim
|
| 143 |
+
self.linear_relpos = nn.Linear(
|
| 144 |
+
self.index_embed_dim, self.index_embed_dim
|
| 145 |
+
)
|
| 146 |
+
elif self.index_embed_type == "neighbor":
|
| 147 |
+
edge_dim_in += 1
|
| 148 |
+
else:
|
| 149 |
+
raise ValueError("index_embed_type must be None/\"none\", 'full' or 'neighbor'.")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
if self.embed_aatype:
|
| 153 |
+
self.aatype_embedding = nn.Linear(21, model_conf.embed.aatype_embed_dim)
|
| 154 |
+
node_dim_in += model_conf.embed.aatype_embed_dim
|
| 155 |
+
|
| 156 |
+
if self.inject_embedder:
|
| 157 |
+
self.latent_dim = int(getattr(latent_cfg, "dim", 16))
|
| 158 |
+
self.num_modes = int(getattr(latent_cfg, "num_modes", self.latent_dim))
|
| 159 |
+
self.node_cond_dim = int(getattr(latent_cfg, "node_cond_dim", self.num_modes))
|
| 160 |
+
self.edge_cond_dim = int(getattr(latent_cfg, "edge_cond_dim", self.num_modes))
|
| 161 |
+
self.z_node_adapter = nn.Sequential(
|
| 162 |
+
nn.Linear(self.node_cond_dim, model_conf.node_embed_size),
|
| 163 |
+
nn.ReLU(),
|
| 164 |
+
nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size),
|
| 165 |
+
)
|
| 166 |
+
self.z_edge_adapter = nn.Sequential(
|
| 167 |
+
nn.Linear(self.edge_cond_dim, model_conf.edge_embed_size),
|
| 168 |
+
nn.ReLU(),
|
| 169 |
+
nn.Linear(model_conf.edge_embed_size, model_conf.edge_embed_size),
|
| 170 |
+
)
|
| 171 |
+
self.disp_node_adapter = nn.Sequential(
|
| 172 |
+
nn.Linear(3, model_conf.node_embed_size),
|
| 173 |
+
nn.ReLU(),
|
| 174 |
+
nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size),
|
| 175 |
+
)
|
| 176 |
+
self.disp_edge_adapter = nn.Sequential(
|
| 177 |
+
nn.Linear(1, model_conf.edge_embed_size),
|
| 178 |
+
nn.ReLU(),
|
| 179 |
+
nn.Linear(model_conf.edge_embed_size, model_conf.edge_embed_size),
|
| 180 |
+
)
|
| 181 |
+
nn.init.zeros_(self.z_node_adapter[-1].weight)
|
| 182 |
+
nn.init.zeros_(self.z_node_adapter[-1].bias)
|
| 183 |
+
nn.init.zeros_(self.z_edge_adapter[-1].weight)
|
| 184 |
+
nn.init.zeros_(self.z_edge_adapter[-1].bias)
|
| 185 |
+
nn.init.zeros_(self.disp_node_adapter[-1].weight)
|
| 186 |
+
nn.init.zeros_(self.disp_node_adapter[-1].bias)
|
| 187 |
+
nn.init.zeros_(self.disp_edge_adapter[-1].weight)
|
| 188 |
+
nn.init.zeros_(self.disp_edge_adapter[-1].bias)
|
| 189 |
+
else:
|
| 190 |
+
self.latent_dim = 0
|
| 191 |
+
self.num_modes = 0
|
| 192 |
+
self.node_cond_dim = 0
|
| 193 |
+
self.edge_cond_dim = 0
|
| 194 |
+
self.z_node_adapter = None
|
| 195 |
+
self.z_edge_adapter = None
|
| 196 |
+
self.disp_node_adapter = None
|
| 197 |
+
self.disp_edge_adapter = None
|
| 198 |
+
|
| 199 |
+
self.linear_s_p = nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size)
|
| 200 |
+
|
| 201 |
+
self.node_embedding = MLP(node_dim_in, model_conf.node_embed_size, num_layers=2)
|
| 202 |
+
self.edge_embedding = MLP(edge_dim_in, model_conf.edge_embed_size, num_layers=2)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
self.timestep_embedder = fn.partial(
|
| 206 |
+
get_time_embedding,
|
| 207 |
+
embedding_dim=self.time_embed_dim,
|
| 208 |
+
)
|
| 209 |
+
self.index_embedder = fn.partial(
|
| 210 |
+
get_index_embedding,
|
| 211 |
+
embed_size=self.model_conf.embed.index_embed_dim,
|
| 212 |
+
)
|
| 213 |
+
self.length_embedder = fn.partial(
|
| 214 |
+
get_length_embedding,
|
| 215 |
+
embed_size=self.model_conf.embed.length_embed_dim,
|
| 216 |
+
max_len=2056
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
def prepare_inference_static(self, input_features):
|
| 220 |
+
"""Cache O(N^2) features that are constant across ODE timesteps."""
|
| 221 |
+
B, N = input_features["B,N"]
|
| 222 |
+
device = input_features["device"]
|
| 223 |
+
cache = {}
|
| 224 |
+
|
| 225 |
+
if self.embed_aatype:
|
| 226 |
+
cache["aatype_embedding"] = self.aatype_embedding(input_features["seq"])
|
| 227 |
+
|
| 228 |
+
cache["length_embedding"] = self.length_embedder(
|
| 229 |
+
torch.empty(1, N, device=device)
|
| 230 |
+
).repeat([B, 1, 1])
|
| 231 |
+
|
| 232 |
+
if self.index_embed_type == "full":
|
| 233 |
+
seq_idx = torch.arange(N, device=device).repeat(B, 1)
|
| 234 |
+
cache["index_node_embedding"] = self.index_embedder(seq_idx)
|
| 235 |
+
rel_seq_offset = seq_idx[:, :, None] - seq_idx[:, None, :]
|
| 236 |
+
cache["index_edge_embedding"] = self.linear_relpos(
|
| 237 |
+
self.index_embedder(rel_seq_offset.reshape([B, N**2]))
|
| 238 |
+
)
|
| 239 |
+
elif self.index_embed_type == "neighbor":
|
| 240 |
+
neighbors = (
|
| 241 |
+
torch.diag_embed(torch.ones(N - 1, device=device), offset=1)
|
| 242 |
+
+ torch.diag_embed(torch.ones(N - 1, device=device), offset=-1)
|
| 243 |
+
)
|
| 244 |
+
cache["index_edge_embedding"] = (
|
| 245 |
+
neighbors[None].repeat(B, 1, 1).reshape([B, N**2, 1])
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
if self.embed_distogram:
|
| 249 |
+
cache["equilibrium_distogram"] = mu.calc_distogram(
|
| 250 |
+
input_features["CA_pos"]["trans_equilibrium"],
|
| 251 |
+
self.model_conf.embed.min_bin_distance,
|
| 252 |
+
self.model_conf.embed.max_bin_distance,
|
| 253 |
+
self.model_conf.embed.num_bins_distance,
|
| 254 |
+
).reshape([B, N**2, -1])
|
| 255 |
+
|
| 256 |
+
if self.embed_direction:
|
| 257 |
+
cache["direction_embedding"] = embed_direction(
|
| 258 |
+
input_features["CA_pos"]["trans_equilibrium"],
|
| 259 |
+
input_features["rotmats_equilibrium"],
|
| 260 |
+
dist_cutoff=self.embed_direction_cutoff,
|
| 261 |
+
).reshape([B, N**2, -1])
|
| 262 |
+
|
| 263 |
+
if self.inject_embedder:
|
| 264 |
+
payload = input_features.get("z")
|
| 265 |
+
if isinstance(payload, dict):
|
| 266 |
+
node_cond = payload.get("node_cond")
|
| 267 |
+
edge_cond = payload.get("edge_cond")
|
| 268 |
+
disp_node_cond = payload.get("disp_node_cond")
|
| 269 |
+
disp_edge_cond = payload.get("disp_edge_cond")
|
| 270 |
+
else:
|
| 271 |
+
node_cond = payload
|
| 272 |
+
edge_cond = payload
|
| 273 |
+
disp_node_cond = None
|
| 274 |
+
disp_edge_cond = None
|
| 275 |
+
if node_cond is None:
|
| 276 |
+
node_cond = torch.zeros(B, N, self.node_cond_dim, device=device)
|
| 277 |
+
if edge_cond is None:
|
| 278 |
+
edge_cond = torch.zeros(B, N, N, self.edge_cond_dim, device=device)
|
| 279 |
+
if disp_node_cond is None:
|
| 280 |
+
disp_node_cond = torch.zeros(B, N, 3, device=device)
|
| 281 |
+
if disp_edge_cond is None:
|
| 282 |
+
disp_edge_cond = torch.zeros(B, N, N, 1, device=device)
|
| 283 |
+
if node_cond.dim() == 2:
|
| 284 |
+
node_cond = node_cond[:, None, :].expand(B, N, -1)
|
| 285 |
+
if edge_cond.dim() == 2:
|
| 286 |
+
edge_cond = edge_cond[:, None, None, :].expand(B, N, N, -1)
|
| 287 |
+
cache["node_condition_embedding"] = (
|
| 288 |
+
self.z_node_adapter(node_cond)
|
| 289 |
+
+ self.disp_node_adapter(disp_node_cond)
|
| 290 |
+
)
|
| 291 |
+
cache["edge_condition_embedding"] = (
|
| 292 |
+
self.z_edge_adapter(edge_cond)
|
| 293 |
+
+ self.disp_edge_adapter(disp_edge_cond)
|
| 294 |
+
)
|
| 295 |
+
return cache
|
| 296 |
+
|
| 297 |
+
def forward(self, input_features):
|
| 298 |
+
"""
|
| 299 |
+
Args:
|
| 300 |
+
t:
|
| 301 |
+
[*, ] time step sampled from [0, 1]
|
| 302 |
+
fixed_mask:
|
| 303 |
+
[*, N_res] mask of fixed (motif) residues
|
| 304 |
+
self_conditioning_ca:
|
| 305 |
+
[*, N_res, 3] Ca positions of self-conditioning input
|
| 306 |
+
rigids:
|
| 307 |
+
[*, N_res] Frame object
|
| 308 |
+
Returns:
|
| 309 |
+
[*, N_res, node_dim] initial node features
|
| 310 |
+
[*, N_res, N_res, edge_dim] initial edge features
|
| 311 |
+
"""
|
| 312 |
+
B, N = input_features["B,N"]
|
| 313 |
+
device = input_features["device"]
|
| 314 |
+
static = input_features.get("inference_static")
|
| 315 |
+
|
| 316 |
+
h_0 = []
|
| 317 |
+
z_0 = []
|
| 318 |
+
|
| 319 |
+
if self.time_embed_dim > 0:
|
| 320 |
+
t_embed = self.timestep_embedder(input_features["time"][:,0])[:, None, :].repeat(1, N, 1)
|
| 321 |
+
h_0.append(t_embed)
|
| 322 |
+
z_0.append(self._cross_concat(t_embed, B, N))
|
| 323 |
+
|
| 324 |
+
if self.embed_aatype:
|
| 325 |
+
if static is not None and "aatype_embedding" in static:
|
| 326 |
+
h_0.append(static["aatype_embedding"])
|
| 327 |
+
else:
|
| 328 |
+
h_0.append(self.aatype_embedding(input_features["seq"]))
|
| 329 |
+
|
| 330 |
+
if self.inject_embedder:
|
| 331 |
+
z_payload = input_features.get("z", None)
|
| 332 |
+
self._last_z_seen = z_payload is not None
|
| 333 |
+
if isinstance(z_payload, dict):
|
| 334 |
+
node_cond = z_payload.get("node_cond")
|
| 335 |
+
edge_cond = z_payload.get("edge_cond")
|
| 336 |
+
disp_node_cond = z_payload.get("disp_node_cond")
|
| 337 |
+
disp_edge_cond = z_payload.get("disp_edge_cond")
|
| 338 |
+
else:
|
| 339 |
+
node_cond = z_payload
|
| 340 |
+
edge_cond = z_payload
|
| 341 |
+
disp_node_cond = None
|
| 342 |
+
disp_edge_cond = None
|
| 343 |
+
if node_cond is None:
|
| 344 |
+
node_cond = torch.zeros(B, N, self.node_cond_dim, device=device)
|
| 345 |
+
if edge_cond is None:
|
| 346 |
+
edge_cond = torch.zeros(B, N, N, self.edge_cond_dim, device=device)
|
| 347 |
+
if disp_node_cond is None:
|
| 348 |
+
disp_node_cond = torch.zeros(B, N, 3, device=device)
|
| 349 |
+
if disp_edge_cond is None:
|
| 350 |
+
disp_edge_cond = torch.zeros(B, N, N, 1, device=device)
|
| 351 |
+
if node_cond.dim() == 2:
|
| 352 |
+
node_cond = node_cond[:, None, :].expand(B, N, -1)
|
| 353 |
+
if edge_cond.dim() == 2:
|
| 354 |
+
edge_cond = edge_cond[:, None, None, :].expand(B, N, N, -1)
|
| 355 |
+
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)
|
| 356 |
+
self._last_z_shape = {
|
| 357 |
+
"node_cond": tuple(node_cond.shape),
|
| 358 |
+
"edge_cond": tuple(edge_cond.shape),
|
| 359 |
+
"disp_node_cond": tuple(disp_node_cond.shape),
|
| 360 |
+
"disp_edge_cond": tuple(disp_edge_cond.shape),
|
| 361 |
+
}
|
| 362 |
+
if self.track_condition_debug:
|
| 363 |
+
self._last_z_abs_mean = float(
|
| 364 |
+
((node_cond.detach().float().abs().mean()
|
| 365 |
+
+ edge_cond.detach().float().abs().mean()
|
| 366 |
+
+ disp_node_cond.detach().float().abs().mean()
|
| 367 |
+
+ disp_edge_cond.detach().float().abs().mean()) / 4.0).cpu().item()
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
for ca_pos_name, ca_pos in input_features["CA_pos"].items():
|
| 371 |
+
if not self.embed_distogram and ca_pos_name == "trans_equilibrium":
|
| 372 |
+
continue
|
| 373 |
+
if (
|
| 374 |
+
static is not None
|
| 375 |
+
and ca_pos_name == "trans_equilibrium"
|
| 376 |
+
and "equilibrium_distogram" in static
|
| 377 |
+
):
|
| 378 |
+
z_0.append(static["equilibrium_distogram"])
|
| 379 |
+
else:
|
| 380 |
+
ca_dgram = mu.calc_distogram(
|
| 381 |
+
ca_pos,
|
| 382 |
+
self.model_conf.embed.min_bin_distance,
|
| 383 |
+
self.model_conf.embed.max_bin_distance,
|
| 384 |
+
self.model_conf.embed.num_bins_distance,
|
| 385 |
+
)
|
| 386 |
+
z_0.append(ca_dgram.reshape([B, N**2, -1]))
|
| 387 |
+
|
| 388 |
+
if self.embed_direction:
|
| 389 |
+
if static is not None and "direction_embedding" in static:
|
| 390 |
+
z_0.append(static["direction_embedding"])
|
| 391 |
+
else:
|
| 392 |
+
direction_embedding = embed_direction(
|
| 393 |
+
input_features["CA_pos"]["trans_equilibrium"],
|
| 394 |
+
input_features["rotmats_equilibrium"],
|
| 395 |
+
dist_cutoff=self.embed_direction_cutoff
|
| 396 |
+
)
|
| 397 |
+
z_0.append(direction_embedding.reshape([B, N**2, -1]))
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
# TODO: get_length_embedding expects a tensor of shape [...,N].
|
| 401 |
+
# It ignores elements and just uses .shape[-1] and device.
|
| 402 |
+
# Don't want to change it, so we just pass in an empty tensor.
|
| 403 |
+
if static is not None and "length_embedding" in static:
|
| 404 |
+
length_embedding = static["length_embedding"]
|
| 405 |
+
else:
|
| 406 |
+
length_embedding = self.length_embedder(
|
| 407 |
+
torch.empty(1, N).to(device=device)
|
| 408 |
+
)
|
| 409 |
+
length_embedding = length_embedding.repeat([B, 1, 1])
|
| 410 |
+
h_0.append(length_embedding)
|
| 411 |
+
|
| 412 |
+
if self.index_embed_type is None:
|
| 413 |
+
pass
|
| 414 |
+
elif self.index_embed_type == "full":
|
| 415 |
+
if static is not None and "index_node_embedding" in static:
|
| 416 |
+
h_0.append(static["index_node_embedding"])
|
| 417 |
+
z_0.append(static["index_edge_embedding"])
|
| 418 |
+
else:
|
| 419 |
+
seq_idx = torch.arange(N).repeat(B, 1).to(device=device)
|
| 420 |
+
h_0.append(self.index_embedder(seq_idx))
|
| 421 |
+
rel_seq_offset = seq_idx[:, :, None] - seq_idx[:, None, :]
|
| 422 |
+
rel_seq_offset = rel_seq_offset.reshape([B, N**2])
|
| 423 |
+
z_0.append(self.linear_relpos(self.index_embedder(rel_seq_offset)))
|
| 424 |
+
elif self.index_embed_type == "neighbor":
|
| 425 |
+
if static is not None and "index_edge_embedding" in static:
|
| 426 |
+
z_0.append(static["index_edge_embedding"])
|
| 427 |
+
else:
|
| 428 |
+
neighbors = torch.diag_embed(torch.ones(N-1, device=device), offset=1) + \
|
| 429 |
+
torch.diag_embed(torch.ones(N-1, device=device), offset=-1)
|
| 430 |
+
neighbors = neighbors[None].repeat(B, 1, 1).reshape([B, N**2])[...,None]
|
| 431 |
+
z_0.append(neighbors)
|
| 432 |
+
else:
|
| 433 |
+
raise ValueError("index_embed_type must be None/'none', 'full' or 'neighbor'.")
|
| 434 |
+
|
| 435 |
+
h_0 = torch.cat(h_0, dim=-1)
|
| 436 |
+
h_0 = self.node_embedding(h_0)
|
| 437 |
+
if self.inject_embedder:
|
| 438 |
+
if static is not None and "node_condition_embedding" in static:
|
| 439 |
+
h_0 = h_0 + static["node_condition_embedding"].to(dtype=h_0.dtype)
|
| 440 |
+
else:
|
| 441 |
+
h_0 = h_0 + self.z_node_adapter(node_cond.to(dtype=h_0.dtype))
|
| 442 |
+
h_0 = h_0 + self.disp_node_adapter(disp_node_cond.to(dtype=h_0.dtype))
|
| 443 |
+
|
| 444 |
+
z_0.append(self._cross_concat(self.linear_s_p(h_0), B, N))
|
| 445 |
+
|
| 446 |
+
z_0 = torch.cat(z_0, dim=-1)
|
| 447 |
+
z_0 = self.edge_embedding(z_0)
|
| 448 |
+
z_0 = z_0.reshape([B, N, N, -1])
|
| 449 |
+
if self.inject_embedder:
|
| 450 |
+
if static is not None and "edge_condition_embedding" in static:
|
| 451 |
+
z_0 = z_0 + static["edge_condition_embedding"].to(dtype=z_0.dtype)
|
| 452 |
+
else:
|
| 453 |
+
z_0 = z_0 + self.z_edge_adapter(edge_cond.to(dtype=z_0.dtype))
|
| 454 |
+
z_0 = z_0 + self.disp_edge_adapter(disp_edge_cond.to(dtype=z_0.dtype))
|
| 455 |
+
|
| 456 |
+
return h_0, z_0
|
| 457 |
+
|
| 458 |
+
def _cross_concat(self, feats_1d, B, N):
|
| 459 |
+
return torch.cat([
|
| 460 |
+
feats_1d[:, :, None, :].expand(-1, -1, N, -1),
|
| 461 |
+
feats_1d[:, None, :, :].expand(-1, N, -1, -1),
|
| 462 |
+
], dim=-1).float().reshape([B, N**2, -1])
|
| 463 |
+
|
bbflow_base/code_exports/a30_redesign_source_20260719/bbflow/models/latent.py
ADDED
|
@@ -0,0 +1,1317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
from bbflow.data.alignment import kabsch_align
|
| 8 |
+
|
| 9 |
+
class _MotionPriorBlock(nn.Module):
|
| 10 |
+
"""Single edge/node message passing block for the motion prior."""
|
| 11 |
+
|
| 12 |
+
def __init__(self, hidden_dim):
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.edge_norm = nn.LayerNorm(3 * hidden_dim)
|
| 15 |
+
self.node_norm = nn.LayerNorm(2 * hidden_dim)
|
| 16 |
+
self.edge_update = nn.Sequential(
|
| 17 |
+
nn.Linear(3 * hidden_dim, hidden_dim),
|
| 18 |
+
nn.ReLU(),
|
| 19 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 20 |
+
nn.ReLU(),
|
| 21 |
+
)
|
| 22 |
+
self.node_update = nn.Sequential(
|
| 23 |
+
nn.Linear(2 * hidden_dim, hidden_dim),
|
| 24 |
+
nn.ReLU(),
|
| 25 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 26 |
+
nn.ReLU(),
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def forward(self, node_state, edge_state, pair_mask):
|
| 30 |
+
pair_mask = pair_mask[..., None]
|
| 31 |
+
masked_edge = edge_state * pair_mask
|
| 32 |
+
|
| 33 |
+
src = node_state[:, :, None, :].expand(-1, -1, node_state.shape[1], -1)
|
| 34 |
+
dst = node_state[:, None, :, :].expand(-1, node_state.shape[1], -1, -1)
|
| 35 |
+
|
| 36 |
+
edge_input = torch.cat([masked_edge, src, dst], dim=-1)
|
| 37 |
+
edge_state = edge_state + self.edge_update(self.edge_norm(edge_input))
|
| 38 |
+
edge_state = edge_state * pair_mask
|
| 39 |
+
|
| 40 |
+
node_mask = pair_mask.squeeze(-1).sum(dim=2).clamp_min(1.0)[..., None]
|
| 41 |
+
incoming = (edge_state * pair_mask).sum(dim=2) / node_mask
|
| 42 |
+
outgoing = (edge_state * pair_mask).sum(dim=1) / node_mask
|
| 43 |
+
node_input = torch.cat([incoming, outgoing], dim=-1)
|
| 44 |
+
node_state = node_state + self.node_update(self.node_norm(node_input))
|
| 45 |
+
return node_state, edge_state
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class LatentEncoder(nn.Module):
|
| 49 |
+
"""Equilibrium-conditioned template-mode motion prior.
|
| 50 |
+
|
| 51 |
+
The prior predicts K global template motion fields from x_eq. Each mode has a
|
| 52 |
+
shared template generated by omega/v/center plus signed per-residue participation
|
| 53 |
+
and a small local-frame residual. The resulting modes reconstruct local/cross
|
| 54 |
+
covariance targets and provide node/edge conditions for BBFlow adapters.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def __init__(self, latent_cfg):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.dim = int(getattr(latent_cfg, "dim", 16))
|
| 60 |
+
self.num_modes = int(getattr(latent_cfg, "num_modes", 8))
|
| 61 |
+
self.node_cond_dim = self.num_modes
|
| 62 |
+
self.edge_cond_dim = self.num_modes
|
| 63 |
+
self.z_stochastic = False
|
| 64 |
+
hidden_dim = int(getattr(latent_cfg, "motion_hidden_dim", 128))
|
| 65 |
+
dist_bins = int(getattr(latent_cfg, "motion_dist_bins", 16))
|
| 66 |
+
self.register_buffer("dist_centers", torch.linspace(0.0, 40.0, dist_bins))
|
| 67 |
+
self.dist_width = float(getattr(latent_cfg, "motion_dist_width", 4.0))
|
| 68 |
+
# Raised 1e-6 -> 1e-4 (norm floor 1e-3 -> 1e-2): bounds how far a collapsing
|
| 69 |
+
# mode's normalization can amplify in the forward, hardening against overflow
|
| 70 |
+
# in the u^4 covariance terms under bf16.
|
| 71 |
+
self.mode_norm_eps = float(getattr(latent_cfg, "mode_norm_eps", 1e-4))
|
| 72 |
+
self.cross_cov_near_distance = float(getattr(latent_cfg, "cross_cov_near_distance", 12.0))
|
| 73 |
+
self.pca_align_top_m = int(getattr(latent_cfg, "pca_align_top_m", 2))
|
| 74 |
+
if bool(getattr(latent_cfg, "use_enm_features", False)):
|
| 75 |
+
raise ValueError("ENM cannot be used as a forward feature; use experiment.training.enm_warmup_epochs for ENM initialization only.")
|
| 76 |
+
self.use_enm_features = False
|
| 77 |
+
self.enm_num_modes = int(getattr(latent_cfg, "enm_num_modes", self.num_modes))
|
| 78 |
+
self.enm_cutoff = float(getattr(latent_cfg, "enm_cutoff", 12.0))
|
| 79 |
+
self.enm_eps = float(getattr(latent_cfg, "enm_eps", 1e-6))
|
| 80 |
+
self.mixture_components = int(getattr(latent_cfg, "mixture_components", 2))
|
| 81 |
+
self.q_lstsq_ridge = float(getattr(latent_cfg, "q_lstsq_ridge", 1e-4))
|
| 82 |
+
self.q_cholesky_jitter = float(getattr(latent_cfg, "q_cholesky_jitter", 1e-4))
|
| 83 |
+
self.q_detach_projection = bool(getattr(latent_cfg, "q_detach_projection", True))
|
| 84 |
+
self.q_detach_shared_encoder = bool(
|
| 85 |
+
getattr(latent_cfg, "q_detach_shared_encoder", False)
|
| 86 |
+
)
|
| 87 |
+
self.sample_coefficients = bool(getattr(latent_cfg, "sample_coefficients", False))
|
| 88 |
+
self.energy_from_q = bool(getattr(latent_cfg, "energy_from_q", False))
|
| 89 |
+
self.energy_from_q_full_cov = bool(getattr(latent_cfg, "energy_from_q_full_cov", False))
|
| 90 |
+
tril = torch.tril_indices(self.num_modes, self.num_modes)
|
| 91 |
+
self.register_buffer("mixture_tril_rows", tril[0], persistent=False)
|
| 92 |
+
self.register_buffer("mixture_tril_cols", tril[1], persistent=False)
|
| 93 |
+
|
| 94 |
+
# The scalar prior encoder must be rotation-invariant. Vector quantities
|
| 95 |
+
# are recovered later as weighted sums of coordinates or local-frame
|
| 96 |
+
# residuals; feeding raw coordinates/rotations here breaks equivariance.
|
| 97 |
+
node_in = 1 + 21 + dist_bins
|
| 98 |
+
pair_in = dist_bins
|
| 99 |
+
self.prior_node_mlp = nn.Sequential(
|
| 100 |
+
nn.Linear(node_in, hidden_dim),
|
| 101 |
+
nn.ReLU(),
|
| 102 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 103 |
+
nn.ReLU(),
|
| 104 |
+
)
|
| 105 |
+
self.prior_pair_mlp = nn.Sequential(
|
| 106 |
+
nn.Linear(pair_in, hidden_dim),
|
| 107 |
+
nn.ReLU(),
|
| 108 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 109 |
+
nn.ReLU(),
|
| 110 |
+
)
|
| 111 |
+
self.motion_message_passing_layers = int(getattr(latent_cfg, "motion_message_passing_layers", 4))
|
| 112 |
+
self.prior_message_passing_layers = nn.ModuleList(
|
| 113 |
+
[_MotionPriorBlock(hidden_dim) for _ in range(self.motion_message_passing_layers)]
|
| 114 |
+
)
|
| 115 |
+
self.prior_update = nn.Sequential(
|
| 116 |
+
nn.Linear(2 * hidden_dim, hidden_dim),
|
| 117 |
+
nn.ReLU(),
|
| 118 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 119 |
+
nn.ReLU(),
|
| 120 |
+
)
|
| 121 |
+
self.energy_out = nn.Sequential(
|
| 122 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 123 |
+
nn.ReLU(),
|
| 124 |
+
nn.Linear(hidden_dim, self.num_modes),
|
| 125 |
+
)
|
| 126 |
+
self.template_residual_scale = float(getattr(latent_cfg, "template_residual_scale", 0.1))
|
| 127 |
+
self.template_remove_rotation = bool(getattr(latent_cfg, "template_remove_rotation", True))
|
| 128 |
+
self.template_center_logits = nn.Linear(hidden_dim, self.num_modes)
|
| 129 |
+
self.template_omega_logits = nn.Linear(hidden_dim, self.num_modes)
|
| 130 |
+
self.template_velocity_logits = nn.Linear(hidden_dim, self.num_modes)
|
| 131 |
+
self.template_participation = nn.Linear(hidden_dim, self.num_modes)
|
| 132 |
+
self.template_residual = nn.Linear(hidden_dim, self.num_modes * 3)
|
| 133 |
+
self.mixture_logits_out = nn.Linear(hidden_dim, self.mixture_components)
|
| 134 |
+
self.mixture_mu_out = nn.Linear(hidden_dim, self.mixture_components * self.num_modes)
|
| 135 |
+
self.mixture_tril_out = nn.Linear(
|
| 136 |
+
hidden_dim,
|
| 137 |
+
self.mixture_components * (self.num_modes * (self.num_modes + 1) // 2),
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
@staticmethod
|
| 141 |
+
def _masked_mean(x, mask):
|
| 142 |
+
denom = mask.sum(dim=1, keepdim=True).clamp_min(1.0)
|
| 143 |
+
return (x * mask[..., None]).sum(dim=1) / denom
|
| 144 |
+
|
| 145 |
+
@staticmethod
|
| 146 |
+
def _masked_std(x, mask):
|
| 147 |
+
mean = LatentEncoder._masked_mean(x[..., None], mask).squeeze(-1)
|
| 148 |
+
denom = mask.sum(dim=1).clamp_min(1.0)
|
| 149 |
+
var = (((x - mean[:, None]) ** 2) * mask).sum(dim=1) / denom
|
| 150 |
+
return torch.sqrt(var.clamp_min(1e-12))
|
| 151 |
+
|
| 152 |
+
@staticmethod
|
| 153 |
+
def align_to_reference(trans, ref_trans, res_mask):
|
| 154 |
+
return kabsch_align(trans, ref_trans, res_mask)
|
| 155 |
+
|
| 156 |
+
@staticmethod
|
| 157 |
+
def relative_displacement(trans, ref_trans, res_mask):
|
| 158 |
+
aligned = LatentEncoder.align_to_reference(trans, ref_trans, res_mask)
|
| 159 |
+
if ref_trans.dim() == 2:
|
| 160 |
+
ref_trans = ref_trans.unsqueeze(0).expand_as(aligned)
|
| 161 |
+
return aligned - ref_trans
|
| 162 |
+
|
| 163 |
+
@staticmethod
|
| 164 |
+
def _group_mean(x, group_index):
|
| 165 |
+
groups = torch.unique(group_index, sorted=True)
|
| 166 |
+
pooled = []
|
| 167 |
+
for group in groups:
|
| 168 |
+
pooled.append(x[group_index == group].mean(dim=0))
|
| 169 |
+
return torch.stack(pooled, dim=0), groups
|
| 170 |
+
|
| 171 |
+
def _pair_rbf(self, trans_eq, res_mask):
|
| 172 |
+
with torch.autocast(device_type=trans_eq.device.type, enabled=False):
|
| 173 |
+
trans = trans_eq.float()
|
| 174 |
+
dists = torch.cdist(trans, trans)
|
| 175 |
+
centers = self.dist_centers.to(device=trans_eq.device, dtype=torch.float32)
|
| 176 |
+
rbf = torch.exp(-((dists[..., None] - centers) / self.dist_width) ** 2)
|
| 177 |
+
pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :]
|
| 178 |
+
return rbf.to(dtype=trans_eq.dtype), pair_mask.to(dtype=trans_eq.dtype)
|
| 179 |
+
|
| 180 |
+
def _pair_distance_features(self, trans_eq, res_mask):
|
| 181 |
+
rbf, pair_mask = self._pair_rbf(trans_eq, res_mask)
|
| 182 |
+
denom = pair_mask.sum(dim=2, keepdim=True).clamp_min(1.0)
|
| 183 |
+
return (rbf * pair_mask[..., None]).sum(dim=2) / denom
|
| 184 |
+
|
| 185 |
+
def _enm_modes_and_weights_single(self, coords, mask):
|
| 186 |
+
valid = mask.bool()
|
| 187 |
+
n_total = coords.shape[0]
|
| 188 |
+
out = coords.new_zeros(n_total, self.enm_num_modes, 3, dtype=torch.float32)
|
| 189 |
+
weights = coords.new_zeros(self.enm_num_modes, dtype=torch.float32)
|
| 190 |
+
coords_valid = coords[valid].float()
|
| 191 |
+
n_valid = coords_valid.shape[0]
|
| 192 |
+
if n_valid < 3:
|
| 193 |
+
return out, weights
|
| 194 |
+
|
| 195 |
+
diff = coords_valid[:, None, :] - coords_valid[None, :, :]
|
| 196 |
+
dist = torch.linalg.norm(diff, dim=-1).clamp_min(self.enm_eps)
|
| 197 |
+
contact = (dist < self.enm_cutoff) & (~torch.eye(n_valid, device=coords.device, dtype=torch.bool))
|
| 198 |
+
if not contact.any():
|
| 199 |
+
return out, weights
|
| 200 |
+
|
| 201 |
+
unit = diff / dist[..., None]
|
| 202 |
+
outer = unit[..., :, None] * unit[..., None, :]
|
| 203 |
+
off_diag = -outer * contact[..., None, None].float()
|
| 204 |
+
h_blocks = off_diag.clone()
|
| 205 |
+
diag_blocks = -off_diag.sum(dim=1)
|
| 206 |
+
idx = torch.arange(n_valid, device=coords.device)
|
| 207 |
+
h_blocks[idx, idx] = diag_blocks
|
| 208 |
+
hessian = h_blocks.permute(0, 2, 1, 3).reshape(3 * n_valid, 3 * n_valid)
|
| 209 |
+
hessian = 0.5 * (hessian + hessian.transpose(0, 1))
|
| 210 |
+
|
| 211 |
+
evals, evecs = torch.linalg.eigh(hessian)
|
| 212 |
+
start = min(6, evecs.shape[1])
|
| 213 |
+
stop = min(start + self.enm_num_modes, evecs.shape[1])
|
| 214 |
+
if stop <= start:
|
| 215 |
+
return out, weights
|
| 216 |
+
modes = evecs[:, start:stop].reshape(n_valid, 3, stop - start).permute(0, 2, 1).contiguous()
|
| 217 |
+
inv_evals = 1.0 / evals[start:stop].float().clamp_min(self.enm_eps)
|
| 218 |
+
inv_evals = inv_evals / inv_evals.mean().clamp_min(self.enm_eps)
|
| 219 |
+
|
| 220 |
+
flat = modes.reshape(modes.shape[0], modes.shape[1], 3)
|
| 221 |
+
for mode_idx in range(modes.shape[1]):
|
| 222 |
+
values = flat[:, mode_idx, :].reshape(-1)
|
| 223 |
+
max_idx = values.abs().argmax()
|
| 224 |
+
sign = torch.sign(values[max_idx]).clamp_min(0.0) * 2.0 - 1.0
|
| 225 |
+
modes[:, mode_idx, :] = modes[:, mode_idx, :] * sign
|
| 226 |
+
out[valid, :modes.shape[1], :] = modes
|
| 227 |
+
weights[:modes.shape[1]] = inv_evals
|
| 228 |
+
return out, weights
|
| 229 |
+
|
| 230 |
+
def _enm_modes_single(self, coords, mask):
|
| 231 |
+
modes, _ = self._enm_modes_and_weights_single(coords, mask)
|
| 232 |
+
return modes
|
| 233 |
+
|
| 234 |
+
def _enm_modes_batch(self, trans_eq, res_mask):
|
| 235 |
+
modes = []
|
| 236 |
+
with torch.no_grad(), torch.autocast(device_type=trans_eq.device.type, enabled=False):
|
| 237 |
+
for coords, mask in zip(trans_eq.float(), res_mask.float()):
|
| 238 |
+
modes.append(self._enm_modes_single(coords, mask))
|
| 239 |
+
return torch.stack(modes, dim=0).to(device=trans_eq.device, dtype=torch.float32)
|
| 240 |
+
|
| 241 |
+
def _enm_modes_and_weights_batch(self, trans_eq, res_mask):
|
| 242 |
+
modes = []
|
| 243 |
+
weights = []
|
| 244 |
+
with torch.no_grad(), torch.autocast(device_type=trans_eq.device.type, enabled=False):
|
| 245 |
+
for coords, mask in zip(trans_eq.float(), res_mask.float()):
|
| 246 |
+
mode, weight = self._enm_modes_and_weights_single(coords, mask)
|
| 247 |
+
modes.append(mode)
|
| 248 |
+
weights.append(weight)
|
| 249 |
+
return (
|
| 250 |
+
torch.stack(modes, dim=0).to(device=trans_eq.device, dtype=torch.float32),
|
| 251 |
+
torch.stack(weights, dim=0).to(device=trans_eq.device, dtype=torch.float32),
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
def _enm_motion_targets(self, trans_eq, res_mask):
|
| 255 |
+
modes, energy = self._enm_modes_and_weights_batch(trans_eq, res_mask)
|
| 256 |
+
if modes.shape[2] < self.num_modes:
|
| 257 |
+
pad = modes.new_zeros(modes.shape[0], modes.shape[1], self.num_modes - modes.shape[2], 3)
|
| 258 |
+
modes = torch.cat([modes, pad], dim=2)
|
| 259 |
+
energy = torch.cat([energy, energy.new_zeros(energy.shape[0], self.num_modes - energy.shape[1])], dim=1)
|
| 260 |
+
modes = modes[:, :, : self.num_modes, :]
|
| 261 |
+
energy = energy[:, : self.num_modes]
|
| 262 |
+
mask = res_mask.float()
|
| 263 |
+
local_cov = torch.einsum("bk,bnki,bnkj->bnij", energy, modes, modes) * mask[:, :, None, None]
|
| 264 |
+
cross_cov = torch.einsum("bk,bikd,bjkd->bij", energy, modes, modes) * mask[:, :, None] * mask[:, None, :]
|
| 265 |
+
rmsf = torch.sqrt(torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)) * mask
|
| 266 |
+
return {
|
| 267 |
+
"enm_modes": modes,
|
| 268 |
+
"enm_energy": energy,
|
| 269 |
+
"local_cov": local_cov,
|
| 270 |
+
"cross_cov": cross_cov,
|
| 271 |
+
"rmsf": rmsf,
|
| 272 |
+
}
|
| 273 |
+
def _enm_node_features(self, trans_eq, rotmats_eq, res_mask):
|
| 274 |
+
del rotmats_eq
|
| 275 |
+
enm_global = self._enm_modes_batch(trans_eq, res_mask)
|
| 276 |
+
enm_mag = torch.linalg.norm(enm_global, dim=-1) * res_mask.float()[:, :, None]
|
| 277 |
+
return enm_mag.to(dtype=trans_eq.dtype)
|
| 278 |
+
|
| 279 |
+
def _enm_pair_features(self, trans_eq, res_mask):
|
| 280 |
+
enm_global = self._enm_modes_batch(trans_eq, res_mask)
|
| 281 |
+
enm_pair = torch.einsum("bikd,bjkd->bijk", enm_global, enm_global)
|
| 282 |
+
pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :]
|
| 283 |
+
return (enm_pair * pair_mask[..., None]).to(dtype=trans_eq.dtype)
|
| 284 |
+
|
| 285 |
+
def _equilibrium_node_feature_segments(self, trans_eq, rotmats_eq, seq, res_mask):
|
| 286 |
+
center = self._masked_mean(trans_eq, res_mask)
|
| 287 |
+
centered = trans_eq - center[:, None, :]
|
| 288 |
+
radius = torch.linalg.norm(centered, dim=-1, keepdim=True)
|
| 289 |
+
dist_feat = self._pair_distance_features(trans_eq, res_mask).to(dtype=trans_eq.dtype)
|
| 290 |
+
segments = [
|
| 291 |
+
("radius_from_center", radius),
|
| 292 |
+
("sequence_onehot", seq),
|
| 293 |
+
("pair_distance_rbf_mean", dist_feat),
|
| 294 |
+
]
|
| 295 |
+
return segments
|
| 296 |
+
|
| 297 |
+
def _equilibrium_node_features(self, trans_eq, rotmats_eq, seq, res_mask):
|
| 298 |
+
segments = self._equilibrium_node_feature_segments(trans_eq, rotmats_eq, seq, res_mask)
|
| 299 |
+
return torch.cat([tensor for _, tensor in segments], dim=-1)
|
| 300 |
+
|
| 301 |
+
def prior_feature_breakdown(self, trans_eq, rotmats_eq, seq, res_mask):
|
| 302 |
+
segments = self._equilibrium_node_feature_segments(trans_eq, rotmats_eq, seq, res_mask)
|
| 303 |
+
rows = []
|
| 304 |
+
start = 0
|
| 305 |
+
for name, tensor in segments:
|
| 306 |
+
dim = int(tensor.shape[-1])
|
| 307 |
+
end = start + dim
|
| 308 |
+
valid = tensor[res_mask.bool()]
|
| 309 |
+
rows.append({
|
| 310 |
+
"name": name,
|
| 311 |
+
"start": start,
|
| 312 |
+
"end": end,
|
| 313 |
+
"dim": dim,
|
| 314 |
+
"shape": list(tensor.shape),
|
| 315 |
+
"mean_abs": float(valid.detach().float().abs().mean().cpu().item()) if valid.numel() else 0.0,
|
| 316 |
+
"std": float(valid.detach().float().std().cpu().item()) if valid.numel() > 1 else 0.0,
|
| 317 |
+
})
|
| 318 |
+
start = end
|
| 319 |
+
node_features = torch.cat([tensor for _, tensor in segments], dim=-1)
|
| 320 |
+
expected_dim = int(self.prior_node_mlp[0].in_features)
|
| 321 |
+
return {
|
| 322 |
+
"segments": rows,
|
| 323 |
+
"total_dim": int(node_features.shape[-1]),
|
| 324 |
+
"expected_prior_node_in": expected_dim,
|
| 325 |
+
"matches_prior_node_in": int(node_features.shape[-1]) == expected_dim,
|
| 326 |
+
"order": [name for name, _ in segments],
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
def _encode_equilibrium(self, trans_eq, rotmats_eq, seq, res_mask):
|
| 330 |
+
node_features = self._equilibrium_node_features(trans_eq, rotmats_eq, seq, res_mask)
|
| 331 |
+
node_state = self.prior_node_mlp(node_features)
|
| 332 |
+
pair_rbf, pair_mask = self._pair_rbf(trans_eq, res_mask)
|
| 333 |
+
pair_features = pair_rbf
|
| 334 |
+
edge_state = self.prior_pair_mlp(pair_features.to(dtype=node_state.dtype))
|
| 335 |
+
pair_mask = pair_mask.to(dtype=node_state.dtype)
|
| 336 |
+
for block in self.prior_message_passing_layers:
|
| 337 |
+
node_state, edge_state = block(node_state, edge_state, pair_mask)
|
| 338 |
+
denom = pair_mask.sum(dim=2, keepdim=True).clamp_min(1.0)
|
| 339 |
+
pair_context = (edge_state * pair_mask[..., None]).sum(dim=2) / denom
|
| 340 |
+
return self.prior_update(torch.cat([node_state, pair_context], dim=-1))
|
| 341 |
+
|
| 342 |
+
@staticmethod
|
| 343 |
+
def _masked_mode_softmax(logits, res_mask):
|
| 344 |
+
mask = res_mask.bool()[:, None, :]
|
| 345 |
+
logits = logits.float().masked_fill(~mask, -1e9)
|
| 346 |
+
return torch.softmax(logits, dim=-1)
|
| 347 |
+
|
| 348 |
+
@staticmethod
|
| 349 |
+
def _global_to_local(u_global, rotmats_eq):
|
| 350 |
+
return torch.einsum("bnij,bnki->bnkj", rotmats_eq.float(), u_global.float())
|
| 351 |
+
|
| 352 |
+
@staticmethod
|
| 353 |
+
def _rotation_design(coords):
|
| 354 |
+
x, y, z = coords.unbind(dim=-1)
|
| 355 |
+
zeros = torch.zeros_like(x)
|
| 356 |
+
return torch.stack([
|
| 357 |
+
torch.stack([zeros, z, -y], dim=-1),
|
| 358 |
+
torch.stack([-z, zeros, x], dim=-1),
|
| 359 |
+
torch.stack([y, -x, zeros], dim=-1),
|
| 360 |
+
], dim=-2)
|
| 361 |
+
def _fit_rigid_motion(self, u_global, centered_coords, res_mask):
|
| 362 |
+
mask = res_mask.float()
|
| 363 |
+
translation = (u_global.float() * mask[:, :, None, None]).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)[:, None, None]
|
| 364 |
+
centered = (u_global.float() - translation[:, None, :, :]) * mask[:, :, None, None]
|
| 365 |
+
eye = torch.eye(3, device=u_global.device, dtype=torch.float32)
|
| 366 |
+
omega_out = []
|
| 367 |
+
rigid_out = []
|
| 368 |
+
coords = centered_coords.float()
|
| 369 |
+
for batch_idx in range(u_global.shape[0]):
|
| 370 |
+
valid = res_mask[batch_idx].bool()
|
| 371 |
+
if valid.sum() < 3:
|
| 372 |
+
omega_out.append(u_global.new_zeros(self.num_modes, 3))
|
| 373 |
+
rigid_out.append(centered[batch_idx])
|
| 374 |
+
continue
|
| 375 |
+
design = self._rotation_design(coords[batch_idx, valid]).reshape(-1, 3)
|
| 376 |
+
gram = design.transpose(0, 1) @ design + 1e-4 * eye
|
| 377 |
+
mode_omegas = []
|
| 378 |
+
mode_rigid = []
|
| 379 |
+
for mode_idx in range(self.num_modes):
|
| 380 |
+
target = centered[batch_idx, valid, mode_idx].reshape(-1)
|
| 381 |
+
rhs = design.transpose(0, 1) @ target
|
| 382 |
+
omega = torch.linalg.solve(gram, rhs)
|
| 383 |
+
rigid = (design @ omega).reshape(-1, 3)
|
| 384 |
+
full = centered[batch_idx, :, mode_idx].clone()
|
| 385 |
+
full[valid] = centered[batch_idx, valid, mode_idx] - rigid
|
| 386 |
+
mode_omegas.append(omega)
|
| 387 |
+
mode_rigid.append(full)
|
| 388 |
+
omega_out.append(torch.stack(mode_omegas, dim=0))
|
| 389 |
+
rigid_out.append(torch.stack(mode_rigid, dim=1))
|
| 390 |
+
return translation, torch.stack(omega_out, dim=0), torch.stack(rigid_out, dim=0)
|
| 391 |
+
|
| 392 |
+
def _remove_rigid_component(self, u_global, centered_coords, res_mask):
|
| 393 |
+
translation, _, cleaned = self._fit_rigid_motion(u_global, centered_coords, res_mask)
|
| 394 |
+
del translation
|
| 395 |
+
return cleaned * res_mask.float()[:, :, None, None]
|
| 396 |
+
def _mixture_params(self, pooled):
|
| 397 |
+
logits = self.mixture_logits_out(pooled)
|
| 398 |
+
mu = self.mixture_mu_out(pooled).reshape(
|
| 399 |
+
pooled.shape[0], self.mixture_components, self.num_modes
|
| 400 |
+
)
|
| 401 |
+
raw_tril = self.mixture_tril_out(pooled).reshape(
|
| 402 |
+
pooled.shape[0],
|
| 403 |
+
self.mixture_components,
|
| 404 |
+
self.num_modes * (self.num_modes + 1) // 2,
|
| 405 |
+
)
|
| 406 |
+
scale_tril = raw_tril.new_zeros(
|
| 407 |
+
pooled.shape[0], self.mixture_components, self.num_modes, self.num_modes
|
| 408 |
+
)
|
| 409 |
+
rows = self.mixture_tril_rows.to(device=raw_tril.device)
|
| 410 |
+
cols = self.mixture_tril_cols.to(device=raw_tril.device)
|
| 411 |
+
scale_tril[:, :, rows, cols] = raw_tril
|
| 412 |
+
diag = torch.diagonal(scale_tril, dim1=-2, dim2=-1)
|
| 413 |
+
scale_tril = scale_tril - torch.diag_embed(diag)
|
| 414 |
+
scale_tril = scale_tril + torch.diag_embed(F.softplus(diag) + self.q_cholesky_jitter)
|
| 415 |
+
return {
|
| 416 |
+
"mixture_logits": logits,
|
| 417 |
+
"mixture_log_probs": F.log_softmax(logits.float(), dim=-1).to(dtype=logits.dtype),
|
| 418 |
+
"mixture_mu": mu,
|
| 419 |
+
"mixture_scale_tril": scale_tril,
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
@staticmethod
|
| 423 |
+
def _mixture_entropy(logits):
|
| 424 |
+
probs = torch.softmax(logits.float(), dim=-1)
|
| 425 |
+
return -(probs * probs.clamp_min(1e-8).log()).sum(dim=-1)
|
| 426 |
+
|
| 427 |
+
@staticmethod
|
| 428 |
+
def mixture_second_moment(condition):
|
| 429 |
+
logits = condition["mixture_logits"].float()
|
| 430 |
+
mu = condition["mixture_mu"].float()
|
| 431 |
+
scale_tril = condition["mixture_scale_tril"].float()
|
| 432 |
+
probs = torch.softmax(logits, dim=-1)
|
| 433 |
+
cov = torch.einsum("bmik,bmjk->bmij", scale_tril, scale_tril)
|
| 434 |
+
second = cov + torch.einsum("bmi,bmj->bmij", mu, mu)
|
| 435 |
+
return torch.einsum("bm,bmij->bij", probs, second)
|
| 436 |
+
|
| 437 |
+
def mixture_nll(self, condition, coefficients):
|
| 438 |
+
coefficients = coefficients.float()
|
| 439 |
+
logits = condition["mixture_logits"].float()
|
| 440 |
+
mu = condition["mixture_mu"].float()
|
| 441 |
+
scale_tril = condition["mixture_scale_tril"].float()
|
| 442 |
+
diff = coefficients[:, None, :] - mu
|
| 443 |
+
solved = torch.linalg.solve_triangular(
|
| 444 |
+
scale_tril,
|
| 445 |
+
diff[..., None],
|
| 446 |
+
upper=False,
|
| 447 |
+
).squeeze(-1)
|
| 448 |
+
maha = solved.square().sum(dim=-1)
|
| 449 |
+
logdet = torch.diagonal(scale_tril, dim1=-2, dim2=-1).clamp_min(1e-8).log().sum(dim=-1)
|
| 450 |
+
normalizer = self.num_modes * math.log(2.0 * math.pi)
|
| 451 |
+
comp_log_prob = -0.5 * (normalizer + maha) - logdet
|
| 452 |
+
log_prob = torch.logsumexp(F.log_softmax(logits, dim=-1) + comp_log_prob, dim=-1)
|
| 453 |
+
return -log_prob.mean()
|
| 454 |
+
|
| 455 |
+
def sample_coefficients_from_q(self, condition):
|
| 456 |
+
logits = condition["mixture_logits"].float()
|
| 457 |
+
mu = condition["mixture_mu"].float()
|
| 458 |
+
scale_tril = condition["mixture_scale_tril"].float()
|
| 459 |
+
component = torch.distributions.Categorical(logits=logits).sample()
|
| 460 |
+
batch = torch.arange(logits.shape[0], device=logits.device)
|
| 461 |
+
selected_mu = mu[batch, component]
|
| 462 |
+
selected_scale = scale_tril[batch, component]
|
| 463 |
+
eps = torch.randn_like(selected_mu)
|
| 464 |
+
coeff = selected_mu + torch.einsum("bij,bj->bi", selected_scale, eps)
|
| 465 |
+
return coeff.to(dtype=condition["u_global"].dtype), component
|
| 466 |
+
|
| 467 |
+
def _condition_from_modes(self, u_global, rotmats_eq, res_mask, h, extra=None):
|
| 468 |
+
mask = res_mask.float()[:, :, None]
|
| 469 |
+
mode_norm = torch.sqrt(
|
| 470 |
+
((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)
|
| 471 |
+
)
|
| 472 |
+
# Stop-gradient on the gauge norm. Backprop through 1/mode_norm carries a
|
| 473 |
+
# 1/mode_norm^2 term that explodes once a mode collapses (norm -> the eps
|
| 474 |
+
# floor), which blows up the shared encoder into NaN. Detaching keeps the
|
| 475 |
+
# forward normalization identical while removing that runaway gradient.
|
| 476 |
+
u_global = u_global.float() / mode_norm.detach()[:, None, :, None]
|
| 477 |
+
u_local = self._global_to_local(u_global, rotmats_eq)
|
| 478 |
+
pooled = self._masked_mean(h, res_mask)
|
| 479 |
+
q_pooled = pooled.detach() if self.q_detach_shared_encoder else pooled
|
| 480 |
+
mixture = self._mixture_params(q_pooled)
|
| 481 |
+
q_second_moment = self.mixture_second_moment(mixture)
|
| 482 |
+
raw_energy = F.softplus(self.energy_out(pooled)) + 1e-6
|
| 483 |
+
if self.energy_from_q or self.energy_from_q_full_cov:
|
| 484 |
+
energy = torch.diagonal(q_second_moment, dim1=-2, dim2=-1).clamp_min(1e-8)
|
| 485 |
+
energy = energy + raw_energy * 0.0
|
| 486 |
+
else:
|
| 487 |
+
energy = raw_energy
|
| 488 |
+
sqrt_energy = torch.sqrt(energy).to(dtype=u_local.dtype)
|
| 489 |
+
node_cond = torch.linalg.norm(u_global.float(), dim=-1).to(dtype=u_local.dtype) * sqrt_energy[:, None, :]
|
| 490 |
+
disp_global = torch.einsum("bk,bnkd->bnd", sqrt_energy.float(), u_global.float())
|
| 491 |
+
disp_local = torch.einsum("bnij,bni->bnj", rotmats_eq.float(), disp_global)
|
| 492 |
+
disp_local = disp_local * res_mask.float()[:, :, None]
|
| 493 |
+
disp_edge_cond = torch.einsum("bid,bjd->bij", disp_global, disp_global)[:, :, :, None]
|
| 494 |
+
pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :]
|
| 495 |
+
disp_edge_cond = disp_edge_cond * pair_mask[:, :, :, None]
|
| 496 |
+
dot = torch.einsum("bikd,bjkd->bijk", u_global.float(), u_global.float())
|
| 497 |
+
edge_cond = dot.to(dtype=u_local.dtype) * energy[:, None, None, :].to(dtype=u_local.dtype)
|
| 498 |
+
if self.energy_from_q_full_cov:
|
| 499 |
+
local_cov_pred = torch.einsum(
|
| 500 |
+
"bkl,bnki,bnlj->bnij",
|
| 501 |
+
q_second_moment,
|
| 502 |
+
u_global.float(),
|
| 503 |
+
u_global.float(),
|
| 504 |
+
)
|
| 505 |
+
cross_cov_pred = torch.einsum(
|
| 506 |
+
"bkl,bikd,bjld->bij",
|
| 507 |
+
q_second_moment,
|
| 508 |
+
u_global.float(),
|
| 509 |
+
u_global.float(),
|
| 510 |
+
)
|
| 511 |
+
else:
|
| 512 |
+
local_cov_pred = torch.einsum("bk,bnki,bnkj->bnij", energy.float(), u_global.float(), u_global.float())
|
| 513 |
+
cross_cov_pred = edge_cond.float().sum(dim=-1)
|
| 514 |
+
rmsf_pred = torch.sqrt(torch.diagonal(local_cov_pred, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8))
|
| 515 |
+
condition = {
|
| 516 |
+
"node_cond": node_cond,
|
| 517 |
+
"edge_cond": edge_cond,
|
| 518 |
+
"disp_node_cond": disp_local.to(dtype=rotmats_eq.dtype),
|
| 519 |
+
"disp_edge_cond": disp_edge_cond.to(dtype=rotmats_eq.dtype),
|
| 520 |
+
"u_local": u_local.to(dtype=rotmats_eq.dtype),
|
| 521 |
+
"u_global": u_global.to(dtype=rotmats_eq.dtype),
|
| 522 |
+
"energy": energy.to(dtype=rotmats_eq.dtype),
|
| 523 |
+
"mode_norm": mode_norm.to(dtype=rotmats_eq.dtype),
|
| 524 |
+
"local_cov_pred": local_cov_pred.to(dtype=rotmats_eq.dtype),
|
| 525 |
+
"cross_cov_pred": cross_cov_pred.to(dtype=rotmats_eq.dtype),
|
| 526 |
+
"rmsf_pred": rmsf_pred.to(dtype=rotmats_eq.dtype),
|
| 527 |
+
"q_second_moment": q_second_moment.to(dtype=rotmats_eq.dtype),
|
| 528 |
+
}
|
| 529 |
+
condition.update(mixture)
|
| 530 |
+
|
| 531 |
+
if extra:
|
| 532 |
+
condition.update(extra)
|
| 533 |
+
return condition
|
| 534 |
+
|
| 535 |
+
def condition_from_mode_coefficients(
|
| 536 |
+
self,
|
| 537 |
+
u_global,
|
| 538 |
+
coefficients,
|
| 539 |
+
rotmats_eq,
|
| 540 |
+
res_mask,
|
| 541 |
+
extra=None,
|
| 542 |
+
include_statistics=True,
|
| 543 |
+
):
|
| 544 |
+
"""Build a sample-specific condition from fixed modes and per-frame coefficients.
|
| 545 |
+
|
| 546 |
+
Per-frame training uses signed mode coordinates c* from the current MD frame,
|
| 547 |
+
giving d_i = sum_k c*_k U_k[i] rather than a static sqrt(energy) field.
|
| 548 |
+
"""
|
| 549 |
+
mask = res_mask.float()[:, :, None]
|
| 550 |
+
u_global = u_global.float()
|
| 551 |
+
coefficients = coefficients.float()
|
| 552 |
+
mode_norm = torch.sqrt(
|
| 553 |
+
((u_global.square().sum(dim=-1) * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)).clamp_min(self.mode_norm_eps)
|
| 554 |
+
)
|
| 555 |
+
# Stop-gradient on the gauge norm (same 1/mode_norm^2 explosion as above).
|
| 556 |
+
# Detaching in BOTH the division and the compensating multiply leaves the
|
| 557 |
+
# forward product coeff*u_global identical while removing the runaway gradient.
|
| 558 |
+
mode_norm_sg = mode_norm.detach()
|
| 559 |
+
u_global = u_global / mode_norm_sg[:, None, :, None]
|
| 560 |
+
coefficients = coefficients * mode_norm_sg
|
| 561 |
+
u_local = self._global_to_local(u_global, rotmats_eq)
|
| 562 |
+
coeff_abs = coefficients.abs().to(dtype=u_local.dtype)
|
| 563 |
+
node_cond = torch.linalg.norm(u_global, dim=-1).to(dtype=u_local.dtype) * coeff_abs[:, None, :]
|
| 564 |
+
disp_global = torch.einsum("bk,bnkd->bnd", coefficients, u_global)
|
| 565 |
+
disp_local = torch.einsum("bnij,bni->bnj", rotmats_eq.float(), disp_global)
|
| 566 |
+
disp_local = disp_local * res_mask.float()[:, :, None]
|
| 567 |
+
pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :]
|
| 568 |
+
disp_edge_cond = torch.einsum("bid,bjd->bij", disp_global, disp_global)[:, :, :, None]
|
| 569 |
+
disp_edge_cond = disp_edge_cond * pair_mask[:, :, :, None]
|
| 570 |
+
dot = torch.einsum("bikd,bjkd->bijk", u_global, u_global)
|
| 571 |
+
edge_cond = dot.to(dtype=u_local.dtype) * coefficients.square()[:, None, None, :].to(dtype=u_local.dtype)
|
| 572 |
+
energy = coefficients.square()
|
| 573 |
+
condition = {
|
| 574 |
+
"node_cond": node_cond,
|
| 575 |
+
"edge_cond": edge_cond,
|
| 576 |
+
"disp_node_cond": disp_local.to(dtype=rotmats_eq.dtype),
|
| 577 |
+
"disp_edge_cond": disp_edge_cond.to(dtype=rotmats_eq.dtype),
|
| 578 |
+
"u_local": u_local.to(dtype=rotmats_eq.dtype),
|
| 579 |
+
"u_global": u_global.to(dtype=rotmats_eq.dtype),
|
| 580 |
+
"energy": energy.to(dtype=rotmats_eq.dtype),
|
| 581 |
+
"mode_coefficients": coefficients.to(dtype=rotmats_eq.dtype),
|
| 582 |
+
"mode_norm": mode_norm.to(dtype=rotmats_eq.dtype),
|
| 583 |
+
}
|
| 584 |
+
if include_statistics:
|
| 585 |
+
local_cov_pred = torch.einsum(
|
| 586 |
+
"bk,bnki,bnkj->bnij", energy, u_global, u_global
|
| 587 |
+
)
|
| 588 |
+
condition.update({
|
| 589 |
+
"local_cov_pred": local_cov_pred.to(dtype=rotmats_eq.dtype),
|
| 590 |
+
"cross_cov_pred": edge_cond.float().sum(dim=-1).to(dtype=rotmats_eq.dtype),
|
| 591 |
+
"rmsf_pred": torch.sqrt(
|
| 592 |
+
torch.diagonal(local_cov_pred, dim1=-2, dim2=-1)
|
| 593 |
+
.sum(dim=-1)
|
| 594 |
+
.clamp_min(1e-8)
|
| 595 |
+
).to(dtype=rotmats_eq.dtype),
|
| 596 |
+
})
|
| 597 |
+
if extra:
|
| 598 |
+
condition.update(extra)
|
| 599 |
+
return condition
|
| 600 |
+
|
| 601 |
+
def oracle_condition_from_targets(self, trans_1, trans_eq, rotmats_eq, res_mask, targets):
|
| 602 |
+
modes = targets["oracle_modes"].to(device=trans_eq.device, dtype=torch.float32)
|
| 603 |
+
mean_disp = targets.get("oracle_mean_disp")
|
| 604 |
+
if mean_disp is None:
|
| 605 |
+
mean_disp = torch.zeros_like(trans_eq, dtype=torch.float32)
|
| 606 |
+
else:
|
| 607 |
+
mean_disp = mean_disp.to(device=trans_eq.device, dtype=torch.float32)
|
| 608 |
+
disp = self.relative_displacement(trans_1.float(), trans_eq.float(), res_mask)
|
| 609 |
+
centered_disp = (disp - mean_disp) * res_mask.float()[:, :, None]
|
| 610 |
+
coefficients = self.project_displacement_to_modes(centered_disp, modes, res_mask)
|
| 611 |
+
recon = torch.einsum("bk,bnkd->bnd", coefficients.float(), modes.float())
|
| 612 |
+
return self.condition_from_mode_coefficients(
|
| 613 |
+
modes,
|
| 614 |
+
coefficients,
|
| 615 |
+
rotmats_eq,
|
| 616 |
+
res_mask,
|
| 617 |
+
extra={
|
| 618 |
+
"oracle_centered_disp": centered_disp.to(dtype=rotmats_eq.dtype),
|
| 619 |
+
"oracle_recon_disp": recon.to(dtype=rotmats_eq.dtype),
|
| 620 |
+
},
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
def frame_condition_from_projection(
|
| 624 |
+
self,
|
| 625 |
+
trans_1,
|
| 626 |
+
trans_eq,
|
| 627 |
+
rotmats_eq,
|
| 628 |
+
res_mask,
|
| 629 |
+
prior_condition,
|
| 630 |
+
mean_disp=None,
|
| 631 |
+
):
|
| 632 |
+
"""Project the frame's centered fluctuation onto predicted motion modes.
|
| 633 |
+
|
| 634 |
+
Motion covariance targets are centered over MD time, so the coefficient
|
| 635 |
+
target must remove the same per-protein mean displacement. The solve uses
|
| 636 |
+
detached modes by default, while flow loss still reaches the original modes
|
| 637 |
+
through the reconstructed generator condition.
|
| 638 |
+
"""
|
| 639 |
+
raw_disp = self.relative_displacement(trans_1.float(), trans_eq.float(), res_mask)
|
| 640 |
+
mask = res_mask.float()[:, :, None]
|
| 641 |
+
if mean_disp is None:
|
| 642 |
+
raise ValueError(
|
| 643 |
+
"per-frame mode projection requires oracle_mean_disp in the motion-target cache; "
|
| 644 |
+
"regenerate the cache or use one that contains centered MD targets"
|
| 645 |
+
)
|
| 646 |
+
mean_disp = mean_disp.to(device=raw_disp.device, dtype=raw_disp.dtype)
|
| 647 |
+
disp = (raw_disp - mean_disp) * mask
|
| 648 |
+
coefficients = self.project_displacement_lstsq(
|
| 649 |
+
disp,
|
| 650 |
+
prior_condition["u_global"],
|
| 651 |
+
res_mask,
|
| 652 |
+
ridge=self.q_lstsq_ridge,
|
| 653 |
+
detach_modes=self.q_detach_projection,
|
| 654 |
+
)
|
| 655 |
+
recon_objective = self.projection_reconstruction_objective(
|
| 656 |
+
disp,
|
| 657 |
+
prior_condition["u_global"],
|
| 658 |
+
coefficients,
|
| 659 |
+
res_mask,
|
| 660 |
+
ridge=self.q_lstsq_ridge,
|
| 661 |
+
)
|
| 662 |
+
recon = recon_objective["recon"]
|
| 663 |
+
uncentered_error = ((raw_disp - recon).square() * mask).sum(dim=(1, 2)).sqrt()
|
| 664 |
+
uncentered_denom = (raw_disp.square() * mask).sum(dim=(1, 2)).sqrt().clamp_min(1e-8)
|
| 665 |
+
passthrough = {
|
| 666 |
+
key: prior_condition[key]
|
| 667 |
+
for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"]
|
| 668 |
+
if key in prior_condition
|
| 669 |
+
}
|
| 670 |
+
condition = self.condition_from_mode_coefficients(
|
| 671 |
+
prior_condition["u_global"],
|
| 672 |
+
coefficients,
|
| 673 |
+
rotmats_eq,
|
| 674 |
+
res_mask,
|
| 675 |
+
extra=passthrough,
|
| 676 |
+
include_statistics=False,
|
| 677 |
+
)
|
| 678 |
+
condition["projection_uncentered_target_disp"] = raw_disp.to(dtype=rotmats_eq.dtype)
|
| 679 |
+
condition["projection_mean_disp"] = mean_disp.to(dtype=rotmats_eq.dtype)
|
| 680 |
+
condition["projection_target_disp"] = disp.to(dtype=rotmats_eq.dtype)
|
| 681 |
+
condition["projection_recon_disp"] = recon.to(dtype=rotmats_eq.dtype)
|
| 682 |
+
condition["projection_recon_loss"] = recon_objective["loss"].to(dtype=rotmats_eq.dtype)
|
| 683 |
+
condition["projection_recon_rel_error"] = recon_objective["rel_error"].to(dtype=rotmats_eq.dtype)
|
| 684 |
+
condition["projection_uncentered_recon_rel_error"] = (
|
| 685 |
+
uncentered_error / uncentered_denom
|
| 686 |
+
).to(dtype=rotmats_eq.dtype)
|
| 687 |
+
return condition, coefficients
|
| 688 |
+
|
| 689 |
+
def _mode_predictions(self, h, trans_eq, rotmats_eq, res_mask):
|
| 690 |
+
center = self._masked_mean(trans_eq.float(), res_mask)
|
| 691 |
+
centered = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None]
|
| 692 |
+
|
| 693 |
+
residual_local = torch.tanh(self.template_residual(h).reshape(h.shape[0], h.shape[1], self.num_modes, 3))
|
| 694 |
+
residual_global = torch.einsum("bnij,bnkj->bnki", rotmats_eq.float(), residual_local.float())
|
| 695 |
+
residual_global = self.template_residual_scale * residual_global
|
| 696 |
+
|
| 697 |
+
center_logits = self.template_center_logits(h).transpose(1, 2)
|
| 698 |
+
omega_logits = self.template_omega_logits(h).transpose(1, 2)
|
| 699 |
+
velocity_logits = self.template_velocity_logits(h).transpose(1, 2)
|
| 700 |
+
center_weights = self._masked_mode_softmax(center_logits, res_mask)
|
| 701 |
+
omega_weights = self._masked_mode_softmax(omega_logits, res_mask)
|
| 702 |
+
velocity_weights = self._masked_mode_softmax(velocity_logits, res_mask)
|
| 703 |
+
|
| 704 |
+
mode_center = torch.einsum("bkn,bnd->bkd", center_weights, centered)
|
| 705 |
+
omega = torch.einsum("bkn,bnd->bkd", omega_weights, centered)
|
| 706 |
+
velocity = torch.einsum("bkn,bnd->bkd", velocity_weights, centered)
|
| 707 |
+
participation = self.template_participation(h)
|
| 708 |
+
|
| 709 |
+
rel = centered[:, :, None, :] - mode_center[:, None, :, :]
|
| 710 |
+
base = torch.cross(omega[:, None, :, :].expand_as(rel), rel, dim=-1) + velocity[:, None, :, :]
|
| 711 |
+
u_global = participation[..., None].float() * base + residual_global
|
| 712 |
+
u_global = self._remove_rigid_component(u_global, centered, res_mask)
|
| 713 |
+
extra = {
|
| 714 |
+
"template_center": mode_center.to(dtype=rotmats_eq.dtype),
|
| 715 |
+
"template_omega": omega.to(dtype=rotmats_eq.dtype),
|
| 716 |
+
"template_velocity": velocity.to(dtype=rotmats_eq.dtype),
|
| 717 |
+
"template_participation": participation.to(dtype=rotmats_eq.dtype),
|
| 718 |
+
"template_residual_global": residual_global.to(dtype=rotmats_eq.dtype),
|
| 719 |
+
}
|
| 720 |
+
return self._condition_from_modes(u_global, rotmats_eq, res_mask, h, extra=extra)
|
| 721 |
+
|
| 722 |
+
def forward_prior(self, trans_eq, rotmats_eq, seq, res_mask):
|
| 723 |
+
h = self._encode_equilibrium(trans_eq, rotmats_eq, seq, res_mask)
|
| 724 |
+
return self._mode_predictions(h, trans_eq, rotmats_eq, res_mask), None
|
| 725 |
+
|
| 726 |
+
def sample_prior_z(self, trans_eq, rotmats_eq, seq, res_mask):
|
| 727 |
+
condition, _ = self.forward_prior(trans_eq, rotmats_eq, seq, res_mask)
|
| 728 |
+
if not self.sample_coefficients:
|
| 729 |
+
return condition
|
| 730 |
+
coefficients, component = self.sample_coefficients_from_q(condition)
|
| 731 |
+
sampled = self.condition_from_mode_coefficients(
|
| 732 |
+
condition["u_global"],
|
| 733 |
+
coefficients,
|
| 734 |
+
rotmats_eq,
|
| 735 |
+
res_mask,
|
| 736 |
+
extra={
|
| 737 |
+
key: condition[key]
|
| 738 |
+
for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"]
|
| 739 |
+
if key in condition
|
| 740 |
+
},
|
| 741 |
+
)
|
| 742 |
+
sampled["sampled_mixture_component"] = component
|
| 743 |
+
return sampled
|
| 744 |
+
@staticmethod
|
| 745 |
+
def repeat_condition(condition, batch_size):
|
| 746 |
+
repeated = {}
|
| 747 |
+
for key, value in condition.items():
|
| 748 |
+
if torch.is_tensor(value):
|
| 749 |
+
repeated[key] = value.repeat(batch_size, *([1] * (value.dim() - 1)))
|
| 750 |
+
else:
|
| 751 |
+
repeated[key] = value
|
| 752 |
+
return repeated
|
| 753 |
+
|
| 754 |
+
@staticmethod
|
| 755 |
+
def compute_motion_targets(frames_group, x_eq, res_mask, num_modes=8):
|
| 756 |
+
"""Offline targets from full MD: covariance targets plus oracle PCA modes."""
|
| 757 |
+
with torch.no_grad():
|
| 758 |
+
disp = LatentEncoder.relative_displacement(
|
| 759 |
+
frames_group.float(),
|
| 760 |
+
x_eq.float(),
|
| 761 |
+
res_mask,
|
| 762 |
+
)
|
| 763 |
+
if res_mask.dim() == 1:
|
| 764 |
+
mask = res_mask.float()
|
| 765 |
+
else:
|
| 766 |
+
mask = res_mask[0].float()
|
| 767 |
+
valid = mask.bool()
|
| 768 |
+
disp_centered = disp - disp.mean(dim=0, keepdim=True)
|
| 769 |
+
denom = float(max(disp_centered.shape[0] - 1, 1))
|
| 770 |
+
local_cov = torch.einsum("tni,tnj->nij", disp_centered, disp_centered) / denom
|
| 771 |
+
cross_cov = torch.einsum("tnd,tmd->nm", disp_centered, disp_centered) / denom
|
| 772 |
+
rmsf = torch.sqrt(torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8))
|
| 773 |
+
local_var = torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)
|
| 774 |
+
dccm = cross_cov / torch.sqrt(local_var[:, None] * local_var[None, :]).clamp_min(1e-8)
|
| 775 |
+
local_cov = local_cov * mask[:, None, None]
|
| 776 |
+
cross_cov = cross_cov * mask[:, None] * mask[None, :]
|
| 777 |
+
dccm = dccm * mask[:, None] * mask[None, :]
|
| 778 |
+
rmsf = rmsf * mask
|
| 779 |
+
oracle_modes, oracle_energy = LatentEncoder.pca_modes_from_centered_displacement(
|
| 780 |
+
disp_centered,
|
| 781 |
+
mask,
|
| 782 |
+
num_modes=num_modes,
|
| 783 |
+
)
|
| 784 |
+
return {
|
| 785 |
+
"local_cov": local_cov.detach().cpu(),
|
| 786 |
+
"cross_cov": cross_cov.detach().cpu(),
|
| 787 |
+
"dccm": dccm.detach().cpu(),
|
| 788 |
+
"rmsf": rmsf.detach().cpu(),
|
| 789 |
+
"res_mask": mask.detach().cpu(),
|
| 790 |
+
"oracle_modes": oracle_modes.detach().cpu(),
|
| 791 |
+
"oracle_energy": oracle_energy.detach().cpu(),
|
| 792 |
+
"oracle_mean_disp": (disp.mean(dim=0) * mask[:, None]).detach().cpu(),
|
| 793 |
+
"num_res": torch.tensor(int(valid.sum().item()), dtype=torch.long),
|
| 794 |
+
}
|
| 795 |
+
|
| 796 |
+
@staticmethod
|
| 797 |
+
def pca_modes_from_centered_displacement(disp_centered, res_mask, num_modes=8):
|
| 798 |
+
mask = res_mask.float()
|
| 799 |
+
flat = (disp_centered.float() * mask[None, :, None]).reshape(disp_centered.shape[0], -1)
|
| 800 |
+
flat = flat - flat.mean(dim=0, keepdim=True)
|
| 801 |
+
if flat.shape[0] < 2 or flat.abs().sum() <= 0:
|
| 802 |
+
return (
|
| 803 |
+
disp_centered.new_zeros(disp_centered.shape[1], num_modes, 3),
|
| 804 |
+
disp_centered.new_zeros(num_modes),
|
| 805 |
+
)
|
| 806 |
+
_, singular_values, vh = torch.linalg.svd(flat, full_matrices=False)
|
| 807 |
+
take = min(num_modes, vh.shape[0])
|
| 808 |
+
modes = disp_centered.new_zeros(disp_centered.shape[1], num_modes, 3)
|
| 809 |
+
modes[:, :take, :] = vh[:take].reshape(take, disp_centered.shape[1], 3).permute(1, 0, 2)
|
| 810 |
+
energy = disp_centered.new_zeros(num_modes)
|
| 811 |
+
energy[:take] = singular_values[:take].square() / float(max(flat.shape[0] - 1, 1))
|
| 812 |
+
return modes * mask[:, None, None], energy
|
| 813 |
+
|
| 814 |
+
@staticmethod
|
| 815 |
+
def project_displacement_to_modes(centered_disp, modes, res_mask):
|
| 816 |
+
mask = res_mask.float()[:, :, None, None]
|
| 817 |
+
modes = modes.float() * mask
|
| 818 |
+
disp = centered_disp.float() * res_mask.float()[:, :, None]
|
| 819 |
+
numerator = torch.einsum("bnd,bnkd->bk", disp, modes)
|
| 820 |
+
denom = modes.square().sum(dim=(1, 3)).clamp_min(1e-8)
|
| 821 |
+
return numerator / denom
|
| 822 |
+
|
| 823 |
+
@staticmethod
|
| 824 |
+
def mode_orthogonality_loss(modes, res_mask):
|
| 825 |
+
"""Scale-invariant squared cosine penalty over distinct mode pairs."""
|
| 826 |
+
basis = modes.float() * res_mask.float()[:, :, None, None]
|
| 827 |
+
gram = torch.einsum("bnkd,bnld->bkl", basis, basis)
|
| 828 |
+
norms = torch.diagonal(gram, dim1=-2, dim2=-1).clamp_min(1e-8).sqrt()
|
| 829 |
+
# Detach the per-mode norm in the cosine denominator. Backprop through
|
| 830 |
+
# 1/norm carries a 1/norm^2 term (up to ~1e12 at the clamp floor) that
|
| 831 |
+
# explodes when a mode collapses, sending a runaway gradient into the
|
| 832 |
+
# shared encoder and NaN-ing mixture_logits on the next forward. Detaching
|
| 833 |
+
# keeps the forward cosine identical while removing the runaway gradient --
|
| 834 |
+
# the same fix already applied to the gauge norm in _condition_from_modes.
|
| 835 |
+
denom = (norms[:, :, None] * norms[:, None, :]).detach()
|
| 836 |
+
cosine = gram / denom
|
| 837 |
+
eye = torch.eye(gram.shape[-1], device=gram.device, dtype=gram.dtype)[None]
|
| 838 |
+
offdiag = 1.0 - eye
|
| 839 |
+
return (cosine.square() * offdiag).sum() / (
|
| 840 |
+
offdiag.sum() * gram.shape[0]
|
| 841 |
+
).clamp_min(1.0)
|
| 842 |
+
|
| 843 |
+
@staticmethod
|
| 844 |
+
def mode_gram_diagnostics(modes, res_mask):
|
| 845 |
+
"""Measure mode collinearity after masking, without changing the modes."""
|
| 846 |
+
basis = modes.detach().float() * res_mask.float()[:, :, None, None]
|
| 847 |
+
gram = torch.einsum("bnkd,bnld->bkl", basis, basis)
|
| 848 |
+
eigvals = torch.linalg.eigvalsh(gram)
|
| 849 |
+
min_eig = eigvals[:, 0].clamp_min(0.0)
|
| 850 |
+
max_eig = eigvals[:, -1].clamp_min(0.0)
|
| 851 |
+
condition = max_eig / min_eig.clamp_min(1e-12)
|
| 852 |
+
|
| 853 |
+
norms = torch.diagonal(gram, dim1=-2, dim2=-1).clamp_min(1e-12).sqrt()
|
| 854 |
+
cosine = gram / (norms[:, :, None] * norms[:, None, :])
|
| 855 |
+
eye = torch.eye(gram.shape[-1], device=gram.device, dtype=torch.bool)[None]
|
| 856 |
+
max_cosine = cosine.abs().masked_fill(eye, 0.0).amax(dim=(1, 2))
|
| 857 |
+
return {
|
| 858 |
+
"mode_gram_min_eig": min_eig,
|
| 859 |
+
"mode_gram_max_eig": max_eig,
|
| 860 |
+
"mode_gram_condition": condition,
|
| 861 |
+
"mode_max_cosine_abs": max_cosine,
|
| 862 |
+
}
|
| 863 |
+
|
| 864 |
+
@staticmethod
|
| 865 |
+
def project_displacement_lstsq(displacement, modes, res_mask, ridge=1e-4, detach_modes=True):
|
| 866 |
+
basis = modes.float()
|
| 867 |
+
if detach_modes:
|
| 868 |
+
basis = basis.detach()
|
| 869 |
+
mask = res_mask.float()
|
| 870 |
+
basis = basis * mask[:, :, None, None]
|
| 871 |
+
disp = displacement.float() * mask[:, :, None]
|
| 872 |
+
gram = torch.einsum("bnkd,bnld->bkl", basis, basis)
|
| 873 |
+
rhs = torch.einsum("bnd,bnkd->bk", disp, basis)
|
| 874 |
+
eye = torch.eye(modes.shape[2], device=modes.device, dtype=gram.dtype)[None]
|
| 875 |
+
# Relative (Levenberg-Marquardt) ridge: an absolute `ridge` (e.g. 1e-4) is
|
| 876 |
+
# numerically swallowed in float32 once the unnormalized modes make the gram
|
| 877 |
+
# scale large (mode-norm gauge -> gram entries up to ~1e13), leaving a
|
| 878 |
+
# near-collinear batch element singular and crashing torch.linalg.solve.
|
| 879 |
+
# Scaling the damping by the mean diagonal keeps it effective at every gauge.
|
| 880 |
+
scale = torch.diagonal(gram, dim1=-2, dim2=-1).mean(dim=-1).clamp_min(1e-8)
|
| 881 |
+
coeff = torch.linalg.solve(
|
| 882 |
+
gram + (float(ridge) * scale)[:, None, None] * eye, rhs[..., None]
|
| 883 |
+
).squeeze(-1)
|
| 884 |
+
return coeff
|
| 885 |
+
|
| 886 |
+
@staticmethod
|
| 887 |
+
def projection_reconstruction_objective(
|
| 888 |
+
displacement,
|
| 889 |
+
modes,
|
| 890 |
+
coefficients,
|
| 891 |
+
res_mask,
|
| 892 |
+
ridge=1e-4,
|
| 893 |
+
eps=1e-8,
|
| 894 |
+
):
|
| 895 |
+
"""Evaluate the ridge least-squares value with stop-gradient coefficients."""
|
| 896 |
+
mask = res_mask.float()[:, :, None]
|
| 897 |
+
disp = displacement.float() * mask
|
| 898 |
+
basis = modes.float() * mask[:, :, None]
|
| 899 |
+
coefficients_for_recon = coefficients.detach().float()
|
| 900 |
+
recon = torch.einsum(
|
| 901 |
+
"bk,bnkd->bnd", coefficients_for_recon, basis
|
| 902 |
+
)
|
| 903 |
+
residual_sq = ((disp - recon).square() * mask).sum(dim=(1, 2))
|
| 904 |
+
target_sq = (disp.square() * mask).sum(dim=(1, 2)).clamp_min(float(eps))
|
| 905 |
+
ridge_sq = float(ridge) * coefficients_for_recon.square().sum(dim=-1)
|
| 906 |
+
return {
|
| 907 |
+
"loss": (residual_sq + ridge_sq) / target_sq,
|
| 908 |
+
"rel_error": torch.sqrt(residual_sq / target_sq),
|
| 909 |
+
"recon": recon,
|
| 910 |
+
}
|
| 911 |
+
|
| 912 |
+
@staticmethod
|
| 913 |
+
def _masked_corr(pred, target, mask):
|
| 914 |
+
pred = pred.float()[mask.bool()]
|
| 915 |
+
target = target.float()[mask.bool()]
|
| 916 |
+
if pred.numel() < 2:
|
| 917 |
+
return pred.new_zeros(())
|
| 918 |
+
pred = pred - pred.mean()
|
| 919 |
+
target = target - target.mean()
|
| 920 |
+
denom = pred.norm() * target.norm()
|
| 921 |
+
if denom <= 1e-8:
|
| 922 |
+
return pred.new_zeros(())
|
| 923 |
+
return (pred * target).sum() / denom
|
| 924 |
+
|
| 925 |
+
@staticmethod
|
| 926 |
+
def _top_abs_sign_agree(pred, target, mask, fraction=0.1):
|
| 927 |
+
pred = pred.float()[mask.bool()]
|
| 928 |
+
target = target.float()[mask.bool()]
|
| 929 |
+
if pred.numel() == 0:
|
| 930 |
+
return pred.new_zeros(())
|
| 931 |
+
k = max(1, int(round(float(pred.numel()) * fraction)))
|
| 932 |
+
k = min(k, pred.numel())
|
| 933 |
+
idx = torch.topk(target.abs(), k=k, largest=True).indices
|
| 934 |
+
return (torch.sign(pred[idx]) == torch.sign(target[idx])).float().mean()
|
| 935 |
+
|
| 936 |
+
def motion_alignment_metrics(self, condition, targets, res_mask, spatial_dists):
|
| 937 |
+
with torch.no_grad():
|
| 938 |
+
mask = res_mask.float()
|
| 939 |
+
pair_mask = mask[:, :, None] * mask[:, None, :]
|
| 940 |
+
eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None]
|
| 941 |
+
offdiag_mask = pair_mask * (1.0 - eye)
|
| 942 |
+
spatial_dists = spatial_dists.to(device=mask.device, dtype=condition["cross_cov_pred"].dtype)
|
| 943 |
+
near_mask = offdiag_mask * (spatial_dists <= self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype)
|
| 944 |
+
far_mask = offdiag_mask * (spatial_dists > self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype)
|
| 945 |
+
pred = condition["cross_cov_pred"].detach().float()
|
| 946 |
+
target = targets["cross_cov"].to(device=pred.device, dtype=pred.dtype)
|
| 947 |
+
return {
|
| 948 |
+
"cross_cov_corr_all": self._masked_corr(pred, target, offdiag_mask),
|
| 949 |
+
"cross_cov_near_corr": self._masked_corr(pred, target, near_mask),
|
| 950 |
+
"cross_cov_far_corr": self._masked_corr(pred, target, far_mask),
|
| 951 |
+
"cross_cov_near_top10_sign_agree": self._top_abs_sign_agree(pred, target, near_mask),
|
| 952 |
+
"cross_cov_far_top10_sign_agree": self._top_abs_sign_agree(pred, target, far_mask),
|
| 953 |
+
"cross_cov_near_pred_abs_mean": (pred.abs() * near_mask).sum() / near_mask.sum().clamp_min(1.0),
|
| 954 |
+
"cross_cov_near_true_abs_mean": (target.abs() * near_mask).sum() / near_mask.sum().clamp_min(1.0),
|
| 955 |
+
"cross_cov_far_pred_abs_mean": (pred.abs() * far_mask).sum() / far_mask.sum().clamp_min(1.0),
|
| 956 |
+
"cross_cov_far_true_abs_mean": (target.abs() * far_mask).sum() / far_mask.sum().clamp_min(1.0),
|
| 957 |
+
}
|
| 958 |
+
|
| 959 |
+
def rigid_component_metrics(self, condition, trans_eq, res_mask):
|
| 960 |
+
with torch.no_grad():
|
| 961 |
+
center = self._masked_mean(trans_eq.float(), res_mask)
|
| 962 |
+
coords = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None]
|
| 963 |
+
translation, omega, _ = self._fit_rigid_motion(condition["u_global"], coords, res_mask)
|
| 964 |
+
translation = translation.float()
|
| 965 |
+
omega = omega.float()
|
| 966 |
+
return {
|
| 967 |
+
"rigid_translation_abs_mean": translation.abs().mean(),
|
| 968 |
+
"rigid_translation_abs_max": translation.abs().max(),
|
| 969 |
+
"rigid_rotation_omega_abs_mean": omega.abs().mean(),
|
| 970 |
+
"rigid_rotation_omega_abs_max": omega.abs().max(),
|
| 971 |
+
}
|
| 972 |
+
|
| 973 |
+
@staticmethod
|
| 974 |
+
def _mode_subspace_basis(u_global, res_mask):
|
| 975 |
+
mask = res_mask.float()[:, :, None, None]
|
| 976 |
+
u = (u_global.float() * mask).permute(0, 2, 1, 3).reshape(u_global.shape[0], u_global.shape[2], -1)
|
| 977 |
+
bases = []
|
| 978 |
+
for sample in u:
|
| 979 |
+
matrix = sample.transpose(0, 1)
|
| 980 |
+
q, _ = torch.linalg.qr(matrix, mode="reduced")
|
| 981 |
+
bases.append(q)
|
| 982 |
+
return torch.stack(bases, dim=0)
|
| 983 |
+
|
| 984 |
+
@staticmethod
|
| 985 |
+
def _mode_subspace_loss(pred_modes, target_modes, res_mask):
|
| 986 |
+
pred_basis = LatentEncoder._mode_subspace_basis(pred_modes, res_mask)
|
| 987 |
+
target_basis = LatentEncoder._mode_subspace_basis(target_modes, res_mask)
|
| 988 |
+
overlap = torch.matmul(pred_basis.transpose(-1, -2), target_basis).square().sum(dim=(-1, -2))
|
| 989 |
+
num_modes = pred_basis.shape[-1]
|
| 990 |
+
normalized_overlap = (overlap / float(max(num_modes, 1))).clamp(0.0, 1.0)
|
| 991 |
+
return 1.0 - normalized_overlap.mean(), normalized_overlap.mean().detach()
|
| 992 |
+
|
| 993 |
+
@staticmethod
|
| 994 |
+
def _masked_flat_modes(modes, res_mask):
|
| 995 |
+
mask = res_mask.float()[:, :, None, None]
|
| 996 |
+
modes = modes.float() * mask
|
| 997 |
+
return modes.permute(0, 2, 1, 3).reshape(modes.shape[0], modes.shape[2], -1)
|
| 998 |
+
|
| 999 |
+
def pca_alignment_loss(self, condition, targets, res_mask, top_m=2):
|
| 1000 |
+
"""Favor assigning high predicted energy to modes aligned with MD top PCs."""
|
| 1001 |
+
pred_modes = condition["u_global"].float()
|
| 1002 |
+
target_modes = targets["oracle_modes"].to(
|
| 1003 |
+
device=pred_modes.device,
|
| 1004 |
+
dtype=torch.float32,
|
| 1005 |
+
)
|
| 1006 |
+
top_m = int(max(1, min(top_m, pred_modes.shape[2], target_modes.shape[2])))
|
| 1007 |
+
target_modes = target_modes[:, :, :top_m, :]
|
| 1008 |
+
|
| 1009 |
+
pred_flat = F.normalize(self._masked_flat_modes(pred_modes, res_mask), dim=-1, eps=1e-8)
|
| 1010 |
+
target_basis = self._mode_subspace_basis(target_modes, res_mask)
|
| 1011 |
+
mode_overlap = torch.matmul(pred_flat, target_basis).square().sum(dim=-1).clamp(0.0, 1.0)
|
| 1012 |
+
|
| 1013 |
+
energy = condition["energy"].float().clamp_min(1e-8)
|
| 1014 |
+
weights = energy / energy.sum(dim=-1, keepdim=True).clamp_min(1e-8)
|
| 1015 |
+
weighted_overlap = (weights * mode_overlap).sum(dim=-1)
|
| 1016 |
+
pca_align_loss = 1.0 - weighted_overlap.mean()
|
| 1017 |
+
|
| 1018 |
+
with torch.no_grad():
|
| 1019 |
+
order = torch.argsort(energy, dim=-1, descending=True)
|
| 1020 |
+
top1_overlap = mode_overlap.gather(1, order[:, :1]).mean()
|
| 1021 |
+
best_overlap = mode_overlap.max(dim=-1).values.mean()
|
| 1022 |
+
top_idx = order[:, :top_m]
|
| 1023 |
+
gather_idx = top_idx[:, None, :, None].expand(-1, pred_modes.shape[1], -1, pred_modes.shape[-1])
|
| 1024 |
+
pred_top_modes = pred_modes.gather(2, gather_idx)
|
| 1025 |
+
_, top_subspace_overlap = self._mode_subspace_loss(pred_top_modes, target_modes, res_mask)
|
| 1026 |
+
|
| 1027 |
+
return {
|
| 1028 |
+
"pca_align_loss": pca_align_loss,
|
| 1029 |
+
"pca_align_weighted_overlap": weighted_overlap.detach().mean(),
|
| 1030 |
+
"pca_align_best_overlap": best_overlap,
|
| 1031 |
+
"pca_align_top_energy_overlap": top1_overlap,
|
| 1032 |
+
"pca_align_top_energy_subspace_overlap": top_subspace_overlap,
|
| 1033 |
+
}
|
| 1034 |
+
|
| 1035 |
+
def enm_initialization_loss(self, condition, trans_eq, res_mask):
|
| 1036 |
+
"""Warmup loss that aligns only the ENM direction subspace.
|
| 1037 |
+
|
| 1038 |
+
ENM is used only as an initialization target. It is not an input feature
|
| 1039 |
+
and does not appear in the mode forward formula. The projection loss is
|
| 1040 |
+
invariant to per-mode sign flips and rotations inside a near-degenerate
|
| 1041 |
+
ENM subspace, unlike ordered mode-by-mode cosine matching.
|
| 1042 |
+
"""
|
| 1043 |
+
targets = self._enm_motion_targets(trans_eq, res_mask)
|
| 1044 |
+
target_modes = targets["enm_modes"].to(device=condition["u_global"].device, dtype=torch.float32)
|
| 1045 |
+
center = self._masked_mean(trans_eq.float(), res_mask)
|
| 1046 |
+
centered = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None]
|
| 1047 |
+
if self.template_remove_rotation:
|
| 1048 |
+
target_modes = self._remove_rigid_component(target_modes, centered, res_mask)
|
| 1049 |
+
subspace_loss, subspace_overlap = self._mode_subspace_loss(
|
| 1050 |
+
condition["u_global"].float(),
|
| 1051 |
+
target_modes,
|
| 1052 |
+
res_mask,
|
| 1053 |
+
)
|
| 1054 |
+
with torch.autocast(device_type=trans_eq.device.type, enabled=False):
|
| 1055 |
+
spatial_dists = torch.cdist(trans_eq.float(), trans_eq.float())
|
| 1056 |
+
align = self.motion_alignment_metrics(condition, targets, res_mask, spatial_dists)
|
| 1057 |
+
metrics = {
|
| 1058 |
+
"enm_warmup_loss": subspace_loss,
|
| 1059 |
+
"enm_warmup_subspace_loss": subspace_loss.detach(),
|
| 1060 |
+
"enm_warmup_subspace_overlap": subspace_overlap,
|
| 1061 |
+
}
|
| 1062 |
+
metrics.update({f"enm_warmup_{key}": value for key, value in align.items()})
|
| 1063 |
+
|
| 1064 |
+
return metrics
|
| 1065 |
+
def motion_recon_loss(self, condition, targets, res_mask, spatial_dists=None):
|
| 1066 |
+
mask = res_mask.float()
|
| 1067 |
+
pair_mask = mask[:, :, None] * mask[:, None, :]
|
| 1068 |
+
eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None]
|
| 1069 |
+
offdiag_mask = pair_mask * (1.0 - eye)
|
| 1070 |
+
local_mask = mask[..., None, None]
|
| 1071 |
+
|
| 1072 |
+
local_target = targets["local_cov"].to(condition["local_cov_pred"].device, condition["local_cov_pred"].dtype)
|
| 1073 |
+
cross_target = targets["cross_cov"].to(condition["cross_cov_pred"].device, condition["cross_cov_pred"].dtype)
|
| 1074 |
+
rmsf_target = targets["rmsf"].to(condition["rmsf_pred"].device, condition["rmsf_pred"].dtype)
|
| 1075 |
+
|
| 1076 |
+
local_diff = (condition["local_cov_pred"] - local_target) * local_mask
|
| 1077 |
+
local_denom = ((local_target * local_mask).square().sum() / local_mask.sum().clamp_min(1.0)).clamp_min(1e-6)
|
| 1078 |
+
local_cov_loss = (local_diff.square().sum() / local_mask.sum().clamp_min(1.0)) / local_denom
|
| 1079 |
+
|
| 1080 |
+
if spatial_dists is None:
|
| 1081 |
+
raise ValueError("spatial_dists is required for near/far cross-cov diagnostics")
|
| 1082 |
+
spatial_dists = spatial_dists.to(device=mask.device, dtype=condition["cross_cov_pred"].dtype)
|
| 1083 |
+
near_mask = offdiag_mask * (spatial_dists <= self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype)
|
| 1084 |
+
far_mask = offdiag_mask * (spatial_dists > self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype)
|
| 1085 |
+
|
| 1086 |
+
cross_diff = (condition["cross_cov_pred"] - cross_target) * offdiag_mask
|
| 1087 |
+
cross_denom = ((cross_target * offdiag_mask).square().sum() / offdiag_mask.sum().clamp_min(1.0)).clamp_min(1e-6)
|
| 1088 |
+
cross_cov_loss = (cross_diff.square().sum() / offdiag_mask.sum().clamp_min(1.0)) / cross_denom
|
| 1089 |
+
|
| 1090 |
+
near_diff = (condition["cross_cov_pred"] - cross_target) * near_mask
|
| 1091 |
+
near_denom = ((cross_target * near_mask).square().sum() / near_mask.sum().clamp_min(1.0)).clamp_min(1e-6)
|
| 1092 |
+
cross_cov_near_loss = (near_diff.square().sum() / near_mask.sum().clamp_min(1.0)) / near_denom
|
| 1093 |
+
|
| 1094 |
+
far_diff = (condition["cross_cov_pred"] - cross_target) * far_mask
|
| 1095 |
+
far_denom = ((cross_target * far_mask).square().sum() / far_mask.sum().clamp_min(1.0)).clamp_min(1e-6)
|
| 1096 |
+
cross_cov_far_loss = (far_diff.square().sum() / far_mask.sum().clamp_min(1.0)) / far_denom
|
| 1097 |
+
|
| 1098 |
+
rmsf_diff = (condition["rmsf_pred"] - rmsf_target) * mask
|
| 1099 |
+
rmsf_denom = ((rmsf_target * mask).square().sum() / mask.sum().clamp_min(1.0)).clamp_min(1e-6)
|
| 1100 |
+
rmsf_loss = (rmsf_diff.square().sum() / mask.sum().clamp_min(1.0)) / rmsf_denom
|
| 1101 |
+
|
| 1102 |
+
losses = {
|
| 1103 |
+
"local_cov_loss": local_cov_loss,
|
| 1104 |
+
"cross_cov_loss": cross_cov_loss,
|
| 1105 |
+
"cross_cov_near_loss": cross_cov_near_loss,
|
| 1106 |
+
"cross_cov_far_loss": cross_cov_far_loss,
|
| 1107 |
+
"rmsf_loss": rmsf_loss,
|
| 1108 |
+
}
|
| 1109 |
+
if "oracle_modes" in targets:
|
| 1110 |
+
losses.update(self.pca_alignment_loss(
|
| 1111 |
+
condition,
|
| 1112 |
+
targets,
|
| 1113 |
+
res_mask,
|
| 1114 |
+
top_m=int(getattr(self, "pca_align_top_m", 2)),
|
| 1115 |
+
))
|
| 1116 |
+
return losses
|
| 1117 |
+
|
| 1118 |
+
def generator_response_cov_loss(
|
| 1119 |
+
self,
|
| 1120 |
+
response_deltas,
|
| 1121 |
+
res_mask,
|
| 1122 |
+
targets,
|
| 1123 |
+
use_cross=False,
|
| 1124 |
+
sample_weight=None,
|
| 1125 |
+
teacher_response_deltas=None,
|
| 1126 |
+
teacher_trace_anchor=None,
|
| 1127 |
+
teacher_trace_denominator="teacher",
|
| 1128 |
+
amplitude_anchor="teacher_trace",
|
| 1129 |
+
trace_target_scale=None,
|
| 1130 |
+
):
|
| 1131 |
+
"""Match generator response shape without rewarding global expansion.
|
| 1132 |
+
|
| 1133 |
+
``response_deltas`` has shape ``(S, B, N, 3)`` and contains antithetic
|
| 1134 |
+
central-difference responses for S independent coefficient perturbations.
|
| 1135 |
+
The loss first averages ``d d^T`` over S and then normalizes by total
|
| 1136 |
+
response trace before comparing to MD covariance. This avoids the v1
|
| 1137 |
+
shortcut where a single rank-1 sample, or a globally amplified response,
|
| 1138 |
+
can reduce the generator-response objective.
|
| 1139 |
+
|
| 1140 |
+
If ``teacher_response_deltas`` is provided, a weak trace anchor keeps the
|
| 1141 |
+
current response norm near the frozen initial/A30 response under the same
|
| 1142 |
+
``t`` and coefficient perturbations. This anchor does not assume that
|
| 1143 |
+
one-step trace equals the 20-step inference ensemble trace.
|
| 1144 |
+
"""
|
| 1145 |
+
with torch.autocast(device_type=res_mask.device.type, enabled=False):
|
| 1146 |
+
d = response_deltas.float()
|
| 1147 |
+
if d.dim() == 3:
|
| 1148 |
+
d = d[None]
|
| 1149 |
+
mask = res_mask.float()
|
| 1150 |
+
if sample_weight is not None:
|
| 1151 |
+
mask = mask * sample_weight.float().to(mask.device)[:, None]
|
| 1152 |
+
d = d * mask[None, :, :, None]
|
| 1153 |
+
|
| 1154 |
+
local_target = targets["local_cov"].to(device=d.device, dtype=d.dtype)
|
| 1155 |
+
target_mask = res_mask.float().to(device=d.device, dtype=d.dtype)
|
| 1156 |
+
local_mask = mask[:, :, None, None]
|
| 1157 |
+
target_local_mask = target_mask[:, :, None, None]
|
| 1158 |
+
|
| 1159 |
+
local_sample = torch.einsum("sbni,sbnj->bnij", d, d) / float(d.shape[0])
|
| 1160 |
+
trace_sample = (
|
| 1161 |
+
torch.diagonal(local_sample, dim1=-2, dim2=-1).sum(dim=-1) * mask
|
| 1162 |
+
).sum(dim=-1).clamp_min(1e-8)
|
| 1163 |
+
trace_target = (
|
| 1164 |
+
torch.diagonal(local_target, dim1=-2, dim2=-1).sum(dim=-1) * target_mask
|
| 1165 |
+
).sum(dim=-1).clamp_min(1e-8)
|
| 1166 |
+
local_sample_norm = local_sample / trace_sample[:, None, None, None]
|
| 1167 |
+
local_target_norm = local_target / trace_target[:, None, None, None]
|
| 1168 |
+
local_diff = (local_sample_norm - local_target_norm) * local_mask
|
| 1169 |
+
local_denom = (
|
| 1170 |
+
(local_target_norm * target_local_mask).square().sum()
|
| 1171 |
+
/ target_local_mask.sum().clamp_min(1.0)
|
| 1172 |
+
).clamp_min(1e-8)
|
| 1173 |
+
local_shape_loss = (
|
| 1174 |
+
local_diff.square().sum() / local_mask.sum().clamp_min(1.0)
|
| 1175 |
+
) / local_denom
|
| 1176 |
+
|
| 1177 |
+
losses = {
|
| 1178 |
+
"gen_local_shape_loss": local_shape_loss,
|
| 1179 |
+
}
|
| 1180 |
+
metrics = {
|
| 1181 |
+
"gen_response_abs_mean": d.detach().abs().mean(),
|
| 1182 |
+
"gen_response_trace_mean": trace_sample.detach().mean(),
|
| 1183 |
+
"gen_response_active_frac": (
|
| 1184 |
+
mask.sum() / res_mask.float().sum().clamp_min(1.0)
|
| 1185 |
+
).detach(),
|
| 1186 |
+
}
|
| 1187 |
+
|
| 1188 |
+
anchor_trace = None
|
| 1189 |
+
if amplitude_anchor in ("md_trace", "rollout_trace"):
|
| 1190 |
+
# Anchor the response magnitude to the MD ensemble's own trace.
|
| 1191 |
+
# trace_target is already computed above for the shape normalization,
|
| 1192 |
+
# so this needs no teacher and no extra forwards.
|
| 1193 |
+
# "rollout_trace" divides the MD trace by a detached no-grad
|
| 1194 |
+
# rollout-measured trace amplification factor before anchoring.
|
| 1195 |
+
#
|
| 1196 |
+
# The "teacher_trace" anchor below is unusable in this codebase: the frozen
|
| 1197 |
+
# teacher is deep-copied from the model at step 0, where every condition
|
| 1198 |
+
# adapter (embedder z_*/disp_* adapters and bbflow_model film_mlp) is
|
| 1199 |
+
# zero-initialized so that a warm-started model reproduces vanilla BBFlow.
|
| 1200 |
+
# The teacher's response to c is therefore identically zero forever, so
|
| 1201 |
+
# teacher_trace pins to the 1e-8 clamp floor and log(trace_sample/1e-8)^2
|
| 1202 |
+
# drives the student's response to zero -- the opposite of the anchor's
|
| 1203 |
+
# purpose. A model that ignores c cannot calibrate a response to c.
|
| 1204 |
+
anchor_trace = trace_target
|
| 1205 |
+
if trace_target_scale is not None:
|
| 1206 |
+
scale = trace_target_scale.to(device=d.device, dtype=d.dtype)
|
| 1207 |
+
anchor_trace = anchor_trace * scale.reshape(-1)[0].clamp_min(1e-8)
|
| 1208 |
+
elif amplitude_anchor != "none" and (
|
| 1209 |
+
teacher_response_deltas is not None or teacher_trace_anchor is not None
|
| 1210 |
+
):
|
| 1211 |
+
if teacher_trace_anchor is not None:
|
| 1212 |
+
teacher_trace = teacher_trace_anchor.to(device=d.device, dtype=d.dtype)
|
| 1213 |
+
if teacher_trace.dim() > 1:
|
| 1214 |
+
teacher_trace = teacher_trace.reshape(teacher_trace.shape[0], -1).mean(dim=-1)
|
| 1215 |
+
teacher_trace = teacher_trace.reshape(-1).clamp_min(1e-8)
|
| 1216 |
+
else:
|
| 1217 |
+
teacher_d = teacher_response_deltas.float()
|
| 1218 |
+
if teacher_d.dim() == 3:
|
| 1219 |
+
teacher_d = teacher_d[None]
|
| 1220 |
+
teacher_d = teacher_d.to(device=d.device, dtype=d.dtype) * mask[None, :, :, None]
|
| 1221 |
+
if teacher_trace_denominator == "teacher":
|
| 1222 |
+
teacher_denom = float(teacher_d.shape[0])
|
| 1223 |
+
elif teacher_trace_denominator == "student":
|
| 1224 |
+
teacher_denom = float(d.shape[0])
|
| 1225 |
+
elif teacher_trace_denominator == "none":
|
| 1226 |
+
teacher_denom = 1.0
|
| 1227 |
+
else:
|
| 1228 |
+
raise ValueError(
|
| 1229 |
+
"teacher_trace_denominator must be one of "
|
| 1230 |
+
f"'teacher', 'student', or 'none'; got {teacher_trace_denominator!r}"
|
| 1231 |
+
)
|
| 1232 |
+
teacher_local = (
|
| 1233 |
+
torch.einsum("sbni,sbnj->bnij", teacher_d, teacher_d)
|
| 1234 |
+
/ teacher_denom
|
| 1235 |
+
)
|
| 1236 |
+
teacher_trace = (
|
| 1237 |
+
torch.diagonal(teacher_local, dim1=-2, dim2=-1).sum(dim=-1) * mask
|
| 1238 |
+
).sum(dim=-1).clamp_min(1e-8)
|
| 1239 |
+
anchor_trace = teacher_trace
|
| 1240 |
+
|
| 1241 |
+
if anchor_trace is not None:
|
| 1242 |
+
valid = (mask.sum(dim=-1) > 0).to(dtype=d.dtype)
|
| 1243 |
+
trace_ratio = (trace_sample / anchor_trace).clamp_min(1e-8)
|
| 1244 |
+
trace_loss = (trace_ratio.log().square() * valid).sum() / valid.sum().clamp_min(1.0)
|
| 1245 |
+
losses["gen_trace_anchor_loss"] = trace_loss
|
| 1246 |
+
# Ratio to whichever amplitude anchor is active (MD trace or teacher trace).
|
| 1247 |
+
# Healthy value is ~1; orders of magnitude away means the anchor is broken.
|
| 1248 |
+
metrics["gen_trace_ratio_to_teacher"] = (
|
| 1249 |
+
(trace_sample.detach() / anchor_trace.detach()).clamp_min(1e-8)
|
| 1250 |
+
* valid
|
| 1251 |
+
).sum() / valid.sum().clamp_min(1.0)
|
| 1252 |
+
metrics["gen_trace_ratio_to_anchor"] = metrics["gen_trace_ratio_to_teacher"]
|
| 1253 |
+
metrics["gen_trace_anchor_mean"] = anchor_trace.detach().mean()
|
| 1254 |
+
|
| 1255 |
+
if use_cross:
|
| 1256 |
+
pair_mask = mask[:, :, None] * mask[:, None, :]
|
| 1257 |
+
target_pair_mask = target_mask[:, :, None] * target_mask[:, None, :]
|
| 1258 |
+
eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None]
|
| 1259 |
+
offdiag_mask = pair_mask * (1.0 - eye)
|
| 1260 |
+
target_offdiag_mask = target_pair_mask * (1.0 - eye)
|
| 1261 |
+
cross_target = targets["cross_cov"].to(device=d.device, dtype=d.dtype)
|
| 1262 |
+
cross_sample = torch.einsum("sbnd,sbmd->bnm", d, d) / float(d.shape[0])
|
| 1263 |
+
cross_sample_norm = cross_sample / trace_sample[:, None, None]
|
| 1264 |
+
cross_target_norm = cross_target / trace_target[:, None, None]
|
| 1265 |
+
cross_diff = (cross_sample_norm - cross_target_norm) * offdiag_mask
|
| 1266 |
+
cross_denom = (
|
| 1267 |
+
(cross_target_norm * target_offdiag_mask).square().sum()
|
| 1268 |
+
/ target_offdiag_mask.sum().clamp_min(1.0)
|
| 1269 |
+
).clamp_min(1e-8)
|
| 1270 |
+
cross_shape_loss = (
|
| 1271 |
+
cross_diff.square().sum() / offdiag_mask.sum().clamp_min(1.0)
|
| 1272 |
+
) / cross_denom
|
| 1273 |
+
losses["gen_cross_shape_loss"] = cross_shape_loss
|
| 1274 |
+
return losses, metrics
|
| 1275 |
+
|
| 1276 |
+
def motion_metrics(self, condition, res_mask):
|
| 1277 |
+
with torch.no_grad():
|
| 1278 |
+
mask = res_mask.float()
|
| 1279 |
+
energy = condition["energy"].float()
|
| 1280 |
+
energy_sum = energy.sum(dim=-1).clamp_min(1e-8)
|
| 1281 |
+
prob = energy / energy_sum[:, None]
|
| 1282 |
+
entropy = -(prob * prob.clamp_min(1e-8).log()).sum(dim=-1)
|
| 1283 |
+
effective_modes = torch.exp(entropy)
|
| 1284 |
+
u_flat = condition["u_global"].float().permute(0, 2, 1, 3).reshape(condition["u_global"].shape[0], condition["u_global"].shape[2], -1)
|
| 1285 |
+
u_flat = F.normalize(u_flat, dim=-1)
|
| 1286 |
+
if self.num_modes > 1:
|
| 1287 |
+
cos = torch.matmul(u_flat, u_flat.transpose(-1, -2))
|
| 1288 |
+
eye = torch.eye(self.num_modes, device=cos.device, dtype=torch.bool)[None].expand_as(cos)
|
| 1289 |
+
mode_cosine_abs = cos.masked_select(~eye).abs().mean()
|
| 1290 |
+
else:
|
| 1291 |
+
mode_cosine_abs = energy.new_zeros(())
|
| 1292 |
+
metrics = {
|
| 1293 |
+
"latent_energy_mean": energy.mean(),
|
| 1294 |
+
"latent_energy_std": energy.std(),
|
| 1295 |
+
"latent_effective_modes": effective_modes.mean(),
|
| 1296 |
+
"latent_mode_cosine_abs": mode_cosine_abs,
|
| 1297 |
+
"latent_node_cond_abs": condition["node_cond"].detach().abs().mean(),
|
| 1298 |
+
"latent_edge_cond_abs": condition["edge_cond"].detach().abs().mean(),
|
| 1299 |
+
"latent_u_global_abs": condition["u_global"].detach().abs().mean(),
|
| 1300 |
+
"latent_u_position_std": (condition["u_global"].detach().float() * mask[:, :, None, None]).std(),
|
| 1301 |
+
}
|
| 1302 |
+
if "template_participation" in condition:
|
| 1303 |
+
metrics.update({
|
| 1304 |
+
"latent_template_participation_abs": condition["template_participation"].detach().float().abs().mean(),
|
| 1305 |
+
"latent_template_omega_abs": condition["template_omega"].detach().float().abs().mean(),
|
| 1306 |
+
"latent_template_velocity_abs": condition["template_velocity"].detach().float().abs().mean(),
|
| 1307 |
+
"latent_template_residual_abs": condition["template_residual_global"].detach().float().abs().mean(),
|
| 1308 |
+
})
|
| 1309 |
+
if "mixture_logits" in condition:
|
| 1310 |
+
diag = torch.diagonal(condition["mixture_scale_tril"].detach().float(), dim1=-2, dim2=-1)
|
| 1311 |
+
metrics.update({
|
| 1312 |
+
"q_mixture_entropy": self._mixture_entropy(condition["mixture_logits"].detach()).mean(),
|
| 1313 |
+
"q_mu_abs": condition["mixture_mu"].detach().float().abs().mean(),
|
| 1314 |
+
"q_scale_diag_mean": diag.mean(),
|
| 1315 |
+
"q_scale_diag_std": diag.std(),
|
| 1316 |
+
})
|
| 1317 |
+
return metrics
|
bbflow_base/code_exports/a30_redesign_source_20260719/configs/experiment/default.yaml
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
debug: False
|
| 2 |
+
use_wandb: True
|
| 3 |
+
use_tqdm: True
|
| 4 |
+
|
| 5 |
+
seed: 123
|
| 6 |
+
num_devices: 1
|
| 7 |
+
warm_start: null
|
| 8 |
+
warm_start_cfg_override: True
|
| 9 |
+
use_swa: False
|
| 10 |
+
first_val_epoch: 0
|
| 11 |
+
reset_epoch: False
|
| 12 |
+
|
| 13 |
+
batch_ot:
|
| 14 |
+
enabled: True
|
| 15 |
+
cost: kabsch
|
| 16 |
+
noise_per_sample: 1
|
| 17 |
+
# permute: False
|
| 18 |
+
training:
|
| 19 |
+
min_plddt_mask: null
|
| 20 |
+
loss: se3_vf_loss
|
| 21 |
+
bb_atom_scale: 0.1
|
| 22 |
+
trans_scale: 0.1
|
| 23 |
+
translation_loss_weight: 2.0
|
| 24 |
+
t_normalize_clip: 0.9
|
| 25 |
+
rotation_loss_weights: 1.0
|
| 26 |
+
aux_loss_weight: 1.0
|
| 27 |
+
aux_loss_t_pass: 0.75
|
| 28 |
+
t_bins: 4
|
| 29 |
+
ca_distmat_loss_weight: 0.0
|
| 30 |
+
ensemble_group_size: 0
|
| 31 |
+
force_grouped_batch: false
|
| 32 |
+
lambda_shape: 1.0
|
| 33 |
+
lambda_local_cov: 1.0
|
| 34 |
+
lambda_cross_cov: 1.0
|
| 35 |
+
lambda_rmsf: 0.25
|
| 36 |
+
lambda_mode_recon: 0.0
|
| 37 |
+
enm_warmup_epochs: 0
|
| 38 |
+
lambda_enm_warmup: 1.0
|
| 39 |
+
log_latent_batch_debug: false
|
| 40 |
+
epoch_condition_probe: true
|
| 41 |
+
condition_probe_scale: 2.0
|
| 42 |
+
diagnostic_interval_steps: 50
|
| 43 |
+
lambda_generator_cov: 0.0
|
| 44 |
+
generator_cov_use_cross: false
|
| 45 |
+
generator_cov_t_min: 0.1
|
| 46 |
+
generator_cov_t_max: 0.6
|
| 47 |
+
generator_cov_delta_scale: 1.0
|
| 48 |
+
generator_cov_num_deltas: 2
|
| 49 |
+
generator_cov_student_chunk_deltas: 1
|
| 50 |
+
generator_cov_teacher_num_deltas: 1
|
| 51 |
+
generator_cov_teacher_reuse_student_delta: true
|
| 52 |
+
generator_cov_teacher_trace_denominator: teacher
|
| 53 |
+
generator_cov_checkpoint: false
|
| 54 |
+
generator_cov_initial_trace_anchor: true
|
| 55 |
+
generator_cov_amplitude_anchor: md_trace
|
| 56 |
+
generator_cov_rollout_calibration: false
|
| 57 |
+
generator_cov_rollout_steps: 2
|
| 58 |
+
generator_cov_rollout_num_deltas: 1
|
| 59 |
+
generator_cov_rollout_max_examples: 4
|
| 60 |
+
generator_cov_rollout_interval_steps: 200
|
| 61 |
+
generator_cov_rollout_ema_decay: 0.9
|
| 62 |
+
lambda_gen_local_shape: 1.0
|
| 63 |
+
lambda_gen_cross_shape: 1.0
|
| 64 |
+
lambda_gen_trace_anchor: 0.05
|
| 65 |
+
wandb:
|
| 66 |
+
name: baseline
|
| 67 |
+
project: bbflow
|
| 68 |
+
save_dir: outputs/
|
| 69 |
+
# save_code: True
|
| 70 |
+
tags: []
|
| 71 |
+
optimizer:
|
| 72 |
+
lr: 0.0001
|
| 73 |
+
reset_optimizer_on_load: False
|
| 74 |
+
warmup_lr: False
|
| 75 |
+
warmup_lr_factor: 0.01
|
| 76 |
+
trainer:
|
| 77 |
+
overfit_batches: 0
|
| 78 |
+
min_epochs: 1 # prevents early stopping
|
| 79 |
+
max_epochs: 250
|
| 80 |
+
accelerator: gpu
|
| 81 |
+
precision: bf16-mixed
|
| 82 |
+
log_every_n_steps: 1
|
| 83 |
+
deterministic: False
|
| 84 |
+
strategy: ddp
|
| 85 |
+
check_val_every_n_epoch: 1
|
| 86 |
+
default_root_dir: outputs/
|
| 87 |
+
accumulate_grad_batches: 1
|
| 88 |
+
checkpointer:
|
| 89 |
+
dirpath: outputs/ckpt/${experiment.wandb.project}/${experiment.wandb.name}/${now:%Y-%m-%d}_${now:%H-%M-%S}
|
| 90 |
+
save_last: True
|
| 91 |
+
save_on_train_epoch_end: True
|
| 92 |
+
filename: "epoch:{epoch:03d}"
|
| 93 |
+
every_n_epochs: 1
|
| 94 |
+
save_top_k: -1
|
| 95 |
+
auto_insert_metric_name: False
|
| 96 |
+
checkpointer2: null # TODO: maybe remove/change
|
| 97 |
+
# dirpath: outputs/ckpt/${experiment.wandb.project}/${experiment.wandb.name}/${now:%Y-%m-%d}_${now:%H-%M-%S}
|
| 98 |
+
# save_last: False
|
| 99 |
+
# filename: "sec_dev:{sec_deviation:.2f}-epoch:{epoch:03d}"
|
| 100 |
+
# save_top_k: 10
|
| 101 |
+
# monitor: valid/sec_deviation
|
| 102 |
+
# mode: min
|
| 103 |
+
# every_n_epochs: 1
|
| 104 |
+
# first_epoch: ${experiment.first_val_epoch}
|
| 105 |
+
# auto_insert_metric_name: False
|
| 106 |
+
profiler:
|
| 107 |
+
enabled: False
|
| 108 |
+
modules: null # Optional list of modules which should be profiled
|
| 109 |
+
profile:
|
| 110 |
+
use_cuda: True
|
| 111 |
+
with_stack: False
|
| 112 |
+
stats:
|
| 113 |
+
group_by_stack_n: 0
|
| 114 |
+
group_by_input_shapes: False
|
| 115 |
+
prefixes: ['layer_0::', 'layer_1::']
|
| 116 |
+
sort_by: 'cpu_time_total'
|
bbflow_base/code_exports/a30_redesign_source_20260719/configs/inference.yaml
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
defaults:
|
| 2 |
+
- data: default
|
| 3 |
+
- experiment: default
|
| 4 |
+
- interpolant: default
|
| 5 |
+
- model: default
|
| 6 |
+
- _self_
|
| 7 |
+
|
| 8 |
+
hydra:
|
| 9 |
+
run:
|
| 10 |
+
dir: outputs/hydra/
|
| 11 |
+
|
| 12 |
+
latent:
|
| 13 |
+
enable: true
|
| 14 |
+
dim: 16
|
| 15 |
+
num_modes: 8
|
| 16 |
+
motion_message_passing_layers: 4
|
| 17 |
+
cross_cov_near_distance: 12.0
|
| 18 |
+
template_residual_scale: 0.1
|
| 19 |
+
template_remove_rotation: true
|
| 20 |
+
use_enm_features: false
|
| 21 |
+
enm_num_modes: 8
|
| 22 |
+
enm_cutoff: 12.0
|
| 23 |
+
enm_eps: 1e-6
|
| 24 |
+
node_cond_dim: 8
|
| 25 |
+
edge_cond_dim: 8
|
| 26 |
+
freeze_foundation: true
|
| 27 |
+
inject_embedder: true
|
| 28 |
+
inject_film: true
|
| 29 |
+
activation_checkpoint: true
|
| 30 |
+
shape_fingerprint_k: 5
|
| 31 |
+
shape_fingerprint_cache_path: null
|
| 32 |
+
motion_target_cache_path: null
|
| 33 |
+
z_stochastic: false
|
| 34 |
+
|
| 35 |
+
inference:
|
| 36 |
+
# Use this to write with date-time stamp.
|
| 37 |
+
name: run_${now:%Y-%m-%d}_${now:%H-%M}
|
| 38 |
+
seed: 123
|
| 39 |
+
ckpt_path: models/bbflow-mini-0.1/bbflow-mini-0.1.ckpt
|
| 40 |
+
output_dir: outputs/inference/
|
| 41 |
+
use_ckpt_name_in_outpath: True
|
| 42 |
+
|
| 43 |
+
use_gpu: True
|
| 44 |
+
num_gpus: 1
|
| 45 |
+
precision: 32-true
|
| 46 |
+
|
| 47 |
+
use_tqdm: True
|
| 48 |
+
log_times: False
|
| 49 |
+
z_per_sample: False
|
| 50 |
+
condition_mode: real # real, zero, shuffled
|
| 51 |
+
condition_scale: 1.0
|
| 52 |
+
postprocess_bfactors: True
|
| 53 |
+
|
| 54 |
+
csv_path: ./dataset_csv/test/ATLAS_test.csv
|
| 55 |
+
sort: False
|
| 56 |
+
num_proteins: null # null = all proteins
|
| 57 |
+
num_workers: 2
|
| 58 |
+
|
| 59 |
+
min_length: null # null = no lower limit
|
| 60 |
+
max_length: null # null = no upper limit
|
| 61 |
+
|
| 62 |
+
save_traj: False
|
| 63 |
+
final_only: True
|
| 64 |
+
cache_static_features: True
|
| 65 |
+
single_file: True
|
| 66 |
+
|
| 67 |
+
interpolant:
|
| 68 |
+
use_tqdm: ${inference.use_tqdm}
|
| 69 |
+
min_t: 0.00
|
| 70 |
+
max_t: 0.99
|
| 71 |
+
rots:
|
| 72 |
+
distribution: uniform # uniform, igso3
|
| 73 |
+
sample_schedule: exp
|
| 74 |
+
exp_rate: 10
|
| 75 |
+
trans:
|
| 76 |
+
sample_schedule: linear
|
| 77 |
+
sampling:
|
| 78 |
+
num_timesteps: 20
|
| 79 |
+
self_condition: True
|
| 80 |
+
|
| 81 |
+
prior: "conditional" # "conditional", "pure_noise"
|
| 82 |
+
prior_conditional:
|
| 83 |
+
gamma_trans: 0.2
|
| 84 |
+
gamma_rots: 0.2
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
samples:
|
| 88 |
+
|
| 89 |
+
samples_per_protein: 25
|
| 90 |
+
|
| 91 |
+
batch_size: 10
|
| 92 |
+
|
| 93 |
+
num_res_squared: 2_900_000
|
bbflow_base/code_exports/a30_redesign_source_20260719/configs/train.yaml
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
defaults:
|
| 2 |
+
- data: default
|
| 3 |
+
- experiment: default
|
| 4 |
+
- interpolant: default
|
| 5 |
+
- model: default
|
| 6 |
+
- _self_
|
| 7 |
+
|
| 8 |
+
hydra:
|
| 9 |
+
run:
|
| 10 |
+
dir: outputs/hydra/
|
| 11 |
+
|
| 12 |
+
latent:
|
| 13 |
+
enable: true
|
| 14 |
+
dim: 16
|
| 15 |
+
num_modes: 8
|
| 16 |
+
motion_message_passing_layers: 4
|
| 17 |
+
cross_cov_near_distance: 12.0
|
| 18 |
+
template_residual_scale: 0.1
|
| 19 |
+
template_remove_rotation: true
|
| 20 |
+
use_enm_features: false
|
| 21 |
+
enm_num_modes: 8
|
| 22 |
+
enm_cutoff: 12.0
|
| 23 |
+
enm_eps: 1e-6
|
| 24 |
+
node_cond_dim: 8
|
| 25 |
+
edge_cond_dim: 8
|
| 26 |
+
freeze_foundation: false
|
| 27 |
+
inject_embedder: true
|
| 28 |
+
inject_film: true
|
| 29 |
+
activation_checkpoint: true
|
| 30 |
+
track_condition_debug: false
|
| 31 |
+
shape_fingerprint_k: 5
|
| 32 |
+
shape_fingerprint_cache_path: null
|
| 33 |
+
motion_target_cache_path: null
|
| 34 |
+
z_stochastic: false
|
bbflow_base/code_exports/a30_redesign_source_20260719/docs/HANDOFF_2026-07-17.txt
ADDED
|
@@ -0,0 +1,924 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
HANDOFF DOCUMENT - BBFlow generator-response covariance line
|
| 3 |
+
Date: 2026-07-17
|
| 4 |
+
Audience: the next Claude / engineer picking this up cold
|
| 5 |
+
================================================================================
|
| 6 |
+
|
| 7 |
+
HOW TO USE THIS DOC
|
| 8 |
+
-------------------
|
| 9 |
+
Read sections 1-4 first (goal, scoreboard, the core diagnosis). Then section 6
|
| 10 |
+
(current mechanism) and section 8 (THE TEACHER BUG - do not repeat it).
|
| 11 |
+
Section 14 lists process rules that were learned the expensive way.
|
| 12 |
+
|
| 13 |
+
This doc supplements docs/experiment_trace_2026-07-05.md, which holds the older
|
| 14 |
+
experiment log. Where they disagree, this doc is newer.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
================================================================================
|
| 18 |
+
1. PROJECT GOAL AND HARD CONSTRAINTS
|
| 19 |
+
================================================================================
|
| 20 |
+
|
| 21 |
+
GOAL
|
| 22 |
+
Beat BBFlow (Wolf et al., NeurIPS 2025) on the ATLAS test set (82 proteins,
|
| 23 |
+
250 conformations each) on its own official metrics:
|
| 24 |
+
- RMSF correlation (r) and RMSF MAE
|
| 25 |
+
- Pairwise RMSD MAE
|
| 26 |
+
- PCA W2
|
| 27 |
+
|
| 28 |
+
USER'S HARD CONSTRAINT (stated repeatedly, non-negotiable)
|
| 29 |
+
"We must be better than BBFlow." Tying is not accepted as a result. Do not
|
| 30 |
+
propose a paper narrative that relies only on cross-covariance / auxiliary
|
| 31 |
+
metrics while conceding the official table.
|
| 32 |
+
|
| 33 |
+
STANDING PROHIBITIONS (user has explicitly rejected these; do not re-propose)
|
| 34 |
+
- ENM (elastic network model) as a basis or forward feature. Absolutely refused.
|
| 35 |
+
- Oracle information in any deployable component. See section 12.
|
| 36 |
+
- Expensive full ensemble-rollout training losses (20-step sampling per step).
|
| 37 |
+
- Multi-seed re-runs purely to measure noise floor ("100% against 多跑").
|
| 38 |
+
|
| 39 |
+
CONTEXT ON WHY THE USER IS FRUSTRATED
|
| 40 |
+
This line has burned weeks. Multiple runs were wasted on OOM crashes and on a
|
| 41 |
+
silent bug (section 8). Be precise, verify before proposing commands, and do
|
| 42 |
+
not over-promise speedups or "free" fixes. Two things this session were
|
| 43 |
+
over-claimed and had to be retracted: (a) "1 delta is unbiased and free" -
|
| 44 |
+
false for the normalized-shape objective, see section 6; (b) "removing the
|
| 45 |
+
teacher restores v1 speed" - it was only ~15%.
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
================================================================================
|
| 49 |
+
2. ENVIRONMENT AND PATHS
|
| 50 |
+
================================================================================
|
| 51 |
+
|
| 52 |
+
MACHINES
|
| 53 |
+
Local (Windows): D:\pycharm\pythonProject\protein\bbflow_base
|
| 54 |
+
- This is a CODE MIRROR ONLY. There is NO python and NO torch installed.
|
| 55 |
+
You can read and edit code here. You CANNOT run, test, or syntax-check
|
| 56 |
+
by execution. Only careful reading.
|
| 57 |
+
- The user copies files to the server MANUALLY.
|
| 58 |
+
Server: gn11 / gn14, 3x NVIDIA H100 PCIe 80GB
|
| 59 |
+
Repo: /home/wangyusong/LD-FPG-main/bbflow_base
|
| 60 |
+
Conda: `protein` env (also seen: /data/shared/conda_envs/ldfpg)
|
| 61 |
+
|
| 62 |
+
KEY PATHS
|
| 63 |
+
Official BBFlow checkpoint (warm-start source for everything):
|
| 64 |
+
/home/wangyusong/LD-FPG-main/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt
|
| 65 |
+
NOTE the path is under .../LD-FPG-main/bbflow/ (NOT bbflow_base/).
|
| 66 |
+
|
| 67 |
+
Repro root:
|
| 68 |
+
/data/shared/wangyusong/atals/bbflow_official_reproduction
|
| 69 |
+
|
| 70 |
+
"Version A" reference run (the protected baseline to beat/compare against):
|
| 71 |
+
${REPRO}/outputs/checkpoints/
|
| 72 |
+
bbflow_base_energy_from_q_diag_orth1_recon0_30ep_3gpu_20260707_165355
|
| 73 |
+
|
| 74 |
+
Motion target cache (used by the current runs):
|
| 75 |
+
/home/wangyusong/LD-FPG-main/bbflow_official_reproduction/shape_fingerprints/
|
| 76 |
+
atlas_full_md_motion_targets_k8_kabsch_v1.pt
|
| 77 |
+
WARNING: docs/experiment_trace_2026-07-05.md lists caches under
|
| 78 |
+
${REPRO}/shape_fingerprints/. The running command uses the /home/... path.
|
| 79 |
+
These may be different copies. VERIFY before trusting a comparison to A.
|
| 80 |
+
Required cache fields: local_cov, cross_cov, rmsf, oracle_mean_disp.
|
| 81 |
+
Optional: gen_response_trace_anchor, oracle_modes, oracle_energy.
|
| 82 |
+
|
| 83 |
+
LAUNCHER / SCRIPT INTERFACES (never write commands from memory - read them)
|
| 84 |
+
Training: base_stages/00_train_final_mog_ddp.sh
|
| 85 |
+
env-var interface + EXTRA_HYDRA_ARGS passthrough.
|
| 86 |
+
`+experiment.training.X=Y` adds NEW hydra keys; existing keys
|
| 87 |
+
take no `+`.
|
| 88 |
+
Sampling: reproduction/02_sample_test.sh
|
| 89 |
+
Uses REPRO_ROOT, METADATA_ROOT, CKPT_PATH, GPU_ID,
|
| 90 |
+
SAMPLES_PER_PROTEIN, SAMPLE_BATCH_SIZE, MAX_NUM_RES_SQUARED,
|
| 91 |
+
INFERENCE_NAME, CONDITION_MODE, CONDITION_SCALE, ...
|
| 92 |
+
It IGNORES OUTPUT_DIR and writes to ${REPRO_ROOT}/inference
|
| 93 |
+
Evaluation: reproduction/03_evaluate.sh
|
| 94 |
+
Uses ENSEMBLE_DIR, ATLAS_VIEW_ROOT, METRICS_DIR, TEST_CSV,
|
| 95 |
+
METHOD_NAME, METHOD_TIME_SECONDS, NUM_WORKERS
|
| 96 |
+
ATLAS_VIEW_ROOT must point at the REAL trajectories:
|
| 97 |
+
${REPRO}/datasets/ATLAS
|
| 98 |
+
If you see "No reference trajectory found ... reproduction/
|
| 99 |
+
outputs/data/ATLAS", STOP - the metrics are invalid.
|
| 100 |
+
|
| 101 |
+
OUTPUTS PER RUN
|
| 102 |
+
${RUN_DIR}/config.yaml <- the ONLY source of truth for
|
| 103 |
+
what actually ran
|
| 104 |
+
${RUN_DIR}/latent_train_epoch_metrics.csv <- one row per epoch, ALL metrics
|
| 105 |
+
(rank 0 only). This is the file
|
| 106 |
+
to read/paste for diagnosis.
|
| 107 |
+
${RUN_DIR}/epoch:0NN.ckpt, last.ckpt
|
| 108 |
+
Console line per epoch: "[epoch NNN md] key=val, ..." driven by
|
| 109 |
+
MD_EPOCH_SUMMARY_KEYS in bbflow/models/bbflow_module.py
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
================================================================================
|
| 113 |
+
3. THE SCOREBOARD (this is what everything is measured against)
|
| 114 |
+
================================================================================
|
| 115 |
+
|
| 116 |
+
Method RMSF r RMSF MAE Pairwise MAE PCA W2
|
| 117 |
+
-------------------------------------- ------ -------- ------------ ------
|
| 118 |
+
BBFlow official rerun (250 samples) 0.89 0.48 0.77 1.34
|
| 119 |
+
(same official, second record) 0.89 0.47 0.78 1.34
|
| 120 |
+
Version A (energy_from_q_diag, 30ep) 0.89 0.45 0.79 1.35
|
| 121 |
+
Long finetune orth1/recon0 100ep 0.88 0.48 0.81 1.35
|
| 122 |
+
A with SHUFFLED condition 0.89 0.48 1.27 1.51
|
| 123 |
+
|
| 124 |
+
READING OF THE SCOREBOARD
|
| 125 |
+
- A WINS RMSF MAE (0.45 vs 0.47-0.48). This is a real, repeated win.
|
| 126 |
+
- A ties RMSF r.
|
| 127 |
+
- A is behind on Pairwise (0.79 vs 0.77-0.78) and PCA W2 (1.35 vs 1.34) by
|
| 128 |
+
0.01-0.02 - i.e. by roughly the amount BBFlow's own two records differ from
|
| 129 |
+
each other (0.77 vs 0.78; 0.47 vs 0.48).
|
| 130 |
+
- Shuffled-condition collapse (Pairwise 0.79 -> 1.27) proves the condition
|
| 131 |
+
carries real information.
|
| 132 |
+
- NOBODY HAS EVER MEASURED THE SEED-TO-SEED VARIANCE of these numbers. The
|
| 133 |
+
user has refused multi-seed runs. So "we are 0.01 behind" is currently not
|
| 134 |
+
distinguishable from noise, and cannot be, under the current constraints.
|
| 135 |
+
A paired significance test over the 82 per-protein values from the EXISTING
|
| 136 |
+
saved runs would answer it at zero GPU cost, if the per-protein metric CSVs
|
| 137 |
+
still exist on the server. This was suggested and declined; it remains the
|
| 138 |
+
cheapest unexploited information in the project.
|
| 139 |
+
|
| 140 |
+
Upper bound reference (NOT deployable, oracle):
|
| 141 |
+
per-protein oracle scale selection gives Pairwise MAE 0.5583.
|
| 142 |
+
Best-scale distribution is bimodal (scale12: 31 proteins, scale30: 27),
|
| 143 |
+
length does not predict it, no deployable predictor was ever found.
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
================================================================================
|
| 147 |
+
4. THE CORE DIAGNOSIS (the reason this whole line exists)
|
| 148 |
+
================================================================================
|
| 149 |
+
|
| 150 |
+
THE ARCHITECTURE
|
| 151 |
+
x_eq --> LatentEncoder --> modes U, prior q(c | x_eq)
|
| 152 |
+
|
|
| 153 |
+
sample c ~ q
|
| 154 |
+
|
|
| 155 |
+
(x_eq, c) --> BBFlow generator --> conformation
|
| 156 |
+
repeat 250x -----------------> ensemble --> official metrics
|
| 157 |
+
|
| 158 |
+
THE BUG IN THE OBJECTIVE (not a code bug - a design gap)
|
| 159 |
+
The existing losses:
|
| 160 |
+
local_cov_loss, cross_cov_loss, rmsf_loss
|
| 161 |
+
supervise the PRIOR's THEORETICAL covariance:
|
| 162 |
+
Sigma_prior = sum_k energy_k * U_k U_k^T ( = U E_q[cc^T] U^T )
|
| 163 |
+
This quantity contains NO GENERATOR PARAMETERS AT ALL.
|
| 164 |
+
|
| 165 |
+
The official metrics measure the GENERATOR's OUTPUT ensemble covariance:
|
| 166 |
+
Sigma_gen = Cov(x_1 ... x_250)
|
| 167 |
+
|
| 168 |
+
There was never a loss connecting the two. The generator hears c (verified:
|
| 169 |
+
condition injection works, FiLM adapters receive nonzero grad, signed paths
|
| 170 |
+
alive) but was never required to turn c into the correct ensemble statistics.
|
| 171 |
+
|
| 172 |
+
This single fact explains the entire history:
|
| 173 |
+
- probe/proxy metrics improve (they measure the prior)
|
| 174 |
+
- downstream stays flat (it measures the generator)
|
| 175 |
+
- more training on proxies makes downstream worse (30->60 pca_align)
|
| 176 |
+
- the generator UNDER-DISPERSES: contraction diagnostics measured
|
| 177 |
+
gen_amp_median/MD = 0.71-0.79, PC1 var/MD = 0.34-0.54
|
| 178 |
+
i.e. the generator systematically compresses the ensemble.
|
| 179 |
+
|
| 180 |
+
Plain statement: "the generator was never controlled at the ensemble level."
|
| 181 |
+
|
| 182 |
+
WHY THE MECHANISM'S SIGNAL DOESN'T SHOW UP IN THE OFFICIAL TABLE
|
| 183 |
+
The condition's information lives in cross-covariance / collective directional
|
| 184 |
+
structure (far cross_cov corr is the one metric that reliably improves). The
|
| 185 |
+
three official metrics are mostly amplitude/spread statistics that BBFlow
|
| 186 |
+
already does well. The improved dimension is largely orthogonal to what the
|
| 187 |
+
metrics reward. That is why proxies win and the table doesn't move.
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
================================================================================
|
| 191 |
+
5. WHAT WAS TRIED BEFORE AND FAILED (condensed - details in experiment_trace)
|
| 192 |
+
================================================================================
|
| 193 |
+
|
| 194 |
+
- Long latent finetune (100ep, orth1/recon0): worse than official on Pairwise.
|
| 195 |
+
- PCA-align loss (lambda 0.1, 30ep): train proxies improve, held-out test82
|
| 196 |
+
mode-PCA alignment DROPS. Not a downstream win.
|
| 197 |
+
NOTE: even ON THE TRAINING SET, with a loss explicitly pushing it, the
|
| 198 |
+
energy-weighted overlap with MD top-2 PCs saturated at only ~0.22 (60ep
|
| 199 |
+
~0.31). Learning MD principal DIRECTIONS from x_eq appears intrinsically
|
| 200 |
+
hard here. Also: pca_align uses oracle_modes as a training target, which
|
| 201 |
+
the "non-negotiable oracle policy" (section 12) appears to forbid. This
|
| 202 |
+
tension was never resolved.
|
| 203 |
+
- PCA-align 30 -> 60 epochs: proxies keep improving, downstream degrades.
|
| 204 |
+
- Global condition_scale sweep on the 60ep ckpt: no globally good scale exists.
|
| 205 |
+
Larger scale fixes the median but not the MAE; PCA W2 best near scale10.
|
| 206 |
+
- Per-protein oracle scale: strong upper bound (0.5583) but bimodal and no
|
| 207 |
+
inference-time predictor was found. Length does not explain the split.
|
| 208 |
+
- Condition cycle loss (lambda 0.05): internal targets improve, downstream
|
| 209 |
+
worse. MECHANISM: cycle forces each frame to equal sum_k c_k U_k exactly,
|
| 210 |
+
which CONTRACTS the ensemble and kills diversity. It is ANTAGONISTIC to the
|
| 211 |
+
current generator-response loss (one contracts, one wants correct
|
| 212 |
+
dispersion). KEEP lambda_condition_cycle = 0.0.
|
| 213 |
+
- q temperature (tau) scaling: improves far cross-cov, hurts Pairwise/PCA.
|
| 214 |
+
- fullcov variant: PCA improves, Pairwise breaks.
|
| 215 |
+
|
| 216 |
+
PATTERN: every local knob produces a seesaw - improve one metric, break
|
| 217 |
+
another. The trace explicitly warns against per-protein drilldowns as a
|
| 218 |
+
default next step; they consumed time without producing decisions.
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
================================================================================
|
| 222 |
+
6. THE CURRENT MECHANISM: generator-response covariance loss
|
| 223 |
+
================================================================================
|
| 224 |
+
|
| 225 |
+
IDEA
|
| 226 |
+
Put a loss on the GENERATOR'S OWN OUTPUT response to the condition, cheaply,
|
| 227 |
+
without any 20-step rollout.
|
| 228 |
+
|
| 229 |
+
ANTITHETIC CENTRAL DIFFERENCE
|
| 230 |
+
For one protein, one noisy state, sample a zero-mean fluctuation of q:
|
| 231 |
+
delta = (c_sample - mu_bar) * delta_scale, c_sample ~ q,
|
| 232 |
+
mu_bar = softmax(mixture_logits) . mixture_mu (the mean of q)
|
| 233 |
+
Build two conditions and run the generator on both:
|
| 234 |
+
c_plus = mu_bar + delta
|
| 235 |
+
c_minus = mu_bar - delta
|
| 236 |
+
Take the one-step clean predictions (model_output["pred_trans"]), align both
|
| 237 |
+
to trans_equilibrium (Kabsch, same convention as the MD targets), and take:
|
| 238 |
+
d = ( align(pred(c_plus)) - align(pred(c_minus)) ) / 2
|
| 239 |
+
|
| 240 |
+
d[i] is the 3D displacement of residue i caused by this fluctuation. Because
|
| 241 |
+
+delta and -delta share the same background noisy state, subtracting cancels
|
| 242 |
+
everything not caused by c.
|
| 243 |
+
|
| 244 |
+
WHY IT IS STATISTICALLY VALID WITH FEW SAMPLES
|
| 245 |
+
To first order d = J*delta, so
|
| 246 |
+
E_delta[ d d^T ] = J Cov_q J^T = the generator's response covariance.
|
| 247 |
+
You NEVER reconstruct the 250-sample covariance. Each step contributes one
|
| 248 |
+
unbiased rank-1 sample and SGD averages over thousands of steps - exactly the
|
| 249 |
+
way flow matching learns a whole distribution one noisy sample at a time.
|
| 250 |
+
"8 vs 250" is a non-issue because nothing is estimated per-step.
|
| 251 |
+
|
| 252 |
+
IMPORTANT CORRECTION (this cost us an argument, get it right):
|
| 253 |
+
The above unbiasedness holds for RAW covariance matching (v1). It does NOT
|
| 254 |
+
hold for the NORMALIZED shape objective (v2), because C/tr(C) is NONLINEAR:
|
| 255 |
+
E[ C / tr(C) ] != E[C] / tr(E[C])
|
| 256 |
+
A single-delta rank-1 normalized outer product is a BIASED estimator of the
|
| 257 |
+
target normalized covariance. Therefore, under v2, going from 2 deltas to
|
| 258 |
+
1 delta CHANGES THE OBJECTIVE - it is not merely a variance increase, and it
|
| 259 |
+
is not "free". DO NOT cut student deltas to 1 to save time.
|
| 260 |
+
|
| 261 |
+
WHY NORMALIZED SHAPE (v2 over v1)
|
| 262 |
+
Raw covariance matching lets the model take a shortcut: globally amplify the
|
| 263 |
+
response. That can improve PCA W2 while blowing up RMSF/Pairwise. v2 compares
|
| 264 |
+
SHAPE only:
|
| 265 |
+
C/tr(C) vs C_MD/tr(C_MD)
|
| 266 |
+
which is scale-invariant, so amplification cannot reduce the shape loss. It
|
| 267 |
+
forces the model to learn WHICH residues/directions move together.
|
| 268 |
+
|
| 269 |
+
WHY AN AMPLITUDE ANCHOR IS THEN REQUIRED
|
| 270 |
+
Shape normalization removes ALL amplitude constraint. Without an anchor the
|
| 271 |
+
response magnitude drifts freely. So a weak anchor pins the trace:
|
| 272 |
+
trace_anchor_loss = mean( log( tr(C) / tr(anchor) )^2 )
|
| 273 |
+
Current anchor target = tr(local_cov_MD), i.e. the MD ensemble's own trace.
|
| 274 |
+
|
| 275 |
+
COST
|
| 276 |
+
Extra forwards per step = 2 * num_deltas (= 4 with 2 deltas), all gradient
|
| 277 |
+
checkpointed. The condition is DETACHED, so gradients flow ONLY into the
|
| 278 |
+
generator - this deliberately isolates "make the generator honor the given
|
| 279 |
+
condition" from the prior/q fit. U and q are NOT trained by this loss.
|
| 280 |
+
|
| 281 |
+
APPLIED ONLY IN A NOISE BAND
|
| 282 |
+
Only samples with t in [GENERATOR_COV_T_MIN, GENERATOR_COV_T_MAX] = [0.1, 0.6]
|
| 283 |
+
contribute. CONVENTION: interpolant_bbflow.py does
|
| 284 |
+
trans_t = (1 - t)*noise + t*data
|
| 285 |
+
so t=1 is CLEAN and t=0 is PURE NOISE. "mid-high noise" = low-to-mid t.
|
| 286 |
+
The extra forwards run on the WHOLE batch every step regardless (out-of-band
|
| 287 |
+
samples get loss weight 0) - this is deliberate, to keep the DDP autograd
|
| 288 |
+
graph STATIC. Do not "optimize" this into a conditional skip without thinking
|
| 289 |
+
about DDP dynamic-graph errors.
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
================================================================================
|
| 293 |
+
7. CURRENT CODE: WHAT IS WHERE
|
| 294 |
+
================================================================================
|
| 295 |
+
|
| 296 |
+
LINEAGE WARNING
|
| 297 |
+
The v1 implementation (single delta, raw covariance) was written by Claude and
|
| 298 |
+
has been ENTIRELY OVERWRITTEN by Codex's v2 rewrite. Do not look for v1 config
|
| 299 |
+
names (lambda_gen_local_cov, lambda_gen_rmsf, generator_cov_use_cross was v1
|
| 300 |
+
too). The md_trace fix (section 8) was applied on top of v2.
|
| 301 |
+
|
| 302 |
+
bbflow/models/latent.py
|
| 303 |
+
def generator_response_cov_loss(
|
| 304 |
+
self, response_deltas, res_mask, targets,
|
| 305 |
+
use_cross=False, sample_weight=None,
|
| 306 |
+
teacher_response_deltas=None, teacher_trace_anchor=None,
|
| 307 |
+
teacher_trace_denominator="teacher",
|
| 308 |
+
amplitude_anchor="teacher_trace")
|
| 309 |
+
- response_deltas has shape (S, B, N, 3), S = number of independent deltas.
|
| 310 |
+
- CRITICAL ORDER (do not break this):
|
| 311 |
+
C = mean_s( d_s d_s^T ) # combine across ALL deltas
|
| 312 |
+
trace_sample = tr(C)
|
| 313 |
+
C_norm = C / trace_sample # normalize ONCE, afterwards
|
| 314 |
+
loss = || C_norm - C_MD_norm ||^2 / denom
|
| 315 |
+
You must NOT compute a shape loss per delta and average them. Because the
|
| 316 |
+
normalization is nonlinear, mean_i( C_i/tr(C_i) ) != (sum_i C_i)/tr(sum_i C_i).
|
| 317 |
+
This invariant holds at EVERY chunking granularity, so chunking the forwards
|
| 318 |
+
is safe; splitting the loss is not.
|
| 319 |
+
- amplitude_anchor == "md_trace" -> anchor_trace = trace_target (MD's trace)
|
| 320 |
+
- amplitude_anchor == "teacher_trace" -> DEAD PATH, see section 8.
|
| 321 |
+
- Everything is wrapped in torch.autocast(enabled=False) and .float(), so the
|
| 322 |
+
covariance/trace/normalization math stays FP32 even under bf16-mixed. This
|
| 323 |
+
is why bf16-mixed is safe for this loss.
|
| 324 |
+
|
| 325 |
+
bbflow/models/bbflow_module.py
|
| 326 |
+
- _generator_response_cov_loss(...) : builds the deltas, the +/- conditions,
|
| 327 |
+
runs the chunked student forwards, optionally the teacher, calls the loss.
|
| 328 |
+
- _initial_generator_response_teacher() : deepcopy(self.model), eval(),
|
| 329 |
+
requires_grad_(False). ONLY reached when amplitude_anchor=="teacher_trace".
|
| 330 |
+
DO NOT RE-ENABLE. See section 8.
|
| 331 |
+
- _latent_group_z(): looks up motion_targets and stashes self._gen_cov_targets
|
| 332 |
+
- training_step(): calls the loss, adds gen_cov_loss into train_loss, and the
|
| 333 |
+
existing NaN guard covers it (NaN -> step skipped, 5 in a row -> raise).
|
| 334 |
+
- MD_EPOCH_SUMMARY_KEYS: the console per-epoch summary key list.
|
| 335 |
+
|
| 336 |
+
LOSS COMPOSITION (as actually assembled)
|
| 337 |
+
train_loss = official_loss (flow matching)
|
| 338 |
+
+ lambda_shape * latent_regularizer (motion/q/orth - PRIOR side)
|
| 339 |
+
+ condition_cycle_loss (currently 0)
|
| 340 |
+
+ gen_cov_loss
|
| 341 |
+
|
| 342 |
+
gen_cov_loss = lambda_generator_cov * (
|
| 343 |
+
lambda_gen_local_shape * gen_local_shape_loss
|
| 344 |
+
+ lambda_gen_cross_shape * gen_cross_shape_loss (if use_cross)
|
| 345 |
+
+ lambda_gen_trace_anchor * gen_trace_anchor_loss )
|
| 346 |
+
|
| 347 |
+
METRIC NAME LANDMINE
|
| 348 |
+
`gen_trace_ratio_to_teacher` IS A MISNOMER. Since the md_trace fix it reports
|
| 349 |
+
tr(C_student) / tr(local_cov_MD)
|
| 350 |
+
It has nothing to do with a teacher any more. The name was never updated.
|
| 351 |
+
Read it as "generator response amplitude / MD amplitude". 1.0 = matched.
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
================================================================================
|
| 355 |
+
8. THE TEACHER BUG - THE MOST IMPORTANT THING IN THIS DOC
|
| 356 |
+
================================================================================
|
| 357 |
+
|
| 358 |
+
WHAT v2 ORIGINALLY DID
|
| 359 |
+
It anchored the response amplitude to a "frozen teacher" =
|
| 360 |
+
copy.deepcopy(self.model) taken at training step 0, run under no_grad with the
|
| 361 |
+
same deltas.
|
| 362 |
+
|
| 363 |
+
WHY IT WAS CATASTROPHICALLY WRONG
|
| 364 |
+
The condition-injection adapters are ZERO-INITIALIZED on purpose, so that a
|
| 365 |
+
warm-started model initially reproduces vanilla BBFlow exactly:
|
| 366 |
+
bbflow/models/embedder.py:181-188
|
| 367 |
+
nn.init.zeros_ on z_node_adapter[-1], z_edge_adapter[-1],
|
| 368 |
+
disp_node_adapter[-1], disp_edge_adapter[-1]
|
| 369 |
+
(both weight and bias)
|
| 370 |
+
bbflow/models/bbflow_model.py:107-108
|
| 371 |
+
nn.init.zeros_ on film_mlp[-1] (weight and bias)
|
| 372 |
+
|
| 373 |
+
Therefore at step 0 the model's response to c is IDENTICALLY ZERO. The teacher
|
| 374 |
+
is a frozen snapshot of exactly that state, so the teacher's response to c is
|
| 375 |
+
zero FOREVER. Then:
|
| 376 |
+
teacher_trace -> clamp_min(1e-8) -> pinned at the floor
|
| 377 |
+
trace_ratio = student_trace / 1e-8 -> ~1e6
|
| 378 |
+
anchor loss = log(ratio)^2, minimized at student_trace = 1e-8
|
| 379 |
+
=> THE ANCHOR WAS ACTIVELY TRAINING THE STUDENT'S RESPONSE TO ZERO.
|
| 380 |
+
A model that ignores c cannot serve as a calibration reference for a response
|
| 381 |
+
to c. The anchor's purpose was inverted.
|
| 382 |
+
|
| 383 |
+
THE EVIDENCE (how it was caught - reuse this technique)
|
| 384 |
+
epoch 0: trace_mean=0.03611, ratio=4.363e6
|
| 385 |
+
epoch 1: trace_mean=0.004766, ratio=5.438e5
|
| 386 |
+
trace ratio between epochs: 0.03611/0.004766 = 7.58
|
| 387 |
+
metric ratio between epochs: 4.363e6/5.438e5 = 8.02
|
| 388 |
+
The two agree => the DENOMINATOR IS A CONSTANT => teacher_trace is pinned at
|
| 389 |
+
the 1e-8 clamp floor. Also 0.03611/1e-8 = 3.6e6, the right order of magnitude.
|
| 390 |
+
Meanwhile gen_response_abs_mean was dying: 0.001946 -> 0.0006519.
|
| 391 |
+
|
| 392 |
+
THE FIX (already applied, in the code now)
|
| 393 |
+
New config: generator_cov_amplitude_anchor, DEFAULT "md_trace".
|
| 394 |
+
"md_trace" -> anchor_trace = trace_target = tr(local_cov_MD).
|
| 395 |
+
Physically real, nonzero, needs NO teacher and NO extra
|
| 396 |
+
forwards (trace_target is already computed for the shape
|
| 397 |
+
normalization).
|
| 398 |
+
"teacher_trace" -> the old, broken path. Retained as dead code.
|
| 399 |
+
generator_cov_initial_trace_anchor=false sets amplitude_anchor="none".
|
| 400 |
+
latent.py carries a comment recording this diagnosis at the md_trace branch.
|
| 401 |
+
|
| 402 |
+
RULE
|
| 403 |
+
DO NOT set generator_cov_amplitude_anchor=teacher_trace. If you ever want a
|
| 404 |
+
teacher-style anchor, the teacher must be a checkpoint whose adapters are
|
| 405 |
+
ALREADY TRAINED (e.g. A30), not a step-0 snapshot.
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
================================================================================
|
| 409 |
+
9. VALIDATION RUN - EVIDENCE THE MECHANISM WORKS
|
| 410 |
+
================================================================================
|
| 411 |
+
|
| 412 |
+
RUN: bbflow_base_gen_cov_v2_mdtrace_k8_10ep_3gpu_120k_bs10_20260717_003351
|
| 413 |
+
CONFIG: use_cross=false, lambda_gen_trace_anchor=0.05, md_trace anchor,
|
| 414 |
+
bf16-mixed, 120000/bs10, 3 GPU, warm start from official BBFlow.
|
| 415 |
+
KILLED at ~epoch 5 (validation achieved; config cannot win PCA W2).
|
| 416 |
+
|
| 417 |
+
metric ep0 ep1 ep2 ep3 ep4 ep5
|
| 418 |
+
---------------------- ------ ------ ------ ------ ------ ------
|
| 419 |
+
gen_trace_ratio(vs MD) 1.044 1.077 1.061 0.655 0.650 0.632
|
| 420 |
+
gen_response_abs_mean 0.512 0.593 0.554 0.460 0.453 0.478
|
| 421 |
+
gen_local_shape_loss 0.706 0.654 0.637 0.563 0.532 0.516
|
| 422 |
+
gen_trace_anchor_loss 1.168 0.658 0.656 0.467 0.325 0.299
|
| 423 |
+
official_loss - 0.760 0.477 0.473 0.442 0.427
|
| 424 |
+
rmsf_loss 0.487 0.488 0.438 0.428 0.429 0.439
|
| 425 |
+
cross_cov_far_corr 0.013 0.063 0.119 0.151 0.178 0.190
|
| 426 |
+
mode_gram_condition 2.3e5 1.8e5 8146 819.9 15.29 6.307
|
| 427 |
+
mode_max_cosine_abs 0.907 0.968 0.809 0.547 0.459 0.375
|
| 428 |
+
|
| 429 |
+
VERDICT: THE MECHANISM IS ENGAGED. All four validation criteria passed:
|
| 430 |
+
- ratio starts at ~1.04 (the 4.36e6 pathology is gone)
|
| 431 |
+
- gen_response_abs_mean stable ~0.45-0.6 (previously dying to 0.0006)
|
| 432 |
+
- gen_local_shape_loss MONOTONICALLY DECREASING 0.706 -> 0.516
|
| 433 |
+
=> the generator IS learning to match MD's covariance SHAPE
|
| 434 |
+
- official_loss healthy 0.760 -> 0.427 (the new loss did not wreck training)
|
| 435 |
+
Also good: mode basis conditioning collapsed from 2.3e5 to 6.3, modes becoming
|
| 436 |
+
orthogonal (max_cosine 0.907 -> 0.375), far cross-cov corr rising 0.013 -> 0.190.
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
================================================================================
|
| 440 |
+
10. THE KNOWN OPEN PROBLEM: AMPLITUDE DRIFT
|
| 441 |
+
================================================================================
|
| 442 |
+
|
| 443 |
+
OBSERVATION
|
| 444 |
+
gen_trace_ratio drifts 1.044 -> 0.632 and is still falling. The generator's
|
| 445 |
+
response amplitude is only ~63% of MD's -> UNDER-DISPERSED BY ~37%.
|
| 446 |
+
|
| 447 |
+
WHY
|
| 448 |
+
- gen_local_shape_loss (lambda 1.0) is SCALE-INVARIANT: it constrains nothing
|
| 449 |
+
about amplitude.
|
| 450 |
+
- gen_trace_anchor_loss is the ONLY amplitude constraint, at lambda 0.05 -
|
| 451 |
+
20x weaker.
|
| 452 |
+
- official_loss / motion_loss structurally PREFER contraction (predicting the
|
| 453 |
+
conditional mean is the safe play for a single-frame objective).
|
| 454 |
+
=> the weak anchor loses; amplitude sinks.
|
| 455 |
+
|
| 456 |
+
WHY IT MATTERS
|
| 457 |
+
This is exactly the project's known failure mode: contraction diagnostics
|
| 458 |
+
measured gen_amp/MD = 0.71-0.79 and PC1 var/MD = 0.34-0.54. Under-dispersion
|
| 459 |
+
directly damages Pairwise RMSD (spread too small) and PCA W2.
|
| 460 |
+
|
| 461 |
+
A TRAP IN READING THE METRICS (do not misdiagnose this)
|
| 462 |
+
gen_trace_anchor_loss DECREASES (1.168 -> 0.299) WHILE the ratio drifts AWAY
|
| 463 |
+
from 1. That is not a contradiction:
|
| 464 |
+
- the metric is mean(ratio)
|
| 465 |
+
- the loss is mean(log(ratio)^2)
|
| 466 |
+
ep0: log(1.044)^2 = 0.002, but loss = 1.168 => almost ALL of it is spread.
|
| 467 |
+
RMS(log) ~ 1.08 => per-sample ratios spanned roughly [0.34, 2.9] and
|
| 468 |
+
merely AVERAGED to 1.04.
|
| 469 |
+
ep5: log(0.632)^2 = 0.211, loss = 0.299 => only 0.088 is spread.
|
| 470 |
+
So the anchor IS working - it tightened the distribution - but it tightened
|
| 471 |
+
around the WRONG CENTER (0.63 instead of 1.0).
|
| 472 |
+
|
| 473 |
+
THE FIX (to be tested in the next run)
|
| 474 |
+
Raise lambda_gen_trace_anchor from 0.05 to 0.3.
|
| 475 |
+
Watch: if ratio still sinks below ~0.8 by epoch 3 -> raise to 0.5-1.0.
|
| 476 |
+
if official_loss starts climbing / NaNs appear -> drop to 0.15.
|
| 477 |
+
|
| 478 |
+
A SUBTLETY WORTH KNOWING (unresolved, probably benign)
|
| 479 |
+
Anchoring the c-INDUCED response trace to MD's FULL trace implicitly asks c
|
| 480 |
+
alone to explain all of MD's variance, ignoring that at inference the flow's
|
| 481 |
+
own noise (different x_0 per sample) also contributes spread. Strictly, the
|
| 482 |
+
ideal target may be < 1.0. BUT empirically the full generated ensemble is
|
| 483 |
+
UNDER-dispersed (0.7-0.8 of MD), so pushing up is the right direction. If a
|
| 484 |
+
future run over-disperses, lower the anchor target to ~0.8 rather than
|
| 485 |
+
abandoning the anchor.
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
================================================================================
|
| 489 |
+
11. WHAT IS RUNNING / THE NEXT RUN
|
| 490 |
+
================================================================================
|
| 491 |
+
|
| 492 |
+
STATUS AS OF 2026-07-17: the validation run was KILLED at ~epoch 5. Nothing is
|
| 493 |
+
training. epoch:005.ckpt from that run still exists and could be evaluated
|
| 494 |
+
downstream on idle GPUs for a free read on local-shape-only (low priority - it
|
| 495 |
+
targets RMSF, the metric already won).
|
| 496 |
+
|
| 497 |
+
NEXT RUN = validation config + EXACTLY TWO CHANGES:
|
| 498 |
+
GENERATOR_COV_USE_CROSS : false -> true (the EXPERIMENT: cross shape is
|
| 499 |
+
the only component that can
|
| 500 |
+
move PCA W2)
|
| 501 |
+
LAMBDA_GEN_TRACE_ANCHOR : 0.05 -> 0.3 (a BUG FIX for section 10)
|
| 502 |
+
|
| 503 |
+
Two changes at once is justified here: one is the experiment, one is a fix for a
|
| 504 |
+
measured defect. Running cross with a provably sinking amplitude would waste the
|
| 505 |
+
run.
|
| 506 |
+
|
| 507 |
+
COMMAND:
|
| 508 |
+
|
| 509 |
+
pkill -u wangyusong -9 -f experiments/train.py; sleep 3
|
| 510 |
+
|
| 511 |
+
cd ~/LD-FPG-main/bbflow_base
|
| 512 |
+
export PYTHONPATH=$PWD:${PYTHONPATH:-}
|
| 513 |
+
|
| 514 |
+
ATLAS_REPRO_ROOT=/data/shared/wangyusong/atals/bbflow_official_reproduction \
|
| 515 |
+
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) \
|
| 516 |
+
FINGERPRINT_CACHE=/home/wangyusong/LD-FPG-main/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt \
|
| 517 |
+
GPU_IDS=0,1,2 NUM_DEVICES=3 MAX_EPOCHS=10 \
|
| 518 |
+
CHECKPOINT_EVERY_N_EPOCHS=1 CHECKPOINT_SAVE_LAST=true CHECKPOINT_SAVE_TOP_K=-1 \
|
| 519 |
+
PRECISION=bf16-mixed MAX_NUM_RES_SQUARED=120000 MAX_BATCH_SIZE=10 \
|
| 520 |
+
ENERGY_FROM_Q=true ENERGY_FROM_Q_FULL_COV=false Q_DETACH_SHARED_ENCODER=false \
|
| 521 |
+
LAMBDA_MOTION=1.0 LAMBDA_Q=1.0 LAMBDA_MODE_ORTH=1.0 LAMBDA_MODE_RECON=0.0 LAMBDA_PCA_ALIGN=0.0 \
|
| 522 |
+
LAMBDA_CONDITION_CYCLE=0.0 \
|
| 523 |
+
LAMBDA_GENERATOR_COV=1.0 GENERATOR_COV_USE_CROSS=true \
|
| 524 |
+
GENERATOR_COV_T_MIN=0.1 GENERATOR_COV_T_MAX=0.6 GENERATOR_COV_DELTA_SCALE=1.0 \
|
| 525 |
+
GENERATOR_COV_NUM_DELTAS=2 GENERATOR_COV_STUDENT_CHUNK_DELTAS=1 \
|
| 526 |
+
GENERATOR_COV_CHECKPOINT=true GENERATOR_COV_INITIAL_TRACE_ANCHOR=true \
|
| 527 |
+
LAMBDA_GEN_LOCAL_SHAPE=1.0 LAMBDA_GEN_CROSS_SHAPE=1.0 LAMBDA_GEN_TRACE_ANCHOR=0.3 \
|
| 528 |
+
bash base_stages/00_train_final_mog_ddp.sh
|
| 529 |
+
|
| 530 |
+
POST-LAUNCH AUDIT (mandatory - a stray value already cost one run):
|
| 531 |
+
RUN_DIR=$(ls -dt .../bbflow_base_gen_cov_v2_mdtrace_cross_* | head -1)
|
| 532 |
+
grep -nE "generator_cov_use_cross|lambda_gen_trace_anchor|lambda_condition_cycle|precision" "$RUN_DIR/config.yaml"
|
| 533 |
+
MUST SEE: use_cross: true / trace_anchor: 0.3 / condition_cycle: 0.0 /
|
| 534 |
+
precision: bf16-mixed
|
| 535 |
+
|
| 536 |
+
WATCH IN THE FIRST FEW EPOCHS:
|
| 537 |
+
1. gen_cross_shape_loss APPEARS and DECREASES. If the key never appears,
|
| 538 |
+
use_cross did not take effect.
|
| 539 |
+
2. gen_trace_ratio_to_teacher (= tr(C)/tr(MD)) holds ~0.9-1.0, does not sink
|
| 540 |
+
to 0.6 again.
|
| 541 |
+
3. official_loss keeps falling smoothly (0.76 -> 0.43 last run).
|
| 542 |
+
|
| 543 |
+
DECISION RULE: if by epoch 3 the ratio is holding and cross shape is falling,
|
| 544 |
+
let it run to 10. Otherwise stop and adjust the anchor rather than burning 20h.
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
================================================================================
|
| 548 |
+
12. THE ORACLE POLICY (verbatim intent, from the trace, 2026-07-09)
|
| 549 |
+
================================================================================
|
| 550 |
+
- Oracle information is forbidden in training, checkpoint selection,
|
| 551 |
+
inference, calibration, routing, gating, or any deployable component.
|
| 552 |
+
- This includes test/validation MD frames, projected per-frame oracle
|
| 553 |
+
coefficients, oracle PCA modes/energies, oracle best scales, and any
|
| 554 |
+
feature derived from the target ensemble.
|
| 555 |
+
- Oracle quantities may only be used AFTER generation as offline diagnostic
|
| 556 |
+
labels or upper-bound analyses.
|
| 557 |
+
|
| 558 |
+
UNRESOLVED TENSION: the policy text explicitly lists "oracle PCA modes/
|
| 559 |
+
energies" as forbidden from influencing model parameters, yet
|
| 560 |
+
pca_alignment_loss trains on oracle_modes. Whoever picks this up should get a
|
| 561 |
+
ruling from the user before using oracle_modes as a training target.
|
| 562 |
+
|
| 563 |
+
GOOD NEWS: the CURRENT generator-response line uses NO oracle quantities. It
|
| 564 |
+
supervises against local_cov / cross_cov / rmsf, which are the ordinary MD
|
| 565 |
+
targets the core method has always used (computed from each TRAINING
|
| 566 |
+
protein's own MD). Keep it that way - it is a genuine advantage of this
|
| 567 |
+
design over pca_align.
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
================================================================================
|
| 571 |
+
13. INFRASTRUCTURE: THE OOM AND SPEED SAGA (so you don't repeat it)
|
| 572 |
+
================================================================================
|
| 573 |
+
|
| 574 |
+
THE MEMORY WALL
|
| 575 |
+
Version A already ran at ~76 GB / 79 GB. There were only ~3 GB of headroom.
|
| 576 |
+
Adding ANY extra forwards OOMs. Two runs were destroyed learning this.
|
| 577 |
+
OOM site: gafl/models/gafl/cfa.py, the attention-like tensor
|
| 578 |
+
`a[..., None, :, :, None]` (a 7.85 GiB single allocation). GAFL's CFA
|
| 579 |
+
materializes a large intermediate; it is memory-bandwidth bound.
|
| 580 |
+
|
| 581 |
+
WHAT ACTUALLY FIXED IT (all four stacked)
|
| 582 |
+
1. PRECISION=bf16-mixed (was 32-true - on an H100 that was throwing away
|
| 583 |
+
more than half the tensor-core throughput AND doubling activations).
|
| 584 |
+
The loss math is FP32-guarded, so this is safe.
|
| 585 |
+
2. 2+2 chunking: merge ONE delta's +/- into a single 2x-batch forward and do
|
| 586 |
+
2 such calls, instead of merging all 4 into one 4x-batch call. Halves the
|
| 587 |
+
attention peak. The statistical target is UNCHANGED (see section 7 - the
|
| 588 |
+
d_s are identical regardless of how the forwards are batched; only the
|
| 589 |
+
"combine C then normalize once" invariant matters).
|
| 590 |
+
3. GENERATOR_COV_CHECKPOINT=true: gradient-checkpoint the extra forwards
|
| 591 |
+
(activations recomputed in backward instead of stored).
|
| 592 |
+
4. MAX_NUM_RES_SQUARED 400000 -> 120000, MAX_BATCH_SIZE 32 -> 10.
|
| 593 |
+
|
| 594 |
+
MEMORY MEASUREMENT RULE (learned painfully)
|
| 595 |
+
A spot reading of 16 GB was a TROUGH, not the peak; the peak was ~70/80 GB.
|
| 596 |
+
Batch composition varies hugely with protein size. ALWAYS measure the peak:
|
| 597 |
+
nvidia-smi --query-gpu=memory.used --format=csv -l 5
|
| 598 |
+
over several minutes before concluding there is headroom.
|
| 599 |
+
|
| 600 |
+
SPEED FACTS
|
| 601 |
+
~1h55m per epoch, 3147 batches/rank, ~0.44 it/s, 3 GPUs, 10 epochs ~19h.
|
| 602 |
+
examples_per_second only ~1.4-3.3 for a 19.8M-parameter model on 3 H100s -
|
| 603 |
+
the GPUs are STARVED (tiny batch + CFA memory-bandwidth bound), not
|
| 604 |
+
compute-limited.
|
| 605 |
+
Removing the teacher gave only ~15% (0.38 -> 0.44 it/s), because with
|
| 606 |
+
teacher_num_deltas=1 + reuse_student_delta the teacher was only ONE merged
|
| 607 |
+
2x-batch no_grad call, not four forwards.
|
| 608 |
+
|
| 609 |
+
REMAINING SPEED LEVERS (in order)
|
| 610 |
+
1. GENERATOR_COV_CHECKPOINT=false - saves recomputing 4 student forwards.
|
| 611 |
+
ONLY if the measured PEAK allows it. The teacher's removal freed a whole
|
| 612 |
+
19.2M-param deepcopy plus its activations, so this may now fit. MEASURE
|
| 613 |
+
FIRST.
|
| 614 |
+
2. Raise batch back up toward A's 400000/32 if peak allows - improves H100
|
| 615 |
+
utilization AND restores a cleaner comparison to A (the reduced batch is
|
| 616 |
+
currently a confound vs A).
|
| 617 |
+
3. Remove NCCL_P2P_DISABLE=1 if it is set and P2P is healthy (it forces
|
| 618 |
+
allreduce through host memory).
|
| 619 |
+
4. CFA query-dimension chunking to re-enable full 4x merging. This is a real
|
| 620 |
+
project (patching third-party gafl attention). Only worth it if the method
|
| 621 |
+
is validated and many runs are needed.
|
| 622 |
+
|
| 623 |
+
DDP NOTES
|
| 624 |
+
strategy: ddp (Lightning default => find_unused_parameters=False,
|
| 625 |
+
static_graph=False). Multiple forwards + a SINGLE backward is fine. The graph
|
| 626 |
+
is kept static on purpose (extra forwards run every step when enabled). Do not
|
| 627 |
+
make the extra forwards conditional per-step without handling DDP dynamic
|
| 628 |
+
graphs. If you ever see "mark a variable ready only once", suspect
|
| 629 |
+
checkpointing interactions.
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
================================================================================
|
| 633 |
+
14. HARD-WON PROCESS RULES
|
| 634 |
+
================================================================================
|
| 635 |
+
1. NEVER write a path/command from memory. Read the script or
|
| 636 |
+
${RUN_DIR}/config.yaml first. This rule exists because it was broken
|
| 637 |
+
repeatedly (02_sample_test.sh ignores OUTPUT_DIR; 03_evaluate.sh needs
|
| 638 |
+
ATLAS_VIEW_ROOT; a hydra +ckpt_path override was silently ignored and a
|
| 639 |
+
"resume" started from scratch).
|
| 640 |
+
2. config.yaml IS THE TRUTH. A stray LAMBDA_CONDITION_CYCLE=0.05 slipped into
|
| 641 |
+
a v2 command and was only caught by grepping config.yaml. Audit every run
|
| 642 |
+
before letting it burn hours.
|
| 643 |
+
3. VERIFY RESUME by the loaded epoch/global_step in the first log lines, never
|
| 644 |
+
by the output directory name.
|
| 645 |
+
4. THE LOCAL MACHINE CANNOT RUN ANYTHING. No python, no torch. Code you write
|
| 646 |
+
is unverified beyond careful reading. Say so plainly; do not hand over a
|
| 647 |
+
large untested training change and imply it is safe.
|
| 648 |
+
5. Do not turn on several loss terms at once - attribution becomes impossible.
|
| 649 |
+
The local-shape-then-cross staging exists for this reason.
|
| 650 |
+
6. Do not propose per-protein drilldowns as a default next step (the trace
|
| 651 |
+
explicitly bans this; they burned time without producing decisions).
|
| 652 |
+
7. Watch the FIRST ~50 steps of any new run (gen_* finite and nonzero,
|
| 653 |
+
response nonzero). That costs nothing and catches silent no-ops.
|
| 654 |
+
8. When a metric looks impossible (e.g. ratio = 4e6), check whether a
|
| 655 |
+
denominator is pinned at a clamp floor. Cross-check by seeing whether the
|
| 656 |
+
metric scales EXACTLY with the numerator across epochs.
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
================================================================================
|
| 660 |
+
15. OPEN QUESTIONS / UNRESOLVED RISKS
|
| 661 |
+
================================================================================
|
| 662 |
+
1. ONE-STEP vs 20-STEP GAP. The response uses pred_trans, a single-step clean
|
| 663 |
+
prediction, not the 20-step ODE sampler's output. This is a known bias. The
|
| 664 |
+
defence is that a biased GENERATOR-AWARE signal beats the previous
|
| 665 |
+
GENERATOR-BLIND prior loss (whose bias was 100%). Unquantified.
|
| 666 |
+
2. FIRST-ORDER / LINEARITY. +/-delta captures only the linear response. It can
|
| 667 |
+
be self-checked cheaply via the second difference
|
| 668 |
+
pred(+d)+pred(-d)-2*pred(0): small => linear regime holds. NEVER MEASURED.
|
| 669 |
+
Would cost one extra forward.
|
| 670 |
+
3. c-INDUCED vs TOTAL VARIANCE (section 10 subtlety).
|
| 671 |
+
4. NO DOWNSTREAM NUMBER EXISTS for ANY generator-response checkpoint. The
|
| 672 |
+
whole line is still validated only by training-side metrics. The first real
|
| 673 |
+
read must come from reproduction/02_sample_test.sh + 03_evaluate.sh.
|
| 674 |
+
5. CROSS SHAPE IS UNTESTED. use_cross=true has never actually run. It is the
|
| 675 |
+
only component that can move PCA W2, and it is also the highest-variance,
|
| 676 |
+
N x N term - historically the seesaw's favourite.
|
| 677 |
+
6. SIGNIFICANCE IS UNMEASURED (section 3). The 0.01-0.02 gaps may be noise.
|
| 678 |
+
7. CACHE PATH DISCREPANCY (section 2) - /home/... vs ${REPRO}/... may not be
|
| 679 |
+
the same file as A used. Verify before claiming a clean A-vs-A+loss
|
| 680 |
+
ablation.
|
| 681 |
+
8. BATCH SIZE CONFOUND. The current runs use 120000/10 while A used 400000/32.
|
| 682 |
+
Strictly this is not a clean ablation against A. Restore if memory permits.
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
================================================================================
|
| 686 |
+
16. IMMEDIATE NEXT STEPS
|
| 687 |
+
================================================================================
|
| 688 |
+
1. Launch the cross+anchor run (section 11). Audit config.yaml immediately.
|
| 689 |
+
2. At epoch 0-1, confirm gen_cross_shape_loss exists and falls, and that the
|
| 690 |
+
ratio holds near 0.9-1.0. If not, stop and fix the anchor weight rather
|
| 691 |
+
than running 10 epochs.
|
| 692 |
+
3. First real deliverable: take a checkpoint (epoch 4 or later) through
|
| 693 |
+
02_sample_test.sh (250 samples, CONDITION_MODE=real) and 03_evaluate.sh,
|
| 694 |
+
and put the four official numbers next to the section 3 scoreboard. THIS
|
| 695 |
+
HAS NEVER BEEN DONE FOR THIS MECHANISM. Everything so far is training-side.
|
| 696 |
+
4. Only after a downstream number exists should anyone invest in CFA tiling,
|
| 697 |
+
batch restoration, or further loss engineering.
|
| 698 |
+
5. If the downstream number is flat: the honest options are (a) the one-step
|
| 699 |
+
proxy is too weak and a real ensemble-level objective is needed (expensive,
|
| 700 |
+
previously rejected), or (b) revisit whether the official metrics can
|
| 701 |
+
measure what this method improves at all (section 4, last paragraph).
|
| 702 |
+
================================================================================
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
================================================================================
|
| 706 |
+
17. G-CALIBRATION + DIVERGENCE ROOT CAUSE + DIRECTION UPDATE (2026-07-18/19)
|
| 707 |
+
================================================================================
|
| 708 |
+
|
| 709 |
+
WHERE A30 ACTUALLY STANDS (do not understate this again)
|
| 710 |
+
A30 = bbflow_base_energy_from_q_diag_orth1_recon0_30ep. Full 250-sample:
|
| 711 |
+
RMSF r 0.89 | RMSF MAE 0.45 | Pairwise 0.79 | PCA W2 1.35.
|
| 712 |
+
- It WINS RMSF MAE (0.45 vs 0.47-0.48, real repeated), TIES RMSF r, and is
|
| 713 |
+
within BBFlow's own record-to-record noise on Pairwise/PCA W2 (0.01-0.02).
|
| 714 |
+
- SHUFFLED-condition control: Pairwise 0.79->1.27, PCA W2 1.35->1.51. So the
|
| 715 |
+
condition carries real, protein-specific information. A30 is a genuine
|
| 716 |
+
partial success, NOT "= BBFlow". The missing piece is a BROAD win (also beat
|
| 717 |
+
Pairwise AND PCA W2), which A30's generator-BLIND prior supervision cannot
|
| 718 |
+
reach - it sits on a documented seesaw (push PCA W2, lose Pairwise).
|
| 719 |
+
|
| 720 |
+
WHAT THE CURRENT LINE CHANGES vs A30
|
| 721 |
+
- generator-BLIND -> generator-AWARE: instead of supervising the prior
|
| 722 |
+
covariance, perturb c by +/-delta and supervise the GENERATOR's actual
|
| 723 |
+
response covariance. Directly targets the generator output structure (PCA
|
| 724 |
+
W2), the thing A30 structurally cannot move.
|
| 725 |
+
- G-calibration: measure G = T_full/T_1step where T_full is the c-response
|
| 726 |
+
trace on the REAL sampler (shared prior noise x0, full linspace(min_t,1,20)
|
| 727 |
+
grid, no_grad), then anchor the single-step response to md_trace/G. Fixes the
|
| 728 |
+
single-step-vs-20-step amplitude gap (measured G ~6.5-10x, i.e. the old
|
| 729 |
+
single-step anchor over-shot ~6-10x -> that was the source of the RMSF-4.6
|
| 730 |
+
over-dispersion, NOT "unfrozen backbone").
|
| 731 |
+
|
| 732 |
+
BUGS FOUND AND FIXED THIS ROUND (all in the crash/over-disperse path)
|
| 733 |
+
- teacher anchor trained response to 0 -> replaced with md_trace reference.
|
| 734 |
+
- single-step vs 20-step 6.5x miscalibration -> G-calibration (rollout T_full
|
| 735 |
+
rewritten to start from shared prior noise x0 over the full grid; Codex's
|
| 736 |
+
first cut wrongly started from the training trans_t over 2 coarse steps).
|
| 737 |
+
- relative (LM) ridge in project_displacement_lstsq (absolute 1e-4 ridge was
|
| 738 |
+
swallowed in fp32 -> singular solve crash).
|
| 739 |
+
- THE DIVERGENCE ROOT CAUSE: mode normalization `u_global / mode_norm`
|
| 740 |
+
(latent.py ~469 and ~552) had NO stop-gradient. Backprop carries a
|
| 741 |
+
1/mode_norm^2 term; once a mode collapses (norm -> the eps floor 1e-3) that
|
| 742 |
+
gradient explodes ~1e6x, burns the shared encoder to NaN (mixture logits NaN
|
| 743 |
+
-> Categorical crash at epoch 3). A positive feedback: shape loss nudges
|
| 744 |
+
modes collinear -> normalization amplifies the collapsed-mode gradient ->
|
| 745 |
+
more collapse. mode_orth (lambda 1) cannot beat a 1e6x amplified gradient.
|
| 746 |
+
FIX: detach mode_norm in both normalizations (forward identical, kills the
|
| 747 |
+
1/c^2 path) + raise mode_norm_eps 1e-6 -> 1e-4. This is a real defect fix,
|
| 748 |
+
NOT gradient clipping (clipping would mask the divergence, not cure it).
|
| 749 |
+
|
| 750 |
+
KEY DIRECTION UPDATE - RECONSIDER FREEZING
|
| 751 |
+
- Freezing the base was introduced to stop the cross-run over-dispersion. But
|
| 752 |
+
that over-dispersion was really the AMPLITUDE miscalibration, which G-cal now
|
| 753 |
+
fixes. A30 ran UNFROZEN and was stable + good, so "unfrozen" was never the
|
| 754 |
+
cause.
|
| 755 |
+
- Freezing also introduced the ADDITIVE CEILING: a frozen base can only ADD
|
| 756 |
+
motion, not REDISTRIBUTE it, and PCA W2 needs redistribution. So freezing
|
| 757 |
+
fights the actual goal.
|
| 758 |
+
- RECOMMENDED next run: UNFROZEN + G-cal + generator-aware response + anchor
|
| 759 |
+
warmup (0->target over ~3 epochs), NO gradient clipping (the mode_norm fix is
|
| 760 |
+
the real fix). This keeps A30's redistribution ability and adds generator-
|
| 761 |
+
aware targeting with the amplitude now calibrated. Watch official_loss (must
|
| 762 |
+
stay ~0.85, not rise = backbone degrading), mode_max_cosine_abs (<0.9),
|
| 763 |
+
cross_cov_far_corr (up = PCA proxy moving).
|
| 764 |
+
- Console epoch log was trimmed (bbflow_module.py on_train_epoch_end) to loss +
|
| 765 |
+
5 tagged watch metrics, one per line. Full metrics remain in
|
| 766 |
+
latent_train_epoch_metrics.csv.
|
| 767 |
+
|
| 768 |
+
DECISION RULE
|
| 769 |
+
- Next clean run's downstream (250 samples, real condition) vs A30/BBFlow:
|
| 770 |
+
- PCA W2 moves below 1.34 WITHOUT losing Pairwise -> generator-aware breaks
|
| 771 |
+
the seesaw; push it (possibly toward a fully differentiable few-step
|
| 772 |
+
rollout objective on the whole ensemble = the only form that can truly
|
| 773 |
+
force redistribution).
|
| 774 |
+
- PCA W2 flat / seesaw persists -> the additive/response-shaping family is
|
| 775 |
+
exhausted; A30 remains the best banked result and the only remaining bet is
|
| 776 |
+
the differentiable rollout objective, not more anchor/scale tuning.
|
| 777 |
+
================================================================================
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
================================================================================
|
| 781 |
+
18. ENDPOINT COVARIANCE TRANSPORT ROUTE (2026-07-19)
|
| 782 |
+
================================================================================
|
| 783 |
+
|
| 784 |
+
WHY THIS ROUTE EXISTS
|
| 785 |
+
The additive / single-step generator-response family kept falling into the same
|
| 786 |
+
two endpoints:
|
| 787 |
+
- unfrozen/additive response -> over-dispersed endpoint ensembles;
|
| 788 |
+
- frozen/weak response -> inert, approximately BBFlow.
|
| 789 |
+
|
| 790 |
+
The new route does NOT retrain the generator and does NOT approximate 20-step
|
| 791 |
+
dynamics with fewer steps. It starts after true 20-step BBFlow sampling has
|
| 792 |
+
already produced endpoint structures. It then applies a cheap endpoint-level
|
| 793 |
+
covariance transport:
|
| 794 |
+
|
| 795 |
+
base stream : official BBFlow, eq -> individual endpoint frames;
|
| 796 |
+
ensemble stream : low-rank learned/oracle correlation structure, applied as
|
| 797 |
+
an endpoint redistribution transform.
|
| 798 |
+
|
| 799 |
+
The key constraint is marginal preservation:
|
| 800 |
+
|
| 801 |
+
C* = D_B^1/2 [(1-lambda) R_B + lambda R_target] D_B^1/2
|
| 802 |
+
|
| 803 |
+
D_B is the diagonal variance of the BBFlow endpoint ensemble. Therefore the
|
| 804 |
+
transform is intended to preserve BBFlow's per-coordinate fluctuation scale and
|
| 805 |
+
total trace while changing only correlation/PCA structure. This is the first
|
| 806 |
+
cheap route that directly acts on real 20-step endpoints and can redistribute
|
| 807 |
+
variance instead of adding extra variance.
|
| 808 |
+
|
| 809 |
+
IMPLEMENTED FILES
|
| 810 |
+
1. scripts/covariance_transport_batch.py
|
| 811 |
+
- Batch transport for a standard ensemble directory.
|
| 812 |
+
- Inputs:
|
| 813 |
+
--ensemble_dir existing BBFlow sampled endpoint directory
|
| 814 |
+
--atlas_root ATLAS MD root with <name>/<name>.pdb and R1/R2/R3 xtc
|
| 815 |
+
--test_csv test CSV, normally dataset_csv/test/ATLAS_test.csv
|
| 816 |
+
--out_dir output directory with <name>/sampled_conformations.pdb
|
| 817 |
+
--mode oracle or a30
|
| 818 |
+
--lam global correlation mixing coefficient
|
| 819 |
+
- Output is CA-only multi-model sampled_conformations.pdb. This is enough
|
| 820 |
+
for the standard RMSF / Pairwise / PCA-W2 path because evaluation slices
|
| 821 |
+
both reference and model to CA for those metrics. Do NOT use CA-only output
|
| 822 |
+
to claim full backbone geometry quality.
|
| 823 |
+
- Uses sample-space whitening/coloring, not dense 3N x 3N eigendecomposition.
|
| 824 |
+
This keeps the cost bounded by the generated ensemble rank.
|
| 825 |
+
|
| 826 |
+
2. scripts/export_condition_modes.py
|
| 827 |
+
- Exports A30 learned condition modes from a checkpoint:
|
| 828 |
+
<modes_dir>/<pdb_name>.npy with shape [N,K,3].
|
| 829 |
+
- Needed only for --mode a30. Oracle transport does not depend on A30.
|
| 830 |
+
|
| 831 |
+
DISCIPLINED EXECUTION ORDER
|
| 832 |
+
Step 1: ORACLE transport first.
|
| 833 |
+
Purpose: test whether the transport mechanism itself can improve PCA-W2 while
|
| 834 |
+
keeping RMSF/Pairwise clean. This separates "transport is flawed" from "A30
|
| 835 |
+
modes are not good enough".
|
| 836 |
+
|
| 837 |
+
Step 2: Only if oracle is clean, export A30 modes and run A30 transport.
|
| 838 |
+
Purpose: measure how much of the oracle gain the learned A30 mode subspace can
|
| 839 |
+
realize. A30 mode-PC overlap on test82 was only around 0.4, so expected gain is
|
| 840 |
+
small, not transformational.
|
| 841 |
+
|
| 842 |
+
Step 3: Evaluate with reproduction/03_evaluate.sh.
|
| 843 |
+
Required checks:
|
| 844 |
+
- RMSF MAE must not regress vs BBFlow/A30.
|
| 845 |
+
- Pairwise MAE must not regress.
|
| 846 |
+
- PCA W2 must improve below BBFlow's 1.34 to count as useful.
|
| 847 |
+
- If possible, add a separate structure-quality check before any paper claim,
|
| 848 |
+
because CA-only transport does not validate N/C/O geometry.
|
| 849 |
+
|
| 850 |
+
SERVER COMMAND TEMPLATE - ORACLE TRANSPORT
|
| 851 |
+
cd ~/LD-FPG-main/bbflow_base
|
| 852 |
+
export PYTHONPATH=$PWD:${PYTHONPATH:-}
|
| 853 |
+
|
| 854 |
+
REPRO_ROOT=/data/shared/wangyusong/atals/bbflow_official_reproduction
|
| 855 |
+
ENSEMBLE_DIR=$REPRO_ROOT/inference/checkpoints/<official_or_bbflow_ensemble_dir>
|
| 856 |
+
OUT_DIR=$REPRO_ROOT/inference/cov_transport_oracle_lam0p50
|
| 857 |
+
|
| 858 |
+
python scripts/covariance_transport_batch.py \
|
| 859 |
+
--ensemble_dir "$ENSEMBLE_DIR" \
|
| 860 |
+
--atlas_root "$REPRO_ROOT/datasets/ATLAS" \
|
| 861 |
+
--test_csv "$REPRO_ROOT/dataset_csv/test/ATLAS_test.csv" \
|
| 862 |
+
--out_dir "$OUT_DIR" \
|
| 863 |
+
--mode oracle \
|
| 864 |
+
--lam 0.50 \
|
| 865 |
+
--md_stride 1 \
|
| 866 |
+
--overwrite
|
| 867 |
+
|
| 868 |
+
ENSEMBLE_DIR="$OUT_DIR" \
|
| 869 |
+
METRICS_DIR="$REPRO_ROOT/metrics/cov_transport_oracle_lam0p50" \
|
| 870 |
+
METHOD_NAME="BBFlow-oracle-cov-transport-lam0p50" \
|
| 871 |
+
ATLAS_VIEW_ROOT="$REPRO_ROOT/datasets/ATLAS" \
|
| 872 |
+
TEST_CSV="$REPRO_ROOT/dataset_csv/test/ATLAS_test.csv" \
|
| 873 |
+
NUM_WORKERS=8 \
|
| 874 |
+
bash reproduction/03_evaluate.sh
|
| 875 |
+
|
| 876 |
+
SERVER COMMAND TEMPLATE - A30 MODE TRANSPORT
|
| 877 |
+
cd ~/LD-FPG-main/bbflow_base
|
| 878 |
+
export PYTHONPATH=$PWD:${PYTHONPATH:-}
|
| 879 |
+
|
| 880 |
+
REPRO_ROOT=/data/shared/wangyusong/atals/bbflow_official_reproduction
|
| 881 |
+
A30_CKPT=<path_to_A30_checkpoint>
|
| 882 |
+
MODES_DIR=$REPRO_ROOT/diagnostics/a30_condition_modes_test82
|
| 883 |
+
ENSEMBLE_DIR=$REPRO_ROOT/inference/checkpoints/<official_or_bbflow_ensemble_dir>
|
| 884 |
+
OUT_DIR=$REPRO_ROOT/inference/cov_transport_a30_lam0p50
|
| 885 |
+
|
| 886 |
+
python scripts/export_condition_modes.py \
|
| 887 |
+
--ckpt_path "$A30_CKPT" \
|
| 888 |
+
--csv_path "$REPRO_ROOT/dataset_csv/test/ATLAS_test.csv" \
|
| 889 |
+
--output_dir "$MODES_DIR" \
|
| 890 |
+
--overwrite
|
| 891 |
+
|
| 892 |
+
python scripts/covariance_transport_batch.py \
|
| 893 |
+
--ensemble_dir "$ENSEMBLE_DIR" \
|
| 894 |
+
--atlas_root "$REPRO_ROOT/datasets/ATLAS" \
|
| 895 |
+
--test_csv "$REPRO_ROOT/dataset_csv/test/ATLAS_test.csv" \
|
| 896 |
+
--out_dir "$OUT_DIR" \
|
| 897 |
+
--mode a30 \
|
| 898 |
+
--modes_dir "$MODES_DIR" \
|
| 899 |
+
--lam 0.50 \
|
| 900 |
+
--md_stride 1 \
|
| 901 |
+
--overwrite
|
| 902 |
+
|
| 903 |
+
ENSEMBLE_DIR="$OUT_DIR" \
|
| 904 |
+
METRICS_DIR="$REPRO_ROOT/metrics/cov_transport_a30_lam0p50" \
|
| 905 |
+
METHOD_NAME="BBFlow-A30-cov-transport-lam0p50" \
|
| 906 |
+
ATLAS_VIEW_ROOT="$REPRO_ROOT/datasets/ATLAS" \
|
| 907 |
+
TEST_CSV="$REPRO_ROOT/dataset_csv/test/ATLAS_test.csv" \
|
| 908 |
+
NUM_WORKERS=8 \
|
| 909 |
+
bash reproduction/03_evaluate.sh
|
| 910 |
+
|
| 911 |
+
FILES TO SYNC TO SERVER FOR THIS ROUTE
|
| 912 |
+
- scripts/covariance_transport_batch.py
|
| 913 |
+
- scripts/export_condition_modes.py
|
| 914 |
+
- docs/HANDOFF_2026-07-17.txt
|
| 915 |
+
|
| 916 |
+
DECISION RULE
|
| 917 |
+
- Oracle transport fails or breaks metrics -> stop this route. The endpoint
|
| 918 |
+
transport mechanism is not viable.
|
| 919 |
+
- Oracle wins but A30 does not -> mechanism is viable, but A30's learned mode
|
| 920 |
+
subspace lacks enough test-time correlation information.
|
| 921 |
+
- A30 transport improves PCA W2 while preserving RMSF/Pairwise -> this is the
|
| 922 |
+
cleanest current "dual-stream" story: BBFlow supplies individual frames and
|
| 923 |
+
learned low-rank modes reshape endpoint ensemble correlations.
|
| 924 |
+
================================================================================
|
bbflow_base/code_exports/a30_redesign_source_20260719/docs/experiment_trace_2026-07-05.md
ADDED
|
@@ -0,0 +1,1367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# BBFlow / Latent Motion Experiments Trace
|
| 2 |
+
|
| 3 |
+
Date: 2026-07-05
|
| 4 |
+
Scope: local record of experiments, code changes, key configs, what each run tried to prove, and what it actually proved.
|
| 5 |
+
|
| 6 |
+
This document is a working memory file. It should be updated whenever a run is launched, evaluated, killed, or reinterpreted.
|
| 7 |
+
|
| 8 |
+
## Core Goal
|
| 9 |
+
|
| 10 |
+
We are trying to improve BBFlow downstream ensemble quality on ATLAS test proteins, especially:
|
| 11 |
+
|
| 12 |
+
- RMSF correlation / MAE
|
| 13 |
+
- Pairwise RMSD MAE
|
| 14 |
+
- PCA W2
|
| 15 |
+
|
| 16 |
+
The central scientific question became:
|
| 17 |
+
|
| 18 |
+
> 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?
|
| 19 |
+
|
| 20 |
+
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.
|
| 21 |
+
|
| 22 |
+
## Important Code Files
|
| 23 |
+
|
| 24 |
+
Core model/training:
|
| 25 |
+
|
| 26 |
+
- `bbflow/models/latent.py`
|
| 27 |
+
- Latent motion prior.
|
| 28 |
+
- MoG coefficient prior.
|
| 29 |
+
- Motion target reconstruction losses.
|
| 30 |
+
- Added `pca_alignment_loss`.
|
| 31 |
+
|
| 32 |
+
- `bbflow/models/bbflow_module.py`
|
| 33 |
+
- Integrates latent prior into training/inference.
|
| 34 |
+
- Looks up motion targets by current batch `pdb_name`.
|
| 35 |
+
- Added `lambda_pca_align` handling and PCA alignment logging.
|
| 36 |
+
|
| 37 |
+
- `base_stages/00_train_final_mog_ddp.sh`
|
| 38 |
+
- Main 3/2-GPU latent training launcher.
|
| 39 |
+
- Supports `LAMBDA_MODE_ORTH`, `LAMBDA_MODE_RECON`, `LAMBDA_PCA_ALIGN`, `PCA_ALIGN_TOP_M`.
|
| 40 |
+
- Uses `experiment.warm_start` for official/model warm start or Lightning resume depending on checkpoint type.
|
| 41 |
+
|
| 42 |
+
Downstream / inference:
|
| 43 |
+
|
| 44 |
+
- `reproduction/02_sample_test.sh`
|
| 45 |
+
- Standard inference.
|
| 46 |
+
- Saves conformations as `sampled_conformations.pdb`.
|
| 47 |
+
- Supports `CONDITION_MODE`, `CONDITION_SCALE`, `POSTPROCESS_BFACTORS`, `SAMPLE_BATCH_SIZE`, `MAX_NUM_RES_SQUARED`.
|
| 48 |
+
|
| 49 |
+
- `reproduction/03_evaluate.sh`
|
| 50 |
+
- Standard downstream evaluation on saved conformations.
|
| 51 |
+
- Computes RMSD/RMSF/PCA-W2.
|
| 52 |
+
|
| 53 |
+
Analysis/diagnostics:
|
| 54 |
+
|
| 55 |
+
- `scripts/diagnose_mode_pca_alignment.py`
|
| 56 |
+
- Compares learned prior modes against MD PCA modes on a chosen CSV.
|
| 57 |
+
- Outputs `summary.json` and per-protein CSV.
|
| 58 |
+
|
| 59 |
+
- `scripts/evaluate_saved_condition_covariances.py`
|
| 60 |
+
- Evaluates generated/saved ensembles against MD covariance targets.
|
| 61 |
+
|
| 62 |
+
- `scripts/plot_epoch_metrics.py`
|
| 63 |
+
- Plots training metrics from `latent_train_epoch_metrics.csv`.
|
| 64 |
+
|
| 65 |
+
- `scripts/diagnose_training_contraction.py`
|
| 66 |
+
- Added after the PCA-align scale sweep.
|
| 67 |
+
- Reads existing epoch metrics and saved `sampled_conformations.pdb` files.
|
| 68 |
+
- Diagnoses whether downstream degradation is caused by ensemble amplitude contraction, MD-PC projection variance loss, or proxy/downstream mismatch.
|
| 69 |
+
|
| 70 |
+
- `scripts/extract_shape_fingerprints.py`
|
| 71 |
+
- Generates motion-target cache.
|
| 72 |
+
- Newer caches should include alignment version `row_kabsch_u_d_vh_v1`.
|
| 73 |
+
- Can store `oracle_modes`, `oracle_energy`, `oracle_mean_disp`.
|
| 74 |
+
|
| 75 |
+
- `scripts/validate_motion_target_cache.py`
|
| 76 |
+
- Checks required cache fields before expensive training.
|
| 77 |
+
|
| 78 |
+
## Important Data / Checkpoint Paths
|
| 79 |
+
|
| 80 |
+
Official BBFlow checkpoint:
|
| 81 |
+
|
| 82 |
+
```text
|
| 83 |
+
/home/wangyusong/LD-FPG-main/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
Official checkpoint rerun output:
|
| 87 |
+
|
| 88 |
+
```text
|
| 89 |
+
/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/official_bbflow_rerun_250
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
Main long finetune run:
|
| 93 |
+
|
| 94 |
+
```text
|
| 95 |
+
/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_official_modelonly_long_finetune_orth1_recon0_100ep_3gpu_20260630_191404
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
PCA-align 0.1 run:
|
| 99 |
+
|
| 100 |
+
```text
|
| 101 |
+
/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_pca_align_orth1_recon0_30ep_3gpu_20260704_055826
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
Scratch run currently being resumed:
|
| 105 |
+
|
| 106 |
+
```text
|
| 107 |
+
/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_scratch_mog_k8_m2_orth1_recon0_30ep_2gpu_20260703_192644
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
Motion target caches:
|
| 111 |
+
|
| 112 |
+
```text
|
| 113 |
+
/data/shared/wangyusong/atals/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt
|
| 114 |
+
/data/shared/wangyusong/atals/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1_oracle.pt
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
Notes:
|
| 118 |
+
|
| 119 |
+
- `_kabsch_v1.pt` is the non-oracle cache used by scratch run.
|
| 120 |
+
- `_kabsch_v1_oracle.pt` includes oracle PCA fields and was used for PCA-align training/diagnostics.
|
| 121 |
+
- 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`.
|
| 122 |
+
|
| 123 |
+
## Confirmed Code Behavior
|
| 124 |
+
|
| 125 |
+
### Training Split vs Cache
|
| 126 |
+
|
| 127 |
+
`PdbDataModuleBBFlow` reads:
|
| 128 |
+
|
| 129 |
+
```text
|
| 130 |
+
data.dataset.train_csv_path
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
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`.
|
| 134 |
+
|
| 135 |
+
Therefore:
|
| 136 |
+
|
| 137 |
+
```text
|
| 138 |
+
cache contains test82 != test82 used in training
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
Actual leakage criterion:
|
| 142 |
+
|
| 143 |
+
```text
|
| 144 |
+
train_csv names intersect test_csv names
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
User confirmed there was no train/test overlap.
|
| 148 |
+
|
| 149 |
+
### Checkpoint Saving
|
| 150 |
+
|
| 151 |
+
Current BBFlow training uses Lightning `ModelCheckpoint`:
|
| 152 |
+
|
| 153 |
+
```yaml
|
| 154 |
+
save_last: True
|
| 155 |
+
save_on_train_epoch_end: True
|
| 156 |
+
filename: "epoch:{epoch:03d}"
|
| 157 |
+
every_n_epochs: 1
|
| 158 |
+
save_top_k: -1
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
Meaning:
|
| 162 |
+
|
| 163 |
+
- Saves every epoch.
|
| 164 |
+
- Updates `last.ckpt`.
|
| 165 |
+
- Does not choose best checkpoint by validation metric.
|
| 166 |
+
- Base stage scripts set `experiment.first_val_epoch=inf`, so training does not run real validation/downstream.
|
| 167 |
+
|
| 168 |
+
Current downstream commands usually test:
|
| 169 |
+
|
| 170 |
+
```text
|
| 171 |
+
CKPT_PATH="$RUN_DIR/last.ckpt"
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
So by default we evaluate the final epoch, not best-val.
|
| 175 |
+
|
| 176 |
+
## Experiment Log
|
| 177 |
+
|
| 178 |
+
### 1. Official BBFlow Rerun
|
| 179 |
+
|
| 180 |
+
Purpose:
|
| 181 |
+
|
| 182 |
+
Prove that the evaluation pipeline and official checkpoint are correct.
|
| 183 |
+
|
| 184 |
+
Checkpoint:
|
| 185 |
+
|
| 186 |
+
```text
|
| 187 |
+
/home/wangyusong/LD-FPG-main/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
Output:
|
| 191 |
+
|
| 192 |
+
```text
|
| 193 |
+
/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/official_bbflow_rerun_250
|
| 194 |
+
```
|
| 195 |
+
|
| 196 |
+
Result:
|
| 197 |
+
|
| 198 |
+
```text
|
| 199 |
+
BBFlow-official-rerun-250:
|
| 200 |
+
RMSF r 0.89
|
| 201 |
+
RMSF MAE 0.48
|
| 202 |
+
Pairwise RMSD MAE 0.77
|
| 203 |
+
PCA W2 1.34
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
Conclusion:
|
| 207 |
+
|
| 208 |
+
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.
|
| 209 |
+
|
| 210 |
+
### 2. Long Finetune, Official Warm Start, Orth1/ReCon0, 100 Epochs
|
| 211 |
+
|
| 212 |
+
Run:
|
| 213 |
+
|
| 214 |
+
```text
|
| 215 |
+
bbflow_base_official_modelonly_long_finetune_orth1_recon0_100ep_3gpu_20260630_191404
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
Purpose:
|
| 219 |
+
|
| 220 |
+
Test whether latent condition with orthogonal mode regularization and no mode recon loss improves standard downstream.
|
| 221 |
+
|
| 222 |
+
Core config:
|
| 223 |
+
|
| 224 |
+
```text
|
| 225 |
+
official BBFlow model-only warm start
|
| 226 |
+
3 GPU
|
| 227 |
+
100 epochs
|
| 228 |
+
lambda_mode_orth=1
|
| 229 |
+
lambda_mode_recon=0
|
| 230 |
+
sample_coefficients=true
|
| 231 |
+
freeze_foundation=false
|
| 232 |
+
condition_mode=real for inference
|
| 233 |
+
```
|
| 234 |
+
|
| 235 |
+
Downstream real result:
|
| 236 |
+
|
| 237 |
+
```text
|
| 238 |
+
BBFlow-long-ft-orth1-recon0-real:
|
| 239 |
+
RMSF r 0.88
|
| 240 |
+
RMSF MAE 0.48
|
| 241 |
+
Pairwise RMSD MAE 0.81
|
| 242 |
+
PCA W2 1.35
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
Official rerun baseline:
|
| 246 |
+
|
| 247 |
+
```text
|
| 248 |
+
RMSF r 0.89
|
| 249 |
+
RMSF MAE 0.48
|
| 250 |
+
Pairwise RMSD MAE 0.77
|
| 251 |
+
PCA W2 1.34
|
| 252 |
+
```
|
| 253 |
+
|
| 254 |
+
Conclusion:
|
| 255 |
+
|
| 256 |
+
Long finetune did not beat official BBFlow. It is slightly worse, especially Pairwise RMSD.
|
| 257 |
+
|
| 258 |
+
### 3. Shuffled Condition Downstream
|
| 259 |
+
|
| 260 |
+
Purpose:
|
| 261 |
+
|
| 262 |
+
Check whether real condition actually matters relative to a corrupted condition.
|
| 263 |
+
|
| 264 |
+
Result:
|
| 265 |
+
|
| 266 |
+
```text
|
| 267 |
+
BBFlow-long-ft-orth1-recon0-shuffled:
|
| 268 |
+
RMSF r 0.89
|
| 269 |
+
RMSF MAE 0.48
|
| 270 |
+
Pairwise RMSD MAE 1.27
|
| 271 |
+
PCA W2 1.51
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
Conclusion:
|
| 275 |
+
|
| 276 |
+
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.
|
| 277 |
+
|
| 278 |
+
### 4. Probe: Real vs Zero/Shuffled Covariance
|
| 279 |
+
|
| 280 |
+
Purpose:
|
| 281 |
+
|
| 282 |
+
Mechanistic check whether condition affects covariance/cross-covariance statistics.
|
| 283 |
+
|
| 284 |
+
Key result:
|
| 285 |
+
|
| 286 |
+
Real condition improved far cross-covariance correlation over zero/shuffled in probe.
|
| 287 |
+
|
| 288 |
+
Representative deltas:
|
| 289 |
+
|
| 290 |
+
```text
|
| 291 |
+
real - zero far_cross_cov_corr delta ≈ +0.045
|
| 292 |
+
real - shuffled far_cross_cov_corr delta ≈ +0.029
|
| 293 |
+
```
|
| 294 |
+
|
| 295 |
+
But rel_loss often got worse:
|
| 296 |
+
|
| 297 |
+
```text
|
| 298 |
+
far_cross_cov_rel_loss delta worse by ~0.36-0.38
|
| 299 |
+
```
|
| 300 |
+
|
| 301 |
+
Conclusion:
|
| 302 |
+
|
| 303 |
+
Condition can improve some correlation structure, but scale/amplitude can be wrong. Also, probe statistics do not automatically transfer to saved-conformation downstream metrics.
|
| 304 |
+
|
| 305 |
+
### 5. Mode-PCA Alignment Diagnosis on Long Finetune
|
| 306 |
+
|
| 307 |
+
Purpose:
|
| 308 |
+
|
| 309 |
+
Test whether learned prior modes align with MD principal motion directions.
|
| 310 |
+
|
| 311 |
+
Command used `scripts/diagnose_mode_pca_alignment.py` on test82.
|
| 312 |
+
|
| 313 |
+
Old long-finetune values:
|
| 314 |
+
|
| 315 |
+
```text
|
| 316 |
+
all_learned_vs_md_top2_subspace_mean_sq_cos: 0.4848
|
| 317 |
+
all_learned_vs_md_top2_subspace_min_sq_cos: 0.3500
|
| 318 |
+
best_abs_cos_to_md_pc1: 0.5149
|
| 319 |
+
best_abs_cos_to_md_pc2: 0.5416
|
| 320 |
+
top_energy_abs_cos_to_md_pc1: 0.3302
|
| 321 |
+
top_energy_abs_cos_to_md_pc2: 0.3461
|
| 322 |
+
top2_energy_vs_md_top2_subspace_mean_sq_cos: 0.3086
|
| 323 |
+
top2_energy_vs_md_top2_subspace_min_sq_cos: 0.1185
|
| 324 |
+
```
|
| 325 |
+
|
| 326 |
+
Interpretation at the time:
|
| 327 |
+
|
| 328 |
+
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.
|
| 329 |
+
|
| 330 |
+
### 6. PCA Alignment Loss Added
|
| 331 |
+
|
| 332 |
+
Purpose:
|
| 333 |
+
|
| 334 |
+
Directly train energy-weighted learned modes to align with MD top PCA subspace.
|
| 335 |
+
|
| 336 |
+
Code:
|
| 337 |
+
|
| 338 |
+
- Added `LatentEncoder.pca_alignment_loss`.
|
| 339 |
+
- Added `lambda_pca_align`.
|
| 340 |
+
- Added metrics:
|
| 341 |
+
- `pca_align_loss`
|
| 342 |
+
- `pca_align_weighted_overlap`
|
| 343 |
+
- `pca_align_best_overlap`
|
| 344 |
+
- `pca_align_top_energy_overlap`
|
| 345 |
+
- `pca_align_top_energy_subspace_overlap`
|
| 346 |
+
|
| 347 |
+
Loss idea:
|
| 348 |
+
|
| 349 |
+
```text
|
| 350 |
+
learned modes U
|
| 351 |
+
MD oracle top PC1/PC2
|
| 352 |
+
mode_overlap = squared projection of each learned mode into MD top-PC subspace
|
| 353 |
+
energy weights = predicted mode energy / total energy
|
| 354 |
+
loss = 1 - sum_k energy_weight_k * mode_overlap_k
|
| 355 |
+
```
|
| 356 |
+
|
| 357 |
+
This is not inference-time PCA. PCA is only used as training supervision where enabled.
|
| 358 |
+
|
| 359 |
+
### 7. PCA-Align 0.1 Run, 30 Epochs, 3 GPU
|
| 360 |
+
|
| 361 |
+
Run:
|
| 362 |
+
|
| 363 |
+
```text
|
| 364 |
+
bbflow_base_pca_align_orth1_recon0_30ep_3gpu_20260704_055826
|
| 365 |
+
```
|
| 366 |
+
|
| 367 |
+
Core config:
|
| 368 |
+
|
| 369 |
+
```text
|
| 370 |
+
official BBFlow model-only warm start
|
| 371 |
+
3 GPU
|
| 372 |
+
30 epochs
|
| 373 |
+
lambda_mode_orth=1
|
| 374 |
+
lambda_mode_recon=0
|
| 375 |
+
lambda_pca_align=0.1
|
| 376 |
+
pca_align_top_m=2
|
| 377 |
+
condition real for inference
|
| 378 |
+
```
|
| 379 |
+
|
| 380 |
+
Training behavior:
|
| 381 |
+
|
| 382 |
+
Metrics improved in train:
|
| 383 |
+
|
| 384 |
+
```text
|
| 385 |
+
pca_align_weighted_overlap:
|
| 386 |
+
epoch 6 ≈ 0.0567
|
| 387 |
+
epoch 17 ≈ 0.0799
|
| 388 |
+
epoch 28 ≈ 0.1114
|
| 389 |
+
|
| 390 |
+
pca_align_top_energy_overlap:
|
| 391 |
+
epoch 6 ≈ 0.0969
|
| 392 |
+
epoch 17 ≈ 0.1374
|
| 393 |
+
epoch 28 ≈ 0.2160
|
| 394 |
+
|
| 395 |
+
mode_max_cosine_abs:
|
| 396 |
+
epoch 6 ≈ 0.6512
|
| 397 |
+
epoch 17 ≈ 0.4076
|
| 398 |
+
epoch 28 ≈ 0.3673
|
| 399 |
+
|
| 400 |
+
mode_gram_condition:
|
| 401 |
+
epoch 6 ≈ 809.9
|
| 402 |
+
epoch 17 ≈ 4.297
|
| 403 |
+
epoch 28 ≈ 3.758
|
| 404 |
+
|
| 405 |
+
cross_cov_far_corr:
|
| 406 |
+
epoch 6 ≈ 0.1811
|
| 407 |
+
epoch 17 ≈ 0.2663
|
| 408 |
+
epoch 28 ≈ 0.3009
|
| 409 |
+
```
|
| 410 |
+
|
| 411 |
+
Initial interpretation:
|
| 412 |
+
|
| 413 |
+
Training dynamics looked healthy. Alignment improved without mode collapse.
|
| 414 |
+
|
| 415 |
+
Test82 mode-PCA diagnosis:
|
| 416 |
+
|
| 417 |
+
```text
|
| 418 |
+
all_learned_vs_md_top2_subspace_mean_sq_cos: 0.3420
|
| 419 |
+
best_abs_cos_to_md_pc1: 0.3997
|
| 420 |
+
best_abs_cos_to_md_pc2: 0.4432
|
| 421 |
+
top_energy_abs_cos_to_md_pc1: 0.2613
|
| 422 |
+
top_energy_abs_cos_to_md_pc2: 0.2992
|
| 423 |
+
top2_energy_vs_md_top2_subspace_mean_sq_cos: 0.2408
|
| 424 |
+
```
|
| 425 |
+
|
| 426 |
+
Compared to old long-finetune diagnosis, all key alignment values decreased.
|
| 427 |
+
|
| 428 |
+
Conclusion:
|
| 429 |
+
|
| 430 |
+
`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.
|
| 431 |
+
|
| 432 |
+
### 8. Leakage Clarification for PCA Oracle Cache
|
| 433 |
+
|
| 434 |
+
Concern:
|
| 435 |
+
|
| 436 |
+
The oracle cache included train/val/test entries:
|
| 437 |
+
|
| 438 |
+
```text
|
| 439 |
+
atlas_full_md_motion_targets_k8_kabsch_v1_oracle.pt
|
| 440 |
+
```
|
| 441 |
+
|
| 442 |
+
At first, this was incorrectly called leakage.
|
| 443 |
+
|
| 444 |
+
Corrected reasoning:
|
| 445 |
+
|
| 446 |
+
- Cache can contain many proteins.
|
| 447 |
+
- Training only looks up current batch names.
|
| 448 |
+
- Current batch names come from train CSV.
|
| 449 |
+
- Therefore leakage only happens if test proteins are present in train CSV.
|
| 450 |
+
|
| 451 |
+
User confirmed no train/test overlap.
|
| 452 |
+
|
| 453 |
+
Conclusion:
|
| 454 |
+
|
| 455 |
+
The test82 mode-PCA drop for PCA-align 0.1 is a clean negative result, not explained by train/test leakage.
|
| 456 |
+
|
| 457 |
+
### 9. Scratch Run
|
| 458 |
+
|
| 459 |
+
Run:
|
| 460 |
+
|
| 461 |
+
```text
|
| 462 |
+
bbflow_base_scratch_mog_k8_m2_orth1_recon0_30ep_2gpu_20260703_192644
|
| 463 |
+
```
|
| 464 |
+
|
| 465 |
+
Config from `config.yaml`:
|
| 466 |
+
|
| 467 |
+
```text
|
| 468 |
+
warm_start: null
|
| 469 |
+
num_devices: 2
|
| 470 |
+
lambda_mode_orth: 1.0
|
| 471 |
+
lambda_mode_recon: 0.0
|
| 472 |
+
lambda_pca_align: not present / 0
|
| 473 |
+
num_modes: 8
|
| 474 |
+
mixture_components: 2
|
| 475 |
+
freeze_foundation: false
|
| 476 |
+
sample_coefficients: true
|
| 477 |
+
motion_target_cache_path:
|
| 478 |
+
/data/shared/wangyusong/atals/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt
|
| 479 |
+
```
|
| 480 |
+
|
| 481 |
+
Important correction:
|
| 482 |
+
|
| 483 |
+
Resume should use the cache from this config:
|
| 484 |
+
|
| 485 |
+
```text
|
| 486 |
+
atlas_full_md_motion_targets_k8_kabsch_v1.pt
|
| 487 |
+
```
|
| 488 |
+
|
| 489 |
+
Not the old default:
|
| 490 |
+
|
| 491 |
+
```text
|
| 492 |
+
atlas_full_md_motion_targets_k8.pt
|
| 493 |
+
```
|
| 494 |
+
|
| 495 |
+
If resume is done with a Lightning checkpoint:
|
| 496 |
+
|
| 497 |
+
```text
|
| 498 |
+
BASE_CKPT="$SCRATCH_RUN/last.ckpt"
|
| 499 |
+
RUN_DIR="$SCRATCH_RUN"
|
| 500 |
+
```
|
| 501 |
+
|
| 502 |
+
Then Lightning should restore epoch/optimizer/scheduler state.
|
| 503 |
+
|
| 504 |
+
## Current Pending / Running Items
|
| 505 |
+
|
| 506 |
+
### PCA-align 0.1 Downstream
|
| 507 |
+
|
| 508 |
+
Purpose:
|
| 509 |
+
|
| 510 |
+
Even though test82 mode-PCA alignment dropped, run full downstream to see whether this diagnosis correlates with saved-conformation metrics.
|
| 511 |
+
|
| 512 |
+
Command intent:
|
| 513 |
+
|
| 514 |
+
```text
|
| 515 |
+
single GPU
|
| 516 |
+
82 proteins
|
| 517 |
+
250 conformations/protein
|
| 518 |
+
SAMPLE_BATCH_SIZE=20
|
| 519 |
+
MAX_NUM_RES_SQUARED=400000
|
| 520 |
+
CONDITION_MODE=real
|
| 521 |
+
save sampled_conformations.pdb
|
| 522 |
+
evaluate RMSF / Pairwise RMSD / PCA W2
|
| 523 |
+
```
|
| 524 |
+
|
| 525 |
+
Question to answer:
|
| 526 |
+
|
| 527 |
+
```text
|
| 528 |
+
Does poorer mode-PCA alignment imply poorer downstream?
|
| 529 |
+
```
|
| 530 |
+
|
| 531 |
+
If yes:
|
| 532 |
+
|
| 533 |
+
Mode-PCA diagnosis is useful as a negative filter.
|
| 534 |
+
|
| 535 |
+
If no:
|
| 536 |
+
|
| 537 |
+
Mode-PCA diagnosis is not reliable enough as a checkpoint selector.
|
| 538 |
+
|
| 539 |
+
### Scratch Resume
|
| 540 |
+
|
| 541 |
+
Purpose:
|
| 542 |
+
|
| 543 |
+
Continue scratch training on GPUs 1,2 while GPU 0 can run downstream.
|
| 544 |
+
|
| 545 |
+
Must use:
|
| 546 |
+
|
| 547 |
+
```text
|
| 548 |
+
RUN_DIR = scratch run directory
|
| 549 |
+
BASE_CKPT = scratch last.ckpt
|
| 550 |
+
FINGERPRINT_CACHE = atlas_full_md_motion_targets_k8_kabsch_v1.pt
|
| 551 |
+
GPU_IDS=1,2
|
| 552 |
+
NUM_DEVICES=2
|
| 553 |
+
```
|
| 554 |
+
|
| 555 |
+
Do not accidentally resume scratch with oracle PCA cache or old non-versioned cache.
|
| 556 |
+
|
| 557 |
+
## Lessons Learned
|
| 558 |
+
|
| 559 |
+
### Proxy metrics are not enough
|
| 560 |
+
|
| 561 |
+
The following are useful but not sufficient:
|
| 562 |
+
|
| 563 |
+
- `cross_cov_far_corr`
|
| 564 |
+
- `cross_cov_far_loss`
|
| 565 |
+
- `pca_align_*`
|
| 566 |
+
- `mode_max_cosine_abs`
|
| 567 |
+
- `mode_gram_condition`
|
| 568 |
+
|
| 569 |
+
They can improve in training while downstream or test82 diagnosis fails.
|
| 570 |
+
|
| 571 |
+
### Need mini-downstream validation
|
| 572 |
+
|
| 573 |
+
Current BBFlow saves every epoch but chooses `last.ckpt`, not best-val. This is weak model selection.
|
| 574 |
+
|
| 575 |
+
Recommended next system:
|
| 576 |
+
|
| 577 |
+
```text
|
| 578 |
+
Every N epochs or selected checkpoints:
|
| 579 |
+
sample 5-10 validation proteins
|
| 580 |
+
50-100 conformations/protein
|
| 581 |
+
compute real downstream-like metrics:
|
| 582 |
+
RMSF
|
| 583 |
+
Pairwise RMSD
|
| 584 |
+
PCA W2
|
| 585 |
+
generated covariance metrics
|
| 586 |
+
use this to choose checkpoint
|
| 587 |
+
```
|
| 588 |
+
|
| 589 |
+
This is not a training loss, but it is much closer to downstream than current proxy metrics.
|
| 590 |
+
|
| 591 |
+
### Downstream tests must save conformations
|
| 592 |
+
|
| 593 |
+
User requirement:
|
| 594 |
+
|
| 595 |
+
> During testing/evaluation, always save conformations. Downstream metrics are first priority.
|
| 596 |
+
|
| 597 |
+
Probe-only statistics do not replace standard downstream.
|
| 598 |
+
|
| 599 |
+
### Checkpoint path discipline
|
| 600 |
+
|
| 601 |
+
Never guess checkpoint paths. Confirm with:
|
| 602 |
+
|
| 603 |
+
```bash
|
| 604 |
+
test -f "$CKPT_PATH"
|
| 605 |
+
grep relevant fields "$RUN_DIR/config.yaml"
|
| 606 |
+
```
|
| 607 |
+
|
| 608 |
+
Official checkpoint:
|
| 609 |
+
|
| 610 |
+
```text
|
| 611 |
+
/home/wangyusong/LD-FPG-main/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt
|
| 612 |
+
```
|
| 613 |
+
|
| 614 |
+
Do not invent:
|
| 615 |
+
|
| 616 |
+
```text
|
| 617 |
+
/data/.../bbflow_official_atlas/last.ckpt
|
| 618 |
+
models/bbflow-0.1/... under bbflow_base if absent
|
| 619 |
+
```
|
| 620 |
+
|
| 621 |
+
### Cache path discipline
|
| 622 |
+
|
| 623 |
+
There are multiple caches with similar names:
|
| 624 |
+
|
| 625 |
+
```text
|
| 626 |
+
atlas_full_md_motion_targets_k8.pt
|
| 627 |
+
atlas_full_md_motion_targets_k8_kabsch_v1.pt
|
| 628 |
+
atlas_full_md_motion_targets_k8_kabsch_v1_oracle.pt
|
| 629 |
+
```
|
| 630 |
+
|
| 631 |
+
Using the wrong one can cause:
|
| 632 |
+
|
| 633 |
+
```text
|
| 634 |
+
alignment_version mismatch
|
| 635 |
+
missing oracle_modes/oracle_energy
|
| 636 |
+
changed training target
|
| 637 |
+
```
|
| 638 |
+
|
| 639 |
+
Before resume, read the run config and reuse the original cache unless intentionally changing the experiment.
|
| 640 |
+
|
| 641 |
+
## Recommended Next Steps
|
| 642 |
+
|
| 643 |
+
1. Do not keep trying to rescue the 60-epoch PCA-align checkpoint with a global scale.
|
| 644 |
+
2. Run the scale-group diagnosis:
|
| 645 |
+
- low group: proteins whose oracle best scale is `scale12`
|
| 646 |
+
- high group: proteins whose oracle best scale is `scale30`
|
| 647 |
+
- mid group: all remaining best scales
|
| 648 |
+
3. Compare low vs high groups using existing features:
|
| 649 |
+
- learned mode energies
|
| 650 |
+
- mode-PCA alignment diagnostics
|
| 651 |
+
- MD pairwise RMSD / PCA W2
|
| 652 |
+
- generated amplitude and MD-PC variance diagnostics
|
| 653 |
+
4. Inspect the two extreme failure examples:
|
| 654 |
+
- `6qj0A`: over-spread at all scales
|
| 655 |
+
- `7c45A`: under-spread at all scales
|
| 656 |
+
5. If low/high groups separate cleanly by available inference-time features, test a per-protein scale rule.
|
| 657 |
+
6. If low/high groups do not separate, treat oracle per-protein scale as an upper bound that is not currently usable.
|
| 658 |
+
7. Implement mini-downstream validation so checkpoint selection is based on actual validation metrics, not only proxy losses.
|
| 659 |
+
8. If trying PCA-align again, lower `LAMBDA_PCA_ALIGN` such as `0.03` and early-stop by mini-downstream metrics.
|
| 660 |
+
9. Resume scratch only with the exact scratch config/cache and verify Lightning restore.
|
| 661 |
+
|
| 662 |
+
## Claims We Can Make Now
|
| 663 |
+
|
| 664 |
+
Safe claims:
|
| 665 |
+
|
| 666 |
+
- Official BBFlow checkpoint and downstream evaluation pipeline are reproduced.
|
| 667 |
+
- Long latent finetune did not beat official BBFlow on standard downstream.
|
| 668 |
+
- Real condition is better than shuffled condition, but that is not sufficient because official BBFlow still wins.
|
| 669 |
+
- Probe/covariance improvements do not automatically imply downstream gains.
|
| 670 |
+
- PCA-align loss with `lambda=0.1` improves training alignment metrics but worsens held-out test82 mode-PCA diagnosis.
|
| 671 |
+
- Current BBFlow checkpoint selection is last-epoch, not best-validation.
|
| 672 |
+
- 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.
|
| 673 |
+
- Continuing the same PCA-align run from 30 to 60 epochs improves proxy losses but degrades downstream, especially Pairwise RMSD and many scale settings.
|
| 674 |
+
- Global `condition_scale` cannot solve the 60-epoch checkpoint: median statistics can be moved, but per-protein Pairwise MAE remains poor.
|
| 675 |
+
- 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.
|
| 676 |
+
- Protein length alone does not explain the per-protein best scale split.
|
| 677 |
+
|
| 678 |
+
Unsafe claims:
|
| 679 |
+
|
| 680 |
+
- PCA-align improves downstream.
|
| 681 |
+
- Mode-PCA alignment is a reliable downstream predictor.
|
| 682 |
+
- Current PCA-align checkpoint is useful for final paper claims.
|
| 683 |
+
- Test leakage occurred just because cache contained test entries.
|
| 684 |
+
- A practical per-protein scale rule has been found.
|
| 685 |
+
- The oracle per-protein scale result is usable at inference time without a predictor.
|
| 686 |
+
|
| 687 |
+
## 2026-07-07 Update: PCA-Align 30->60, Scale Sweep, and Per-Protein Scale
|
| 688 |
+
|
| 689 |
+
### Runs / Outputs
|
| 690 |
+
|
| 691 |
+
Main run:
|
| 692 |
+
|
| 693 |
+
```text
|
| 694 |
+
/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_pca_align_orth1_recon0_30ep_3gpu_20260704_055826
|
| 695 |
+
```
|
| 696 |
+
|
| 697 |
+
Important generated/evaluation directories:
|
| 698 |
+
|
| 699 |
+
```text
|
| 700 |
+
standard_downstream_extend60_scale05_250
|
| 701 |
+
standard_downstream_extend60_scale07_250
|
| 702 |
+
standard_downstream_extend60_scale10_250
|
| 703 |
+
standard_downstream_extend60_scale_gt1_grid_250
|
| 704 |
+
contraction_diagnostics_30to60
|
| 705 |
+
per_protein_scale_error_analysis
|
| 706 |
+
scale_group_diagnosis
|
| 707 |
+
```
|
| 708 |
+
|
| 709 |
+
### 30->60 Training Metrics
|
| 710 |
+
|
| 711 |
+
The 30-epoch checkpoint was resumed to epoch 59/60 with Lightning optimizer state preserved. Training proxy metrics continued to improve:
|
| 712 |
+
|
| 713 |
+
```text
|
| 714 |
+
motion_loss 1.664174 -> 1.323183 (-0.340991)
|
| 715 |
+
local_cov_loss 0.707414 -> 0.567489 (-0.139924)
|
| 716 |
+
cross_cov_loss 0.792517 -> 0.623544 (-0.168973)
|
| 717 |
+
cross_cov_far_corr 0.320930 -> 0.472915 (+0.151985)
|
| 718 |
+
cross_cov_far_loss 0.964359 -> 0.818648 (-0.145711)
|
| 719 |
+
rmsf_loss 0.302754 -> 0.203370 (-0.099384)
|
| 720 |
+
pca_align_loss 0.885546 -> 0.813072 (-0.072474)
|
| 721 |
+
pca_align_weighted_overlap 0.114454 -> 0.186928 (+0.072474)
|
| 722 |
+
pca_align_top_energy_overlap 0.207225 -> 0.310178 (+0.102954)
|
| 723 |
+
mode_coeff_abs 0.305543 -> 0.355761 (+0.050217)
|
| 724 |
+
mode_coeff_std 0.451974 -> 0.535341 (+0.083367)
|
| 725 |
+
q_nll_per_dim 0.099669 -> 0.184764 (+0.085096)
|
| 726 |
+
```
|
| 727 |
+
|
| 728 |
+
Interpretation:
|
| 729 |
+
|
| 730 |
+
- The condition coefficient magnitude did not collapse; it increased.
|
| 731 |
+
- The model became better at the proxy losses.
|
| 732 |
+
- Downstream got worse anyway, proving the proxy/downstream gap is real.
|
| 733 |
+
|
| 734 |
+
### 60-Epoch Global Scale Sweep
|
| 735 |
+
|
| 736 |
+
Downstream for 60-epoch PCA-align checkpoint:
|
| 737 |
+
|
| 738 |
+
```text
|
| 739 |
+
Official BBFlow: Pairwise MAE 0.78, Pairwise median 2.76, PCA W2 1.34, RMSF MAE 0.47
|
| 740 |
+
|
| 741 |
+
scale10: Pairwise MAE 0.88, Pairwise median 2.52, PCA W2 1.31, RMSF MAE 0.48
|
| 742 |
+
scale12: Pairwise MAE 0.87, Pairwise median 2.74, PCA W2 1.39, RMSF MAE 0.49
|
| 743 |
+
scale14: Pairwise MAE 0.92, Pairwise median 2.91, PCA W2 1.41, RMSF MAE 0.49
|
| 744 |
+
scale16: Pairwise MAE 0.95, Pairwise median 3.05, PCA W2 1.39, RMSF MAE 0.52
|
| 745 |
+
scale18: Pairwise MAE 0.98, Pairwise median 3.23, PCA W2 1.39, RMSF MAE 0.54
|
| 746 |
+
scale20: Pairwise MAE 1.06, Pairwise median 3.33, PCA W2 1.45, RMSF MAE 0.58
|
| 747 |
+
scale30: Pairwise MAE 1.49, Pairwise median 3.99, PCA W2 1.52, RMSF MAE 0.74
|
| 748 |
+
```
|
| 749 |
+
|
| 750 |
+
Interpretation:
|
| 751 |
+
|
| 752 |
+
- Increasing scale fixes the global Pairwise median around `scale12` to `scale14`.
|
| 753 |
+
- It does not fix Pairwise MAE.
|
| 754 |
+
- PCA W2 is best around `scale10`; larger scales damage PCA W2.
|
| 755 |
+
- Global `condition_scale` only moves overall amplitude; it cannot fix per-protein distribution shape.
|
| 756 |
+
- The 60-epoch checkpoint has no globally good scale.
|
| 757 |
+
|
| 758 |
+
### Amplitude / Direction Diagnosis
|
| 759 |
+
|
| 760 |
+
`diagnose_training_contraction.py` compared generated ensembles with MD amplitude and MD top-PC projection.
|
| 761 |
+
|
| 762 |
+
For 60-epoch scales:
|
| 763 |
+
|
| 764 |
+
```text
|
| 765 |
+
gen_amp_median/MD gen_amp_q90/MD PC1 var/MD PC2 var/MD residue RMS ratio
|
| 766 |
+
scale05 0.7112 0.7253 0.3385 0.5951 0.7260
|
| 767 |
+
scale07 0.7458 0.7697 0.4147 0.7216 0.7620
|
| 768 |
+
scale10 0.7947 0.8402 0.5364 0.9140 0.8208
|
| 769 |
+
```
|
| 770 |
+
|
| 771 |
+
Interpretation:
|
| 772 |
+
|
| 773 |
+
- Generated ensembles are too small at scales <= 1.0.
|
| 774 |
+
- PC1 variance is especially under-dispersed.
|
| 775 |
+
- But increasing global scale later showed that amplitude correction alone does not recover Pairwise MAE or PCA W2.
|
| 776 |
+
|
| 777 |
+
### Per-Protein Scale Oracle
|
| 778 |
+
|
| 779 |
+
Existing scale grid:
|
| 780 |
+
|
| 781 |
+
```text
|
| 782 |
+
scale12, scale14, scale16, scale18, scale20, scale30
|
| 783 |
+
```
|
| 784 |
+
|
| 785 |
+
For each protein, choosing the best scale by Pairwise RMSD absolute error gives:
|
| 786 |
+
|
| 787 |
+
```text
|
| 788 |
+
oracle_pairwise_mae: 0.5583
|
| 789 |
+
oracle_model_pairwise_median: 2.8824
|
| 790 |
+
md_pairwise_median: 2.8905
|
| 791 |
+
oracle_md_pca_w2_median: 1.346
|
| 792 |
+
oracle_joint_pca_w2_median: 1.8231
|
| 793 |
+
```
|
| 794 |
+
|
| 795 |
+
This is much better than:
|
| 796 |
+
|
| 797 |
+
```text
|
| 798 |
+
official Pairwise MAE: 0.78
|
| 799 |
+
best global 60ep scale Pairwise MAE: ~0.87
|
| 800 |
+
```
|
| 801 |
+
|
| 802 |
+
Interpretation:
|
| 803 |
+
|
| 804 |
+
- The 6-way discrete oracle is a strong signal, not a tiny tuning artifact.
|
| 805 |
+
- Different proteins need very different scales.
|
| 806 |
+
- The oracle is not usable directly because it uses MD ground truth to choose scale.
|
| 807 |
+
- It provides an upper bound and motivates a per-protein scale predictor/classifier.
|
| 808 |
+
|
| 809 |
+
Best scale distribution:
|
| 810 |
+
|
| 811 |
+
```text
|
| 812 |
+
scale12 31 proteins
|
| 813 |
+
scale30 27 proteins
|
| 814 |
+
scale18 9 proteins
|
| 815 |
+
scale20 7 proteins
|
| 816 |
+
scale14 7 proteins
|
| 817 |
+
scale16 1 protein
|
| 818 |
+
```
|
| 819 |
+
|
| 820 |
+
Interpretation:
|
| 821 |
+
|
| 822 |
+
- The distribution is bimodal/extreme-heavy.
|
| 823 |
+
- This looks more like a classification problem than a continuous scale-regression problem.
|
| 824 |
+
- A simple global scale or simple length-based formula is unlikely to work.
|
| 825 |
+
|
| 826 |
+
Length correlation:
|
| 827 |
+
|
| 828 |
+
```text
|
| 829 |
+
corr(length, signed_error): about -0.10 to -0.12 across scales
|
| 830 |
+
corr(length, abs_error): about -0.03 to +0.04
|
| 831 |
+
```
|
| 832 |
+
|
| 833 |
+
Interpretation:
|
| 834 |
+
|
| 835 |
+
- Protein length alone does not explain whether a protein needs low or high scale.
|
| 836 |
+
|
| 837 |
+
### Extreme Failure Examples
|
| 838 |
+
|
| 839 |
+
Over-spread at all scales:
|
| 840 |
+
|
| 841 |
+
```text
|
| 842 |
+
6qj0A
|
| 843 |
+
scale12: MD 3.4330, model 10.4792, diff +7.0462
|
| 844 |
+
scale30: MD 3.4776, model 16.8809, diff +13.4032
|
| 845 |
+
```
|
| 846 |
+
|
| 847 |
+
Under-spread at all scales:
|
| 848 |
+
|
| 849 |
+
```text
|
| 850 |
+
7c45A
|
| 851 |
+
scale12: MD 9.6570, model 4.2683, diff -5.3888
|
| 852 |
+
scale30: MD 9.6113, model 6.6184, diff -2.9929
|
| 853 |
+
```
|
| 854 |
+
|
| 855 |
+
Interpretation:
|
| 856 |
+
|
| 857 |
+
- These represent opposite failure modes.
|
| 858 |
+
- `6qj0A` is too mobile even at low scale.
|
| 859 |
+
- `7c45A` is too conservative even at extreme scale.
|
| 860 |
+
- This suggests that failure is not just a scalar amplitude problem; learned mode quality/energy or generator response differs qualitatively by protein.
|
| 861 |
+
|
| 862 |
+
### Current Scientific Interpretation
|
| 863 |
+
|
| 864 |
+
The project has moved through these stages:
|
| 865 |
+
|
| 866 |
+
1. Latent condition improves some proxy statistics.
|
| 867 |
+
2. Standard downstream does not broadly improve over official BBFlow.
|
| 868 |
+
3. PCA-align can move PCA-related metrics but hurts or fails Pairwise RMSD.
|
| 869 |
+
4. More PCA-align training improves proxy losses but worsens downstream.
|
| 870 |
+
5. Global inference scale cannot solve the 60-epoch checkpoint.
|
| 871 |
+
6. Per-protein oracle scale has strong potential, but only if a non-oracle predictor can identify protein-specific scale needs.
|
| 872 |
+
|
| 873 |
+
Plain-language summary:
|
| 874 |
+
|
| 875 |
+
```text
|
| 876 |
+
The method has signal, but different proteins fail in opposite ways.
|
| 877 |
+
Some are already too energetic and need low scale.
|
| 878 |
+
Some are too conservative and need high scale.
|
| 879 |
+
A single global scale averages these failures and cannot win.
|
| 880 |
+
The next useful question is whether the low-scale and high-scale proteins can be distinguished using features available at inference time.
|
| 881 |
+
```
|
| 882 |
+
|
| 883 |
+
### Immediate Next Analysis
|
| 884 |
+
|
| 885 |
+
Run the scale-group diagnosis:
|
| 886 |
+
|
| 887 |
+
```text
|
| 888 |
+
low_scale12 = proteins whose oracle best scale is scale12
|
| 889 |
+
high_scale30 = proteins whose oracle best scale is scale30
|
| 890 |
+
mid_scale = all others
|
| 891 |
+
```
|
| 892 |
+
|
| 893 |
+
Compare group features:
|
| 894 |
+
|
| 895 |
+
```text
|
| 896 |
+
num_res
|
| 897 |
+
md_pairwise
|
| 898 |
+
md_pca_w2
|
| 899 |
+
joint_pca_w2
|
| 900 |
+
learned_energy_top0/top1
|
| 901 |
+
top_energy_abs_cos_to_md_pc1/pc2
|
| 902 |
+
top2_energy_vs_md_top2_subspace_mean_sq_cos
|
| 903 |
+
all_learned_vs_md_top2_subspace_mean_sq_cos
|
| 904 |
+
generated amplitude diagnostics if merged
|
| 905 |
+
```
|
| 906 |
+
|
| 907 |
+
Important methodological point:
|
| 908 |
+
|
| 909 |
+
- Do not rely only on Pearson correlation with continuous scale.
|
| 910 |
+
- The best-scale distribution is bimodal.
|
| 911 |
+
- Use group comparison / classification-style diagnostics first.
|
| 912 |
+
|
| 913 |
+
Outcome criteria:
|
| 914 |
+
|
| 915 |
+
- If low/high groups separate by inference-time features, test a per-protein scale rule.
|
| 916 |
+
- If they only separate by MD-ground-truth features, the oracle is not deployable.
|
| 917 |
+
- If they do not separate, treat per-protein oracle scale as an informative upper bound but not a practical method yet.
|
| 918 |
+
|
| 919 |
+
## 2026-07-08 Command/Path Failure Reflection
|
| 920 |
+
|
| 921 |
+
### What Happened
|
| 922 |
+
|
| 923 |
+
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.
|
| 924 |
+
|
| 925 |
+
The concrete failures were:
|
| 926 |
+
|
| 927 |
+
1. I assumed `reproduction/02_sample_test.sh` accepted an `OUTPUT_DIR` environment variable.
|
| 928 |
+
2. In reality, `02_sample_test.sh` ignores `OUTPUT_DIR` and writes to:
|
| 929 |
+
|
| 930 |
+
```text
|
| 931 |
+
${REPRO_ROOT}/inference
|
| 932 |
+
```
|
| 933 |
+
|
| 934 |
+
3. I therefore looked for generated conformations under the checkpoint `RUN_DIR`, where they did not exist.
|
| 935 |
+
4. I also assumed `reproduction/03_evaluate.sh` accepted `ATLAS_ROOT` and `OUT_DIR`.
|
| 936 |
+
5. In reality, `03_evaluate.sh` uses:
|
| 937 |
+
|
| 938 |
+
```text
|
| 939 |
+
ENSEMBLE_DIR
|
| 940 |
+
ATLAS_VIEW_ROOT
|
| 941 |
+
METRICS_DIR
|
| 942 |
+
TEST_CSV
|
| 943 |
+
METHOD_NAME
|
| 944 |
+
```
|
| 945 |
+
|
| 946 |
+
6. Because I used the wrong reference variable, evaluation fell back to the default:
|
| 947 |
+
|
| 948 |
+
```text
|
| 949 |
+
bbflow_base/reproduction/outputs/data/ATLAS
|
| 950 |
+
```
|
| 951 |
+
|
| 952 |
+
and produced repeated `No reference trajectory found` warnings.
|
| 953 |
+
|
| 954 |
+
### Root Cause
|
| 955 |
+
|
| 956 |
+
The root cause was not a confusing directory structure. The root cause was a bad operating procedure:
|
| 957 |
+
|
| 958 |
+
```text
|
| 959 |
+
I wrote commands from memory before checking the current script interfaces.
|
| 960 |
+
```
|
| 961 |
+
|
| 962 |
+
This violated the project rule that paths and runtime commands must be checked against the actual code before being given.
|
| 963 |
+
|
| 964 |
+
### Correct Script Interfaces
|
| 965 |
+
|
| 966 |
+
For sampling:
|
| 967 |
+
|
| 968 |
+
```bash
|
| 969 |
+
reproduction/02_sample_test.sh
|
| 970 |
+
```
|
| 971 |
+
|
| 972 |
+
uses:
|
| 973 |
+
|
| 974 |
+
```text
|
| 975 |
+
REPRO_ROOT
|
| 976 |
+
METADATA_ROOT
|
| 977 |
+
CKPT_PATH
|
| 978 |
+
GPU_ID
|
| 979 |
+
SAMPLES_PER_PROTEIN
|
| 980 |
+
SAMPLE_BATCH_SIZE
|
| 981 |
+
MAX_NUM_RES_SQUARED
|
| 982 |
+
INFERENCE_NAME
|
| 983 |
+
CONDITION_MODE
|
| 984 |
+
CONDITION_SCALE
|
| 985 |
+
POSTPROCESS_BFACTORS
|
| 986 |
+
INFERENCE_NUM_WORKERS
|
| 987 |
+
```
|
| 988 |
+
|
| 989 |
+
and writes to:
|
| 990 |
+
|
| 991 |
+
```text
|
| 992 |
+
${REPRO_ROOT}/inference
|
| 993 |
+
```
|
| 994 |
+
|
| 995 |
+
For evaluation:
|
| 996 |
+
|
| 997 |
+
```bash
|
| 998 |
+
reproduction/03_evaluate.sh
|
| 999 |
+
```
|
| 1000 |
+
|
| 1001 |
+
uses:
|
| 1002 |
+
|
| 1003 |
+
```text
|
| 1004 |
+
ENSEMBLE_DIR
|
| 1005 |
+
ATLAS_VIEW_ROOT
|
| 1006 |
+
METRICS_DIR
|
| 1007 |
+
TEST_CSV
|
| 1008 |
+
METHOD_NAME
|
| 1009 |
+
METHOD_TIME_SECONDS
|
| 1010 |
+
NUM_WORKERS
|
| 1011 |
+
```
|
| 1012 |
+
|
| 1013 |
+
and passes the reference trajectory directory through:
|
| 1014 |
+
|
| 1015 |
+
```text
|
| 1016 |
+
--md_dirs "${ATLAS_VIEW_ROOT}"
|
| 1017 |
+
```
|
| 1018 |
+
|
| 1019 |
+
### Correct Evaluation Command Pattern
|
| 1020 |
+
|
| 1021 |
+
For the `energy_from_q_diag` run, the correct structure is:
|
| 1022 |
+
|
| 1023 |
+
```bash
|
| 1024 |
+
RUN_DIR=/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_energy_from_q_diag_orth1_recon0_30ep_3gpu_20260707_165355
|
| 1025 |
+
|
| 1026 |
+
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 \
|
| 1027 |
+
ATLAS_VIEW_ROOT=/data/shared/wangyusong/atals/bbflow_official_reproduction/datasets/ATLAS \
|
| 1028 |
+
METRICS_DIR="$RUN_DIR/standard_downstream_metrics_real_250" \
|
| 1029 |
+
METHOD_NAME="BBFlow-energy-from-q-diag-30ep-real-250" \
|
| 1030 |
+
TEST_CSV=/data/shared/wangyusong/atals/bbflow_official_reproduction/dataset_csv/test/ATLAS_test.csv \
|
| 1031 |
+
bash reproduction/03_evaluate.sh
|
| 1032 |
+
```
|
| 1033 |
+
|
| 1034 |
+
### Rule Going Forward
|
| 1035 |
+
|
| 1036 |
+
Before giving any command involving paths, output directories, or environment variables:
|
| 1037 |
+
|
| 1038 |
+
```bash
|
| 1039 |
+
grep -n "VARIABLE_NAME\|script_argument" target_script.sh
|
| 1040 |
+
```
|
| 1041 |
+
|
| 1042 |
+
or open the script directly.
|
| 1043 |
+
|
| 1044 |
+
No command should be given from memory when the script interface is available.
|
| 1045 |
+
|
| 1046 |
+
Minimum checklist:
|
| 1047 |
+
|
| 1048 |
+
1. Read the sampling/evaluation script.
|
| 1049 |
+
2. Confirm the exact environment variables it accepts.
|
| 1050 |
+
3. Confirm where it writes outputs.
|
| 1051 |
+
4. Confirm the real generated directory with `find`.
|
| 1052 |
+
5. Only then provide the final command.
|
| 1053 |
+
|
| 1054 |
+
This is especially mandatory for:
|
| 1055 |
+
|
| 1056 |
+
```text
|
| 1057 |
+
02_sample_test.sh
|
| 1058 |
+
03_evaluate.sh
|
| 1059 |
+
training scripts
|
| 1060 |
+
checkpoint resume commands
|
| 1061 |
+
cleanup commands
|
| 1062 |
+
```
|
| 1063 |
+
# Non-negotiable oracle policy (2026-07-09)
|
| 1064 |
+
|
| 1065 |
+
- Oracle information is forbidden in training, checkpoint selection, inference,
|
| 1066 |
+
calibration, routing, gating, or any deployable method component.
|
| 1067 |
+
- This includes test/validation MD frames, projected per-frame oracle
|
| 1068 |
+
coefficients, oracle PCA modes/energies, oracle best scales, and any feature
|
| 1069 |
+
derived from the target ensemble.
|
| 1070 |
+
- Oracle quantities may only be used after generation as offline diagnostic
|
| 1071 |
+
labels or upper-bound analyses. They must never influence model parameters,
|
| 1072 |
+
hyperparameters selected on test data, or per-protein inference behavior.
|
| 1073 |
+
- Before every run, verify the effective config and cache path. A cache that
|
| 1074 |
+
contains oracle fields must not be used by a training or inference command,
|
| 1075 |
+
even if the current code path appears not to read those fields.
|
| 1076 |
+
- Any proposed experiment that conditions the generator on projected target
|
| 1077 |
+
coefficients is diagnostic-only and cannot be presented as an inference
|
| 1078 |
+
method or used to select a deployable checkpoint.
|
| 1079 |
+
|
| 1080 |
+
## Inference performance lesson (2026-07-09)
|
| 1081 |
+
|
| 1082 |
+
- Do not call multi-GPU parallelism an algorithmic inference speedup. Report
|
| 1083 |
+
single-GPU latency separately from throughput scaling.
|
| 1084 |
+
- The old sampler performed avoidable work at every ODE step: it copied every
|
| 1085 |
+
clean prediction to CPU, retained the complete rigid trajectory, converted
|
| 1086 |
+
every step to atom37, recomputed equilibrium geometry, and reran condition
|
| 1087 |
+
adapter MLPs even though only the final frame was written.
|
| 1088 |
+
- The optimized path keeps only the current ODE state and final frame, caches
|
| 1089 |
+
equilibrium/condition features once per sample batch, and exposes the number
|
| 1090 |
+
of function evaluations explicitly.
|
| 1091 |
+
- A true order-of-magnitude latency reduction requires reducing ODE model
|
| 1092 |
+
evaluations (for example 20 to 5) in addition to removing implementation
|
| 1093 |
+
waste. Any lower-NFE preset must pass downstream-quality comparison before it
|
| 1094 |
+
replaces the 20-step reference.
|
| 1095 |
+
|
| 1096 |
+
## Diagnostic script reliability lesson (2026-07-10)
|
| 1097 |
+
|
| 1098 |
+
- Do not assume metadata columns. The ATLAS test CSV used here contains only
|
| 1099 |
+
`name` and `pdb_path`; diagnostic scripts must derive the protein folder from
|
| 1100 |
+
`Path(pdb_path).parent` or fail loudly.
|
| 1101 |
+
- Do not use guessed MD frame indices. If `num_conformations` is absent, read
|
| 1102 |
+
the real frame count from the trajectory file. If the trajectory cannot be
|
| 1103 |
+
opened, stop the diagnostic instead of silently using early frames.
|
| 1104 |
+
- Do not rely on upstream device placement in diagnostic code. Any function that
|
| 1105 |
+
combines generated tensors with dataset frames must explicitly move all inputs
|
| 1106 |
+
to the generated tensor's device at the function boundary. This is mandatory
|
| 1107 |
+
for projection/cycle-consistency diagnostics where generated coordinates,
|
| 1108 |
+
equilibrium coordinates, mode tensors, and masks are mixed.
|
| 1109 |
+
- Before asking the user to rerun a new diagnostic script on the server, run a
|
| 1110 |
+
local syntax check and inspect every path where CPU/GPU tensors are mixed.
|
| 1111 |
+
Repeated server failures from avoidable metadata or device assumptions waste
|
| 1112 |
+
GPU time and user trust.
|
| 1113 |
+
|
| 1114 |
+
## Checkpoint resume lesson (2026-07-11)
|
| 1115 |
+
|
| 1116 |
+
- Do not assume a Hydra override such as `+ckpt_path=...` will be consumed by a
|
| 1117 |
+
training wrapper. If the wrapper script does not explicitly forward that key
|
| 1118 |
+
to `Trainer.fit(ckpt_path=...)`, the run may silently start from scratch while
|
| 1119 |
+
still writing into the intended `RUN_DIR`.
|
| 1120 |
+
- Before giving any resume command, inspect the training wrapper for the exact
|
| 1121 |
+
resume variable/name it supports, then verify the command line printed by the
|
| 1122 |
+
script contains that value.
|
| 1123 |
+
- A resume command is not considered valid until the first log lines show the
|
| 1124 |
+
loaded checkpoint epoch/global_step or the next epoch continues after the
|
| 1125 |
+
checkpoint. If `last.ckpt` was epoch 15, seeing `Epoch 0/1/2` means the command
|
| 1126 |
+
failed and must be stopped immediately.
|
| 1127 |
+
- Never continue a suspected resume run just because the config path or `RUN_DIR`
|
| 1128 |
+
looks correct. Effective resume state is determined by loaded optimizer state
|
| 1129 |
+
and epoch/global_step, not by output directory names.
|
| 1130 |
+
|
| 1131 |
+
## Evaluation reference path lesson (2026-07-11)
|
| 1132 |
+
|
| 1133 |
+
- Evaluation commands must explicitly set the real ATLAS reference trajectory
|
| 1134 |
+
directory. Do not allow `reproduction/03_evaluate.sh` or
|
| 1135 |
+
`scripts/analysis_script.py` to fall back to
|
| 1136 |
+
`reproduction/outputs/data/ATLAS`, because that local default does not contain
|
| 1137 |
+
the ATLAS trajectories used for these runs.
|
| 1138 |
+
- Before every evaluation, inspect `reproduction/03_evaluate.sh` and pass the
|
| 1139 |
+
exact reference variable it supports, pointing to:
|
| 1140 |
+
`/data/shared/wangyusong/atals/bbflow_official_reproduction/datasets/ATLAS`.
|
| 1141 |
+
- If warnings say `No reference trajectory found for ... in
|
| 1142 |
+
/home/wangyusong/LD-FPG-main/bbflow_base/reproduction/outputs/data/ATLAS`,
|
| 1143 |
+
stop the evaluation immediately. The generated ensembles may be correct, but
|
| 1144 |
+
the evaluation command is using the wrong reference path and the metrics are
|
| 1145 |
+
invalid.
|
| 1146 |
+
|
| 1147 |
+
## Per-protein analysis lesson (2026-07-11)
|
| 1148 |
+
|
| 1149 |
+
- Do not propose per-protein drilldowns as the default next step. In this
|
| 1150 |
+
project, repeated per-protein analyses have consumed time without producing
|
| 1151 |
+
stable design decisions.
|
| 1152 |
+
- Avoid narratives based on a few named proteins or post-hoc per-protein
|
| 1153 |
+
examples unless the user explicitly asks for case studies.
|
| 1154 |
+
- Prefer mechanism-level diagnostics that aggregate over a fixed protein set:
|
| 1155 |
+
subspace vs residual decomposition, distribution-level statistics, paired
|
| 1156 |
+
checkpoint comparisons, and controlled ablations.
|
| 1157 |
+
- If a proposed analysis requires interpreting individual protein identities,
|
| 1158 |
+
treat it as low priority and do not use it to decide the next method change.
|
| 1159 |
+
|
| 1160 |
+
## Code-inspection-before-guessing lesson (2026-07-13)
|
| 1161 |
+
|
| 1162 |
+
- If the answer is determined by repository code, generated configs, or wrapper
|
| 1163 |
+
scripts, inspect those files before advising the user. Do not answer with
|
| 1164 |
+
"probably", "likely", "should", or similar uncertainty when the code can give
|
| 1165 |
+
a concrete answer.
|
| 1166 |
+
- Before saying an inference job can resume, skip existing proteins, preserve
|
| 1167 |
+
partial outputs, or avoid overwriting, inspect the exact inference script and
|
| 1168 |
+
output-writing path. Do not infer skip/overwrite behavior from naming
|
| 1169 |
+
conventions or previous runs.
|
| 1170 |
+
- Before recommending checkpoint paths or checkpoint cadence, list the actual
|
| 1171 |
+
checkpoint files and read the saved run `config.yaml`. Log epochs are not
|
| 1172 |
+
checkpoint files, and `last.ckpt` only reflects the configured checkpoint
|
| 1173 |
+
trigger.
|
| 1174 |
+
- When a prior answer was based on an unchecked assumption, stop and correct the
|
| 1175 |
+
workflow by reading the relevant code/config first; do not ask the user to
|
| 1176 |
+
continue experiments based on that assumption.
|
| 1177 |
+
|
| 1178 |
+
## Do-not-close-experiments lesson (2026-07-13)
|
| 1179 |
+
|
| 1180 |
+
- Do not declare an experiment line finished, archived, or ready to stop unless
|
| 1181 |
+
the user explicitly says to conclude it. A negative or mixed result should be
|
| 1182 |
+
recorded as a stage observation, not as a terminal decision.
|
| 1183 |
+
- Phrases like "archive this route", "stop this line", or "this is the final
|
| 1184 |
+
conclusion" require explicit user approval. Until then, continue treating the
|
| 1185 |
+
result as evidence for the next design decision.
|
| 1186 |
+
- When reporting a failed or mixed checkpoint, separate the measured fact from
|
| 1187 |
+
the decision: state what changed in the metrics, then propose next options
|
| 1188 |
+
without closing the project direction on the user's behalf.
|
| 1189 |
+
|
| 1190 |
+
## Training launch lesson (2026-07-13)
|
| 1191 |
+
|
| 1192 |
+
- Do not start long training jobs with a trailing background `&` in commands
|
| 1193 |
+
given to the user unless the user explicitly asks for background execution.
|
| 1194 |
+
The shell job marker like `[1] 1350285` is not useful operational feedback and
|
| 1195 |
+
has repeatedly made process control harder.
|
| 1196 |
+
- Prefer foreground commands with `2>&1 | tee "$RUN_DIR/train_console.log"` so
|
| 1197 |
+
the user sees failures immediately while logs are still saved. Use `tmux`,
|
| 1198 |
+
`screen`, or an explicit scheduler only when the user requests detached runs.
|
| 1199 |
+
- If a previous command used background execution and must be stopped, give
|
| 1200 |
+
concrete `pkill`/`ps` checks before any new launch command.
|
| 1201 |
+
|
| 1202 |
+
## DDP/NCCL launch stability lesson (2026-07-14)
|
| 1203 |
+
|
| 1204 |
+
- On `gn11`, do not "simplify" or delete the known-good DDP/NCCL environment
|
| 1205 |
+
block when only testing model, loss, or batch-size changes. This mistake has
|
| 1206 |
+
repeatedly produced startup hangs where both H100s show about 660 MiB memory
|
| 1207 |
+
and 100% GPU utilization before real training begins.
|
| 1208 |
+
- The current stable dual-GPU launch template for `00_train_final_mog_ddp.sh`
|
| 1209 |
+
must keep:
|
| 1210 |
+
- `NCCL_DEBUG=WARN`
|
| 1211 |
+
- `NCCL_ASYNC_ERROR_HANDLING=1`
|
| 1212 |
+
- `NCCL_IB_DISABLE=1`
|
| 1213 |
+
- `NCCL_P2P_DISABLE=1`
|
| 1214 |
+
- `NCCL_SOCKET_IFNAME=enp1s0`
|
| 1215 |
+
- `GLOO_SOCKET_IFNAME=enp1s0`
|
| 1216 |
+
- `MASTER_ADDR=127.0.0.1`
|
| 1217 |
+
- `MASTER_PORT=$((20000 + RANDOM % 20000))`
|
| 1218 |
+
- `EXTRA_HYDRA_ARGS="experiment.trainer.strategy=ddp"`
|
| 1219 |
+
- For controlled experiments, change only the intended experimental variables
|
| 1220 |
+
such as `MAX_NUM_RES_SQUARED`, `MAX_BATCH_SIZE`, loss weights, epoch counts,
|
| 1221 |
+
or generator-cov settings. Do not change communication variables at the same
|
| 1222 |
+
time; otherwise a hang cannot be attributed to the model change.
|
| 1223 |
+
- If `nvidia-smi` shows tiny memory use with 100% GPU utilization, treat it as a
|
| 1224 |
+
DDP/NCCL launch hang first. Kill the training PIDs, restore the known-good
|
| 1225 |
+
DDP/NCCL block above, and only then retry.
|
| 1226 |
+
|
| 1227 |
+
## Generator-response downstream reckoning (2026-07-18)
|
| 1228 |
+
|
| 1229 |
+
This is the first session where the generator-response line was ever measured on
|
| 1230 |
+
DOWNSTREAM ensemble metrics (sampling + analysis_script), not just training-side
|
| 1231 |
+
proxies. Every conclusion below is grounded in a measured 5znjA/82-protein read.
|
| 1232 |
+
|
| 1233 |
+
### 0. What was fixed at the start, and what it exposed
|
| 1234 |
+
- The `teacher_trace` anchor was diagnosed as a dead reference: the teacher is a
|
| 1235 |
+
`deepcopy` of the model at the first step, when all condition adapters are still
|
| 1236 |
+
zero-init, so its condition response is identically 0. `clamp_min(1e-8)` pinned
|
| 1237 |
+
`teacher_trace` to a constant, and `trace_loss=log(trace_sample/1e-8)^2` was
|
| 1238 |
+
actively training the student response TO ZERO. Confirmed by arithmetic on the
|
| 1239 |
+
logged `trace_mean`/`ratio` (ratio proportional to student trace; teacher const).
|
| 1240 |
+
- Fix applied: anchor reference switched teacher -> MD trace (`md_trace`, reuses
|
| 1241 |
+
`trace_target` already computed for shape normalization). Teacher forwards
|
| 1242 |
+
skipped entirely. `latent.py` `project_displacement_lstsq` also got a relative
|
| 1243 |
+
(Levenberg-Marquardt) ridge because the absolute 1e-4 ridge was swallowed in
|
| 1244 |
+
float32 once unnormalized-mode gram scale grew large -> `torch.linalg.solve`
|
| 1245 |
+
crashed mid-epoch (singular). Both are correct fixes, but see section 3.
|
| 1246 |
+
|
| 1247 |
+
### 1. First downstream numbers (gen_cov + cross, md_trace anchor, UNFROZEN)
|
| 1248 |
+
5znjA + full 82. BBFlow (Ours) reference row RMSF-MAE/Pairwise-MAE/PCA-W2 =
|
| 1249 |
+
0.47 / 0.78 / 1.34. Measured `gen_cov_cross_ep{0,2,4}`:
|
| 1250 |
+
- RMSF MAE 6.04 / 6.97 / 5.19 (~10x worse)
|
| 1251 |
+
- Pairwise 7.34 / 8.83 / 6.40 (~8x worse)
|
| 1252 |
+
- PCA W2 3.12 / 1.70 / 1.58
|
| 1253 |
+
- RMSF r 0.06 / 0.59 / 0.70 (PATTERN is learned and improving)
|
| 1254 |
+
Scale-invariant metrics (r, PCA-W2) improve while absolute-A metrics are ~3x
|
| 1255 |
+
inflated -> "correct pattern, wrong magnitude" = over-dispersion, not garbage.
|
| 1256 |
+
5znjA pseudo-RMSF mean 4.72, uniform (median 4.71, min 3.28), NO rigid core.
|
| 1257 |
+
|
| 1258 |
+
### 2. Ruling out the pipeline and the config (both clean)
|
| 1259 |
+
- `analysis_script.py:31-37` the leaderboard rows (BBFlow 0.47 etc.) are HARDCODED
|
| 1260 |
+
paper constants, NOT recomputed. The table cannot validate the pipeline.
|
| 1261 |
+
- Kabsch-aligning the 100 samples: 4.72 -> 4.65. Superposition removes nothing ->
|
| 1262 |
+
the dispersion is genuine internal conformational spread, not a framing artifact.
|
| 1263 |
+
- `condition_scale` sweep on ep004: 1.0/0.5/0.25 -> 4.62/4.51/4.56. SCALE-INVARIANT
|
| 1264 |
+
-> the over-dispersion is in the BASE/backbone, not the condition. The condition
|
| 1265 |
+
is nearly inert at sampling; the backbone absorbed both the pattern (r up) and
|
| 1266 |
+
the diffuseness.
|
| 1267 |
+
- CONTROL: official `bbflow-0.1.ckpt` (latent OFF) through the SAME pipeline ->
|
| 1268 |
+
pseudo-RMSF 1.46 (matches MD median 1.48), 59% residues < 1.5 (proper rigid
|
| 1269 |
+
core). Pipeline + sampler are CORRECT. The problem is 100% our model.
|
| 1270 |
+
- Config-mismatch also ruled out: re-sampling ep004 with the checkpoint's exact
|
| 1271 |
+
latent config (`energy_from_q`, `sample_coefficients`, etc., which `inference.yaml`
|
| 1272 |
+
omits and would silently drop under `strict=False`) still gave 4.62.
|
| 1273 |
+
|
| 1274 |
+
### 3. Root cause (corrected twice; final version)
|
| 1275 |
+
- `freeze_foundation` was ALWAYS false (backbone always trainable). It is NOT the
|
| 1276 |
+
differentiator vs older "comparable-at-best" runs. (First wrong hypothesis.)
|
| 1277 |
+
- The real change this session was teacher->md_trace, which flipped the condition
|
| 1278 |
+
from SUPPRESSED (teacher anchor trained response->0 => condition inert => model
|
| 1279 |
+
~= base BBFlow => old runs looked "fine / slightly worse") to ALIVE for the
|
| 1280 |
+
first time. An alive condition whose amplitude is calibrated on the SINGLE-STEP
|
| 1281 |
+
`pred_trans` response (training `gen_trace_ratio ~= 1.0`) over-disperses ~3x once
|
| 1282 |
+
run through the real 20-step ODE sampler. official_loss rose 0.85 (no-cross) ->
|
| 1283 |
+
1.5 (cross) and stayed elevated: aux losses degraded the trainable base.
|
| 1284 |
+
- `condition_scale`-invariance is the tell: the damage is baked into the backbone,
|
| 1285 |
+
not delivered by the condition at sample time.
|
| 1286 |
+
|
| 1287 |
+
### 4. Frozen isolation run (freeze_foundation=true, trace_anchor=0, shape only)
|
| 1288 |
+
`_freeze_foundation_model` (bbflow_module.py:171) freezes all of `self.model`
|
| 1289 |
+
except 5 injection modules (z_node/z_edge/disp_node/disp_edge adapters + film_mlp);
|
| 1290 |
+
`_set_frozen_foundation_eval` re-applies eval() every epoch. Verified clean.
|
| 1291 |
+
- BASE PRESERVED: official_loss 0.88 -> 0.66 -> 0.44 (falling, not rising). Freeze
|
| 1292 |
+
protects marginals by construction. This half of the thesis WORKS.
|
| 1293 |
+
- CONDITION WENT INERT: gen_response_abs_mean 0.018 (vs 0.48), gen_trace_mean
|
| 1294 |
+
~1.9 (vs 1103), gen_trace_ratio 0.0016 (~0.2% of MD). cross_cov_far_corr flat
|
| 1295 |
+
~0.11. Reason: with trace_anchor=0 there is NOTHING driving condition amplitude,
|
| 1296 |
+
and the shape losses are SCALE-INVARIANT (indifferent to amplitude). Zero-init
|
| 1297 |
+
adapters + no amplitude driver => condition stays ~0, shaping a negligible signal.
|
| 1298 |
+
- Net: frozen+no-anchor -> ~= BBFlow (base preserved, no gain).
|
| 1299 |
+
|
| 1300 |
+
### 5. The design box, and the fundamental diagnosis
|
| 1301 |
+
- trace_anchor ON at single-step MD -> 20-step overshoot ~3x (unfrozen: 4.6).
|
| 1302 |
+
- trace_anchor OFF -> condition starves to inert (frozen: ~BBFlow).
|
| 1303 |
+
- A scaled anchor target (e.g. md/9) would be a FUDGE FACTOR for the single-step
|
| 1304 |
+
vs 20-step gap -> parameter tuning, not a cure.
|
| 1305 |
+
- ROOT CAUSE of all of it: the objective measures the SINGLE-STEP `pred_trans`
|
| 1306 |
+
response, never the actual 20-step sampled ensemble. Amplitude is therefore
|
| 1307 |
+
miscalibrated by construction and every proxy (trace ratio, shape losses) is
|
| 1308 |
+
measured on the wrong quantity (generator-blind).
|
| 1309 |
+
- Additional structural limit: a FROZEN base can mostly only ADD motion, not
|
| 1310 |
+
REDISTRIBUTE it; improving PCA W2 requires redistribution (less motion in wrong
|
| 1311 |
+
directions, more in MD directions). So even a perfectly amplitude-calibrated
|
| 1312 |
+
frozen run likely has a PCA-W2 ceiling. (FiLM gives partial redistribution.)
|
| 1313 |
+
- FUNDAMENTAL CURE (not yet built): compute the objective on a differentiable
|
| 1314 |
+
FEW-STEP rollout of the real sampler and match MD ensemble statistics on it.
|
| 1315 |
+
Then amplitude is correct by construction, the signal is generator-aware, no
|
| 1316 |
+
per-protein fudge factor, and it works frozen or unfrozen. This is a real
|
| 1317 |
+
implementation (differentiable 2-4 step rollout + ensemble covariance), not a knob.
|
| 1318 |
+
|
| 1319 |
+
### 6. Lessons
|
| 1320 |
+
- Training-side proxies on this line do NOT predict downstream and repeatedly
|
| 1321 |
+
misled (trace_ratio ~1 while the sampler was 3x over-dispersed). Always get a
|
| 1322 |
+
downstream read before concluding a generator-response run is good or bad.
|
| 1323 |
+
- The leaderboard table printed by `03_evaluate` is hardcoded reference values;
|
| 1324 |
+
never treat "BBFlow (Ours)" appearing next to your row as pipeline validation.
|
| 1325 |
+
- To sample a latent checkpoint, `experiments/inference.py` must be given the
|
| 1326 |
+
checkpoint's latent config explicitly (`+latent.energy_from_q`, `sample_coefficients`,
|
| 1327 |
+
`mixture_components`, ...). `inference.yaml` omits them; `strict=False` then
|
| 1328 |
+
silently loads a random q-head and produces garbage that looks like a model fail.
|
| 1329 |
+
- `00_train_final_mog_ddp.sh` hardcoded `latent.freeze_foundation=false`; it is now
|
| 1330 |
+
an env var (`FREEZE_FOUNDATION`). Verify freeze at runtime via the first
|
| 1331 |
+
`[grad-flow-check]` line: `bbflow_backbone ... params_with_grad` drops 534 -> ~20.
|
| 1332 |
+
|
| 1333 |
+
## Rollout-aware G-calibration: works, then diverges (2026-07-18, later)
|
| 1334 |
+
|
| 1335 |
+
Built rollout amplitude calibration: measure G = T_full / T_1step where T_full is the
|
| 1336 |
+
c-response trace on the REAL sampler (shared prior noise x0, full linspace(min_t,1,20)
|
| 1337 |
+
grid, no_grad, few proteins, once per interval), then anchor the single-step response to
|
| 1338 |
+
md_trace * (1/G_ema). Fixes the single-step vs 20-step miscalibration WITHOUT a fudge
|
| 1339 |
+
factor. (Codex's first cut measured T_full from the training-time trans_t over 2 coarse
|
| 1340 |
+
steps -> silently wrong G; corrected to prior-noise + full grid in `_rollout_final_pred_trans`.)
|
| 1341 |
+
|
| 1342 |
+
RESULT of frozen + G-cal + anchor 0.3 (bbflow_frozen_Gcal, run 20260718_172144):
|
| 1343 |
+
- The mechanism WORKS. G measured ~6.5 -> 10.5 (EMA), empirically confirming the 20-step
|
| 1344 |
+
sampler amplifies the single-step response ~6-10x (bigger than the ~3x guessed earlier;
|
| 1345 |
+
this is exactly why the old single-step anchor over-dispersed). Condition went ALIVE:
|
| 1346 |
+
gen_response_abs_mean 0.16 (vs 0.018 inert / 0.48 over), gen_trace_ratio_to_anchor
|
| 1347 |
+
0.63 -> 0.93 -> 0.99 converging to the calibrated target. First stable-ish "alive,
|
| 1348 |
+
calibrated" condition ever observed.
|
| 1349 |
+
- But it DIVERGED. Latent mode geometry collapsed monotonically from epoch 0:
|
| 1350 |
+
mode_max_cosine_abs 0.928 -> 0.987 -> 0.989, mode_gram_min_eig 1.14 -> 0.031,
|
| 1351 |
+
mode_gram_condition 2.8e5 -> 3.1e5 -> 5.4e13; official_loss 4.3 -> 5.7 (high, and the
|
| 1352 |
+
frozen backbone cannot be the cause). At epoch 3 step 220 (a NON-measure step, so the
|
| 1353 |
+
rollout is NOT in the crash path) the prior mixture head produced NaN logits ->
|
| 1354 |
+
Categorical crash in sample_coefficients_from_q. There is NO gradient clipping anywhere
|
| 1355 |
+
in the codebase.
|
| 1356 |
+
- Reading: the calibrated anchor driving the condition to MD amplitude, on a frozen base
|
| 1357 |
+
whose amplitude is already correct, fights the mode structure (mode_orth loss at 1.0 did
|
| 1358 |
+
not hold it) and collapses the latent to NaN. This is the "additive tension" made concrete
|
| 1359 |
+
as a divergence. Frozen+additive is now boxed both ways: no anchor -> inert; anchor -> diverge.
|
| 1360 |
+
|
| 1361 |
+
OPEN: is the divergence a maskable instability or a genuine defect? Decided NOT to paper it
|
| 1362 |
+
with gradient clipping (that hides the divergence signal instead of finding the root cause).
|
| 1363 |
+
Next when resumed: find the actual NaN source in the latent forward (mixture head / mode
|
| 1364 |
+
normalization / the near-degenerate-gram path) rather than clipping; and evaluate the
|
| 1365 |
+
pre-NaN checkpoint (epoch 1, condition alive, geometry not yet fully collapsed) downstream
|
| 1366 |
+
to see whether an alive-but-pre-collapse condition moved PCA W2 at all -- the only signal
|
| 1367 |
+
this run line can still yield.
|
bbflow_base/code_exports/a30_redesign_source_20260719/docs/protein_project_conversation_record_2026-07-13.txt
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Protein Project Conversation Record
|
| 2 |
+
Date: 2026-07-13
|
| 3 |
+
|
| 4 |
+
Raw local Codex storage:
|
| 5 |
+
C:\Users\wykstc\.codex\sessions\2026\...
|
| 6 |
+
C:\Users\wykstc\.codex\archived_sessions\...
|
| 7 |
+
|
| 8 |
+
Project context:
|
| 9 |
+
- Workspace: D:\pycharm\pythonProject\protein
|
| 10 |
+
- Main repo discussed: bbflow_base
|
| 11 |
+
- Goal: improve BBFlow-like protein generation and evaluation, especially checkpoint handling, inference behavior, and post-training diagnosis.
|
| 12 |
+
|
| 13 |
+
Key conversation record:
|
| 14 |
+
|
| 15 |
+
1. Training resume and checkpoint behavior
|
| 16 |
+
- We traced why a resumed run only had epoch:004.ckpt and last.ckpt, both at epoch=4/global_step=17995.
|
| 17 |
+
- The server run used a config with every_n_epochs: 5, so checkpoints were only written every five epochs.
|
| 18 |
+
- We added a project lesson that code/config must be inspected before claiming resume/skip/checkpoint behavior.
|
| 19 |
+
- We updated the local training launcher bbflow_base/base_stages/00_train_base_ddp.sh to expose checkpoint cadence explicitly through:
|
| 20 |
+
CHECKPOINT_EVERY_N_EPOCHS
|
| 21 |
+
CHECKPOINT_SAVE_LAST
|
| 22 |
+
CHECKPOINT_SAVE_TOP_K
|
| 23 |
+
- Default behavior in that script is now every epoch save, save_last=true, save_top_k=-1.
|
| 24 |
+
|
| 25 |
+
2. Inference and resume lessons
|
| 26 |
+
- We confirmed that the inference pipeline can skip proteins that already have sampled_conformations.pdb, by checking the code path in bbflow_module.py.
|
| 27 |
+
- We added a lesson to the project trace: do not assume inference will skip or resume safely unless the code path is inspected.
|
| 28 |
+
- 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.
|
| 29 |
+
- We recorded that the raw inference logs and outputs live under the shared reproduction tree, not in the repo itself.
|
| 30 |
+
|
| 31 |
+
3. Generator-response training direction
|
| 32 |
+
- We introduced and implemented a generator-response covariance loss path in bbflow_module.py.
|
| 33 |
+
- 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.
|
| 34 |
+
- The motivation was to make the covariance supervision pass through the generator instead of only living in the prior/q statistics.
|
| 35 |
+
- Internal metric trends during the run were promising:
|
| 36 |
+
- gen_response_abs_mean increased steadily.
|
| 37 |
+
- gen_rmsf_loss and gen_cov_loss decreased.
|
| 38 |
+
- cross_cov_far_corr improved.
|
| 39 |
+
- The run was interrupted by host fan warnings and SIGTERM.
|
| 40 |
+
|
| 41 |
+
4. Inference run interruption and file protection
|
| 42 |
+
- We stopped an inference run when the host fan health alarms triggered.
|
| 43 |
+
- The run was started with:
|
| 44 |
+
INFERENCE_NAME=atlas_test_250_genresp_v1_epoch004_5ep_real
|
| 45 |
+
CKPT_PATH=.../epoch:004.ckpt
|
| 46 |
+
- We confirmed the inference code skips already-completed proteins based on the presence of sampled_conformations.pdb in the output directory.
|
| 47 |
+
- We recorded that partial outputs are not automatically guaranteed to be safely reused unless that file exists.
|
| 48 |
+
|
| 49 |
+
5. Diagnostic rigor lessons
|
| 50 |
+
- We documented multiple times that code/config must be checked directly before claiming:
|
| 51 |
+
- checkpoint cadence
|
| 52 |
+
- resume behavior
|
| 53 |
+
- inference skip behavior
|
| 54 |
+
- device placement
|
| 55 |
+
- reference-path selection
|
| 56 |
+
- We explicitly recorded that the project should not rely on "probably" or "likely" when the repository code can determine the answer.
|
| 57 |
+
- We also recorded that per-protein drilldowns are low priority unless explicitly needed.
|
| 58 |
+
|
| 59 |
+
6. Where the raw conversation is stored
|
| 60 |
+
- The Codex desktop app keeps its local session archive under:
|
| 61 |
+
C:\Users\wykstc\.codex\sessions\YYYY\MM\DD\rollout-*.jsonl
|
| 62 |
+
- Older archived sessions may also appear under:
|
| 63 |
+
C:\Users\wykstc\.codex\archived_sessions\rollout-*.jsonl
|
| 64 |
+
- The project repo itself does not store the raw full transcript automatically unless we write a copy into docs/.
|
| 65 |
+
|
| 66 |
+
7. Working conclusion at the end of this thread
|
| 67 |
+
- The current best recoverable checkpoint from the interrupted run is epoch:004.ckpt.
|
| 68 |
+
- 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.
|
| 69 |
+
- 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.
|
| 70 |
+
|
| 71 |
+
End of record.
|
bbflow_base/code_exports/a30_redesign_source_20260719/experiments/inference.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 Max Planck Institute for Polymer Research
|
| 2 |
+
# Copyright (c) 2024 HITS gGmbH
|
| 3 |
+
# Copyright (c) Microsoft Corporation.
|
| 4 |
+
# Licensed under the MIT license.
|
| 5 |
+
|
| 6 |
+
"""DDP inference script."""
|
| 7 |
+
import os
|
| 8 |
+
import time
|
| 9 |
+
import numpy as np
|
| 10 |
+
import hydra
|
| 11 |
+
import torch
|
| 12 |
+
from torch.utils.data import DataLoader
|
| 13 |
+
from typing import Optional
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import pandas as pd
|
| 16 |
+
from pytorch_lightning import Trainer
|
| 17 |
+
from omegaconf import DictConfig, OmegaConf
|
| 18 |
+
import logging
|
| 19 |
+
|
| 20 |
+
from gafl import experiment_utils as eu
|
| 21 |
+
|
| 22 |
+
from bbflow.models.bbflow_module import BBFlowModule
|
| 23 |
+
from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb
|
| 24 |
+
|
| 25 |
+
log = eu.get_pylogger(__name__)
|
| 26 |
+
logging.getLogger('MDAnalysis.analysis.base').setLevel(logging.WARNING)
|
| 27 |
+
logging.getLogger('MDAnalysis.analysis.align').setLevel(logging.WARNING)
|
| 28 |
+
torch.set_float32_matmul_precision('high')
|
| 29 |
+
|
| 30 |
+
class Sampler:
|
| 31 |
+
|
| 32 |
+
def __init__(self, cfg: DictConfig):
|
| 33 |
+
"""Initialize sampler.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
cfg: inference config.
|
| 37 |
+
"""
|
| 38 |
+
ckpt_path = cfg.inference.ckpt_path
|
| 39 |
+
assert os.path.isfile(ckpt_path), f'Checkpoint path {ckpt_path} does not exist!'
|
| 40 |
+
ckpt_dir = os.path.dirname(ckpt_path)
|
| 41 |
+
cfg_path = os.path.join(ckpt_dir, 'config.yaml')
|
| 42 |
+
assert os.path.isfile(cfg_path), f'Config file {cfg_path} does not exist!'
|
| 43 |
+
ckpt_cfg = OmegaConf.load(os.path.join(ckpt_dir, 'config.yaml'))
|
| 44 |
+
|
| 45 |
+
# Set-up config.
|
| 46 |
+
OmegaConf.set_struct(cfg, False)
|
| 47 |
+
OmegaConf.set_struct(ckpt_cfg, False)
|
| 48 |
+
cfg = OmegaConf.merge(cfg, ckpt_cfg)
|
| 49 |
+
cfg.experiment.checkpointer.dirpath = './'
|
| 50 |
+
cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior
|
| 51 |
+
# both only necessary if prior != pure_noise
|
| 52 |
+
cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional
|
| 53 |
+
cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot
|
| 54 |
+
cfg.model.embed = ckpt_cfg.model.embed
|
| 55 |
+
|
| 56 |
+
self._cfg = cfg
|
| 57 |
+
self._ckpt_cfg = ckpt_cfg
|
| 58 |
+
self._infer_cfg = cfg.inference
|
| 59 |
+
self._samples_cfg = self._infer_cfg.samples
|
| 60 |
+
self._rng = np.random.default_rng(self._infer_cfg.seed)
|
| 61 |
+
|
| 62 |
+
# Set-up directories to write results to
|
| 63 |
+
if self._infer_cfg.use_ckpt_name_in_outpath:
|
| 64 |
+
self._ckpt_name = '/'.join(ckpt_path.replace('.ckpt', '').split('/')[-3:])
|
| 65 |
+
self._output_dir = os.path.join(
|
| 66 |
+
self._infer_cfg.output_dir,
|
| 67 |
+
self._ckpt_name,
|
| 68 |
+
self._infer_cfg.name,
|
| 69 |
+
)
|
| 70 |
+
else:
|
| 71 |
+
self._output_dir = os.path.join(
|
| 72 |
+
self._infer_cfg.output_dir,
|
| 73 |
+
self._infer_cfg.name,
|
| 74 |
+
)
|
| 75 |
+
os.makedirs(self._output_dir, exist_ok=True)
|
| 76 |
+
config_path = os.path.join(self._output_dir, 'config.yaml')
|
| 77 |
+
with open(config_path, 'w') as f:
|
| 78 |
+
OmegaConf.save(config=self._cfg, f=f)
|
| 79 |
+
log.info(f'Saving inference config to {config_path}')
|
| 80 |
+
|
| 81 |
+
self._flow_module = self.load_module(ckpt_path)
|
| 82 |
+
self._flow_module.eval()
|
| 83 |
+
self._flow_module._infer_cfg = self._infer_cfg
|
| 84 |
+
self._flow_module._samples_cfg = self._samples_cfg
|
| 85 |
+
self._flow_module._output_dir = self._output_dir
|
| 86 |
+
|
| 87 |
+
def load_module(self, ckpt_path):
|
| 88 |
+
# Keep the module on CPU until Lightning assigns one copy to each DDP rank.
|
| 89 |
+
ckpt = torch.load(ckpt_path, map_location='cpu')
|
| 90 |
+
module = BBFlowModule(self._cfg)
|
| 91 |
+
current_state = module.state_dict()
|
| 92 |
+
compatible_state = {
|
| 93 |
+
k: v for k, v in ckpt["state_dict"].items()
|
| 94 |
+
if k in current_state and current_state[k].shape == v.shape
|
| 95 |
+
}
|
| 96 |
+
module.load_state_dict(compatible_state, strict=False)
|
| 97 |
+
return module
|
| 98 |
+
|
| 99 |
+
def run_sampling(self):
|
| 100 |
+
visible_device_count = torch.cuda.device_count()
|
| 101 |
+
requested_devices = int(self._infer_cfg.num_gpus)
|
| 102 |
+
if visible_device_count < requested_devices:
|
| 103 |
+
raise RuntimeError(
|
| 104 |
+
f"Requested {requested_devices} CUDA device(s), but PyTorch sees "
|
| 105 |
+
f"{visible_device_count}. Check CUDA_VISIBLE_DEVICES."
|
| 106 |
+
)
|
| 107 |
+
devices = list(range(requested_devices))
|
| 108 |
+
device_names = [torch.cuda.get_device_name(i) for i in devices]
|
| 109 |
+
log.info(f"Using devices: {devices} ({device_names})")
|
| 110 |
+
# eval_dataset = eu.LengthDataset(self._samples_cfg)
|
| 111 |
+
|
| 112 |
+
if self._infer_cfg.csv_path is not None:
|
| 113 |
+
csv = pd.read_csv(self._infer_cfg.csv_path)
|
| 114 |
+
# randomly subsample proteins if num_proteins is set
|
| 115 |
+
if self._infer_cfg.num_proteins is not None:
|
| 116 |
+
csv = csv.sample(
|
| 117 |
+
n=self._infer_cfg.num_proteins,
|
| 118 |
+
random_state=self._infer_cfg.seed,
|
| 119 |
+
).reset_index(drop=True)
|
| 120 |
+
dataset = PDBDatasetBBFlowFromPdb(
|
| 121 |
+
csv,
|
| 122 |
+
sort=self._infer_cfg.sort,
|
| 123 |
+
min_length=0 if self._infer_cfg.min_length is None else self._infer_cfg.min_length,
|
| 124 |
+
max_length=np.inf if self._infer_cfg.max_length is None else self._infer_cfg.max_length,
|
| 125 |
+
)
|
| 126 |
+
else:
|
| 127 |
+
raise ValueError('No csv path provided')
|
| 128 |
+
|
| 129 |
+
log.info(f"Sampling {self._infer_cfg.samples.samples_per_protein} conformations per Protein for {len(dataset)} proteins.")
|
| 130 |
+
|
| 131 |
+
dataloader = DataLoader(
|
| 132 |
+
dataset,
|
| 133 |
+
batch_size=1,
|
| 134 |
+
shuffle=False,
|
| 135 |
+
num_workers=int(getattr(self._infer_cfg, "num_workers", 2)),
|
| 136 |
+
prefetch_factor=None if int(getattr(self._infer_cfg, "num_workers", 2)) == 0 else 2,
|
| 137 |
+
persistent_workers=int(getattr(self._infer_cfg, "num_workers", 2)) > 0,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
trainer = Trainer(
|
| 141 |
+
accelerator="gpu",
|
| 142 |
+
strategy="ddp" if requested_devices > 1 else "auto",
|
| 143 |
+
devices=devices,
|
| 144 |
+
precision=str(getattr(
|
| 145 |
+
self._infer_cfg,
|
| 146 |
+
"precision",
|
| 147 |
+
self._cfg.experiment.trainer.precision,
|
| 148 |
+
)),
|
| 149 |
+
enable_progress_bar=self._infer_cfg.use_tqdm,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
hashtagline = '#' * 80
|
| 153 |
+
log.info(f'\n\n{hashtagline}\n'
|
| 154 |
+
f'Starting inference run: {self._infer_cfg.name}\nSaving results to {self._output_dir}\n{hashtagline}\n')
|
| 155 |
+
|
| 156 |
+
trainer.predict(self._flow_module, dataloaders=dataloader)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@hydra.main(version_base=None, config_path="../configs", config_name="inference")
|
| 160 |
+
def run(cfg: DictConfig) -> None:
|
| 161 |
+
|
| 162 |
+
# Read model checkpoint.
|
| 163 |
+
log.info(f'Starting inference with {cfg.inference.num_gpus} GPUs')
|
| 164 |
+
start_time = time.time()
|
| 165 |
+
sampler = Sampler(cfg)
|
| 166 |
+
sampler.run_sampling()
|
| 167 |
+
elapsed_time = time.time() - start_time
|
| 168 |
+
log.info(f'Finished in {elapsed_time:.2f}s')
|
| 169 |
+
|
| 170 |
+
if __name__ == '__main__':
|
| 171 |
+
run()
|
bbflow_base/code_exports/a30_redesign_source_20260719/experiments/train.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 Max Planck Institute for Polymer Research
|
| 2 |
+
# Copyright (c) 2024 HITS gGmbH
|
| 3 |
+
# Copyright (c) Microsoft Corporation.
|
| 4 |
+
# Licensed under the MIT license.
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
# import torch.multiprocessing as mp
|
| 10 |
+
# mp.set_start_method('spawn', force=True)
|
| 11 |
+
|
| 12 |
+
import hydra
|
| 13 |
+
from omegaconf import DictConfig, OmegaConf
|
| 14 |
+
|
| 15 |
+
# Pytorch lightning imports
|
| 16 |
+
import pytorch_lightning as pl
|
| 17 |
+
from pytorch_lightning import LightningDataModule, LightningModule, Trainer
|
| 18 |
+
from pytorch_lightning.loggers.wandb import WandbLogger
|
| 19 |
+
from pytorch_lightning.trainer import Trainer
|
| 20 |
+
from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor
|
| 21 |
+
import wandb
|
| 22 |
+
import logging
|
| 23 |
+
|
| 24 |
+
from gafl import experiment_utils as eu
|
| 25 |
+
|
| 26 |
+
from bbflow.models.bbflow_module import BBFlowModule
|
| 27 |
+
from bbflow.data.pdb_dataloader_bbflow import PdbDataModuleBBFlow
|
| 28 |
+
|
| 29 |
+
from packaging import version
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
log = eu.get_pylogger(__name__)
|
| 33 |
+
torch.set_float32_matmul_precision('high')
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Experiment:
|
| 37 |
+
|
| 38 |
+
def __init__(self, *, cfg: DictConfig):
|
| 39 |
+
os.makedirs(cfg.experiment.checkpointer.dirpath, exist_ok=True)
|
| 40 |
+
self._cfg = cfg
|
| 41 |
+
self._data_cfg = cfg.data
|
| 42 |
+
self._exp_cfg = cfg.experiment
|
| 43 |
+
|
| 44 |
+
self.create_data_module()
|
| 45 |
+
self.create_module()
|
| 46 |
+
|
| 47 |
+
def create_module(self):
|
| 48 |
+
self._model: LightningModule = BBFlowModule(self._cfg)
|
| 49 |
+
|
| 50 |
+
def create_data_module(self):
|
| 51 |
+
latent_cfg = self._cfg.latent if hasattr(self._cfg, "latent") else None
|
| 52 |
+
self._datamodule: LightningDataModule = PdbDataModuleBBFlow(
|
| 53 |
+
self._data_cfg,
|
| 54 |
+
training_cfg=self._exp_cfg.training,
|
| 55 |
+
latent_cfg=latent_cfg,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
def train(self):
|
| 59 |
+
callbacks = []
|
| 60 |
+
if self._exp_cfg.debug:
|
| 61 |
+
log.info("Debug mode.")
|
| 62 |
+
logger = None
|
| 63 |
+
self._exp_cfg.num_devices = 1
|
| 64 |
+
self._data_cfg.loader.num_workers = 0
|
| 65 |
+
else:
|
| 66 |
+
if self._exp_cfg.use_wandb:
|
| 67 |
+
logger = WandbLogger(
|
| 68 |
+
**self._exp_cfg.wandb,
|
| 69 |
+
)
|
| 70 |
+
else:
|
| 71 |
+
logger = False
|
| 72 |
+
|
| 73 |
+
# Checkpoint directory.
|
| 74 |
+
ckpt_dir = self._exp_cfg.checkpointer.dirpath
|
| 75 |
+
os.makedirs(ckpt_dir, exist_ok=True)
|
| 76 |
+
log.info(f"Checkpoints saved to {ckpt_dir}")
|
| 77 |
+
|
| 78 |
+
# Model checkpoints
|
| 79 |
+
callbacks.append(ModelCheckpoint(**self._exp_cfg.checkpointer))
|
| 80 |
+
callbacks.append(eu.ValidationCallback(self._exp_cfg.first_val_epoch))
|
| 81 |
+
|
| 82 |
+
scheduler_cfg = self._exp_cfg.get("scheduler")
|
| 83 |
+
if scheduler_cfg is not None and scheduler_cfg.get("enabled", False) and logger is not None:
|
| 84 |
+
lr_monitor = LearningRateMonitor(logging_interval='epoch')
|
| 85 |
+
callbacks.append(lr_monitor)
|
| 86 |
+
|
| 87 |
+
# Save config
|
| 88 |
+
cfg_path = os.path.join(ckpt_dir, 'config.yaml')
|
| 89 |
+
with open(cfg_path, 'w') as f:
|
| 90 |
+
OmegaConf.save(config=self._cfg, f=f.name)
|
| 91 |
+
cfg_dict = OmegaConf.to_container(self._cfg, resolve=True)
|
| 92 |
+
flat_cfg = dict(eu.flatten_dict(cfg_dict))
|
| 93 |
+
if self._exp_cfg.use_wandb and isinstance(logger.experiment.config, wandb.sdk.wandb_config.Config):
|
| 94 |
+
logger.experiment.config.update(flat_cfg)
|
| 95 |
+
|
| 96 |
+
visible_device_count = torch.cuda.device_count()
|
| 97 |
+
requested_devices = int(self._exp_cfg.num_devices)
|
| 98 |
+
if visible_device_count < requested_devices:
|
| 99 |
+
raise RuntimeError(
|
| 100 |
+
f"Requested {requested_devices} CUDA device(s), but PyTorch sees "
|
| 101 |
+
f"{visible_device_count}. Check CUDA_VISIBLE_DEVICES."
|
| 102 |
+
)
|
| 103 |
+
devices = list(range(requested_devices))
|
| 104 |
+
device_names = [torch.cuda.get_device_name(i) for i in devices]
|
| 105 |
+
log.info(f"Using devices: {devices} ({device_names})")
|
| 106 |
+
|
| 107 |
+
trainer_kwargs = dict(
|
| 108 |
+
**self._exp_cfg.trainer,
|
| 109 |
+
callbacks=callbacks,
|
| 110 |
+
logger=logger,
|
| 111 |
+
enable_progress_bar=self._exp_cfg.use_tqdm,
|
| 112 |
+
enable_model_summary=True,
|
| 113 |
+
devices=devices,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# the `replace_sampler_ddp` flag is deprecated in newer versions of PL
|
| 117 |
+
PL_VERSION = version.parse(pl.__version__)
|
| 118 |
+
if PL_VERSION >= version.parse("2.3.0"):
|
| 119 |
+
trainer_kwargs["use_distributed_sampler"] = False
|
| 120 |
+
else:
|
| 121 |
+
trainer_kwargs["replace_sampler_ddp"] = False
|
| 122 |
+
|
| 123 |
+
trainer = Trainer(
|
| 124 |
+
**trainer_kwargs
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
fit_ckpt_path = self._exp_cfg.warm_start
|
| 128 |
+
if fit_ckpt_path is not None:
|
| 129 |
+
ckpt = torch.load(fit_ckpt_path, map_location="cpu", weights_only=True)
|
| 130 |
+
if "pytorch-lightning_version" not in ckpt:
|
| 131 |
+
model_ckpt = ckpt["state_dict"]
|
| 132 |
+
model_ckpt = {k.replace("model.", ""): v for k, v in model_ckpt.items()}
|
| 133 |
+
current_state = self._model.model.state_dict()
|
| 134 |
+
compatible_state = {
|
| 135 |
+
k: v for k, v in model_ckpt.items()
|
| 136 |
+
if k in current_state and current_state[k].shape == v.shape
|
| 137 |
+
}
|
| 138 |
+
missing, unexpected = self._model.model.load_state_dict(compatible_state, strict=False)
|
| 139 |
+
log.info(
|
| 140 |
+
"Loaded non-Lightning warm start into model only: "
|
| 141 |
+
f"{len(compatible_state)} tensors, missing={len(missing)}, unexpected={len(unexpected)}"
|
| 142 |
+
)
|
| 143 |
+
fit_ckpt_path = None
|
| 144 |
+
|
| 145 |
+
trainer.fit(
|
| 146 |
+
model=self._model,
|
| 147 |
+
datamodule=self._datamodule,
|
| 148 |
+
ckpt_path=fit_ckpt_path
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
@hydra.main(version_base=None, config_path="../configs", config_name="train.yaml")
|
| 152 |
+
def main(cfg: DictConfig):
|
| 153 |
+
|
| 154 |
+
if cfg.experiment.warm_start is not None and cfg.experiment.warm_start_cfg_override:
|
| 155 |
+
# Loads warm start config.
|
| 156 |
+
warm_start_cfg_path = os.path.join(
|
| 157 |
+
os.path.dirname(cfg.experiment.warm_start), 'config.yaml')
|
| 158 |
+
warm_start_cfg = OmegaConf.load(warm_start_cfg_path)
|
| 159 |
+
|
| 160 |
+
# Warm start config may not have latest fields in the base config.
|
| 161 |
+
# Add these fields to the warm start config.
|
| 162 |
+
OmegaConf.set_struct(cfg.model, False)
|
| 163 |
+
OmegaConf.set_struct(warm_start_cfg.model, False)
|
| 164 |
+
cfg.model = OmegaConf.merge(cfg.model, warm_start_cfg.model)
|
| 165 |
+
OmegaConf.set_struct(cfg.model, True)
|
| 166 |
+
log.info(f'Loaded warm start config from {warm_start_cfg_path}')
|
| 167 |
+
|
| 168 |
+
# Ensure that all processes write to the same output directory.
|
| 169 |
+
if int(os.environ.get("LOCAL_RANK", 0)) == 0:
|
| 170 |
+
base_output_dir = cfg.experiment.checkpointer.dirpath
|
| 171 |
+
else:
|
| 172 |
+
base_output_dir = os.environ.get("HYDRA_OUTPUT_DIR", cfg.experiment.checkpointer.dirpath)
|
| 173 |
+
os.environ['HYDRA_OUTPUT_DIR'] = base_output_dir
|
| 174 |
+
cfg.experiment.checkpointer.dirpath = base_output_dir
|
| 175 |
+
|
| 176 |
+
exp = Experiment(cfg=cfg)
|
| 177 |
+
exp.train()
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
main()
|
bbflow_base/reproduction/00_prepare_data.sh
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
BBFLOW_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
| 5 |
+
cd "${BBFLOW_ROOT}"
|
| 6 |
+
|
| 7 |
+
ATLAS_RAW_ROOT="${ATLAS_RAW_ROOT:-/data/shared/wangyusong/atals}"
|
| 8 |
+
REPRO_ROOT="${REPRO_ROOT:-${BBFLOW_ROOT}/reproduction/outputs}"
|
| 9 |
+
ATLAS_VIEW_ROOT="${ATLAS_VIEW_ROOT:-${REPRO_ROOT}/data/ATLAS}"
|
| 10 |
+
METADATA_ROOT="${METADATA_ROOT:-${REPRO_ROOT}/metadata}"
|
| 11 |
+
|
| 12 |
+
python reproduction/prepare_atlas_view.py \
|
| 13 |
+
--raw-root "${ATLAS_RAW_ROOT}" \
|
| 14 |
+
--split-root "${BBFLOW_ROOT}/dataset_csv/ATLAS_split" \
|
| 15 |
+
--view-root "${ATLAS_VIEW_ROOT}" \
|
| 16 |
+
--metadata-root "${METADATA_ROOT}"
|
| 17 |
+
|
| 18 |
+
python - <<PY
|
| 19 |
+
import pandas as pd
|
| 20 |
+
from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow
|
| 21 |
+
|
| 22 |
+
csv_path = "${METADATA_ROOT}/train/ATLAS_train.csv"
|
| 23 |
+
dataset = PDBDatasetBBFlow(pd.read_csv(csv_path).iloc[:1].copy())
|
| 24 |
+
item = dataset[(0, 0, 0)]
|
| 25 |
+
print("[preflight] first training example:", item["pdb_name"])
|
| 26 |
+
print("[preflight] residues:", int(item["trans_1"].shape[0]))
|
| 27 |
+
print("[preflight] BBFlow data loading passed")
|
| 28 |
+
PY
|
bbflow_base/reproduction/00_reproduce_official_pretrained.sh
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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-}"
|
| 7 |
+
|
| 8 |
+
OFFICIAL_ROOT="${OFFICIAL_ROOT:-${BBFLOW_ROOT}/reproduction/official_pretrained}"
|
| 9 |
+
DATA_ROOT="${DATA_ROOT:-${OFFICIAL_ROOT}/datasets/ATLAS}"
|
| 10 |
+
CSV_ROOT="${CSV_ROOT:-${OFFICIAL_ROOT}/dataset_csv}"
|
| 11 |
+
INFERENCE_ROOT="${INFERENCE_ROOT:-${OFFICIAL_ROOT}/outputs/inference}"
|
| 12 |
+
METRICS_ROOT="${METRICS_ROOT:-${OFFICIAL_ROOT}/outputs/metrics/bbflow-0.1_atlas_test_250}"
|
| 13 |
+
GPU_IDS="${GPU_IDS:-0,1}"
|
| 14 |
+
NUM_GPUS="${NUM_GPUS:-2}"
|
| 15 |
+
SAMPLES_PER_PROTEIN="${SAMPLES_PER_PROTEIN:-250}"
|
| 16 |
+
SAMPLE_BATCH_SIZE="${SAMPLE_BATCH_SIZE:-10}"
|
| 17 |
+
NUM_WORKERS="${NUM_WORKERS:-8}"
|
| 18 |
+
DOWNLOAD_MAX_RETRIES="${DOWNLOAD_MAX_RETRIES:-10}"
|
| 19 |
+
DOWNLOAD_RETRY_DELAY="${DOWNLOAD_RETRY_DELAY:-15}"
|
| 20 |
+
STAGE="${STAGE:-all}"
|
| 21 |
+
EXPECTED_TRAIN_COUNT=1269
|
| 22 |
+
EXPECTED_VALIDATION_COUNT=39
|
| 23 |
+
EXPECTED_TEST_COUNT=82
|
| 24 |
+
INFERENCE_NAME="${INFERENCE_NAME:-atlas_test_250}"
|
| 25 |
+
|
| 26 |
+
TRAIN_CSV="${CSV_ROOT}/train/ATLAS_train.csv"
|
| 27 |
+
VALIDATION_CSV="${CSV_ROOT}/validation/ATLAS_validation.csv"
|
| 28 |
+
TEST_CSV="${CSV_ROOT}/test/ATLAS_test.csv"
|
| 29 |
+
CKPT_PATH="${BBFLOW_ROOT}/models/bbflow-0.1/bbflow-0.1.ckpt"
|
| 30 |
+
INFERENCE_DIR="${INFERENCE_ROOT}/models/bbflow-0.1/bbflow-0.1/${INFERENCE_NAME}"
|
| 31 |
+
SUMMARY_PATH="${METRICS_ROOT}/summary_metrics.csv"
|
| 32 |
+
|
| 33 |
+
mkdir -p "${OFFICIAL_ROOT}" "${CSV_ROOT}" "${INFERENCE_ROOT}" "${METRICS_ROOT}"
|
| 34 |
+
|
| 35 |
+
case "${STAGE}" in
|
| 36 |
+
all|data|model|sample|eval) ;;
|
| 37 |
+
*)
|
| 38 |
+
echo "[official] Invalid STAGE=${STAGE}; expected all, data, model, sample, or eval"
|
| 39 |
+
exit 2
|
| 40 |
+
;;
|
| 41 |
+
esac
|
| 42 |
+
|
| 43 |
+
run_stage() {
|
| 44 |
+
local wanted="$1"
|
| 45 |
+
[[ "${STAGE}" == "all" || "${STAGE}" == "${wanted}" ]]
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
check_official_data() {
|
| 49 |
+
DATA_ROOT="${DATA_ROOT}" \
|
| 50 |
+
TRAIN_CSV="${TRAIN_CSV}" \
|
| 51 |
+
VALIDATION_CSV="${VALIDATION_CSV}" \
|
| 52 |
+
TEST_CSV="${TEST_CSV}" \
|
| 53 |
+
EXPECTED_TRAIN_COUNT="${EXPECTED_TRAIN_COUNT}" \
|
| 54 |
+
EXPECTED_VALIDATION_COUNT="${EXPECTED_VALIDATION_COUNT}" \
|
| 55 |
+
EXPECTED_TEST_COUNT="${EXPECTED_TEST_COUNT}" \
|
| 56 |
+
python - <<'PY'
|
| 57 |
+
import os
|
| 58 |
+
from pathlib import Path
|
| 59 |
+
|
| 60 |
+
import pandas as pd
|
| 61 |
+
|
| 62 |
+
data_root = Path(os.environ["DATA_ROOT"])
|
| 63 |
+
specs = [
|
| 64 |
+
("train", Path(os.environ["TRAIN_CSV"]), int(os.environ["EXPECTED_TRAIN_COUNT"])),
|
| 65 |
+
(
|
| 66 |
+
"validation",
|
| 67 |
+
Path(os.environ["VALIDATION_CSV"]),
|
| 68 |
+
int(os.environ["EXPECTED_VALIDATION_COUNT"]),
|
| 69 |
+
),
|
| 70 |
+
("test", Path(os.environ["TEST_CSV"]), int(os.environ["EXPECTED_TEST_COUNT"])),
|
| 71 |
+
]
|
| 72 |
+
|
| 73 |
+
missing = []
|
| 74 |
+
for split, csv_path, expected in specs:
|
| 75 |
+
if not csv_path.is_file():
|
| 76 |
+
missing.append(str(csv_path))
|
| 77 |
+
continue
|
| 78 |
+
frame = pd.read_csv(csv_path)
|
| 79 |
+
if len(frame) != expected:
|
| 80 |
+
raise RuntimeError(
|
| 81 |
+
f"{split}: expected {expected} rows, found {len(frame)} in {csv_path}"
|
| 82 |
+
)
|
| 83 |
+
for name in frame["name"].astype(str):
|
| 84 |
+
entry = data_root / name
|
| 85 |
+
required = [
|
| 86 |
+
entry / f"{name}.pdb",
|
| 87 |
+
entry / f"{name}_R1.xtc",
|
| 88 |
+
entry / f"{name}_R2.xtc",
|
| 89 |
+
entry / f"{name}_R3.xtc",
|
| 90 |
+
]
|
| 91 |
+
missing.extend(str(path) for path in required if not path.is_file())
|
| 92 |
+
|
| 93 |
+
if missing:
|
| 94 |
+
print(f"[official:data] missing files: {len(missing)}")
|
| 95 |
+
for path in missing[:10]:
|
| 96 |
+
print(f" {path}")
|
| 97 |
+
raise SystemExit(1)
|
| 98 |
+
|
| 99 |
+
print("[official:data] verified train=1269 validation=39 test=82")
|
| 100 |
+
PY
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
check_official_samples() {
|
| 104 |
+
TEST_CSV="${TEST_CSV}" \
|
| 105 |
+
INFERENCE_DIR="${INFERENCE_DIR}" \
|
| 106 |
+
EXPECTED_TEST_COUNT="${EXPECTED_TEST_COUNT}" \
|
| 107 |
+
EXPECTED_SAMPLES="${SAMPLES_PER_PROTEIN}" \
|
| 108 |
+
python - <<'PY'
|
| 109 |
+
import os
|
| 110 |
+
from pathlib import Path
|
| 111 |
+
|
| 112 |
+
import pandas as pd
|
| 113 |
+
|
| 114 |
+
test_csv = Path(os.environ["TEST_CSV"])
|
| 115 |
+
inference_dir = Path(os.environ["INFERENCE_DIR"])
|
| 116 |
+
expected = int(os.environ["EXPECTED_TEST_COUNT"])
|
| 117 |
+
expected_samples = int(os.environ["EXPECTED_SAMPLES"])
|
| 118 |
+
|
| 119 |
+
if not test_csv.is_file():
|
| 120 |
+
raise SystemExit(1)
|
| 121 |
+
|
| 122 |
+
names = pd.read_csv(test_csv)["name"].astype(str).tolist()
|
| 123 |
+
if len(names) != expected:
|
| 124 |
+
raise RuntimeError(f"Expected {expected} test names, found {len(names)}")
|
| 125 |
+
|
| 126 |
+
missing = []
|
| 127 |
+
wrong_counts = []
|
| 128 |
+
for name in names:
|
| 129 |
+
path = inference_dir / name / "sampled_conformations.pdb"
|
| 130 |
+
if not path.is_file():
|
| 131 |
+
missing.append(name)
|
| 132 |
+
continue
|
| 133 |
+
with path.open(errors="replace") as handle:
|
| 134 |
+
model_count = sum(1 for line in handle if line.startswith("MODEL"))
|
| 135 |
+
if model_count != expected_samples:
|
| 136 |
+
wrong_counts.append((name, model_count))
|
| 137 |
+
|
| 138 |
+
if missing:
|
| 139 |
+
print(f"[official:sample] missing ensembles: {len(missing)}")
|
| 140 |
+
raise SystemExit(1)
|
| 141 |
+
if wrong_counts:
|
| 142 |
+
print(
|
| 143 |
+
f"[official:sample] ensembles with wrong MODEL count: "
|
| 144 |
+
f"{len(wrong_counts)}; expected {expected_samples}"
|
| 145 |
+
)
|
| 146 |
+
for name, count in wrong_counts[:10]:
|
| 147 |
+
print(f" {name}: {count}")
|
| 148 |
+
raise SystemExit(1)
|
| 149 |
+
|
| 150 |
+
print(
|
| 151 |
+
f"[official:sample] verified {expected} ensembles "
|
| 152 |
+
f"with {expected_samples} samples each"
|
| 153 |
+
)
|
| 154 |
+
PY
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
if run_stage data; then
|
| 158 |
+
echo "============================================================"
|
| 159 |
+
echo "[official:data] Using upstream scripts/download_atlas.py"
|
| 160 |
+
echo " DATA_ROOT=${DATA_ROOT}"
|
| 161 |
+
echo " CSV_ROOT=${CSV_ROOT}"
|
| 162 |
+
if check_official_data >/dev/null 2>&1; then
|
| 163 |
+
echo "[official:data] Existing official dataset is complete; skipping download"
|
| 164 |
+
else
|
| 165 |
+
python scripts/download_atlas.py \
|
| 166 |
+
--out_folder "${DATA_ROOT}" \
|
| 167 |
+
--train_csv "${BBFLOW_ROOT}/dataset_csv/ATLAS_split/ATLAS_train.csv" \
|
| 168 |
+
--validation_csv "${BBFLOW_ROOT}/dataset_csv/ATLAS_split/ATLAS_validation.csv" \
|
| 169 |
+
--test_csv "${BBFLOW_ROOT}/dataset_csv/ATLAS_split/ATLAS_test.csv" \
|
| 170 |
+
--out_csv_folder "${CSV_ROOT}" \
|
| 171 |
+
--max_retries "${DOWNLOAD_MAX_RETRIES}" \
|
| 172 |
+
--retry_delay "${DOWNLOAD_RETRY_DELAY}"
|
| 173 |
+
fi
|
| 174 |
+
check_official_data
|
| 175 |
+
fi
|
| 176 |
+
|
| 177 |
+
if run_stage model; then
|
| 178 |
+
echo "============================================================"
|
| 179 |
+
echo "[official:model] Downloading/checking upstream bbflow-0.1"
|
| 180 |
+
python - <<'PY'
|
| 181 |
+
from bbflow.deployment.utils import ckpt_path_from_tag
|
| 182 |
+
|
| 183 |
+
path = ckpt_path_from_tag("bbflow-0.1")
|
| 184 |
+
print(f"[official:model] checkpoint={path}")
|
| 185 |
+
print(f"[official:model] config={path.parent / 'config.yaml'}")
|
| 186 |
+
PY
|
| 187 |
+
[[ -f "${CKPT_PATH}" ]] || {
|
| 188 |
+
echo "[official:model] Missing checkpoint after download: ${CKPT_PATH}"
|
| 189 |
+
exit 1
|
| 190 |
+
}
|
| 191 |
+
[[ -f "${BBFLOW_ROOT}/models/bbflow-0.1/config.yaml" ]] || {
|
| 192 |
+
echo "[official:model] Missing official model config"
|
| 193 |
+
exit 1
|
| 194 |
+
}
|
| 195 |
+
fi
|
| 196 |
+
|
| 197 |
+
if run_stage sample; then
|
| 198 |
+
echo "============================================================"
|
| 199 |
+
echo "[official:sample] Generating ${SAMPLES_PER_PROTEIN} samples for 82 proteins"
|
| 200 |
+
echo " GPU_IDS=${GPU_IDS}"
|
| 201 |
+
echo " NUM_GPUS=${NUM_GPUS}"
|
| 202 |
+
check_official_data
|
| 203 |
+
[[ -f "${CKPT_PATH}" ]] || {
|
| 204 |
+
echo "[official:sample] Missing ${CKPT_PATH}; run STAGE=model first"
|
| 205 |
+
exit 1
|
| 206 |
+
}
|
| 207 |
+
echo "[official:sample] Removing previous inference output: ${INFERENCE_DIR}"
|
| 208 |
+
rm -rf -- "${INFERENCE_DIR}"
|
| 209 |
+
echo "[official:sample] Removing previous evaluation output: ${METRICS_ROOT}"
|
| 210 |
+
rm -rf -- "${METRICS_ROOT}"
|
| 211 |
+
env -u NVIDIA_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES="${GPU_IDS}" \
|
| 212 |
+
python experiments/inference.py \
|
| 213 |
+
"inference.ckpt_path=${CKPT_PATH}" \
|
| 214 |
+
"inference.csv_path=${TEST_CSV}" \
|
| 215 |
+
"inference.output_dir=${INFERENCE_ROOT}" \
|
| 216 |
+
"inference.name=${INFERENCE_NAME}" \
|
| 217 |
+
"inference.num_gpus=${NUM_GPUS}" \
|
| 218 |
+
"inference.samples.samples_per_protein=${SAMPLES_PER_PROTEIN}" \
|
| 219 |
+
"inference.samples.batch_size=${SAMPLE_BATCH_SIZE}" \
|
| 220 |
+
"inference.log_times=true"
|
| 221 |
+
check_official_samples
|
| 222 |
+
fi
|
| 223 |
+
|
| 224 |
+
if run_stage eval; then
|
| 225 |
+
echo "============================================================"
|
| 226 |
+
echo "[official:eval] Running unmodified BBFlow analysis"
|
| 227 |
+
check_official_data
|
| 228 |
+
check_official_samples
|
| 229 |
+
if [[ -f "${SUMMARY_PATH}" ]]; then
|
| 230 |
+
echo "[official:eval] Existing summary found; skipping evaluation"
|
| 231 |
+
else
|
| 232 |
+
ENSEMBLE_DIR="${INFERENCE_DIR}" \
|
| 233 |
+
ATLAS_VIEW_ROOT="${DATA_ROOT}" \
|
| 234 |
+
TEST_CSV="${TEST_CSV}" \
|
| 235 |
+
NUM_WORKERS="${NUM_WORKERS}" \
|
| 236 |
+
METRICS_DIR="${METRICS_ROOT}" \
|
| 237 |
+
bash reproduction/03_evaluate.sh
|
| 238 |
+
fi
|
| 239 |
+
[[ -f "${SUMMARY_PATH}" ]] || {
|
| 240 |
+
echo "[official:eval] Missing summary after evaluation: ${SUMMARY_PATH}"
|
| 241 |
+
exit 1
|
| 242 |
+
}
|
| 243 |
+
echo
|
| 244 |
+
echo "[official:eval] Final BBFlow metrics"
|
| 245 |
+
cat "${SUMMARY_PATH}"
|
| 246 |
+
fi
|
| 247 |
+
|
| 248 |
+
if [[ "${STAGE}" == "all" ]]; then
|
| 249 |
+
echo
|
| 250 |
+
echo "[official] Reproduction complete"
|
| 251 |
+
echo " checkpoint=${CKPT_PATH}"
|
| 252 |
+
echo " ensembles=${INFERENCE_DIR}"
|
| 253 |
+
echo " metrics=${SUMMARY_PATH}"
|
| 254 |
+
fi
|
bbflow_base/reproduction/01_download_official.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
BBFLOW_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
| 5 |
+
cd "${BBFLOW_ROOT}"
|
| 6 |
+
export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}"
|
| 7 |
+
|
| 8 |
+
python - <<'PY'
|
| 9 |
+
from bbflow.deployment.utils import ckpt_path_from_tag
|
| 10 |
+
|
| 11 |
+
path = ckpt_path_from_tag("bbflow-0.1")
|
| 12 |
+
print(f"[bbflow:official] checkpoint={path}")
|
| 13 |
+
print(f"[bbflow:official] config={path.parent / 'config.yaml'}")
|
| 14 |
+
PY
|
bbflow_base/reproduction/01_train.sh
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
BBFLOW_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
| 5 |
+
cd "${BBFLOW_ROOT}"
|
| 6 |
+
export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}"
|
| 7 |
+
|
| 8 |
+
REPRO_ROOT="${REPRO_ROOT:-${BBFLOW_ROOT}/reproduction/outputs}"
|
| 9 |
+
RUN_NAME="${RUN_NAME:-bbflow_official_atlas_2gpu}"
|
| 10 |
+
GPU_IDS="${GPU_IDS:-0,1}"
|
| 11 |
+
NUM_DEVICES="${NUM_DEVICES:-2}"
|
| 12 |
+
NUM_WORKERS="${NUM_WORKERS:-8}"
|
| 13 |
+
MAX_EPOCHS="${MAX_EPOCHS:-250}"
|
| 14 |
+
CHECKPOINT_EVERY_N_EPOCHS="${CHECKPOINT_EVERY_N_EPOCHS:-1}"
|
| 15 |
+
RESUME_CKPT="${RESUME_CKPT:-}"
|
| 16 |
+
|
| 17 |
+
TRAIN_CSV="${REPRO_ROOT}/metadata/train/ATLAS_train.csv"
|
| 18 |
+
VALID_CSV="${REPRO_ROOT}/metadata/validation/ATLAS_validation.csv"
|
| 19 |
+
TEST_CSV="${REPRO_ROOT}/metadata/test/ATLAS_test.csv"
|
| 20 |
+
ATLAS_VIEW_ROOT="${REPRO_ROOT}/data/ATLAS"
|
| 21 |
+
CHECKPOINT_DIR="${REPRO_ROOT}/checkpoints/${RUN_NAME}"
|
| 22 |
+
|
| 23 |
+
for path in "${TRAIN_CSV}" "${VALID_CSV}" "${TEST_CSV}"; do
|
| 24 |
+
[[ -f "${path}" ]] || {
|
| 25 |
+
echo "[bbflow:train] Missing prepared metadata: ${path}"
|
| 26 |
+
echo "Run reproduction/00_prepare_data.sh first."
|
| 27 |
+
exit 1
|
| 28 |
+
}
|
| 29 |
+
done
|
| 30 |
+
|
| 31 |
+
[[ -d "${ATLAS_VIEW_ROOT}" ]] || {
|
| 32 |
+
echo "[bbflow:train] Missing prepared ATLAS view: ${ATLAS_VIEW_ROOT}"
|
| 33 |
+
exit 1
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
mkdir -p "${CHECKPOINT_DIR}"
|
| 37 |
+
|
| 38 |
+
WARM_START_ARGS=()
|
| 39 |
+
if [[ -n "${RESUME_CKPT}" ]]; then
|
| 40 |
+
[[ -f "${RESUME_CKPT}" ]] || {
|
| 41 |
+
echo "[bbflow:train] Missing resume checkpoint: ${RESUME_CKPT}"
|
| 42 |
+
exit 1
|
| 43 |
+
}
|
| 44 |
+
WARM_START_ARGS=(
|
| 45 |
+
"experiment.warm_start=${RESUME_CKPT}"
|
| 46 |
+
"experiment.warm_start_cfg_override=false"
|
| 47 |
+
)
|
| 48 |
+
fi
|
| 49 |
+
|
| 50 |
+
echo "[bbflow:train] Upstream BBFlow ATLAS training"
|
| 51 |
+
echo " GPU_IDS=${GPU_IDS}"
|
| 52 |
+
echo " NUM_DEVICES=${NUM_DEVICES}"
|
| 53 |
+
echo " NUM_WORKERS=${NUM_WORKERS} per rank"
|
| 54 |
+
echo " MAX_EPOCHS=${MAX_EPOCHS}"
|
| 55 |
+
echo " sampler.max_num_res_squared=200000 (upstream default)"
|
| 56 |
+
echo " sampler.max_conformations=20 (upstream default)"
|
| 57 |
+
echo " validation=every epoch (upstream default)"
|
| 58 |
+
echo " checkpoints=${CHECKPOINT_DIR}"
|
| 59 |
+
|
| 60 |
+
env -u NVIDIA_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES="${GPU_IDS}" \
|
| 61 |
+
python experiments/train.py \
|
| 62 |
+
"data.dataset.train_csv_path=${TRAIN_CSV}" \
|
| 63 |
+
"data.dataset.valid_csv_paths=[${VALID_CSV}]" \
|
| 64 |
+
"data.dataset.valid_dataset_names=[ATLAS_validation]" \
|
| 65 |
+
"data.dataset.test_csv_path=${TEST_CSV}" \
|
| 66 |
+
"data.dataset.split_path=${CHECKPOINT_DIR}" \
|
| 67 |
+
"data.validation.valid_xtc_paths=[${ATLAS_VIEW_ROOT}]" \
|
| 68 |
+
"data.loader.num_workers=${NUM_WORKERS}" \
|
| 69 |
+
"experiment.wandb.name=${RUN_NAME}" \
|
| 70 |
+
"experiment.use_wandb=false" \
|
| 71 |
+
"experiment.num_devices=${NUM_DEVICES}" \
|
| 72 |
+
"experiment.first_val_epoch=0" \
|
| 73 |
+
"experiment.trainer.max_epochs=${MAX_EPOCHS}" \
|
| 74 |
+
"experiment.checkpointer.every_n_epochs=${CHECKPOINT_EVERY_N_EPOCHS}" \
|
| 75 |
+
"experiment.checkpointer.dirpath=${CHECKPOINT_DIR}" \
|
| 76 |
+
"${WARM_START_ARGS[@]}"
|
bbflow_base/reproduction/02_sample_test.sh
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
BBFLOW_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
| 5 |
+
cd "${BBFLOW_ROOT}"
|
| 6 |
+
export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}"
|
| 7 |
+
|
| 8 |
+
GPU_ID="${GPU_ID:-0}"
|
| 9 |
+
GPU_IDS="${GPU_IDS:-${GPU_ID}}"
|
| 10 |
+
NUM_GPUS="${NUM_GPUS:-1}"
|
| 11 |
+
REPRO_ROOT="${REPRO_ROOT:-${BBFLOW_ROOT}/reproduction/outputs}"
|
| 12 |
+
METADATA_ROOT="${METADATA_ROOT:-${REPRO_ROOT}/metadata}"
|
| 13 |
+
CKPT_PATH="${CKPT_PATH:-${REPRO_ROOT}/checkpoints/bbflow_official_atlas/last.ckpt}"
|
| 14 |
+
SAMPLES_PER_PROTEIN="${SAMPLES_PER_PROTEIN:-250}"
|
| 15 |
+
SAMPLE_BATCH_SIZE="${SAMPLE_BATCH_SIZE:-20}"
|
| 16 |
+
MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-2900000}"
|
| 17 |
+
INFERENCE_NAME="${INFERENCE_NAME:-atlas_test_250}"
|
| 18 |
+
CONDITION_MODE="${CONDITION_MODE:-real}"
|
| 19 |
+
CONDITION_SCALE="${CONDITION_SCALE:-1.0}"
|
| 20 |
+
POSTPROCESS_BFACTORS="${POSTPROCESS_BFACTORS:-true}"
|
| 21 |
+
INFERENCE_NUM_WORKERS="${INFERENCE_NUM_WORKERS:-2}"
|
| 22 |
+
INFERENCE_PRECISION="${INFERENCE_PRECISION:-32-true}"
|
| 23 |
+
INFERENCE_FINAL_ONLY="${INFERENCE_FINAL_ONLY:-true}"
|
| 24 |
+
INFERENCE_CACHE_STATIC="${INFERENCE_CACHE_STATIC:-true}"
|
| 25 |
+
INFERENCE_NUM_TIMESTEPS="${INFERENCE_NUM_TIMESTEPS:-20}"
|
| 26 |
+
|
| 27 |
+
export OMP_NUM_THREADS="${OMP_NUM_THREADS:-1}"
|
| 28 |
+
export MKL_NUM_THREADS="${MKL_NUM_THREADS:-1}"
|
| 29 |
+
export OPENBLAS_NUM_THREADS="${OPENBLAS_NUM_THREADS:-1}"
|
| 30 |
+
export NUMEXPR_NUM_THREADS="${NUMEXPR_NUM_THREADS:-1}"
|
| 31 |
+
|
| 32 |
+
[[ -f "${CKPT_PATH}" ]] || {
|
| 33 |
+
echo "[bbflow:sample] Checkpoint does not exist: ${CKPT_PATH}"
|
| 34 |
+
exit 1
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
env -u NVIDIA_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES="${GPU_IDS}" \
|
| 38 |
+
python experiments/inference.py \
|
| 39 |
+
"inference.ckpt_path=${CKPT_PATH}" \
|
| 40 |
+
"inference.csv_path=${METADATA_ROOT}/test/ATLAS_test.csv" \
|
| 41 |
+
"inference.output_dir=${REPRO_ROOT}/inference" \
|
| 42 |
+
"inference.name=${INFERENCE_NAME}" \
|
| 43 |
+
"inference.num_gpus=${NUM_GPUS}" \
|
| 44 |
+
"inference.samples.samples_per_protein=${SAMPLES_PER_PROTEIN}" \
|
| 45 |
+
"inference.samples.batch_size=${SAMPLE_BATCH_SIZE}" \
|
| 46 |
+
"inference.samples.num_res_squared=${MAX_NUM_RES_SQUARED}" \
|
| 47 |
+
"inference.condition_mode=${CONDITION_MODE}" \
|
| 48 |
+
"inference.condition_scale=${CONDITION_SCALE}" \
|
| 49 |
+
"inference.postprocess_bfactors=${POSTPROCESS_BFACTORS}" \
|
| 50 |
+
"inference.num_workers=${INFERENCE_NUM_WORKERS}" \
|
| 51 |
+
"inference.precision=${INFERENCE_PRECISION}" \
|
| 52 |
+
"inference.final_only=${INFERENCE_FINAL_ONLY}" \
|
| 53 |
+
"inference.cache_static_features=${INFERENCE_CACHE_STATIC}" \
|
| 54 |
+
"inference.interpolant.sampling.num_timesteps=${INFERENCE_NUM_TIMESTEPS}" \
|
| 55 |
+
"inference.log_times=true"
|
bbflow_base/reproduction/03_evaluate.sh
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
BBFLOW_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
| 5 |
+
cd "${BBFLOW_ROOT}"
|
| 6 |
+
export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}"
|
| 7 |
+
|
| 8 |
+
REPRO_ROOT="${REPRO_ROOT:-${BBFLOW_ROOT}/reproduction/outputs}"
|
| 9 |
+
ATLAS_VIEW_ROOT="${ATLAS_VIEW_ROOT:-${REPRO_ROOT}/data/ATLAS}"
|
| 10 |
+
ENSEMBLE_DIR="${ENSEMBLE_DIR:-}"
|
| 11 |
+
NUM_WORKERS="${NUM_WORKERS:-8}"
|
| 12 |
+
METRICS_DIR="${METRICS_DIR:-${REPRO_ROOT}/metrics}"
|
| 13 |
+
TEST_CSV="${TEST_CSV:-${REPRO_ROOT}/metadata/test/ATLAS_test.csv}"
|
| 14 |
+
METHOD_NAME="${METHOD_NAME:-BBFlow-base-prior-z}"
|
| 15 |
+
METHOD_TIME_SECONDS="${METHOD_TIME_SECONDS:-}"
|
| 16 |
+
|
| 17 |
+
[[ -n "${ENSEMBLE_DIR}" ]] || {
|
| 18 |
+
echo "[bbflow:eval] Set ENSEMBLE_DIR to the inference run containing protein folders."
|
| 19 |
+
exit 1
|
| 20 |
+
}
|
| 21 |
+
[[ -d "${ENSEMBLE_DIR}" ]] || {
|
| 22 |
+
echo "[bbflow:eval] Ensemble directory does not exist: ${ENSEMBLE_DIR}"
|
| 23 |
+
exit 1
|
| 24 |
+
}
|
| 25 |
+
[[ -f "${TEST_CSV}" ]] || {
|
| 26 |
+
echo "[bbflow:eval] Test metadata does not exist: ${TEST_CSV}"
|
| 27 |
+
exit 1
|
| 28 |
+
}
|
| 29 |
+
mkdir -p "${METRICS_DIR}"
|
| 30 |
+
|
| 31 |
+
mapfile -t TEST_NAMES < <(tail -n +2 "${TEST_CSV}" | cut -d, -f1 | tr -d '\r')
|
| 32 |
+
[[ "${#TEST_NAMES[@]}" -eq 82 ]] || {
|
| 33 |
+
echo "[bbflow:eval] Expected 82 test proteins, found ${#TEST_NAMES[@]} in ${TEST_CSV}"
|
| 34 |
+
exit 1
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
ANALYSIS_ARGS=(
|
| 38 |
+
scripts/analysis_script.py
|
| 39 |
+
--md_dirs "${ATLAS_VIEW_ROOT}"
|
| 40 |
+
--ensemble_dirs "${ENSEMBLE_DIR}"
|
| 41 |
+
--names "${TEST_NAMES[@]}"
|
| 42 |
+
--num_workers "${NUM_WORKERS}"
|
| 43 |
+
--metrics RMSD RMSF PCA-W2
|
| 44 |
+
--analysis_data_path "${METRICS_DIR}/analysis_data.pkl"
|
| 45 |
+
--analysis_metrics_path "${METRICS_DIR}/summary_metrics.csv"
|
| 46 |
+
--compact_metrics_path "${METRICS_DIR}/compact_metrics.csv"
|
| 47 |
+
--compact_method_name "${METHOD_NAME}"
|
| 48 |
+
--print_metrics
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
if [[ -n "${METHOD_TIME_SECONDS}" ]]; then
|
| 52 |
+
ANALYSIS_ARGS+=(--compact_time_seconds "${METHOD_TIME_SECONDS}")
|
| 53 |
+
fi
|
| 54 |
+
|
| 55 |
+
python "${ANALYSIS_ARGS[@]}"
|
| 56 |
+
|
| 57 |
+
echo "[bbflow:eval] Metrics: ${METRICS_DIR}/summary_metrics.csv"
|
| 58 |
+
echo "[bbflow:eval] Compact metrics: ${METRICS_DIR}/compact_metrics.csv"
|
bbflow_base/reproduction/10h_sweep_then_resume.sh
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# ==============================================================================
|
| 3 |
+
# 10h window plan:
|
| 4 |
+
# PHASE 1 (mandatory, high value): downstream sweep over epoch 0/2/4 of the
|
| 5 |
+
# crashed cross run. This is the FIRST real downstream read on the
|
| 6 |
+
# entire generator-response line. Runs on CURRENT code -- inference
|
| 7 |
+
# samples from q (sample_coefficients_from_q) and never touches the
|
| 8 |
+
# singular lstsq path, so no code change is needed for the sweep.
|
| 9 |
+
# PHASE 2 (optional, default OFF): resume-with-ridge-fix toward epoch 9 to
|
| 10 |
+
# produce a fully-trained, evaluable checkpoint for the NEXT window.
|
| 11 |
+
# Resume is a documented landmine in this repo -- do not run it
|
| 12 |
+
# unattended without reading the verification note at the bottom.
|
| 13 |
+
#
|
| 14 |
+
# Fresh restart is deliberately NOT offered: in 10h it only reaches ~epoch 5
|
| 15 |
+
# (where it crashed) = zero new information, and discards 4 trained epochs.
|
| 16 |
+
# ==============================================================================
|
| 17 |
+
set -euo pipefail
|
| 18 |
+
|
| 19 |
+
# ------------------------------------------------------------------ CONFIRM ME
|
| 20 |
+
# The 4 paths below are the only things that can silently break this run.
|
| 21 |
+
BBFLOW_ROOT="${BBFLOW_ROOT:-$HOME/LD-FPG-main/bbflow_base}"
|
| 22 |
+
REPRO_ROOT="${REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}"
|
| 23 |
+
CRASHED_RUN="${CRASHED_RUN:-${REPRO_ROOT}/outputs/checkpoints/bbflow_base_gen_cov_v2_mdtrace_cross_k8_10ep_3gpu_120k_bs10_20260717_125700}"
|
| 24 |
+
# ATLAS real trajectories for eval. Handoff section 2 warns /home vs ${REPRO}
|
| 25 |
+
# may differ -- verify this is the SAME data the official baseline was scored on.
|
| 26 |
+
ATLAS_VIEW_ROOT="${ATLAS_VIEW_ROOT:-${REPRO_ROOT}/datasets/ATLAS}"
|
| 27 |
+
TEST_CSV="${TEST_CSV:-${REPRO_ROOT}/metadata/test/ATLAS_test.csv}"
|
| 28 |
+
METADATA_ROOT="${METADATA_ROOT:-${REPRO_ROOT}/metadata}"
|
| 29 |
+
# -----------------------------------------------------------------------------
|
| 30 |
+
|
| 31 |
+
# ---- sweep knobs ----
|
| 32 |
+
SWEEP_EPOCHS=(4 0 2) # endpoints first, middle last (survives a timeout)
|
| 33 |
+
SWEEP_SAMPLES="${SWEEP_SAMPLES:-100}" # same across all 3; 250 is the official full count
|
| 34 |
+
SAMPLE_BATCH_SIZE="${SAMPLE_BATCH_SIZE:-20}"
|
| 35 |
+
GPU_IDS="${GPU_IDS:-0,1,2}"
|
| 36 |
+
NUM_GPUS="${NUM_GPUS:-3}"
|
| 37 |
+
|
| 38 |
+
# ---- phase 2 (resume) toggle ----
|
| 39 |
+
RUN_RESUME="${RUN_RESUME:-false}" # set true ONLY after reading the note below
|
| 40 |
+
RESUME_FROM_EPOCH="${RESUME_FROM_EPOCH:-004}"
|
| 41 |
+
|
| 42 |
+
cd "${BBFLOW_ROOT}"
|
| 43 |
+
export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}"
|
| 44 |
+
|
| 45 |
+
die() { echo "[10h] FATAL: $*" >&2; exit 1; }
|
| 46 |
+
|
| 47 |
+
# ---- preflight: every checkpoint the sweep needs must exist ----
|
| 48 |
+
for e in "${SWEEP_EPOCHS[@]}"; do
|
| 49 |
+
ep=$(printf "%03d" "$e")
|
| 50 |
+
[[ -f "${CRASHED_RUN}/epoch:${ep}.ckpt" ]] || die "missing ${CRASHED_RUN}/epoch:${ep}.ckpt"
|
| 51 |
+
done
|
| 52 |
+
[[ -f "${TEST_CSV}" ]] || die "TEST_CSV not found: ${TEST_CSV}"
|
| 53 |
+
[[ -d "${ATLAS_VIEW_ROOT}" ]] || die "ATLAS_VIEW_ROOT not found: ${ATLAS_VIEW_ROOT}"
|
| 54 |
+
echo "[10h] preflight OK. sweep epochs=${SWEEP_EPOCHS[*]} samples=${SWEEP_SAMPLES}"
|
| 55 |
+
|
| 56 |
+
# =============================== PHASE 1: SWEEP ===============================
|
| 57 |
+
for e in "${SWEEP_EPOCHS[@]}"; do
|
| 58 |
+
ep=$(printf "%03d" "$e")
|
| 59 |
+
name="sweep_ep${ep}"
|
| 60 |
+
echo "======================================================================"
|
| 61 |
+
echo "[10h] PHASE1 epoch ${ep}: sampling ${SWEEP_SAMPLES}/protein"
|
| 62 |
+
t0=$(date +%s)
|
| 63 |
+
|
| 64 |
+
CKPT_PATH="${CRASHED_RUN}/epoch:${ep}.ckpt" \
|
| 65 |
+
INFERENCE_NAME="${name}" \
|
| 66 |
+
SAMPLES_PER_PROTEIN="${SWEEP_SAMPLES}" \
|
| 67 |
+
SAMPLE_BATCH_SIZE="${SAMPLE_BATCH_SIZE}" \
|
| 68 |
+
GPU_IDS="${GPU_IDS}" NUM_GPUS="${NUM_GPUS}" \
|
| 69 |
+
REPRO_ROOT="${REPRO_ROOT}" METADATA_ROOT="${METADATA_ROOT}" \
|
| 70 |
+
bash reproduction/02_sample_test.sh
|
| 71 |
+
|
| 72 |
+
# auto-detect the ensemble dir 02 wrote (the folder holding the 82 proteins)
|
| 73 |
+
ENSEMBLE_DIR=$(find "${REPRO_ROOT}/inference" -type d -path "*${name}*" 2>/dev/null \
|
| 74 |
+
| while read -r d; do
|
| 75 |
+
n=$(find "$d" -maxdepth 1 -mindepth 1 -type d | wc -l)
|
| 76 |
+
[[ "$n" -ge 82 ]] && echo "$d"
|
| 77 |
+
done | head -1)
|
| 78 |
+
[[ -n "${ENSEMBLE_DIR}" ]] || die "could not locate ensemble dir for ${name} under ${REPRO_ROOT}/inference (ls it and set ENSEMBLE_DIR by hand)"
|
| 79 |
+
echo "[10h] ensemble: ${ENSEMBLE_DIR}"
|
| 80 |
+
|
| 81 |
+
ENSEMBLE_DIR="${ENSEMBLE_DIR}" \
|
| 82 |
+
METRICS_DIR="${REPRO_ROOT}/metrics/${name}" \
|
| 83 |
+
METHOD_NAME="gen_cov_cross_ep${ep}" \
|
| 84 |
+
ATLAS_VIEW_ROOT="${ATLAS_VIEW_ROOT}" TEST_CSV="${TEST_CSV}" \
|
| 85 |
+
REPRO_ROOT="${REPRO_ROOT}" \
|
| 86 |
+
bash reproduction/03_evaluate.sh
|
| 87 |
+
|
| 88 |
+
echo "[10h] PHASE1 epoch ${ep} DONE in $(( $(date +%s) - t0 ))s"
|
| 89 |
+
echo "[10h] metrics -> ${REPRO_ROOT}/metrics/${name}/compact_metrics.csv"
|
| 90 |
+
done
|
| 91 |
+
|
| 92 |
+
echo "======================================================================"
|
| 93 |
+
echo "[10h] SWEEP COMPLETE. Compare across epochs (PCA-W2 lower=better, RMSF, Pairwise):"
|
| 94 |
+
for e in "${SWEEP_EPOCHS[@]}"; do
|
| 95 |
+
ep=$(printf "%03d" "$e")
|
| 96 |
+
echo " --- ep${ep} ---"
|
| 97 |
+
cat "${REPRO_ROOT}/metrics/sweep_ep${ep}/compact_metrics.csv" 2>/dev/null || echo " (missing)"
|
| 98 |
+
done
|
| 99 |
+
|
| 100 |
+
# ============================= PHASE 2: RESUME ===============================
|
| 101 |
+
# Default OFF. Only produces value if you have read the verification note.
|
| 102 |
+
if [[ "${RUN_RESUME}" != "true" ]]; then
|
| 103 |
+
echo "[10h] PHASE2 skipped (RUN_RESUME=false). Sweep-only, as planned."
|
| 104 |
+
exit 0
|
| 105 |
+
fi
|
| 106 |
+
|
| 107 |
+
echo "[10h] PHASE2: resume from epoch:${RESUME_FROM_EPOCH} with relative-ridge fix"
|
| 108 |
+
pkill -u "$USER" -9 -f experiments/train.py; sleep 3
|
| 109 |
+
export ATLAS_REPRO_ROOT="${REPRO_ROOT}"
|
| 110 |
+
|
| 111 |
+
# Resume works by pointing warm_start (BASE_CKPT) at the Lightning ckpt of the
|
| 112 |
+
# crashed run: train.py:130 sees the pytorch-lightning_version key and hands it
|
| 113 |
+
# to trainer.fit(ckpt_path=...) = full resume with optimizer + epoch state.
|
| 114 |
+
BASE_CKPT="${CRASHED_RUN}/epoch:${RESUME_FROM_EPOCH}.ckpt" \
|
| 115 |
+
RUN_DIR="${CRASHED_RUN}_resume_$(date +%Y%m%d_%H%M%S)" \
|
| 116 |
+
FINGERPRINT_CACHE=/home/wangyusong/LD-FPG-main/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt \
|
| 117 |
+
GPU_IDS=0,1,2 NUM_DEVICES=3 MAX_EPOCHS=10 \
|
| 118 |
+
CHECKPOINT_EVERY_N_EPOCHS=1 CHECKPOINT_SAVE_LAST=true CHECKPOINT_SAVE_TOP_K=-1 \
|
| 119 |
+
PRECISION=bf16-mixed MAX_NUM_RES_SQUARED=120000 MAX_BATCH_SIZE=10 \
|
| 120 |
+
ENERGY_FROM_Q=true ENERGY_FROM_Q_FULL_COV=false Q_DETACH_SHARED_ENCODER=false \
|
| 121 |
+
LAMBDA_MOTION=1.0 LAMBDA_Q=1.0 LAMBDA_MODE_ORTH=1.0 LAMBDA_MODE_RECON=0.0 LAMBDA_PCA_ALIGN=0.0 \
|
| 122 |
+
LAMBDA_CONDITION_CYCLE=0.0 \
|
| 123 |
+
LAMBDA_GENERATOR_COV=1.0 GENERATOR_COV_USE_CROSS=true \
|
| 124 |
+
GENERATOR_COV_T_MIN=0.1 GENERATOR_COV_T_MAX=0.6 GENERATOR_COV_DELTA_SCALE=1.0 \
|
| 125 |
+
GENERATOR_COV_NUM_DELTAS=2 GENERATOR_COV_STUDENT_CHUNK_DELTAS=1 \
|
| 126 |
+
GENERATOR_COV_CHECKPOINT=true GENERATOR_COV_INITIAL_TRACE_ANCHOR=true \
|
| 127 |
+
LAMBDA_GEN_LOCAL_SHAPE=1.0 LAMBDA_GEN_CROSS_SHAPE=1.0 LAMBDA_GEN_TRACE_ANCHOR=0.3 \
|
| 128 |
+
bash base_stages/00_train_final_mog_ddp.sh
|
| 129 |
+
|
| 130 |
+
# VERIFY RESUME TOOK EFFECT (see note): the first progress line MUST read
|
| 131 |
+
# "Epoch 5/9", NOT "Epoch 0/9", and the warm-start log MUST NOT say
|
| 132 |
+
# "Loaded non-Lightning warm start into model only". If it starts at Epoch 0,
|
| 133 |
+
# resume silently failed -- kill it, do not waste the window.
|
bbflow_base/reproduction/README.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# BBFlow ATLAS reproduction
|
| 2 |
+
|
| 3 |
+
This directory runs the upstream BBFlow implementation without changing its
|
| 4 |
+
model or loss. It creates a lightweight symlink view of an existing raw ATLAS
|
| 5 |
+
download, trains on the official 1269/39/82 split, samples 250 conformations
|
| 6 |
+
for each test protein, and evaluates with BBFlow's own analysis code.
|
| 7 |
+
|
| 8 |
+
```bash
|
| 9 |
+
cd bbflow
|
| 10 |
+
bash reproduction/00_prepare_data.sh
|
| 11 |
+
bash reproduction/01_download_official.sh
|
| 12 |
+
CKPT_PATH="$PWD/models/bbflow-0.1/bbflow-0.1.ckpt" \
|
| 13 |
+
GPU_ID=0 bash reproduction/02_sample_test.sh
|
| 14 |
+
ENSEMBLE_DIR=/absolute/path/to/inference/run \
|
| 15 |
+
bash reproduction/03_evaluate.sh
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
The commands above reproduce the published model first. To reproduce training
|
| 19 |
+
from scratch, run `GPU_ID=0 bash reproduction/01_train.sh`, then pass the
|
| 20 |
+
resulting `last.ckpt` to `02_sample_test.sh`.
|
| 21 |
+
|
| 22 |
+
Training defaults match the upstream configuration: 250 epochs, conditional
|
| 23 |
+
prior, intra-protein batch OT, and at most 20 conformations per protein per
|
| 24 |
+
epoch. Checkpoints are saved every 5 epochs by default, with `last.ckpt`
|
| 25 |
+
retained. Set `RESUME_CKPT=/path/to/last.ckpt` to resume training.
|
bbflow_base/reproduction/__pycache__/prepare_atlas_view.cpython-39.pyc
ADDED
|
Binary file (4.93 kB). View file
|
|
|
bbflow_base/reproduction/outputs/metrics/compact_metrics.csv
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Method,RMSF r (↑),RMSF MAE (↓),RMSF Median (1.48),Pairwise RMSD MAE (↓),Pairwise RMSD Median (2.90),PCA W2 (↓),Time [s]
|
| 2 |
+
AlphaFlow,0.86,0.59 (0.01),1.51,1.34 (0.01),2.89,1.47 (0.03),32.0
|
| 3 |
+
ConfDiff,0.88,0.62 (0.01),2.00,1.45 (0.01),3.43,1.41 (0.03),20.2
|
| 4 |
+
AlphaFlow-T,0.92,0.41 (0.01),1.17,0.91 (0.01),2.18,1.28 (0.03),32.6
|
| 5 |
+
ESMFlow-T,0.92,0.52 (0.01),0.94,1.22 (0.01),2.00,1.48 (0.03),11.2
|
| 6 |
+
AlphaFlow-T dist,0.92,0.68 (0.01),0.90,1.41 (0.01),1.73,1.44 (0.03),3.3
|
| 7 |
+
"AlphaFlow-T 12L,dist",0.90,0.85 (0.01),0.68,1.80 (0.01),1.40,1.60 (0.03),1.2
|
| 8 |
+
BBFlow (Ours),0.89,0.47 (0.01),1.48,0.78 (0.01),2.76,1.34 (0.03),0.9
|
| 9 |
+
BBFlow-genresp-v1-epoch004-5ep-250,0.90,0.53,1.79,0.83,3.39,1.29,-
|
bbflow_base/reproduction/outputs/metrics/summary_metrics.csv
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
,
|
| 2 |
+
MD pairwise RMSD,2.8955
|
| 3 |
+
Pairwise RMSD,3.3919
|
| 4 |
+
MD pairwise RMSD mean,3.5538
|
| 5 |
+
Pairwise RMSD mean,3.8871
|
| 6 |
+
Pairwise RMSD r,0.8386
|
| 7 |
+
Pairwise RMSD MAE,0.8274
|
| 8 |
+
Pairwise RMSD RMSE,1.1859
|
| 9 |
+
Pairwise RMSD MAE max,4.8212
|
| 10 |
+
Pairwise RMSD RMSE max,4.8212
|
| 11 |
+
MD RMSF,1.4819
|
| 12 |
+
RMSF,1.7858
|
| 13 |
+
MD RMSF mean,2.1219
|
| 14 |
+
RMSF mean,2.3659
|
| 15 |
+
Global RMSF r,0.8307
|
| 16 |
+
Global RMSF MAE,0.7416
|
| 17 |
+
Global RMSF RMSE,1.2232
|
| 18 |
+
Per target RMSF r,0.8961
|
| 19 |
+
Per target RMSF r mean,0.8727
|
| 20 |
+
Per target RMSF r min,0.475
|
| 21 |
+
Per target RMSF MAE,0.5291
|
| 22 |
+
Per target RMSF MAE mean,0.7324
|
| 23 |
+
Per target RMSF MAE max,2.5885
|
| 24 |
+
Per target RMSF RMSE,0.7741
|
| 25 |
+
Per target RMSF RMSE mean,0.9988
|
| 26 |
+
Per target RMSF RMSE max,4.1436
|
| 27 |
+
MD PCA W2,1.2921
|
| 28 |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|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
SPLITS = {
|
| 11 |
+
"train": "ATLAS_train.csv",
|
| 12 |
+
"validation": "ATLAS_validation.csv",
|
| 13 |
+
"test": "ATLAS_test.csv",
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def normalized(value):
|
| 18 |
+
return re.sub(r"[^a-z0-9]", "", str(value).lower())
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def canonical_name(value):
|
| 22 |
+
value = str(value).strip()
|
| 23 |
+
if "_" in value:
|
| 24 |
+
pdb_id, chain = value.split("_", 1)
|
| 25 |
+
return f"{pdb_id[:4].lower()}{chain[:1].upper()}"
|
| 26 |
+
return f"{value[:4].lower()}{value[4:5].upper()}"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def build_file_index(raw_root, excluded_root):
|
| 30 |
+
index = {}
|
| 31 |
+
excluded_root = excluded_root.resolve()
|
| 32 |
+
for root, dirs, files in os.walk(raw_root):
|
| 33 |
+
root_path = Path(root).resolve()
|
| 34 |
+
dirs[:] = [
|
| 35 |
+
dirname
|
| 36 |
+
for dirname in dirs
|
| 37 |
+
if not (root_path / dirname).resolve().is_relative_to(excluded_root)
|
| 38 |
+
]
|
| 39 |
+
for filename in files:
|
| 40 |
+
path = root_path / filename
|
| 41 |
+
suffix = path.suffix.lower()
|
| 42 |
+
if suffix not in {".pdb", ".xtc"}:
|
| 43 |
+
continue
|
| 44 |
+
index.setdefault((normalized(path.stem), suffix), []).append(path)
|
| 45 |
+
return index
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def choose(index, keys, suffix, entry):
|
| 49 |
+
matches = []
|
| 50 |
+
for key in keys:
|
| 51 |
+
matches.extend(index.get((normalized(key), suffix), []))
|
| 52 |
+
matches = sorted(set(matches), key=lambda path: (len(str(path)), str(path)))
|
| 53 |
+
if not matches:
|
| 54 |
+
raise FileNotFoundError(
|
| 55 |
+
f"Missing {suffix} for {entry}; searched stems={keys}"
|
| 56 |
+
)
|
| 57 |
+
if len(matches) > 1:
|
| 58 |
+
print(f"[prepare] {entry}: using {matches[0]} among {len(matches)} matches")
|
| 59 |
+
return matches[0]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def link_file(source, destination):
|
| 63 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
if destination.is_symlink() or destination.exists():
|
| 65 |
+
if destination.resolve() == source.resolve():
|
| 66 |
+
return
|
| 67 |
+
destination.unlink()
|
| 68 |
+
destination.symlink_to(source.resolve())
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def prepare_split(split, source_csv, index, view_root, metadata_root):
|
| 72 |
+
source = pd.read_csv(source_csv)
|
| 73 |
+
rows = []
|
| 74 |
+
for _, row in source.iterrows():
|
| 75 |
+
name = canonical_name(row["name"])
|
| 76 |
+
target_dir = (view_root / name).resolve()
|
| 77 |
+
original = str(row["name"]).strip()
|
| 78 |
+
pdb = choose(
|
| 79 |
+
index,
|
| 80 |
+
[name, original, f"{name[:4]}_{name[4]}", f"{original}_analysis"],
|
| 81 |
+
".pdb",
|
| 82 |
+
name,
|
| 83 |
+
)
|
| 84 |
+
trajectories = [
|
| 85 |
+
choose(
|
| 86 |
+
index,
|
| 87 |
+
[
|
| 88 |
+
f"{name}_R{replicate}",
|
| 89 |
+
f"{name[:4]}_{name[4]}_R{replicate}",
|
| 90 |
+
f"{original}_R{replicate}",
|
| 91 |
+
],
|
| 92 |
+
".xtc",
|
| 93 |
+
name,
|
| 94 |
+
)
|
| 95 |
+
for replicate in range(1, 4)
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
link_file(pdb, target_dir / f"{name}.pdb")
|
| 99 |
+
for replicate, trajectory in enumerate(trajectories, start=1):
|
| 100 |
+
link_file(trajectory, target_dir / f"{name}_R{replicate}.xtc")
|
| 101 |
+
|
| 102 |
+
output = {
|
| 103 |
+
"name": name,
|
| 104 |
+
"pdb_path": str(target_dir / f"{name}.pdb"),
|
| 105 |
+
}
|
| 106 |
+
if split == "train":
|
| 107 |
+
output.update(
|
| 108 |
+
modeled_seq_len=int(row["modeled_seq_len"]),
|
| 109 |
+
folder=str(target_dir),
|
| 110 |
+
num_conformations=int(row["num_conformations"]),
|
| 111 |
+
)
|
| 112 |
+
rows.append(output)
|
| 113 |
+
|
| 114 |
+
output_dir = metadata_root / split
|
| 115 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 116 |
+
output_path = output_dir / f"ATLAS_{split}.csv"
|
| 117 |
+
frame = pd.DataFrame(rows)
|
| 118 |
+
if split == "train":
|
| 119 |
+
frame = frame.sort_values("modeled_seq_len").reset_index(drop=True)
|
| 120 |
+
frame.to_csv(output_path, index=False)
|
| 121 |
+
print(f"[prepare] {split}: {len(frame)} entries -> {output_path}")
|
| 122 |
+
return len(frame)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def main():
|
| 126 |
+
parser = argparse.ArgumentParser()
|
| 127 |
+
parser.add_argument("--raw-root", required=True, type=Path)
|
| 128 |
+
parser.add_argument("--split-root", required=True, type=Path)
|
| 129 |
+
parser.add_argument("--view-root", required=True, type=Path)
|
| 130 |
+
parser.add_argument("--metadata-root", required=True, type=Path)
|
| 131 |
+
args = parser.parse_args()
|
| 132 |
+
|
| 133 |
+
raw_root = args.raw_root.resolve()
|
| 134 |
+
split_root = args.split_root.resolve()
|
| 135 |
+
view_root = args.view_root.resolve()
|
| 136 |
+
metadata_root = args.metadata_root.resolve()
|
| 137 |
+
if not raw_root.is_dir():
|
| 138 |
+
raise NotADirectoryError(f"ATLAS raw root does not exist: {raw_root}")
|
| 139 |
+
|
| 140 |
+
view_root.mkdir(parents=True, exist_ok=True)
|
| 141 |
+
metadata_root.mkdir(parents=True, exist_ok=True)
|
| 142 |
+
print(f"[prepare] indexing PDB/XTC files under {raw_root}")
|
| 143 |
+
index = build_file_index(raw_root, view_root)
|
| 144 |
+
print(f"[prepare] indexed {sum(len(paths) for paths in index.values())} files")
|
| 145 |
+
|
| 146 |
+
counts = {}
|
| 147 |
+
for split, filename in SPLITS.items():
|
| 148 |
+
source_csv = split_root / filename
|
| 149 |
+
if not source_csv.is_file():
|
| 150 |
+
raise FileNotFoundError(f"Missing official split CSV: {source_csv}")
|
| 151 |
+
counts[split] = prepare_split(
|
| 152 |
+
split, source_csv, index, view_root, metadata_root
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
expected = {"train": 1269, "validation": 39, "test": 82}
|
| 156 |
+
if counts != expected:
|
| 157 |
+
raise RuntimeError(f"Unexpected split counts: {counts}; expected {expected}")
|
| 158 |
+
print("[prepare] BBFlow ATLAS view is complete: train=1269 validation=39 test=82")
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
if __name__ == "__main__":
|
| 162 |
+
main()
|
bbflow_base/reproduction/watch_train_then_infer.sh
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Watch the frozen training run; when it EXITS (completes or is killed), auto-run
|
| 3 |
+
# downstream inference on the latest checkpoint: quick 5znjA read, then full 82.
|
| 4 |
+
# Launch in background: nohup bash reproduction/watch_train_then_infer.sh > ~/watch_frozen.log 2>&1 &
|
| 5 |
+
set -uo pipefail
|
| 6 |
+
|
| 7 |
+
REPRO_ROOT=/data/shared/wangyusong/atals/bbflow_official_reproduction
|
| 8 |
+
BBFLOW="$HOME/LD-FPG-main/bbflow_base"
|
| 9 |
+
# latest frozen run dir (auto-detect; override by exporting RUN_DIR before launch)
|
| 10 |
+
RUN_DIR="${RUN_DIR:-$(ls -dt ${REPRO_ROOT}/outputs/checkpoints/bbflow_base_frozen_shape_notrace_* | head -1)}"
|
| 11 |
+
|
| 12 |
+
# latent config that MUST match the frozen checkpoint (else q-head loads random -> garbage)
|
| 13 |
+
LATENT_ARGS="latent.enable=true \
|
| 14 |
+
+latent.mixture_components=2 \
|
| 15 |
+
+latent.energy_from_q=true +latent.energy_from_q_full_cov=false +latent.sample_coefficients=true \
|
| 16 |
+
+latent.q_detach_projection=true +latent.q_detach_shared_encoder=false \
|
| 17 |
+
+latent.q_lstsq_ridge=1e-4 +latent.q_cholesky_jitter=1e-4"
|
| 18 |
+
|
| 19 |
+
TEST_CSV=${REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv
|
| 20 |
+
ATLAS_VIEW_ROOT=${REPRO_ROOT}/datasets/ATLAS
|
| 21 |
+
|
| 22 |
+
cd "$BBFLOW"; export PYTHONPATH="$PWD:${PYTHONPATH:-}"
|
| 23 |
+
echo "[watch] RUN_DIR=$RUN_DIR"
|
| 24 |
+
|
| 25 |
+
rmsf_check () { # $1 = inference name, $2 = protein
|
| 26 |
+
python - "$1" "$2" <<'EOF'
|
| 27 |
+
import numpy as np, glob, sys
|
| 28 |
+
name, prot = sys.argv[1], sys.argv[2]
|
| 29 |
+
REPRO="/data/shared/wangyusong/atals/bbflow_official_reproduction"
|
| 30 |
+
fs=sorted(glob.glob(f"{REPRO}/inference/**/{name}/**/{prot}/sampled_conformations.pdb", recursive=True))
|
| 31 |
+
if not fs: print(f"[watch] no output for {name}/{prot}"); sys.exit(0)
|
| 32 |
+
M=[];c=[]
|
| 33 |
+
for ln in open(fs[0]):
|
| 34 |
+
if ln.startswith("MODEL"): c=[]
|
| 35 |
+
elif ln.startswith("ENDMDL"):
|
| 36 |
+
if c: M.append(c)
|
| 37 |
+
elif ln.startswith(("ATOM","HETATM")) and ln[12:16].strip()=="CA":
|
| 38 |
+
c.append([float(ln[30:38]),float(ln[38:46]),float(ln[46:54])])
|
| 39 |
+
X=np.array(M); r=X.std(0).mean(-1)
|
| 40 |
+
print(f"[watch] {name}/{prot} RMSF mean/median: {r.mean():.2f}/{np.median(r):.2f} | <1.5 frac: {(r<1.5).mean():.3f}")
|
| 41 |
+
EOF
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
# 1) wait for training to exit, then let GPUs settle
|
| 45 |
+
echo "[watch] waiting for training to finish... ($(date))"
|
| 46 |
+
while pgrep -u "$USER" -f experiments/train.py >/dev/null; do sleep 120; done
|
| 47 |
+
echo "[watch] training gone at $(date). waiting 60s for GPU release."; sleep 60
|
| 48 |
+
|
| 49 |
+
# 2) latest checkpoint
|
| 50 |
+
CKPT=$(ls -t "$RUN_DIR"/epoch:*.ckpt 2>/dev/null | head -1); [[ -z "$CKPT" ]] && CKPT="$RUN_DIR/last.ckpt"
|
| 51 |
+
[[ -f "$CKPT" ]] || { echo "[watch] no checkpoint in $RUN_DIR"; exit 1; }
|
| 52 |
+
echo "[watch] evaluating $CKPT"
|
| 53 |
+
|
| 54 |
+
# 3) QUICK: single protein for an immediate base-preserved read
|
| 55 |
+
head -1 "$TEST_CSV" > /tmp/one_5znjA.csv; grep -E "^5znjA," "$TEST_CSV" >> /tmp/one_5znjA.csv
|
| 56 |
+
env -u NVIDIA_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES=0 \
|
| 57 |
+
python experiments/inference.py $LATENT_ARGS \
|
| 58 |
+
inference.ckpt_path="$CKPT" inference.csv_path=/tmp/one_5znjA.csv \
|
| 59 |
+
inference.output_dir="$REPRO_ROOT/inference" inference.name=frozen_quick_5znjA \
|
| 60 |
+
inference.num_gpus=1 inference.samples.samples_per_protein=100 inference.samples.batch_size=20 \
|
| 61 |
+
inference.samples.num_res_squared=2900000 inference.precision=32-true \
|
| 62 |
+
inference.final_only=true inference.interpolant.sampling.num_timesteps=20
|
| 63 |
+
rmsf_check frozen_quick_5znjA 5znjA
|
| 64 |
+
|
| 65 |
+
# 4) FULL: 82 proteins on 3 GPUs, then 03 eval (PCA W2 vs BBFlow)
|
| 66 |
+
env -u NVIDIA_VISIBLE_DEVICES CUDA_VISIBLE_DEVICES=0,1,2 \
|
| 67 |
+
python experiments/inference.py $LATENT_ARGS \
|
| 68 |
+
inference.ckpt_path="$CKPT" inference.csv_path="$TEST_CSV" \
|
| 69 |
+
inference.output_dir="$REPRO_ROOT/inference" inference.name=frozen_full \
|
| 70 |
+
inference.num_gpus=3 inference.samples.samples_per_protein=100 inference.samples.batch_size=20 \
|
| 71 |
+
inference.samples.num_res_squared=2900000 inference.precision=32-true \
|
| 72 |
+
inference.final_only=true inference.interpolant.sampling.num_timesteps=20
|
| 73 |
+
|
| 74 |
+
ENSEMBLE_DIR=$(find "$REPRO_ROOT/inference" -type d -path "*frozen_full*" \
|
| 75 |
+
| while read -r d; do [[ $(find "$d" -maxdepth 1 -mindepth 1 -type d|wc -l) -ge 82 ]] && echo "$d"; done | head -1)
|
| 76 |
+
if [[ -n "$ENSEMBLE_DIR" ]]; then
|
| 77 |
+
ENSEMBLE_DIR="$ENSEMBLE_DIR" METRICS_DIR="$REPRO_ROOT/metrics/frozen_full" METHOD_NAME=frozen_shape \
|
| 78 |
+
ATLAS_VIEW_ROOT="$ATLAS_VIEW_ROOT" TEST_CSV="$TEST_CSV" REPRO_ROOT="$REPRO_ROOT" NUM_WORKERS=8 \
|
| 79 |
+
bash reproduction/03_evaluate.sh
|
| 80 |
+
echo "[watch] DONE. metrics -> $REPRO_ROOT/metrics/frozen_full/compact_metrics.csv"
|
| 81 |
+
cat "$REPRO_ROOT/metrics/frozen_full/compact_metrics.csv"
|
| 82 |
+
else
|
| 83 |
+
echo "[watch] full ensemble dir not found; check $REPRO_ROOT/inference for frozen_full"
|
| 84 |
+
fi
|
bbflow_base/scripts/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Executable diagnostics and experiment utilities."""
|
bbflow_base/scripts/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (213 Bytes). View file
|
|
|
bbflow_base/scripts/__pycache__/check_directional_condition_equivariance.cpython-39.pyc
ADDED
|
Binary file (2.47 kB). View file
|
|
|
bbflow_base/scripts/__pycache__/diagnose_film.cpython-39.pyc
ADDED
|
Binary file (6.12 kB). View file
|
|
|
bbflow_base/scripts/__pycache__/diagnose_pca_projection_ceiling.cpython-39.pyc
ADDED
|
Binary file (4.21 kB). View file
|
|
|
bbflow_base/scripts/__pycache__/diagnose_z.cpython-311.pyc
ADDED
|
Binary file (23.1 kB). View file
|
|
|
bbflow_base/scripts/__pycache__/fit_motion_template_upper_bound.cpython-311.pyc
ADDED
|
Binary file (30.6 kB). View file
|
|
|
bbflow_base/scripts/__pycache__/fit_motion_template_upper_bound.cpython-39.pyc
ADDED
|
Binary file (12.4 kB). View file
|
|
|
bbflow_base/scripts/__pycache__/probe_condition_ensemble_cov.cpython-39.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
bbflow_base/scripts/__pycache__/probe_sample_condition.cpython-39.pyc
ADDED
|
Binary file (8.76 kB). View file
|
|
|
bbflow_base/scripts/__pycache__/rescore_pca_w2.cpython-311.pyc
ADDED
|
Binary file (13.7 kB). View file
|
|
|
bbflow_base/scripts/__pycache__/sp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
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import pickle
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
import functools
|
| 7 |
+
from multiprocessing import Pool
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
from scipy.stats import bootstrap
|
| 10 |
+
from typing import List, Tuple, Dict, Union, Optional
|
| 11 |
+
|
| 12 |
+
from bbflow.analysis.analyse_bbflow import (
|
| 13 |
+
_load_ref_traj_full,
|
| 14 |
+
_load_ref_traj_subset,
|
| 15 |
+
_load_model_traj,
|
| 16 |
+
_calc_metrics_bootstrap,
|
| 17 |
+
_analyze_data,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
default_metrics = [
|
| 21 |
+
"RMSD",
|
| 22 |
+
"RMSF",
|
| 23 |
+
"DCCM",
|
| 24 |
+
"RMWD",
|
| 25 |
+
"PCA-W2",
|
| 26 |
+
"Cosine Sim",
|
| 27 |
+
"Weak Transient Contacts",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
COMPACT_BASELINE_ROWS = [
|
| 31 |
+
("AlphaFlow", "0.86", "0.59 (0.01)", "1.51", "1.34 (0.01)", "2.89", "1.47 (0.03)", "32.0"),
|
| 32 |
+
("ConfDiff", "0.88", "0.62 (0.01)", "2.00", "1.45 (0.01)", "3.43", "1.41 (0.03)", "20.2"),
|
| 33 |
+
("AlphaFlow-T", "0.92", "0.41 (0.01)", "1.17", "0.91 (0.01)", "2.18", "1.28 (0.03)", "32.6"),
|
| 34 |
+
("ESMFlow-T", "0.92", "0.52 (0.01)", "0.94", "1.22 (0.01)", "2.00", "1.48 (0.03)", "11.2"),
|
| 35 |
+
("AlphaFlow-T dist", "0.92", "0.68 (0.01)", "0.90", "1.41 (0.01)", "1.73", "1.44 (0.03)", "3.3"),
|
| 36 |
+
("AlphaFlow-T 12L,dist", "0.90", "0.85 (0.01)", "0.68", "1.80 (0.01)", "1.40", "1.60 (0.03)", "1.2"),
|
| 37 |
+
("BBFlow (Ours)", "0.89", "0.47 (0.01)", "1.48", "0.78 (0.01)", "2.76", "1.34 (0.03)", "0.9"),
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _fmt_metric(metrics_dict, key, digits=2):
|
| 42 |
+
value = metrics_dict.get(key)
|
| 43 |
+
if value is None or pd.isna(value):
|
| 44 |
+
return "-"
|
| 45 |
+
return f"{float(value):.{digits}f}"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _compact_metrics_df(metrics_dict, method_name, time_seconds=None):
|
| 49 |
+
md_rmsf = _fmt_metric(metrics_dict, "MD RMSF", digits=2)
|
| 50 |
+
md_pairwise = _fmt_metric(metrics_dict, "MD pairwise RMSD", digits=2)
|
| 51 |
+
time_value = "-" if time_seconds is None else f"{time_seconds:.1f}"
|
| 52 |
+
columns = [
|
| 53 |
+
"Method",
|
| 54 |
+
"RMSF r (↑)",
|
| 55 |
+
"RMSF MAE (↓)",
|
| 56 |
+
f"RMSF Median ({md_rmsf})",
|
| 57 |
+
"Pairwise RMSD MAE (↓)",
|
| 58 |
+
f"Pairwise RMSD Median ({md_pairwise})",
|
| 59 |
+
"PCA W2 (↓)",
|
| 60 |
+
"Time [s]",
|
| 61 |
+
]
|
| 62 |
+
rows = [dict(zip(columns, row)) for row in COMPACT_BASELINE_ROWS]
|
| 63 |
+
rows.append({
|
| 64 |
+
"Method": method_name,
|
| 65 |
+
"RMSF r (↑)": _fmt_metric(metrics_dict, "Per target RMSF r", digits=2),
|
| 66 |
+
"RMSF MAE (↓)": _fmt_metric(metrics_dict, "Per target RMSF MAE", digits=2),
|
| 67 |
+
f"RMSF Median ({md_rmsf})": _fmt_metric(metrics_dict, "RMSF", digits=2),
|
| 68 |
+
"Pairwise RMSD MAE (↓)": _fmt_metric(metrics_dict, "Pairwise RMSD MAE", digits=2),
|
| 69 |
+
f"Pairwise RMSD Median ({md_pairwise})": _fmt_metric(metrics_dict, "Pairwise RMSD", digits=2),
|
| 70 |
+
"PCA W2 (↓)": _fmt_metric(metrics_dict, "MD PCA W2", digits=2),
|
| 71 |
+
"Time [s]": time_value,
|
| 72 |
+
})
|
| 73 |
+
return pd.DataFrame(rows, columns=columns)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def calc_metrics(
|
| 77 |
+
names: Union[List[str]]=None,
|
| 78 |
+
md_dirs: Optional[List[str]]=None,
|
| 79 |
+
ensemble_dirs: Optional[List[str]]=None,
|
| 80 |
+
paths: Optional[List[Tuple]]=None,
|
| 81 |
+
num_workers: int=8,
|
| 82 |
+
metrics_subset: Optional[List[str]]=None,
|
| 83 |
+
use_tqdm: bool=True,
|
| 84 |
+
analysis_data_path: str="",
|
| 85 |
+
analysis_metrics_path: str="",
|
| 86 |
+
compact_metrics_path: str="",
|
| 87 |
+
compact_method_name: str="BBFlow-base-prior-z",
|
| 88 |
+
compact_time_seconds: Optional[float]=None,
|
| 89 |
+
print_metrics: bool=True,
|
| 90 |
+
):
|
| 91 |
+
"""
|
| 92 |
+
Calculate metrics for protein ensembles against reference MD trajectories.
|
| 93 |
+
|
| 94 |
+
Either provide:
|
| 95 |
+
1. names, md_dirs and ensemble_dirs
|
| 96 |
+
or
|
| 97 |
+
2. paths: list of tuples, each containing
|
| 98 |
+
(model_ensemble_pdb, reference_pdb, reference_traj1, ..., reference_trajN)
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
names:
|
| 102 |
+
List of names of the ensembles to analyze. For each name, there must
|
| 103 |
+
be a corresponding pdb file or directory in each of the ensemble_dirs,
|
| 104 |
+
i.e. `ensemble_dirs[i]/name.pdb` or `ensemble_dirs[i]/name/sampled_conformations.pdb`,
|
| 105 |
+
as well as a corresponding reference pdb and trajs in each of the md_dirs,
|
| 106 |
+
i.e. `md_dirs[i]/name.pdb` and `md_dirs[i]/name/name_traj_R{j}.xtc` for j=1,2,3.
|
| 107 |
+
md_dirs:
|
| 108 |
+
List of directories containing reference MD data. Each directory must contain
|
| 109 |
+
reference pdbs and 3 trajectories.
|
| 110 |
+
ensemble_dirs:
|
| 111 |
+
List of directories containing model ensembles. Each directory must contain
|
| 112 |
+
pdb files or directories for each ensemble.
|
| 113 |
+
paths:
|
| 114 |
+
List of tuples, each containing
|
| 115 |
+
(model_ensemble.pdb, reference.pdb, reference_traj1.xtc, ..., reference_trajN.xtc)
|
| 116 |
+
num_workers:
|
| 117 |
+
Number of parallel workers to use.
|
| 118 |
+
metrics_subset:
|
| 119 |
+
Subset of metrics to calculate. If None, all metrics are calculated.
|
| 120 |
+
use_tqdm:
|
| 121 |
+
Whether to use tqdm progress bar.
|
| 122 |
+
analysis_data_path:
|
| 123 |
+
Path to save raw analysis data (pickle file). If empty, no file is saved.
|
| 124 |
+
analysis_metrics_path:
|
| 125 |
+
Path to save metrics summary (CSV file). If empty, no file is saved.
|
| 126 |
+
print_metrics:
|
| 127 |
+
Whether to print metrics to console.
|
| 128 |
+
"""
|
| 129 |
+
if paths is not None:
|
| 130 |
+
if names is not None or md_dirs is not None or ensemble_dirs is not None:
|
| 131 |
+
raise ValueError("Either provide paths OR names, md_dirs and ensemble_dirs.")
|
| 132 |
+
names = paths
|
| 133 |
+
|
| 134 |
+
if metrics_subset is None:
|
| 135 |
+
metrics_subset = default_metrics
|
| 136 |
+
|
| 137 |
+
if num_workers > 1:
|
| 138 |
+
p = Pool(num_workers)
|
| 139 |
+
p.__enter__()
|
| 140 |
+
__map__ = p.imap
|
| 141 |
+
else:
|
| 142 |
+
__map__ = map
|
| 143 |
+
|
| 144 |
+
_calc_metrics_partial = functools.partial(
|
| 145 |
+
_calc_metrics_bootstrap,
|
| 146 |
+
reference_dirs=md_dirs,
|
| 147 |
+
pdbdirs=ensemble_dirs,
|
| 148 |
+
metrics_subset=metrics_subset
|
| 149 |
+
)
|
| 150 |
+
if use_tqdm:
|
| 151 |
+
out = dict(tqdm(__map__(_calc_metrics_partial, names), total=len(names), leave=False))
|
| 152 |
+
else:
|
| 153 |
+
out = dict(__map__(_calc_metrics_partial, names))
|
| 154 |
+
if num_workers > 1:
|
| 155 |
+
p.__exit__(None, None, None)
|
| 156 |
+
|
| 157 |
+
out = {k: v for k, v in out.items() if v is not None}
|
| 158 |
+
if len(out) == 0:
|
| 159 |
+
raise ValueError("No valid trajectories were loaded.")
|
| 160 |
+
|
| 161 |
+
metrics_dict = _analyze_data(out, metrics_subset)
|
| 162 |
+
|
| 163 |
+
if analysis_data_path != "":
|
| 164 |
+
if paths is not None:
|
| 165 |
+
# replace keys with range(len(paths)), otherwise keys are unreadable tuples
|
| 166 |
+
out = {f"path_{i}": out[k] for i, k in enumerate(out.keys())}
|
| 167 |
+
with open(analysis_data_path, 'wb') as f:
|
| 168 |
+
pickle.dump(out, f)
|
| 169 |
+
|
| 170 |
+
if analysis_metrics_path != "":
|
| 171 |
+
df = pd.DataFrame({"": metrics_dict}).round(4)
|
| 172 |
+
df = df.reindex([k for k in metrics_dict.keys()])
|
| 173 |
+
df.to_csv(analysis_metrics_path)
|
| 174 |
+
|
| 175 |
+
compact_df = _compact_metrics_df(
|
| 176 |
+
metrics_dict,
|
| 177 |
+
method_name=compact_method_name,
|
| 178 |
+
time_seconds=compact_time_seconds,
|
| 179 |
+
)
|
| 180 |
+
if compact_metrics_path != "":
|
| 181 |
+
compact_df.to_csv(compact_metrics_path, index=False)
|
| 182 |
+
|
| 183 |
+
if print_metrics:
|
| 184 |
+
print(compact_df.to_string(index=False))
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def main():
|
| 188 |
+
"""
|
| 189 |
+
Command line interface for calculating metrics.
|
| 190 |
+
|
| 191 |
+
Usage:
|
| 192 |
+
1. Provide md_dirs, ensemble_dirs and names:
|
| 193 |
+
|
| 194 |
+
`
|
| 195 |
+
python analysis_script.py --md_dirs md_dir1 md_dir2 ... \
|
| 196 |
+
--ensemble_dirs ensemble_dir1 ensemble_dir2 ... \
|
| 197 |
+
--names name1 name2 ...
|
| 198 |
+
`
|
| 199 |
+
|
| 200 |
+
2. Provide md_dirs, ensemble_dirs and auto-detect names from ensemble_dirs:
|
| 201 |
+
|
| 202 |
+
`
|
| 203 |
+
python analysis_script.py --md_dirs md_dir1 md_dir2 ... \
|
| 204 |
+
--ensemble_dirs ensemble_dir1 ensemble_dir2 ...
|
| 205 |
+
`
|
| 206 |
+
|
| 207 |
+
3. Provide paths directly of the form:
|
| 208 |
+
|
| 209 |
+
`
|
| 210 |
+
python analysis_script.py --paths \
|
| 211 |
+
model1.pdb ref1.pdb ref_traj1.xtc ... ref_trajN1.xtc \
|
| 212 |
+
model2.pdb ref2.pdb ref_traj1.xtc ... ref_trajN2.xtc ...
|
| 213 |
+
`
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
Additional arguments:
|
| 217 |
+
|
| 218 |
+
```
|
| 219 |
+
--num_workers N : Number of parallel workers (default: 8)
|
| 220 |
+
--metrics metric1 metric2 ... : Subset of metrics to calculate (default: all)
|
| 221 |
+
--use_tqdm : Show progress bar
|
| 222 |
+
--analysis_data_path path : Path to save raw analysis data (pickle file)
|
| 223 |
+
--analysis_metrics_path path : Path to save metrics summary (CSV file)
|
| 224 |
+
--print_metrics : Print metrics to console
|
| 225 |
+
```
|
| 226 |
+
|
| 227 |
+
"""
|
| 228 |
+
parser = argparse.ArgumentParser()
|
| 229 |
+
parser.add_argument('--md_dirs', nargs='*', default=[])
|
| 230 |
+
parser.add_argument('--ensemble_dirs', nargs='*', default=[])
|
| 231 |
+
parser.add_argument('--names', nargs='*', default=[])
|
| 232 |
+
parser.add_argument('--paths', nargs='*', default=[])
|
| 233 |
+
parser.add_argument('--num_workers', type=int, default=1)
|
| 234 |
+
parser.add_argument('--metrics', nargs='*', default=default_metrics)
|
| 235 |
+
parser.add_argument('--no_tqdm', action='store_true')
|
| 236 |
+
parser.add_argument('--analysis_data_path', type=str, default='')
|
| 237 |
+
parser.add_argument('--analysis_metrics_path', type=str, default='')
|
| 238 |
+
parser.add_argument('--compact_metrics_path', type=str, default='')
|
| 239 |
+
parser.add_argument('--compact_method_name', type=str, default='BBFlow-base-prior-z')
|
| 240 |
+
parser.add_argument('--compact_time_seconds', type=float, default=None)
|
| 241 |
+
parser.add_argument('--print_metrics', action='store_true')
|
| 242 |
+
args = parser.parse_args()
|
| 243 |
+
|
| 244 |
+
# Either provide md_dirs, ensemble_dirs and names,
|
| 245 |
+
# or provide paths where each path contains both md and ensemble pdbs.
|
| 246 |
+
if len(args.paths) > 0:
|
| 247 |
+
if len(args.md_dirs) > 0 or len(args.ensemble_dirs) > 0 or len(args.names) > 0:
|
| 248 |
+
raise ValueError("Either provide --paths OR --md_dirs, --ensemble_dirs and --names.")
|
| 249 |
+
args.md_dirs = None
|
| 250 |
+
args.ensemble_dirs = None
|
| 251 |
+
args.names = None
|
| 252 |
+
paths = []
|
| 253 |
+
# args.paths must be in the format:
|
| 254 |
+
# model1.pdb, ref1.pdb, ref_traj1.xtc, ..., ref_trajN1.xtc,
|
| 255 |
+
# model2.pdb, ref2.pdb, ref_traj1.xtc, ..., ref_trajN2.xtc,
|
| 256 |
+
# ...
|
| 257 |
+
paths.append([])
|
| 258 |
+
for p in args.paths:
|
| 259 |
+
if p.endswith('.pdb') and len(paths[-1]) < 2:
|
| 260 |
+
# model ensemble pdb or reference pdb
|
| 261 |
+
paths[-1].append(p)
|
| 262 |
+
elif p.endswith('.pdb') and len(paths[-1]) >= 3:
|
| 263 |
+
# start a new entry
|
| 264 |
+
paths.append([p])
|
| 265 |
+
elif p.endswith('.xtc'):
|
| 266 |
+
# reference traj
|
| 267 |
+
if len(paths[-1]) < 2:
|
| 268 |
+
raise ValueError("Reference traj provided before model ensemble pdb or reference pdb.")
|
| 269 |
+
paths[-1].append(p)
|
| 270 |
+
elif p.endswith('.pdb') and len(paths[-1]) == 2:
|
| 271 |
+
raise ValueError("More than two pdbs provided before reference trajs.")
|
| 272 |
+
|
| 273 |
+
if len(paths[-1]) == 0:
|
| 274 |
+
paths = paths[:-1]
|
| 275 |
+
|
| 276 |
+
if len(paths) == 0:
|
| 277 |
+
raise ValueError("No valid paths provided.")
|
| 278 |
+
|
| 279 |
+
if not paths[-1][-1].endswith('.xtc'):
|
| 280 |
+
raise ValueError("Last entry in paths missing reference trajs.")
|
| 281 |
+
|
| 282 |
+
for i in range(len(paths)):
|
| 283 |
+
paths[i] = tuple(paths[i])
|
| 284 |
+
|
| 285 |
+
names = None
|
| 286 |
+
|
| 287 |
+
else:
|
| 288 |
+
paths = None
|
| 289 |
+
if len(args.names) == 0:
|
| 290 |
+
# auto-detect names from ensemble_dirs.
|
| 291 |
+
# Include all pdbs and dirs in ensemble_dirs
|
| 292 |
+
names = []
|
| 293 |
+
for ensemble_dir in args.ensemble_dirs:
|
| 294 |
+
names_ = [
|
| 295 |
+
f for f in os.listdir(ensemble_dir)
|
| 296 |
+
if f.endswith('.pdb') or os.path.isdir(os.path.join(ensemble_dir, f))
|
| 297 |
+
]
|
| 298 |
+
names.extend(names_)
|
| 299 |
+
names = list(set(names))
|
| 300 |
+
print(f"Found {len(names)} generated ensembles to analyze:")
|
| 301 |
+
print(names)
|
| 302 |
+
else:
|
| 303 |
+
names = args.names
|
| 304 |
+
|
| 305 |
+
assert len(names) > 0, "No names provided for analysis."
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
calc_metrics(
|
| 309 |
+
names=names,
|
| 310 |
+
md_dirs=args.md_dirs,
|
| 311 |
+
ensemble_dirs=args.ensemble_dirs,
|
| 312 |
+
paths=paths,
|
| 313 |
+
num_workers=args.num_workers,
|
| 314 |
+
metrics_subset=args.metrics,
|
| 315 |
+
use_tqdm=not args.no_tqdm,
|
| 316 |
+
analysis_data_path=args.analysis_data_path,
|
| 317 |
+
analysis_metrics_path=args.analysis_metrics_path,
|
| 318 |
+
compact_metrics_path=args.compact_metrics_path,
|
| 319 |
+
compact_method_name=args.compact_method_name,
|
| 320 |
+
compact_time_seconds=args.compact_time_seconds,
|
| 321 |
+
print_metrics=args.print_metrics,
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+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|
+
import argparse
|
| 3 |
+
import pickle
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def load_analysis(path: Path, tag: str) -> pd.DataFrame:
|
| 11 |
+
with path.open("rb") as handle:
|
| 12 |
+
payload = pickle.load(handle)
|
| 13 |
+
|
| 14 |
+
rows = []
|
| 15 |
+
for name, values in payload.items():
|
| 16 |
+
model_rmsf = np.asarray(values["model_rmsf"], dtype=float)
|
| 17 |
+
ref_rmsf = np.asarray(values["ref_rmsf"], dtype=float)
|
| 18 |
+
rows.append(
|
| 19 |
+
{
|
| 20 |
+
"pdb_name": name,
|
| 21 |
+
f"{tag}_pca_w2": float(values["md_pca_w2"]),
|
| 22 |
+
f"{tag}_joint_pca_w2": float(values["joint_pca_w2"]),
|
| 23 |
+
f"{tag}_model_pairwise": float(values["model_mean_pairwise_rmsd"]),
|
| 24 |
+
f"{tag}_ref_pairwise": float(values["ref_mean_pairwise_rmsd"]),
|
| 25 |
+
f"{tag}_pairwise_abs_error": abs(
|
| 26 |
+
float(values["model_mean_pairwise_rmsd"])
|
| 27 |
+
- float(values["ref_mean_pairwise_rmsd"])
|
| 28 |
+
),
|
| 29 |
+
f"{tag}_model_rmsf_mean": float(np.mean(model_rmsf)),
|
| 30 |
+
f"{tag}_rmsf_mae": float(np.mean(np.abs(model_rmsf - ref_rmsf))),
|
| 31 |
+
}
|
| 32 |
+
)
|
| 33 |
+
return pd.DataFrame(rows)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def regression_summary(frame: pd.DataFrame, start: str, end: str) -> dict:
|
| 37 |
+
delta_pca = frame[f"{end}_pca_w2"] - frame[f"{start}_pca_w2"]
|
| 38 |
+
delta_pairwise = (
|
| 39 |
+
frame[f"{end}_model_pairwise"] - frame[f"{start}_model_pairwise"]
|
| 40 |
+
)
|
| 41 |
+
delta_rmsf = (
|
| 42 |
+
frame[f"{end}_model_rmsf_mean"] - frame[f"{start}_model_rmsf_mean"]
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
x = np.column_stack(
|
| 46 |
+
[np.ones(len(frame)), delta_pairwise.to_numpy(), delta_rmsf.to_numpy()]
|
| 47 |
+
)
|
| 48 |
+
y = delta_pca.to_numpy()
|
| 49 |
+
coef, *_ = np.linalg.lstsq(x, y, rcond=None)
|
| 50 |
+
prediction = x @ coef
|
| 51 |
+
ss_total = np.sum((y - y.mean()) ** 2)
|
| 52 |
+
r2 = 1.0 - np.sum((y - prediction) ** 2) / ss_total if ss_total > 0 else np.nan
|
| 53 |
+
|
| 54 |
+
amplitude_change = np.sqrt(
|
| 55 |
+
delta_pairwise.to_numpy() ** 2 + delta_rmsf.to_numpy() ** 2
|
| 56 |
+
)
|
| 57 |
+
stable_cutoff = float(np.quantile(amplitude_change, 0.25))
|
| 58 |
+
stable = amplitude_change <= stable_cutoff
|
| 59 |
+
|
| 60 |
+
return {
|
| 61 |
+
"comparison": f"{start}_to_{end}",
|
| 62 |
+
"n": len(frame),
|
| 63 |
+
"median_delta_pca_w2": float(delta_pca.median()),
|
| 64 |
+
"pca_improved_fraction": float((delta_pca < 0).mean()),
|
| 65 |
+
"median_delta_model_pairwise": float(delta_pairwise.median()),
|
| 66 |
+
"pearson_delta_pca_vs_pairwise": float(
|
| 67 |
+
delta_pca.corr(delta_pairwise, method="pearson")
|
| 68 |
+
),
|
| 69 |
+
"spearman_delta_pca_vs_pairwise": float(
|
| 70 |
+
delta_pca.corr(delta_pairwise, method="spearman")
|
| 71 |
+
),
|
| 72 |
+
"amplitude_regression_r2": float(r2),
|
| 73 |
+
"coef_delta_pairwise": float(coef[1]),
|
| 74 |
+
"coef_delta_rmsf": float(coef[2]),
|
| 75 |
+
"stable_amplitude_cutoff": stable_cutoff,
|
| 76 |
+
"stable_amplitude_n": int(stable.sum()),
|
| 77 |
+
"stable_amplitude_median_delta_pca": float(np.median(y[stable])),
|
| 78 |
+
"stable_amplitude_pca_improved_fraction": float(np.mean(y[stable] < 0)),
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def main():
|
| 83 |
+
parser = argparse.ArgumentParser()
|
| 84 |
+
parser.add_argument("--epoch10", type=Path, required=True)
|
| 85 |
+
parser.add_argument("--epoch30", type=Path, required=True)
|
| 86 |
+
parser.add_argument("--epoch40", type=Path, required=True)
|
| 87 |
+
parser.add_argument("--output_dir", type=Path, required=True)
|
| 88 |
+
args = parser.parse_args()
|
| 89 |
+
|
| 90 |
+
frames = [
|
| 91 |
+
load_analysis(args.epoch10, "epoch10"),
|
| 92 |
+
load_analysis(args.epoch30, "epoch30"),
|
| 93 |
+
load_analysis(args.epoch40, "epoch40"),
|
| 94 |
+
]
|
| 95 |
+
merged = frames[0]
|
| 96 |
+
for frame in frames[1:]:
|
| 97 |
+
merged = merged.merge(frame, on="pdb_name", how="inner", validate="one_to_one")
|
| 98 |
+
|
| 99 |
+
for end in ("epoch30", "epoch40"):
|
| 100 |
+
merged[f"{end}_minus_epoch10_pca_w2"] = (
|
| 101 |
+
merged[f"{end}_pca_w2"] - merged["epoch10_pca_w2"]
|
| 102 |
+
)
|
| 103 |
+
merged[f"{end}_minus_epoch10_model_pairwise"] = (
|
| 104 |
+
merged[f"{end}_model_pairwise"] - merged["epoch10_model_pairwise"]
|
| 105 |
+
)
|
| 106 |
+
merged[f"{end}_minus_epoch10_model_rmsf_mean"] = (
|
| 107 |
+
merged[f"{end}_model_rmsf_mean"] - merged["epoch10_model_rmsf_mean"]
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
summaries = pd.DataFrame(
|
| 111 |
+
[
|
| 112 |
+
regression_summary(merged, "epoch10", "epoch30"),
|
| 113 |
+
regression_summary(merged, "epoch10", "epoch40"),
|
| 114 |
+
regression_summary(merged, "epoch30", "epoch40"),
|
| 115 |
+
]
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 119 |
+
merged.to_csv(args.output_dir / "per_protein_pca_contraction.csv", index=False)
|
| 120 |
+
summaries.to_csv(args.output_dir / "pca_contraction_summary.csv", index=False)
|
| 121 |
+
|
| 122 |
+
delta_pca = merged["epoch40_minus_epoch10_pca_w2"].abs()
|
| 123 |
+
delta_amp = merged["epoch40_minus_epoch10_model_pairwise"].abs()
|
| 124 |
+
stable = delta_amp <= delta_amp.quantile(0.25)
|
| 125 |
+
informative = merged.loc[
|
| 126 |
+
stable & (merged["epoch40_minus_epoch10_pca_w2"] < 0)
|
| 127 |
+
].sort_values("epoch40_minus_epoch10_pca_w2")
|
| 128 |
+
informative.to_csv(
|
| 129 |
+
args.output_dir / "pca_improved_with_stable_pairwise.csv", index=False
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
print(f"proteins: {len(merged)}")
|
| 133 |
+
print("\n=== paired change and amplitude-control summary ===")
|
| 134 |
+
print(summaries.to_string(index=False, float_format=lambda value: f"{value:.4f}"))
|
| 135 |
+
print("\n=== strongest PCA improvements with stable Pairwise amplitude ===")
|
| 136 |
+
columns = [
|
| 137 |
+
"pdb_name",
|
| 138 |
+
"epoch10_pca_w2",
|
| 139 |
+
"epoch40_pca_w2",
|
| 140 |
+
"epoch40_minus_epoch10_pca_w2",
|
| 141 |
+
"epoch10_model_pairwise",
|
| 142 |
+
"epoch40_model_pairwise",
|
| 143 |
+
"epoch40_minus_epoch10_model_pairwise",
|
| 144 |
+
]
|
| 145 |
+
print(informative[columns].head(15).to_string(index=False))
|
| 146 |
+
print(f"\nSaved to: {args.output_dir}")
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
main()
|
bbflow_base/scripts/audit_condition_branch_weights.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def tensor_norm(x):
|
| 8 |
+
x = x.detach().float()
|
| 9 |
+
return {
|
| 10 |
+
"shape": list(x.shape),
|
| 11 |
+
"l2": float(x.norm().cpu()),
|
| 12 |
+
"mean_abs": float(x.abs().mean().cpu()),
|
| 13 |
+
"max_abs": float(x.abs().max().cpu()),
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def main():
|
| 18 |
+
ap = argparse.ArgumentParser()
|
| 19 |
+
ap.add_argument("--ckpt", required=True)
|
| 20 |
+
ap.add_argument("--out", required=True)
|
| 21 |
+
args = ap.parse_args()
|
| 22 |
+
|
| 23 |
+
ckpt = torch.load(args.ckpt, map_location="cpu", weights_only=False)
|
| 24 |
+
sd = ckpt.get("state_dict", ckpt)
|
| 25 |
+
|
| 26 |
+
groups = {
|
| 27 |
+
"unsigned_node_z_node_adapter": ["z_node_adapter"],
|
| 28 |
+
"signed_node_disp_node_adapter": ["disp_node_adapter"],
|
| 29 |
+
"unsigned_edge_z_edge_adapter": ["z_edge_adapter"],
|
| 30 |
+
"signed_edge_disp_edge_adapter": ["disp_edge_adapter"],
|
| 31 |
+
"unsigned_film_mlp": ["film_mlp"],
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
report = {}
|
| 35 |
+
for group, tokens in groups.items():
|
| 36 |
+
items = {}
|
| 37 |
+
for k, v in sd.items():
|
| 38 |
+
if not torch.is_tensor(v):
|
| 39 |
+
continue
|
| 40 |
+
if all(t in k for t in tokens):
|
| 41 |
+
items[k] = tensor_norm(v)
|
| 42 |
+
report[group] = items
|
| 43 |
+
|
| 44 |
+
summary = {}
|
| 45 |
+
for group, items in report.items():
|
| 46 |
+
total_l2_sq = 0.0
|
| 47 |
+
last_layer_l2_sq = 0.0
|
| 48 |
+
n = 0
|
| 49 |
+
for k, stats in items.items():
|
| 50 |
+
total_l2_sq += stats["l2"] ** 2
|
| 51 |
+
n += 1
|
| 52 |
+
if any(s in k for s in ["2.weight", "2.bias", "film_mlp.2.weight", "film_mlp.2.bias"]):
|
| 53 |
+
last_layer_l2_sq += stats["l2"] ** 2
|
| 54 |
+
summary[group] = {
|
| 55 |
+
"num_tensors": n,
|
| 56 |
+
"total_l2": total_l2_sq ** 0.5,
|
| 57 |
+
"last_layer_l2": last_layer_l2_sq ** 0.5,
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
out = Path(args.out)
|
| 61 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 62 |
+
out.write_text(json.dumps({"summary": summary, "details": report}, indent=2), encoding="utf-8")
|
| 63 |
+
|
| 64 |
+
print("===== condition branch weight summary =====")
|
| 65 |
+
print(json.dumps(summary, indent=2))
|
| 66 |
+
print("\nSaved:", out)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
if __name__ == "__main__":
|
| 70 |
+
main()
|
bbflow_base/scripts/audit_condition_forward_paths.py
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Forward audit for signed vs unsigned latent-condition paths.
|
| 3 |
+
|
| 4 |
+
Diagnostic only: no training, no source mutation, no checkpoint mutation.
|
| 5 |
+
|
| 6 |
+
This script uses matched frame pairs and measures, on the same forward batch:
|
| 7 |
+
* unsigned adapter outputs vs signed adapter outputs;
|
| 8 |
+
* cosine between unsigned and signed adapter outputs after projection;
|
| 9 |
+
* FiLM gamma/beta amplitudes, separated;
|
| 10 |
+
* c -> -c effects versus c_a -> c_b effects at final update and pred_trans.
|
| 11 |
+
"""
|
| 12 |
+
import argparse
|
| 13 |
+
import copy
|
| 14 |
+
import json
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import sys
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
import torch
|
| 21 |
+
from omegaconf import OmegaConf
|
| 22 |
+
|
| 23 |
+
REPO_ROOT = Path(__file__).resolve().parents[1]
|
| 24 |
+
if str(REPO_ROOT) not in sys.path:
|
| 25 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 26 |
+
|
| 27 |
+
from bbflow.data.interpolant_bbflow import InterpolantBBFlow
|
| 28 |
+
from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow
|
| 29 |
+
from bbflow.models.bbflow_module import BBFlowModule
|
| 30 |
+
|
| 31 |
+
from scripts.diagnose_condition_interface import (
|
| 32 |
+
frame_indices_for_row,
|
| 33 |
+
mean_disp_from_frames,
|
| 34 |
+
move_item_to_device,
|
| 35 |
+
build_cstar_condition,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_module(ckpt_path, device, num_timesteps=None):
|
| 40 |
+
ckpt_path = Path(ckpt_path)
|
| 41 |
+
cfg_path = ckpt_path.with_name("config.yaml")
|
| 42 |
+
if not cfg_path.exists():
|
| 43 |
+
raise FileNotFoundError(f"Missing checkpoint config: {cfg_path}")
|
| 44 |
+
|
| 45 |
+
infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml")
|
| 46 |
+
ckpt_cfg = OmegaConf.load(cfg_path)
|
| 47 |
+
OmegaConf.set_struct(infer_cfg, False)
|
| 48 |
+
OmegaConf.set_struct(ckpt_cfg, False)
|
| 49 |
+
cfg = OmegaConf.merge(infer_cfg, ckpt_cfg)
|
| 50 |
+
cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior
|
| 51 |
+
cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional
|
| 52 |
+
cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot
|
| 53 |
+
cfg.inference.interpolant.use_tqdm = False
|
| 54 |
+
cfg.model.embed = ckpt_cfg.model.embed
|
| 55 |
+
if num_timesteps is not None:
|
| 56 |
+
cfg.inference.interpolant.rots.num_timesteps = int(num_timesteps)
|
| 57 |
+
cfg.inference.interpolant.trans.num_timesteps = int(num_timesteps)
|
| 58 |
+
|
| 59 |
+
module = BBFlowModule(cfg)
|
| 60 |
+
checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 61 |
+
current = module.state_dict()
|
| 62 |
+
compatible = {
|
| 63 |
+
key: value
|
| 64 |
+
for key, value in checkpoint["state_dict"].items()
|
| 65 |
+
if key in current and current[key].shape == value.shape
|
| 66 |
+
}
|
| 67 |
+
missing, unexpected = module.load_state_dict(compatible, strict=False)
|
| 68 |
+
module.to(device)
|
| 69 |
+
module.eval()
|
| 70 |
+
interpolant = InterpolantBBFlow(cfg.inference.interpolant)
|
| 71 |
+
interpolant.set_device(device)
|
| 72 |
+
module.interpolant = interpolant
|
| 73 |
+
return module, {
|
| 74 |
+
"loaded": len(compatible),
|
| 75 |
+
"missing": len(missing),
|
| 76 |
+
"unexpected": len(unexpected),
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def normalize_csv(df):
|
| 81 |
+
df = df.copy()
|
| 82 |
+
if "name" not in df.columns and "pdb_name" in df.columns:
|
| 83 |
+
df["name"] = df["pdb_name"]
|
| 84 |
+
if "folder" not in df.columns and "pdb_path" in df.columns:
|
| 85 |
+
df["folder"] = df["pdb_path"].map(lambda p: str(Path(str(p)).parent))
|
| 86 |
+
return df
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def clone_condition(condition):
|
| 90 |
+
return {
|
| 91 |
+
key: value.clone() if torch.is_tensor(value) else copy.deepcopy(value)
|
| 92 |
+
for key, value in condition.items()
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def condition_from_coeff(module, prior, coeff, rotmats_eq, res_mask):
|
| 97 |
+
extra = {
|
| 98 |
+
key: prior[key]
|
| 99 |
+
for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"]
|
| 100 |
+
if key in prior
|
| 101 |
+
}
|
| 102 |
+
return module.latent_encoder.condition_from_mode_coefficients(
|
| 103 |
+
prior["u_global"],
|
| 104 |
+
coeff,
|
| 105 |
+
rotmats_eq,
|
| 106 |
+
res_mask,
|
| 107 |
+
extra=extra,
|
| 108 |
+
include_statistics=False,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def masked_mean_abs(tensor, mask=None, edge=False):
|
| 113 |
+
x = tensor.detach().float().abs()
|
| 114 |
+
if mask is None:
|
| 115 |
+
return float(x.mean().cpu().item())
|
| 116 |
+
m = mask.float()
|
| 117 |
+
if edge:
|
| 118 |
+
m = m[:, :, None] * m[:, None, :]
|
| 119 |
+
while m.dim() < x.dim():
|
| 120 |
+
m = m[..., None]
|
| 121 |
+
else:
|
| 122 |
+
while m.dim() < x.dim():
|
| 123 |
+
m = m[..., None]
|
| 124 |
+
return float(((x * m).sum() / m.sum().clamp_min(1.0)).cpu().item())
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def rms(tensor, mask=None, edge=False):
|
| 128 |
+
x = tensor.detach().float().square()
|
| 129 |
+
if mask is None:
|
| 130 |
+
return float(x.mean().sqrt().cpu().item())
|
| 131 |
+
m = mask.float()
|
| 132 |
+
if edge:
|
| 133 |
+
m = m[:, :, None] * m[:, None, :]
|
| 134 |
+
while m.dim() < x.dim():
|
| 135 |
+
m = m[..., None]
|
| 136 |
+
else:
|
| 137 |
+
while m.dim() < x.dim():
|
| 138 |
+
m = m[..., None]
|
| 139 |
+
return float(((x * m).sum() / m.sum().clamp_min(1.0)).sqrt().cpu().item())
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def flat_cosine(a, b, mask=None, edge=False):
|
| 143 |
+
aa = a.detach().float()
|
| 144 |
+
bb = b.detach().float().to(device=aa.device)
|
| 145 |
+
if mask is not None:
|
| 146 |
+
m = mask.float()
|
| 147 |
+
if edge:
|
| 148 |
+
m = m[:, :, None] * m[:, None, :]
|
| 149 |
+
while m.dim() < aa.dim():
|
| 150 |
+
m = m[..., None]
|
| 151 |
+
else:
|
| 152 |
+
while m.dim() < aa.dim():
|
| 153 |
+
m = m[..., None]
|
| 154 |
+
aa = aa * m
|
| 155 |
+
bb = bb * m
|
| 156 |
+
aa = aa.reshape(-1)
|
| 157 |
+
bb = bb.reshape(-1)
|
| 158 |
+
denom = aa.norm().clamp_min(1e-8) * bb.norm().clamp_min(1e-8)
|
| 159 |
+
return float((aa * bb).sum().div(denom).cpu().item())
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def rel_delta(reference, changed, mask=None, edge=False):
|
| 163 |
+
denom = masked_mean_abs(reference, mask=mask, edge=edge)
|
| 164 |
+
delta = masked_mean_abs(changed - reference, mask=mask, edge=edge)
|
| 165 |
+
return float(delta / max(denom, 1e-8))
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def adapter_outputs(module, condition):
|
| 169 |
+
embedder = module.model.embedder
|
| 170 |
+
return {
|
| 171 |
+
"z_node": embedder.z_node_adapter(condition["node_cond"]),
|
| 172 |
+
"disp_node": embedder.disp_node_adapter(condition["disp_node_cond"]),
|
| 173 |
+
"z_edge": embedder.z_edge_adapter(condition["edge_cond"]),
|
| 174 |
+
"disp_edge": embedder.disp_edge_adapter(condition["disp_edge_cond"]),
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def film_outputs(module, condition):
|
| 179 |
+
model = module.model
|
| 180 |
+
if not getattr(model, "inject_film", False):
|
| 181 |
+
return None
|
| 182 |
+
cond = condition["node_cond"]
|
| 183 |
+
gamma_beta = model.film_mlp(cond)
|
| 184 |
+
gamma, beta = torch.chunk(gamma_beta, 2, dim=-1)
|
| 185 |
+
return {"gamma": gamma, "beta": beta}
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def build_forward_batch(module, item, condition, seed):
|
| 189 |
+
device = item["trans_equilibrium"].device
|
| 190 |
+
trans_eq = item["trans_equilibrium"]
|
| 191 |
+
rotmats_eq = item["rotmats_equilibrium"]
|
| 192 |
+
seq = item["seq"]
|
| 193 |
+
res_mask = torch.ones_like(trans_eq[..., 0])
|
| 194 |
+
_, num_res = trans_eq.shape[:2]
|
| 195 |
+
torch.manual_seed(int(seed))
|
| 196 |
+
np.random.seed(int(seed) % (2**32 - 1))
|
| 197 |
+
trans_t, rotmats_t = module.interpolant.sample_from_prior(
|
| 198 |
+
1, int(num_res), trans_eq, rotmats_eq
|
| 199 |
+
)
|
| 200 |
+
return {
|
| 201 |
+
"res_mask": res_mask,
|
| 202 |
+
"trans_equilibrium": trans_eq,
|
| 203 |
+
"rotmats_equilibrium": rotmats_eq,
|
| 204 |
+
"seq": seq,
|
| 205 |
+
"trans_t": trans_t,
|
| 206 |
+
"rotmats_t": rotmats_t,
|
| 207 |
+
"t": torch.full(
|
| 208 |
+
(1, 1),
|
| 209 |
+
module.interpolant._cfg.min_t,
|
| 210 |
+
device=device,
|
| 211 |
+
dtype=trans_eq.dtype,
|
| 212 |
+
),
|
| 213 |
+
"z": condition,
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def run_model_capture(module, base_batch, condition):
|
| 218 |
+
captured = {}
|
| 219 |
+
model = module.model
|
| 220 |
+
last_block = model._gfa_conf.num_blocks - 1
|
| 221 |
+
last_update = model.trunk[f"bb_update_{last_block}"]
|
| 222 |
+
|
| 223 |
+
def pre_hook(_mod, args):
|
| 224 |
+
captured["final_update_node_embed"] = args[0].detach().clone()
|
| 225 |
+
|
| 226 |
+
handle = last_update.register_forward_pre_hook(pre_hook)
|
| 227 |
+
batch = dict(base_batch)
|
| 228 |
+
batch["z"] = condition
|
| 229 |
+
try:
|
| 230 |
+
with torch.no_grad():
|
| 231 |
+
out = model(batch)
|
| 232 |
+
finally:
|
| 233 |
+
handle.remove()
|
| 234 |
+
return {
|
| 235 |
+
"final_update_node_embed": captured["final_update_node_embed"],
|
| 236 |
+
"pred_trans": out["pred_trans"].detach().clone(),
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def summarize_rows(df, value_cols):
|
| 241 |
+
out = {}
|
| 242 |
+
for col in value_cols:
|
| 243 |
+
vals = pd.to_numeric(df[col], errors="coerce").replace([np.inf, -np.inf], np.nan).dropna()
|
| 244 |
+
if len(vals) == 0:
|
| 245 |
+
continue
|
| 246 |
+
out[col] = {
|
| 247 |
+
"n": int(len(vals)),
|
| 248 |
+
"mean": float(vals.mean()),
|
| 249 |
+
"median": float(vals.median()),
|
| 250 |
+
"min": float(vals.min()),
|
| 251 |
+
"max": float(vals.max()),
|
| 252 |
+
}
|
| 253 |
+
return out
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def main():
|
| 257 |
+
ap = argparse.ArgumentParser()
|
| 258 |
+
ap.add_argument("--ckpt_path", required=True)
|
| 259 |
+
ap.add_argument("--csv_path", required=True)
|
| 260 |
+
ap.add_argument("--matched_csv", required=True)
|
| 261 |
+
ap.add_argument("--out_dir", required=True)
|
| 262 |
+
ap.add_argument("--device", default="cuda")
|
| 263 |
+
ap.add_argument("--num_frames", type=int, default=6)
|
| 264 |
+
ap.add_argument("--seed", type=int, default=20260712)
|
| 265 |
+
ap.add_argument("--num_timesteps", type=int, default=20)
|
| 266 |
+
args = ap.parse_args()
|
| 267 |
+
|
| 268 |
+
device = torch.device(args.device if (args.device == "cpu" or torch.cuda.is_available()) else "cpu")
|
| 269 |
+
module, load_info = load_module(args.ckpt_path, device, args.num_timesteps)
|
| 270 |
+
|
| 271 |
+
df = normalize_csv(pd.read_csv(args.csv_path))
|
| 272 |
+
matched = pd.read_csv(args.matched_csv)
|
| 273 |
+
dataset = PDBDatasetBBFlow(df)
|
| 274 |
+
by_name = {str(name): idx for idx, name in enumerate(dataset.pdb_names)}
|
| 275 |
+
|
| 276 |
+
rows = []
|
| 277 |
+
for row_idx, matched_row in matched.iterrows():
|
| 278 |
+
name = str(matched_row["pdb_name"])
|
| 279 |
+
if name not in by_name:
|
| 280 |
+
raise ValueError(f"pdb_name from matched_csv not found in csv_path: {name}")
|
| 281 |
+
protein_idx = by_name[name]
|
| 282 |
+
csv_row = dataset.csv.iloc[protein_idx]
|
| 283 |
+
frame_ids = frame_indices_for_row(csv_row, args.num_frames)
|
| 284 |
+
|
| 285 |
+
a_id = int(matched_row["frame_a"])
|
| 286 |
+
b_id = int(matched_row["frame_b"])
|
| 287 |
+
item_a = move_item_to_device(dataset[(protein_idx, 0, a_id)], device)
|
| 288 |
+
item_b = move_item_to_device(dataset[(protein_idx, 0, b_id)], device)
|
| 289 |
+
res_mask = torch.ones_like(item_a["trans_equilibrium"][..., 0])
|
| 290 |
+
|
| 291 |
+
with torch.no_grad():
|
| 292 |
+
prior, _ = module.latent_encoder.forward_prior(
|
| 293 |
+
item_a["trans_equilibrium"],
|
| 294 |
+
item_a["rotmats_equilibrium"],
|
| 295 |
+
item_a["seq"],
|
| 296 |
+
res_mask,
|
| 297 |
+
)
|
| 298 |
+
mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device)
|
| 299 |
+
cond_a, coeff_a = build_cstar_condition(module, item_a, prior, mean_disp=mean_disp)
|
| 300 |
+
cond_b, coeff_b = build_cstar_condition(module, item_b, prior, mean_disp=mean_disp)
|
| 301 |
+
cond_neg_a = condition_from_coeff(
|
| 302 |
+
module,
|
| 303 |
+
prior,
|
| 304 |
+
-coeff_a,
|
| 305 |
+
item_a["rotmats_equilibrium"],
|
| 306 |
+
res_mask,
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
adapters_a = adapter_outputs(module, cond_a)
|
| 310 |
+
film_a = film_outputs(module, cond_a)
|
| 311 |
+
film_neg_a = film_outputs(module, cond_neg_a)
|
| 312 |
+
film_b = film_outputs(module, cond_b)
|
| 313 |
+
|
| 314 |
+
base_batch = build_forward_batch(module, item_a, cond_a, args.seed + int(row_idx))
|
| 315 |
+
forward_a = run_model_capture(module, base_batch, cond_a)
|
| 316 |
+
forward_neg_a = run_model_capture(module, base_batch, cond_neg_a)
|
| 317 |
+
forward_b = run_model_capture(module, base_batch, cond_b)
|
| 318 |
+
|
| 319 |
+
record = {
|
| 320 |
+
"pdb_name": name,
|
| 321 |
+
"frame_a": a_id,
|
| 322 |
+
"frame_b": b_id,
|
| 323 |
+
"frame_gap": abs(b_id - a_id),
|
| 324 |
+
"num_res": int(item_a["trans_equilibrium"].shape[1]),
|
| 325 |
+
"coeff_cos_ab": flat_cosine(coeff_a, coeff_b),
|
| 326 |
+
"coeff_signflip_frac_ab": float(((coeff_a * coeff_b) < 0).float().mean().detach().cpu().item()),
|
| 327 |
+
"node_unsigned_abs": masked_mean_abs(adapters_a["z_node"], res_mask),
|
| 328 |
+
"node_signed_abs": masked_mean_abs(adapters_a["disp_node"], res_mask),
|
| 329 |
+
"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),
|
| 330 |
+
"node_adapter_cosine": flat_cosine(adapters_a["z_node"], adapters_a["disp_node"], res_mask),
|
| 331 |
+
"edge_unsigned_abs": masked_mean_abs(adapters_a["z_edge"], res_mask, edge=True),
|
| 332 |
+
"edge_signed_abs": masked_mean_abs(adapters_a["disp_edge"], res_mask, edge=True),
|
| 333 |
+
"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),
|
| 334 |
+
"edge_adapter_cosine": flat_cosine(adapters_a["z_edge"], adapters_a["disp_edge"], res_mask, edge=True),
|
| 335 |
+
"final_embed_rel_delta_signflip": rel_delta(
|
| 336 |
+
forward_a["final_update_node_embed"], forward_neg_a["final_update_node_embed"], res_mask
|
| 337 |
+
),
|
| 338 |
+
"final_embed_rel_delta_ab": rel_delta(
|
| 339 |
+
forward_a["final_update_node_embed"], forward_b["final_update_node_embed"], res_mask
|
| 340 |
+
),
|
| 341 |
+
"pred_trans_rel_delta_signflip": rel_delta(forward_a["pred_trans"], forward_neg_a["pred_trans"], res_mask),
|
| 342 |
+
"pred_trans_rel_delta_ab": rel_delta(forward_a["pred_trans"], forward_b["pred_trans"], res_mask),
|
| 343 |
+
"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),
|
| 344 |
+
"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),
|
| 345 |
+
}
|
| 346 |
+
if film_a is not None:
|
| 347 |
+
for key in ["gamma", "beta"]:
|
| 348 |
+
record[f"film_{key}_abs"] = masked_mean_abs(film_a[key], res_mask)
|
| 349 |
+
record[f"film_{key}_rms"] = rms(film_a[key], res_mask)
|
| 350 |
+
record[f"film_{key}_rel_delta_signflip"] = rel_delta(film_a[key], film_neg_a[key], res_mask)
|
| 351 |
+
record[f"film_{key}_rel_delta_ab"] = rel_delta(film_a[key], film_b[key], res_mask)
|
| 352 |
+
rows.append(record)
|
| 353 |
+
|
| 354 |
+
result = pd.DataFrame(rows)
|
| 355 |
+
out_dir = Path(args.out_dir)
|
| 356 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 357 |
+
result.to_csv(out_dir / "condition_forward_audit_rows.csv", index=False)
|
| 358 |
+
|
| 359 |
+
value_cols = [
|
| 360 |
+
"node_unsigned_abs",
|
| 361 |
+
"node_signed_abs",
|
| 362 |
+
"node_signed_over_unsigned",
|
| 363 |
+
"node_adapter_cosine",
|
| 364 |
+
"edge_unsigned_abs",
|
| 365 |
+
"edge_signed_abs",
|
| 366 |
+
"edge_signed_over_unsigned",
|
| 367 |
+
"edge_adapter_cosine",
|
| 368 |
+
"film_gamma_abs",
|
| 369 |
+
"film_gamma_rms",
|
| 370 |
+
"film_gamma_rel_delta_signflip",
|
| 371 |
+
"film_gamma_rel_delta_ab",
|
| 372 |
+
"film_beta_abs",
|
| 373 |
+
"film_beta_rms",
|
| 374 |
+
"film_beta_rel_delta_signflip",
|
| 375 |
+
"film_beta_rel_delta_ab",
|
| 376 |
+
"final_embed_rel_delta_signflip",
|
| 377 |
+
"final_embed_rel_delta_ab",
|
| 378 |
+
"final_embed_signflip_over_ab",
|
| 379 |
+
"pred_trans_rel_delta_signflip",
|
| 380 |
+
"pred_trans_rel_delta_ab",
|
| 381 |
+
"pred_trans_signflip_over_ab",
|
| 382 |
+
]
|
| 383 |
+
value_cols = [c for c in value_cols if c in result.columns]
|
| 384 |
+
summary = {
|
| 385 |
+
"load_info": load_info,
|
| 386 |
+
"n": int(len(result)),
|
| 387 |
+
"ckpt_path": str(args.ckpt_path),
|
| 388 |
+
"matched_csv": str(args.matched_csv),
|
| 389 |
+
"metrics": summarize_rows(result, value_cols),
|
| 390 |
+
}
|
| 391 |
+
(out_dir / "condition_forward_audit_summary.json").write_text(
|
| 392 |
+
json.dumps(summary, indent=2),
|
| 393 |
+
encoding="utf-8",
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
compact_cols = [
|
| 397 |
+
"node_signed_over_unsigned",
|
| 398 |
+
"node_adapter_cosine",
|
| 399 |
+
"edge_signed_over_unsigned",
|
| 400 |
+
"edge_adapter_cosine",
|
| 401 |
+
"film_gamma_abs",
|
| 402 |
+
"film_beta_abs",
|
| 403 |
+
"film_gamma_rel_delta_signflip",
|
| 404 |
+
"film_gamma_rel_delta_ab",
|
| 405 |
+
"film_beta_rel_delta_signflip",
|
| 406 |
+
"film_beta_rel_delta_ab",
|
| 407 |
+
"final_embed_signflip_over_ab",
|
| 408 |
+
"pred_trans_signflip_over_ab",
|
| 409 |
+
]
|
| 410 |
+
compact_cols = [c for c in compact_cols if c in result.columns]
|
| 411 |
+
compact = result[compact_cols].agg(["mean", "median", "min", "max"]).T
|
| 412 |
+
compact.to_csv(out_dir / "condition_forward_audit_compact.csv")
|
| 413 |
+
|
| 414 |
+
print("===== forward audit compact =====")
|
| 415 |
+
print(compact.to_string())
|
| 416 |
+
print("\n===== key interpretation helpers =====")
|
| 417 |
+
print(json.dumps({
|
| 418 |
+
"n": int(len(result)),
|
| 419 |
+
"film_unsigned_expected": "film_*_rel_delta_signflip should be 0 or near 0 because FiLM sees node_cond=|c|",
|
| 420 |
+
"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",
|
| 421 |
+
"adapter_cosine": "high positive cosine means signed and unsigned adapter outputs are aligned/redundant after projection",
|
| 422 |
+
}, indent=2))
|
| 423 |
+
print("\nSaved:", out_dir)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
if __name__ == "__main__":
|
| 427 |
+
main()
|
bbflow_base/scripts/audit_condition_sign_loss.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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Path
|
| 7 |
+
|
| 8 |
+
import mdtraj
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import torch
|
| 12 |
+
from omegaconf import OmegaConf
|
| 13 |
+
|
| 14 |
+
REPO_ROOT = Path(__file__).resolve().parents[1]
|
| 15 |
+
if str(REPO_ROOT) not in sys.path:
|
| 16 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 17 |
+
|
| 18 |
+
from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow
|
| 19 |
+
from bbflow.models.bbflow_module import BBFlowModule
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def normalize_csv(csv_path):
|
| 23 |
+
df = pd.read_csv(csv_path)
|
| 24 |
+
if "folder" not in df.columns:
|
| 25 |
+
if "pdb_path" not in df.columns:
|
| 26 |
+
raise RuntimeError(f"{csv_path} has neither folder nor pdb_path")
|
| 27 |
+
df = df.copy()
|
| 28 |
+
df["folder"] = df["pdb_path"].map(lambda x: str(Path(str(x)).parent))
|
| 29 |
+
return df
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def load_module(ckpt_path, device):
|
| 33 |
+
ckpt_path = Path(ckpt_path)
|
| 34 |
+
cfg_path = ckpt_path.with_name("config.yaml")
|
| 35 |
+
if not cfg_path.exists():
|
| 36 |
+
raise FileNotFoundError(f"Missing config next to checkpoint: {cfg_path}")
|
| 37 |
+
|
| 38 |
+
infer_cfg = OmegaConf.load(REPO_ROOT / "configs" / "inference.yaml")
|
| 39 |
+
ckpt_cfg = OmegaConf.load(cfg_path)
|
| 40 |
+
OmegaConf.set_struct(infer_cfg, False)
|
| 41 |
+
OmegaConf.set_struct(ckpt_cfg, False)
|
| 42 |
+
cfg = OmegaConf.merge(infer_cfg, ckpt_cfg)
|
| 43 |
+
cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior
|
| 44 |
+
cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional
|
| 45 |
+
cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot
|
| 46 |
+
cfg.inference.interpolant.use_tqdm = False
|
| 47 |
+
cfg.model.embed = ckpt_cfg.model.embed
|
| 48 |
+
|
| 49 |
+
module = BBFlowModule(cfg)
|
| 50 |
+
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 51 |
+
current = module.state_dict()
|
| 52 |
+
compatible = {
|
| 53 |
+
k: v for k, v in ckpt["state_dict"].items()
|
| 54 |
+
if k in current and current[k].shape == v.shape
|
| 55 |
+
}
|
| 56 |
+
module.load_state_dict(compatible, strict=False)
|
| 57 |
+
module.to(device)
|
| 58 |
+
module.eval()
|
| 59 |
+
return module
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def infer_num_frames(row):
|
| 63 |
+
for key in ["num_conformations", "num_frames", "n_frames", "traj_num_frames"]:
|
| 64 |
+
if key in row and pd.notna(row[key]):
|
| 65 |
+
return int(row[key])
|
| 66 |
+
name = str(row["name"])
|
| 67 |
+
folder = Path(str(row["folder"]))
|
| 68 |
+
xtc = folder / f"{name}_R1.xtc"
|
| 69 |
+
if not xtc.exists():
|
| 70 |
+
raise FileNotFoundError(f"Missing trajectory: {xtc}")
|
| 71 |
+
with mdtraj.open(str(xtc)) as handle:
|
| 72 |
+
return int(handle.n_frames if hasattr(handle, "n_frames") else len(handle))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def move_item(item, device):
|
| 76 |
+
out = {}
|
| 77 |
+
for k, v in item.items():
|
| 78 |
+
out[k] = v[None].to(device) if torch.is_tensor(v) else v
|
| 79 |
+
return out
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device):
|
| 83 |
+
disps = []
|
| 84 |
+
for fid in frame_ids:
|
| 85 |
+
item = move_item(dataset[(protein_idx, 0, int(fid))], device)
|
| 86 |
+
mask = torch.ones_like(item["trans_equilibrium"][..., 0])
|
| 87 |
+
disp = module.latent_encoder.relative_displacement(
|
| 88 |
+
item["trans_1"].float(),
|
| 89 |
+
item["trans_equilibrium"].float(),
|
| 90 |
+
mask,
|
| 91 |
+
)
|
| 92 |
+
disps.append(disp)
|
| 93 |
+
return torch.cat(disps, dim=0).mean(dim=0, keepdim=True)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def coeff_for_frame(module, dataset, protein_idx, frame_id, prior, mean_disp, device):
|
| 97 |
+
item = move_item(dataset[(protein_idx, 0, int(frame_id))], device)
|
| 98 |
+
cond, coeff = module.latent_encoder.frame_condition_from_projection(
|
| 99 |
+
item["trans_1"],
|
| 100 |
+
item["trans_equilibrium"],
|
| 101 |
+
item["rotmats_equilibrium"],
|
| 102 |
+
torch.ones_like(item["trans_equilibrium"][..., 0]),
|
| 103 |
+
prior,
|
| 104 |
+
mean_disp=mean_disp,
|
| 105 |
+
)
|
| 106 |
+
return cond, coeff.detach().float()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def rel_l2(a, b):
|
| 110 |
+
a = a.detach().float()
|
| 111 |
+
b = b.detach().float().to(a.device)
|
| 112 |
+
return float(((a - b).norm() / a.norm().clamp_min(1e-8)).detach().cpu())
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def cosine(a, b):
|
| 116 |
+
a = a.detach().float().reshape(-1)
|
| 117 |
+
b = b.detach().float().reshape(-1).to(a.device)
|
| 118 |
+
return float(((a * b).sum() / (a.norm().clamp_min(1e-8) * b.norm().clamp_min(1e-8))).detach().cpu())
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def sign_flip_fraction(a, b):
|
| 122 |
+
a = a.detach().float().reshape(-1)
|
| 123 |
+
b = b.detach().float().reshape(-1).to(a.device)
|
| 124 |
+
valid = (a.abs() > 1e-8) & (b.abs() > 1e-8)
|
| 125 |
+
if valid.sum() == 0:
|
| 126 |
+
return float("nan")
|
| 127 |
+
return float(((a[valid] * b[valid]) < 0).float().mean().detach().cpu())
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def condition_for_coeff(module, prior, coeff, item):
|
| 131 |
+
return module.latent_encoder.condition_from_mode_coefficients(
|
| 132 |
+
prior["u_global"],
|
| 133 |
+
coeff,
|
| 134 |
+
item["rotmats_equilibrium"],
|
| 135 |
+
torch.ones_like(item["trans_equilibrium"][..., 0]),
|
| 136 |
+
extra={
|
| 137 |
+
key: prior[key]
|
| 138 |
+
for key in ["mixture_logits", "mixture_log_probs", "mixture_mu", "mixture_scale_tril"]
|
| 139 |
+
if key in prior
|
| 140 |
+
},
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def selected_rows_from_matched(matched_csv, dataset):
|
| 145 |
+
matched = pd.read_csv(matched_csv)
|
| 146 |
+
by_name = {str(name): i for i, name in enumerate(dataset.pdb_names)}
|
| 147 |
+
rows = []
|
| 148 |
+
for _, r in matched.iterrows():
|
| 149 |
+
name = str(r["pdb_name"])
|
| 150 |
+
if name not in by_name:
|
| 151 |
+
continue
|
| 152 |
+
if "frame_a" not in r or "frame_b" not in r:
|
| 153 |
+
raise RuntimeError("matched_csv must contain frame_a and frame_b columns")
|
| 154 |
+
rows.append((by_name[name], r))
|
| 155 |
+
return rows
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def main():
|
| 159 |
+
ap = argparse.ArgumentParser()
|
| 160 |
+
ap.add_argument("--ckpt_path", required=True)
|
| 161 |
+
ap.add_argument("--csv_path", required=True)
|
| 162 |
+
ap.add_argument("--matched_csv", required=True)
|
| 163 |
+
ap.add_argument("--out_dir", required=True)
|
| 164 |
+
ap.add_argument("--device", default="cuda")
|
| 165 |
+
ap.add_argument("--num_mean_frames", type=int, default=6)
|
| 166 |
+
args = ap.parse_args()
|
| 167 |
+
|
| 168 |
+
out_dir = Path(args.out_dir)
|
| 169 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 170 |
+
|
| 171 |
+
device = torch.device(args.device if args.device.startswith("cuda") and torch.cuda.is_available() else "cpu")
|
| 172 |
+
module = load_module(args.ckpt_path, device)
|
| 173 |
+
|
| 174 |
+
df = normalize_csv(args.csv_path)
|
| 175 |
+
dataset = PDBDatasetBBFlow(csv=df)
|
| 176 |
+
|
| 177 |
+
matched_rows = selected_rows_from_matched(args.matched_csv, dataset)
|
| 178 |
+
print(f"[audit] matched rows loaded: {len(matched_rows)}", flush=True)
|
| 179 |
+
|
| 180 |
+
rows = []
|
| 181 |
+
|
| 182 |
+
with torch.no_grad():
|
| 183 |
+
for protein_idx, matched in matched_rows:
|
| 184 |
+
meta = dataset.csv.iloc[protein_idx]
|
| 185 |
+
name = str(meta["name"])
|
| 186 |
+
total = infer_num_frames(meta)
|
| 187 |
+
|
| 188 |
+
# Reconstruct the same mean-disp convention used by earlier diagnostics:
|
| 189 |
+
# spread frames across trajectory. This is only for aggregate testing.
|
| 190 |
+
frame_grid = sorted(set(np.linspace(0, total - 1, args.num_mean_frames, dtype=int).tolist()))
|
| 191 |
+
frame_a = int(matched["frame_a"])
|
| 192 |
+
frame_b = int(matched["frame_b"])
|
| 193 |
+
for fid in [frame_a, frame_b]:
|
| 194 |
+
if fid not in frame_grid:
|
| 195 |
+
frame_grid.append(fid)
|
| 196 |
+
frame_grid = sorted(set(frame_grid))
|
| 197 |
+
|
| 198 |
+
eq_item = move_item(dataset[(protein_idx, 0, frame_grid[0])], device)
|
| 199 |
+
mask = torch.ones_like(eq_item["trans_equilibrium"][..., 0])
|
| 200 |
+
prior, _ = module.latent_encoder.forward_prior(
|
| 201 |
+
eq_item["trans_equilibrium"],
|
| 202 |
+
eq_item["rotmats_equilibrium"],
|
| 203 |
+
eq_item["seq"],
|
| 204 |
+
mask,
|
| 205 |
+
)
|
| 206 |
+
mean_disp = mean_disp_from_frames(module, dataset, protein_idx, frame_grid, device)
|
| 207 |
+
|
| 208 |
+
cond_a, coeff_a = coeff_for_frame(module, dataset, protein_idx, frame_a, prior, mean_disp, device)
|
| 209 |
+
cond_b, coeff_b = coeff_for_frame(module, dataset, protein_idx, frame_b, prior, mean_disp, device)
|
| 210 |
+
|
| 211 |
+
# Exact sign-flip audit on condition tensors for coeff_a vs -coeff_a.
|
| 212 |
+
cond_pos = condition_for_coeff(module, prior, coeff_a, eq_item)
|
| 213 |
+
cond_neg = condition_for_coeff(module, prior, -coeff_a, eq_item)
|
| 214 |
+
|
| 215 |
+
# Direct a-vs-b condition distance.
|
| 216 |
+
even_keys = ["node_cond", "edge_cond", "disp_edge_cond"]
|
| 217 |
+
odd_keys = ["disp_node_cond"]
|
| 218 |
+
|
| 219 |
+
row = {
|
| 220 |
+
"pdb_name": name,
|
| 221 |
+
"frame_a": frame_a,
|
| 222 |
+
"frame_b": frame_b,
|
| 223 |
+
"coeff_cos_ab": cosine(coeff_a, coeff_b),
|
| 224 |
+
"coeff_sign_flip_frac_ab": sign_flip_fraction(coeff_a, coeff_b),
|
| 225 |
+
"coeff_norm_ratio_b_over_a": float((coeff_b.norm() / coeff_a.norm().clamp_min(1e-8)).detach().cpu()),
|
| 226 |
+
"a_condition_correct_fraction": float(matched.get("a_condition_correct_fraction", float("nan"))),
|
| 227 |
+
"b_condition_correct_fraction": float(matched.get("b_condition_correct_fraction", float("nan"))),
|
| 228 |
+
"mean_correct_fraction": float(matched.get("mean_correct_fraction", float("nan"))),
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
for key in even_keys + odd_keys:
|
| 232 |
+
row[f"flip_rel_l2_{key}"] = rel_l2(cond_pos[key], cond_neg[key])
|
| 233 |
+
row[f"ab_rel_l2_{key}"] = rel_l2(cond_a[key], cond_b[key])
|
| 234 |
+
|
| 235 |
+
rows.append(row)
|
| 236 |
+
print(f"[audit] {name} done", flush=True)
|
| 237 |
+
|
| 238 |
+
result = pd.DataFrame(rows)
|
| 239 |
+
result.to_csv(out_dir / "condition_sign_loss_audit.csv", index=False)
|
| 240 |
+
|
| 241 |
+
summary = {
|
| 242 |
+
"n": int(len(result)),
|
| 243 |
+
"coeff_cos_ab_mean": float(result["coeff_cos_ab"].mean()),
|
| 244 |
+
"coeff_cos_ab_median": float(result["coeff_cos_ab"].median()),
|
| 245 |
+
"coeff_sign_flip_frac_mean": float(result["coeff_sign_flip_frac_ab"].mean()),
|
| 246 |
+
"b_correct_mean": float(result["b_condition_correct_fraction"].mean()),
|
| 247 |
+
"a_correct_mean": float(result["a_condition_correct_fraction"].mean()),
|
| 248 |
+
"mean_correct_mean": float(result["mean_correct_fraction"].mean()),
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
# Static exactness: c vs -c should leave even paths almost unchanged and flip linear path.
|
| 252 |
+
for key in ["node_cond", "edge_cond", "disp_edge_cond", "disp_node_cond"]:
|
| 253 |
+
summary[f"flip_rel_l2_{key}_mean"] = float(result[f"flip_rel_l2_{key}"].mean())
|
| 254 |
+
summary[f"flip_rel_l2_{key}_median"] = float(result[f"flip_rel_l2_{key}"].median())
|
| 255 |
+
|
| 256 |
+
# Correlations. No per-protein story, only aggregate statistics.
|
| 257 |
+
corr_cols = [
|
| 258 |
+
"b_condition_correct_fraction",
|
| 259 |
+
"a_condition_correct_fraction",
|
| 260 |
+
"mean_correct_fraction",
|
| 261 |
+
]
|
| 262 |
+
for y in corr_cols:
|
| 263 |
+
valid = result[["coeff_cos_ab", "coeff_sign_flip_frac_ab", y]].dropna()
|
| 264 |
+
if len(valid) >= 3:
|
| 265 |
+
summary[f"pearson_coeff_cos_vs_{y}"] = float(valid["coeff_cos_ab"].corr(valid[y], method="pearson"))
|
| 266 |
+
summary[f"spearman_coeff_cos_vs_{y}"] = float(valid["coeff_cos_ab"].corr(valid[y], method="spearman"))
|
| 267 |
+
summary[f"pearson_signflip_vs_{y}"] = float(valid["coeff_sign_flip_frac_ab"].corr(valid[y], method="pearson"))
|
| 268 |
+
summary[f"spearman_signflip_vs_{y}"] = float(valid["coeff_sign_flip_frac_ab"].corr(valid[y], method="spearman"))
|
| 269 |
+
|
| 270 |
+
# Distribution bins, still aggregate.
|
| 271 |
+
bins = [-1.01, -0.5, 0.0, 0.5, 1.01]
|
| 272 |
+
labels = ["cos<-0.5", "-0.5<=cos<0", "0<=cos<0.5", "cos>=0.5"]
|
| 273 |
+
result["coeff_cos_bin"] = pd.cut(result["coeff_cos_ab"], bins=bins, labels=labels)
|
| 274 |
+
grouped = result.groupby("coeff_cos_bin", observed=False).agg(
|
| 275 |
+
n=("pdb_name", "count"),
|
| 276 |
+
b_correct_mean=("b_condition_correct_fraction", "mean"),
|
| 277 |
+
a_correct_mean=("a_condition_correct_fraction", "mean"),
|
| 278 |
+
mean_correct=("mean_correct_fraction", "mean"),
|
| 279 |
+
signflip_mean=("coeff_sign_flip_frac_ab", "mean"),
|
| 280 |
+
).reset_index()
|
| 281 |
+
grouped.to_csv(out_dir / "condition_sign_loss_bins.csv", index=False)
|
| 282 |
+
|
| 283 |
+
(out_dir / "condition_sign_loss_summary.json").write_text(
|
| 284 |
+
json.dumps(summary, indent=2, sort_keys=True) + "\n"
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
print("\n=== condition sign-loss summary ===")
|
| 288 |
+
print(json.dumps(summary, indent=2, sort_keys=True))
|
| 289 |
+
print("\n=== coeff cosine bins ===")
|
| 290 |
+
print(grouped.to_string(index=False))
|
| 291 |
+
print("\nSaved:", out_dir)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
if __name__ == "__main__":
|
| 295 |
+
main()
|
bbflow_base/scripts/audit_condition_sign_loss_min.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 6 |
+
|
| 7 |
+
import mdtraj
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import torch
|
| 11 |
+
from omegaconf import OmegaConf
|
| 12 |
+
|
| 13 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 14 |
+
sys.path.insert(0, str(ROOT))
|
| 15 |
+
|
| 16 |
+
from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlow
|
| 17 |
+
from bbflow.models.bbflow_module import BBFlowModule
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def normalize_csv(path):
|
| 21 |
+
df = pd.read_csv(path)
|
| 22 |
+
if "folder" not in df.columns:
|
| 23 |
+
if "pdb_path" not in df.columns:
|
| 24 |
+
raise RuntimeError(f"{path} has neither folder nor pdb_path column")
|
| 25 |
+
df = df.copy()
|
| 26 |
+
df["folder"] = df["pdb_path"].map(lambda x: str(Path(str(x)).parent))
|
| 27 |
+
return df
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def load_module(ckpt_path, device):
|
| 31 |
+
ckpt_path = Path(ckpt_path)
|
| 32 |
+
infer_cfg = OmegaConf.load(ROOT / "configs" / "inference.yaml")
|
| 33 |
+
ckpt_cfg = OmegaConf.load(ckpt_path.with_name("config.yaml"))
|
| 34 |
+
|
| 35 |
+
OmegaConf.set_struct(infer_cfg, False)
|
| 36 |
+
OmegaConf.set_struct(ckpt_cfg, False)
|
| 37 |
+
|
| 38 |
+
cfg = OmegaConf.merge(infer_cfg, ckpt_cfg)
|
| 39 |
+
cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior
|
| 40 |
+
cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional
|
| 41 |
+
cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot
|
| 42 |
+
cfg.model.embed = ckpt_cfg.model.embed
|
| 43 |
+
|
| 44 |
+
module = BBFlowModule(cfg)
|
| 45 |
+
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 46 |
+
|
| 47 |
+
current = module.state_dict()
|
| 48 |
+
compatible = {
|
| 49 |
+
key: value
|
| 50 |
+
for key, value in ckpt["state_dict"].items()
|
| 51 |
+
if key in current and current[key].shape == value.shape
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
module.load_state_dict(compatible, strict=False)
|
| 55 |
+
module.to(device)
|
| 56 |
+
module.eval()
|
| 57 |
+
return module
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def move_item(item, device):
|
| 61 |
+
out = {}
|
| 62 |
+
for key, value in item.items():
|
| 63 |
+
if torch.is_tensor(value):
|
| 64 |
+
out[key] = value[None].to(device)
|
| 65 |
+
else:
|
| 66 |
+
out[key] = value
|
| 67 |
+
return out
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def infer_num_frames(row):
|
| 71 |
+
name = str(row["name"])
|
| 72 |
+
folder = Path(str(row["folder"]))
|
| 73 |
+
xtc = folder / f"{name}_R1.xtc"
|
| 74 |
+
if not xtc.exists():
|
| 75 |
+
raise FileNotFoundError(f"Missing trajectory: {xtc}")
|
| 76 |
+
|
| 77 |
+
with mdtraj.open(str(xtc)) as handle:
|
| 78 |
+
return int(handle.n_frames if hasattr(handle, "n_frames") else len(handle))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def mean_disp_from_frames(module, dataset, protein_idx, frame_ids, device):
|
| 82 |
+
disps = []
|
| 83 |
+
for frame_id in frame_ids:
|
| 84 |
+
item = move_item(dataset[(protein_idx, 0, int(frame_id))], device)
|
| 85 |
+
mask = torch.ones_like(item["trans_equilibrium"][..., 0])
|
| 86 |
+
disp = module.latent_encoder.relative_displacement(
|
| 87 |
+
item["trans_1"].float(),
|
| 88 |
+
item["trans_equilibrium"].float(),
|
| 89 |
+
mask,
|
| 90 |
+
)
|
| 91 |
+
disps.append(disp)
|
| 92 |
+
|
| 93 |
+
return torch.cat(disps, dim=0).mean(dim=0, keepdim=True)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def coeff_for_frame(module, dataset, protein_idx, frame_id, prior, mean_disp, device):
|
| 97 |
+
item = move_item(dataset[(protein_idx, 0, int(frame_id))], device)
|
| 98 |
+
|
| 99 |
+
condition, coeff = module.latent_encoder.frame_condition_from_projection(
|
| 100 |
+
item["trans_1"],
|
| 101 |
+
item["trans_equilibrium"],
|
| 102 |
+
item["rotmats_equilibrium"],
|
| 103 |
+
torch.ones_like(item["trans_equilibrium"][..., 0]),
|
| 104 |
+
prior,
|
| 105 |
+
mean_disp=mean_disp,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
return item, condition, coeff.detach().float()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def condition_for_coeff(module, prior, coeff, item):
|
| 112 |
+
extra = {
|
| 113 |
+
key: prior[key]
|
| 114 |
+
for key in [
|
| 115 |
+
"mixture_logits",
|
| 116 |
+
"mixture_log_probs",
|
| 117 |
+
"mixture_mu",
|
| 118 |
+
"mixture_scale_tril",
|
| 119 |
+
]
|
| 120 |
+
if key in prior
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
return module.latent_encoder.condition_from_mode_coefficients(
|
| 124 |
+
prior["u_global"],
|
| 125 |
+
coeff,
|
| 126 |
+
item["rotmats_equilibrium"],
|
| 127 |
+
torch.ones_like(item["trans_equilibrium"][..., 0]),
|
| 128 |
+
extra=extra,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def rel_l2(a, b):
|
| 133 |
+
a = a.detach().float()
|
| 134 |
+
b = b.detach().float().to(a.device)
|
| 135 |
+
return float(((a - b).norm() / a.norm().clamp_min(1e-8)).detach().cpu())
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def cosine(a, b):
|
| 139 |
+
a = a.detach().float().reshape(-1)
|
| 140 |
+
b = b.detach().float().reshape(-1).to(a.device)
|
| 141 |
+
denom = a.norm().clamp_min(1e-8) * b.norm().clamp_min(1e-8)
|
| 142 |
+
return float(((a * b).sum() / denom).detach().cpu())
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def signflip_fraction(a, b):
|
| 146 |
+
a = a.detach().float().reshape(-1)
|
| 147 |
+
b = b.detach().float().reshape(-1).to(a.device)
|
| 148 |
+
|
| 149 |
+
valid = (a.abs() > 1e-8) & (b.abs() > 1e-8)
|
| 150 |
+
if valid.sum() == 0:
|
| 151 |
+
return float("nan")
|
| 152 |
+
|
| 153 |
+
return float(((a[valid] * b[valid]) < 0).float().mean().detach().cpu())
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def main():
|
| 157 |
+
parser = argparse.ArgumentParser()
|
| 158 |
+
parser.add_argument("--ckpt_path", required=True)
|
| 159 |
+
parser.add_argument("--csv_path", required=True)
|
| 160 |
+
parser.add_argument("--matched_csv", required=True)
|
| 161 |
+
parser.add_argument("--out_dir", required=True)
|
| 162 |
+
parser.add_argument("--device", default="cuda")
|
| 163 |
+
args = parser.parse_args()
|
| 164 |
+
|
| 165 |
+
out_dir = Path(args.out_dir)
|
| 166 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 167 |
+
|
| 168 |
+
device = torch.device(
|
| 169 |
+
args.device
|
| 170 |
+
if args.device.startswith("cuda") and torch.cuda.is_available()
|
| 171 |
+
else "cpu"
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
module = load_module(args.ckpt_path, device)
|
| 175 |
+
|
| 176 |
+
metadata = normalize_csv(args.csv_path)
|
| 177 |
+
dataset = PDBDatasetBBFlow(csv=metadata)
|
| 178 |
+
|
| 179 |
+
matched = pd.read_csv(args.matched_csv)
|
| 180 |
+
name_to_idx = {str(name): idx for idx, name in enumerate(dataset.pdb_names)}
|
| 181 |
+
|
| 182 |
+
rows = []
|
| 183 |
+
|
| 184 |
+
with torch.no_grad():
|
| 185 |
+
for _, row in matched.iterrows():
|
| 186 |
+
pdb_name = str(row["pdb_name"])
|
| 187 |
+
if pdb_name not in name_to_idx:
|
| 188 |
+
continue
|
| 189 |
+
|
| 190 |
+
protein_idx = name_to_idx[pdb_name]
|
| 191 |
+
total_frames = infer_num_frames(dataset.csv.iloc[protein_idx])
|
| 192 |
+
|
| 193 |
+
frame_a = int(row["frame_a"])
|
| 194 |
+
frame_b = int(row["frame_b"])
|
| 195 |
+
|
| 196 |
+
frame_grid = np.linspace(0, total_frames - 1, 6, dtype=int).tolist()
|
| 197 |
+
frame_grid = sorted(set(frame_grid + [frame_a, frame_b]))
|
| 198 |
+
|
| 199 |
+
eq_item = move_item(dataset[(protein_idx, 0, int(frame_grid[0]))], device)
|
| 200 |
+
mask = torch.ones_like(eq_item["trans_equilibrium"][..., 0])
|
| 201 |
+
|
| 202 |
+
prior, _ = module.latent_encoder.forward_prior(
|
| 203 |
+
eq_item["trans_equilibrium"],
|
| 204 |
+
eq_item["rotmats_equilibrium"],
|
| 205 |
+
eq_item["seq"],
|
| 206 |
+
mask,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
mean_disp = mean_disp_from_frames(
|
| 210 |
+
module,
|
| 211 |
+
dataset,
|
| 212 |
+
protein_idx,
|
| 213 |
+
frame_grid,
|
| 214 |
+
device,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
item_a, cond_a, coeff_a = coeff_for_frame(
|
| 218 |
+
module,
|
| 219 |
+
dataset,
|
| 220 |
+
protein_idx,
|
| 221 |
+
frame_a,
|
| 222 |
+
prior,
|
| 223 |
+
mean_disp,
|
| 224 |
+
device,
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
_, cond_b, coeff_b = coeff_for_frame(
|
| 228 |
+
module,
|
| 229 |
+
dataset,
|
| 230 |
+
protein_idx,
|
| 231 |
+
frame_b,
|
| 232 |
+
prior,
|
| 233 |
+
mean_disp,
|
| 234 |
+
device,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
cond_pos = condition_for_coeff(module, prior, coeff_a, item_a)
|
| 238 |
+
cond_neg = condition_for_coeff(module, prior, -coeff_a, item_a)
|
| 239 |
+
|
| 240 |
+
audit_row = {
|
| 241 |
+
"pdb_name": pdb_name,
|
| 242 |
+
"frame_a": frame_a,
|
| 243 |
+
"frame_b": frame_b,
|
| 244 |
+
"coeff_cos_ab": cosine(coeff_a, coeff_b),
|
| 245 |
+
"coeff_signflip_frac_ab": signflip_fraction(coeff_a, coeff_b),
|
| 246 |
+
"coeff_norm_ratio_b_over_a": float(
|
| 247 |
+
(coeff_b.norm() / coeff_a.norm().clamp_min(1e-8))
|
| 248 |
+
.detach()
|
| 249 |
+
.cpu()
|
| 250 |
+
),
|
| 251 |
+
"a_condition_correct_fraction": float(
|
| 252 |
+
row.get("a_condition_correct_fraction", np.nan)
|
| 253 |
+
),
|
| 254 |
+
"b_condition_correct_fraction": float(
|
| 255 |
+
row.get("b_condition_correct_fraction", np.nan)
|
| 256 |
+
),
|
| 257 |
+
"mean_correct_fraction": float(
|
| 258 |
+
row.get("mean_correct_fraction", np.nan)
|
| 259 |
+
),
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
for key in [
|
| 263 |
+
"node_cond",
|
| 264 |
+
"edge_cond",
|
| 265 |
+
"disp_edge_cond",
|
| 266 |
+
"disp_node_cond",
|
| 267 |
+
]:
|
| 268 |
+
audit_row[f"flip_rel_l2_{key}"] = rel_l2(
|
| 269 |
+
cond_pos[key],
|
| 270 |
+
cond_neg[key],
|
| 271 |
+
)
|
| 272 |
+
audit_row[f"ab_rel_l2_{key}"] = rel_l2(
|
| 273 |
+
cond_a[key],
|
| 274 |
+
cond_b[key],
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
rows.append(audit_row)
|
| 278 |
+
print(f"[audit] {pdb_name}", flush=True)
|
| 279 |
+
|
| 280 |
+
result = pd.DataFrame(rows)
|
| 281 |
+
result.to_csv(out_dir / "condition_sign_loss_audit.csv", index=False)
|
| 282 |
+
|
| 283 |
+
summary = {
|
| 284 |
+
"n": int(len(result)),
|
| 285 |
+
"coeff_cos_ab_mean": float(result["coeff_cos_ab"].mean()),
|
| 286 |
+
"coeff_cos_ab_median": float(result["coeff_cos_ab"].median()),
|
| 287 |
+
"coeff_signflip_frac_mean": float(
|
| 288 |
+
result["coeff_signflip_frac_ab"].mean()
|
| 289 |
+
),
|
| 290 |
+
"a_correct_mean": float(
|
| 291 |
+
result["a_condition_correct_fraction"].mean()
|
| 292 |
+
),
|
| 293 |
+
"b_correct_mean": float(
|
| 294 |
+
result["b_condition_correct_fraction"].mean()
|
| 295 |
+
),
|
| 296 |
+
"mean_correct_mean": float(result["mean_correct_fraction"].mean()),
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
for key in [
|
| 300 |
+
"node_cond",
|
| 301 |
+
"edge_cond",
|
| 302 |
+
"disp_edge_cond",
|
| 303 |
+
"disp_node_cond",
|
| 304 |
+
]:
|
| 305 |
+
summary[f"flip_rel_l2_{key}_mean"] = float(
|
| 306 |
+
result[f"flip_rel_l2_{key}"].mean()
|
| 307 |
+
)
|
| 308 |
+
summary[f"flip_rel_l2_{key}_median"] = float(
|
| 309 |
+
result[f"flip_rel_l2_{key}"].median()
|
| 310 |
+
)
|
| 311 |
+
summary[f"ab_rel_l2_{key}_mean"] = float(
|
| 312 |
+
result[f"ab_rel_l2_{key}"].mean()
|
| 313 |
+
)
|
| 314 |
+
summary[f"ab_rel_l2_{key}_median"] = float(
|
| 315 |
+
result[f"ab_rel_l2_{key}"].median()
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
for metric in [
|
| 319 |
+
"b_condition_correct_fraction",
|
| 320 |
+
"a_condition_correct_fraction",
|
| 321 |
+
"mean_correct_fraction",
|
| 322 |
+
]:
|
| 323 |
+
valid = result[
|
| 324 |
+
["coeff_cos_ab", "coeff_signflip_frac_ab", metric]
|
| 325 |
+
].dropna()
|
| 326 |
+
|
| 327 |
+
summary[f"pearson_coeff_cos_vs_{metric}"] = float(
|
| 328 |
+
valid["coeff_cos_ab"].corr(valid[metric], method="pearson")
|
| 329 |
+
)
|
| 330 |
+
summary[f"spearman_coeff_cos_vs_{metric}"] = float(
|
| 331 |
+
valid["coeff_cos_ab"].corr(valid[metric], method="spearman")
|
| 332 |
+
)
|
| 333 |
+
summary[f"pearson_signflip_vs_{metric}"] = float(
|
| 334 |
+
valid["coeff_signflip_frac_ab"].corr(valid[metric], method="pearson")
|
| 335 |
+
)
|
| 336 |
+
summary[f"spearman_signflip_vs_{metric}"] = float(
|
| 337 |
+
valid["coeff_signflip_frac_ab"].corr(valid[metric], method="spearman")
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
bins = [-1.01, -0.5, 0.0, 0.5, 1.01]
|
| 341 |
+
labels = ["cos<-0.5", "-0.5<=cos<0", "0<=cos<0.5", "cos>=0.5"]
|
| 342 |
+
|
| 343 |
+
result["coeff_cos_bin"] = pd.cut(
|
| 344 |
+
result["coeff_cos_ab"],
|
| 345 |
+
bins=bins,
|
| 346 |
+
labels=labels,
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
grouped = (
|
| 350 |
+
result.groupby("coeff_cos_bin", observed=False)
|
| 351 |
+
.agg(
|
| 352 |
+
n=("pdb_name", "count"),
|
| 353 |
+
b_correct_mean=("b_condition_correct_fraction", "mean"),
|
| 354 |
+
a_correct_mean=("a_condition_correct_fraction", "mean"),
|
| 355 |
+
mean_correct=("mean_correct_fraction", "mean"),
|
| 356 |
+
signflip_mean=("coeff_signflip_frac_ab", "mean"),
|
| 357 |
+
)
|
| 358 |
+
.reset_index()
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
grouped.to_csv(out_dir / "condition_sign_loss_bins.csv", index=False)
|
| 362 |
+
|
| 363 |
+
(out_dir / "condition_sign_loss_summary.json").write_text(
|
| 364 |
+
json.dumps(summary, indent=2, sort_keys=True) + "\n"
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
print("\n=== condition sign-loss summary ===")
|
| 368 |
+
print(json.dumps(summary, indent=2, sort_keys=True))
|
| 369 |
+
|
| 370 |
+
print("\n=== coeff cosine bins ===")
|
| 371 |
+
print(grouped.to_string(index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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def read_text(path):
|
| 8 |
+
return Path(path).read_text(encoding="utf-8", errors="replace")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def line_no_offsets(text):
|
| 12 |
+
starts = [0]
|
| 13 |
+
for m in re.finditer("\n", text):
|
| 14 |
+
starts.append(m.end())
|
| 15 |
+
return starts
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def pos_to_line(starts, pos):
|
| 19 |
+
lo, hi = 0, len(starts) - 1
|
| 20 |
+
while lo <= hi:
|
| 21 |
+
mid = (lo + hi) // 2
|
| 22 |
+
if starts[mid] <= pos:
|
| 23 |
+
lo = mid + 1
|
| 24 |
+
else:
|
| 25 |
+
hi = mid - 1
|
| 26 |
+
return hi + 1
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def extract_def(text, name):
|
| 30 |
+
pattern = re.compile(rf"^(\s*)def\s+{re.escape(name)}\s*\(", re.MULTILINE)
|
| 31 |
+
m = pattern.search(text)
|
| 32 |
+
if not m:
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
indent = len(m.group(1))
|
| 36 |
+
start = m.start()
|
| 37 |
+
lines = text[start:].splitlines()
|
| 38 |
+
out = []
|
| 39 |
+
for i, line in enumerate(lines):
|
| 40 |
+
if i > 0 and line.strip():
|
| 41 |
+
cur_indent = len(line) - len(line.lstrip(" "))
|
| 42 |
+
if cur_indent <= indent and re.match(r"\s*(def|class)\s+", line):
|
| 43 |
+
break
|
| 44 |
+
out.append(line)
|
| 45 |
+
return "\n".join(out)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def extract_class_method(text, method_name):
|
| 49 |
+
return extract_def(text, method_name)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def grep_files(root, patterns, include_ext=(".py",)):
|
| 53 |
+
root = Path(root)
|
| 54 |
+
hits = []
|
| 55 |
+
for path in root.rglob("*"):
|
| 56 |
+
if not path.is_file():
|
| 57 |
+
continue
|
| 58 |
+
if path.suffix not in include_ext:
|
| 59 |
+
continue
|
| 60 |
+
try:
|
| 61 |
+
text = read_text(path)
|
| 62 |
+
except Exception:
|
| 63 |
+
continue
|
| 64 |
+
starts = line_no_offsets(text)
|
| 65 |
+
for pat in patterns:
|
| 66 |
+
for m in re.finditer(pat, text):
|
| 67 |
+
hits.append({
|
| 68 |
+
"file": str(path),
|
| 69 |
+
"line": pos_to_line(starts, m.start()),
|
| 70 |
+
"pattern": pat,
|
| 71 |
+
"text": text[m.start(): text.find("\n", m.start()) if text.find("\n", m.start()) != -1 else m.end()],
|
| 72 |
+
})
|
| 73 |
+
return hits
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def find_file_containing(root, token):
|
| 77 |
+
root = Path(root)
|
| 78 |
+
found = []
|
| 79 |
+
for path in root.rglob("*.py"):
|
| 80 |
+
try:
|
| 81 |
+
text = read_text(path)
|
| 82 |
+
except Exception:
|
| 83 |
+
continue
|
| 84 |
+
if token in text:
|
| 85 |
+
found.append(path)
|
| 86 |
+
return found
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def bool_pattern(text, pattern):
|
| 90 |
+
return bool(re.search(pattern, text, flags=re.MULTILINE | re.DOTALL))
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def main():
|
| 94 |
+
ap = argparse.ArgumentParser()
|
| 95 |
+
ap.add_argument("--repo", default=".")
|
| 96 |
+
ap.add_argument("--out_dir", required=True)
|
| 97 |
+
args = ap.parse_args()
|
| 98 |
+
|
| 99 |
+
repo = Path(args.repo).resolve()
|
| 100 |
+
out = Path(args.out_dir)
|
| 101 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 102 |
+
|
| 103 |
+
bbflow = repo / "bbflow"
|
| 104 |
+
models = bbflow / "models"
|
| 105 |
+
data = bbflow / "data"
|
| 106 |
+
|
| 107 |
+
report = {
|
| 108 |
+
"repo": str(repo),
|
| 109 |
+
"checks": {},
|
| 110 |
+
"files": {},
|
| 111 |
+
"hits": {},
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
print("===== locate condition_from_mode_coefficients =====")
|
| 115 |
+
cond_files = find_file_containing(bbflow, "condition_from_mode_coefficients")
|
| 116 |
+
report["files"]["condition_from_mode_coefficients"] = [str(p) for p in cond_files]
|
| 117 |
+
for p in cond_files:
|
| 118 |
+
print(p)
|
| 119 |
+
|
| 120 |
+
print("\n===== condition_from_mode_coefficients source =====")
|
| 121 |
+
for p in cond_files:
|
| 122 |
+
text = read_text(p)
|
| 123 |
+
src = extract_def(text, "condition_from_mode_coefficients")
|
| 124 |
+
if src:
|
| 125 |
+
print(f"\n--- {p} ---")
|
| 126 |
+
print(src)
|
| 127 |
+
(out / f"{p.name}.condition_from_mode_coefficients.txt").write_text(src, encoding="utf-8")
|
| 128 |
+
|
| 129 |
+
report["checks"]["condition_uses_coefficients"] = {
|
| 130 |
+
"coeff_abs": "coeff_abs" in src,
|
| 131 |
+
"coefficients_abs": "abs" in src and "coeff" in src,
|
| 132 |
+
"coefficients_square": "coefficients.square" in src or ".square()" in src,
|
| 133 |
+
"disp_global_from_coefficients": bool_pattern(
|
| 134 |
+
src,
|
| 135 |
+
r"disp_global\s*=.*coefficients|coefficients.*disp_global|einsum\(.*coefficients|matmul\(.*coefficients",
|
| 136 |
+
),
|
| 137 |
+
"disp_local_from_disp_global": "disp_local" in src and "disp_global" in src,
|
| 138 |
+
"has_detach": ".detach()" in src or "detach(" in src,
|
| 139 |
+
"has_no_grad": "no_grad" in src,
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
print("\n===== locate FiLM / adapter functions =====")
|
| 143 |
+
film_files = []
|
| 144 |
+
for token in ["_apply_latent_film", "z_node_adapter", "disp_node_adapter", "node_condition_embedding"]:
|
| 145 |
+
files = find_file_containing(models, token)
|
| 146 |
+
report["files"][token] = [str(p) for p in files]
|
| 147 |
+
for p in files:
|
| 148 |
+
if p not in film_files:
|
| 149 |
+
film_files.append(p)
|
| 150 |
+
print(token, "=>", p)
|
| 151 |
+
|
| 152 |
+
print("\n===== _apply_latent_film source =====")
|
| 153 |
+
for p in film_files:
|
| 154 |
+
text = read_text(p)
|
| 155 |
+
src = extract_class_method(text, "_apply_latent_film")
|
| 156 |
+
if src:
|
| 157 |
+
print(f"\n--- {p} ---")
|
| 158 |
+
print(src)
|
| 159 |
+
(out / f"{p.name}._apply_latent_film.txt").write_text(src, encoding="utf-8")
|
| 160 |
+
report["checks"]["film"] = {
|
| 161 |
+
"uses_node_cond": "node_cond" in src,
|
| 162 |
+
"uses_disp_node_cond": "disp_node_cond" in src,
|
| 163 |
+
"uses_edge_cond": "edge_cond" in src,
|
| 164 |
+
"uses_disp_edge_cond": "disp_edge_cond" in src,
|
| 165 |
+
"uses_tanh": "tanh" in src,
|
| 166 |
+
"has_detach": ".detach()" in src or "detach(" in src,
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
print("\n===== adapter / condition embedding relevant lines =====")
|
| 170 |
+
adapter_patterns = [
|
| 171 |
+
r"node_condition_embedding.*",
|
| 172 |
+
r"edge_condition_embedding.*",
|
| 173 |
+
r"z_node_adapter.*",
|
| 174 |
+
r"disp_node_adapter.*",
|
| 175 |
+
r"z_edge_adapter.*",
|
| 176 |
+
r"disp_edge_adapter.*",
|
| 177 |
+
r"node_cond.*",
|
| 178 |
+
r"disp_node_cond.*",
|
| 179 |
+
r"edge_cond.*",
|
| 180 |
+
r"disp_edge_cond.*",
|
| 181 |
+
]
|
| 182 |
+
adapter_hits = grep_files(models, adapter_patterns)
|
| 183 |
+
report["hits"]["adapter_lines"] = adapter_hits
|
| 184 |
+
for h in adapter_hits[:220]:
|
| 185 |
+
print(f"{h['file']}:{h['line']}: {h['text']}")
|
| 186 |
+
|
| 187 |
+
print("\n===== detach / no_grad / requires_grad near condition paths =====")
|
| 188 |
+
detach_patterns = [
|
| 189 |
+
r".{0,80}detach\(\).{0,80}",
|
| 190 |
+
r".{0,80}no_grad.{0,80}",
|
| 191 |
+
r".{0,80}requires_grad.{0,80}",
|
| 192 |
+
]
|
| 193 |
+
detach_hits = []
|
| 194 |
+
for h in grep_files(bbflow, detach_patterns):
|
| 195 |
+
low = h["text"].lower()
|
| 196 |
+
if any(k in low for k in ["condition", "coeff", "disp", "latent", "film", "adapter", "mode"]):
|
| 197 |
+
detach_hits.append(h)
|
| 198 |
+
report["hits"]["detach_lines"] = detach_hits
|
| 199 |
+
for h in detach_hits[:160]:
|
| 200 |
+
print(f"{h['file']}:{h['line']}: {h['text']}")
|
| 201 |
+
|
| 202 |
+
print("\n===== loss terms involving coefficients / condition =====")
|
| 203 |
+
loss_patterns = [
|
| 204 |
+
r".{0,80}condition_cycle.{0,80}",
|
| 205 |
+
r".{0,80}cycle_loss.{0,80}",
|
| 206 |
+
r".{0,80}motion_loss.{0,80}",
|
| 207 |
+
r".{0,80}q_nll.{0,80}",
|
| 208 |
+
r".{0,80}mode_coeff.{0,80}",
|
| 209 |
+
r".{0,80}cross_cov_loss.{0,80}",
|
| 210 |
+
r".{0,80}local_cov_loss.{0,80}",
|
| 211 |
+
]
|
| 212 |
+
loss_hits = grep_files(bbflow, loss_patterns)
|
| 213 |
+
report["hits"]["loss_lines"] = loss_hits
|
| 214 |
+
for h in loss_hits[:220]:
|
| 215 |
+
print(f"{h['file']}:{h['line']}: {h['text']}")
|
| 216 |
+
|
| 217 |
+
print("\n===== possible sampled-c inference path =====")
|
| 218 |
+
infer_patterns = [
|
| 219 |
+
r".{0,80}sample_coefficients_from_q.{0,80}",
|
| 220 |
+
r".{0,80}condition_from_mode_coefficients.{0,80}",
|
| 221 |
+
r".{0,80}sample_prior_z.{0,80}",
|
| 222 |
+
r".{0,80}forward_prior.{0,80}",
|
| 223 |
+
r".{0,80}condition_scale.{0,80}",
|
| 224 |
+
r".{0,80}condition_mode.{0,80}",
|
| 225 |
+
]
|
| 226 |
+
infer_hits = grep_files(bbflow, infer_patterns)
|
| 227 |
+
report["hits"]["inference_condition_lines"] = infer_hits
|
| 228 |
+
for h in infer_hits[:220]:
|
| 229 |
+
print(f"{h['file']}:{h['line']}: {h['text']}")
|
| 230 |
+
|
| 231 |
+
print("\n===== automatic verdict =====")
|
| 232 |
+
verdict = {}
|
| 233 |
+
|
| 234 |
+
cond_check = report["checks"].get("condition_uses_coefficients", {})
|
| 235 |
+
film_check = report["checks"].get("film", {})
|
| 236 |
+
|
| 237 |
+
verdict["disp_path_source"] = (
|
| 238 |
+
"likely_from_coefficients"
|
| 239 |
+
if cond_check.get("disp_global_from_coefficients") and cond_check.get("disp_local_from_disp_global")
|
| 240 |
+
else "unclear_check_source_snippet"
|
| 241 |
+
)
|
| 242 |
+
verdict["condition_path_has_detach_in_function"] = bool(cond_check.get("has_detach") or cond_check.get("has_no_grad"))
|
| 243 |
+
verdict["node_edge_sign_invariant_by_construction"] = bool(
|
| 244 |
+
cond_check.get("coeff_abs") or cond_check.get("coefficients_square")
|
| 245 |
+
)
|
| 246 |
+
verdict["film_signed_or_unsigned"] = (
|
| 247 |
+
"unsigned_only_node_cond"
|
| 248 |
+
if film_check.get("uses_node_cond") and not film_check.get("uses_disp_node_cond")
|
| 249 |
+
else "uses_signed_disp_or_unclear"
|
| 250 |
+
)
|
| 251 |
+
verdict["film_has_tanh"] = bool(film_check.get("uses_tanh"))
|
| 252 |
+
|
| 253 |
+
print(json.dumps(verdict, indent=2, ensure_ascii=False))
|
| 254 |
+
|
| 255 |
+
report["verdict"] = verdict
|
| 256 |
+
(out / "condition_source_audit_report.json").write_text(
|
| 257 |
+
json.dumps(report, indent=2, ensure_ascii=False),
|
| 258 |
+
encoding="utf-8",
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
print("\nSaved:", out)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
if __name__ == "__main__":
|
| 265 |
+
main()
|
bbflow_base/scripts/audit_covariance_transport.py
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Audit endpoint covariance transport outputs.
|
| 3 |
+
|
| 4 |
+
This is a verification script, not a generator. It checks the exact concerns
|
| 5 |
+
raised after the first oracle transport run:
|
| 6 |
+
|
| 7 |
+
* same-batch base vs transported statistics;
|
| 8 |
+
* lambda=0 near-identity after per-model Kabsch alignment;
|
| 9 |
+
* input residue metadata agreement;
|
| 10 |
+
* det(R)=+1 for all Kabsch rotations used by this audit;
|
| 11 |
+
* output-vs-target covariance errors, including off-diagonal error;
|
| 12 |
+
* top-PC subspace overlap;
|
| 13 |
+
* CA continuity, CA clashes, and radius of gyration.
|
| 14 |
+
|
| 15 |
+
All coordinates are CA-only and reported in Angstrom.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import csv
|
| 22 |
+
import json
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Iterable
|
| 25 |
+
|
| 26 |
+
import mdtraj
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def read_test_names(csv_path: Path) -> list[str]:
|
| 31 |
+
with csv_path.open(newline="") as handle:
|
| 32 |
+
reader = csv.DictReader(handle)
|
| 33 |
+
if reader.fieldnames is None:
|
| 34 |
+
raise ValueError(f"Empty CSV: {csv_path}")
|
| 35 |
+
key = "pdb_name" if "pdb_name" in reader.fieldnames else reader.fieldnames[0]
|
| 36 |
+
return [str(row[key]).strip() for row in reader if str(row[key]).strip()]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_ca_traj(pdb_path: Path) -> tuple[mdtraj.Trajectory, np.ndarray]:
|
| 40 |
+
traj = mdtraj.load(str(pdb_path))
|
| 41 |
+
ca = traj.topology.select("name CA")
|
| 42 |
+
if ca.size == 0:
|
| 43 |
+
raise ValueError(f"No CA atoms in {pdb_path}")
|
| 44 |
+
return traj, np.asarray(traj.xyz[:, ca, :] * 10.0, dtype=np.float64)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def load_md_ca(atlas_root: Path, pdb_name: str, stride: int, max_frames: int, seed: int) -> tuple[mdtraj.Trajectory, np.ndarray]:
|
| 48 |
+
entry = atlas_root / pdb_name
|
| 49 |
+
top_path = entry / f"{pdb_name}.pdb"
|
| 50 |
+
if not top_path.exists():
|
| 51 |
+
raise FileNotFoundError(top_path)
|
| 52 |
+
top = mdtraj.load(str(top_path))
|
| 53 |
+
ca = top.topology.select("name CA")
|
| 54 |
+
if ca.size == 0:
|
| 55 |
+
raise ValueError(f"No CA atoms in {top_path}")
|
| 56 |
+
frames = []
|
| 57 |
+
for replica in (1, 2, 3):
|
| 58 |
+
xtc = entry / f"{pdb_name}_R{replica}.xtc"
|
| 59 |
+
if not xtc.exists():
|
| 60 |
+
raise FileNotFoundError(xtc)
|
| 61 |
+
traj = mdtraj.load(str(xtc), top=str(top_path), atom_indices=ca, stride=max(1, stride))
|
| 62 |
+
frames.append(np.asarray(traj.xyz * 10.0, dtype=np.float64))
|
| 63 |
+
coords = np.concatenate(frames, axis=0)
|
| 64 |
+
if max_frames and coords.shape[0] > max_frames:
|
| 65 |
+
rng = np.random.default_rng(seed)
|
| 66 |
+
idx = np.sort(rng.choice(coords.shape[0], size=max_frames, replace=False))
|
| 67 |
+
coords = coords[idx]
|
| 68 |
+
return top, coords
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def ca_residue_signature(traj: mdtraj.Trajectory) -> list[tuple[int, int, str, str]]:
|
| 72 |
+
ca = traj.topology.select("name CA")
|
| 73 |
+
sig = []
|
| 74 |
+
for atom_idx in ca:
|
| 75 |
+
atom = traj.topology.atom(int(atom_idx))
|
| 76 |
+
residue = atom.residue
|
| 77 |
+
chain_index = residue.chain.index
|
| 78 |
+
# mdtraj PDB loaders do not consistently expose insertion codes, so keep
|
| 79 |
+
# the fields it reliably preserves.
|
| 80 |
+
sig.append((chain_index, residue.resSeq, residue.name, atom.name))
|
| 81 |
+
return sig
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def kabsch(P: np.ndarray, Q: np.ndarray) -> tuple[np.ndarray, float]:
|
| 85 |
+
H = P.T @ Q
|
| 86 |
+
U, _, Vt = np.linalg.svd(H, full_matrices=False)
|
| 87 |
+
sign = np.sign(np.linalg.det(Vt.T @ U.T))
|
| 88 |
+
if sign == 0:
|
| 89 |
+
sign = 1.0
|
| 90 |
+
D = np.diag([1.0, 1.0, sign])
|
| 91 |
+
R = U @ D @ Vt
|
| 92 |
+
return R, float(np.linalg.det(R))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def center_frames(X: np.ndarray) -> np.ndarray:
|
| 96 |
+
return X - X.mean(axis=1, keepdims=True)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def superpose_to_reference(X: np.ndarray, ref: np.ndarray) -> tuple[np.ndarray, list[float]]:
|
| 100 |
+
out = []
|
| 101 |
+
dets = []
|
| 102 |
+
ref_c = ref - ref.mean(axis=0, keepdims=True)
|
| 103 |
+
for frame in X:
|
| 104 |
+
frame_c = frame - frame.mean(axis=0, keepdims=True)
|
| 105 |
+
R, det = kabsch(frame_c, ref_c)
|
| 106 |
+
out.append(frame_c @ R)
|
| 107 |
+
dets.append(det)
|
| 108 |
+
return np.stack(out, axis=0), dets
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def superpose_to_mean(X: np.ndarray, iterations: int = 3) -> tuple[np.ndarray, np.ndarray, list[float]]:
|
| 112 |
+
Xc = center_frames(X)
|
| 113 |
+
ref = Xc[0]
|
| 114 |
+
dets_all = []
|
| 115 |
+
aligned = Xc
|
| 116 |
+
for _ in range(iterations):
|
| 117 |
+
frames = []
|
| 118 |
+
for frame in aligned:
|
| 119 |
+
R, det = kabsch(frame - frame.mean(axis=0, keepdims=True), ref)
|
| 120 |
+
frames.append((frame - frame.mean(axis=0, keepdims=True)) @ R)
|
| 121 |
+
dets_all.append(det)
|
| 122 |
+
aligned = np.stack(frames, axis=0)
|
| 123 |
+
ref = aligned.mean(axis=0)
|
| 124 |
+
ref = ref - ref.mean(axis=0, keepdims=True)
|
| 125 |
+
return aligned, ref, dets_all
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def flatten_centered(X: np.ndarray) -> np.ndarray:
|
| 129 |
+
return X.reshape(X.shape[0], -1) - X.reshape(X.shape[0], -1).mean(axis=0, keepdims=True)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def covariance(X: np.ndarray) -> np.ndarray:
|
| 133 |
+
Xc = X - X.mean(axis=0, keepdims=True)
|
| 134 |
+
return (Xc.T @ Xc) / max(Xc.shape[0] - 1, 1)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def covariance_diag(X: np.ndarray) -> np.ndarray:
|
| 138 |
+
return np.var(X, axis=0, ddof=1)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def offdiag_mask(size: int) -> np.ndarray:
|
| 142 |
+
mask = np.ones((size, size), dtype=bool)
|
| 143 |
+
np.fill_diagonal(mask, False)
|
| 144 |
+
return mask
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def oracle_target_cov(Fg: np.ndarray, Fr: np.ndarray, lam: float, eps: float) -> np.ndarray:
|
| 148 |
+
Cg = covariance(Fg)
|
| 149 |
+
Cr = covariance(Fr)
|
| 150 |
+
dg = np.clip(np.diag(Cg), eps, None)
|
| 151 |
+
dr = np.clip(np.diag(Cr), eps, None)
|
| 152 |
+
scale = np.sqrt(dg / dr)
|
| 153 |
+
Cr_scaled = Cr * scale[:, None] * scale[None, :]
|
| 154 |
+
return (1.0 - lam) * Cg + lam * Cr_scaled
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def rel_fro(A: np.ndarray, B: np.ndarray, mask: np.ndarray | None = None, eps: float = 1e-8) -> float:
|
| 158 |
+
if mask is not None:
|
| 159 |
+
A = A[mask]
|
| 160 |
+
B = B[mask]
|
| 161 |
+
return float(np.linalg.norm(A - B) / max(np.linalg.norm(B), eps))
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def top_pc_overlap(Ca: np.ndarray, Cb: np.ndarray, k: int) -> float:
|
| 165 |
+
k = min(k, Ca.shape[0], Cb.shape[0])
|
| 166 |
+
if k <= 0:
|
| 167 |
+
return float("nan")
|
| 168 |
+
_, Va = np.linalg.eigh((Ca + Ca.T) * 0.5)
|
| 169 |
+
_, Vb = np.linalg.eigh((Cb + Cb.T) * 0.5)
|
| 170 |
+
Qa = Va[:, -k:]
|
| 171 |
+
Qb = Vb[:, -k:]
|
| 172 |
+
s = np.linalg.svd(Qa.T @ Qb, compute_uv=False)
|
| 173 |
+
return float(np.mean(s * s))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def pairwise_rmsd_mean(X: np.ndarray) -> float:
|
| 177 |
+
F = X.reshape(X.shape[0], -1)
|
| 178 |
+
diff = F[:, None, :] - F[None, :, :]
|
| 179 |
+
dist = np.sqrt(np.mean(diff * diff, axis=-1))
|
| 180 |
+
return float(dist.mean())
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def rmsf_profile(X: np.ndarray, ref: np.ndarray) -> np.ndarray:
|
| 184 |
+
X_al, _ = superpose_to_reference(X, ref)
|
| 185 |
+
return np.sqrt(np.mean(np.sum((X_al - ref[None]) ** 2, axis=-1), axis=0))
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def radius_of_gyration(X: np.ndarray) -> np.ndarray:
|
| 189 |
+
centered = X - X.mean(axis=1, keepdims=True)
|
| 190 |
+
return np.sqrt(np.mean(np.sum(centered * centered, axis=-1), axis=1))
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def ca_continuity_stats(X: np.ndarray) -> dict[str, float]:
|
| 194 |
+
d = np.linalg.norm(X[:, 1:, :] - X[:, :-1, :], axis=-1)
|
| 195 |
+
return {
|
| 196 |
+
"ca_neighbor_dist_mean": float(d.mean()),
|
| 197 |
+
"ca_neighbor_dist_max": float(d.max()),
|
| 198 |
+
"ca_neighbor_break_frac_gt4p5": float((d > 4.5).mean()),
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def ca_clash_frac(X: np.ndarray, threshold: float) -> float:
|
| 203 |
+
n = X.shape[1]
|
| 204 |
+
diff = X[:, :, None, :] - X[:, None, :, :]
|
| 205 |
+
dist = np.linalg.norm(diff, axis=-1)
|
| 206 |
+
sep = np.abs(np.arange(n)[:, None] - np.arange(n)[None, :])
|
| 207 |
+
mask = sep > 1
|
| 208 |
+
return float((dist[:, mask] < threshold).mean())
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def bootstrap_delta(values_a: np.ndarray, values_b: np.ndarray, seed: int, samples: int) -> dict[str, float]:
|
| 212 |
+
values_a = np.asarray(values_a, dtype=np.float64)
|
| 213 |
+
values_b = np.asarray(values_b, dtype=np.float64)
|
| 214 |
+
delta = values_b - values_a
|
| 215 |
+
rng = np.random.default_rng(seed)
|
| 216 |
+
boot = []
|
| 217 |
+
for _ in range(samples):
|
| 218 |
+
idx = rng.integers(0, len(delta), size=len(delta))
|
| 219 |
+
boot.append(delta[idx].mean())
|
| 220 |
+
boot = np.asarray(boot)
|
| 221 |
+
return {
|
| 222 |
+
"base_mean": float(values_a.mean()),
|
| 223 |
+
"transport_mean": float(values_b.mean()),
|
| 224 |
+
"delta_transport_minus_base": float(delta.mean()),
|
| 225 |
+
"delta_ci95_low": float(np.quantile(boot, 0.025)),
|
| 226 |
+
"delta_ci95_high": float(np.quantile(boot, 0.975)),
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def audit_one(
|
| 231 |
+
pdb_name: str,
|
| 232 |
+
base_dir: Path,
|
| 233 |
+
transport_dir: Path,
|
| 234 |
+
atlas_root: Path,
|
| 235 |
+
lam: float,
|
| 236 |
+
md_stride: int,
|
| 237 |
+
max_md_frames: int,
|
| 238 |
+
seed: int,
|
| 239 |
+
eps: float,
|
| 240 |
+
top_pc_k: int,
|
| 241 |
+
) -> dict[str, float | int | str | bool]:
|
| 242 |
+
base_pdb = base_dir / pdb_name / "sampled_conformations.pdb"
|
| 243 |
+
trans_pdb = transport_dir / pdb_name / "sampled_conformations.pdb"
|
| 244 |
+
if not base_pdb.exists():
|
| 245 |
+
return {"pdb_name": pdb_name, "status": "missing_base"}
|
| 246 |
+
if not trans_pdb.exists():
|
| 247 |
+
return {"pdb_name": pdb_name, "status": "missing_transport"}
|
| 248 |
+
|
| 249 |
+
base_traj, Xb_raw = load_ca_traj(base_pdb)
|
| 250 |
+
trans_traj, Xt_raw = load_ca_traj(trans_pdb)
|
| 251 |
+
md_top, Xm_raw = load_md_ca(atlas_root, pdb_name, md_stride, max_md_frames, seed)
|
| 252 |
+
|
| 253 |
+
base_sig = ca_residue_signature(base_traj)
|
| 254 |
+
md_sig = ca_residue_signature(md_top)
|
| 255 |
+
residue_exact_match = base_sig == md_sig
|
| 256 |
+
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
|
| 257 |
+
|
| 258 |
+
if Xb_raw.shape != Xt_raw.shape:
|
| 259 |
+
raise ValueError(f"{pdb_name}: base/transport shape mismatch {Xb_raw.shape} vs {Xt_raw.shape}")
|
| 260 |
+
if Xb_raw.shape[1] != Xm_raw.shape[1]:
|
| 261 |
+
raise ValueError(f"{pdb_name}: base/MD residue mismatch {Xb_raw.shape[1]} vs {Xm_raw.shape[1]}")
|
| 262 |
+
|
| 263 |
+
Xb, mean_b, dets_b = superpose_to_mean(Xb_raw)
|
| 264 |
+
Xm, mean_m, dets_m = superpose_to_mean(Xm_raw)
|
| 265 |
+
Rb2m, det_b2m = kabsch(mean_b, mean_m)
|
| 266 |
+
Xb = Xb @ Rb2m
|
| 267 |
+
mean_b = mean_b @ Rb2m
|
| 268 |
+
Xt_aligned, dets_t = superpose_to_reference(Xt_raw, mean_b)
|
| 269 |
+
|
| 270 |
+
Fb = flatten_centered(Xb)
|
| 271 |
+
Ft = flatten_centered(Xt_aligned)
|
| 272 |
+
Fm = flatten_centered(Xm)
|
| 273 |
+
Cb = covariance(Fb)
|
| 274 |
+
Ct = covariance(Ft)
|
| 275 |
+
Ctarget = oracle_target_cov(Fb, Fm, lam=lam, eps=eps)
|
| 276 |
+
mask_off = offdiag_mask(Cb.shape[0])
|
| 277 |
+
|
| 278 |
+
ref = Xb.mean(axis=0)
|
| 279 |
+
rmsf_b = rmsf_profile(Xb_raw, ref)
|
| 280 |
+
rmsf_t = rmsf_profile(Xt_raw, ref)
|
| 281 |
+
|
| 282 |
+
# Per-frame identity error after Kabsch. This should be PDB quantization level
|
| 283 |
+
# for lambda=0 if the transform is actually identity-like.
|
| 284 |
+
aligned_t_to_b = []
|
| 285 |
+
dets_identity = []
|
| 286 |
+
for frame_b, frame_t in zip(Xb_raw, Xt_raw):
|
| 287 |
+
b = frame_b - frame_b.mean(axis=0, keepdims=True)
|
| 288 |
+
t = frame_t - frame_t.mean(axis=0, keepdims=True)
|
| 289 |
+
R, det = kabsch(t, b)
|
| 290 |
+
aligned_t_to_b.append(t @ R)
|
| 291 |
+
dets_identity.append(det)
|
| 292 |
+
aligned_t_to_b = np.stack(aligned_t_to_b, axis=0)
|
| 293 |
+
centered_b_raw = center_frames(Xb_raw)
|
| 294 |
+
identity_diff = aligned_t_to_b - centered_b_raw
|
| 295 |
+
|
| 296 |
+
rg_b = radius_of_gyration(Xb_raw)
|
| 297 |
+
rg_t = radius_of_gyration(Xt_raw)
|
| 298 |
+
cont_b = ca_continuity_stats(Xb_raw)
|
| 299 |
+
cont_t = ca_continuity_stats(Xt_raw)
|
| 300 |
+
|
| 301 |
+
row: dict[str, float | int | str | bool] = {
|
| 302 |
+
"pdb_name": pdb_name,
|
| 303 |
+
"status": "ok",
|
| 304 |
+
"num_res": int(Xb_raw.shape[1]),
|
| 305 |
+
"num_frames": int(Xb_raw.shape[0]),
|
| 306 |
+
"residue_exact_match_base_md": bool(residue_exact_match),
|
| 307 |
+
"residue_name_match_frac_base_md": residue_name_match_frac,
|
| 308 |
+
"det_min": float(min(dets_b + dets_m + dets_t + dets_identity + [det_b2m])),
|
| 309 |
+
"det_max": float(max(dets_b + dets_m + dets_t + dets_identity + [det_b2m])),
|
| 310 |
+
"trace_base": float(np.trace(Cb)),
|
| 311 |
+
"trace_transport": float(np.trace(Ct)),
|
| 312 |
+
"trace_target": float(np.trace(Ctarget)),
|
| 313 |
+
"diag_rel_l1_base_transport": float(np.mean(np.abs(np.diag(Ct) - np.diag(Cb))) / max(np.mean(np.diag(Cb)), eps)),
|
| 314 |
+
"cov_rel_fro_transport_vs_target": rel_fro(Ct, Ctarget, eps=eps),
|
| 315 |
+
"cov_offdiag_rel_fro_transport_vs_target": rel_fro(Ct, Ctarget, mask=mask_off, eps=eps),
|
| 316 |
+
"cov_offdiag_rel_fro_transport_vs_base": rel_fro(Ct, Cb, mask=mask_off, eps=eps),
|
| 317 |
+
"top_pc_overlap_transport_target": top_pc_overlap(Ct, Ctarget, top_pc_k),
|
| 318 |
+
"top_pc_overlap_transport_md": top_pc_overlap(Ct, covariance(Fm), top_pc_k),
|
| 319 |
+
"top_pc_overlap_base_md": top_pc_overlap(Cb, covariance(Fm), top_pc_k),
|
| 320 |
+
"identity_rmsd_mean": float(np.sqrt(np.mean(identity_diff * identity_diff))),
|
| 321 |
+
"identity_rmsd_max": float(np.sqrt(np.max(np.mean(identity_diff * identity_diff, axis=(1, 2))))),
|
| 322 |
+
"rmsf_mae_base_transport": float(np.mean(np.abs(rmsf_t - rmsf_b))),
|
| 323 |
+
"rmsf_median_base": float(np.median(rmsf_b)),
|
| 324 |
+
"rmsf_median_transport": float(np.median(rmsf_t)),
|
| 325 |
+
"pairwise_mean_base": pairwise_rmsd_mean(Xb_raw),
|
| 326 |
+
"pairwise_mean_transport": pairwise_rmsd_mean(Xt_raw),
|
| 327 |
+
"rg_mean_base": float(rg_b.mean()),
|
| 328 |
+
"rg_mean_transport": float(rg_t.mean()),
|
| 329 |
+
"rg_delta_mean": float((rg_t - rg_b).mean()),
|
| 330 |
+
"ca_clash_frac_base_lt3p0": ca_clash_frac(Xb_raw, 3.0),
|
| 331 |
+
"ca_clash_frac_transport_lt3p0": ca_clash_frac(Xt_raw, 3.0),
|
| 332 |
+
}
|
| 333 |
+
for key, value in cont_b.items():
|
| 334 |
+
row[f"base_{key}"] = value
|
| 335 |
+
for key, value in cont_t.items():
|
| 336 |
+
row[f"transport_{key}"] = value
|
| 337 |
+
return row
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def parse_args() -> argparse.Namespace:
|
| 341 |
+
parser = argparse.ArgumentParser()
|
| 342 |
+
parser.add_argument("--base_dir", required=True, type=Path)
|
| 343 |
+
parser.add_argument("--transport_dir", required=True, type=Path)
|
| 344 |
+
parser.add_argument("--atlas_root", required=True, type=Path)
|
| 345 |
+
parser.add_argument("--test_csv", required=True, type=Path)
|
| 346 |
+
parser.add_argument("--out_dir", required=True, type=Path)
|
| 347 |
+
parser.add_argument("--lam", type=float, default=0.0)
|
| 348 |
+
parser.add_argument("--md_stride", type=int, default=1)
|
| 349 |
+
parser.add_argument("--max_md_frames", type=int, default=0)
|
| 350 |
+
parser.add_argument("--seed", type=int, default=123)
|
| 351 |
+
parser.add_argument("--bootstrap_samples", type=int, default=2000)
|
| 352 |
+
parser.add_argument("--top_pc_k", type=int, default=2)
|
| 353 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 354 |
+
parser.add_argument("--eps", type=float, default=1e-8)
|
| 355 |
+
return parser.parse_args()
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def numeric_summary(rows: list[dict[str, object]], seed: int, bootstrap_samples: int) -> dict[str, object]:
|
| 359 |
+
ok = [row for row in rows if row.get("status") == "ok"]
|
| 360 |
+
summary: dict[str, object] = {"n": len(rows), "n_ok": len(ok)}
|
| 361 |
+
if not ok:
|
| 362 |
+
return summary
|
| 363 |
+
keys = sorted({key for row in ok for key, value in row.items() if isinstance(value, (int, float, bool))})
|
| 364 |
+
for key in keys:
|
| 365 |
+
vals = np.asarray([float(row[key]) for row in ok if key in row], dtype=np.float64)
|
| 366 |
+
if vals.size:
|
| 367 |
+
summary[f"{key}_mean"] = float(vals.mean())
|
| 368 |
+
summary[f"{key}_median"] = float(np.median(vals))
|
| 369 |
+
|
| 370 |
+
for base_key, transport_key, label in [
|
| 371 |
+
("pairwise_mean_base", "pairwise_mean_transport", "pairwise_mean"),
|
| 372 |
+
("rg_mean_base", "rg_mean_transport", "rg_mean"),
|
| 373 |
+
("ca_clash_frac_base_lt3p0", "ca_clash_frac_transport_lt3p0", "ca_clash_frac_lt3p0"),
|
| 374 |
+
("base_ca_neighbor_break_frac_gt4p5", "transport_ca_neighbor_break_frac_gt4p5", "ca_neighbor_break_frac_gt4p5"),
|
| 375 |
+
]:
|
| 376 |
+
if all(base_key in row and transport_key in row for row in ok):
|
| 377 |
+
summary[f"paired_{label}"] = bootstrap_delta(
|
| 378 |
+
np.asarray([row[base_key] for row in ok], dtype=np.float64),
|
| 379 |
+
np.asarray([row[transport_key] for row in ok], dtype=np.float64),
|
| 380 |
+
seed=seed,
|
| 381 |
+
samples=bootstrap_samples,
|
| 382 |
+
)
|
| 383 |
+
return summary
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def main() -> None:
|
| 387 |
+
args = parse_args()
|
| 388 |
+
names = read_test_names(args.test_csv)
|
| 389 |
+
if args.limit > 0:
|
| 390 |
+
names = names[: args.limit]
|
| 391 |
+
args.out_dir.mkdir(parents=True, exist_ok=True)
|
| 392 |
+
|
| 393 |
+
rows = []
|
| 394 |
+
for idx, name in enumerate(names, start=1):
|
| 395 |
+
print(f"[{idx}/{len(names)}] audit {name}")
|
| 396 |
+
row = audit_one(
|
| 397 |
+
pdb_name=name,
|
| 398 |
+
base_dir=args.base_dir,
|
| 399 |
+
transport_dir=args.transport_dir,
|
| 400 |
+
atlas_root=args.atlas_root,
|
| 401 |
+
lam=args.lam,
|
| 402 |
+
md_stride=args.md_stride,
|
| 403 |
+
max_md_frames=args.max_md_frames,
|
| 404 |
+
seed=args.seed + idx,
|
| 405 |
+
eps=args.eps,
|
| 406 |
+
top_pc_k=args.top_pc_k,
|
| 407 |
+
)
|
| 408 |
+
rows.append(row)
|
| 409 |
+
print(json.dumps(row, sort_keys=True))
|
| 410 |
+
|
| 411 |
+
payload = {
|
| 412 |
+
"base_dir": str(args.base_dir),
|
| 413 |
+
"transport_dir": str(args.transport_dir),
|
| 414 |
+
"atlas_root": str(args.atlas_root),
|
| 415 |
+
"test_csv": str(args.test_csv),
|
| 416 |
+
"lambda": args.lam,
|
| 417 |
+
"rows": rows,
|
| 418 |
+
"summary": numeric_summary(rows, seed=args.seed, bootstrap_samples=args.bootstrap_samples),
|
| 419 |
+
}
|
| 420 |
+
out_path = args.out_dir / "covariance_transport_audit.json"
|
| 421 |
+
with out_path.open("w") as handle:
|
| 422 |
+
json.dump(payload, handle, indent=2, sort_keys=True)
|
| 423 |
+
print(f"Saved: {out_path}")
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
if __name__ == "__main__":
|
| 427 |
+
main()
|
bbflow_base/scripts/audit_frame_gap_confound.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def rank(a):
|
| 9 |
+
return pd.Series(a).rank(method="average").to_numpy(float)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def pearson(x, y):
|
| 13 |
+
x = np.asarray(x, float)
|
| 14 |
+
y = np.asarray(y, float)
|
| 15 |
+
if len(x) < 3 or np.std(x) == 0 or np.std(y) == 0:
|
| 16 |
+
return float("nan")
|
| 17 |
+
return float(np.corrcoef(x, y)[0, 1])
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def corr(df, x, y, method="pearson"):
|
| 21 |
+
z = df[[x, y]].replace([np.inf, -np.inf], np.nan).dropna()
|
| 22 |
+
xx = z[x].to_numpy(float)
|
| 23 |
+
yy = z[y].to_numpy(float)
|
| 24 |
+
if method == "spearman":
|
| 25 |
+
xx = rank(xx)
|
| 26 |
+
yy = rank(yy)
|
| 27 |
+
return pearson(xx, yy)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def residualize(y, controls):
|
| 31 |
+
y = np.asarray(y, float)
|
| 32 |
+
X = [np.ones_like(y)]
|
| 33 |
+
for c in controls:
|
| 34 |
+
X.append(np.asarray(c, float))
|
| 35 |
+
X = np.stack(X, axis=1)
|
| 36 |
+
beta, *_ = np.linalg.lstsq(X, y, rcond=None)
|
| 37 |
+
return y - X @ beta
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def partial_corr(df, x, y, controls, method="pearson"):
|
| 41 |
+
cols = [x, y] + controls
|
| 42 |
+
z = df[cols].replace([np.inf, -np.inf], np.nan).dropna()
|
| 43 |
+
if len(z) < len(controls) + 3:
|
| 44 |
+
return float("nan")
|
| 45 |
+
xx = z[x].to_numpy(float)
|
| 46 |
+
yy = z[y].to_numpy(float)
|
| 47 |
+
cc = [z[c].to_numpy(float) for c in controls]
|
| 48 |
+
if method == "spearman":
|
| 49 |
+
xx = rank(xx)
|
| 50 |
+
yy = rank(yy)
|
| 51 |
+
cc = [rank(c) for c in cc]
|
| 52 |
+
return pearson(residualize(xx, cc), residualize(yy, cc))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def leave_one_out(df, x, y, method="pearson"):
|
| 56 |
+
vals = []
|
| 57 |
+
for i in range(len(df)):
|
| 58 |
+
vals.append(corr(df.drop(df.index[i]), x, y, method))
|
| 59 |
+
vals = np.array([v for v in vals if np.isfinite(v)], float)
|
| 60 |
+
return {
|
| 61 |
+
"min": float(vals.min()) if len(vals) else float("nan"),
|
| 62 |
+
"max": float(vals.max()) if len(vals) else float("nan"),
|
| 63 |
+
"median": float(np.median(vals)) if len(vals) else float("nan"),
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def main():
|
| 68 |
+
ap = argparse.ArgumentParser()
|
| 69 |
+
ap.add_argument("--joined_csv", required=True)
|
| 70 |
+
ap.add_argument("--out_dir", required=True)
|
| 71 |
+
args = ap.parse_args()
|
| 72 |
+
|
| 73 |
+
out = Path(args.out_dir)
|
| 74 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 75 |
+
|
| 76 |
+
df = pd.read_csv(args.joined_csv)
|
| 77 |
+
df["frame_gap"] = (df["frame_b"] - df["frame_a"]).abs()
|
| 78 |
+
|
| 79 |
+
y_cols = ["direction_score", "gain_score", "cycle_error_mean"]
|
| 80 |
+
rows = []
|
| 81 |
+
for y in y_cols:
|
| 82 |
+
rows.append({
|
| 83 |
+
"y": y,
|
| 84 |
+
"n": int(len(df)),
|
| 85 |
+
"corr_cos_y_pearson": corr(df, "coeff_cos_ab", y, "pearson"),
|
| 86 |
+
"corr_cos_y_spearman": corr(df, "coeff_cos_ab", y, "spearman"),
|
| 87 |
+
"corr_framegap_y_pearson": corr(df, "frame_gap", y, "pearson"),
|
| 88 |
+
"corr_framegap_y_spearman": corr(df, "frame_gap", y, "spearman"),
|
| 89 |
+
"corr_cos_framegap_pearson": corr(df, "coeff_cos_ab", "frame_gap", "pearson"),
|
| 90 |
+
"corr_cos_framegap_spearman": corr(df, "coeff_cos_ab", "frame_gap", "spearman"),
|
| 91 |
+
"partial_cos_y_control_target": partial_corr(df, "coeff_cos_ab", y, ["target_pair_rmsd"], "pearson"),
|
| 92 |
+
"partial_cos_y_control_framegap": partial_corr(df, "coeff_cos_ab", y, ["frame_gap"], "pearson"),
|
| 93 |
+
"partial_cos_y_control_both": partial_corr(df, "coeff_cos_ab", y, ["target_pair_rmsd", "frame_gap"], "pearson"),
|
| 94 |
+
"partial_cos_y_control_both_spearman": partial_corr(df, "coeff_cos_ab", y, ["target_pair_rmsd", "frame_gap"], "spearman"),
|
| 95 |
+
"loo_pearson_min": leave_one_out(df, "coeff_cos_ab", y, "pearson")["min"],
|
| 96 |
+
"loo_pearson_max": leave_one_out(df, "coeff_cos_ab", y, "pearson")["max"],
|
| 97 |
+
})
|
| 98 |
+
|
| 99 |
+
full = pd.DataFrame(rows)
|
| 100 |
+
|
| 101 |
+
no_qj0 = df[df["pdb_name"] != "6qj0A"].copy()
|
| 102 |
+
outlier_rows = []
|
| 103 |
+
for y in y_cols:
|
| 104 |
+
outlier_rows.append({
|
| 105 |
+
"removed": "6qj0A",
|
| 106 |
+
"y": y,
|
| 107 |
+
"n": int(len(no_qj0)),
|
| 108 |
+
"corr_cos_y_pearson": corr(no_qj0, "coeff_cos_ab", y, "pearson"),
|
| 109 |
+
"corr_cos_y_spearman": corr(no_qj0, "coeff_cos_ab", y, "spearman"),
|
| 110 |
+
"partial_cos_y_control_both": partial_corr(no_qj0, "coeff_cos_ab", y, ["target_pair_rmsd", "frame_gap"], "pearson"),
|
| 111 |
+
"partial_cos_y_control_both_spearman": partial_corr(no_qj0, "coeff_cos_ab", y, ["target_pair_rmsd", "frame_gap"], "spearman"),
|
| 112 |
+
})
|
| 113 |
+
no_qj0_df = pd.DataFrame(outlier_rows)
|
| 114 |
+
|
| 115 |
+
bins = pd.cut(
|
| 116 |
+
df["frame_gap"],
|
| 117 |
+
bins=[-1, 200, 400, 600, 800, 2000],
|
| 118 |
+
labels=["<=200", "201-400", "401-600", "601-800", ">800"],
|
| 119 |
+
)
|
| 120 |
+
gap_bins = df.groupby(bins, observed=False).agg(
|
| 121 |
+
n=("pdb_name", "count"),
|
| 122 |
+
coeff_cos_mean=("coeff_cos_ab", "mean"),
|
| 123 |
+
target_pair_rmsd_mean=("target_pair_rmsd", "mean"),
|
| 124 |
+
direction_score_mean=("direction_score", "mean"),
|
| 125 |
+
gain_score_mean=("gain_score", "mean"),
|
| 126 |
+
cycle_error_mean=("cycle_error_mean", "mean"),
|
| 127 |
+
).reset_index().rename(columns={"frame_gap": "frame_gap_bin"})
|
| 128 |
+
|
| 129 |
+
scatter = df[[
|
| 130 |
+
"pdb_name", "frame_a", "frame_b", "frame_gap",
|
| 131 |
+
"coeff_cos_ab", "target_pair_rmsd",
|
| 132 |
+
"direction_score", "gain_score", "cycle_error_mean",
|
| 133 |
+
"generated_pair_rmsd",
|
| 134 |
+
]].sort_values("coeff_cos_ab")
|
| 135 |
+
|
| 136 |
+
summary = {
|
| 137 |
+
"n": int(len(df)),
|
| 138 |
+
"n_without_6qj0A": int(len(no_qj0)),
|
| 139 |
+
"frame_gap_values": sorted([int(x) for x in df["frame_gap"].unique()]),
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
full.to_csv(out / "frame_gap_confound_full.csv", index=False)
|
| 143 |
+
no_qj0_df.to_csv(out / "frame_gap_confound_without_6qj0A.csv", index=False)
|
| 144 |
+
gap_bins.to_csv(out / "frame_gap_bins.csv", index=False)
|
| 145 |
+
scatter.to_csv(out / "frame_gap_scatter.csv", index=False)
|
| 146 |
+
(out / "frame_gap_confound_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
|
| 147 |
+
|
| 148 |
+
print("===== summary =====")
|
| 149 |
+
print(json.dumps(summary, indent=2))
|
| 150 |
+
print("\n===== full correlations =====")
|
| 151 |
+
print(full.to_string(index=False))
|
| 152 |
+
print("\n===== without 6qj0A =====")
|
| 153 |
+
print(no_qj0_df.to_string(index=False))
|
| 154 |
+
print("\n===== frame gap bins =====")
|
| 155 |
+
print(gap_bins.to_string(index=False))
|
| 156 |
+
print("\nSaved:", out)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
if __name__ == "__main__":
|
| 160 |
+
main()
|
bbflow_base/scripts/audit_sign_loss_confound.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def clean_xy(df, x, y):
|
| 10 |
+
z = df[[x, y]].replace([np.inf, -np.inf], np.nan).dropna()
|
| 11 |
+
return z[x].to_numpy(float), z[y].to_numpy(float)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def pearson_np(x, y):
|
| 15 |
+
if len(x) < 3:
|
| 16 |
+
return float("nan")
|
| 17 |
+
if np.std(x) == 0 or np.std(y) == 0:
|
| 18 |
+
return float("nan")
|
| 19 |
+
return float(np.corrcoef(x, y)[0, 1])
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def rankdata(a):
|
| 23 |
+
s = pd.Series(a)
|
| 24 |
+
return s.rank(method="average").to_numpy(float)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def corr(df, x, y, method):
|
| 28 |
+
xx, yy = clean_xy(df, x, y)
|
| 29 |
+
if method == "spearman":
|
| 30 |
+
xx, yy = rankdata(xx), rankdata(yy)
|
| 31 |
+
return pearson_np(xx, yy)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def residualize(y, x):
|
| 35 |
+
y = np.asarray(y, float)
|
| 36 |
+
x = np.asarray(x, float)
|
| 37 |
+
X = np.stack([np.ones_like(x), x], axis=1)
|
| 38 |
+
beta, *_ = np.linalg.lstsq(X, y, rcond=None)
|
| 39 |
+
return y - X @ beta
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def partial_corr(df, x, y, control, method):
|
| 43 |
+
cols = [x, y, control]
|
| 44 |
+
z = df[cols].replace([np.inf, -np.inf], np.nan).dropna()
|
| 45 |
+
if len(z) < 4:
|
| 46 |
+
return float("nan")
|
| 47 |
+
xx = z[x].to_numpy(float)
|
| 48 |
+
yy = z[y].to_numpy(float)
|
| 49 |
+
cc = z[control].to_numpy(float)
|
| 50 |
+
if method == "spearman":
|
| 51 |
+
xx, yy, cc = rankdata(xx), rankdata(yy), rankdata(cc)
|
| 52 |
+
rx = residualize(xx, cc)
|
| 53 |
+
ry = residualize(yy, cc)
|
| 54 |
+
return pearson_np(rx, ry)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def permutation_pvalue(df, x, y, method, n_perm=20000, seed=20260712):
|
| 58 |
+
z = df[[x, y]].replace([np.inf, -np.inf], np.nan).dropna()
|
| 59 |
+
if len(z) < 3:
|
| 60 |
+
return float("nan")
|
| 61 |
+
xx = z[x].to_numpy(float)
|
| 62 |
+
yy = z[y].to_numpy(float)
|
| 63 |
+
if method == "spearman":
|
| 64 |
+
xx, yy = rankdata(xx), rankdata(yy)
|
| 65 |
+
observed = abs(pearson_np(xx, yy))
|
| 66 |
+
if not np.isfinite(observed):
|
| 67 |
+
return float("nan")
|
| 68 |
+
rng = np.random.default_rng(seed)
|
| 69 |
+
count = 0
|
| 70 |
+
for _ in range(n_perm):
|
| 71 |
+
yp = rng.permutation(yy)
|
| 72 |
+
if abs(pearson_np(xx, yp)) >= observed:
|
| 73 |
+
count += 1
|
| 74 |
+
return float((count + 1) / (n_perm + 1))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def leave_one_out(df, x, y, method):
|
| 78 |
+
vals = []
|
| 79 |
+
for i in range(len(df)):
|
| 80 |
+
sub = df.drop(df.index[i])
|
| 81 |
+
vals.append(corr(sub, x, y, method))
|
| 82 |
+
vals = np.array(vals, dtype=float)
|
| 83 |
+
vals = vals[np.isfinite(vals)]
|
| 84 |
+
if len(vals) == 0:
|
| 85 |
+
return {
|
| 86 |
+
"min": float("nan"),
|
| 87 |
+
"max": float("nan"),
|
| 88 |
+
"mean": float("nan"),
|
| 89 |
+
"median": float("nan"),
|
| 90 |
+
}
|
| 91 |
+
return {
|
| 92 |
+
"min": float(vals.min()),
|
| 93 |
+
"max": float(vals.max()),
|
| 94 |
+
"mean": float(vals.mean()),
|
| 95 |
+
"median": float(np.median(vals)),
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def summarize_series(s):
|
| 100 |
+
a = pd.Series(s).replace([np.inf, -np.inf], np.nan).dropna().to_numpy(float)
|
| 101 |
+
if len(a) == 0:
|
| 102 |
+
return {}
|
| 103 |
+
return {
|
| 104 |
+
"n": int(len(a)),
|
| 105 |
+
"mean": float(np.mean(a)),
|
| 106 |
+
"median": float(np.median(a)),
|
| 107 |
+
"min": float(np.min(a)),
|
| 108 |
+
"max": float(np.max(a)),
|
| 109 |
+
"q25": float(np.quantile(a, 0.25)),
|
| 110 |
+
"q75": float(np.quantile(a, 0.75)),
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def main():
|
| 115 |
+
ap = argparse.ArgumentParser()
|
| 116 |
+
ap.add_argument("--joined_csv", required=True)
|
| 117 |
+
ap.add_argument("--out_dir", required=True)
|
| 118 |
+
args = ap.parse_args()
|
| 119 |
+
|
| 120 |
+
joined_csv = Path(args.joined_csv)
|
| 121 |
+
out_dir = Path(args.out_dir)
|
| 122 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 123 |
+
|
| 124 |
+
df = pd.read_csv(joined_csv)
|
| 125 |
+
|
| 126 |
+
required = ["coeff_cos_ab", "target_pair_rmsd", "direction_score", "gain_score", "cycle_error_mean"]
|
| 127 |
+
missing = [c for c in required if c not in df.columns]
|
| 128 |
+
if missing:
|
| 129 |
+
raise ValueError(f"Missing required columns: {missing}. Existing columns: {df.columns.tolist()}")
|
| 130 |
+
|
| 131 |
+
pairs = [
|
| 132 |
+
("coeff_cos_ab", "direction_score"),
|
| 133 |
+
("coeff_cos_ab", "gain_score"),
|
| 134 |
+
("coeff_cos_ab", "cycle_error_mean"),
|
| 135 |
+
("coeff_cos_ab", "target_pair_rmsd"),
|
| 136 |
+
("target_pair_rmsd", "direction_score"),
|
| 137 |
+
("target_pair_rmsd", "gain_score"),
|
| 138 |
+
("target_pair_rmsd", "cycle_error_mean"),
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
rows = []
|
| 142 |
+
for x, y in pairs:
|
| 143 |
+
rows.append({
|
| 144 |
+
"x": x,
|
| 145 |
+
"y": y,
|
| 146 |
+
"n": int(df[[x, y]].replace([np.inf, -np.inf], np.nan).dropna().shape[0]),
|
| 147 |
+
"pearson": corr(df, x, y, "pearson"),
|
| 148 |
+
"pearson_perm_p": permutation_pvalue(df, x, y, "pearson"),
|
| 149 |
+
"spearman": corr(df, x, y, "spearman"),
|
| 150 |
+
"spearman_perm_p": permutation_pvalue(df, x, y, "spearman"),
|
| 151 |
+
"loo_pearson_min": leave_one_out(df, x, y, "pearson")["min"],
|
| 152 |
+
"loo_pearson_max": leave_one_out(df, x, y, "pearson")["max"],
|
| 153 |
+
"loo_spearman_min": leave_one_out(df, x, y, "spearman")["min"],
|
| 154 |
+
"loo_spearman_max": leave_one_out(df, x, y, "spearman")["max"],
|
| 155 |
+
})
|
| 156 |
+
corr_df = pd.DataFrame(rows)
|
| 157 |
+
|
| 158 |
+
partial_rows = []
|
| 159 |
+
for y in ["direction_score", "gain_score", "cycle_error_mean"]:
|
| 160 |
+
partial_rows.append({
|
| 161 |
+
"x": "coeff_cos_ab",
|
| 162 |
+
"y": y,
|
| 163 |
+
"control": "target_pair_rmsd",
|
| 164 |
+
"partial_pearson": partial_corr(df, "coeff_cos_ab", y, "target_pair_rmsd", "pearson"),
|
| 165 |
+
"partial_spearman": partial_corr(df, "coeff_cos_ab", y, "target_pair_rmsd", "spearman"),
|
| 166 |
+
})
|
| 167 |
+
partial_df = pd.DataFrame(partial_rows)
|
| 168 |
+
|
| 169 |
+
bin_df = pd.DataFrame()
|
| 170 |
+
bins = pd.cut(
|
| 171 |
+
df["coeff_cos_ab"],
|
| 172 |
+
bins=[-1.01, -0.9, -0.75, -0.5, 0.0, 0.5, 1.01],
|
| 173 |
+
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"],
|
| 174 |
+
)
|
| 175 |
+
bin_df = df.groupby(bins, observed=False).agg(
|
| 176 |
+
n=("coeff_cos_ab", "count"),
|
| 177 |
+
target_pair_rmsd_mean=("target_pair_rmsd", "mean"),
|
| 178 |
+
target_pair_rmsd_median=("target_pair_rmsd", "median"),
|
| 179 |
+
direction_score_mean=("direction_score", "mean"),
|
| 180 |
+
direction_score_median=("direction_score", "median"),
|
| 181 |
+
gain_score_mean=("gain_score", "mean"),
|
| 182 |
+
gain_score_median=("gain_score", "median"),
|
| 183 |
+
cycle_error_mean=("cycle_error_mean", "mean"),
|
| 184 |
+
).reset_index().rename(columns={"coeff_cos_ab": "coeff_cos_bin"})
|
| 185 |
+
|
| 186 |
+
distribution = {
|
| 187 |
+
"n": int(len(df)),
|
| 188 |
+
"coeff_cos_ab": summarize_series(df["coeff_cos_ab"]),
|
| 189 |
+
"target_pair_rmsd": summarize_series(df["target_pair_rmsd"]),
|
| 190 |
+
"direction_score": summarize_series(df["direction_score"]),
|
| 191 |
+
"gain_score": summarize_series(df["gain_score"]),
|
| 192 |
+
"cycle_error_mean": summarize_series(df["cycle_error_mean"]),
|
| 193 |
+
}
|
| 194 |
+
if "coeff_signflip_frac_ab" in df.columns:
|
| 195 |
+
distribution["coeff_signflip_frac_ab"] = summarize_series(df["coeff_signflip_frac_ab"])
|
| 196 |
+
|
| 197 |
+
counts = {
|
| 198 |
+
"n_total": int(len(df)),
|
| 199 |
+
"n_cos_lt_minus_0p9": int((df["coeff_cos_ab"] < -0.9).sum()),
|
| 200 |
+
"n_cos_lt_minus_0p75": int((df["coeff_cos_ab"] < -0.75).sum()),
|
| 201 |
+
"n_cos_lt_minus_0p5": int((df["coeff_cos_ab"] < -0.5).sum()),
|
| 202 |
+
"n_cos_ge_0p5": int((df["coeff_cos_ab"] >= 0.5).sum()),
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
scatter_cols = [
|
| 206 |
+
"pdb_name",
|
| 207 |
+
"frame_a",
|
| 208 |
+
"frame_b",
|
| 209 |
+
"coeff_cos_ab",
|
| 210 |
+
"target_pair_rmsd",
|
| 211 |
+
"direction_score",
|
| 212 |
+
"gain_score",
|
| 213 |
+
"cycle_error_mean",
|
| 214 |
+
"generated_pair_rmsd",
|
| 215 |
+
]
|
| 216 |
+
if "coeff_signflip_frac_ab" in df.columns:
|
| 217 |
+
scatter_cols.append("coeff_signflip_frac_ab")
|
| 218 |
+
scatter_cols = [c for c in scatter_cols if c in df.columns]
|
| 219 |
+
scatter_df = df[scatter_cols].sort_values("coeff_cos_ab")
|
| 220 |
+
|
| 221 |
+
corr_df.to_csv(out_dir / "confound_correlations.csv", index=False)
|
| 222 |
+
partial_df.to_csv(out_dir / "confound_partial_correlations.csv", index=False)
|
| 223 |
+
bin_df.to_csv(out_dir / "confound_coeff_cos_bins.csv", index=False)
|
| 224 |
+
scatter_df.to_csv(out_dir / "confound_scatter_points.csv", index=False)
|
| 225 |
+
(out_dir / "confound_distribution.json").write_text(json.dumps(distribution, indent=2), encoding="utf-8")
|
| 226 |
+
(out_dir / "confound_counts.json").write_text(json.dumps(counts, indent=2), encoding="utf-8")
|
| 227 |
+
|
| 228 |
+
print("===== counts =====")
|
| 229 |
+
print(json.dumps(counts, indent=2))
|
| 230 |
+
print("\n===== distributions =====")
|
| 231 |
+
print(json.dumps(distribution, indent=2))
|
| 232 |
+
print("\n===== correlations and permutation p-values =====")
|
| 233 |
+
print(corr_df.to_string(index=False))
|
| 234 |
+
print("\n===== partial correlations controlling target_pair_rmsd =====")
|
| 235 |
+
print(partial_df.to_string(index=False))
|
| 236 |
+
print("\n===== coeff cosine bins =====")
|
| 237 |
+
print(bin_df.to_string(index=False))
|
| 238 |
+
print("\n===== scatter points sorted by coeff_cos_ab =====")
|
| 239 |
+
print(scatter_df.to_string(index=False))
|
| 240 |
+
print("\nSaved:", out_dir)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
if __name__ == "__main__":
|
| 244 |
+
main()
|
bbflow_base/scripts/audit_sign_loss_vs_response.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def corr(x, y, method):
|
| 9 |
+
valid = pd.DataFrame({"x": x, "y": y}).replace([np.inf, -np.inf], np.nan).dropna()
|
| 10 |
+
if len(valid) < 3:
|
| 11 |
+
return float("nan")
|
| 12 |
+
if valid["x"].nunique() < 2 or valid["y"].nunique() < 2:
|
| 13 |
+
return float("nan")
|
| 14 |
+
return float(valid["x"].corr(valid["y"], method=method))
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def find_audit_csv(audit_dir: Path):
|
| 18 |
+
candidates = []
|
| 19 |
+
for p in audit_dir.glob("*.csv"):
|
| 20 |
+
try:
|
| 21 |
+
cols = set(pd.read_csv(p, nrows=2).columns)
|
| 22 |
+
except Exception:
|
| 23 |
+
continue
|
| 24 |
+
score = 0
|
| 25 |
+
for c in ["coeff_cos_ab", "coeff_signflip_frac_ab", "pdb_name", "frame_a", "frame_b"]:
|
| 26 |
+
if c in cols:
|
| 27 |
+
score += 1
|
| 28 |
+
if score >= 2:
|
| 29 |
+
candidates.append((score, p))
|
| 30 |
+
if not candidates:
|
| 31 |
+
raise FileNotFoundError(f"No usable audit csv found in {audit_dir}")
|
| 32 |
+
return sorted(candidates, reverse=True)[0][1]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def main():
|
| 36 |
+
ap = argparse.ArgumentParser()
|
| 37 |
+
ap.add_argument("--audit_dir", required=True)
|
| 38 |
+
ap.add_argument("--matched_csv", required=True)
|
| 39 |
+
ap.add_argument("--out_dir", required=True)
|
| 40 |
+
args = ap.parse_args()
|
| 41 |
+
|
| 42 |
+
audit_dir = Path(args.audit_dir)
|
| 43 |
+
out_dir = Path(args.out_dir)
|
| 44 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 45 |
+
|
| 46 |
+
audit_csv = find_audit_csv(audit_dir)
|
| 47 |
+
audit = pd.read_csv(audit_csv)
|
| 48 |
+
matched = pd.read_csv(args.matched_csv)
|
| 49 |
+
|
| 50 |
+
rename = {}
|
| 51 |
+
if "name" in audit.columns and "pdb_name" not in audit.columns:
|
| 52 |
+
rename["name"] = "pdb_name"
|
| 53 |
+
audit = audit.rename(columns=rename)
|
| 54 |
+
|
| 55 |
+
join_cols = [c for c in ["pdb_name", "frame_a", "frame_b"] if c in audit.columns and c in matched.columns]
|
| 56 |
+
if "pdb_name" not in join_cols:
|
| 57 |
+
raise ValueError(f"Cannot join: audit columns={audit.columns.tolist()} matched columns={matched.columns.tolist()}")
|
| 58 |
+
|
| 59 |
+
merged = matched.merge(audit, on=join_cols, how="inner", suffixes=("", "_audit"))
|
| 60 |
+
if len(merged) == 0:
|
| 61 |
+
raise ValueError("Join produced zero rows.")
|
| 62 |
+
|
| 63 |
+
x_cols = [c for c in ["coeff_cos_ab", "coeff_signflip_frac_ab"] if c in merged.columns]
|
| 64 |
+
y_cols = [
|
| 65 |
+
"direction_score",
|
| 66 |
+
"gain_score",
|
| 67 |
+
"cycle_error_mean",
|
| 68 |
+
"generated_pair_rmsd",
|
| 69 |
+
"coeff_direction_score",
|
| 70 |
+
"coeff_gain_score",
|
| 71 |
+
]
|
| 72 |
+
y_cols = [c for c in y_cols if c in merged.columns]
|
| 73 |
+
|
| 74 |
+
rows = []
|
| 75 |
+
for x in x_cols:
|
| 76 |
+
for y in y_cols:
|
| 77 |
+
rows.append({
|
| 78 |
+
"x": x,
|
| 79 |
+
"y": y,
|
| 80 |
+
"n": int(merged[[x, y]].replace([np.inf, -np.inf], np.nan).dropna().shape[0]),
|
| 81 |
+
"pearson": corr(merged[x], merged[y], "pearson"),
|
| 82 |
+
"spearman": corr(merged[x], merged[y], "spearman"),
|
| 83 |
+
})
|
| 84 |
+
corr_df = pd.DataFrame(rows)
|
| 85 |
+
|
| 86 |
+
if "coeff_cos_ab" in merged.columns:
|
| 87 |
+
bins = pd.cut(
|
| 88 |
+
merged["coeff_cos_ab"],
|
| 89 |
+
bins=[-1.01, -0.5, 0.0, 0.5, 1.01],
|
| 90 |
+
labels=["cos<-0.5", "-0.5<=cos<0", "0<=cos<0.5", "cos>=0.5"],
|
| 91 |
+
)
|
| 92 |
+
bin_df = merged.groupby(bins, observed=False).agg(
|
| 93 |
+
n=("pdb_name", "count"),
|
| 94 |
+
direction_score_mean=("direction_score", "mean"),
|
| 95 |
+
gain_score_mean=("gain_score", "mean"),
|
| 96 |
+
cycle_error_mean=("cycle_error_mean", "mean"),
|
| 97 |
+
generated_pair_rmsd_mean=("generated_pair_rmsd", "mean"),
|
| 98 |
+
coeff_signflip_frac_mean=("coeff_signflip_frac_ab", "mean") if "coeff_signflip_frac_ab" in merged.columns else ("pdb_name", "count"),
|
| 99 |
+
).reset_index().rename(columns={"coeff_cos_ab": "coeff_cos_bin"})
|
| 100 |
+
else:
|
| 101 |
+
bin_df = pd.DataFrame()
|
| 102 |
+
|
| 103 |
+
summary = {
|
| 104 |
+
"audit_csv": str(audit_csv),
|
| 105 |
+
"n_joined": int(len(merged)),
|
| 106 |
+
"audit_columns": audit.columns.tolist(),
|
| 107 |
+
"matched_columns": matched.columns.tolist(),
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
merged.to_csv(out_dir / "sign_loss_response_joined.csv", index=False)
|
| 111 |
+
corr_df.to_csv(out_dir / "sign_loss_response_correlations.csv", index=False)
|
| 112 |
+
bin_df.to_csv(out_dir / "sign_loss_response_bins.csv", index=False)
|
| 113 |
+
(out_dir / "sign_loss_response_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
|
| 114 |
+
|
| 115 |
+
print("===== joined summary =====")
|
| 116 |
+
print(json.dumps(summary, indent=2))
|
| 117 |
+
print("\n===== correlations =====")
|
| 118 |
+
print(corr_df.to_string(index=False))
|
| 119 |
+
print("\n===== coeff cosine bins =====")
|
| 120 |
+
print(bin_df.to_string(index=False))
|
| 121 |
+
print("\nSaved:", out_dir)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
main()
|