diff --git a/bbflow_base/base_stages/00_extract_shape_fingerprints.sh b/bbflow_base/base_stages/00_extract_shape_fingerprints.sh new file mode 100644 index 0000000000000000000000000000000000000000..6d6cbf8a06a44ed45a04d3e53bbe503e8a66d931 --- /dev/null +++ b/bbflow_base/base_stages/00_extract_shape_fingerprints.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +ATLAS_DATASET_DIR="${ATLAS_DATASET_DIR:-${ATLAS_REPRO_ROOT}/datasets/ATLAS}" +FINGERPRINT_CACHE="${FINGERPRINT_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k8.pt}" +SHAPE_K="${SHAPE_K:-5}" +NUM_MODES="${NUM_MODES:-8}" + +TRAIN_CSV="${TRAIN_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/train/ATLAS_train.csv}" +VAL_CSV="${VAL_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/validation/ATLAS_validation.csv}" +TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" + +echo "[base:extract] Offline full-MD motion targets" +echo " ATLAS_DATASET_DIR=${ATLAS_DATASET_DIR}" +echo " FINGERPRINT_CACHE=${FINGERPRINT_CACHE}" +echo " SHAPE_K=${SHAPE_K} (legacy arg; motion targets do not use global spectrum)" +echo " NUM_MODES=${NUM_MODES} (oracle PCA modes stored in motion targets)" + +python scripts/extract_shape_fingerprints.py \ + --atlas_root "${ATLAS_DATASET_DIR}" \ + --csv "${TRAIN_CSV}" \ + --csv "${VAL_CSV}" \ + --csv "${TEST_CSV}" \ + --out_path "${FINGERPRINT_CACHE}" \ + --shape_k "${SHAPE_K}" \ + --num_modes "${NUM_MODES}" + +ls -lh "${FINGERPRINT_CACHE}" "${FINGERPRINT_CACHE%.pt}.tsv" diff --git a/bbflow_base/base_stages/00_train_base_ddp.sh b/bbflow_base/base_stages/00_train_base_ddp.sh new file mode 100644 index 0000000000000000000000000000000000000000..e39efca980f52302461d76806f4afb02910055f1 --- /dev/null +++ b/bbflow_base/base_stages/00_train_base_ddp.sh @@ -0,0 +1,155 @@ +#!/usr/bin/env bash +set -e +set -u +set -o pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +PROJECT_ROOT="$(cd "${BBFLOW_ROOT}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_template_modes_k8_fp32_15ep_ddp}" +GPU_IDS="${GPU_IDS:-0,1}" +NUM_DEVICES="${NUM_DEVICES:-2}" + +DEFAULT_BASE_CKPT="${BBFLOW_ROOT}/models/bbflow-0.1/bbflow-0.1.ckpt" +if [[ ! -f "${DEFAULT_BASE_CKPT}" && -f "${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" ]]; then + DEFAULT_BASE_CKPT="${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" +fi +BASE_CKPT="${BASE_CKPT:-${DEFAULT_BASE_CKPT}}" +LATENT_DIM="${LATENT_DIM:-16}" +NUM_MODES="${NUM_MODES:-8}" +MOTION_MESSAGE_PASSING_LAYERS="${MOTION_MESSAGE_PASSING_LAYERS:-4}" +CROSS_COV_NEAR_DISTANCE="${CROSS_COV_NEAR_DISTANCE:-12.0}" +TEMPLATE_RESIDUAL_SCALE="${TEMPLATE_RESIDUAL_SCALE:-0.1}" +TEMPLATE_REMOVE_ROTATION="${TEMPLATE_REMOVE_ROTATION:-true}" +ENM_NUM_MODES="${ENM_NUM_MODES:-${NUM_MODES}}" +ENM_CUTOFF="${ENM_CUTOFF:-12.0}" +ENM_EPS="${ENM_EPS:-1e-6}" +LAMBDA_SHAPE="${LAMBDA_SHAPE:-1.0}" +LAMBDA_LOCAL_COV="${LAMBDA_LOCAL_COV:-1.0}" +LAMBDA_CROSS_COV="${LAMBDA_CROSS_COV:-1.0}" +LAMBDA_RMSF="${LAMBDA_RMSF:-0.25}" +ENM_WARMUP_EPOCHS="${ENM_WARMUP_EPOCHS:-0}" +LAMBDA_ENM_WARMUP="${LAMBDA_ENM_WARMUP:-1.0}" +SHAPE_K="${SHAPE_K:-5}" +INJECT_EMBEDDER="${INJECT_EMBEDDER:-true}" +INJECT_FILM="${INJECT_FILM:-true}" +ACTIVATION_CHECKPOINT="${ACTIVATION_CHECKPOINT:-true}" +FREEZE_FOUNDATION="${FREEZE_FOUNDATION:-false}" +Z_STOCHASTIC="${Z_STOCHASTIC:-false}" +MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-400000}" +MAX_BATCH_SIZE="${MAX_BATCH_SIZE:-32}" +PRECISION="${PRECISION:-32-true}" +MAX_EPOCHS="${MAX_EPOCHS:-15}" +CHECKPOINT_EVERY_N_EPOCHS="${CHECKPOINT_EVERY_N_EPOCHS:-1}" +CHECKPOINT_SAVE_LAST="${CHECKPOINT_SAVE_LAST:-true}" +CHECKPOINT_SAVE_TOP_K="${CHECKPOINT_SAVE_TOP_K:--1}" +RESET_EPOCH="${RESET_EPOCH:-false}" +RESET_OPTIMIZER_ON_LOAD="${RESET_OPTIMIZER_ON_LOAD:-false}" +EPOCH_CONDITION_PROBE="${EPOCH_CONDITION_PROBE:-true}" +CONDITION_PROBE_SCALE="${CONDITION_PROBE_SCALE:-2.0}" +LAMBDA_GENERATOR_COV="${LAMBDA_GENERATOR_COV:-0.0}" +GENERATOR_COV_USE_CROSS="${GENERATOR_COV_USE_CROSS:-false}" +GENERATOR_COV_T_MIN="${GENERATOR_COV_T_MIN:-0.1}" +GENERATOR_COV_T_MAX="${GENERATOR_COV_T_MAX:-0.6}" +GENERATOR_COV_DELTA_SCALE="${GENERATOR_COV_DELTA_SCALE:-1.0}" +GENERATOR_COV_NUM_DELTAS="${GENERATOR_COV_NUM_DELTAS:-2}" +GENERATOR_COV_CHECKPOINT="${GENERATOR_COV_CHECKPOINT:-true}" +GENERATOR_COV_INITIAL_TRACE_ANCHOR="${GENERATOR_COV_INITIAL_TRACE_ANCHOR:-true}" +LAMBDA_GEN_LOCAL_SHAPE="${LAMBDA_GEN_LOCAL_SHAPE:-1.0}" +LAMBDA_GEN_CROSS_SHAPE="${LAMBDA_GEN_CROSS_SHAPE:-1.0}" +LAMBDA_GEN_TRACE_ANCHOR="${LAMBDA_GEN_TRACE_ANCHOR:-0.05}" +FINGERPRINT_CACHE="${FINGERPRINT_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k${NUM_MODES}.pt}" + +TRAIN_CSV="${TRAIN_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/train/ATLAS_train.csv}" +VAL_CSV="${VAL_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/validation/ATLAS_validation.csv}" +TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +ATLAS_DATASET_DIR="${ATLAS_DATASET_DIR:-${ATLAS_REPRO_ROOT}/datasets/ATLAS}" + +mkdir -p "${RUN_DIR}" + +echo "[base:00] Train template-mode prior BBFlow" +echo " RUN_DIR=${RUN_DIR}" +echo " GPU_IDS=${GPU_IDS} NUM_DEVICES=${NUM_DEVICES}" +echo " BASE_CKPT=${BASE_CKPT}" +echo " NUM_MODES=${NUM_MODES} MPNN_LAYERS=${MOTION_MESSAGE_PASSING_LAYERS} NEAR_DIST_A=${CROSS_COV_NEAR_DISTANCE} TEMPLATE_RESIDUAL_SCALE=${TEMPLATE_RESIDUAL_SCALE} TEMPLATE_REMOVE_ROTATION=${TEMPLATE_REMOVE_ROTATION} ENM_NUM_MODES=${ENM_NUM_MODES} ENM_CUTOFF=${ENM_CUTOFF} LATENT_DIM=${LATENT_DIM} FREEZE_FOUNDATION=${FREEZE_FOUNDATION}" +echo " MOTION_TARGET_CACHE=${FINGERPRINT_CACHE}" +echo " INJECT_EMBEDDER=${INJECT_EMBEDDER} INJECT_FILM=${INJECT_FILM} ACTIVATION_CHECKPOINT=${ACTIVATION_CHECKPOINT}" +echo " FORCE_GROUPED_BATCH=false ENSEMBLE_GROUP_SIZE=0" +echo " MAX_NUM_RES_SQUARED=${MAX_NUM_RES_SQUARED} MAX_BATCH_SIZE=${MAX_BATCH_SIZE} PRECISION=${PRECISION}" +echo " ENM_WARMUP_EPOCHS=${ENM_WARMUP_EPOCHS} LAMBDA_ENM_WARMUP=${LAMBDA_ENM_WARMUP}" +echo " CHECKPOINT_EVERY_N_EPOCHS=${CHECKPOINT_EVERY_N_EPOCHS} CHECKPOINT_SAVE_LAST=${CHECKPOINT_SAVE_LAST} CHECKPOINT_SAVE_TOP_K=${CHECKPOINT_SAVE_TOP_K}" +echo " RESET_EPOCH=${RESET_EPOCH} RESET_OPTIMIZER_ON_LOAD=${RESET_OPTIMIZER_ON_LOAD}" +echo " EPOCH_CONDITION_PROBE=${EPOCH_CONDITION_PROBE} CONDITION_PROBE_SCALE=${CONDITION_PROBE_SCALE}" +echo " LAMBDA_GENERATOR_COV=${LAMBDA_GENERATOR_COV} GEN_NUM_DELTAS=${GENERATOR_COV_NUM_DELTAS} GEN_USE_CROSS=${GENERATOR_COV_USE_CROSS} GEN_TRACE_ANCHOR=${LAMBDA_GEN_TRACE_ANCHOR}" + +CUDA_VISIBLE_DEVICES="${GPU_IDS}" python experiments/train.py \ + latent.enable=true \ + latent.dim="${LATENT_DIM}" \ + latent.num_modes="${NUM_MODES}" \ + latent.motion_message_passing_layers="${MOTION_MESSAGE_PASSING_LAYERS}" \ + latent.cross_cov_near_distance="${CROSS_COV_NEAR_DISTANCE}" \ + latent.template_residual_scale="${TEMPLATE_RESIDUAL_SCALE}" \ + latent.template_remove_rotation="${TEMPLATE_REMOVE_ROTATION}" \ + latent.enm_num_modes="${ENM_NUM_MODES}" \ + latent.enm_cutoff="${ENM_CUTOFF}" \ + latent.enm_eps="${ENM_EPS}" \ + latent.node_cond_dim="${NUM_MODES}" \ + latent.edge_cond_dim="${NUM_MODES}" \ + latent.freeze_foundation="${FREEZE_FOUNDATION}" \ + latent.inject_embedder="${INJECT_EMBEDDER}" \ + latent.inject_film="${INJECT_FILM}" \ + latent.activation_checkpoint="${ACTIVATION_CHECKPOINT}" \ + latent.shape_fingerprint_k="${SHAPE_K}" \ + latent.shape_fingerprint_cache_path="${FINGERPRINT_CACHE}" \ + latent.motion_target_cache_path="${FINGERPRINT_CACHE}" \ + latent.z_stochastic="${Z_STOCHASTIC}" \ + experiment.num_devices="${NUM_DEVICES}" \ + experiment.training.force_grouped_batch=false \ + experiment.training.ensemble_group_size=0 \ + experiment.training.lambda_shape="${LAMBDA_SHAPE}" \ + experiment.training.lambda_local_cov="${LAMBDA_LOCAL_COV}" \ + experiment.training.lambda_cross_cov="${LAMBDA_CROSS_COV}" \ + experiment.training.lambda_rmsf="${LAMBDA_RMSF}" \ + experiment.training.enm_warmup_epochs="${ENM_WARMUP_EPOCHS}" \ + experiment.training.lambda_enm_warmup="${LAMBDA_ENM_WARMUP}" \ + experiment.training.epoch_condition_probe="${EPOCH_CONDITION_PROBE}" \ + experiment.training.condition_probe_scale="${CONDITION_PROBE_SCALE}" \ + experiment.training.lambda_generator_cov="${LAMBDA_GENERATOR_COV}" \ + experiment.training.generator_cov_use_cross="${GENERATOR_COV_USE_CROSS}" \ + experiment.training.generator_cov_t_min="${GENERATOR_COV_T_MIN}" \ + experiment.training.generator_cov_t_max="${GENERATOR_COV_T_MAX}" \ + experiment.training.generator_cov_delta_scale="${GENERATOR_COV_DELTA_SCALE}" \ + experiment.training.generator_cov_num_deltas="${GENERATOR_COV_NUM_DELTAS}" \ + experiment.training.generator_cov_checkpoint="${GENERATOR_COV_CHECKPOINT}" \ + experiment.training.generator_cov_initial_trace_anchor="${GENERATOR_COV_INITIAL_TRACE_ANCHOR}" \ + experiment.training.lambda_gen_local_shape="${LAMBDA_GEN_LOCAL_SHAPE}" \ + experiment.training.lambda_gen_cross_shape="${LAMBDA_GEN_CROSS_SHAPE}" \ + experiment.training.lambda_gen_trace_anchor="${LAMBDA_GEN_TRACE_ANCHOR}" \ + data.sampler.max_num_res_squared="${MAX_NUM_RES_SQUARED}" \ + data.sampler.max_batch_size="${MAX_BATCH_SIZE}" \ + experiment.trainer.precision="${PRECISION}" \ + experiment.trainer.default_root_dir="${RUN_DIR}" \ + experiment.use_wandb=false \ + experiment.warm_start="${BASE_CKPT}" \ + experiment.warm_start_cfg_override=false \ + experiment.reset_epoch="${RESET_EPOCH}" \ + experiment.reset_optimizer_on_load="${RESET_OPTIMIZER_ON_LOAD}" \ + experiment.wandb.name="$(basename "${RUN_DIR}")" \ + experiment.trainer.max_epochs="${MAX_EPOCHS}" \ + +experiment.trainer.num_sanity_val_steps=0 \ + experiment.first_val_epoch=inf \ + experiment.checkpointer.dirpath="${RUN_DIR}" \ + experiment.checkpointer.every_n_epochs="${CHECKPOINT_EVERY_N_EPOCHS}" \ + experiment.checkpointer.save_last="${CHECKPOINT_SAVE_LAST}" \ + experiment.checkpointer.save_top_k="${CHECKPOINT_SAVE_TOP_K}" \ + data.dataset.train_csv_path="${TRAIN_CSV}" \ + "data.dataset.valid_csv_paths=[${VAL_CSV}]" \ + "data.dataset.valid_dataset_names=[ATLAS_validation]" \ + data.dataset.test_csv_path="${TEST_CSV}" \ + data.dataset.split_path="${RUN_DIR}" \ + "data.validation.valid_xtc_paths=[${ATLAS_DATASET_DIR}]" + +echo "[base:00] Latent metrics: ${RUN_DIR}/latent_train_epoch_metrics.csv" diff --git a/bbflow_base/base_stages/00_train_base_pure_ddp.sh b/bbflow_base/base_stages/00_train_base_pure_ddp.sh new file mode 100644 index 0000000000000000000000000000000000000000..97bdd4a781fe9c2352ac9bc8147ac3b5495ab6da --- /dev/null +++ b/bbflow_base/base_stages/00_train_base_pure_ddp.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +PROJECT_ROOT="$(cd "${BBFLOW_ROOT}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_pure_main_15ep_ddp}" +GPU_IDS="${GPU_IDS:-0,1}" +NUM_DEVICES="${NUM_DEVICES:-2}" + +DEFAULT_BASE_CKPT="${BBFLOW_ROOT}/models/bbflow-0.1/bbflow-0.1.ckpt" +if [[ ! -f "${DEFAULT_BASE_CKPT}" && -f "${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" ]]; then + DEFAULT_BASE_CKPT="${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" +fi +BASE_CKPT="${BASE_CKPT:-${DEFAULT_BASE_CKPT}}" +LATENT_DIM="${LATENT_DIM:-16}" +NUM_MODES="${NUM_MODES:-8}" +MOTION_MESSAGE_PASSING_LAYERS="${MOTION_MESSAGE_PASSING_LAYERS:-4}" +CROSS_COV_NEAR_DISTANCE="${CROSS_COV_NEAR_DISTANCE:-12.0}" +TEMPLATE_RESIDUAL_SCALE="${TEMPLATE_RESIDUAL_SCALE:-0.1}" +TEMPLATE_REMOVE_ROTATION="${TEMPLATE_REMOVE_ROTATION:-true}" +MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-400000}" +MAX_BATCH_SIZE="${MAX_BATCH_SIZE:-32}" +PRECISION="${PRECISION:-32-true}" +MAX_EPOCHS="${MAX_EPOCHS:-15}" +FINGERPRINT_CACHE="${FINGERPRINT_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k${NUM_MODES}.pt}" + +TRAIN_CSV="${TRAIN_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/train/ATLAS_train.csv}" +VAL_CSV="${VAL_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/validation/ATLAS_validation.csv}" +TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +ATLAS_DATASET_DIR="${ATLAS_DATASET_DIR:-${ATLAS_REPRO_ROOT}/datasets/ATLAS}" + +mkdir -p "${RUN_DIR}" + +echo "[base:00] Train pure main BBFlow (no ENM warmup)" +echo " RUN_DIR=${RUN_DIR}" +echo " GPU_IDS=${GPU_IDS} NUM_DEVICES=${NUM_DEVICES}" +echo " BASE_CKPT=${BASE_CKPT}" +echo " NUM_MODES=${NUM_MODES} MPNN_LAYERS=${MOTION_MESSAGE_PASSING_LAYERS} NEAR_DIST_A=${CROSS_COV_NEAR_DISTANCE} TEMPLATE_RESIDUAL_SCALE=${TEMPLATE_RESIDUAL_SCALE} TEMPLATE_REMOVE_ROTATION=${TEMPLATE_REMOVE_ROTATION}" +echo " MOTION_TARGET_CACHE=${FINGERPRINT_CACHE}" +echo " INJECT_EMBEDDER=true INJECT_FILM=true ACTIVATION_CHECKPOINT=true" +echo " FORCE_GROUPED_BATCH=false ENSEMBLE_GROUP_SIZE=0" +echo " MAX_NUM_RES_SQUARED=${MAX_NUM_RES_SQUARED} MAX_BATCH_SIZE=${MAX_BATCH_SIZE} PRECISION=${PRECISION}" + +CUDA_VISIBLE_DEVICES="${GPU_IDS}" python experiments/train.py \ + latent.enable=true \ + latent.dim="${LATENT_DIM}" \ + latent.num_modes="${NUM_MODES}" \ + latent.motion_message_passing_layers="${MOTION_MESSAGE_PASSING_LAYERS}" \ + latent.cross_cov_near_distance="${CROSS_COV_NEAR_DISTANCE}" \ + latent.template_residual_scale="${TEMPLATE_RESIDUAL_SCALE}" \ + latent.template_remove_rotation="${TEMPLATE_REMOVE_ROTATION}" \ + latent.node_cond_dim="${NUM_MODES}" \ + latent.edge_cond_dim="${NUM_MODES}" \ + latent.freeze_foundation=false \ + latent.inject_embedder=true \ + latent.inject_film=true \ + latent.activation_checkpoint=true \ + latent.shape_fingerprint_k=5 \ + latent.shape_fingerprint_cache_path="${FINGERPRINT_CACHE}" \ + latent.motion_target_cache_path="${FINGERPRINT_CACHE}" \ + latent.z_stochastic=false \ + experiment.num_devices="${NUM_DEVICES}" \ + experiment.training.force_grouped_batch=false \ + experiment.training.ensemble_group_size=0 \ + experiment.training.lambda_shape=1.0 \ + experiment.training.lambda_local_cov=1.0 \ + experiment.training.lambda_cross_cov=1.0 \ + experiment.training.lambda_rmsf=0.25 \ + data.sampler.max_num_res_squared="${MAX_NUM_RES_SQUARED}" \ + data.sampler.max_batch_size="${MAX_BATCH_SIZE}" \ + experiment.trainer.precision="${PRECISION}" \ + experiment.trainer.default_root_dir="${RUN_DIR}" \ + experiment.use_wandb=false \ + experiment.warm_start="${BASE_CKPT}" \ + experiment.warm_start_cfg_override=false \ + experiment.wandb.name="$(basename "${RUN_DIR}")" \ + experiment.trainer.max_epochs="${MAX_EPOCHS}" \ + +experiment.trainer.num_sanity_val_steps=0 \ + experiment.first_val_epoch=inf \ + experiment.checkpointer.dirpath="${RUN_DIR}" \ + data.dataset.train_csv_path="${TRAIN_CSV}" \ + "data.dataset.valid_csv_paths=[${VAL_CSV}]" \ + "data.dataset.valid_dataset_names=[ATLAS_validation]" \ + data.dataset.test_csv_path="${TEST_CSV}" \ + data.dataset.split_path="${RUN_DIR}" \ + "data.validation.valid_xtc_paths=[${ATLAS_DATASET_DIR}]" + +echo "[base:00] Latent metrics: ${RUN_DIR}/latent_train_epoch_metrics.csv" diff --git a/bbflow_base/base_stages/00_train_base_pure_then_probe_ddp.sh b/bbflow_base/base_stages/00_train_base_pure_then_probe_ddp.sh new file mode 100644 index 0000000000000000000000000000000000000000..916d0c329856747333495e7000bda05d77a528c5 --- /dev/null +++ b/bbflow_base/base_stages/00_train_base_pure_then_probe_ddp.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_pure_main_15ep_ddp}" +TRAIN_STAGE="${TRAIN_STAGE:-base_stages/00_train_base_pure_ddp.sh}" +PROBE_STAGE="${PROBE_STAGE:-base_stages/06_probe_condition_ensemble_cov.sh}" +PROBE_NUM_PROTEINS="${PROBE_NUM_PROTEINS:-3}" +PROBE_NUM_SAMPLES="${PROBE_NUM_SAMPLES:-50}" +PROBE_BATCH_SIZE="${PROBE_BATCH_SIZE:-10}" +PROBE_GPU_ID="${PROBE_GPU_ID:-0}" + +echo "[base:00+06] Run training then condition ensemble probe" +echo " TRAIN_STAGE=${TRAIN_STAGE}" +echo " PROBE_STAGE=${PROBE_STAGE}" +echo " RUN_DIR=${RUN_DIR}" +echo " PROBE_NUM_PROTEINS=${PROBE_NUM_PROTEINS} PROBE_NUM_SAMPLES=${PROBE_NUM_SAMPLES} PROBE_BATCH_SIZE=${PROBE_BATCH_SIZE} PROBE_GPU_ID=${PROBE_GPU_ID}" + +bash "${TRAIN_STAGE}" + +RUN_DIR="${RUN_DIR}" \ +GPU_ID="${PROBE_GPU_ID}" \ +NUM_PROTEINS="${PROBE_NUM_PROTEINS}" \ +NUM_SAMPLES="${PROBE_NUM_SAMPLES}" \ +BATCH_SIZE="${PROBE_BATCH_SIZE}" \ +bash "${PROBE_STAGE}" diff --git a/bbflow_base/base_stages/00_train_final_mog_ddp.sh b/bbflow_base/base_stages/00_train_final_mog_ddp.sh new file mode 100644 index 0000000000000000000000000000000000000000..df763b09481c335dcb77d78b708333a93c0c3818 --- /dev/null +++ b/bbflow_base/base_stages/00_train_final_mog_ddp.sh @@ -0,0 +1,239 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +PROJECT_ROOT="$(cd "${BBFLOW_ROOT}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_final_mog_k8_m2_30ep_ddp}" +GPU_IDS="${GPU_IDS:-0,1,2}" +NUM_DEVICES="${NUM_DEVICES:-3}" + +DEFAULT_BASE_CKPT="${BBFLOW_ROOT}/models/bbflow-0.1/bbflow-0.1.ckpt" +if [[ ! -f "${DEFAULT_BASE_CKPT}" && -f "${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" ]]; then + DEFAULT_BASE_CKPT="${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" +fi +BASE_CKPT="${BASE_CKPT:-${DEFAULT_BASE_CKPT}}" +LATENT_DIM="${LATENT_DIM:-16}" +NUM_MODES="${NUM_MODES:-8}" +MIXTURE_COMPONENTS="${MIXTURE_COMPONENTS:-2}" +Q_LSTSQ_RIDGE="${Q_LSTSQ_RIDGE:-1e-4}" +Q_CHOLESKY_JITTER="${Q_CHOLESKY_JITTER:-1e-4}" +Q_DETACH_PROJECTION="${Q_DETACH_PROJECTION:-true}" +Q_DETACH_SHARED_ENCODER="${Q_DETACH_SHARED_ENCODER:-false}" +ENERGY_FROM_Q="${ENERGY_FROM_Q:-false}" +ENERGY_FROM_Q_FULL_COV="${ENERGY_FROM_Q_FULL_COV:-false}" +LAMBDA_MOTION="${LAMBDA_MOTION:-1.0}" +LAMBDA_Q="${LAMBDA_Q:-1.0}" +LAMBDA_MODE_ORTH="${LAMBDA_MODE_ORTH:-0.0}" +LAMBDA_MODE_RECON="${LAMBDA_MODE_RECON:-0.0}" +LAMBDA_PCA_ALIGN="${LAMBDA_PCA_ALIGN:-0.0}" +LAMBDA_CONDITION_CYCLE="${LAMBDA_CONDITION_CYCLE:-0.0}" +# lambda_shape ALSO gates whether the MD motion-target cache is looked up at all +# (motion_loss_enabled := lambda_shape != 0), independent of LAMBDA_MOTION. Stage-1 +# (X_eq -> U only, via mode_recon+mode_orth) sets this to 0 so it needs no cache +# content -- the file only has to pass the field-name existence check below. +LAMBDA_SHAPE="${LAMBDA_SHAPE:-1.0}" +# Stage-2 switch: freeze U (trunk + template heads); see LatentEncoder.freeze_prior_backbone. +FREEZE_MODE_HEAD="${FREEZE_MODE_HEAD:-false}" +PCA_ALIGN_TOP_M="${PCA_ALIGN_TOP_M:-2}" +MOTION_MESSAGE_PASSING_LAYERS="${MOTION_MESSAGE_PASSING_LAYERS:-4}" +CROSS_COV_NEAR_DISTANCE="${CROSS_COV_NEAR_DISTANCE:-12.0}" +TEMPLATE_RESIDUAL_SCALE="${TEMPLATE_RESIDUAL_SCALE:-0.1}" +TEMPLATE_REMOVE_ROTATION="${TEMPLATE_REMOVE_ROTATION:-true}" +MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-400000}" +MAX_BATCH_SIZE="${MAX_BATCH_SIZE:-32}" +ENSEMBLE_GROUP_SIZE="${ENSEMBLE_GROUP_SIZE:-0}" +if [[ "${ENSEMBLE_GROUP_SIZE}" -gt 1 ]]; then + FORCE_GROUPED_BATCH=true +else + FORCE_GROUPED_BATCH=false +fi +PRECISION="${PRECISION:-bf16-mixed}" +ACTIVATION_CHECKPOINT="${ACTIVATION_CHECKPOINT:-true}" +MAX_EPOCHS="${MAX_EPOCHS:-30}" +MIN_EPOCHS="${MIN_EPOCHS:-1}" +MAX_STEPS="${MAX_STEPS:--1}" +TRAINER_PROFILER="${TRAINER_PROFILER:-null}" +SELF_CONDITION="${SELF_CONDITION:-true}" +EMBED_SELF_CONDITIONING="${EMBED_SELF_CONDITIONING:-true}" +if [[ "${EMBED_SELF_CONDITIONING}" != "true" ]]; then + echo "[base:00] ERROR: EMBED_SELF_CONDITIONING must stay true for checkpoint-compatible BBFlow inputs; set SELF_CONDITION=false to disable the extra self-conditioning forward." >&2 + return 2 2>/dev/null || exit 2 +fi +DIAGNOSTIC_INTERVAL_STEPS="${DIAGNOSTIC_INTERVAL_STEPS:-50}" +TRACK_CONDITION_DEBUG="${TRACK_CONDITION_DEBUG:-false}" +EPOCH_CONDITION_PROBE="${EPOCH_CONDITION_PROBE:-false}" +LOG_EVERY_N_STEPS="${LOG_EVERY_N_STEPS:-50}" +VALID_SAMPLES_PER_PROTEIN="${VALID_SAMPLES_PER_PROTEIN:-6}" +CHECKPOINT_EVERY_N_EPOCHS="${CHECKPOINT_EVERY_N_EPOCHS:-1}" +CHECKPOINT_SAVE_LAST="${CHECKPOINT_SAVE_LAST:-true}" +CHECKPOINT_SAVE_TOP_K="${CHECKPOINT_SAVE_TOP_K:--1}" +RESET_EPOCH="${RESET_EPOCH:-false}" +RESET_OPTIMIZER_ON_LOAD="${RESET_OPTIMIZER_ON_LOAD:-false}" +MODEL_ONLY_WARM_START="${MODEL_ONLY_WARM_START:-false}" +LAMBDA_GENERATOR_COV="${LAMBDA_GENERATOR_COV:-0.0}" +GENERATOR_COV_USE_CROSS="${GENERATOR_COV_USE_CROSS:-false}" +FREEZE_FOUNDATION="${FREEZE_FOUNDATION:-false}" +GENERATOR_COV_T_MIN="${GENERATOR_COV_T_MIN:-0.1}" +GENERATOR_COV_T_MAX="${GENERATOR_COV_T_MAX:-0.6}" +GENERATOR_COV_DELTA_SCALE="${GENERATOR_COV_DELTA_SCALE:-1.0}" +GENERATOR_COV_NUM_DELTAS="${GENERATOR_COV_NUM_DELTAS:-2}" +GENERATOR_COV_STUDENT_CHUNK_DELTAS="${GENERATOR_COV_STUDENT_CHUNK_DELTAS:-1}" +GENERATOR_COV_TEACHER_NUM_DELTAS="${GENERATOR_COV_TEACHER_NUM_DELTAS:-1}" +GENERATOR_COV_TEACHER_REUSE_STUDENT_DELTA="${GENERATOR_COV_TEACHER_REUSE_STUDENT_DELTA:-true}" +GENERATOR_COV_TEACHER_TRACE_DENOMINATOR="${GENERATOR_COV_TEACHER_TRACE_DENOMINATOR:-teacher}" +GENERATOR_COV_CHECKPOINT="${GENERATOR_COV_CHECKPOINT:-false}" +GENERATOR_COV_INITIAL_TRACE_ANCHOR="${GENERATOR_COV_INITIAL_TRACE_ANCHOR:-true}" +GENERATOR_COV_AMPLITUDE_ANCHOR="${GENERATOR_COV_AMPLITUDE_ANCHOR:-md_trace}" +GENERATOR_COV_ROLLOUT_CALIBRATION="${GENERATOR_COV_ROLLOUT_CALIBRATION:-false}" +GENERATOR_COV_ROLLOUT_STEPS="${GENERATOR_COV_ROLLOUT_STEPS:-2}" +GENERATOR_COV_ROLLOUT_NUM_DELTAS="${GENERATOR_COV_ROLLOUT_NUM_DELTAS:-1}" +GENERATOR_COV_ROLLOUT_MAX_EXAMPLES="${GENERATOR_COV_ROLLOUT_MAX_EXAMPLES:-4}" +GENERATOR_COV_ROLLOUT_INTERVAL_STEPS="${GENERATOR_COV_ROLLOUT_INTERVAL_STEPS:-200}" +GENERATOR_COV_ROLLOUT_EMA_DECAY="${GENERATOR_COV_ROLLOUT_EMA_DECAY:-0.9}" +LAMBDA_GEN_LOCAL_SHAPE="${LAMBDA_GEN_LOCAL_SHAPE:-1.0}" +LAMBDA_GEN_CROSS_SHAPE="${LAMBDA_GEN_CROSS_SHAPE:-1.0}" +LAMBDA_GEN_TRACE_ANCHOR="${LAMBDA_GEN_TRACE_ANCHOR:-0.05}" +FINGERPRINT_CACHE="${FINGERPRINT_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k${NUM_MODES}.pt}" +EXTRA_HYDRA_ARGS="${EXTRA_HYDRA_ARGS:-}" + +TRAIN_CSV="${TRAIN_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/train/ATLAS_train.csv}" +VAL_CSV="${VAL_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/validation/ATLAS_validation.csv}" +TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +ATLAS_DATASET_DIR="${ATLAS_DATASET_DIR:-${ATLAS_REPRO_ROOT}/datasets/ATLAS}" + +mkdir -p "${RUN_DIR}" + +CACHE_REQUIRE_FIELDS=(local_cov cross_cov rmsf oracle_mean_disp) +if [[ "${LAMBDA_PCA_ALIGN}" != "0" && "${LAMBDA_PCA_ALIGN}" != "0.0" ]]; then + CACHE_REQUIRE_FIELDS+=(oracle_modes oracle_energy) +fi + +python scripts/validate_motion_target_cache.py \ + --path "${FINGERPRINT_CACHE}" \ + --require "${CACHE_REQUIRE_FIELDS[@]}" + +echo "[base:00] Train final MoG per-conformation BBFlow" +echo " RUN_DIR=${RUN_DIR}" +echo " GPU_IDS=${GPU_IDS} NUM_DEVICES=${NUM_DEVICES} MAX_EPOCHS=${MAX_EPOCHS} VALID_SAMPLES_PER_PROTEIN=${VALID_SAMPLES_PER_PROTEIN}" +echo " BASE_CKPT=${BASE_CKPT}" +echo " NUM_MODES=${NUM_MODES} MIXTURE_COMPONENTS=${MIXTURE_COMPONENTS} Q_RIDGE=${Q_LSTSQ_RIDGE} Q_DETACH_PROJECTION=${Q_DETACH_PROJECTION} Q_DETACH_SHARED_ENCODER=${Q_DETACH_SHARED_ENCODER}" +echo " ENERGY_FROM_Q=${ENERGY_FROM_Q} ENERGY_FROM_Q_FULL_COV=${ENERGY_FROM_Q_FULL_COV}" +echo " LAMBDA_MOTION=${LAMBDA_MOTION} LAMBDA_Q=${LAMBDA_Q} LAMBDA_MODE_ORTH=${LAMBDA_MODE_ORTH} LAMBDA_MODE_RECON=${LAMBDA_MODE_RECON} LAMBDA_PCA_ALIGN=${LAMBDA_PCA_ALIGN} LAMBDA_CONDITION_CYCLE=${LAMBDA_CONDITION_CYCLE} PCA_ALIGN_TOP_M=${PCA_ALIGN_TOP_M} MOTION_TARGET_CACHE=${FINGERPRINT_CACHE}" +echo " LAMBDA_SHAPE=${LAMBDA_SHAPE} FREEZE_FOUNDATION=${FREEZE_FOUNDATION} FREEZE_MODE_HEAD=${FREEZE_MODE_HEAD}" +echo " GROUPED_BATCH=${FORCE_GROUPED_BATCH} ENSEMBLE_GROUP_SIZE=${ENSEMBLE_GROUP_SIZE}" +echo " CHECKPOINT_EVERY_N_EPOCHS=${CHECKPOINT_EVERY_N_EPOCHS} CHECKPOINT_SAVE_LAST=${CHECKPOINT_SAVE_LAST} CHECKPOINT_SAVE_TOP_K=${CHECKPOINT_SAVE_TOP_K}" +echo " RESET_EPOCH=${RESET_EPOCH} RESET_OPTIMIZER_ON_LOAD=${RESET_OPTIMIZER_ON_LOAD} MODEL_ONLY_WARM_START=${MODEL_ONLY_WARM_START}" +echo " LAMBDA_GENERATOR_COV=${LAMBDA_GENERATOR_COV} GEN_NUM_DELTAS=${GENERATOR_COV_NUM_DELTAS} GEN_STUDENT_CHUNK_DELTAS=${GENERATOR_COV_STUDENT_CHUNK_DELTAS} GEN_TEACHER_NUM_DELTAS=${GENERATOR_COV_TEACHER_NUM_DELTAS} GEN_TEACHER_REUSE_STUDENT_DELTA=${GENERATOR_COV_TEACHER_REUSE_STUDENT_DELTA} GEN_TEACHER_TRACE_DENOMINATOR=${GENERATOR_COV_TEACHER_TRACE_DENOMINATOR} GEN_USE_CROSS=${GENERATOR_COV_USE_CROSS} GEN_TRACE_ANCHOR=${LAMBDA_GEN_TRACE_ANCHOR}" +echo " GEN_AMPLITUDE_ANCHOR=${GENERATOR_COV_AMPLITUDE_ANCHOR} GEN_ROLLOUT_CAL=${GENERATOR_COV_ROLLOUT_CALIBRATION} GEN_ROLLOUT_STEPS=${GENERATOR_COV_ROLLOUT_STEPS} GEN_ROLLOUT_NUM_DELTAS=${GENERATOR_COV_ROLLOUT_NUM_DELTAS} GEN_ROLLOUT_MAX_EXAMPLES=${GENERATOR_COV_ROLLOUT_MAX_EXAMPLES} GEN_ROLLOUT_INTERVAL=${GENERATOR_COV_ROLLOUT_INTERVAL_STEPS} GEN_ROLLOUT_EMA=${GENERATOR_COV_ROLLOUT_EMA_DECAY}" +echo " TRAIN: c*=lstsq(U, Kabsch(x_t,x_eq)-x_eq); INFER: c~q(c|x_eq)" +echo " INJECT_EMBEDDER=true INJECT_FILM=true SAMPLE_COEFFICIENTS=true FREEZE_FOUNDATION=${FREEZE_FOUNDATION}" + +CUDA_VISIBLE_DEVICES="${GPU_IDS}" python experiments/train.py \ + latent.enable=true \ + latent.dim="${LATENT_DIM}" \ + latent.num_modes="${NUM_MODES}" \ + +latent.mixture_components="${MIXTURE_COMPONENTS}" \ + +latent.q_lstsq_ridge="${Q_LSTSQ_RIDGE}" \ + +latent.q_cholesky_jitter="${Q_CHOLESKY_JITTER}" \ + +latent.q_detach_projection="${Q_DETACH_PROJECTION}" \ + +latent.q_detach_shared_encoder="${Q_DETACH_SHARED_ENCODER}" \ + +latent.energy_from_q="${ENERGY_FROM_Q}" \ + +latent.energy_from_q_full_cov="${ENERGY_FROM_Q_FULL_COV}" \ + +latent.sample_coefficients=true \ + latent.motion_message_passing_layers="${MOTION_MESSAGE_PASSING_LAYERS}" \ + latent.cross_cov_near_distance="${CROSS_COV_NEAR_DISTANCE}" \ + +latent.pca_align_top_m="${PCA_ALIGN_TOP_M}" \ + latent.template_residual_scale="${TEMPLATE_RESIDUAL_SCALE}" \ + latent.template_remove_rotation="${TEMPLATE_REMOVE_ROTATION}" \ + latent.node_cond_dim="${NUM_MODES}" \ + latent.edge_cond_dim="${NUM_MODES}" \ + latent.freeze_foundation="${FREEZE_FOUNDATION}" \ + latent.freeze_mode_head="${FREEZE_MODE_HEAD}" \ + latent.inject_embedder=true \ + latent.inject_film=true \ + latent.activation_checkpoint="${ACTIVATION_CHECKPOINT}" \ + latent.track_condition_debug="${TRACK_CONDITION_DEBUG}" \ + model.embed.embed_self_conditioning="${EMBED_SELF_CONDITIONING}" \ + interpolant.self_condition="${SELF_CONDITION}" \ + latent.shape_fingerprint_k=5 \ + latent.shape_fingerprint_cache_path="${FINGERPRINT_CACHE}" \ + latent.motion_target_cache_path="${FINGERPRINT_CACHE}" \ + latent.z_stochastic=false \ + experiment.num_devices="${NUM_DEVICES}" \ + experiment.training.force_grouped_batch="${FORCE_GROUPED_BATCH}" \ + experiment.training.ensemble_group_size="${ENSEMBLE_GROUP_SIZE}" \ + +experiment.training.per_frame_coeff_condition=true \ + experiment.training.lambda_shape="${LAMBDA_SHAPE}" \ + +experiment.training.lambda_motion="${LAMBDA_MOTION}" \ + +experiment.training.lambda_q="${LAMBDA_Q}" \ + +experiment.training.lambda_mode_orth="${LAMBDA_MODE_ORTH}" \ + experiment.training.lambda_mode_recon="${LAMBDA_MODE_RECON}" \ + +experiment.training.lambda_pca_align="${LAMBDA_PCA_ALIGN}" \ + +experiment.training.lambda_condition_cycle="${LAMBDA_CONDITION_CYCLE}" \ + experiment.training.lambda_local_cov=1.0 \ + experiment.training.lambda_cross_cov=1.0 \ + experiment.training.lambda_rmsf=0.25 \ + experiment.training.enm_warmup_epochs=0 \ + +experiment.training.oracle_condition=false \ + +experiment.training.grad_flow_check=true \ + +experiment.training.log_optimizer_coverage=true \ + experiment.training.epoch_condition_probe="${EPOCH_CONDITION_PROBE}" \ + experiment.training.lambda_generator_cov="${LAMBDA_GENERATOR_COV}" \ + experiment.training.generator_cov_use_cross="${GENERATOR_COV_USE_CROSS}" \ + experiment.training.generator_cov_t_min="${GENERATOR_COV_T_MIN}" \ + experiment.training.generator_cov_t_max="${GENERATOR_COV_T_MAX}" \ + experiment.training.generator_cov_delta_scale="${GENERATOR_COV_DELTA_SCALE}" \ + experiment.training.generator_cov_num_deltas="${GENERATOR_COV_NUM_DELTAS}" \ + experiment.training.generator_cov_student_chunk_deltas="${GENERATOR_COV_STUDENT_CHUNK_DELTAS}" \ + experiment.training.generator_cov_teacher_num_deltas="${GENERATOR_COV_TEACHER_NUM_DELTAS}" \ + experiment.training.generator_cov_teacher_reuse_student_delta="${GENERATOR_COV_TEACHER_REUSE_STUDENT_DELTA}" \ + experiment.training.generator_cov_teacher_trace_denominator="${GENERATOR_COV_TEACHER_TRACE_DENOMINATOR}" \ + experiment.training.generator_cov_checkpoint="${GENERATOR_COV_CHECKPOINT}" \ + experiment.training.generator_cov_initial_trace_anchor="${GENERATOR_COV_INITIAL_TRACE_ANCHOR}" \ + experiment.training.generator_cov_amplitude_anchor="${GENERATOR_COV_AMPLITUDE_ANCHOR}" \ + experiment.training.generator_cov_rollout_calibration="${GENERATOR_COV_ROLLOUT_CALIBRATION}" \ + experiment.training.generator_cov_rollout_steps="${GENERATOR_COV_ROLLOUT_STEPS}" \ + experiment.training.generator_cov_rollout_num_deltas="${GENERATOR_COV_ROLLOUT_NUM_DELTAS}" \ + experiment.training.generator_cov_rollout_max_examples="${GENERATOR_COV_ROLLOUT_MAX_EXAMPLES}" \ + experiment.training.generator_cov_rollout_interval_steps="${GENERATOR_COV_ROLLOUT_INTERVAL_STEPS}" \ + experiment.training.generator_cov_rollout_ema_decay="${GENERATOR_COV_ROLLOUT_EMA_DECAY}" \ + experiment.training.lambda_gen_local_shape="${LAMBDA_GEN_LOCAL_SHAPE}" \ + experiment.training.lambda_gen_cross_shape="${LAMBDA_GEN_CROSS_SHAPE}" \ + experiment.training.lambda_gen_trace_anchor="${LAMBDA_GEN_TRACE_ANCHOR}" \ + data.sampler.max_num_res_squared="${MAX_NUM_RES_SQUARED}" \ + data.sampler.max_batch_size="${MAX_BATCH_SIZE}" \ + experiment.trainer.precision="${PRECISION}" \ + experiment.trainer.default_root_dir="${RUN_DIR}" \ + experiment.trainer.log_every_n_steps="${LOG_EVERY_N_STEPS}" \ + experiment.use_wandb=false \ + experiment.warm_start="${BASE_CKPT}" \ + experiment.warm_start_cfg_override=false \ + experiment.reset_epoch="${RESET_EPOCH}" \ + experiment.reset_optimizer_on_load="${RESET_OPTIMIZER_ON_LOAD}" \ + experiment.model_only_warm_start="${MODEL_ONLY_WARM_START}" \ + experiment.wandb.name="$(basename "${RUN_DIR}")" \ + experiment.trainer.max_epochs="${MAX_EPOCHS}" \ + experiment.trainer.min_epochs="${MIN_EPOCHS}" \ + +experiment.trainer.max_steps="${MAX_STEPS}" \ + +experiment.trainer.profiler="${TRAINER_PROFILER}" \ + experiment.training.diagnostic_interval_steps="${DIAGNOSTIC_INTERVAL_STEPS}" \ + data.validation.samples_per_valid_protein="${VALID_SAMPLES_PER_PROTEIN}" \ + +experiment.trainer.num_sanity_val_steps=0 \ + experiment.first_val_epoch=inf \ + experiment.checkpointer.dirpath="${RUN_DIR}" \ + experiment.checkpointer.every_n_epochs="${CHECKPOINT_EVERY_N_EPOCHS}" \ + experiment.checkpointer.save_last="${CHECKPOINT_SAVE_LAST}" \ + experiment.checkpointer.save_top_k="${CHECKPOINT_SAVE_TOP_K}" \ + data.dataset.train_csv_path="${TRAIN_CSV}" \ + "data.dataset.valid_csv_paths=[${VAL_CSV}]" \ + "data.dataset.valid_dataset_names=[ATLAS_validation]" \ + data.dataset.test_csv_path="${TEST_CSV}" \ + data.dataset.split_path="${RUN_DIR}" \ + "data.validation.valid_xtc_paths=[${ATLAS_DATASET_DIR}]" \ + ${EXTRA_HYDRA_ARGS} + +echo "[base:00] Latent metrics: ${RUN_DIR}/latent_train_epoch_metrics.csv" diff --git a/bbflow_base/base_stages/01_train_control_baseline_ddp.sh b/bbflow_base/base_stages/01_train_control_baseline_ddp.sh new file mode 100644 index 0000000000000000000000000000000000000000..9f5609d3023fa2ef934d768e6469854275f5bcc5 --- /dev/null +++ b/bbflow_base/base_stages/01_train_control_baseline_ddp.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +PROJECT_ROOT="$(cd "${BBFLOW_ROOT}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_directional_modes_control_400930_fp32_15ep_ddp}" +GPU_IDS="${GPU_IDS:-0,1}" +NUM_DEVICES="${NUM_DEVICES:-2}" + +DEFAULT_BASE_CKPT="${BBFLOW_ROOT}/models/bbflow-0.1/bbflow-0.1.ckpt" +if [[ ! -f "${DEFAULT_BASE_CKPT}" && -f "${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" ]]; then + DEFAULT_BASE_CKPT="${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" +fi +BASE_CKPT="${BASE_CKPT:-${DEFAULT_BASE_CKPT}}" +LATENT_DIM="${LATENT_DIM:-16}" +NUM_MODES="${NUM_MODES:-8}" +MOTION_MESSAGE_PASSING_LAYERS="${MOTION_MESSAGE_PASSING_LAYERS:-4}" +CROSS_COV_NEAR_DISTANCE="${CROSS_COV_NEAR_DISTANCE:-12.0}" +MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-400000}" +MAX_BATCH_SIZE="${MAX_BATCH_SIZE:-32}" +PRECISION="${PRECISION:-32-true}" +MAX_EPOCHS="${MAX_EPOCHS:-15}" +FINGERPRINT_CACHE="${FINGERPRINT_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k${NUM_MODES}.pt}" + +TRAIN_CSV="${TRAIN_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/train/ATLAS_train.csv}" +VAL_CSV="${VAL_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/validation/ATLAS_validation.csv}" +TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +ATLAS_DATASET_DIR="${ATLAS_DATASET_DIR:-${ATLAS_REPRO_ROOT}/datasets/ATLAS}" + +mkdir -p "${RUN_DIR}" + +echo "[base:01] Unified-path control: latent module on, no injection, no motion loss" +echo " RUN_DIR=${RUN_DIR}" +echo " GPU_IDS=${GPU_IDS} NUM_DEVICES=${NUM_DEVICES}" +echo " BASE_CKPT=${BASE_CKPT}" +echo " NUM_MODES=${NUM_MODES} MPNN_LAYERS=${MOTION_MESSAGE_PASSING_LAYERS} NEAR_DIST_A=${CROSS_COV_NEAR_DISTANCE} PRECISION=${PRECISION} MAX_EPOCHS=${MAX_EPOCHS}" +echo " INJECT_EMBEDDER=false INJECT_FILM=false LAMBDA_SHAPE=0" +echo " FORCE_GROUPED_BATCH=false ENSEMBLE_GROUP_SIZE=0" + +CUDA_VISIBLE_DEVICES="${GPU_IDS}" python experiments/train.py \ + latent.enable=true \ + latent.dim="${LATENT_DIM}" \ + latent.num_modes="${NUM_MODES}" \ + latent.motion_message_passing_layers="${MOTION_MESSAGE_PASSING_LAYERS}" \ + latent.cross_cov_near_distance="${CROSS_COV_NEAR_DISTANCE}" \ + latent.node_cond_dim="${NUM_MODES}" \ + latent.edge_cond_dim="${NUM_MODES}" \ + latent.freeze_foundation=false \ + latent.inject_embedder=false \ + latent.inject_film=false \ + latent.activation_checkpoint=false \ + latent.motion_target_cache_path="${FINGERPRINT_CACHE}" \ + latent.z_stochastic=false \ + experiment.num_devices="${NUM_DEVICES}" \ + experiment.training.force_grouped_batch=false \ + experiment.training.ensemble_group_size=0 \ + experiment.training.lambda_shape=0.0 \ + experiment.training.lambda_local_cov=0.0 \ + experiment.training.lambda_cross_cov=0.0 \ + experiment.training.lambda_rmsf=0.0 \ + data.sampler.max_num_res_squared="${MAX_NUM_RES_SQUARED}" \ + data.sampler.max_batch_size="${MAX_BATCH_SIZE}" \ + experiment.trainer.precision="${PRECISION}" \ + experiment.trainer.default_root_dir="${RUN_DIR}" \ + experiment.use_wandb=false \ + experiment.warm_start="${BASE_CKPT}" \ + experiment.warm_start_cfg_override=false \ + experiment.wandb.name="$(basename "${RUN_DIR}")" \ + experiment.trainer.max_epochs="${MAX_EPOCHS}" \ + +experiment.trainer.num_sanity_val_steps=0 \ + experiment.first_val_epoch=inf \ + experiment.checkpointer.dirpath="${RUN_DIR}" \ + data.dataset.train_csv_path="${TRAIN_CSV}" \ + "data.dataset.valid_csv_paths=[${VAL_CSV}]" \ + "data.dataset.valid_dataset_names=[ATLAS_validation]" \ + data.dataset.test_csv_path="${TEST_CSV}" \ + data.dataset.split_path="${RUN_DIR}" \ + "data.validation.valid_xtc_paths=[${ATLAS_DATASET_DIR}]" + +echo "[base:01] Latent metrics: ${RUN_DIR}/latent_train_epoch_metrics.csv" diff --git a/bbflow_base/base_stages/02_diagnose_z.sh b/bbflow_base/base_stages/02_diagnose_z.sh new file mode 100644 index 0000000000000000000000000000000000000000..b553cb57e0442817d1e64e69aa6669247230f3fc --- /dev/null +++ b/bbflow_base/base_stages/02_diagnose_z.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_directional_modes_k8_fp32_15ep_ddp}" +CKPT="${CKPT:-${RUN_DIR}/last.ckpt}" +OUT_DIR="${OUT_DIR:-${RUN_DIR}/diagnose_z}" + +CUDA_VISIBLE_DEVICES="${GPU_ID:-0}" python scripts/diagnose_z.py \ + --ckpt_path "${CKPT}" \ + --csv_path "${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv" \ + --output_dir "${OUT_DIR}" \ + --num_proteins "${NUM_PROTEINS:-10}" \ + --num_z "${NUM_Z:-8}" \ + --samples_per_z "${SAMPLES_PER_Z:-8}" \ + --z_mode "${Z_MODE:-dimension}" \ + --z_delta "${Z_DELTA:-0.25}" \ + --device cuda diff --git a/bbflow_base/base_stages/03_diagnose_film.sh b/bbflow_base/base_stages/03_diagnose_film.sh new file mode 100644 index 0000000000000000000000000000000000000000..db547b4a0168371dc97fc00687bb1d5250d849fd --- /dev/null +++ b/bbflow_base/base_stages/03_diagnose_film.sh @@ -0,0 +1,46 @@ + +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_directional_modes_k8_fp32_15ep_ddp}" +CKPT="${CKPT:-${RUN_DIR}/last.ckpt}" +OUT_PATH="${OUT_PATH:-${RUN_DIR}/mode_condition_diagnostics.json}" +GPU_ID="${GPU_ID:-0}" +NUM_BATCHES="${NUM_BATCHES:-4}" +NUM_MODES="${NUM_MODES:-8}" +MOTION_MESSAGE_PASSING_LAYERS="${MOTION_MESSAGE_PASSING_LAYERS:-4}" +CROSS_COV_NEAR_DISTANCE="${CROSS_COV_NEAR_DISTANCE:-12.0}" +MOTION_TARGET_CACHE="${MOTION_TARGET_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k${NUM_MODES}.pt}" + +TRAIN_CSV="${TRAIN_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/train/ATLAS_train.csv}" +VAL_CSV="${VAL_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/validation/ATLAS_validation.csv}" +TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +ATLAS_DATASET_DIR="${ATLAS_DATASET_DIR:-${ATLAS_REPRO_ROOT}/datasets/ATLAS}" + +echo "[base:03] Diagnose mode-condition adapter statistics" +echo " CKPT=${CKPT}" +echo " OUT_PATH=${OUT_PATH}" +echo " NUM_BATCHES=${NUM_BATCHES}" + +CUDA_VISIBLE_DEVICES="${GPU_ID}" python scripts/diagnose_film.py \ + --ckpt_path "${CKPT}" \ + --out_path "${OUT_PATH}" \ + --device cuda \ + --num_batches "${NUM_BATCHES}" \ + --override latent.num_modes="${NUM_MODES}" \ + --override latent.motion_message_passing_layers="${MOTION_MESSAGE_PASSING_LAYERS}" \ + --override latent.cross_cov_near_distance="${CROSS_COV_NEAR_DISTANCE}" \ + --override latent.node_cond_dim="${NUM_MODES}" \ + --override latent.edge_cond_dim="${NUM_MODES}" \ + --override latent.motion_target_cache_path="${MOTION_TARGET_CACHE}" \ + --override data.dataset.train_csv_path="${TRAIN_CSV}" \ + --override "data.dataset.valid_csv_paths=[${VAL_CSV}]" \ + --override "data.dataset.valid_dataset_names=[ATLAS_validation]" \ + --override data.dataset.test_csv_path="${TEST_CSV}" \ + --override data.dataset.split_path="${RUN_DIR}/mode_condition_diagnostics_split" \ + --override "data.validation.valid_xtc_paths=[${ATLAS_DATASET_DIR}]" diff --git a/bbflow_base/base_stages/04_fit_template_upper_bound.sh b/bbflow_base/base_stages/04_fit_template_upper_bound.sh new file mode 100644 index 0000000000000000000000000000000000000000..a9350fcfea6eddd1bdd3159f1286939c970c415a --- /dev/null +++ b/bbflow_base/base_stages/04_fit_template_upper_bound.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +NUM_MODES="${NUM_MODES:-8}" +MOTION_TARGET_CACHE="${MOTION_TARGET_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k${NUM_MODES}.pt}" +TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +OUT_DIR="${OUT_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/template_upper_bound_k${NUM_MODES}}" +PDB_NAMES="${PDB_NAMES:-6o2vA,6qj0A}" +NUM_PROTEINS="${NUM_PROTEINS:-2}" +STEPS="${STEPS:-1000}" +LR="${LR:-0.03}" +NEAR_DISTANCE="${NEAR_DISTANCE:-12.0}" +RESIDUAL_SCALE="${RESIDUAL_SCALE:-0.1}" +DEVICE="${DEVICE:-cuda}" +GPU_ID="${GPU_ID:-0}" +LOG_EVERY="${LOG_EVERY:-100}" + +mkdir -p "${OUT_DIR}" + +echo "[base:04] Template-mode upper-bound fit" +echo " MOTION_TARGET_CACHE=${MOTION_TARGET_CACHE}" +echo " TEST_CSV=${TEST_CSV}" +echo " OUT_DIR=${OUT_DIR}" +echo " PDB_NAMES=${PDB_NAMES} NUM_PROTEINS=${NUM_PROTEINS}" +echo " NUM_MODES=${NUM_MODES} STEPS=${STEPS} LR=${LR} RESIDUAL_SCALE=${RESIDUAL_SCALE}" +echo " NEAR_DISTANCE=${NEAR_DISTANCE} DEVICE=${DEVICE} GPU_ID=${GPU_ID}" + +CUDA_VISIBLE_DEVICES="${GPU_ID}" python scripts/fit_motion_template_upper_bound.py \ + --motion_target_cache_path "${MOTION_TARGET_CACHE}" \ + --csv_path "${TEST_CSV}" \ + --output_dir "${OUT_DIR}" \ + --pdb_names "${PDB_NAMES}" \ + --num_proteins "${NUM_PROTEINS}" \ + --num_modes "${NUM_MODES}" \ + --steps "${STEPS}" \ + --lr "${LR}" \ + --near_distance "${NEAR_DISTANCE}" \ + --residual_scale "${RESIDUAL_SCALE}" \ + --device "${DEVICE}" \ + --log_every "${LOG_EVERY}" + +echo "[base:04] Summary: ${OUT_DIR}/template_upper_bound_summary.csv" +echo "[base:04] Aggregate: ${OUT_DIR}/template_upper_bound_aggregate.json" diff --git a/bbflow_base/base_stages/05_probe_sample_condition.sh b/bbflow_base/base_stages/05_probe_sample_condition.sh new file mode 100644 index 0000000000000000000000000000000000000000..d6c4aa641d023e156c381abbe7e38a631659045b --- /dev/null +++ b/bbflow_base/base_stages/05_probe_sample_condition.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +cd "${BBFLOW_ROOT}" +export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_template_enm_subspace_warm2_5ep_ddp}" +CKPT="${CKPT:-${RUN_DIR}/last.ckpt}" +OUT_PATH="${OUT_PATH:-${RUN_DIR}/sample_condition_probe.json}" +GPU_ID="${GPU_ID:-0}" +NUM_BATCHES="${NUM_BATCHES:-1}" +NUM_TRIALS="${NUM_TRIALS:-8}" +COEFFICIENT_SCALE="${COEFFICIENT_SCALE:-1.0}" +STATIC_SCALE="${STATIC_SCALE:-2.0}" +SEED="${SEED:-7}" + +TRAIN_CSV="${TRAIN_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/train/ATLAS_train.csv}" +VAL_CSV="${VAL_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/validation/ATLAS_validation.csv}" +TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +ATLAS_DATASET_DIR="${ATLAS_DATASET_DIR:-${ATLAS_REPRO_ROOT}/datasets/ATLAS}" +SPLIT_PATH="${SPLIT_PATH:-${RUN_DIR}/sample_condition_probe_split}" + +mkdir -p "$(dirname "${OUT_PATH}")" "${SPLIT_PATH}" + +echo "[base:05] Probe static vs per-sample coefficient condition" +echo " CKPT=${CKPT}" +echo " OUT_PATH=${OUT_PATH}" +echo " NUM_BATCHES=${NUM_BATCHES} NUM_TRIALS=${NUM_TRIALS}" +echo " COEFFICIENT_SCALE=${COEFFICIENT_SCALE} STATIC_SCALE=${STATIC_SCALE}" + +CUDA_VISIBLE_DEVICES="${GPU_ID}" python scripts/probe_sample_condition.py \ + --ckpt_path "${CKPT}" \ + --out_path "${OUT_PATH}" \ + --device cuda \ + --num_batches "${NUM_BATCHES}" \ + --num_trials "${NUM_TRIALS}" \ + --coefficient_scale "${COEFFICIENT_SCALE}" \ + --static_scale "${STATIC_SCALE}" \ + --seed "${SEED}" \ + --override data.dataset.train_csv_path="${TRAIN_CSV}" \ + --override "data.dataset.valid_csv_paths=[${VAL_CSV}]" \ + --override "data.dataset.valid_dataset_names=[ATLAS_validation]" \ + --override data.dataset.test_csv_path="${TEST_CSV}" \ + --override data.dataset.split_path="${SPLIT_PATH}" \ + --override "data.validation.valid_xtc_paths=[${ATLAS_DATASET_DIR}]" + +echo "[base:05] Wrote ${OUT_PATH}" diff --git a/bbflow_base/base_stages/06_probe_condition_ensemble_cov.sh b/bbflow_base/base_stages/06_probe_condition_ensemble_cov.sh new file mode 100644 index 0000000000000000000000000000000000000000..f12d44514f4759a78c179656b99d44ac31518997 --- /dev/null +++ b/bbflow_base/base_stages/06_probe_condition_ensemble_cov.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +cd "${BBFLOW_ROOT}" +export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_template_enm_subspace_warm2_5ep_ddp}" +CKPT="${CKPT:-${RUN_DIR}/last.ckpt}" +CSV_PATH="${CSV_PATH:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +OUTPUT_DIR="${OUTPUT_DIR:-${RUN_DIR}/condition_ensemble_cov_probe}" +GPU_ID="${GPU_ID:-0}" +NUM_PROTEINS="${NUM_PROTEINS:-3}" +PDB_NAME="${PDB_NAME:-}" +NUM_SAMPLES="${NUM_SAMPLES:-50}" +BATCH_SIZE="${BATCH_SIZE:-10}" +NEAR_DISTANCE="${NEAR_DISTANCE:-12.0}" + +mkdir -p "${OUTPUT_DIR}" + +echo "[base:06] Probe full-ensemble covariance static vs zero condition" +echo " CKPT=${CKPT}" +echo " CSV_PATH=${CSV_PATH}" +echo " OUTPUT_DIR=${OUTPUT_DIR}" +echo " NUM_PROTEINS=${NUM_PROTEINS} PDB_NAME=${PDB_NAME}" +echo " NUM_SAMPLES=${NUM_SAMPLES} BATCH_SIZE=${BATCH_SIZE}" + +ARGS=( + scripts/probe_condition_ensemble_cov.py + --ckpt_path "${CKPT}" + --csv_path "${CSV_PATH}" + --output_dir "${OUTPUT_DIR}" + --num_proteins "${NUM_PROTEINS}" + --num_samples "${NUM_SAMPLES}" + --batch_size "${BATCH_SIZE}" + --near_distance "${NEAR_DISTANCE}" + --device cuda +) + +if [[ -n "${PDB_NAME}" ]]; then + ARGS+=(--pdb_name "${PDB_NAME}") +fi + +CUDA_VISIBLE_DEVICES="${GPU_ID}" python "${ARGS[@]}" + +echo "[base:06] Wrote ${OUTPUT_DIR}/summary.json" diff --git a/bbflow_base/base_stages/07_probe_condition_quality_vs_md.sh b/bbflow_base/base_stages/07_probe_condition_quality_vs_md.sh new file mode 100644 index 0000000000000000000000000000000000000000..bfa823cef9e1f83e122be762b4375d3262954616 --- /dev/null +++ b/bbflow_base/base_stages/07_probe_condition_quality_vs_md.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +cd "${BBFLOW_ROOT}" +export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_pure_main_edge_directional_15ep_ddp}" +CKPT="${CKPT:-${RUN_DIR}/last.ckpt}" +CSV_PATH="${CSV_PATH:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +MOTION_TARGET_CACHE="${MOTION_TARGET_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k8.pt}" +OUTPUT_DIR="${OUTPUT_DIR:-${RUN_DIR}/condition_quality_vs_md_probe}" +GPU_ID="${GPU_ID:-0}" +NUM_PROTEINS="${NUM_PROTEINS:-10}" +PDB_NAME="${PDB_NAME:-}" +NUM_SAMPLES="${NUM_SAMPLES:-250}" +BATCH_SIZE="${BATCH_SIZE:-5}" +NEAR_DISTANCE="${NEAR_DISTANCE:-12.0}" +SEED="${SEED:-2026}" +PROGRESS_DIR="${PROGRESS_DIR:-}" + +mkdir -p "${OUTPUT_DIR}" + +echo "[base:07] Probe condition quality against MD targets" +echo " CKPT=${CKPT}" +echo " CSV_PATH=${CSV_PATH}" +echo " MOTION_TARGET_CACHE=${MOTION_TARGET_CACHE}" +echo " OUTPUT_DIR=${OUTPUT_DIR}" +echo " NUM_PROTEINS=${NUM_PROTEINS} PDB_NAME=${PDB_NAME}" +echo " NUM_SAMPLES=${NUM_SAMPLES} BATCH_SIZE=${BATCH_SIZE}" +echo " GPU_ID=${GPU_ID}" + +ARGS=( + scripts/probe_condition_quality_vs_md.py + --ckpt_path "${CKPT}" + --csv_path "${CSV_PATH}" + --motion_target_cache_path "${MOTION_TARGET_CACHE}" + --output_dir "${OUTPUT_DIR}" + --num_proteins "${NUM_PROTEINS}" + --num_samples "${NUM_SAMPLES}" + --batch_size "${BATCH_SIZE}" + --near_distance "${NEAR_DISTANCE}" + --seed "${SEED}" + --device cuda +) + +if [[ -n "${PDB_NAME}" ]]; then + ARGS+=(--pdb_name "${PDB_NAME}") +fi + +if [[ -n "${PROGRESS_DIR}" ]]; then + ARGS+=(--progress_dir "${PROGRESS_DIR}") +fi + +CUDA_VISIBLE_DEVICES="${GPU_ID}" python "${ARGS[@]}" + +echo "[base:07] Wrote ${OUTPUT_DIR}/summary.json" \ No newline at end of file diff --git a/bbflow_base/base_stages/08_eval_long_finetune_downstream.sh b/bbflow_base/base_stages/08_eval_long_finetune_downstream.sh new file mode 100644 index 0000000000000000000000000000000000000000..e65aa6398e8dcf959a6c9f70756ac728027faf54 --- /dev/null +++ b/bbflow_base/base_stages/08_eval_long_finetune_downstream.sh @@ -0,0 +1,175 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +cd "${BBFLOW_ROOT}" +export PYTHONPATH="${BBFLOW_ROOT}:${PYTHONPATH:-}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_official_modelonly_long_finetune_orth1_recon0_100ep_3gpu_20260630_191404}" +CKPT="${CKPT:-${RUN_DIR}/last.ckpt}" +CSV_PATH="${CSV_PATH:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +MOTION_TARGET_CACHE="${MOTION_TARGET_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt}" +OUTPUT_DIR="${OUTPUT_DIR:-${RUN_DIR}/downstream_quality_vs_md_real_zero_shuffled}" +GPU_IDS="${GPU_IDS:-0,1,2}" +NUM_PROTEINS="${NUM_PROTEINS:-82}" +PDB_NAME="${PDB_NAME:-}" +NUM_SAMPLES="${NUM_SAMPLES:-250}" +BATCH_SIZE="${BATCH_SIZE:-5}" +NEAR_DISTANCE="${NEAR_DISTANCE:-12.0}" +SEED="${SEED:-2026}" + +IFS=',' read -r -a GPU_ARRAY <<< "${GPU_IDS}" +if [[ "${#GPU_ARRAY[@]}" -lt 3 ]]; then + echo "[base:08] ERROR: GPU_IDS must contain at least 3 comma-separated ids, got ${GPU_IDS}" >&2 + exit 2 +fi + +mkdir -p "${OUTPUT_DIR}" + +echo "[base:08] Downstream quality vs MD, one condition per GPU" +echo " RUN_DIR=${RUN_DIR}" +echo " CKPT=${CKPT}" +echo " CSV_PATH=${CSV_PATH}" +echo " MOTION_TARGET_CACHE=${MOTION_TARGET_CACHE}" +echo " OUTPUT_DIR=${OUTPUT_DIR}" +echo " CONDITIONS=real,zero,shuffled" +echo " NUM_PROTEINS=${NUM_PROTEINS} PDB_NAME=${PDB_NAME}" +echo " NUM_SAMPLES=${NUM_SAMPLES} BATCH_SIZE=${BATCH_SIZE}" +echo " GPU_IDS=${GPU_IDS} SEED=${SEED}" + +run_condition() { + local condition="$1" + local gpu_id="$2" + local condition_dir="${OUTPUT_DIR}/${condition}" + local progress_dir="${condition_dir}/progress" + mkdir -p "${condition_dir}" "${progress_dir}" + + local args=( + scripts/probe_condition_quality_vs_md.py + --ckpt_path "${CKPT}" + --csv_path "${CSV_PATH}" + --motion_target_cache_path "${MOTION_TARGET_CACHE}" + --output_dir "${condition_dir}" + --num_proteins "${NUM_PROTEINS}" + --num_samples "${NUM_SAMPLES}" + --batch_size "${BATCH_SIZE}" + --near_distance "${NEAR_DISTANCE}" + --seed "${SEED}" + --progress_dir "${progress_dir}" + --resume_existing + --conditions "${condition}" + --device cuda + ) + + if [[ -n "${PDB_NAME}" ]]; then + args+=(--pdb_name "${PDB_NAME}") + fi + + echo "[base:08] start condition=${condition} gpu=${gpu_id}" + CUDA_VISIBLE_DEVICES="${gpu_id}" python "${args[@]}" 2>&1 | tee "${condition_dir}/eval.log" +} + +run_condition real "${GPU_ARRAY[0]}" & +pid_real=$! +run_condition zero "${GPU_ARRAY[1]}" & +pid_zero=$! +run_condition shuffled "${GPU_ARRAY[2]}" & +pid_shuffled=$! + +wait "${pid_real}" +wait "${pid_zero}" +wait "${pid_shuffled}" + +python - "${OUTPUT_DIR}/summary_merged.json" \ + "${OUTPUT_DIR}/real/summary.json" \ + "${OUTPUT_DIR}/zero/summary.json" \ + "${OUTPUT_DIR}/shuffled/summary.json" <<'PY' +import json +import sys +from pathlib import Path + +import torch + + +def numeric_mean(rows): + if not rows: + return {} + keys = [key for key, value in rows[0].items() if isinstance(value, (int, float))] + return { + key: float(torch.tensor([row[key] for row in rows if key in row], dtype=torch.float32).mean().item()) + for key in keys + } + + +def improvement_vs(metrics, baseline, prefix): + out = {} + for key, value in metrics.items(): + if not isinstance(value, (int, float)) or key not in baseline: + continue + if key.endswith("_rel_loss"): + out[f"{prefix}_{key}_delta_vs_baseline"] = float(value - baseline[key]) + out[f"{prefix}_{key}_improvement_vs_baseline"] = float(baseline[key] - value) + elif key.endswith("_corr") or key.endswith("sign_agree"): + out[f"{prefix}_{key}_delta_vs_baseline"] = float(value - baseline[key]) + return out + + +output_path = Path(sys.argv[1]) +summary_paths = [Path(path) for path in sys.argv[2:]] +merged_rows = [] +for path in summary_paths: + merged_rows.extend(json.loads(path.read_text()).get("proteins", [])) + +if not merged_rows: + raise SystemExit("No protein rows found in condition summaries") + +by_protein = {} +for row in merged_rows: + by_protein.setdefault(row["pdb_name"], {})[row["condition"]] = row + +completed_rows = [] +for condition_rows in by_protein.values(): + for row in condition_rows.values(): + row = dict(row) + if row["condition"] == "real": + if "zero" in condition_rows: + row.update(improvement_vs(row, condition_rows["zero"], "real_minus_zero")) + if "shuffled" in condition_rows: + row.update(improvement_vs(row, condition_rows["shuffled"], "real_minus_shuffled")) + completed_rows.append(row) + +condition_names = sorted({row["condition"] for row in completed_rows}) +aggregate = { + condition: numeric_mean([row for row in completed_rows if row["condition"] == condition]) + for condition in condition_names +} +real_rows = [row for row in completed_rows if row["condition"] == "real"] +delta_keys = sorted({ + key + for row in real_rows + for key, value in row.items() + if isinstance(value, (int, float)) and ("delta_vs_baseline" in key or "improvement_vs_baseline" in key) +}) +real_deltas = { + key: float(torch.tensor([row[key] for row in real_rows if key in row], dtype=torch.float32).mean().item()) + for key in delta_keys +} + +output = { + "source_summaries": [str(path) for path in summary_paths], + "num_proteins": len(by_protein), + "conditions": condition_names, + "aggregate_by_condition": aggregate, + "real_condition_deltas": real_deltas, + "proteins": completed_rows, +} +output_path.write_text(json.dumps(output, indent=2, sort_keys=True) + "\n") +print(f"[base:08] Wrote {output_path}") +print("== real deltas; negative loss delta / positive improvement is good ==") +for key in sorted(real_deltas): + print(f"{key}: {real_deltas[key]:.6f}") +PY + +echo "[base:08] Wrote ${OUTPUT_DIR}/summary_merged.json" diff --git a/bbflow_base/base_stages/10_train_cmfm_ddp.sh b/bbflow_base/base_stages/10_train_cmfm_ddp.sh new file mode 100644 index 0000000000000000000000000000000000000000..3d2fb94edaacc2beb6ef59d3a8634789ed6be078 --- /dev/null +++ b/bbflow_base/base_stages/10_train_cmfm_ddp.sh @@ -0,0 +1,91 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +PROJECT_ROOT="$(cd "${BBFLOW_ROOT}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_cmfm_k8_r4_m2_100ep_3gpu}" +DEFAULT_BASE_CKPT="${BBFLOW_ROOT}/models/bbflow-0.1/bbflow-0.1.ckpt" +if [[ ! -f "${DEFAULT_BASE_CKPT}" && -f "${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" ]]; then + DEFAULT_BASE_CKPT="${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" +fi +BASE_CKPT="${BASE_CKPT:-${DEFAULT_BASE_CKPT}}" +DEFAULT_FINGERPRINT_CACHE="${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt" +if [[ ! -f "${DEFAULT_FINGERPRINT_CACHE}" && -f "${PROJECT_ROOT}/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt" ]]; then + DEFAULT_FINGERPRINT_CACHE="${PROJECT_ROOT}/bbflow_official_reproduction/shape_fingerprints/atlas_full_md_motion_targets_k8_kabsch_v1.pt" +fi +FINGERPRINT_CACHE="${FINGERPRINT_CACHE:-${DEFAULT_FINGERPRINT_CACHE}}" + +if [[ ! -f "${BASE_CKPT}" ]]; then + echo "Missing official BBFlow checkpoint: ${BASE_CKPT}" >&2 + exit 2 +fi +if [[ ! -f "${FINGERPRINT_CACHE}" ]]; then + echo "Missing K8 motion-target cache: ${FINGERPRINT_CACHE}" >&2 + exit 2 +fi + +export RUN_DIR +export BASE_CKPT +export FINGERPRINT_CACHE +export GPU_IDS="${GPU_IDS:-0,1,2}" +export NUM_DEVICES="${NUM_DEVICES:-3}" +export NUM_MODES=8 +export MIXTURE_COMPONENTS=2 +export ENSEMBLE_GROUP_SIZE="${ENSEMBLE_GROUP_SIZE:-8}" +export MAX_BATCH_SIZE="${MAX_BATCH_SIZE:-8}" +export MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-4500000}" +export MAX_EPOCHS="${MAX_EPOCHS:-100}" +export PRECISION="${PRECISION:-bf16-mixed}" +export ACTIVATION_CHECKPOINT="${ACTIVATION_CHECKPOINT:-true}" +export COLLECTIVE_BACKBONE_CHUNK_SIZE="${COLLECTIVE_BACKBONE_CHUNK_SIZE:-4}" +export SELF_CONDITION="${SELF_CONDITION:-true}" +export Q_DETACH_PROJECTION=true +export Q_DETACH_SHARED_ENCODER=true +export FREEZE_FOUNDATION="${FREEZE_FOUNDATION:-false}" +# Overridable: with a stage-1 warm start the mode head arrives already aligned +# (mode_max_cosine 0.871, cross_cov_far_corr 0.236) and one epoch of CMFM +# training destroys it -- the template head takes a gradient norm ~24x the +# backbone's on 54x fewer tensors. Freezing keeps stage-1's U and lets CMFM +# train only q and the controller. +export FREEZE_MODE_HEAD="${FREEZE_MODE_HEAD:-false}" +export MODEL_ONLY_WARM_START=true +export LAMBDA_GENERATOR_COV=0.0 +export LAMBDA_CONDITION_CYCLE=0.0 +export LAMBDA_MOTION=1.0 +export LAMBDA_Q=1.0 +export LAMBDA_MODE_ORTH=1.0 +export LAMBDA_MODE_RECON=0.0 +export VALID_SAMPLES_PER_PROTEIN="${VALID_SAMPLES_PER_PROTEIN:-6}" +export EPOCH_CONDITION_PROBE=false +export DIAGNOSTIC_INTERVAL_STEPS="${DIAGNOSTIC_INTERVAL_STEPS:-50}" + +EXTRA_HYDRA_ARGS="${EXTRA_HYDRA_ARGS:-}" +export EXTRA_HYDRA_ARGS="latent.collective_enable=true \ +latent.collective_rank=4 \ +latent.collective_hidden_dim=128 \ +latent.collective_output_scale=1.0 \ +latent.collective_spectrum_eps=1e-6 \ +latent.collective_basis_from_data=${COLLECTIVE_BASIS_FROM_DATA:-false} \ +latent.collective_rate_weighted=${COLLECTIVE_RATE_WEIGHTED:-true} \ +experiment.training.lambda_collective_measure=1.0 \ ++experiment.training.collective_backbone_chunk_size=${COLLECTIVE_BACKBONE_CHUNK_SIZE} \ ++experiment.training.lambda_condition_usage=0.0 \ +experiment.training.cmfm_numerics_log_interval=${CMFM_NUMERICS_LOG_INTERVAL:-50} \ +experiment.training.cmfm_grad_guard=${CMFM_GRAD_GUARD:-true} \ +experiment.training.cmfm_capture_failure=${CMFM_CAPTURE_FAILURE:-true} \ +experiment.training.cmfm_dump_state_dict=${CMFM_DUMP_STATE_DICT:-true} \ +${EXTRA_HYDRA_ARGS}" + +echo "[cmfm] Full-model training from official BBFlow weights" +echo " RUN_DIR=${RUN_DIR}" +echo " GPU_IDS=${GPU_IDS} GROUP_SIZE=${ENSEMBLE_GROUP_SIZE} K=8 R=4" +echo " MAX_BATCH_SIZE=${MAX_BATCH_SIZE} BACKBONE_CHUNK_SIZE=${COLLECTIVE_BACKBONE_CHUNK_SIZE} PRECISION=${PRECISION}" +echo " failure localization: per-rank per-microbatch numerics + first-bad-microbatch dump" +echo " see docs/cmfm_failure_localization.md; replay with scripts/cmfm_replay_failure.py" +echo " optimizer/scheduler are initialized fresh; no Lightning resume" + +exec bash base_stages/00_train_final_mog_ddp.sh diff --git a/bbflow_base/base_stages/11_infer_cmfm.sh b/bbflow_base/base_stages/11_infer_cmfm.sh new file mode 100644 index 0000000000000000000000000000000000000000..401bd88f7c5d31952fbb21643dc237cdd96e4dd5 --- /dev/null +++ b/bbflow_base/base_stages/11_infer_cmfm.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +CKPT="${CKPT:?Set CKPT to a trained CMFM checkpoint}" +GPU_IDS="${GPU_IDS:-0,1,2}" +NUM_GPUS="${NUM_GPUS:-3}" +TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +OUTPUT_DIR="${OUTPUT_DIR:-${ATLAS_REPRO_ROOT}/inference/cmfm}" +RUN_NAME="${RUN_NAME:-cmfm_k8_r4_250}" + +if [[ ! -f "${CKPT}" ]]; then + echo "Missing CMFM checkpoint: ${CKPT}" >&2 + exit 2 +fi +if [[ ! -f "${TEST_CSV}" ]]; then + echo "Missing test CSV: ${TEST_CSV}" >&2 + exit 2 +fi + +echo "[cmfm] 20-step joint ensemble inference" +echo " CKPT=${CKPT}" +echo " GPU_IDS=${GPU_IDS} samples=250 joint_group=10" + +CUDA_VISIBLE_DEVICES="${GPU_IDS}" python experiments/inference.py \ + inference.ckpt_path="${CKPT}" \ + inference.csv_path="${TEST_CSV}" \ + inference.output_dir="${OUTPUT_DIR}" \ + inference.name="${RUN_NAME}" \ + inference.num_gpus="${NUM_GPUS}" \ + inference.z_per_sample=true \ + inference.samples.samples_per_protein=250 \ + inference.samples.batch_size=10 \ + inference.samples.num_res_squared=6000000 \ + inference.interpolant.sampling.num_timesteps=20 diff --git a/bbflow_base/base_stages/13_train_md_subspace_ddp.sh b/bbflow_base/base_stages/13_train_md_subspace_ddp.sh new file mode 100644 index 0000000000000000000000000000000000000000..ae6203001a38fc8a530238906467119d4f4adbd4 --- /dev/null +++ b/bbflow_base/base_stages/13_train_md_subspace_ddp.sh @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Train against the reference covariance expressed in the reference eigenbasis. +# +# What changes relative to 10_train_cmfm_ddp.sh: +# +# * The collective objective is off. It existed to estimate a covariance from G=8 +# generated conformations; the reference eigenvectors and variances are precomputed +# from the full trajectory and sit in the fingerprint cache, so the estimate is not +# needed. With it goes the grouped batch, the shared-time sampler, the backbone +# chunking, and the rank-4 restriction that the G&2 + exit 2 +fi +if [[ ! -f "${FINGERPRINT_CACHE}" ]]; then + echo "Missing motion-target cache: ${FINGERPRINT_CACHE}" >&2 + exit 2 +fi + +# The subspace loss reads oracle_modes / oracle_energy; fail here rather than at step 1. +python scripts/validate_motion_target_cache.py \ + --path "${FINGERPRINT_CACHE}" \ + --require local_cov cross_cov rmsf oracle_mean_disp oracle_modes oracle_energy + +export RUN_DIR BASE_CKPT FINGERPRINT_CACHE +export GPU_IDS="${GPU_IDS:-0,1,2}" +export NUM_DEVICES="${NUM_DEVICES:-3}" +export NUM_MODES=8 +export MIXTURE_COMPONENTS=2 + +# No grouping: 00_ derives FORCE_GROUPED_BATCH from this being zero. +export ENSEMBLE_GROUP_SIZE=0 +export MAX_BATCH_SIZE="${MAX_BATCH_SIZE:-8}" +# Halved relative to the CMFM run. That run fitted in memory because the collective +# path routed the backbone through `forward_chunked(chunk_size=4, checkpoint_chunks=True)`, +# and that branch is gated on `collective_enabled` (bbflow_module._run_training_model). +# Turning the collective objective off therefore also removed its batch chunking and +# per-chunk checkpointing, and the first attempt OOMed in backward at ~16 GiB. +# `full_model_activation_checkpoint` below restores the checkpointing; this restores the +# effective chunk width. Drop to 1500000 if it still does not fit -- smaller batches cost +# throughput only, nothing about the objective changes. +# The sampler takes `min(max_batch_size, max_num_res_squared // seq_len**2 + 1)`, and +# `max_num_res: 750` already caps the length, so at the longest proteins this value alone +# sets the batch: 4500000 -> 8 (what the CMFM run requested, then chunked to 4 in the +# backbone), 2250000 -> 5, 1125000 -> 3. The first attempt used 2250000 on the assumption +# that halving shrank the batch, but 5 is larger than the 4 the chunked path actually ran, +# and it OOMed at the same 16.62 GiB both times. 1125000 reproduces the CMFM memory +# envelope. Drop to 562500 (batch 2) if a longer protein still does not fit. +export MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-1125000}" +export MAX_EPOCHS="${MAX_EPOCHS:-30}" +export PRECISION="${PRECISION:-bf16-mixed}" +export ACTIVATION_CHECKPOINT="${ACTIVATION_CHECKPOINT:-true}" +export SELF_CONDITION="${SELF_CONDITION:-true}" +export Q_DETACH_PROJECTION=true +# Left at the CMFM setting. The subspace loss already reaches the shared encoder +# through u_global, which is built from an undetached h; this flag only gates the +# mixture head's own path back to the encoder, so flipping it would be a behaviour +# change with no bearing on whether the new loss trains. +export Q_DETACH_SHARED_ENCODER=true +export FREEZE_FOUNDATION="${FREEZE_FOUNDATION:-false}" +export FREEZE_MODE_HEAD=false # U is what the subspace loss is meant to move +export MODEL_ONLY_WARM_START=true + +export LAMBDA_GENERATOR_COV="${LAMBDA_GENERATOR_COV:-0.0}" +export LAMBDA_CONDITION_CYCLE=0.0 +export LAMBDA_MODE_RECON=0.0 +export LAMBDA_MOTION=1.0 # gate for motion_recon; per-term weights below +export LAMBDA_Q=1.0 +export LAMBDA_MODE_ORTH=1.0 + +export CHECKPOINT_EVERY_N_EPOCHS="${CHECKPOINT_EVERY_N_EPOCHS:-5}" +export CHECKPOINT_SAVE_LAST="${CHECKPOINT_SAVE_LAST:-true}" + +export EXTRA_HYDRA_ARGS="latent.collective_enable=false \ +experiment.training.full_model_activation_checkpoint=true \ +experiment.training.lambda_collective_measure=0.0 \ +experiment.training.lambda_local_cov=0.0 \ +experiment.training.lambda_cross_cov=0.0 \ +experiment.training.lambda_rmsf=${LAMBDA_RMSF:-1.0} \ +experiment.training.lambda_md_subspace=${LAMBDA_MD_SUBSPACE:-1.0} \ +experiment.training.lambda_md_subspace_trace=${LAMBDA_MD_SUBSPACE_TRACE:-1.0} \ +${EXTRA_HYDRA_ARGS:-}" + +mkdir -p "${RUN_DIR}" + +echo "[md-subspace] closed-form covariance matching in the reference eigenbasis" +echo " RUN_DIR=${RUN_DIR}" +echo " GPU_IDS=${GPU_IDS} NUM_DEVICES=${NUM_DEVICES} MAX_EPOCHS=${MAX_EPOCHS}" +echo " collective OFF, grouped batch OFF, K=${NUM_MODES}" +echo " lambda_md_subspace=${LAMBDA_MD_SUBSPACE:-1.0} trace=${LAMBDA_MD_SUBSPACE_TRACE:-1.0}" +echo " local_cov/cross_cov OFF, rmsf 0.25 retained as the amplitude anchor" +echo " watch: md_subspace_offdiag_share (misalignment share of the residual)" +echo " md_subspace_variance_ratio (should approach 1.0)" + +exec bash base_stages/00_train_final_mog_ddp.sh diff --git a/bbflow_base/base_stages/13_train_md_subspace_ddp.sh.bak b/bbflow_base/base_stages/13_train_md_subspace_ddp.sh.bak new file mode 100644 index 0000000000000000000000000000000000000000..ae6203001a38fc8a530238906467119d4f4adbd4 --- /dev/null +++ b/bbflow_base/base_stages/13_train_md_subspace_ddp.sh.bak @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Train against the reference covariance expressed in the reference eigenbasis. +# +# What changes relative to 10_train_cmfm_ddp.sh: +# +# * The collective objective is off. It existed to estimate a covariance from G=8 +# generated conformations; the reference eigenvectors and variances are precomputed +# from the full trajectory and sit in the fingerprint cache, so the estimate is not +# needed. With it goes the grouped batch, the shared-time sampler, the backbone +# chunking, and the rank-4 restriction that the G&2 + exit 2 +fi +if [[ ! -f "${FINGERPRINT_CACHE}" ]]; then + echo "Missing motion-target cache: ${FINGERPRINT_CACHE}" >&2 + exit 2 +fi + +# The subspace loss reads oracle_modes / oracle_energy; fail here rather than at step 1. +python scripts/validate_motion_target_cache.py \ + --path "${FINGERPRINT_CACHE}" \ + --require local_cov cross_cov rmsf oracle_mean_disp oracle_modes oracle_energy + +export RUN_DIR BASE_CKPT FINGERPRINT_CACHE +export GPU_IDS="${GPU_IDS:-0,1,2}" +export NUM_DEVICES="${NUM_DEVICES:-3}" +export NUM_MODES=8 +export MIXTURE_COMPONENTS=2 + +# No grouping: 00_ derives FORCE_GROUPED_BATCH from this being zero. +export ENSEMBLE_GROUP_SIZE=0 +export MAX_BATCH_SIZE="${MAX_BATCH_SIZE:-8}" +# Halved relative to the CMFM run. That run fitted in memory because the collective +# path routed the backbone through `forward_chunked(chunk_size=4, checkpoint_chunks=True)`, +# and that branch is gated on `collective_enabled` (bbflow_module._run_training_model). +# Turning the collective objective off therefore also removed its batch chunking and +# per-chunk checkpointing, and the first attempt OOMed in backward at ~16 GiB. +# `full_model_activation_checkpoint` below restores the checkpointing; this restores the +# effective chunk width. Drop to 1500000 if it still does not fit -- smaller batches cost +# throughput only, nothing about the objective changes. +# The sampler takes `min(max_batch_size, max_num_res_squared // seq_len**2 + 1)`, and +# `max_num_res: 750` already caps the length, so at the longest proteins this value alone +# sets the batch: 4500000 -> 8 (what the CMFM run requested, then chunked to 4 in the +# backbone), 2250000 -> 5, 1125000 -> 3. The first attempt used 2250000 on the assumption +# that halving shrank the batch, but 5 is larger than the 4 the chunked path actually ran, +# and it OOMed at the same 16.62 GiB both times. 1125000 reproduces the CMFM memory +# envelope. Drop to 562500 (batch 2) if a longer protein still does not fit. +export MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-1125000}" +export MAX_EPOCHS="${MAX_EPOCHS:-30}" +export PRECISION="${PRECISION:-bf16-mixed}" +export ACTIVATION_CHECKPOINT="${ACTIVATION_CHECKPOINT:-true}" +export SELF_CONDITION="${SELF_CONDITION:-true}" +export Q_DETACH_PROJECTION=true +# Left at the CMFM setting. The subspace loss already reaches the shared encoder +# through u_global, which is built from an undetached h; this flag only gates the +# mixture head's own path back to the encoder, so flipping it would be a behaviour +# change with no bearing on whether the new loss trains. +export Q_DETACH_SHARED_ENCODER=true +export FREEZE_FOUNDATION="${FREEZE_FOUNDATION:-false}" +export FREEZE_MODE_HEAD=false # U is what the subspace loss is meant to move +export MODEL_ONLY_WARM_START=true + +export LAMBDA_GENERATOR_COV="${LAMBDA_GENERATOR_COV:-0.0}" +export LAMBDA_CONDITION_CYCLE=0.0 +export LAMBDA_MODE_RECON=0.0 +export LAMBDA_MOTION=1.0 # gate for motion_recon; per-term weights below +export LAMBDA_Q=1.0 +export LAMBDA_MODE_ORTH=1.0 + +export CHECKPOINT_EVERY_N_EPOCHS="${CHECKPOINT_EVERY_N_EPOCHS:-5}" +export CHECKPOINT_SAVE_LAST="${CHECKPOINT_SAVE_LAST:-true}" + +export EXTRA_HYDRA_ARGS="latent.collective_enable=false \ +experiment.training.full_model_activation_checkpoint=true \ +experiment.training.lambda_collective_measure=0.0 \ +experiment.training.lambda_local_cov=0.0 \ +experiment.training.lambda_cross_cov=0.0 \ +experiment.training.lambda_rmsf=${LAMBDA_RMSF:-1.0} \ +experiment.training.lambda_md_subspace=${LAMBDA_MD_SUBSPACE:-1.0} \ +experiment.training.lambda_md_subspace_trace=${LAMBDA_MD_SUBSPACE_TRACE:-1.0} \ +${EXTRA_HYDRA_ARGS:-}" + +mkdir -p "${RUN_DIR}" + +echo "[md-subspace] closed-form covariance matching in the reference eigenbasis" +echo " RUN_DIR=${RUN_DIR}" +echo " GPU_IDS=${GPU_IDS} NUM_DEVICES=${NUM_DEVICES} MAX_EPOCHS=${MAX_EPOCHS}" +echo " collective OFF, grouped batch OFF, K=${NUM_MODES}" +echo " lambda_md_subspace=${LAMBDA_MD_SUBSPACE:-1.0} trace=${LAMBDA_MD_SUBSPACE_TRACE:-1.0}" +echo " local_cov/cross_cov OFF, rmsf 0.25 retained as the amplitude anchor" +echo " watch: md_subspace_offdiag_share (misalignment share of the residual)" +echo " md_subspace_variance_ratio (should approach 1.0)" + +exec bash base_stages/00_train_final_mog_ddp.sh diff --git a/bbflow_base/base_stages/14_serial_diagnose_then_train.sh b/bbflow_base/base_stages/14_serial_diagnose_then_train.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e010c07d4e94ec46724d80a112ca7254627f40d --- /dev/null +++ b/bbflow_base/base_stages/14_serial_diagnose_then_train.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# Serial driver: two read-only diagnostics, then the new training run. +# +# The diagnostics need no GPU and take minutes. They run first so their output exists +# regardless of what happens to the training, and they are wrapped so that a failure in +# either does not prevent the run from starting -- if you are away from the console, a +# broken audit script should not cost you the night. +# +# Read the two diagnostic logs before acting on the training result. If the rescore shows +# the six existing runs are separable at K=10 under a paired comparison, the premise that +# nothing has moved the metric is false, and the training below is not the right next +# experiment. + +set -uo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +MD_DIR="${MD_DIR:-/data/shared/wangyusong/Atlas}" +INFER_ROOT="${INFER_ROOT:-${ATLAS_REPRO_ROOT}/inference/cmfm/checkpoints}" + +# Generated ensembles to score. Add more "label=path" entries as runs become available; +# the first is used as the paired baseline. +ENSEMBLES=( + "databasis_ep024=${INFER_ROOT}/cmfm_databasis_20260801_024854/epoch:024/cmfm_databasis_ep024" +) + +OUT_DIR="${OUT_DIR:-${ATLAS_REPRO_ROOT}/diagnostics/$(date +%Y%m%d_%H%M%S)}" +mkdir -p "${OUT_DIR}" + +echo "==============================================================" +echo " outputs -> ${OUT_DIR}" +echo "==============================================================" + +# ---------------------------------------------------------------- 1. subspace audit +echo +echo "[1/3] subspace variance audit (no GPU)" +FIRST_ENS="${ENSEMBLES[0]#*=}" +if [[ -d "${FIRST_ENS}" ]]; then + python scripts/subspace_variance_audit.py \ + --md_dir "${MD_DIR}" \ + --ensemble_dir "${FIRST_ENS}" \ + --k 2 10 \ + --out_csv "${OUT_DIR}/subspace_audit.csv" \ + 2>&1 | tee "${OUT_DIR}/subspace_audit.log" + echo "[1/3] exit=${PIPESTATUS[0]}" +else + echo " SKIP: ${FIRST_ENS} not found" | tee "${OUT_DIR}/subspace_audit.log" +fi + +# ---------------------------------------------------------------- 2. rescore at K=10 +echo +echo "[2/3] PCA-W2 rescore at K=2 and K=10, per protein (no GPU)" +LABELS=(); DIRS=() +for entry in "${ENSEMBLES[@]}"; do + label="${entry%%=*}"; path="${entry#*=}" + if [[ -d "${path}" ]]; then LABELS+=("${label}"); DIRS+=("${path}"); fi +done +if [[ ${#DIRS[@]} -gt 0 ]]; then + python scripts/rescore_pca_w2.py \ + --md_dir "${MD_DIR}" \ + --ensemble_dirs "${DIRS[@]}" \ + --names "${LABELS[@]}" \ + --k 2 10 \ + --out_csv "${OUT_DIR}/pca_w2_per_protein.csv" \ + 2>&1 | tee "${OUT_DIR}/rescore.log" + echo "[2/3] exit=${PIPESTATUS[0]}" +else + echo " SKIP: no ensemble directories found" | tee "${OUT_DIR}/rescore.log" +fi + +# ---------------------------------------------------------------- 3. training +echo +echo "[3/3] training: closed-form covariance matching (3 GPUs)" +echo " free the GPUs first if anything is still resident" +nvidia-smi --query-gpu=index,memory.used --format=csv || true + +export RUN_DIR="${RUN_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/mdsubspace_$(date +%Y%m%d_%H%M%S)}" +echo " RUN_DIR=${RUN_DIR}" +echo " log -> ${OUT_DIR}/train.log" + +bash base_stages/13_train_md_subspace_ddp.sh 2>&1 | tee "${OUT_DIR}/train.log" +echo "[3/3] exit=${PIPESTATUS[0]}" + +echo +echo "==============================================================" +echo " done. read in this order:" +echo " ${OUT_DIR}/rescore.log <- does K=10 + pairing separate the runs?" +echo " ${OUT_DIR}/subspace_audit.log <- is variance hiding outside the metric?" +echo " ${OUT_DIR}/train.log <- md_subspace_offdiag_share, variance_ratio" +echo "==============================================================" diff --git a/bbflow_base/base_stages/99_preflight_base.sh b/bbflow_base/base_stages/99_preflight_base.sh new file mode 100644 index 0000000000000000000000000000000000000000..26358e115e0c88f5d346eec3edf530de3f0d1ba0 --- /dev/null +++ b/bbflow_base/base_stages/99_preflight_base.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +set -e +set -u +set -o pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BBFLOW_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" +PROJECT_ROOT="$(cd "${BBFLOW_ROOT}/.." && pwd)" +cd "${BBFLOW_ROOT}" + +ATLAS_REPRO_ROOT="${ATLAS_REPRO_ROOT:-/data/shared/wangyusong/atals/bbflow_official_reproduction}" +OUT_DIR="${OUT_DIR:-${ATLAS_REPRO_ROOT}/outputs/checkpoints/bbflow_base_template_modes_preflight}" +GPU_ID="${GPU_ID:-0}" + +DEFAULT_BASE_CKPT="${BBFLOW_ROOT}/models/bbflow-0.1/bbflow-0.1.ckpt" +if [[ ! -f "${DEFAULT_BASE_CKPT}" && -f "${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" ]]; then + DEFAULT_BASE_CKPT="${PROJECT_ROOT}/bbflow/models/bbflow-0.1/bbflow-0.1.ckpt" +fi +BASE_CKPT="${BASE_CKPT:-${DEFAULT_BASE_CKPT}}" +LATENT_DIM="${LATENT_DIM:-16}" +NUM_MODES="${NUM_MODES:-8}" +MOTION_MESSAGE_PASSING_LAYERS="${MOTION_MESSAGE_PASSING_LAYERS:-4}" +CROSS_COV_NEAR_DISTANCE="${CROSS_COV_NEAR_DISTANCE:-12.0}" +TEMPLATE_RESIDUAL_SCALE="${TEMPLATE_RESIDUAL_SCALE:-0.1}" +TEMPLATE_REMOVE_ROTATION="${TEMPLATE_REMOVE_ROTATION:-true}" +ENM_NUM_MODES="${ENM_NUM_MODES:-${NUM_MODES}}" +ENM_CUTOFF="${ENM_CUTOFF:-12.0}" +ENM_EPS="${ENM_EPS:-1e-6}" +LAMBDA_SHAPE="${LAMBDA_SHAPE:-1.0}" +LAMBDA_LOCAL_COV="${LAMBDA_LOCAL_COV:-1.0}" +LAMBDA_CROSS_COV="${LAMBDA_CROSS_COV:-1.0}" +LAMBDA_RMSF="${LAMBDA_RMSF:-0.25}" +ENM_WARMUP_EPOCHS="${ENM_WARMUP_EPOCHS:-0}" +LAMBDA_ENM_WARMUP="${LAMBDA_ENM_WARMUP:-1.0}" +INJECT_EMBEDDER="${INJECT_EMBEDDER:-true}" +INJECT_FILM="${INJECT_FILM:-true}" +ACTIVATION_CHECKPOINT="${ACTIVATION_CHECKPOINT:-true}" +FREEZE_FOUNDATION="${FREEZE_FOUNDATION:-false}" +MAX_NUM_RES_SQUARED="${MAX_NUM_RES_SQUARED:-400000}" +MAX_BATCH_SIZE="${MAX_BATCH_SIZE:-32}" +PRECISION="${PRECISION:-32-true}" +MOTION_TARGET_CACHE="${MOTION_TARGET_CACHE:-${ATLAS_REPRO_ROOT}/shape_fingerprints/atlas_full_md_motion_targets_k${NUM_MODES}.pt}" + +TRAIN_CSV="${TRAIN_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/train/ATLAS_train.csv}" +VAL_CSV="${VAL_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/validation/ATLAS_validation.csv}" +TEST_CSV="${TEST_CSV:-${ATLAS_REPRO_ROOT}/dataset_csv/test/ATLAS_test.csv}" +ATLAS_DATASET_DIR="${ATLAS_DATASET_DIR:-${ATLAS_REPRO_ROOT}/datasets/ATLAS}" + +mkdir -p "${OUT_DIR}" + +echo "[base:99] Preflight template-mode prior BBFlow" +echo " OUT_DIR=${OUT_DIR}" +echo " GPU_ID=${GPU_ID}" +echo " BASE_CKPT=${BASE_CKPT}" +echo " NUM_MODES=${NUM_MODES} MPNN_LAYERS=${MOTION_MESSAGE_PASSING_LAYERS} NEAR_DIST_A=${CROSS_COV_NEAR_DISTANCE} TEMPLATE_RESIDUAL_SCALE=${TEMPLATE_RESIDUAL_SCALE} TEMPLATE_REMOVE_ROTATION=${TEMPLATE_REMOVE_ROTATION} ENM_NUM_MODES=${ENM_NUM_MODES} ENM_CUTOFF=${ENM_CUTOFF} FREEZE_FOUNDATION=${FREEZE_FOUNDATION}" +echo " MOTION_TARGET_CACHE=${MOTION_TARGET_CACHE}" +echo " LAMBDA_SHAPE=${LAMBDA_SHAPE} LOCAL=${LAMBDA_LOCAL_COV} CROSS=${LAMBDA_CROSS_COV} RMSF=${LAMBDA_RMSF} ENM_WARMUP_EPOCHS=${ENM_WARMUP_EPOCHS} LAMBDA_ENM_WARMUP=${LAMBDA_ENM_WARMUP}" +echo " INJECT_EMBEDDER=${INJECT_EMBEDDER} INJECT_FILM=${INJECT_FILM} ACTIVATION_CHECKPOINT=${ACTIVATION_CHECKPOINT}" +echo " FORCE_GROUPED_BATCH=false ENSEMBLE_GROUP_SIZE=0" +echo " MAX_NUM_RES_SQUARED=${MAX_NUM_RES_SQUARED} MAX_BATCH_SIZE=${MAX_BATCH_SIZE} PRECISION=${PRECISION}" + +CUDA_VISIBLE_DEVICES="${GPU_ID}" python scripts/check_latent_smoke.py \ + --out_dir "${OUT_DIR}" \ + --device cuda \ + --ckpt_path "${BASE_CKPT}" \ + --override latent.enable=true \ + --override latent.dim="${LATENT_DIM}" \ + --override latent.num_modes="${NUM_MODES}" \ + --override latent.motion_message_passing_layers="${MOTION_MESSAGE_PASSING_LAYERS}" \ + --override latent.cross_cov_near_distance="${CROSS_COV_NEAR_DISTANCE}" \ + --override latent.template_residual_scale="${TEMPLATE_RESIDUAL_SCALE}" \ + --override latent.template_remove_rotation="${TEMPLATE_REMOVE_ROTATION}" \ + --override latent.enm_num_modes="${ENM_NUM_MODES}" \ + --override latent.enm_cutoff="${ENM_CUTOFF}" \ + --override latent.enm_eps="${ENM_EPS}" \ + --override latent.node_cond_dim="${NUM_MODES}" \ + --override latent.edge_cond_dim="${NUM_MODES}" \ + --override latent.freeze_foundation="${FREEZE_FOUNDATION}" \ + --override latent.inject_embedder="${INJECT_EMBEDDER}" \ + --override latent.inject_film="${INJECT_FILM}" \ + --override latent.activation_checkpoint="${ACTIVATION_CHECKPOINT}" \ + --override latent.motion_target_cache_path="${MOTION_TARGET_CACHE}" \ + --override experiment.training.force_grouped_batch=false \ + --override experiment.training.ensemble_group_size=0 \ + --override experiment.training.lambda_shape="${LAMBDA_SHAPE}" \ + --override experiment.training.lambda_local_cov="${LAMBDA_LOCAL_COV}" \ + --override experiment.training.lambda_cross_cov="${LAMBDA_CROSS_COV}" \ + --override experiment.training.lambda_rmsf="${LAMBDA_RMSF}" \ + --override experiment.training.enm_warmup_epochs="${ENM_WARMUP_EPOCHS}" \ + --override experiment.training.lambda_enm_warmup="${LAMBDA_ENM_WARMUP}" \ + --override data.sampler.max_num_res_squared="${MAX_NUM_RES_SQUARED}" \ + --override data.sampler.max_batch_size="${MAX_BATCH_SIZE}" \ + --override experiment.trainer.precision="${PRECISION}" \ + --override experiment.trainer.default_root_dir="${OUT_DIR}" \ + --override data.dataset.train_csv_path="${TRAIN_CSV}" \ + --override "data.dataset.valid_csv_paths=[${VAL_CSV}]" \ + --override "data.dataset.valid_dataset_names=[ATLAS_validation]" \ + --override data.dataset.test_csv_path="${TEST_CSV}" \ + --override data.dataset.split_path="${OUT_DIR}" \ + --override "data.validation.valid_xtc_paths=[${ATLAS_DATASET_DIR}]" + +cat "${OUT_DIR}/latent_smoke_summary.json" \ No newline at end of file diff --git a/bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-310.pyc b/bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b4d4bfd56b316465db0266488cc608ddcba1861 Binary files /dev/null and b/bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-310.pyc differ diff --git a/bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-311.pyc b/bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e62e7c471055b12d1e69b46b918258df18a16b7 Binary files /dev/null and b/bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-311.pyc differ diff --git a/bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-39.pyc b/bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8684bbb565ce509dfb90f83cbb47539fbe837039 Binary files /dev/null and b/bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-39.pyc differ diff --git a/bbflow_base/bbflow/analysis/__pycache__/utils.cpython-310.pyc b/bbflow_base/bbflow/analysis/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d27c507bbc51076a56c238298d5eb621205acbdd Binary files /dev/null and b/bbflow_base/bbflow/analysis/__pycache__/utils.cpython-310.pyc differ diff --git a/bbflow_base/bbflow/analysis/__pycache__/utils.cpython-311.pyc b/bbflow_base/bbflow/analysis/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d65daa877e2df0a3dc83db54bdcc258bb72a70d Binary files /dev/null and b/bbflow_base/bbflow/analysis/__pycache__/utils.cpython-311.pyc differ diff --git a/bbflow_base/bbflow/analysis/analyse_bbflow.py b/bbflow_base/bbflow/analysis/analyse_bbflow.py new file mode 100644 index 0000000000000000000000000000000000000000..fce931be69ae661a99b4caf86759c6c80586f2b8 --- /dev/null +++ b/bbflow_base/bbflow/analysis/analyse_bbflow.py @@ -0,0 +1,1007 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Licensed under the MIT license. + +import numpy as np +import warnings +import pandas as pd +import scipy.stats +import os +import functools +from sklearn.decomposition import PCA +from scipy.stats import bootstrap +import mdtraj +from tqdm import tqdm +from datetime import datetime +import pandas as pd +import numpy as np +from multiprocessing import Pool +from scipy.optimize import linear_sum_assignment +import MDAnalysis as mda +import warnings +import time + + + +def _correlations(a, b, correlation_type="pearson"): + if a.shape[0] == 1 or b.shape[0] == 1: + return np.nan + if correlation_type == "pearson": + return scipy.stats.pearsonr(a, b)[0] + elif correlation_type == "spearman": + return scipy.stats.spearmanr(a, b)[0] + elif correlation_type == "kendall": + return scipy.stats.kendalltau(a, b)[0] + +def _get_pca(xyz): + traj_reshaped = xyz.reshape(xyz.shape[0], -1) + pca = PCA(n_components=min(traj_reshaped.shape)) + coords = pca.fit_transform(traj_reshaped) + return pca, coords + +def _get_rmsds(traj1, traj2, broadcast=False): + n_atoms = traj1.shape[1] + traj1 = traj1.reshape(traj1.shape[0], n_atoms * 3) + traj2 = traj2.reshape(traj2.shape[0], n_atoms * 3) + if broadcast: + traj1, traj2 = traj1[:,None], traj2[None] + distmat = np.square(traj1 - traj2).sum(-1)**0.5 / n_atoms**0.5 * 10 + return distmat + +def _get_mean_covar(xyz): + mean = xyz.mean(0) + xyz = xyz - mean + covar = (xyz[...,None] * xyz[...,None,:]).mean(0) + return mean, covar + +def _sqrtm(M): + D, P = np.linalg.eig(M) + out = (P * np.sqrt(D[:,None])) @ np.linalg.inv(P) + return out + +def _get_wasserstein(distmat, p=2): + assert distmat.shape[0] == distmat.shape[1] + distmat = distmat ** p + row_ind, col_ind = linear_sum_assignment(distmat) + return distmat[row_ind, col_ind].mean() ** (1/p) + +def _get_names(top, ignore_resname=False): + names = [] + for residue in top.residues: + for atom in residue.atoms: + name = f"{atom.residue.chain.index}-{atom.residue.index}" + if not ignore_resname: + name += f"-{atom.residue.name}" + name += f"-{atom.name}" + names.append(name) + return names + +def _align_tops(top1, top2, ignore_resname=False): + names1 = _get_names(top1, ignore_resname) + names2 = _get_names(top2, ignore_resname) + + intersection = [nam for nam in names1 if nam in names2] + + mask1 = [names1.index(nam) for nam in intersection] + mask2 = [names2.index(nam) for nam in intersection] + return sorted(mask1), sorted(mask2) + +def _calculate_dccm_vectorized(traj): + ca_indices = traj.topology.select('name CA') + ca_coords = traj.xyz[:, ca_indices, :] + + n_frames = traj.n_frames + n_ca = len(ca_indices) + ca_coords_reshaped = ca_coords.reshape(n_frames, 3 * n_ca) + + # mean coordinates and displacements for each atom over time + mean_coords = np.mean(ca_coords_reshaped, axis=0) + displacements = ca_coords_reshaped - mean_coords + + covariance_matrix = np.cov(displacements.T) + block_covariances = covariance_matrix.reshape(n_ca, 3, n_ca, 3) + + # Calculate the RMSD for each atom by taking the trace of the 3x3 covariance submatrices + cov = np.einsum('ikjk->ij', block_covariances) + rmsd = np.sqrt(np.diag(cov)) + cov[cov == 0] = 1e-8 + + dccm = cov / (rmsd[:, None] * rmsd[None, :]) + + return dccm + +def _calc_rmsd(ref_traj_1, ref_traj_2, model_traj): + # print("Calculating RMSD") + time_start = datetime.now() + ref_rmsd_matrix = _get_rmsds(ref_traj_1.xyz, ref_traj_2.xyz, broadcast=True) + model_rmsd_matrix = _get_rmsds(model_traj.xyz, model_traj.xyz, broadcast=True) + ref_mean_pairwise_rmsd = ref_rmsd_matrix.mean() + model_mean_pairwise_rmsd = model_rmsd_matrix.mean() + return { + 'ref_mean_pairwise_rmsd': ref_mean_pairwise_rmsd, + 'model_mean_pairwise_rmsd': model_mean_pairwise_rmsd, + 'ref_rmsd_matrix': ref_rmsd_matrix, + 'model_rmsd_matrix': model_rmsd_matrix, + 'rmsd_time_elapsed': (datetime.now() - time_start).total_seconds(), + } + +def _center_coordinates(traj: mdtraj.Trajectory): + """ + mdtraj's parallel centering function might cause problems with multiprocessing. + """ + means = np.mean(traj.xyz.astype(np.float64), axis=1, keepdims=True) + traj.xyz -= means + traces = np.sum(traj.xyz**2, axis=(1,2)) + traj._rmsd_traces = traces + return traj + +def _rmsf_bootstrap(trajs, indices): + # rmsf changes the trajectory inplace, so we need to clone it + a = mdtraj.Trajectory(trajs[0].xyz.copy(), trajs[0].top) + b = mdtraj.Trajectory(trajs[1].xyz.copy(), trajs[1].top) + a = _center_coordinates(a) + b = _center_coordinates(b) + return mdtraj.rmsf(a[indices], b, parallel=False, precentered=True) * 10 + +def _calc_rmsf(traj, ref, bootstrap=False): + # print("Calculating RMSF") + if bootstrap: + rmsf, low, high = _bootstrap( + _rmsf_bootstrap, [traj, ref], traj.n_frames, n_iterations=100, alpha=0.05 + ) + return { + 'rmsf': rmsf, + 'rmsf_low': low, + 'rmsf_high': high, + } + else: + traj = _center_coordinates(traj) + ref = _center_coordinates(ref) + return mdtraj.rmsf(traj, ref, parallel=False, precentered=True) * 10 + +def _calc_dccm(ref_traj, model_traj): + # print("Calculating DCCM") + time_start = datetime.now() + ref_dccm = _calculate_dccm_vectorized(ref_traj) + model_dccm = _calculate_dccm_vectorized(model_traj) + return { + 'ref_dccm': ref_dccm, + 'model_dccm': model_dccm, + 'dccm_time_elapsed': (datetime.now() - time_start).total_seconds(), + } + +def _calc_rmwd(ref_traj, model_traj): + # print("Calculating RMWD") + time_start = datetime.now() + ref_mean, ref_covar = _get_mean_covar(ref_traj.xyz) + model_mean, model_covar = _get_mean_covar(model_traj.xyz) + emd_mean = (np.square(ref_mean - model_mean).sum(-1) ** 0.5) * 10 + try: + emd_var = (np.trace(ref_covar + model_covar - 2*_sqrtm(ref_covar @ model_covar), axis1=1,axis2=2) ** 0.5) * 10 + except: + emd_var = np.trace(ref_covar) ** 0.5 * 10 + + rmwd_trans = np.square(emd_mean).mean() ** 0.5 + rmwd_var = np.square(emd_var).mean() ** 0.5 + rmwd = np.sqrt(rmwd_trans ** 2 + rmwd_var ** 2) + + return { + # 'emd_mean': emd_mean, + # 'emd_var': emd_var, + 'rmwd': rmwd, + 'rmwd_trans': rmwd_trans, + 'rmwd_var': rmwd_var, + 'rmwd_time_elapsed': (datetime.now() - time_start).total_seconds(), + } + +def _pca_w2(ref_coords, model_coords, n_atoms, K=None, prefix=""): + # print("Calculating PCA-W2") + if len(ref_coords.shape) == 3: + ref_coords = ref_coords.reshape(ref_coords.shape[0], -1) + model_coords = model_coords.reshape(model_coords.shape[0], -1) + if K is not None: + ref_coords = ref_coords[:,:K] + model_coords = model_coords[:,:K] + + distmat = np.square(ref_coords[:,None] - model_coords[None]).sum(-1) + distmat = distmat ** 0.5 / n_atoms ** 0.5 * 10 + return { + f'{prefix}pca_w2': _get_wasserstein(distmat), + } + +def _calc_cosine_sim(ref_pca, model_pca): + # print("Calculating Cosine Sim") + time_start = datetime.now() + return { + 'cosine_sim': (ref_pca.components_[0] * model_pca.components_[0]).sum(), + 'cosine_sim_time_elapsed': (datetime.now() - time_start).total_seconds(), + } + +def _calc_weak_transient_contacts(ref_traj, model_traj, ref): + # print("Calculating Weak Transient Contacts") + time_start = datetime.now() + ref_distmat = np.linalg.norm(ref_traj.xyz[:,None,:] - ref_traj.xyz[:,:,None], axis=-1) + model_distmat = np.linalg.norm(model_traj.xyz[:,None,:] - model_traj.xyz[:,:,None], axis=-1) + + ref_contact_prob = (ref_distmat < 0.8).mean(0) + model_contact_prob = (model_distmat < 0.8).mean(0) + crystal_distmat = np.linalg.norm(ref.xyz[0,None,:] - ref.xyz[0,:,None], axis=-1) + + crystal_contact_mask = crystal_distmat < 0.8 + ref_transient_mask = (~crystal_contact_mask) & (ref_contact_prob > 0.1) + model_transient_mask = (~crystal_contact_mask) & (model_contact_prob > 0.1) + ref_weak_mask = crystal_contact_mask & (ref_contact_prob < 0.9) + model_weak_mask = crystal_contact_mask & (model_contact_prob < 0.9) + + weak_contacts = (ref_weak_mask & model_weak_mask).sum() / (ref_weak_mask | model_weak_mask).sum() + transient_contacts = (ref_transient_mask & model_transient_mask).sum() / (ref_transient_mask | model_transient_mask).sum() + + return { + 'weak_contacts': weak_contacts, + 'transient_contacts': transient_contacts, + # 'ref_contact_prob': ref_contact_prob, + # 'model_contact_prob': model_contact_prob, + # 'crystal_distmat': crystal_distmat, + 'weak_transient_contacts_time_elapsed': (datetime.now() - time_start).total_seconds(), + } + +def _calc_clashes(traj, ref, threshold=3): + # print("Calculating clashes") + time_start = datetime.now() + distmat = np.linalg.norm(traj.xyz[:,None,:,:] - traj.xyz[:,:,None,:], axis=-1) + distmat = distmat * 10 + distmat[:, np.arange(traj.n_residues), np.arange(traj.n_residues)] = np.inf + indices = np.triu_indices(distmat.shape[1], k=1) + + if threshold == "include_CACA_MD_dist": + # some input equilibrium structures of ATLAS have neighbours + # whose distance is around 3.2 A, instead of the normal 3.8. + dist_CACA_ref = np.linalg.norm(ref.xyz[0,1:,:] - ref.xyz[0,:-1,:], axis=-1) + dist_CACA_ref = dist_CACA_ref * 10 + small_CA_dist = dist_CACA_ref < 3.5 + default_threshold = 3.0 + CA_dist_threshold = np.ones((traj.n_frames, traj.n_residues-1)) * default_threshold + CA_dist_threshold[:,small_CA_dist] = 2.8 + threshold = default_threshold * np.ones_like(distmat) + threshold[:, np.arange(traj.n_residues-1), np.arange(1, traj.n_residues)] = CA_dist_threshold + threshold[:, np.arange(1, traj.n_residues), np.arange(traj.n_residues-1)] = CA_dist_threshold + threshold_flat = threshold.reshape(traj.n_frames, -1) + threshold_nn = threshold[:, indices[0], indices[1]] + else: + threshold_flat = threshold * np.ones_like(distmat.reshape(traj.n_frames, -1)) + threshold_nn = threshold * np.ones_like(distmat[:, indices[0], indices[1]]) + + conf_contains_clashes = np.any(distmat.reshape(traj.n_frames, -1) < threshold_flat, axis=1) + + distances = distmat[:, indices[0], indices[1]] + + return { + 'clashes_ratio_conf': conf_contains_clashes.mean(), # (num confs with clashes) / (num confs) + 'clashes_ratio_all': (distances < threshold_nn).mean(), # (num respairs with clashes) / (num respairs) + 'clashes_all': (distances < threshold_nn).sum(), # (num respairs with clashes) + 'clashes_time_elapsed': (datetime.now() - time_start).total_seconds(), + } + +def _calc_CACA_breaks(traj, ref_traj, threshold=4.19): + # print("Calculating breaks") + time_start = datetime.now() + + if threshold == "max_MD": + threshold = np.max(np.linalg.norm(ref_traj.xyz[:,1:,:] - ref_traj.xyz[:,:-1,:], axis=-1)) * 10 + + distances = np.linalg.norm(traj.xyz[:,1:,:] - traj.xyz[:,:-1,:], axis=-1) + distances = distances * 10 + conf_contains_breaks = np.any(distances > threshold, axis=1) + return { + 'breaks_CACA_ratio_conf': conf_contains_breaks.mean(), # (num confs with breaks) / (num confs) + 'breaks_CACA_ratio_all': (distances > threshold).mean(), # (num neighbours with breaks) / (num neighbours) + 'breaks_CACA_all': (distances > threshold).sum(), # (num neighbours with breaks) + 'breaks_CACA_time_elapsed': (datetime.now() - time_start).total_seconds(), + } + +def _calc_NC_breaks(traj, ref_traj, threshold=1.5): + # print("Calculating breaks") + time_start = datetime.now() + + if threshold == "max_MD": + N_pos = ref_traj.xyz[:,ref_traj.top.select('name N'),:] + C_pos = ref_traj.xyz[:,ref_traj.top.select('name C'),:] + threshold = np.max(np.linalg.norm(N_pos[:,1:,:] - C_pos[:,:-1,:], axis=-1)) * 10 + + N_pos = traj.xyz[:,traj.top.select('name N'),:] + C_pos = traj.xyz[:,traj.top.select('name C'),:] + distances = np.linalg.norm(N_pos[:,1:,:] - C_pos[:,:-1,:], axis=-1) + distances = distances * 10 + conf_contains_breaks = np.any(distances > threshold, axis=1) + return { + 'breaks_NC_ratio_conf': conf_contains_breaks.mean(), # (num confs with breaks) / (num confs) + 'breaks_NC_ratio_all': (distances > threshold).mean(), # (num neighbours with breaks) / (num neighbours) + 'breaks_NC_all': (distances > threshold).sum(), # (num neighbours with breaks) + 'breaks_NC_time_elapsed': (datetime.now() - time_start).total_seconds(), + } + + +def _bootstrap(func, data, n_samples, n_iterations=100, alpha=0.05): + sample_estimate = func(data, np.arange(n_samples)) + + bootstrap_estimates = np.zeros((n_iterations, *sample_estimate.shape)) + for i in range(n_iterations): + bootstrap_indices = np.random.choice(n_samples, n_samples, replace=True) + bootstrap_estimates[i] = func(data, bootstrap_indices) + + low = 2 * sample_estimate - np.percentile(bootstrap_estimates, 100 * (1-alpha/2), axis=0) + high = 2 * sample_estimate - np.percentile(bootstrap_estimates, 100 * (alpha/2), axis=0) + + return sample_estimate, low, high + + +def _load_model_traj(name, pdbdirs): + model_traj_aa = None + if isinstance(name, (tuple, list)): + model_traj_path = name[0] + if not os.path.exists(model_traj_path): + warnings.warn(f"Expected model trajectory path {model_traj_path} does not exist. Skipping...") + return None + model_traj_aa = mdtraj.load(model_traj_path) + + else: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + for pdbdir in pdbdirs: + if os.path.exists(f'{pdbdir}/{name}/sampled_conformations.pdb'): + model_traj_aa = mdtraj.load(f'{pdbdir}/{name}/sampled_conformations.pdb') + elif len(name) == 5 and os.path.exists(f'{pdbdir}/{name[:4]}_{name[4]}.pdb'): + model_traj_aa = mdtraj.load(f'{pdbdir}/{name[:4]}_{name[4]}.pdb') + elif os.path.exists(f'{pdbdir}/{name}.pdb'): + model_traj_aa = mdtraj.load(f'{pdbdir}/{name}.pdb') + if model_traj_aa is None: + warnings.warn(f"No model samples found for {name} in {pdbdirs}. Skipping...") + + return model_traj_aa + +def _load_ref_traj_full(name, reference_dirs, n_confs): + # print(f"Loading {name}") + ref_aa = ref_traj_aa = None + if isinstance(name, (tuple, list)): + if not all(os.path.exists(p) for p in name[1:]): + warnings.warn(f"Expected reference trajectory paths {name[1:]} do not all exist. Skipping...") + return None, None, None + topfile = name[1] + ref_traj_pahts = name[2:] + ref_aa = mdtraj.load(topfile) + ref_traj_aa = mdtraj.load(ref_traj_pahts[0], top=topfile) + for path in ref_traj_pahts[1:]: + ref_traj_aa += mdtraj.load(path, top=topfile) + + else: + for reference_dir in reference_dirs: + if not os.path.exists(f'{reference_dir}/{name}/{name}.pdb'): + continue + ref_aa = mdtraj.load(f'{reference_dir}/{name}/{name}.pdb') + topfile = f'{reference_dir}/{name}/{name}.pdb' + ref_traj_aa = mdtraj.load(f'{reference_dir}/{name}/{name}_R1.xtc', top=topfile) \ + + mdtraj.load(f'{reference_dir}/{name}/{name}_R2.xtc', top=topfile) \ + + mdtraj.load(f'{reference_dir}/{name}/{name}_R3.xtc', top=topfile) + + if ref_aa is None or ref_traj_aa is None: + warnings.warn(f"No reference trajectory found for {name} in {reference_dirs}. Skipping...") + return None, None, None + + RAND1 = np.random.randint(0, ref_traj_aa.n_frames, n_confs) + RAND2 = np.random.randint(0, ref_traj_aa.n_frames, n_confs) + RAND1K = np.random.randint(0, ref_traj_aa.n_frames, 1000) + return ref_aa, ref_traj_aa, (RAND1, RAND2, RAND1K) + +def _load_ref_traj_indices(paths, topfile, indices, n_frames_cumsum): + frames = [] + for i, path in enumerate(paths): + indices_i = indices[(indices >= n_frames_cumsum[i]) & (indices < n_frames_cumsum[i+1])] + indices_i -= n_frames_cumsum[i] + traj = mda.coordinates.XTC.XTCReader(path,refresh_offsets=True) + traj = traj.trajectory + frames_i = np.stack([traj[i].positions.copy() for i in indices_i], axis=0) + frames.append(frames_i) + + frames = np.concatenate(frames, axis=0) + return mdtraj.Trajectory(frames/10, mdtraj.load(topfile).topology) +def _load_ref_traj_subset(name, reference_dirs, n_confs): + ref_aa = ref_traj_aa = None + for reference_dir in reference_dirs: + if not os.path.exists(f'{reference_dir}/{name}/{name}.pdb'): + continue + ref_aa = mdtraj.load(f'{reference_dir}/{name}/{name}.pdb') + topfile = f'{reference_dir}/{name}/{name}.pdb' + + n_frames = [ + mda.coordinates.XTC.XTCReader( + f'{reference_dir}/{name}/{name}_R{i+1}.xtc', refresh_offsets=True + ).n_frames for i in range(3) + ] + RAND1 = np.random.randint(0, sum(n_frames), n_confs) + RAND2 = np.random.randint(0, sum(n_frames), n_confs) + RAND1K = np.random.randint(0, sum(n_frames), 1000) + ref_traj_paths = [f'{reference_dir}/{name}/{name}_R{i+1}.xtc' for i in range(3)] + n_frames_cumsum = (np.cumsum([0]+n_frames)).astype(int) + ref_traj_1 = _load_ref_traj_indices( + ref_traj_paths, topfile, RAND1, n_frames_cumsum + ) + ref_traj_2 = _load_ref_traj_indices( + ref_traj_paths, topfile, RAND2, n_frames_cumsum + ) + ref_traj_1K = _load_ref_traj_indices( + ref_traj_paths, topfile, RAND1K, n_frames_cumsum + ) + ref_traj_aa = ref_traj_1 + ref_traj_2 + ref_traj_1K + if ref_aa is None: + print(f"No reference trajectory found for {name}") + + RAND1 = np.arange(0, n_confs) + RAND2 = np.arange(n_confs, 2*n_confs) + RAND1K = np.arange(2*n_confs, 2*n_confs+1000) + return ref_aa, ref_traj_aa, (RAND1, RAND2, RAND1K) + +def _slice_and_superpose(ref_aa, ref_traj_aa, model_traj_aa): + time_start = datetime.now() + + ref_traj_aa.atom_slice([a.index for a in ref_traj_aa.top.atoms if a.element.symbol != 'H'], True) + ref_aa.atom_slice([a.index for a in ref_aa.top.atoms if a.element.symbol != 'H'], True) + model_traj_aa.atom_slice([a.index for a in model_traj_aa.top.atoms if a.element.symbol != 'H'], True) + + # only backbone atoms, since our model only predicts backbone atoms + model_traj_aa.atom_slice([a.index for a in model_traj_aa.top.atoms if a.name in ['CA', 'C', 'N', 'O', 'OXT']], True) + + refmask, modelmask = _align_tops(ref_traj_aa.top, model_traj_aa.top, True) + ref_traj_aa.atom_slice(refmask, True) + ref_aa.atom_slice(refmask, True) + model_traj_aa.atom_slice(modelmask, True) + + ref_traj_aa.superpose(ref_aa, parallel=False) + model_traj_aa.superpose(ref_aa, parallel=False) + + ca_mask = [a.index for a in ref_traj_aa.top.atoms if a.name == 'CA'] + ca_mask_model = [a.index for a in model_traj_aa.top.atoms if a.name == 'CA'] + ref_traj = ref_traj_aa.atom_slice(ca_mask, False) + ref = ref_aa.atom_slice(ca_mask, False) + model_traj = model_traj_aa.atom_slice(ca_mask_model, False) + + ref_traj.superpose(ref, parallel=False) + model_traj.superpose(ref, parallel=False) + + slice_superpose_time_elapsed = (datetime.now() - time_start).total_seconds() + + return ( + (ref_aa, ref), + (ref_traj_aa, ref_traj), + (model_traj_aa, model_traj), + slice_superpose_time_elapsed + ) + +def _calc_metrics( + name, metrics_subset, load_subset, + ref_aa, ref, + ref_traj_aa, ref_traj, + model_traj_aa, model_traj, + RAND1, RAND2, RAND1K, + ): + n_atoms = ref_traj.n_atoms + + # ref_traj_aa_RAND1 = ref_traj_aa[RAND1] # not used + # ref_traj_aa_RAND2 = ref_traj_aa[RAND2] # not used + ref_traj_aa_RAND1K = ref_traj_aa[RAND1K] + ref_traj_RAND1 = ref_traj[RAND1] + ref_traj_RAND2 = ref_traj[RAND2] + ref_traj_RAND1K = ref_traj[RAND1K] + if load_subset: + ref_traj = ref_traj[RAND1K] + ref_traj_aa = ref_traj_aa[RAND1K] + + out = {} + + out["length"] = ref_traj.n_residues + out["num_conformations"] = model_traj.n_frames + + if metrics_subset is None or "RMSD" in metrics_subset: + out.update(_calc_rmsd(ref_traj_RAND1, ref_traj_RAND2, model_traj)) + + if metrics_subset is None or "RMSF" in metrics_subset: + time_start = datetime.now() + + # CA_rmsf with bootstrap for plotting. + ref_traj_cloned = mdtraj.Trajectory(ref_traj.xyz.copy(), ref_traj.top) + model_traj_cloned = mdtraj.Trajectory(model_traj.xyz.copy(), model_traj.top) + ref_cloned = mdtraj.Trajectory(ref.xyz.copy(), ref.top) + CA_ref_rmsf = _calc_rmsf(ref_traj_cloned, ref_cloned, bootstrap=True) + CA_model_rmsf = _calc_rmsf(model_traj_cloned, ref_cloned, bootstrap=True) + out.update({f"CA_ref_{k}": v for k, v in CA_ref_rmsf.items()}) + out.update({f"CA_model_{k}": v for k, v in CA_model_rmsf.items()}) + + # rmsf on CA only without bootstrap for analysis + ref_traj_cloned = mdtraj.Trajectory(ref_traj.xyz.copy(), ref_traj.top) + model_traj_cloned = mdtraj.Trajectory(model_traj.xyz.copy(), model_traj.top) + ref_cloned = mdtraj.Trajectory(ref.xyz.copy(), ref.top) + out["ref_rmsf"] = _calc_rmsf(ref_traj_cloned, ref_cloned, bootstrap=False) + out["model_rmsf"] = _calc_rmsf(model_traj_cloned, ref_cloned, bootstrap=False) + + out['rmsf_time_elapsed'] = (datetime.now() - time_start).total_seconds() + + if metrics_subset is None or "BB-RMSF" in metrics_subset: + time_start = datetime.now() + + # rmsf on backbone and full reference trajectory for analysis + ref_traj_cloned = mdtraj.Trajectory(ref_traj_aa.xyz.copy(), ref_traj_aa.top) + model_traj_cloned = mdtraj.Trajectory(model_traj_aa.xyz.copy(), model_traj_aa.top) + ref_cloned = mdtraj.Trajectory(ref_aa.xyz.copy(), ref_aa.top) + out["BB_ref_rmsf"] = _calc_rmsf(ref_traj_cloned, ref_cloned, bootstrap=False) + out["BB_model_rmsf"] = _calc_rmsf(model_traj_cloned, ref_cloned, bootstrap=False) + + out['bb_rmsf_time_elapsed'] = (datetime.now() - time_start).total_seconds() + + if metrics_subset is None or "DCCM" in metrics_subset: + out.update(_calc_dccm(ref_traj, model_traj)) + + if metrics_subset is None or "RMWD" in metrics_subset: + out.update(_calc_rmwd(ref_traj_RAND1K, model_traj)) + rmwd_bb = _calc_rmwd(ref_traj_aa_RAND1K, model_traj_aa) + out.update({f"BB_{k}": v for k, v in rmwd_bb.items()}) + + ref_pca = model_pca = None + if metrics_subset is None or "PCA-W2" in metrics_subset: + time_start = datetime.now() + ref_pca, ref_coords = _get_pca(ref_traj.xyz) + model_pca, _ = _get_pca(model_traj.xyz) + model_coords_ref_pca = ref_pca.transform(model_traj.xyz.reshape(model_traj.n_frames, -1)) + joint_pca, _ = _get_pca(np.concatenate([ref_traj_RAND1.xyz, model_traj.xyz])) + ref_coords_joint_pca = joint_pca.transform(ref_traj.xyz.reshape(ref_traj.n_frames, -1)) + model_coords_joint_pca = joint_pca.transform(model_traj.xyz.reshape(model_traj.n_frames, -1)) + + out['ref_variance'] = ref_pca.explained_variance_ / n_atoms * 100 + out['model_variance'] = model_pca.explained_variance_ / n_atoms * 100 + out['joint_variance'] = joint_pca.explained_variance_ / n_atoms * 100 + + out['md_pca_ref_coords'] = ref_coords + out['md_pca_model_coords'] = model_coords_ref_pca + out['joint_pca_ref_coords'] = ref_coords_joint_pca + out['joint_pca_model_coords'] = model_coords_joint_pca + + RAND1 = np.random.randint(0, ref_traj.n_frames, model_traj.n_frames) + out.update(_pca_w2(ref_coords[RAND1], model_coords_ref_pca, n_atoms, K=2, prefix="md_")) + out.update(_pca_w2(ref_coords_joint_pca[RAND1], model_coords_joint_pca, n_atoms, K=2, prefix="joint_")) + out['pca_w2_time_elapsed'] = (datetime.now() - time_start).total_seconds() + + if metrics_subset is None or "Cosine Sim" in metrics_subset: + if ref_pca is None: + ref_pca, _ = _get_pca(ref_traj.xyz) + model_pca, _ = _get_pca(model_traj.xyz) + out.update(_calc_cosine_sim(ref_pca, model_pca)) + + if metrics_subset is None or "Weak Transient Contacts" in metrics_subset: + out.update(_calc_weak_transient_contacts(ref_traj_RAND1, model_traj, ref)) + + if metrics_subset is None or "Breaks and Clashes" in metrics_subset: + out.update(_calc_clashes(model_traj, ref, threshold="include_CACA_MD_dist")) + out.update(_calc_CACA_breaks(model_traj, ref_traj, threshold="max_MD")) + out.update(_calc_NC_breaks(model_traj_aa, ref_traj_aa, threshold="max_MD")) + + return out +def _calc_metrics_bootstrap( + name, reference_dirs, pdbdirs, num_conformations=None, num_bootstrap_samples=1, + seed=None, load_subset=False, metrics_subset=None, + load_ref_fn=_load_ref_traj_full, load_model_fn=_load_model_traj, + ): + if seed is not None: + np.random.seed(seed) + else: + np.random.seed((os.getpid() * hash(name) * int(time.time())) % 2**32) + + time_start = datetime.now() + # load reference and model trajectories + model_traj_aa = load_model_fn(name, pdbdirs) + if model_traj_aa is None: + return name, None + ref_aa, ref_traj_aa, rand_indices = load_ref_fn( + name, reference_dirs, + model_traj_aa.n_frames if num_conformations is None else num_conformations + ) + if ref_aa is None or ref_traj_aa is None: + return name, None + loading_traj_time_elapsed = (datetime.now() - time_start).total_seconds() + RAND1, RAND2, RAND1K = rand_indices + + ref, ref_traj, model_traj, slice_superpose_time_elapsed = _slice_and_superpose( + ref_aa, ref_traj_aa, model_traj_aa + ) + ref_aa, ref = ref + ref_traj_aa, ref_traj = ref_traj + model_traj_aa, model_traj = model_traj + + + if num_bootstrap_samples == 1: + if num_conformations is not None and num_conformations < model_traj_aa.n_frames: + model_indices = np.random.choice( + model_traj_aa.n_frames, num_conformations, replace=False + ) + model_traj_aa = model_traj_aa[model_indices] + model_traj = model_traj[model_indices] + + RAND1 = np.random.randint(0, ref_traj_aa.n_frames, model_traj_aa.n_frames) + RAND2 = np.random.randint(0, ref_traj_aa.n_frames, model_traj_aa.n_frames) + RAND1K = np.random.randint(0, ref_traj_aa.n_frames, 1000) + + out = _calc_metrics( + name, metrics_subset, load_subset, + ref_aa, ref, + ref_traj_aa, ref_traj, + model_traj_aa, model_traj, + RAND1, RAND2, RAND1K, + ) + out["loading_traj_time_elapsed"] = loading_traj_time_elapsed + out["slice_superpose_time_elapsed"] = slice_superpose_time_elapsed + return name, out + + + else: + + out = {} + for i in range(num_bootstrap_samples): + if num_conformations is not None and num_conformations < model_traj_aa.n_frames: + model_indices = np.random.choice( + model_traj_aa.n_frames, num_conformations, replace=False + ) + model_traj_aa_i = model_traj_aa[model_indices] + model_traj_i = model_traj[model_indices] + else: + model_traj_aa_i = model_traj_aa + model_traj_i = model_traj + + RAND1 = np.random.randint(0, ref_traj_aa.n_frames, model_traj_aa_i.n_frames) + RAND2 = np.random.randint(0, ref_traj_aa.n_frames, model_traj_aa_i.n_frames) + RAND1K = np.random.randint(0, ref_traj_aa.n_frames, 1000) + + out_i = _calc_metrics( + name, metrics_subset, load_subset, + ref_aa, ref, + ref_traj_aa, ref_traj, + model_traj_aa_i, model_traj_i, + RAND1, RAND2, RAND1K, + ) + for key, val in out_i.items(): + if key not in out: + out[key] = [] + out[key].append(val) + + for key, val in out.items(): + out[key] = np.array(val) + out["loading_traj_time_elapsed"] = loading_traj_time_elapsed*np.ones(num_bootstrap_samples) + out["slice_superpose_time_elapsed"] = slice_superpose_time_elapsed*np.ones(num_bootstrap_samples) + + + return name, out + +def _analyze_data(data, metrics_subset=None): + # print("Analyzing data") + concatenated_lists = {} + if metrics_subset is None or "RMSF" in metrics_subset: + concatenated_lists["rmsf"] = { + "ref": np.concatenate([data[name]['ref_rmsf'] for name in data]), + "model": np.concatenate([data[name]['model_rmsf'] for name in data]), + } + if metrics_subset is None or "BB-RMSF" in metrics_subset: + concatenated_lists["BB_rmsf"] = { + "ref": np.concatenate([data[name]['BB_ref_rmsf'] for name in data]), + "model": np.concatenate([data[name]['BB_model_rmsf'] for name in data]), + } + if metrics_subset is None or "DCCM" in metrics_subset: + concatenated_lists["dccm"] = { + "ref": np.concatenate([data[name]['ref_dccm'].flatten() for name in data]), + "model": np.concatenate([data[name]['model_dccm'].flatten() for name in data]), + } + if metrics_subset is None or "Breaks and Clashes" in metrics_subset: + total_number_of_clashes = np.sum([data[name]['clashes_all'] for name in data]) + total_number_of_confs_with_clashes = np.sum([data[name]['clashes_ratio_conf']*data[name]['num_conformations'] for name in data]) + total_number_of_nn_pairs = sum([int(data[name]['length']*(data[name]['length']-1)/2) for name in data]) + total_number_of_breaks_CACA = np.sum([data[name]['breaks_CACA_all'] for name in data]) + total_number_of_confs_with_breaks_CACA = np.sum([data[name]['breaks_CACA_ratio_conf']*data[name]['num_conformations'] for name in data]) + total_number_of_breaks_NC = np.sum([data[name]['breaks_NC_all'] for name in data]) + total_number_of_confs_with_breaks_NC = np.sum([data[name]['breaks_NC_ratio_conf']*data[name]['num_conformations'] for name in data]) + total_number_of_neighbours = sum([data[name]['length']-1 for name in data]) + total_number_of_confs = sum([data[name]['num_conformations'] for name in data]) + + df = [] + + for name, out in data.items(): + item = { + "name": name, + "loading_traj_time_elapsed": out["loading_traj_time_elapsed"], + "slice_superpose_time_elapsed": out["slice_superpose_time_elapsed"] + } + if metrics_subset is None or "RMSD" in metrics_subset: + item.update({ + "md_pairwise_rmsd": out['ref_mean_pairwise_rmsd'], + "model_pairwise_rmsd": out['model_mean_pairwise_rmsd'], + "rmsd_time_elapsed": out['rmsd_time_elapsed'], + }) + + if metrics_subset is None or "RMSF" in metrics_subset: + item["per_target_rmsf_corr"] = _correlations( + out['model_rmsf'], + out['ref_rmsf'], + correlation_type="pearson" + ) + item["per_target_rmsf_mae"] = np.abs(out['model_rmsf'] - out['ref_rmsf']).mean() + item["per_target_rmsf_rmse"] = np.sqrt(((out['model_rmsf'] - out['ref_rmsf']) ** 2).mean()) + item["rmsf_time_elapsed"] = out['rmsf_time_elapsed'] + + if metrics_subset is None or "BB-RMSF" in metrics_subset: + item["per_target_rmsf_corr_bb"] = _correlations( + out['BB_model_rmsf'], + out['BB_ref_rmsf'], + correlation_type="pearson" + ) + item["per_target_rmsf_mae_bb"] = np.abs(out['BB_model_rmsf'] - out['BB_ref_rmsf']).mean() + item["per_target_rmsf_rmse_bb"] = np.sqrt(((out['BB_model_rmsf'] - out['BB_ref_rmsf']) ** 2).mean()) + item["rmsf_time_elapsed"] = out['rmsf_time_elapsed'] + + if metrics_subset is None or "DCCM" in metrics_subset: + item["per_target_dccm_corr"] = _correlations( + out['model_dccm'].flatten(), + out['ref_dccm'].flatten(), + correlation_type="pearson" + ) + item["per_target_dccm_mae"] = np.abs(out['model_dccm'].flatten() - out['ref_dccm'].flatten()).mean() + item["per_target_dccm_rmse"] = np.sqrt(((out['model_dccm'].flatten() - out['ref_dccm'].flatten()) ** 2).mean()) + item["dccm_time_elapsed"] = out['dccm_time_elapsed'] + + if metrics_subset is None or "RMWD" in metrics_subset: + item.update({ + 'rmwd': out['rmwd'], + 'rmwd_trans': out['rmwd_trans'], + 'rmwd_var': out['rmwd_var'], + 'BB_rmwd': out['BB_rmwd'], + 'BB_rmwd_trans': out['BB_rmwd_trans'], + 'BB_rmwd_var': out['BB_rmwd_var'], + 'rmwd_time_elapsed': out['rmwd_time_elapsed']+out['BB_rmwd_time_elapsed'], + }) + + if metrics_subset is None or "PCA-W2" in metrics_subset: + item.update({ + 'md_pca_w2': out['md_pca_w2'], + 'joint_pca_w2': out['joint_pca_w2'], + 'pca_w2_time_elapsed': out['pca_w2_time_elapsed'], + }) + + if metrics_subset is None or "Cosine Sim" in metrics_subset: + item['cosine_sim'] = out['cosine_sim'] + item['cosine_sim_time_elapsed'] = out['cosine_sim_time_elapsed'] + + if metrics_subset is None or "Weak Transient Contacts" in metrics_subset: + item.update({ + 'weak_contacts': out['weak_contacts'], + 'transient_contacts': out['transient_contacts'], + 'weak_transient_contacts_time_elapsed': out['weak_transient_contacts_time_elapsed'], + }) + + if metrics_subset is None or "Breaks and Clashes" in metrics_subset: + item.update({ + 'clashes_ratio_conf': out['clashes_ratio_conf'], + 'clashes_ratio_all': out['clashes_ratio_all'], + 'clashes_all': out['clashes_all'], + 'breaks_CACA_ratio_conf': out['breaks_CACA_ratio_conf'], + 'breaks_CACA_ratio_all': out['breaks_CACA_ratio_all'], + 'breaks_CACA_all': out['breaks_CACA_all'], + 'breaks_NC_ratio_conf': out['breaks_NC_ratio_conf'], + 'breaks_NC_ratio_all': out['breaks_NC_ratio_all'], + 'breaks_NC_all': out['breaks_NC_all'], + 'breaks_and_clashes_time_elapsed': out['clashes_time_elapsed'] + out['breaks_CACA_time_elapsed'] + out['breaks_NC_time_elapsed'] + }) + + df.append(item) + + df = pd.DataFrame(df).set_index('name') + + metrics_dict = {} + if metrics_subset is None or "RMSD" in metrics_subset: + metrics_dict["MD pairwise RMSD"] = df.md_pairwise_rmsd.median() + metrics_dict["Pairwise RMSD"] = df.model_pairwise_rmsd.median() + metrics_dict["MD pairwise RMSD mean"] = df.md_pairwise_rmsd.mean() + metrics_dict["Pairwise RMSD mean"] = df.model_pairwise_rmsd.mean() + metrics_dict["Pairwise RMSD r"] = _correlations(df.md_pairwise_rmsd, df.model_pairwise_rmsd, "pearson") + metrics_dict["Pairwise RMSD MAE"] = np.abs(df.md_pairwise_rmsd - df.model_pairwise_rmsd).mean() + metrics_dict["Pairwise RMSD RMSE"] = np.sqrt(((df.md_pairwise_rmsd - df.model_pairwise_rmsd) ** 2).mean()) + metrics_dict["Pairwise RMSD MAE max"] = np.abs(df.md_pairwise_rmsd - df.model_pairwise_rmsd).max() + metrics_dict["Pairwise RMSD RMSE max"] = np.sqrt(((df.md_pairwise_rmsd - df.model_pairwise_rmsd) ** 2).max()) + + if metrics_subset is None or "RMSF" in metrics_subset: + metrics_dict["MD RMSF"] = np.median(concatenated_lists["rmsf"]["ref"]) + metrics_dict["RMSF"] = np.median(concatenated_lists["rmsf"]["model"]) + metrics_dict["MD RMSF mean"] = np.mean(concatenated_lists["rmsf"]["ref"]) + metrics_dict["RMSF mean"] = np.mean(concatenated_lists["rmsf"]["model"]) + metrics_dict["Global RMSF r"] = _correlations(concatenated_lists["rmsf"]["ref"], concatenated_lists["rmsf"]["model"], "pearson") + metrics_dict["Global RMSF MAE"] = np.abs(concatenated_lists["rmsf"]["ref"] - concatenated_lists["rmsf"]["model"]).mean() + metrics_dict["Global RMSF RMSE"] = np.sqrt(((concatenated_lists["rmsf"]["ref"] - concatenated_lists["rmsf"]["model"]) ** 2).mean()) + metrics_dict["Per target RMSF r"] = df.per_target_rmsf_corr.median() + metrics_dict["Per target RMSF r mean"] = df.per_target_rmsf_corr.mean() + metrics_dict["Per target RMSF r min"] = df.per_target_rmsf_corr.min() + metrics_dict["Per target RMSF MAE"] = df.per_target_rmsf_mae.median() + metrics_dict["Per target RMSF MAE mean"] = df.per_target_rmsf_mae.mean() + metrics_dict["Per target RMSF MAE max"] = df.per_target_rmsf_mae.max() + metrics_dict["Per target RMSF RMSE"] = df.per_target_rmsf_rmse.median() + metrics_dict["Per target RMSF RMSE mean"] = df.per_target_rmsf_rmse.mean() + metrics_dict["Per target RMSF RMSE max"] = df.per_target_rmsf_rmse.max() + + if metrics_subset is None or "BB-RMSF" in metrics_subset: + metrics_dict["MD BB-RMSF"] = np.median(concatenated_lists["BB_rmsf"]["ref"]) + metrics_dict["BB-RMSF"] = np.median(concatenated_lists["BB_rmsf"]["model"]) + metrics_dict["MD BB-RMSF mean"] = np.mean(concatenated_lists["BB_rmsf"]["ref"]) + metrics_dict["BB-RMSF mean"] = np.mean(concatenated_lists["BB_rmsf"]["model"]) + metrics_dict["Global BB-RMSF r"] = _correlations(concatenated_lists["BB_rmsf"]["ref"], concatenated_lists["BB_rmsf"]["model"], "pearson") + metrics_dict["Global BB-RMSF MAE"] = np.abs(concatenated_lists["BB_rmsf"]["ref"] - concatenated_lists["BB_rmsf"]["model"]).mean() + metrics_dict["Global BB-RMSF RMSE"] = np.sqrt(((concatenated_lists["BB_rmsf"]["ref"] - concatenated_lists["BB_rmsf"]["model"]) ** 2).mean()) + metrics_dict["Per target BB-RMSF r"] = df.per_target_rmsf_corr_bb.median() + metrics_dict["Per target BB-RMSF r mean"] = df.per_target_rmsf_corr_bb.mean() + metrics_dict["Per target BB-RMSF r min"] = df.per_target_rmsf_corr_bb.min() + metrics_dict["Per target BB-RMSF MAE"] = df.per_target_rmsf_mae_bb.median() + metrics_dict["Per target BB-RMSF MAE mean"] = df.per_target_rmsf_mae_bb.mean() + metrics_dict["Per target BB-RMSF MAE max"] = df.per_target_rmsf_mae_bb.max() + metrics_dict["Per target BB-RMSF RMSE"] = df.per_target_rmsf_rmse_bb.median() + metrics_dict["Per target BB-RMSF RMSE mean"] = df.per_target_rmsf_rmse_bb.mean() + metrics_dict["Per target BB-RMSF RMSE max"] = df.per_target_rmsf_rmse_bb.max() + + if metrics_subset is None or "DCCM" in metrics_subset: + metrics_dict["MD DCCM"] = np.median(concatenated_lists["dccm"]["ref"]) + metrics_dict["DCCM"] = np.median(concatenated_lists["dccm"]["model"]) + metrics_dict["MD DCCM mean"] = np.mean(concatenated_lists["dccm"]["ref"]) + metrics_dict["DCCM mean"] = np.mean(concatenated_lists["dccm"]["model"]) + metrics_dict["Global DCCM r"] = _correlations(concatenated_lists["dccm"]["ref"], concatenated_lists["dccm"]["model"], "pearson") + metrics_dict["Global DCCM MAE"] = np.abs(concatenated_lists["dccm"]["ref"] - concatenated_lists["dccm"]["model"]).mean() + metrics_dict["Global DCCM RMSE"] = np.sqrt(((concatenated_lists["dccm"]["ref"] - concatenated_lists["dccm"]["model"]) ** 2).mean()) + metrics_dict["Per target DCCM r"] = df.per_target_dccm_corr.median() + metrics_dict["Per target DCCM r mean"] = df.per_target_dccm_corr.mean() + metrics_dict["Per target DCCM r min"] = df.per_target_dccm_corr.min() + metrics_dict["Per target DCCM MAE"] = df.per_target_dccm_mae.median() + metrics_dict["Per target DCCM MAE mean"] = df.per_target_dccm_mae.mean() + metrics_dict["Per target DCCM MAE max"] = df.per_target_dccm_mae.max() + metrics_dict["Per target DCCM RMSE"] = df.per_target_dccm_rmse.median() + metrics_dict["Per target DCCM RMSE mean"] = df.per_target_dccm_rmse.mean() + metrics_dict["Per target DCCM RMSE max"] = df.per_target_dccm_rmse.max() + + if metrics_subset is None or "RMWD" in metrics_subset: + metrics_dict["RMWD"] = df.rmwd.median() + metrics_dict["RMWD translation"] = df.rmwd_trans.median() + metrics_dict["RMWD variance"] = df.rmwd_var.median() + + metrics_dict["BB RMWD"] = df.BB_rmwd.median() + metrics_dict["BB RMWD translation"] = df.BB_rmwd_trans.median() + metrics_dict["BB RMWD variance"] = df.BB_rmwd_var.median() + + if metrics_subset is None or "PCA-W2" in metrics_subset: + metrics_dict["MD PCA W2"] = df.md_pca_w2.median() + metrics_dict["Joint PCA W2"] = df.joint_pca_w2.median() + + if metrics_subset is None or "Cosine Sim" in metrics_subset: + metrics_dict["% PC sim > 0.5"] = (df.cosine_sim.abs() > 0.5).mean() * 100 + + if metrics_subset is None or "Weak Transient Contacts" in metrics_subset: + metrics_dict["Weak contacts J"] = df.weak_contacts.median() + metrics_dict["Weak contacts nans"] = df.weak_contacts.isna().mean() + metrics_dict["Transient contacts J"] = df.transient_contacts.median() + metrics_dict["Transient contacts nans"] = df.transient_contacts.isna().mean() + + if metrics_subset is None or "Breaks and Clashes" in metrics_subset: + metrics_dict["Conf \\w clash ratio"] = df.clashes_ratio_conf.median() * 100 + metrics_dict["Conf \\w clash ratio mean"] = df.clashes_ratio_conf.mean() * 100 + metrics_dict["Conf \\w clash ratio max"] = df.clashes_ratio_conf.max() * 100 + metrics_dict["Per target clash ratio"] = df.clashes_ratio_all.median() * 100 + metrics_dict["Per target clash ratio mean"] = df.clashes_ratio_all.mean() * 100 + metrics_dict["Per target clash ratio max"] = df.clashes_ratio_all.max() * 100 + metrics_dict["Clash ratio"] = total_number_of_clashes / (total_number_of_nn_pairs * total_number_of_confs) * 100 + metrics_dict["Conf \\w clash ratio total"] = total_number_of_confs_with_clashes / total_number_of_confs * 100 + + metrics_dict["Conf \\w CACA breaks ratio"] = df.breaks_CACA_ratio_conf.median() * 100 + metrics_dict["Conf \\w CACA breaks ratio mean"] = df.breaks_CACA_ratio_conf.mean() * 100 + metrics_dict["Conf \\w CACA breaks ratio max"] = df.breaks_CACA_ratio_conf.max() * 100 + metrics_dict["Per target CACA breaks ratio"] = df.breaks_CACA_ratio_all.median() * 100 + metrics_dict["Per target CACA breaks ratio mean"] = df.breaks_CACA_ratio_all.mean() * 100 + metrics_dict["Per target CACA breaks ratio max"] = df.breaks_CACA_ratio_all.max() * 100 + metrics_dict["CACA breaks ratio"] = total_number_of_breaks_CACA / (total_number_of_neighbours * total_number_of_confs) * 100 + metrics_dict["Conf \\w CACA breaks ratio total"] = total_number_of_confs_with_breaks_CACA / total_number_of_confs * 100 + + metrics_dict["Conf \\w NC breaks ratio"] = df.breaks_NC_ratio_conf.median() * 100 + metrics_dict["Conf \\w NC breaks ratio mean"] = df.breaks_NC_ratio_conf.mean() * 100 + metrics_dict["Conf \\w NC breaks ratio max"] = df.breaks_NC_ratio_conf.max() * 100 + metrics_dict["Per target NC breaks ratio"] = df.breaks_NC_ratio_all.median() * 100 + metrics_dict["Per target NC breaks ratio mean"] = df.breaks_NC_ratio_all.mean() * 100 + metrics_dict["Per target NC breaks ratio max"] = df.breaks_NC_ratio_all.max() * 100 + metrics_dict["NC breaks ratio"] = total_number_of_breaks_NC / (total_number_of_neighbours * total_number_of_confs) * 100 + metrics_dict["Conf \\w NC breaks ratio total"] = total_number_of_confs_with_breaks_NC / total_number_of_confs * 100 + + + #for col in df.columns: + # if col.endswith("_time_elapsed"): + # print(col, df[col].sum()) + # # metrics_dict[col] = df[col].sum() + + return metrics_dict + + +def calc_metrics( + pdb_names, reference_dirs, pdbdirs, seed, num_workers, + num_conformations=None, num_bootstrap_samples=1, + load_subset=False, metrics_subset=None, + load_ref_fn=_load_ref_traj_full, load_model_fn=_load_model_traj, + use_tqdm=False + ): + if type(reference_dirs) == str: + reference_dirs = [reference_dirs] + if type(pdbdirs) == str: + pdbdirs = [pdbdirs] + print("Calc metrics:", metrics_subset) + + if num_workers > 1: + p = Pool(num_workers) + p.__enter__() + __map__ = p.imap + else: + __map__ = map + + _calc_metrics_partial = functools.partial( + _calc_metrics_bootstrap, + reference_dirs=reference_dirs, + pdbdirs=pdbdirs, + num_conformations=num_conformations, + num_bootstrap_samples=num_bootstrap_samples, + seed=seed, + load_subset=load_subset, + load_ref_fn=load_ref_fn, + load_model_fn=load_model_fn, + metrics_subset=metrics_subset + ) + if use_tqdm: + out = dict(tqdm(__map__(_calc_metrics_partial, pdb_names), total=len(pdb_names), leave=False)) + else: + out = dict(__map__(_calc_metrics_partial, pdb_names)) + if num_workers > 1: + p.__exit__(None, None, None) + + out = {k: v for k, v in out.items() if v is not None} + if len(out) == 0: + raise ValueError("No valid trajectories were loaded.") + + if num_bootstrap_samples == 1: + metrics_dict = _analyze_data(out, metrics_subset) + return out, metrics_dict, None + + else: + metrics_dict_bootstrap = {} + for i in range(num_bootstrap_samples): + out_i = { + name: {k: v[i] for k, v in out[name].items()} for name in out + } + metrics_dict_i = _analyze_data(out_i, metrics_subset) + for key, val in metrics_dict_i.items(): + if key not in metrics_dict_bootstrap: + metrics_dict_bootstrap[key] = [] + metrics_dict_bootstrap[key].append(val) + + metrics_dict_mean = {} + metrics_dict_sem = {} + metrics_dict_low = {} + metrics_dict_high = {} + for key, val in metrics_dict_bootstrap.items(): + val = np.array(val) + ci = bootstrap((val,), np.mean, confidence_level=.95, vectorized=True) + metrics_dict_mean[key] = val.mean() + metrics_dict_sem[key] = ci.standard_error + metrics_dict_low[key] = ci.confidence_interval.low + metrics_dict_high[key] = ci.confidence_interval.high + + metrics_dict = { + "mean": metrics_dict_mean, + "sem": metrics_dict_sem, + "low": metrics_dict_low, + "high": metrics_dict_high, + "bootstrap_samples": metrics_dict_bootstrap, + } + + return out, metrics_dict, None + + + diff --git a/bbflow_base/bbflow/analysis/utils.py b/bbflow_base/bbflow/analysis/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4a3bd97140a58678ab23bed5be6c4479ff0bbc2b --- /dev/null +++ b/bbflow_base/bbflow/analysis/utils.py @@ -0,0 +1,114 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +# TODO: Differs from gafl.analysis.utils only in create_full_prot where +# residue_index is set to start from 1 instead of 0 + + +import numpy as np +import os +import re +from Bio import PDB + +from openfold.utils import rigid_utils +from gafl.data import protein +from gafl.analysis.utils import write_prot_to_pdb, get_pdb_length +from pathlib import Path + +Rigid = rigid_utils.Rigid + + +def create_full_prot( + atom37: np.ndarray, + atom37_mask: np.ndarray, + aatype=None, + b_factors=None, + chain_index=None, + ): + assert atom37.ndim == 3 + assert atom37.shape[-1] == 3 + assert atom37.shape[-2] == 37 + n = atom37.shape[0] + # residue_index = np.arange(n) + if chain_index is None: + chain_index = np.zeros(n) + residue_index = np.arange(n) + 1 # residue index should start from 1 (at least for analyse_bbflow necessary) + else: + _, counts = np.unique(chain_index, return_counts=True) + residue_index = np.concatenate([(np.arange(count) + 1) for count in counts]) + + if b_factors is None: + b_factors = np.zeros([n, 37]) + if aatype is None: + aatype = np.zeros(n, dtype=int) + return protein.Protein( + atom_positions=atom37, + atom_mask=atom37_mask, + aatype=aatype, + residue_index=residue_index, + chain_index=chain_index, + b_factors=b_factors) + + +def write_prot_to_pdb( + prot_pos: np.ndarray, + file_path: str, + aatype: np.ndarray=None, + overwrite=False, + no_indexing=False, + b_factors=None, + chain_index=None, + ): + if overwrite: + max_existing_idx = 0 + else: + file_name = os.path.basename(file_path).strip('.pdb') + existing_files = [str(file) for file in Path(file_path).parent.glob(f'{file_name}*.pdb')] + max_existing_idx = max([ + int(re.findall(r'_(\d+).pdb', x)[0]) for x in existing_files if re.findall(r'_(\d+).pdb', x) + if re.findall(r'_(\d+).pdb', x)] + [0]) + if not no_indexing: + save_path = file_path.replace('.pdb', '') + f'_{max_existing_idx+1}.pdb' + else: + save_path = file_path + with open(save_path, 'w') as f: + if prot_pos.ndim == 4: + for t, pos37 in enumerate(prot_pos): + atom37_mask = np.sum(np.abs(pos37), axis=-1) > 1e-7 + prot = create_full_prot( + pos37, atom37_mask, aatype=aatype, b_factors=b_factors, chain_index=chain_index) + pdb_prot = protein.to_pdb(prot, model=t + 1, add_end=False) + f.write(pdb_prot) + elif prot_pos.ndim == 3: + atom37_mask = np.sum(np.abs(prot_pos), axis=-1) > 1e-7 + prot = create_full_prot( + prot_pos, atom37_mask, aatype=aatype, b_factors=b_factors) + pdb_prot = protein.to_pdb(prot, model=1, add_end=False) + f.write(pdb_prot) + else: + raise ValueError(f'Invalid positions shape {prot_pos.shape}') + f.write('END') + return save_path + +def get_pdb_length(path: str): + # Initialize the PDB parser + parser = PDB.PDBParser(QUIET=True) # QUIET=True suppresses some warnings + + # Parse the PDB file + structure = parser.get_structure("sample", path) + + # Initialize a set to track unique residues + unique_residues = set() + + # Iterate through the chains and residues in the structure + for model in structure: + for chain in model: + for residue in chain: + # Residue's ID is a tuple (hetero-flag, sequence number, insertion code) + # Only consider non-hetero residues (ignore water, ions, etc.) + if residue.id[0] == " ": + unique_residues.add(residue.id) + + # Get the total number of unique residues + return len(unique_residues) \ No newline at end of file diff --git a/bbflow_base/bbflow/data/__pycache__/alignment.cpython-310.pyc b/bbflow_base/bbflow/data/__pycache__/alignment.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45cdadb511d083ba83ae6c278e4d3178ff13bace Binary files /dev/null and b/bbflow_base/bbflow/data/__pycache__/alignment.cpython-310.pyc differ diff --git a/bbflow_base/bbflow/data/__pycache__/alignment.cpython-311.pyc b/bbflow_base/bbflow/data/__pycache__/alignment.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ed350e13cc7cc238708ee45dd065f949da52e6a Binary files /dev/null and b/bbflow_base/bbflow/data/__pycache__/alignment.cpython-311.pyc differ diff --git a/bbflow_base/bbflow/data/__pycache__/alignment.cpython-39.pyc b/bbflow_base/bbflow/data/__pycache__/alignment.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c74a4f957cad72e034fac31e8cfdea42c56cd9a2 Binary files /dev/null and b/bbflow_base/bbflow/data/__pycache__/alignment.cpython-39.pyc differ diff --git a/bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-310.pyc b/bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f93f2db74fff1f5b95f95308fca1b410f34ef347 Binary files /dev/null and b/bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-310.pyc differ diff --git a/bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-311.pyc b/bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7f8350e265f79fb88ebdce14e9b4d37c7782ac1 Binary files /dev/null and b/bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-311.pyc differ diff --git a/bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-39.pyc b/bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..475ae0d686dee9e33ed6beac9829ced281570488 Binary files /dev/null and b/bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-39.pyc differ diff --git a/bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-310.pyc b/bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25c138e427487a7727e8a050775310e9beff479f Binary files /dev/null and b/bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-310.pyc differ diff --git a/bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-311.pyc b/bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2e710f75f3dddda95873b5ff2a15273f8fc25a1 Binary files /dev/null and b/bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-311.pyc differ diff --git a/bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-39.pyc b/bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a06e7dc831e7a949c2657a1f254a3f56e9bd245 Binary files /dev/null and b/bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-39.pyc differ diff --git a/bbflow_base/bbflow/data/__pycache__/utils.cpython-310.pyc b/bbflow_base/bbflow/data/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d7f9b607e5766ba40770c911af3984e2a54b1b8 Binary files /dev/null and b/bbflow_base/bbflow/data/__pycache__/utils.cpython-310.pyc differ diff --git a/bbflow_base/bbflow/data/__pycache__/utils.cpython-311.pyc b/bbflow_base/bbflow/data/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6909f3ce73b1614e546a541dfdf0b339e8cae0d5 Binary files /dev/null and b/bbflow_base/bbflow/data/__pycache__/utils.cpython-311.pyc differ diff --git a/bbflow_base/bbflow/data/alignment.py b/bbflow_base/bbflow/data/alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..7cb490f246fad400e18417f3d044c5d57f2f8cde --- /dev/null +++ b/bbflow_base/bbflow/data/alignment.py @@ -0,0 +1,60 @@ +import torch + + +ALIGNMENT_VERSION = "row_kabsch_u_d_vh_v1" + + +def require_alignment_version(payload, source="motion-target cache"): + actual = payload.get("alignment_version") if isinstance(payload, dict) else None + if actual != ALIGNMENT_VERSION: + raise ValueError( + f"{source} alignment_version mismatch: expected " + f"{ALIGNMENT_VERSION!r}, got {actual!r}; regenerate the cache with " + "scripts/extract_shape_fingerprints.py" + ) + + +def kabsch_align(moving, target, mask): + """Align batched row-vector coordinates onto targets with proper rotations.""" + out_dtype = moving.dtype + if target.dim() == 2: + target = target.unsqueeze(0).expand(moving.shape[0], -1, -1) + if mask.dim() == 1: + mask = mask.unsqueeze(0).expand(moving.shape[0], -1) + + aligned = [] + with torch.autocast(device_type=moving.device.type, enabled=False): + moving_f = moving.float() + target_f = target.to(device=moving.device, dtype=torch.float32) + mask_f = mask.to(device=moving.device, dtype=torch.float32) + for sample_moving, sample_target, sample_mask in zip( + moving_f, target_f, mask_f + ): + valid = sample_mask.bool() + moving_valid = sample_moving[valid] + target_valid = sample_target[valid] + moving_mean = moving_valid.mean(dim=0, keepdim=True) + target_mean = target_valid.mean(dim=0, keepdim=True) + if int(valid.sum().item()) < 3: + aligned.append( + sample_moving - moving_mean + target_mean + ) + continue + + covariance = ( + moving_valid - moving_mean + ).transpose(0, 1) @ (target_valid - target_mean) + u, _, vh = torch.linalg.svd(covariance) + correction = torch.eye( + 3, device=moving.device, dtype=torch.float32 + ) + correction[-1, -1] = torch.where( + torch.det(u @ vh) < 0, + correction.new_tensor(-1.0), + correction.new_tensor(1.0), + ) + rotation = u @ correction @ vh + aligned.append( + (sample_moving - moving_mean) @ rotation + target_mean + ) + return torch.stack(aligned, dim=0).to(dtype=out_dtype) diff --git a/bbflow_base/bbflow/data/interpolant_bbflow.py b/bbflow_base/bbflow/data/interpolant_bbflow.py new file mode 100644 index 0000000000000000000000000000000000000000..2a50a139cbbc353abdbb8aee98626bd96c3581cd --- /dev/null +++ b/bbflow_base/bbflow/data/interpolant_bbflow.py @@ -0,0 +1,318 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import torch +import numpy as np +from scipy.spatial.transform import Rotation +import os +import contextlib +from scipy.optimize import linear_sum_assignment +from sklearn.metrics import pairwise_distances +from tqdm.auto import tqdm +import pandas as pd +import logging +from torch.utils.data.distributed import dist + +from gafl.data import so3_utils +from gafl.data import utils as du +from gafl.data import all_atom +from gafl.data.interpolant import ( + Interpolant, + _centered_gaussian, + _uniform_so3, + _trans_diffuse_mask, + _rots_diffuse_mask +) + + +class InterpolantBBFlow(Interpolant): + + def __init__(self, cfg): + self._cfg = cfg + self._rots_cfg = cfg.rots + self._trans_cfg = cfg.trans + self._sample_cfg = cfg.sampling + self._rot_distribution = self._rots_cfg.distribution + self._igso3 = None + self._log = logging.getLogger(__name__) + + super().__init__(cfg) + + def _fp32_linalg_context(self): + device_type = getattr(getattr(self, "_device", None), "type", None) + if device_type == "cuda": + return torch.autocast(device_type="cuda", enabled=False) + return contextlib.nullcontext() + + def _intra_batch_ot(self, trans_1, trans_0, t, res_mask): + B, N = trans_0.shape[:2] + + if self._cfg.batch_ot == "intra_permute": + + trans_0_ordered = torch.zeros_like(trans_0) + for b in range(B): + cost_matrix_x = pairwise_distances( + trans_1[b].numpy(force=True), + trans_0[b].numpy(force=True) + ) + + cost_matrix = cost_matrix_x #+ cost_matrix_r + _, col_ind = linear_sum_assignment(cost_matrix) + + aligned_0, _, _ = du.batch_align_structures( + trans_0[b].clone()[col_ind].unsqueeze(0), + trans_1[b].unsqueeze(0) + ) + trans_0_ordered[b] = aligned_0[0] + + return trans_0_ordered + else: + trans_0, trans_1, _ = du.batch_align_structures( + trans_0, trans_1, mask=res_mask + ) + return trans_0 + + def _corrupt_trans(self, trans_1, trans_0, t, res_mask): + + if self._cfg.batch_ot == "inter": + trans_0 = self._batch_ot(trans_0, trans_1, res_mask) + elif self._cfg.batch_ot in ["intra", "intra_permute"]: + trans_0 = self._intra_batch_ot(trans_1, trans_0, t, res_mask) + elif self._cfg.batch_ot == "none": + pass + else: + raise ValueError(f'Unknown batch ot type {self._cfg.batch_ot}') + trans_t = (1 - t[..., None]) * trans_0 + t[..., None] * trans_1 + trans_t = _trans_diffuse_mask(trans_t, trans_1, res_mask) + + return trans_t * res_mask[..., None] + + def _corrupt_rotmats(self, rotmats_1, rotmats_0, t, res_mask): + rotmats_t = so3_utils.geodesic_t(t[..., None], rotmats_1, rotmats_0) + identity = torch.eye(3, device=self._device) + rotmats_t = ( + rotmats_t * res_mask[..., None, None] + + identity[None, None] * (1 - res_mask[..., None, None]) + ) + return _rots_diffuse_mask(rotmats_t, rotmats_1, res_mask) + + def corrupt_batch(self, batch, t=None): + noisy_batch = dict(batch) + + trans_equilibrium = batch["trans_equilibrium"].float() + rotmats_equilibrium = batch["rotmats_equilibrium"].float() + B, N = trans_equilibrium.shape[:2] + with self._fp32_linalg_context(): + trans_0, rotmats_0 = self.sample_from_prior( + B, N, + trans_equilibrium, + rotmats_equilibrium, + ) + + if t is None: + # [B, 1] + t = self.sample_t(B)[:, None] + t = t.float() + + # [B, N, 3] + trans_1 = batch['trans_1'].float() # Angstrom + + # [B, N, 3, 3] + rotmats_1 = batch['rotmats_1'].float() + + # [B, N] + res_mask = batch['res_mask'].float() + + # Apply corruptions + trans_t = self._corrupt_trans(trans_1, trans_0, t, res_mask) + rotmats_t = self._corrupt_rotmats(rotmats_1, rotmats_0, t, res_mask) + + noisy_batch['t'] = t + noisy_batch['trans_t'] = trans_t + noisy_batch['rotmats_t'] = rotmats_t + return noisy_batch + + def _pure_noise_prior(self, num_batch, num_res, rotmats_1): + trans_nm_0 = _centered_gaussian(num_batch, num_res, self._device) + trans_0 = trans_nm_0 * du.NM_TO_ANG_SCALE + trans_0 *= self.noise_scale + + # make the noise blob larger the longer the protein is: + if self.noise_res_scaling_power > 0: + trans_0 *= (trans_0.shape[1] / 128.)**self.noise_res_scaling_power + + if self._rot_distribution == 'uniform': + rotmats_0 = _uniform_so3(num_batch, num_res, self._device) + elif self._rot_distribution == 'igso3': + noisy_rotmats = self.igso3.sample( + torch.tensor([1.5]), + num_batch*num_res + ).to(self._device) + noisy_rotmats = noisy_rotmats.reshape(num_batch, num_res, 3, 3) + rotmats_0 = torch.einsum("...ij,...jk->...ik", rotmats_1, noisy_rotmats) + else: + raise ValueError(f'Unknown SO(3) distribution {self._rot_distribution}') + + return trans_0, rotmats_0 + + def _conditional_prior(self, num_batch, num_res, trans_equilibrium, rotmats_equilibrium): + res_mask = torch.ones(num_batch, num_res, device=self._device) + trans_equilibrium = trans_equilibrium.float() + rotmats_equilibrium = rotmats_equilibrium.float() + trans_0, rotmats_0 = self._pure_noise_prior(num_batch, num_res, rotmats_equilibrium) + + trans_0 = self._corrupt_trans( + trans_equilibrium, + trans_0, + self._cfg.prior_conditional.gamma_trans * torch.ones(num_batch, 1, device=self._device, dtype=torch.float32), + res_mask + ) + rotmats_0 = self._corrupt_rotmats( + rotmats_equilibrium, + rotmats_0, + self._cfg.prior_conditional.gamma_rots * torch.ones(num_batch, 1, device=self._device, dtype=torch.float32), + res_mask + ) + + return trans_0, rotmats_0 + + def sample_from_prior( + self, + num_batch, + num_res, + trans_equilibrium, + rotmats_equilibrium, + ): + + prior_type = self._cfg.prior + + if prior_type == 'conditional': + with self._fp32_linalg_context(): + return self._conditional_prior( + num_batch, num_res, trans_equilibrium, rotmats_equilibrium + ) + elif prior_type == 'pure_noise': + return self._pure_noise_prior(num_batch, num_res, rotmats_equilibrium) + + else: + raise ValueError(f'Unknown prior type {prior_type}') + + + def sample( + self, + num_batch, + num_res, + model, + trans_equilibrium, + rotmats_equilibrium, + seq, + z=None, + return_trajectory=True, + cache_static_features=True, + ): + + res_mask = torch.ones(num_batch, num_res, device=self._device) + + # Set-up initial prior samples + trans_0, rotmats_0 = self.sample_from_prior( + num_batch, num_res, trans_equilibrium, rotmats_equilibrium + ) + batch = { + "res_mask": res_mask, + "trans_equilibrium": trans_equilibrium, + "rotmats_equilibrium": rotmats_equilibrium, + "seq": seq, + } + if z is not None: + batch["z"] = z + if cache_static_features and hasattr(model, "prepare_inference_static"): + batch["_embedder_static"] = model.prepare_inference_static(batch) + + # Set-up time + ts = torch.linspace( + self._cfg.min_t, 1.0, self._sample_cfg.num_timesteps) + t_1 = ts[0] + + prot_traj = [(trans_0, rotmats_0)] if return_trajectory else None + clean_traj = [] + trans_current, rotmats_current = trans_0, rotmats_0 + if self._cfg.use_tqdm: + # Only a progress-bar label, but dist.get_rank() raises outright when no + # process group exists -- which is the case for single-device inference, + # where Lightning never initialises one. Sampling has no other reason to + # need distributed state, so fall back to 0 rather than making a one-GPU + # run impossible. + rank = dist.get_rank() if dist.is_available() and dist.is_initialized() else 0 + iterator = tqdm( + ts[1:], + leave=False, + desc=f'Sampl. {num_batch} states, len {num_res}, rank {rank} - timesteps' + ) + + else: + iterator = ts[1:] + for t_2 in iterator: + + # Run model. + trans_t_1, rotmats_t_1 = trans_current, rotmats_current + t = torch.ones((num_batch, 1), device=self._device) * t_1 + batch['trans_t'] = trans_t_1 + batch['rotmats_t'] = rotmats_t_1 + batch['t'] = t + with torch.no_grad(): + model_out = model(batch) + # Process model output. + pred_trans_1 = model_out['pred_trans'] + pred_rotmats_1 = model_out['pred_rotmats'] + if return_trajectory: + clean_traj.append( + (pred_trans_1.detach().cpu(), pred_rotmats_1.detach().cpu()) + ) + if self._cfg.self_condition: + batch['trans_sc'] = pred_trans_1 + + d_t = t_2 - t_1 + # Take reverse step + trans_t_2 = self._trans_euler_step( + d_t, t_1, pred_trans_1, trans_t_1) + rotmats_t_2 = self._rots_euler_step( + d_t, t_1, pred_rotmats_1, rotmats_t_1) + + trans_current, rotmats_current = trans_t_2, rotmats_t_2 + if return_trajectory: + prot_traj.append((trans_t_2, rotmats_t_2)) + t_1 = t_2 + + + + t_1 = ts[-1] + trans_t_1, rotmats_t_1 = trans_current, rotmats_current + t = torch.ones((num_batch, 1), device=self._device) * t_1 + batch['trans_t'] = trans_t_1 + batch['rotmats_t'] = rotmats_t_1 + batch['t'] = t + + with torch.no_grad(): + model_out = model(batch) + # Process model output. + pred_trans_1 = model_out['pred_trans'] + pred_rotmats_1 = model_out['pred_rotmats'] + if return_trajectory: + clean_traj.append( + (pred_trans_1.detach().cpu(), pred_rotmats_1.detach().cpu()) + ) + prot_traj.append((pred_trans_1, pred_rotmats_1)) + else: + # Keep the historical return structure, but materialize only the + # final state that inference actually writes. + prot_traj = [(pred_trans_1, pred_rotmats_1)] + clean_traj = [(pred_trans_1, pred_rotmats_1)] + + # Convert trajectories to atom37. + atom37_traj = all_atom.transrot_to_atom37(prot_traj, res_mask) + clean_atom37_traj = all_atom.transrot_to_atom37(clean_traj, res_mask) + + return atom37_traj, clean_atom37_traj, clean_traj + diff --git a/bbflow_base/bbflow/data/pdb_dataloader_bbflow.py b/bbflow_base/bbflow/data/pdb_dataloader_bbflow.py new file mode 100644 index 0000000000000000000000000000000000000000..88069aa9f26b9b0518b8d0ab1772a55a830d52fd --- /dev/null +++ b/bbflow_base/bbflow/data/pdb_dataloader_bbflow.py @@ -0,0 +1,590 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""PDB data loader.""" +import math +import torch +import tree +import numpy as np +import torch +import pandas as pd +import logging +import json +import os +import shutil +from pytorch_lightning import LightningDataModule +from torch.utils.data import DataLoader, Dataset +from torch.utils.data.distributed import dist +import mdtraj + +from gafl.data.residue_constants import restype_order, restype_3to1, restypes + +from bbflow.data.utils import frames_from_pdb, backbone_to_frames, get_alphaflow_valid_rmsf + +class PdbDataModuleBBFlow(LightningDataModule): + def __init__(self, data_cfg, training_cfg=None, latent_cfg=None): + super().__init__() + self._log = logging.getLogger(__name__) + self.data_cfg = data_cfg + + self.loader_cfg = data_cfg.loader + self.dataset_cfg = data_cfg.dataset + self.conditional_val_cfg = data_cfg.validation + self.sampler_cfg = data_cfg.sampler + grouped_baseline = bool(getattr(training_cfg, "force_grouped_batch", False)) if training_cfg is not None else False + self.ensemble_group_size = ( + int(getattr(training_cfg, "ensemble_group_size", 0)) + if grouped_baseline + else 0 + ) + self.collective_enabled = bool( + latent_cfg is not None and getattr(latent_cfg, "collective_enable", False) + ) + self.collective_rank = int( + getattr(latent_cfg, "collective_rank", 0) + ) if self.collective_enabled else 0 + if self.collective_enabled and self.ensemble_group_size <= self.collective_rank: + raise ValueError( + f"CMFM ensemble_group_size must exceed collective_rank=" + f"{self.collective_rank}, got {self.ensemble_group_size}" + ) + + self.train_csv = pd.read_csv(self.dataset_cfg.train_csv_path) + self.train_csv = self.train_csv[self.train_csv.modeled_seq_len <= self.dataset_cfg.max_num_res] + self.train_csv = self.train_csv[self.train_csv.modeled_seq_len >= self.dataset_cfg.min_num_res] + self.train_csv = self.train_csv.sort_values('modeled_seq_len', ascending=True).reset_index(drop=True) + + self.valid_csvs = [] + for i, valid_csv_path in enumerate(self.dataset_cfg.valid_csv_paths): + valid_csv = pd.read_csv(valid_csv_path) + # valid_csv = valid_csv[valid_csv.modeled_seq_len <= self.dataset_cfg.max_num_res] + # valid_csv = valid_csv[valid_csv.modeled_seq_len >= self.dataset_cfg.min_num_res] + # valid_csv = valid_csv.sort_values('modeled_seq_len', ascending=False).reset_index(drop=True) + valid_csv.insert(0, 'dataset_name', self.dataset_cfg.valid_dataset_names[i]) + self.valid_csvs.append(valid_csv) + + + self.test_csv = pd.read_csv(self.dataset_cfg.test_csv_path) + # self.test_csv = self.test_csv[self.test_csv.modeled_seq_len <= self.dataset_cfg.max_num_res] + # self.test_csv = self.test_csv[self.test_csv.modeled_seq_len >= self.dataset_cfg.min_num_res] + # self.test_csv = self.test_csv.sort_values('modeled_seq_len', ascending=True).reset_index(drop=True) + + if self.dataset_cfg.subset is not None: + self.train_csv = self.train_csv.iloc[:self.dataset_cfg.subset] + for i, valid_csv in enumerate(self.valid_csvs): + self.valid_csvs[i] = valid_csv.iloc[:self.dataset_cfg.subset] + + self.train_csv.to_csv(os.path.join(self.dataset_cfg.split_path, 'train.csv'), index=False) + self.test_csv.to_csv(os.path.join(self.dataset_cfg.split_path, 'test.csv'), index=False) + pd.concat(self.valid_csvs).to_csv(os.path.join(self.dataset_cfg.split_path, 'valid.csv'), index=False) + + + if self.conditional_val_cfg.alphaflow_valid_rmsf_path is not None: + # if the path is not None, rmsf for alphaflow's validation set ensembles are precomputed + # This is used in the validation step to plot the rmsf-profiles together with MD rmsf and + # bbflow's rmsf using wandb. + af_rmsf = {} + for i in range(len(self.valid_csvs)): + valid_csv = self.valid_csvs[i] + xtc_path = self.conditional_val_cfg.valid_xtc_paths[i] + af_pdb_path = self.conditional_val_cfg.alphaflow_valid_pdb_paths[i] + af_rmsf_i = get_alphaflow_valid_rmsf( + af_pdb_path, + os.path.basename(self.conditional_val_cfg.alphaflow_valid_rmsf_path), + xtc_path, + valid_csv + ) + af_rmsf.update(af_rmsf_i) + + af_valid_rmsf_path = os.path.abspath(self.conditional_val_cfg.alphaflow_valid_rmsf_path) + with open(af_valid_rmsf_path, "w") as f: + json.dump(af_rmsf, f) + + + + + def setup(self, stage: str): + self._log.info(f'Training: {len(self.train_csv)} examples') + self._train_dataset = PDBDatasetBBFlow( + csv=self.train_csv, + ) + self._log.info(f"Validation: {sum([len(valid_csv) for valid_csv in self.valid_csvs])} examples") + self._valid_datasets = [ + PDBDatasetBBFlowFromPdb(valid_csv, sort=True) + for valid_csv in self.valid_csvs + ] + + def train_dataloader(self, rank=None, num_replicas=None): + num_workers = self.loader_cfg.num_workers + pin_memory = bool(getattr(self.loader_cfg, "pin_memory", False)) + batch_sampler = LengthBatcherBBFlow( + sampler_cfg=self.sampler_cfg, + metadata_csv=self._train_dataset.csv, + ensemble_group_size=self.ensemble_group_size, + strict_ensemble_group_size=self.collective_enabled, + rank=rank, + num_replicas=num_replicas, + ) + return DataLoader( + self._train_dataset, + batch_sampler=batch_sampler, + num_workers=num_workers, + prefetch_factor=None if num_workers == 0 else self.loader_cfg.prefetch_factor, + pin_memory=pin_memory, + persistent_workers=True if num_workers > 0 else False, + ) + + def val_dataloader(self): + valid_dataloader = [ + DataLoader( + valid_dataset, + shuffle=False, + num_workers=2, + prefetch_factor=2, + persistent_workers=True, + ) + for valid_dataset in self._valid_datasets + ] + + return valid_dataloader + + +class PDBDatasetBBFlow(Dataset): + def __init__(self, csv): + self._log = logging.getLogger(__name__) + self.csv = csv + + self._log.info(f'Training: {len(self.csv)} examples') + + self._init_data() + + def _init_data(self): + """Prepare metadata and lazy cache for equilibrium structures.""" + num_proteins = len(self.csv) + self.num_proteins = num_proteins + if len(self.csv) > 0 and "modeled_seq_len" in self.csv.columns: + self.max_protein_length = int(self.csv["modeled_seq_len"].max()) + else: + self.max_protein_length = 0 + + self.trans_equilibrium = [None] * num_proteins + self.rotmats_equilibrium = [None] * num_proteins + self.seq_1letter = [None] * num_proteins + self.seq_onehot = [None] * num_proteins + self.chain_ids = [None] * num_proteins + if "modeled_seq_len" in self.csv.columns: + self.protein_length = self.csv["modeled_seq_len"].astype(int).tolist() + else: + self.protein_length = [None] * num_proteins + if "name" in self.csv.columns: + self.pdb_names = self.csv["name"].tolist() + else: + self.pdb_names = [None] * num_proteins + self._equilibrium_cache = {} + + def _get_eq_structure_atlas(self, pdb_idx): + cached = self._equilibrium_cache.get(pdb_idx) + if cached is not None: + return cached + + row = self.csv.iloc[pdb_idx] + name = row["name"] + protein_folder = row["folder"] + + trans, rotmats, seq_onehot, chain_ids = frames_from_pdb( + os.path.join(protein_folder, f"{name}.pdb") + ) + seq_indices = seq_onehot.argmax(1).tolist() + seq_1letter = np.array([restypes[i] for i in seq_indices]) + protein_len = len(seq_indices) + + data = { + "trans": trans, + "rotmats": rotmats, + "seq_letters": seq_1letter, + "seq_onehot": seq_onehot, + "length": protein_len, + "chain_ids": chain_ids, + } + + self.trans_equilibrium[pdb_idx] = trans + self.rotmats_equilibrium[pdb_idx] = rotmats + self.seq_1letter[pdb_idx] = seq_1letter + self.seq_onehot[pdb_idx] = seq_onehot + self.chain_ids[pdb_idx] = chain_ids + self.protein_length[pdb_idx] = protein_len + self._equilibrium_cache[pdb_idx] = data + + return data + + def __len__(self): + return len(self.csv) + + def __getitem__(self, idx): + # Sample data example. + if isinstance(idx, int): + pdb_idx = idx + trajectory_index = 0 + conformation_idx = 0 + group_index = None + else: + if len(idx) == 4: + pdb_idx, trajectory_index, conformation_idx, group_index = idx + else: + pdb_idx, trajectory_index, conformation_idx = idx + group_index = None + + # mdtraj.load_frame(path, i, top=f"{path[:-7]}.pdb") + folder = self.csv.iloc[pdb_idx]["folder"] + name = self.csv.iloc[pdb_idx]["name"] + traj_path = os.path.join(folder, f"{name}_R{trajectory_index+1}.xtc") + eq_path = os.path.join(folder, f"{name}.pdb") + + conformation = mdtraj.load_frame(traj_path, conformation_idx, top=eq_path) + N_atoms = conformation.xyz[0, conformation.top.select('name N'), :] * 10 + CA_atoms = conformation.xyz[0, conformation.top.select('name CA'), :] * 10 + C_atoms = conformation.xyz[0, conformation.top.select('name C'), :] * 10 + + eq_data = self._get_eq_structure_atlas(pdb_idx) + data = backbone_to_frames(N_atoms, CA_atoms, C_atoms, eq_data["seq_letters"]) + + N = eq_data["length"] + in_feats = { + "res_mask": torch.ones(N), + "trans_equilibrium": eq_data["trans"], + "rotmats_equilibrium": eq_data["rotmats"], + "trans_1": data["trans"], + "rotmats_1": data["rotmats"], + "seq": eq_data["seq_onehot"], + "pdb_name": self.pdb_names[pdb_idx], + "conformation_idx": conformation_idx, + "trajectory_idx": trajectory_index, + } + if group_index is not None: + in_feats["group_index"] = int(group_index) + + return in_feats + + + +class PDBDatasetBBFlowFromPdb(Dataset): + """ + Used for inference where a csv file with pdb paths + is given and for the validation set during training. + """ + def __init__(self, csv, sort=False, min_length=0, max_length=np.inf): + self.csv = csv + + self.trans = [] + self.rotmats = [] + self.pdb_names = [] + self.seqs = [] + self._preprocess_pdb(sort, min_length, max_length) + + def _preprocess_pdb(self, sort, min_length, max_length): + lengths = [] + for i, row in self.csv.iterrows(): + pdb_path = row['pdb_path'] + pdb_name = row['name'] if 'name' in row else row['pdb_name'] + + trans, rotmats, seq_onehot, _ = frames_from_pdb(pdb_path) + + lengths.append(len(seq_onehot)) + if len(seq_onehot) < min_length or len(seq_onehot) > max_length: + continue + + self.trans.append(trans) + self.rotmats.append(rotmats) + self.pdb_names.append(pdb_name) + self.seqs.append(seq_onehot) + + self.csv.insert(len(self.csv.columns), 'modeled_seq_len', lengths) + self.csv = self.csv[self.csv['modeled_seq_len'] >= min_length] + self.csv = self.csv[self.csv['modeled_seq_len'] <= max_length] + self.csv = self.csv.reset_index(drop=True) + + lengths = [len(seq) for seq in self.seqs] + if sort: + if sort == "descending" or sort == "reverse": + indices = np.argsort(lengths)[::-1] + else: + indices = np.argsort(lengths) + self.trans = [self.trans[i] for i in indices] + self.rotmats = [self.rotmats[i] for i in indices] + self.pdb_names = [self.pdb_names[i] for i in indices] + self.seqs = [self.seqs[i] for i in indices] + self.csv = self.csv.iloc[indices] + lengths = [lengths[i] for i in indices] + + self.csv = self.csv.reset_index(drop=True) + + + def __len__(self): + return len(self.csv) + + def __getitem__(self, idx): + return { + "pdb_name": self.pdb_names[idx], + "seq": self.seqs[idx], + "trans_equilibrium": self.trans[idx], + "rotmats_equilibrium": self.rotmats[idx], + } + + + +class LengthBatcherBBFlow: + + def __init__( + self, + *, + sampler_cfg, + metadata_csv, + seed=123, + shuffle=True, + ensemble_group_size=0, + strict_ensemble_group_size=False, + num_replicas=None, + rank=None, + ): + super().__init__() + self._log = logging.getLogger(__name__) + if num_replicas is None: + self.num_replicas = dist.get_world_size() if dist.is_available() and dist.is_initialized() else 1 + else: + self.num_replicas = num_replicas + if rank is None: + self.rank = dist.get_rank() if dist.is_available() and dist.is_initialized() else 0 + else: + self.rank = rank + + self._sampler_cfg = sampler_cfg + self._data_csv = metadata_csv + # Each replica needs the same number of batches. We set the number + # of batches to arbitrarily be the number of examples per replica. + self.max_conformations = self._sampler_cfg.max_conformations + num_total = 0 + for i in range(len(self._data_csv)): + num_total += min( + self._data_csv.iloc[i]['num_conformations'], + self.max_conformations + ) + # self._num_batches = math.ceil(num_total / self.num_replicas) + self._data_csv['index'] = list(range(len(self._data_csv))) + self.seed = seed + self.shuffle = shuffle + self.epoch = 0 + self.ensemble_group_size = int(ensemble_group_size or 0) + self.strict_ensemble_group_size = bool(strict_ensemble_group_size) + self.max_batch_size = self._sampler_cfg.max_batch_size + self.max_num_res_squared = self._sampler_cfg.max_num_res_squared + self._log.info(f'Created dataloader rank {self.rank} out of {self.num_replicas}') + self.sample_order = None + lengths = [] + for r in range(self.num_replicas): + lengths.append(len(self._replica_epoch_batches(r))) + self._log.info(f"Rank {r} has {lengths[-1]} batches") + self._num_batches = max(lengths) + self._log.info(f"Using {self._num_batches} batches per rank") + + def _frame_rng(self, rank, draw=0): + """Deterministic MD-frame RNG, keyed on (seed, epoch, rank, draw). + + The frame draw used to come from the global ``np.random`` state while + only the protein permutation was seeded, so which 8 conformations formed + a CMFM group was irreproducible across runs. That makes every + lambda/normalizer comparison a sampling lottery. Keying on rank as well + keeps the replicas drawing different frames; keying on epoch keeps them + different across epochs. A dedicated Generator is required rather than + seeding the global state because ``__init__`` pre-scans every rank to + count batches, which would otherwise consume the global stream before + epoch 0 even starts. + + ``draw`` distinguishes the augmentation rounds of ``_create_batches``, + which calls back into the epoch builder until it has ``_num_batches``. + Without it every round would replay the same frames instead of drawing + fresh ones, silently shrinking the conformations seen per epoch. + """ + return np.random.default_rng( + [int(self.seed), int(self.epoch), int(rank), int(draw)] + ) + + def _get_indices(self, max_conformations, num_conformations, index, rng): + # Number of trajectories per protein hardcoded to 3 for now (as in ATLAS) + traj_indices = np.sort(rng.choice(3, max_conformations, replace=True)) + traj_indices = torch.tensor(traj_indices) + conf_indices = [] + for i in range(3): + conf_indices.append(rng.choice(num_conformations, (traj_indices==i).sum().item(), replace=False)) + conf_indices = torch.tensor(np.concatenate(conf_indices)) + + protein_index = torch.ones(max_conformations, dtype=torch.long) * index + return torch.stack([ + protein_index, # index of protein + traj_indices, # index of trajectory + conf_indices, # index of conformation in trajectory + ], dim=1) + + def _get_group_indices(self, group_size, num_conformations, index, group_index, rng): + traj_indices = np.sort(rng.choice(3, group_size, replace=True)) + traj_indices = torch.tensor(traj_indices) + conf_indices = [] + for i in range(3): + n_for_traj = (traj_indices == i).sum().item() + if n_for_traj == 0: + continue + replace = n_for_traj > num_conformations + conf_indices.append(rng.choice(num_conformations, n_for_traj, replace=replace)) + conf_indices = torch.tensor(np.concatenate(conf_indices)) + protein_index = torch.ones(group_size, dtype=torch.long) * index + group_index = torch.ones(group_size, dtype=torch.long) * group_index + return torch.stack([ + protein_index, + traj_indices, + conf_indices, + group_index, + ], dim=1) + + def _replica_epoch_batches_grouped(self, rank=0, draw=0): + rng = torch.Generator() + rng.manual_seed(self.seed + self.epoch) + frame_rng = self._frame_rng(rank, draw) + if self.shuffle: + indices = torch.randperm(len(self._data_csv), generator=rng).tolist() + else: + indices = list(range(len(self._data_csv))) + + if len(self._data_csv) > self.num_replicas: + replica_csv = self._data_csv.iloc[ + indices[rank::self.num_replicas] + ] + else: + replica_csv = self._data_csv + + sample_order = [] + next_group_index = 0 + group_size = self.ensemble_group_size + for seq_len, len_df in replica_csv.groupby('modeled_seq_len'): + max_batch_size = min( + self.max_batch_size, + self.max_num_res_squared // seq_len**2 + 1, + ) + if self.strict_ensemble_group_size and max_batch_size < group_size: + raise ValueError( + f"CMFM group_size={group_size} does not fit length={seq_len}: " + f"maximum batch size is {max_batch_size}. Increase " + "data.sampler.max_num_res_squared or lower the explicit group size." + ) + effective_group_size = max(1, min(group_size, max_batch_size)) + max_groups_per_batch = max(1, max_batch_size // effective_group_size) + group_blocks = [] + for _, row in len_df.iterrows(): + max_conformations = min( + self.max_conformations, + row['num_conformations'] + ) + num_groups = max(1, max_conformations // effective_group_size) + for _ in range(num_groups): + group_blocks.append(self._get_group_indices( + effective_group_size, + row['num_conformations'], + row['index'], + next_group_index, + frame_rng, + )) + next_group_index += 1 + + if len(group_blocks) == 0: + continue + perm = torch.randperm(len(group_blocks), generator=rng).tolist() + group_blocks = [group_blocks[i] for i in perm] + num_batches = math.ceil(len(group_blocks) / max_groups_per_batch) + for i in range(num_batches): + batch_groups = group_blocks[i*max_groups_per_batch:(i+1)*max_groups_per_batch] + sample_order.append(torch.cat(batch_groups, dim=0).numpy()) + + new_order = torch.randperm(len(sample_order), generator=rng).numpy().tolist() + return [sample_order[i] for i in new_order] + + def _replica_epoch_batches(self, rank=0, draw=0): + if self.ensemble_group_size > 1: + return self._replica_epoch_batches_grouped(rank, draw) + # Make sure all replicas share the same seed on each epoch. + rng = torch.Generator() + rng.manual_seed(self.seed + self.epoch) + frame_rng = self._frame_rng(rank, draw) + if self.shuffle: + indices = torch.randperm(len(self._data_csv), generator=rng).tolist() + else: + indices = list(range(len(self._data_csv))) + + if len(self._data_csv) > self.num_replicas: + replica_csv = self._data_csv.iloc[ + indices[rank::self.num_replicas] + ] + else: + replica_csv = self._data_csv + + # Each batch contains multiple proteins of the same length. + sample_order = [] + for seq_len, len_df in replica_csv.groupby('modeled_seq_len'): + max_batch_size = min( + self.max_batch_size, + self.max_num_res_squared // seq_len**2 + 1, + ) + + protein_indices = [] + for i, row in len_df.iterrows(): + max_conformations = min( + self.max_conformations, + row['num_conformations'] + ) + + indices = self._get_indices( + max_conformations, row['num_conformations'], row['index'], frame_rng + ) + + protein_indices.append(indices) + + + protein_indices = torch.cat(protein_indices, dim=0) + perm = torch.randperm(len(protein_indices), generator=rng) + protein_indices = protein_indices[perm].numpy() + + num_batches = math.ceil(len(protein_indices) / max_batch_size) + for i in range(num_batches): + batch_indices = protein_indices[i*max_batch_size:(i+1)*max_batch_size] + sample_order.append(batch_indices) + + # Remove any length bias. + new_order = torch.randperm(len(sample_order), generator=rng).numpy().tolist() + return [sample_order[i] for i in new_order] + + + def _create_batches(self): + # Make sure all replicas have the same number of batches Otherwise leads to bugs. + # See bugs with shuffling https://github.com/Lightning-AI/lightning/issues/10947 + all_batches = [] + num_augments = -1 + while len(all_batches) < self._num_batches: + all_batches.extend( + self._replica_epoch_batches(self.rank, draw=num_augments + 1) + ) + num_augments += 1 + if num_augments > 1000: + raise ValueError('Exceeded number of augmentations.') + if len(all_batches) >= self._num_batches: + all_batches = all_batches[:self._num_batches] + self.sample_order = all_batches + self._log.info(f"Create batches: Rank {self.rank} has {len(all_batches)} batches.") + return all_batches + + def __iter__(self): + self._create_batches() + self.epoch += 1 + return iter(self.sample_order) + + def __len__(self): + return self._num_batches + # return len(self.sample_order) diff --git a/bbflow_base/bbflow/data/utils.py b/bbflow_base/bbflow/data/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a92aa29092232024bf0c3e50b3d0e9e03174dae0 --- /dev/null +++ b/bbflow_base/bbflow/data/utils.py @@ -0,0 +1,115 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Licensed under the MIT license. + +from pathlib import Path +from typing import List, Tuple, Dict, Any +import torch +import numpy as np +import mdtraj +import os +from tqdm.auto import tqdm + +from openfold.data.data_transforms import atom37_to_frames +from openfold.utils.rigid_utils import Rigid + +from gafl.data.residue_constants import restype_order + +# from bbflow.analysis.analyse_bbflow import calc_aligned_rmsf +from bbflow.analysis.analyse_bbflow import _calc_rmsf, _align_tops +import json + +def backbone_to_frames(N_atoms, CA_atoms, C_atoms, resnames): + seq_numerical = torch.tensor([restype_order[aa] for aa in resnames]) + seq_onehot = torch.nn.functional.one_hot(seq_numerical, 21).float() + + N = len(N_atoms) + X = torch.zeros(N, 37, 3) + X[:, 0] = torch.tensor(N_atoms) + X[:, 1] = torch.tensor(CA_atoms) + X[:, 2] = torch.tensor(C_atoms) + X -= torch.mean(torch.tensor(CA_atoms), dim=0) + aatypes = torch.tensor([restype_order[aa] for aa in resnames]).long() + atom_mask = torch.zeros((N, 37)).double() + atom_mask[:, :3] = 1 + protein = { + "aatype": aatypes, + "all_atom_positions": X, + "all_atom_mask": atom_mask, + } + frames = atom37_to_frames(protein) + rigids_0 = Rigid.from_tensor_4x4(frames['rigidgroups_gt_frames'])[:,0] + trans = rigids_0.get_trans() + rotmats = rigids_0.get_rots().get_rot_mats() + + return { + "trans": trans, + "rotmats": rotmats, + "seq_onehot": seq_onehot, + } + +def frames_from_pdb(pdb_path:Path)->Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Extracts frames from a PDB file. + + Args: + pdb_path: Path to the PDB file. + + Returns: + Tuple of trans, rotmats, seq_onehot. + """ + + eq = mdtraj.load(pdb_path) + + N_atoms = eq.xyz[0, eq.top.select('name N'), :] * 10 + CA_atoms = eq.xyz[0, eq.top.select('name CA'), :] * 10 + C_atoms = eq.xyz[0, eq.top.select('name C'), :] * 10 + seq = np.array(list("".join(eq.top.to_fasta()))) + + chain_ids = np.array([res.chain.index for res in eq.top.residues]) + + data = backbone_to_frames(N_atoms, CA_atoms, C_atoms, seq) + return data["trans"], data["rotmats"], data["seq_onehot"], chain_ids + + + + +def get_alphaflow_valid_rmsf(pdb_path, rmsf_file_name, xtc_path, valid_csv): + # Precompute RMSF for validation proteins for AlphaFlow + # Used for plotting rmsf-profiles in validation + af_valid_pdb_folder = os.path.abspath(pdb_path) + af_valid_rmsf_precomputed_path = os.path.abspath(os.path.join( + pdb_path, rmsf_file_name + )) + if os.path.exists(af_valid_rmsf_precomputed_path): + with open(af_valid_rmsf_precomputed_path, "r") as f: + rmsfs = json.load(f) + else: + rmsfs = {} + for i, row in tqdm(valid_csv.iterrows(), total=len(valid_csv), desc="calculate rmsf for alphaflow valid"): + pdb_name = row['pdb_name'] + af_pdb_name = f"{pdb_name[:4]}_{pdb_name[4]}" + if not os.path.exists(os.path.join(af_valid_pdb_folder, f"{af_pdb_name}.pdb")): + af_pdb_name = pdb_name + ref = mdtraj.load(os.path.join(xtc_path, f"{pdb_name}/{pdb_name}.pdb")) + af_traj = mdtraj.load(os.path.join(af_valid_pdb_folder, f"{af_pdb_name}.pdb")) + ref.atom_slice([a.index for a in ref.top.atoms if a.element.symbol != 'H'], True) + af_traj.atom_slice([a.index for a in af_traj.top.atoms if a.element.symbol != 'H'], True) + af_traj.atom_slice([a.index for a in af_traj.top.atoms if a.name in ['CA', 'C', 'N', 'O', 'OXT']], True) + refmask, afmask = _align_tops(ref.top, af_traj.top, True) + ref.atom_slice(refmask, True) + af_traj.atom_slice(afmask, True) + ca_mask = [a.index for a in ref.top.atoms if a.name == 'CA'] + ca_mask_model = [a.index for a in af_traj.top.atoms if a.name == 'CA'] + ref = ref.atom_slice(ca_mask, False) + af_traj = af_traj.atom_slice(ca_mask_model, False) + af_traj.superpose(ref) + rmsf = _calc_rmsf(af_traj, ref, bootstrap=True) + rmsfs[pdb_name] = { + "rmsf": rmsf["rmsf"].tolist(), + "low": rmsf["rmsf_low"].tolist(), + "high": rmsf["rmsf_high"].tolist(), + } + with open(af_valid_rmsf_precomputed_path, "w") as f: + json.dump(rmsfs, f) + + return rmsfs \ No newline at end of file diff --git a/bbflow_base/bbflow/deployment/__pycache__/bbflow.cpython-39.pyc b/bbflow_base/bbflow/deployment/__pycache__/bbflow.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49b929b344b4dc2ac9f09be8f200545b888ae4ed Binary files /dev/null and b/bbflow_base/bbflow/deployment/__pycache__/bbflow.cpython-39.pyc differ diff --git a/bbflow_base/bbflow/deployment/__pycache__/utils.cpython-39.pyc b/bbflow_base/bbflow/deployment/__pycache__/utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23789faa3f2353add149e8aea8b07208a219e0ed Binary files /dev/null and b/bbflow_base/bbflow/deployment/__pycache__/utils.cpython-39.pyc differ diff --git a/bbflow_base/bbflow/deployment/bbflow.py b/bbflow_base/bbflow/deployment/bbflow.py new file mode 100644 index 0000000000000000000000000000000000000000..360a720ada3948cffbeae3055e5147770054c33a --- /dev/null +++ b/bbflow_base/bbflow/deployment/bbflow.py @@ -0,0 +1,311 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Licensed under the MIT license. + +import os +import time +import numpy as np +import hydra +import torch +from torch.utils.data import DataLoader +import GPUtil +import subprocess +from typing import Optional +from pathlib import Path +import pandas as pd +from pytorch_lightning import Trainer +import warnings +import logging +from typing import Union +from pathlib import Path +from tqdm.auto import tqdm + +from omegaconf import DictConfig, OmegaConf +from omegaconf.base import ContainerMetadata +# depending on the torch version (higher than 2.6), we need to add the DictConfig and ContainerMetadata to the safe globals: +if hasattr(torch.serialization, 'add_safe_globals'): + torch.serialization.add_safe_globals([DictConfig, ContainerMetadata]) # needed for loading the checkpoint with weights_only=True + +from gafl import experiment_utils as eu +from gafl.data import utils as du +from bbflow.analysis import utils as au +from bbflow.deployment.utils import estimate_max_batchsize, recursive_update, ckpt_path_from_tag + +from bbflow.models.bbflow_module import BBFlowModule +from bbflow.data.utils import frames_from_pdb + + + +log = eu.get_pylogger(__name__) +torch.set_float32_matmul_precision('high') + +class BBFlow: + + def __init__(self, ckpt_path: Union[Path,str], cfg:dict={}, timesteps:int=20, gamma_trans:float=None, gamma_rots:float=None, progress_bar:bool=True, _pbar_kwargs={}, device:str='cuda'): + """ + Arguments: + ckpt_path: Path or str. Path to checkpoint file. Must contain a 'config.yaml' file in the same directory. + cfg: dict. default:{}. Configuration dictionary. Will overwrite the configuration from the checkpoint for the entries given. + timesteps: int or None. default:20. Number of timesteps to sample. Overwrites the configuration from the checkpoint or in cfg. + gamma_trans: float or None. default:None. Conditional prior parameter controlling how close the prior is to the equilibrium structure. Overwrites the configuration from the checkpoint or in cfg. + gamma_rots: float or None. default:None. Conditional prior parameter controlling how close the prior is to the equilibrium structure. Overwrites the configuration from the checkpoint or in cfg. + progress_bar: bool. default:True. Whether to show a progress bar during sampling. + _pbar_kwargs: dict. default:{} Additional arguments to pass to the progress bar. + device: str. default:'cuda'. Device to use. + """ + + self.device = device + + ckpt_dir = os.path.dirname(ckpt_path) + config_path = os.path.join(ckpt_dir, 'config.yaml') + if not os.path.exists(ckpt_path): + raise FileNotFoundError(f"Checkpoint file {ckpt_path} does not exist.") + if not os.path.exists(config_path): + raise FileNotFoundError(f"Config file {os.path.join(ckpt_dir, 'config.yaml')} does not exist.") + + ckpt_cfg = OmegaConf.load(config_path) + + self._pbar_kwargs = _pbar_kwargs + + + # Set-up config. + if timesteps is not None: + assert isinstance(timesteps, int), "timesteps must be an integer." + if not 'inference' in cfg: + cfg['inference'] = {} + if not 'interpolant' in cfg['inference']: + cfg['inference']['interpolant'] = {} + if not 'sampling' in cfg['inference']['interpolant']: + cfg['inference']['interpolant']['sampling'] = {} + cfg['inference']['interpolant']['sampling']['num_timesteps'] = timesteps + + default_inference_config = Path(__file__).parent.parent.parent / 'configs/inference.yaml' + cfg_ = OmegaConf.load(default_inference_config) + OmegaConf.set_struct(cfg_, True) + + recursive_update(cfg, cfg_) + + OmegaConf.set_struct(cfg_, False) + + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(cfg_, ckpt_cfg) + cfg.experiment.checkpointer.dirpath = './' + + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + + if gamma_rots is None: + gamma_rots = ckpt_cfg.interpolant.prior_conditional.gamma_rots + if gamma_trans is None: + gamma_trans = ckpt_cfg.interpolant.prior_conditional.gamma_trans + + cfg.inference.interpolant.prior_conditional.gamma_rots = gamma_rots + cfg.inference.interpolant.prior_conditional.gamma_trans = gamma_trans + cfg.model = ckpt_cfg.model + + self._cfg = cfg + self._cfg.interpolant = cfg.inference.interpolant + self._cfg.interpolant.use_tqdm = False + self._ckpt_cfg = ckpt_cfg + self._infer_cfg = cfg.inference + self._samples_cfg = self._infer_cfg.samples + + # set the number of devices to 1: + self._cfg.experiment.num_devices = 1 + + self._progress_bar = progress_bar + + # Read checkpoint and initialize module. + self._flow_module = self.load_module(ckpt_path) + self._flow_module.eval() + self._flow_module._infer_cfg = self._infer_cfg + self._flow_module._samples_cfg = self._samples_cfg + + @classmethod + def from_tag(cls, tag:str='latest', cfg:dict={}, timesteps:int=20, gamma_trans:float=None, gamma_rots:float=None, progress_bar:bool=True, _pbar_kwargs={}, force_download:bool=False, device:str='cuda'): + """ + Arguments: + tag: str. Tag of the checkpoint to load. Searches the checkpoint at models/{tag}/*.ckpt. If not present, tries to download it. + cfg: dict. default:{}. Configuration dictionary. Will overwrite the configuration from the checkpoint for the entries given. + timesteps: int or None. default:None. Number of timesteps to sample. Overwrites the configuration from the checkpoint or in cfg. + gamma_trans: float or None. default:None. Conditional prior parameter controlling how close the prior is to the equilibrium structure. Overwrites the configuration from the checkpoint or in cfg. + gamma_rots: float or None. default:None. Conditional prior parameter controlling how close the prior is to the equilibrium structure. Overwrites the configuration from the checkpoint or in cfg. + progress_bar: bool. default:True. Whether to show a progress bar during sampling. + _pbar_kwargs: dict. default:{} Additional arguments to pass to the progress bar. + force_download: bool. default:False. If True, forces the download of the checkpoint even if it is already present. + device: str. default:'cuda'. Device to use. + """ + ckpt_path = ckpt_path_from_tag(tag, force_download=force_download) + return cls(ckpt_path, cfg=cfg, timesteps=timesteps, gamma_trans=gamma_trans, gamma_rots=gamma_rots, progress_bar=progress_bar, _pbar_kwargs=_pbar_kwargs, device=device) + + def load_module(self, ckpt_path): + ckpt = torch.load(ckpt_path, map_location=torch.device(self.device), weights_only=True) + model_ckpt = ckpt["state_dict"] + model_ckpt = {k.replace('model.', ''): v for k, v in model_ckpt.items()} + + module = BBFlowModule(self._cfg) + current_state = module.model.state_dict() + compatible_state = { + k: v for k, v in model_ckpt.items() + if k in current_state and current_state[k].shape == v.shape + } + module.model.load_state_dict(compatible_state, strict=False) + module.to(self.device) + return module + + def to(self, device: str): + self._flow_module.to(device) + self.device = device + + def _sample_states(self, trans_eq:torch.Tensor, rotmats_eq:torch.Tensor, seq:torch.Tensor, n_samples:int=10, batch_size:int=None, device:str=None, cuda_memory_GB:int=40): + """ + trans_equilibrium: torch.Tensor of shape (n_residues, 3) + rotmats_equilibrium: torch.Tensor of shape (n_residues, 3, 3) + seq: torch.Tensor of shape (n_residues, 21) + n_samples: int + batch_size: int or None. If not None, overrides the batch size estimation. Otherwise, the batch size is estimated based on the number of residues in the protein. + device: str or None. If None, uses self.device. + cuda_memory_GB: int. Maximum amount of memory to use on the GPU. Used for estimating the batch size if batch_size is None. + + Returns: + atom37_traj: np.array of shape (n_samples, n_residues, 37, 3) + """ + num_res = trans_eq.shape[0] + if batch_size is None: + batch_size = estimate_max_batchsize(n_res=num_res, memory_GB=cuda_memory_GB) + B = batch_size + + if device is None: + device = self.device + + if device != 'cpu': + assert torch.cuda.is_available(), "CUDA is not available." + + self._flow_module.to(device) + self._flow_module.interpolant.set_device(device) + trans_eq = trans_eq.to(device) + rotmats_eq = rotmats_eq.to(device) + seq = seq.to(device) + + interpolant = self._flow_module.interpolant + batches = [] + for i in range(n_samples // B): + batches.append(B) + if n_samples % B != 0: + batches.append(n_samples % B) + + if self._progress_bar: + progress_bar = tqdm(total=n_samples, desc='Sampling states', dynamic_ncols=True, **self._pbar_kwargs) + + # sample states: + sampled_conformations = [] + + with torch.no_grad(): + for b in batches: + atom37_traj, pred_traj, _ = interpolant.sample( + b, + num_res, + self._flow_module.model, + trans_eq.repeat(b, 1, 1), + rotmats_eq.repeat(b, 1, 1, 1), + seq.repeat(b, 1, 1), + ) + atom37_traj = du.to_numpy(torch.stack(atom37_traj, dim=1)) + + # remove the c betas. they are not predicted by the network but rule based and have no real meaning + # Masking CB atoms + # atom37 bb order = ['N', 'CA', 'C', 'CB', 'O'] + atom37_traj[..., 3, :] = 0 + + for i in range(b): + sampled_conformations.append(atom37_traj[i][-1]) + + if self._progress_bar: + progress_bar.update(b) + + # (num_samples, num_residues, 37, 3) + sampled_conformations = np.stack(sampled_conformations, axis=0) + + return sampled_conformations + + + + def sample( + self, + input_path:Union[Path,str], + num_samples:int=10, + output_path:Union[Path,str]=None, + device:str=None, + cuda_memory_GB:int=40, + batch_size:int=None, + output_dir:Optional[Union[Path,str]]=None, + output_fmt:str='pdb', + overwrite:bool=True + ): + """ + Loads a PDB file describing the equilibrium structure of a protein and samples num_samples conformations. Stores the sampled backbone conformations in a PDB file and returns them as array of shape (num_samples, n_residues, 37, 3). + + Arguments: + input_path: Path or str. Path to PDB file. + num_samples: int. Number of conformations to sample. + output_path: Path or str. Path to output PDB file. If None, the sampled conformations are not stored. + device: str. If None, uses self.device from the init call. + cuda_memory_GB: int. Maximum amount of memory to use on the GPU. Used for estimating the batch size if batch_size is None. + batch_size: int. Batch size for sampling. If None, the batch size is estimated based on the number of residues in the protein. + output_dir: Path or str. Path to output directory, in which the pdb file with the sampled conformations will be stored as 'sampled_conformations.pdb' if no output_path is given. + output_fmt: str. 'pdb' or 'xtc'. Format of the output file if output_dir is given. + overwrite: bool. If True, overwrites the output file if it already exists. + """ + + # some checks: + assert input_path is not None, "Input path must be given." + if not str(input_path).endswith('.pdb'): + raise ValueError(f"Input path must be a PDB file but got {input_path}.") + + if output_path is None and output_dir is None: + raise ValueError("Either output_path or output_dir must be given.") + + if output_path is not None and output_dir is not None: + raise ValueError("Only one of output_path or output_dir must be given.") + + # infer output path: + if output_dir is not None: + output_path = Path(output_dir) / f'sampled_conformations.{output_fmt}' + + output_path = Path(output_path) + + # print warning if the suffix of the given output path does not match the output format: + if output_fmt != Path(output_path).suffix[1:]: + log.warning(f"Output format {output_fmt} does not match the suffix of the given output path {output_path}.") + + if output_path.exists(): + if overwrite: + warnings.warn(f"An output path already exists and will be overwritten.") + else: + raise ValueError(f"Output path {output_path} already exists.") + + # Load trans/rotmats from PDB + trans_eq, rotmats_eq, seq, chain_ids = frames_from_pdb(input_path) + + # Sample states + sampled_conformations = self._sample_states( + trans_eq=trans_eq, + rotmats_eq=rotmats_eq, + seq=seq, + n_samples=num_samples, + batch_size=batch_size, + device=device, + cuda_memory_GB=cuda_memory_GB + ) + + if str(output_path).endswith('.xtc'): + raise NotImplementedError("XTC output format is not implemented yet.") + else: + + logging.info(f"Writing sampled conformations to {output_path}") + + au.write_prot_to_pdb( + sampled_conformations, + str(output_path), + aatype=seq.argmax(-1).numpy(), + no_indexing=True, + chain_index=chain_ids + ) diff --git a/bbflow_base/bbflow/deployment/cmd_line_entry.py b/bbflow_base/bbflow/deployment/cmd_line_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..2d9f66e716d4db4f4c8a1bff231a2b3771ce0f14 --- /dev/null +++ b/bbflow_base/bbflow/deployment/cmd_line_entry.py @@ -0,0 +1,228 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Licensed under the MIT license. + +from bbflow.deployment.bbflow import BBFlow +from argparse import ArgumentParser +from pathlib import Path +from tqdm.auto import tqdm + +def _sample(): + arg_parser = ArgumentParser(description="Sample conformations of protein backbone structures using BBFlow.") + + arg_parser.add_argument( + "--input_path", + "-pdb", + type=str, + nargs='+', + required=False, + default=None, + help="Path to the input PDB file(s) containing the protein backbone structure used as initial conformation. If given, the output_path argument must also be given and contain the same number of paths." + ) + arg_parser.add_argument( + "--output_path", + "-o", + type=str, + nargs='+', + required=False, + default=None, + help="Path to the output PDB/xtc file(s) where the sampled conformations will be saved. File ending can either be .pdb or .xtc. If given, the input_path argument must also be given and contain the same number of paths." + ) + arg_parser.add_argument( + "--input_dir", + "-d", + type=str, + required=False, + default=None, + help="Path to the input directory containing the PDB files used as initial conformations. If given, the output_dir argument must also be given. input_dir and input_path are mutually exclusive." + ) + arg_parser.add_argument( + "--output_dir", + "-od", + type=str, + required=False, + default=None, + help="Path to the output directory where the sampled conformations will be saved. If given, the input_dir argument must also be given." + ) + arg_parser.add_argument( + "--output_format", + "-fmt", + type=str, + required=False, + default="pdb", + choices=["pdb", "xtc"], + help="Output format of the sampled conformations if the output_path argument is not being used. Can be either pdb or xtc. Default is pdb." + ) + arg_parser.add_argument( + "--num_samples", + "-n", + type=int, + required=False, + default=100, + help="Number of conformations to sample. Default is 100." + ) + arg_parser.add_argument( + "--batch_size", + "-bs", + type=int, + required=False, + default=None, + help="Batch size for sampling. If not given, the batch size will be estimated based on the GPU memory. Default is None." + ) + arg_parser.add_argument( + "--cuda_memory_GB", + "-vram", + type=float, + required=False, + default=40, + help="Amount of GPU memory in GB to use for estimating the batch size. If not given, the batch size will be estimated based on the GPU memory. Default is None." + ) + arg_parser.add_argument( + "--tag", + "-t", + type=str, + required=False, + default="latest", + help="Tag of the model to use. Default is latest." + ) + arg_parser.add_argument( + "--no_overwrite", + action="store_true", + help="Whether to overwrite the output files if they already exist. Default is False, i.e. to overwrite the files." + ) + arg_parser.add_argument( + "--device", + type=str, + required=False, + default="cuda", + help="Device to use for sampling. Default is cuda." + ) + arg_parser.add_argument( + "--ckpt_path", + type=str, + required=False, + default=None, + help="Path to the checkpoint file. If given, the tag argument will be ignored." + ) + arg_parser.add_argument( + "--timesteps", + type=int, + required=False, + default=20, + help="Number of timesteps to use for sampling. Default is 20." + ) + arg_parser.add_argument( + "--hide_progbar", + action="store_true", + help="Hide the progress bar during sampling. Default is False, i.e. to show the progress bar." + ) + arg_parser.add_argument( + "--gamma_trans", + type=float, + required=False, + default=None, + help="Gamma parameter for the translational part. If not given, the parameter will be chosen in accordance to the training config. Default is None." + ) + arg_parser.add_argument( + "--gamma_rots", + type=float, + required=False, + default=None, + help="Gamma parameter for the rotational part. If not given, the parameter will be chosen in accordance to the training config. Default is None." + ) + + args = arg_parser.parse_args() + + # Check if the arguments are valid + _check_arg_validity(args) + + if args.input_path is not None: + input_paths = args.input_path + output_paths = [Path(p) for p in args.output_path] + elif args.input_dir is not None: + input_paths = list(Path(args.input_dir).glob('*.pdb')) + output_paths = [Path(args.output_dir) / f'samples_{Path(p).stem}.{args.output_format}' for p in input_paths] + else: + raise ValueError("Either input_path or input_dir must be given.") # redundant, but for clarity + + # create the parent dirs of the output paths if they do not exist + for path in output_paths: + path.parent.mkdir(parents=True, exist_ok=True) + + # load the sampler class: + init_kwargs = { + "timesteps": args.timesteps, + "gamma_rots": args.gamma_rots, + "gamma_trans": args.gamma_trans, + "progress_bar": not args.hide_progbar, + "device": args.device, + } + + sample_kwargs = { + "num_samples": args.num_samples, + "batch_size": args.batch_size, + "cuda_memory_GB": args.cuda_memory_GB, + "overwrite": not args.no_overwrite, + } + + if not args.hide_progbar: + pbar = lambda x: tqdm(x, total=len(input_paths), desc="Processing PDB files", unit="file", dynamic_ncols=True, position=0) + p_bar_inner = {'position':1, 'leave':False} + init_kwargs['_pbar_kwargs'] = p_bar_inner + else: + pbar = lambda x: x + + if args.ckpt_path is not None: + bbflow_sampler = BBFlow(ckpt_path=args.ckpt_path, **init_kwargs) + else: + bbflow_sampler = BBFlow.from_tag(args.tag, **init_kwargs) + + # sample conformations: + print(f"Sampling {args.num_samples} confs for {len(input_paths)} input PDB files...\n") + + for input_path, output_path in pbar(zip(input_paths, output_paths)): + bbflow_sampler.sample( + input_path=input_path, + output_path=output_path, + output_fmt=output_path.suffix[1:], + **sample_kwargs + ) + + +def _check_arg_validity(args): + # Check if input_path and input_dir are given + if args.input_path is None and args.input_dir is None: + raise ValueError("Either input_path or input_dir must be given.") + + # Check if output_path and output_dir are given + if args.output_path is None and args.output_dir is None: + raise ValueError("Either output_path or output_dir must be given.") + + # Check that not both input_path and input_dir are given + if args.input_path is not None and args.input_dir is not None: + raise ValueError("input_path and input_dir are mutually exclusive. Please provide only one of them.") + if args.output_path is not None and args.output_dir is not None: + raise ValueError("output_path and output_dir are mutually exclusive. Please provide only one of them.") + + + # Check if input_path and output_path are given + if args.input_path is not None: + assert args.output_path is not None, "If input_path is given, output_path must also be given." + assert len(args.input_path) == len(args.output_path), f"If input_path is given, output_path must also be given and contain the same number of paths, {len(args.input_path)} != {len(args.output_path)}." + # check that all paths exist: + for path in args.input_path: + assert Path(path).exists(), f"Input path {path} does not exist." + # check that all paths are .pdb + assert Path(path).suffix == '.pdb', f"Found input path {path}. It must have .pdb ending." + + for path in args.output_path: + assert Path(path).suffix in ['.pdb', '.xtc'], f"Output path {path} must have .pdb or .xtc ending." + + # check that all paths are not the same as input paths + assert Path(path) not in [Path(p) for p in args.input_path], f"Output path {path} must not be the same as input path." + + # Check if input_dir and output_dir are given + if args.input_dir is not None: + assert args.output_dir is not None, "If input_dir is given, output_dir must also be given." + assert Path(args.input_dir).exists(), f"Input directory {args.input_dir} does not exist." + # check that at least one pdb file exists in the input directory + assert len(list(Path(args.input_dir).glob('*.pdb'))) > 0, f"No PDB files found in {args.input_dir}." \ No newline at end of file diff --git a/bbflow_base/bbflow/deployment/utils.py b/bbflow_base/bbflow/deployment/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..58f774d4da3d57aecf000e4a060569860cf2c5bd --- /dev/null +++ b/bbflow_base/bbflow/deployment/utils.py @@ -0,0 +1,149 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Licensed under the MIT license. + +import numpy as np +from pathlib import Path +from typing import Union +import logging +import requests +from tqdm.auto import tqdm + + +LATEST_TAG = 'bbflow-multimer-0.2' +CKPT_URLS = { + 'bbflow-0.1': 'https://keeper.mpdl.mpg.de/f/918e443c39ee43d1a3e5/?dl=1', + 'bbflow-0.1-old': 'https://keeper.mpdl.mpg.de/f/bee3c06a20b94ee2ac92/?dl=1', + 'bbflow-mini-0.1': 'https://keeper.mpdl.mpg.de/f/6468bf14741241ada585/?dl=1', + 'bbflow-multimer-0.1': 'https://keeper.mpdl.mpg.de/f/5f34210827e44bbabea3/?dl=1', + 'bbflow-multimer-0.2': 'https://keeper.mpdl.mpg.de/f/6a7b1fedd8ac4dda8e22/?dl=1', +} +CONFIG_URLS = { + 'bbflow-0.1': 'https://keeper.mpdl.mpg.de/f/2d9db8c0433f429c8d2f/?dl=1', + 'bbflow-0.1-old': 'https://keeper.mpdl.mpg.de/f/7ed49e41d7c444569a11/?dl=1', + 'bbflow-mini-0.1': 'https://keeper.mpdl.mpg.de/f/f45f13e93d564d29a605/?dl=1', + 'bbflow-multimer-0.1': 'https://keeper.mpdl.mpg.de/f/2c66f84f39b640faab38/?dl=1', + 'bbflow-multimer-0.2': 'https://keeper.mpdl.mpg.de/f/346a25bca784417a8e3d/?dl=1', +} + + +def estimate_max_batchsize(n_res, memory_GB=40): + """ + Estimate the maximum batch size that can be used for sampling. Hard-coded from empiric experiments. We found a dependency that is inversely proportional to the number of residues in the protein. + """ + if not isinstance(n_res, np.ndarray): + n_res = np.array([n_res]) + A = 5e4 + B = 40 + batchsize = A/(n_res+B)**2 * memory_GB + batchsize = np.floor(batchsize) + ones = np.ones_like(batchsize) + out = np.max(np.stack([batchsize, ones], axis=0), axis=0) + if out.shape == (1,): + return int(out[0]) + return out.astype(int) + + +# overwrite args that are specified in cfg: +def recursive_update(cfg:dict, cfg_:dict): + for key in cfg.keys(): + if key in cfg_.keys(): + if isinstance(cfg[key], dict): + recursive_update(cfg[key], cfg_[key]) + else: + cfg_[key] = cfg[key] + +def get_root_dir()->Path: + """ + Get the root directory of the package. + """ + return Path(__file__).parent.parent.parent + + +def ckpt_path_from_tag(tag:str='latest', force_download:bool=False) -> Path: + """ + Get the path to the checkpoint assumed to be located at root_dir/models/tag/*.ckpt. Checks existence and uniqueness of the checkpoint file and existence of the config file. + """ + + if tag == 'latest': + tag = LATEST_TAG + + root_dir = get_root_dir() + ckpt_dir = root_dir / 'models' / tag + + if not (ckpt_dir/'config.yaml').exists() or force_download: + if not (ckpt_dir/'config.yaml').exists(): + logging.info(f"Config file not found in {ckpt_dir}.") + logging.info(f"Downloading the model with tag {tag}...") + + if not tag in CKPT_URLS.keys(): + raise FileNotFoundError(f"Checkpoint directory {ckpt_dir} not found and {tag} not found in the hard-coded URLs for downloading.") + else: + ckpt_path = download_model(tag) + return ckpt_path + + ckpt_files = list(ckpt_dir.glob('*.ckpt')) + if len(ckpt_files) == 0: + if not tag in CKPT_URLS.keys(): + raise FileNotFoundError(f"No checkpoint files found in {ckpt_dir} and {tag} not found in the hard-coded URLs for downloading.") + else: + ckpt_path = download_model(tag) + return ckpt_path + elif len(ckpt_files) > 1: + raise FileNotFoundError(f"Multiple checkpoint files found in {ckpt_dir}.") + if not (ckpt_dir/'config.yaml').exists(): + raise FileNotFoundError(f"No config file found in {ckpt_dir}.") + + return ckpt_files[0] + +def _download_file(url:str, target_path:Path, progress_bar:bool=True): + # Start the download + headers = {'User-Agent': 'Wget/1.21'} + response = requests.get(url, stream=True, headers=headers) + response.raise_for_status() # Ensure the request was successful + + if 'text/html' in response.headers.get('Content-Type', '') and b'Link does not exist' in response.content: + raise ValueError(f"Invalid or expired link: {url}") + + + if progress_bar: + # Get the total file size from headers + total_size = int(response.headers.get('content-length', 0)) + + # Initialize the progress bar + with tqdm(total=total_size, unit='B', unit_scale=True) as t: + with open(target_path, 'wb') as file: + for chunk in response.iter_content(chunk_size=1024*2**2): + file.write(chunk) + t.update(len(chunk)) + else: + with open(target_path, 'wb') as file: + for chunk in response.iter_content(chunk_size=1024*2**2): + file.write(chunk) + + assert target_path.exists(), f"Download failed, file not found at {target_path}" + + +def download_model(tag:str='latest'): + """ + Download the model checkpoint and config file from the hard-coded URLS. + """ + if tag == 'latest': + tag = LATEST_TAG + + root_dir = get_root_dir() + ckpt_dir = root_dir / 'models' / tag + ckpt_dir.mkdir(parents=True, exist_ok=True) + + if not tag in CKPT_URLS.keys(): + raise FileNotFoundError(f"Tag {tag} not recognized. Possible tags: {list(CKPT_URLS.keys())}.") + + ckpt_url = CKPT_URLS[tag] + config_url = CONFIG_URLS[tag] + + ckpt_path = ckpt_dir / f'{tag}.ckpt' + config_path = ckpt_dir / 'config.yaml' + + _download_file(config_url, config_path, progress_bar=False) + _download_file(ckpt_url, ckpt_path, progress_bar=True) + + return ckpt_path diff --git a/bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-310.pyc b/bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daa9e137cce235d9de7127ae8572469c003d3c19 Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-310.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-311.pyc b/bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5675c8042fff3443bced50f6f1c48d6c45f54765 Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-311.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-39.pyc b/bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e61eb7555b23e76978aa78ff344e4a06e0949b12 Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-39.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-310.pyc b/bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b30636fa4a0377cda0f7852c0b8d2789be93387d Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-310.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-313.pyc b/bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bce3b4e246d6f1a6babbbc0b7b7f0f80467f229 Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-313.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-39.pyc b/bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e81851825ca5000f0886408fe3943ea0e0a53f1 Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-39.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/collective.cpython-310.pyc b/bbflow_base/bbflow/models/__pycache__/collective.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74c06f819215e9d5bd7fec9de1089574054627cc Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/collective.cpython-310.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/collective.cpython-39.pyc b/bbflow_base/bbflow/models/__pycache__/collective.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fead6546c68ec9f32ecbc5d87160e96e47719ecc Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/collective.cpython-39.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/embedder.cpython-310.pyc b/bbflow_base/bbflow/models/__pycache__/embedder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..805bee4245c5fc7adcac4e1603a99cd17867618a Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/embedder.cpython-310.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/embedder.cpython-311.pyc b/bbflow_base/bbflow/models/__pycache__/embedder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e094946db2a04264d7a936999efcbda64d1901f Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/embedder.cpython-311.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/embedder.cpython-39.pyc b/bbflow_base/bbflow/models/__pycache__/embedder.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2517a9727b0a7c37a5d1e7251b4724d3fb3fb546 Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/embedder.cpython-39.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/latent.cpython-310.pyc b/bbflow_base/bbflow/models/__pycache__/latent.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6d41ee55ae4a976a2943a67d45de40cdb9f1b60 Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/latent.cpython-310.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/latent.cpython-313.pyc b/bbflow_base/bbflow/models/__pycache__/latent.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..590482133a88a52d8aff63756c5030e8311f5bb8 Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/latent.cpython-313.pyc differ diff --git a/bbflow_base/bbflow/models/__pycache__/latent.cpython-39.pyc b/bbflow_base/bbflow/models/__pycache__/latent.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe444a7124d3c14fc39591a04d14e136f6451241 Binary files /dev/null and b/bbflow_base/bbflow/models/__pycache__/latent.cpython-39.pyc differ diff --git a/bbflow_base/bbflow/models/bbflow_model.py b/bbflow_base/bbflow/models/bbflow_model.py new file mode 100644 index 0000000000000000000000000000000000000000..5475d3608fee98bbad1f8c1b0b892be7ff555c30 --- /dev/null +++ b/bbflow_base/bbflow/models/bbflow_model.py @@ -0,0 +1,407 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import numpy as np +import torch +import torch.nn as nn +from torch.utils.checkpoint import checkpoint + +from gafl.models import ipa_pytorch +from gafl.data import utils as du +from gafl.models.gafl.pga_utils import embed_frames, EquiLayerNorm +from gafl.models.gafl.cfa import GeometricFrameAttention, Linear, BackboneUpdate + +from bbflow.models.embedder import Embedder +from bbflow.models.collective import CollectiveMeasureController + + +from omegaconf import DictConfig, OmegaConf +from omegaconf.base import ContainerMetadata +# depending on the torch version (higher than 2.6), we need to add the DictConfig and ContainerMetadata to the safe globals: +import torch +import builtins +from typing import Any +from collections import defaultdict +from omegaconf import DictConfig, OmegaConf, ListConfig +from omegaconf.nodes import AnyNode +from omegaconf.base import ContainerMetadata, Metadata + +# depending on the torch version (>=2.6), we need to add all types the checkpoint asked for +if hasattr(torch.serialization, "add_safe_globals"): + torch.serialization.add_safe_globals([ + (Any, "typing.Any"), + (defaultdict, "collections.defaultdict"), + (DictConfig, "omegaconf.dictconfig.DictConfig"), + (ListConfig, "omegaconf.listconfig.ListConfig"), + (AnyNode, "omegaconf.nodes.AnyNode"), + (ContainerMetadata, "omegaconf.base.ContainerMetadata"), + (Metadata, "omegaconf.base.Metadata"), + (builtins.dict, "builtins.dict"), + (builtins.int, "builtins.int"), + (builtins.list, "builtins.list"), + ]) + + +class BBFlowModel(nn.Module): + + def __init__(self, model_conf, latent_cfg=None): + super(BBFlowModel, self).__init__() + + self._model_conf = model_conf + self._gfa_conf = model_conf.gfa + self.rigids_ang_to_nm = lambda x: x.apply_trans_fn(lambda x: x * du.ANG_TO_NM_SCALE) + self.rigids_nm_to_ang = lambda x: x.apply_trans_fn(lambda x: x * du.NM_TO_ANG_SCALE) + self.embedder = Embedder(model_conf, latent_cfg=latent_cfg) + self.latent_enabled = bool(latent_cfg is not None and getattr(latent_cfg, "enable", False)) + self.inject_film = bool( + self.latent_enabled and getattr(latent_cfg, "inject_film", True) + ) + self.activation_checkpoint = bool( + latent_cfg is not None and getattr(latent_cfg, "activation_checkpoint", False) + ) + self.collective_enabled = bool( + self.latent_enabled and getattr(latent_cfg, "collective_enable", False) + ) + if self.collective_enabled: + self.collective_rank = int(getattr(latent_cfg, "collective_rank", 4)) + self.collective_controller = CollectiveMeasureController( + rank=self.collective_rank, + hidden_dim=int(getattr(latent_cfg, "collective_hidden_dim", 128)), + output_scale=float(getattr(latent_cfg, "collective_output_scale", 1.0)), + ) + else: + self.collective_rank = 0 + self.collective_controller = None + + # Attention trunk + self.trunk = nn.ModuleDict() + for b in range(self._gfa_conf.num_blocks): + self.trunk[f'gfa_{b}'] = GeometricFrameAttention(self._gfa_conf, geometric_input=bool(b), geometric_output=True) + self.trunk[f'gfa_ln_{b}'] = nn.LayerNorm(self._gfa_conf.c_s) + self.trunk[f'g_ln_{b}'] = EquiLayerNorm() + tfmr_in = self._gfa_conf.c_s + tfmr_layer = nn.TransformerEncoderLayer( + d_model=tfmr_in, + nhead=self._gfa_conf.seq_tfmr_num_heads, + dim_feedforward=tfmr_in, + batch_first=True, + dropout=0.0, + norm_first=False + ) + self.trunk[f'seq_tfmr_{b}'] = nn.TransformerEncoder( + tfmr_layer, self._gfa_conf.seq_tfmr_num_layers, enable_nested_tensor=False) + self.trunk[f'post_tfmr_{b}'] = Linear( + tfmr_in, self._gfa_conf.c_s, init="final") + self.trunk[f'node_transition_{b}'] = ipa_pytorch.StructureModuleTransition( + c=self._gfa_conf.c_s) + self.trunk[f'bb_update_{b}'] = BackboneUpdate( + self._gfa_conf.c_s, + self._gfa_conf.no_v_points, + self._gfa_conf.no_heads,) + + if b < self._gfa_conf.num_blocks-1: + # No edge update on the last block. + edge_in = self._model_conf.edge_embed_size + self.trunk[f'edge_transition_{b}'] = ipa_pytorch.EdgeTransition( + node_embed_size=self._gfa_conf.c_s, + edge_embed_in=edge_in, + edge_embed_out=self._model_conf.edge_embed_size, + ) + + if self.inject_film: + self.latent_dim = int(getattr(latent_cfg, "dim", 16)) + self.film_cond_dim = int(getattr(latent_cfg, "node_cond_dim", getattr(latent_cfg, "num_modes", self.latent_dim))) + self.film_mlp = nn.Sequential( + nn.Linear(self.film_cond_dim, self._gfa_conf.c_s), + nn.ReLU(), + nn.Linear(self._gfa_conf.c_s, 2 * self._gfa_conf.c_s), + ) + nn.init.zeros_(self.film_mlp[-1].weight) + nn.init.zeros_(self.film_mlp[-1].bias) + else: + self.latent_dim = 0 + self.film_cond_dim = 0 + self.film_mlp = None + + def _apply_latent_film(self, node_embed, z): + if not self.inject_film: + return node_embed + if isinstance(z, dict): + cond = z.get("node_cond") + else: + cond = z + if cond is None: + cond = torch.zeros( + node_embed.shape[0], + node_embed.shape[1], + self.film_cond_dim, + device=node_embed.device, + dtype=node_embed.dtype, + ) + if cond.dim() == 2: + cond = cond[:, None, :].expand(node_embed.shape[0], node_embed.shape[1], -1) + gamma_beta = self.film_mlp(cond.to(dtype=node_embed.dtype)) + gamma, beta = torch.chunk(gamma_beta, 2, dim=-1) + return node_embed * (1.0 + gamma) + beta + + def _collective_update(self, input_feats): + if not self.collective_enabled: + return None, None + condition = input_feats.get("z") + if not isinstance(condition, dict): + raise ValueError("CMFM requires a dictionary condition") + required = ( + "collective_basis_global", + "collective_target_covariance", + "collective_group_index", + ) + missing = [key for key in required if key not in condition] + if missing: + raise ValueError(f"CMFM condition is missing required keys: {missing}") + return self.collective_controller( + input_feats["trans_t"], + input_feats["trans_equilibrium"], + input_feats["res_mask"], + condition["collective_basis_global"], + condition["collective_target_covariance"], + condition["collective_group_index"].long(), + input_feats["t"], + ) + + def prepare_inference_static(self, batch): + B, N = batch["res_mask"].shape[:2] + return self.embedder.prepare_inference_static({ + "B,N": (B, N), + "device": batch["res_mask"].device, + "CA_pos": { + "trans_equilibrium": batch["trans_equilibrium"], + }, + "rotmats_equilibrium": batch["rotmats_equilibrium"], + "seq": batch["seq"], + "z": batch.get("z"), + }) + + def _run_gfa(self, block_idx, node_embed, g, edge_embed, curr_frames, node_mask): + gfa = self.trunk[f'gfa_{block_idx}'] + if not (self.training and self.activation_checkpoint and torch.is_grad_enabled()): + return gfa(node_embed, g, edge_embed, curr_frames, node_mask) + + if g is None: + def first_gfa_forward(node_embed_, edge_embed_, curr_frames_, node_mask_): + return gfa( + node_embed_, None, edge_embed_, curr_frames_, node_mask_ + ) + + return checkpoint( + first_gfa_forward, + node_embed, + edge_embed, + curr_frames, + node_mask, + use_reentrant=False, + preserve_rng_state=False, + ) + + def gfa_forward(node_embed_, g_, edge_embed_, curr_frames_, node_mask_): + return gfa(node_embed_, g_, edge_embed_, curr_frames_, node_mask_) + + return checkpoint( + gfa_forward, + node_embed, + g, + edge_embed, + curr_frames, + node_mask, + use_reentrant=False, + preserve_rng_state=False, + ) + + def _run_edge_transition(self, block_idx, node_embed, edge_embed): + edge_transition = self.trunk[f'edge_transition_{block_idx}'] + if not ( + self.training + and self.activation_checkpoint + and torch.is_grad_enabled() + ): + return edge_transition(node_embed, edge_embed) + + def edge_forward(node_embed_, edge_embed_): + return edge_transition(node_embed_, edge_embed_) + + return checkpoint( + edge_forward, + node_embed, + edge_embed, + use_reentrant=False, + preserve_rng_state=False, + ) + + + def forward_backbone(self, input_feats): + node_mask = input_feats['res_mask'] + edge_mask = node_mask[:, None] * node_mask[:, :, None] + continuous_t = input_feats['t'] + trans_t = input_feats['trans_t'] + rotmats_t = input_feats['rotmats_t'] + + # Initialize node and edge embeddings + if 'trans_sc' not in input_feats: + trans_sc = torch.zeros_like(trans_t) + else: + trans_sc = input_feats['trans_sc'] + + B, N = node_mask.shape[:2] + CA_pos = { + "trans_t": trans_t, + "trans_sc": trans_sc, + "trans_equilibrium": input_feats["trans_equilibrium"] + } + embedder_input_feats = { + "B,N": (B, N), + "device": node_mask.device, + "time": continuous_t, + "CA_pos": CA_pos, + "rotmats_equilibrium": input_feats["rotmats_equilibrium"], + "seq": input_feats["seq"], + } + if "dataset_type_onehot" in input_feats: + embedder_input_feats["dataset_type_onehot"] = input_feats["dataset_type_onehot"] + if "z" in input_feats: + embedder_input_feats["z"] = input_feats["z"] + if "_embedder_static" in input_feats: + embedder_input_feats["inference_static"] = input_feats["_embedder_static"] + init_node_embed, init_edge_embed = self.embedder(embedder_input_feats) + + + # Initial rigids + # curr_frames = embed_frames(rotmats_t, trans_t * du.ANG_TO_NM_SCALE) + curr_rigids = du.create_rigid(rotmats_t, trans_t,) + curr_rigids = self.rigids_ang_to_nm(curr_rigids) + curr_frames = embed_frames(rotmats_t, trans_t * du.ANG_TO_NM_SCALE) + + # Main trunk + init_node_embed = init_node_embed * node_mask[..., None] + node_embed = init_node_embed * node_mask[..., None] + edge_embed = init_edge_embed * edge_mask[..., None] + g = None + for b in range(self._gfa_conf.num_blocks): + gfa_embed, g_gfa, gfa_rel = self._run_gfa( + b, + node_embed, + g, + edge_embed, + curr_frames, + node_mask) + gfa_embed *= node_mask[..., None] + gfa_rel = gfa_rel * node_mask[..., None, None] + node_embed = self.trunk[f'gfa_ln_{b}'](node_embed + gfa_embed) + + if g is not None: + g = self.trunk[f'g_ln_{b}'](g + g_gfa) + else: + g = self.trunk[f'g_ln_{b}'](g_gfa) + g = g * node_mask[..., None, None] + + seq_tfmr_out = self.trunk[f'seq_tfmr_{b}']( + node_embed, src_key_padding_mask=(1 - node_mask).bool()) + node_embed = node_embed + self.trunk[f'post_tfmr_{b}'](seq_tfmr_out) + node_embed = self.trunk[f'node_transition_{b}'](node_embed) + node_embed = node_embed * node_mask[..., None] + update_node_embed = node_embed + if b == self._gfa_conf.num_blocks - 1: + update_node_embed = self._apply_latent_film( + node_embed, + input_feats.get("z", None), + ) + curr_frames, curr_rigids = self.trunk[f'bb_update_{b}']( + update_node_embed, + g, + gfa_rel, + curr_frames, + curr_rigids, + node_mask[..., None],) + + if b < self._gfa_conf.num_blocks-1: + edge_embed = self._run_edge_transition( + b, node_embed, edge_embed) + edge_embed *= edge_mask[..., None] + + curr_rigids = self.rigids_nm_to_ang(curr_rigids) + pred_trans = curr_rigids.get_trans() + pred_rotmats = curr_rigids.get_rots().get_rot_mats() + return { + 'pred_trans': pred_trans, + 'pred_rotmats': pred_rotmats, + } + + @classmethod + def _slice_batch_value(cls, value, start, end, batch_size): + if torch.is_tensor(value): + if value.ndim > 0 and value.shape[0] == batch_size: + return value[start:end] + return value + if isinstance(value, dict): + return { + key: cls._slice_batch_value(item, start, end, batch_size) + for key, item in value.items() + } + if isinstance(value, list) and len(value) == batch_size: + return value[start:end] + if isinstance(value, tuple) and len(value) == batch_size: + return value[start:end] + return value + + def forward_chunked(self, input_feats, chunk_size, checkpoint_chunks=True): + """Run the particle-independent backbone in chunks, then couple the full group.""" + batch_size = int(input_feats['res_mask'].shape[0]) + chunk_size = int(chunk_size) + if chunk_size <= 0: + raise ValueError(f"chunk_size must be positive, got {chunk_size}") + if chunk_size >= batch_size: + return self.forward(input_feats) + + chunk_outputs = [] + for start in range(0, batch_size, chunk_size): + end = min(start + chunk_size, batch_size) + chunk_input = self._slice_batch_value( + input_feats, + start, + end, + batch_size, + ) + if checkpoint_chunks and self.training and torch.is_grad_enabled(): + chunk_output = checkpoint( + self.forward_backbone, + chunk_input, + use_reentrant=False, + ) + else: + chunk_output = self.forward_backbone(chunk_input) + chunk_outputs.append(chunk_output) + + output_keys = tuple(chunk_outputs[0]) + if any(tuple(output) != output_keys for output in chunk_outputs[1:]): + raise RuntimeError("backbone chunk outputs do not have matching keys") + backbone_output = { + key: torch.cat([output[key] for output in chunk_outputs], dim=0) + for key in output_keys + } + return self.apply_collective_update(input_feats, backbone_output) + + def apply_collective_update(self, input_feats, output): + output = dict(output) + collective_update, collective_coefficients = self._collective_update(input_feats) + if collective_update is None: + return output + output['pred_trans'] = output['pred_trans'] + collective_update.to( + dtype=output['pred_trans'].dtype + ) + output['collective_update_global'] = collective_update + output['collective_coefficients_t'] = collective_coefficients + return output + + def forward(self, input_feats): + backbone_output = self.forward_backbone(input_feats) + return self.apply_collective_update(input_feats, backbone_output) diff --git a/bbflow_base/bbflow/models/bbflow_module.py b/bbflow_base/bbflow/models/bbflow_module.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1dcb40bcc14bda5f26b84236f2da9504fd33e8 --- /dev/null +++ b/bbflow_base/bbflow/models/bbflow_module.py @@ -0,0 +1,2817 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from typing import Any +import copy +import torch +import torch.utils.checkpoint +import time +import os +import random +import logging +import wandb +import numpy as np +import pandas as pd +import shutil +import json +from datetime import datetime +from pytorch_lightning.utilities import rank_zero_only +import torch.distributed as dist +import matplotlib +import mdtraj +import warnings + +from gafl.analysis import metrics +from gafl.models.flow_module import FlowModule +from gafl.data import utils as du +from gafl.models import utils as mu +import gafl.experiment_utils as eu + +from bbflow.data.alignment import require_alignment_version +from bbflow.models.bbflow_model import BBFlowModel +from bbflow.models.latent import LatentEncoder +from bbflow.models.collective import collective_measure_dynamics_loss +from bbflow.analysis import utils as au +from bbflow.analysis.analyse_bbflow import calc_metrics +from bbflow.data.interpolant_bbflow import InterpolantBBFlow + +# depending on the torch version (higher than 2.6), we need to add the DictConfig and ContainerMetadata to the safe globals: +from omegaconf import DictConfig, OmegaConf +from omegaconf.base import ContainerMetadata +if hasattr(torch.serialization, 'add_safe_globals'): + torch.serialization.add_safe_globals([DictConfig, ContainerMetadata]) # needed for loading the checkpoint with weights_only=True + +WARMUP_EPOCH_SUMMARY_KEYS = [ + "train_loss", + "official_loss", + "enm_warmup_loss", + "enm_warmup_subspace_overlap", + "enm_warmup_cross_cov_far_top10_sign_agree", + "enm_warmup_cross_cov_far_corr", + "enm_warmup_active", + "latent_effective_modes", + "condition_scaled_pred_trans_delta_rel", +] + +MD_EPOCH_SUMMARY_KEYS = [ + "train_loss", + "official_loss", + "motion_loss", + "mode_orth_loss", + "mode_recon_loss", + "q_nll_loss", + "q_nll_per_dim", + "mode_coeff_abs", + "mode_coeff_std", + "mode_recon_centered_rel_error", + "mode_recon_uncentered_rel_error", + "mode_gram_min_eig", + "mode_gram_condition", + "mode_max_cosine_abs", + "local_cov_loss", + "cross_cov_loss", + "cross_cov_near_loss", + "cross_cov_far_loss", + "cross_cov_far_corr", + "cross_cov_far_top10_sign_agree", + "cross_cov_near_top10_sign_agree", + "rmsf_loss", + "gen_cov_loss", + "gen_local_shape_loss", + "gen_cross_shape_loss", + "gen_trace_anchor_loss", + "gen_response_abs_mean", + "gen_response_trace_mean", + "gen_trace_ratio_to_teacher", + "gen_trace_ratio_to_anchor", + "gen_trace_anchor_mean", + "gen_rollout_trace_ratio", + "gen_rollout_trace_ratio_ema", + "gen_rollout_trace_target_scale", + "gen_rollout_trace_measured", + "gen_rollout_trace_steps", + "gen_rollout_batch", + "gen_rollout_num_res", + "gen_response_active_frac", + "pca_align_loss", + "pca_align_weighted_overlap", + "pca_align_best_overlap", + "pca_align_top_energy_overlap", + "pca_align_top_energy_subspace_overlap", + "condition_cycle_loss", + "condition_cycle_rel_error", + "condition_cycle_cosine", + "enm_warmup_active", + "latent_effective_modes", + "condition_scaled_pred_trans_delta_rel", + "collective_measure_loss", + "collective_mean_dynamics_abs_error", + "collective_cov_dynamics_loss", + "collective_update_abs", + "collective_retained_fraction", +] + + +def epoch_summary_stage(metrics): + warmup_active = float(metrics.get("enm_warmup_active", 0.0) or 0.0) > 0.5 + return "enm-init" if warmup_active else "md" + + +def epoch_summary_keys(metrics): + """Return the concise console summary for the current training stage.""" + return WARMUP_EPOCH_SUMMARY_KEYS if epoch_summary_stage(metrics) == "enm-init" else MD_EPOCH_SUMMARY_KEYS + + +class BBFlowModule(FlowModule): + + def __init__(self, cfg, folding_cfg=None): + self._latent_cfg_raw = cfg.latent if hasattr(cfg, "latent") else None + super().__init__(cfg, folding_cfg) + self._print_logger = eu.get_pylogger(__name__) + if hasattr(self._exp_cfg, 'reset_epoch'): + self.reset_epoch = self._exp_cfg.reset_epoch + else: + self.reset_epoch = False + if hasattr(self._exp_cfg, 'reset_optimizer_on_load'): + self.reset_optimizer_on_load = self._exp_cfg.reset_optimizer_on_load + else: + self.reset_optimizer_on_load = False + + # set samples per valid protein: + num_ranks = cfg.experiment.num_devices + total_samples_per_valid_prot = self._data_cfg.validation.samples_per_valid_protein + self.samples_per_valid_protein_per_rank = total_samples_per_valid_prot // num_ranks + + assert total_samples_per_valid_prot % num_ranks == 0, f"Samples per valid protein ({self.samples_per_valid_protein_per_rank}) must be divisible by the number of ranks ({num_ranks}), set by the coinfig parameter experiment.num_devices." + assert self.samples_per_valid_protein_per_rank > 0 + + def create_model(self): + latent_enabled = bool(self._latent_cfg_raw is not None and getattr(self._latent_cfg_raw, "enable", False)) + self.model = BBFlowModel(self._model_cfg, latent_cfg=self._latent_cfg_raw) + self.interpolant = InterpolantBBFlow(self._interpolant_cfg) + self.latent_enabled = latent_enabled + training_cfg = self._exp_cfg.training + self.motion_loss_enabled = bool( + latent_enabled and float(getattr(training_cfg, "lambda_shape", 1.0)) != 0.0 + ) + self.condition_enabled = bool( + latent_enabled and ( + getattr(self._latent_cfg_raw, "inject_embedder", True) + or getattr(self._latent_cfg_raw, "inject_film", True) + ) + ) + self.collective_enabled = bool( + latent_enabled and getattr(self._latent_cfg_raw, "collective_enable", False) + ) + self.collective_rank = int( + getattr(self._latent_cfg_raw, "collective_rank", 0) + ) if self.collective_enabled else 0 + # Take the collective basis from the data instead of from the model's own + # implied covariance. The self-referential version measures the model's + # error in a basis the model chooses, which has two measured + # consequences: the basis walks (its spectrum is nearly flat, so the + # eigenvectors are unstable), and directions where nothing happens are + # free to inflate until they reach the model's own rank-R eigenvalue -- + # observed at 10^-0.15 of that level on 39 of 82 systems. Anchoring to + # the cached MD principal directions removes both. It also raises the + # fraction of the reference variance the objective can reach at all, + # from ~18% (a random 4-plane inside the mode span) to the top-R share. + self.collective_basis_from_data = bool( + self.collective_enabled + and getattr(self._latent_cfg_raw, "collective_basis_from_data", False) + ) + # Keep the 1/tau in the velocities. Default True only to leave the + # existing configuration alone; see the loss docstring for why False is + # the better choice. + self.collective_rate_weighted = bool( + getattr(self._latent_cfg_raw, "collective_rate_weighted", True) + ) + if self.collective_enabled: + if bool(getattr(self._latent_cfg_raw, "freeze_foundation", False)): + raise ValueError("CMFM requires the full BBFlow foundation to be unfrozen") + # freeze_mode_head is allowed here. It used to be rejected because the + # blanket requires_grad_(True) below silently undid it; that unfreeze + # now respects the flag. With a stage-1 warm start the mode head + # arrives aligned (mode_max_cosine 0.871, cross_cov_far_corr 0.236) + # and one epoch of CMFM training destroys it -- the template head + # takes a gradient norm ~24x the backbone's on 54x fewer tensors. + group_size = int(getattr(training_cfg, "ensemble_group_size", 0)) + if group_size <= self.collective_rank: + raise ValueError( + f"CMFM ensemble_group_size must exceed collective_rank=" + f"{self.collective_rank}, got {group_size}" + ) + self.training_epoch_metrics = [] + self._grad_flow_reported = False + self._condition_probe_epoch = None + self._gen_cov_rollout_trace_ratio_ema = None + self.freeze_foundation = bool( + latent_enabled and getattr(self._latent_cfg_raw, "freeze_foundation", True) + ) + if latent_enabled: + self.latent_encoder = LatentEncoder(self._latent_cfg_raw) + self.motion_target_cache = None + self.motion_target_device_cache = {} + self.equilibrium_distance_cache = {} + self.motion_target_cache_path = getattr( + self._latent_cfg_raw, + "motion_target_cache_path", + getattr(self._latent_cfg_raw, "shape_fingerprint_cache_path", None), + ) + if not self.motion_loss_enabled and not self.condition_enabled: + for param in self.latent_encoder.parameters(): + param.requires_grad = False + if self.freeze_foundation: + self._freeze_foundation_model() + # Stage-2 switch: freeze U (trunk + template heads) so c* = Proj_U(D) is + # a stable target and q/generator train against a fixed representation. + # Orthogonal to freeze_foundation (that freezes the GENERATOR; this + # freezes the LATENT mode pathway). Load a stage-1 checkpoint's weights + # via experiment.warm_start before relying on this -- freezing does not + # by itself give you a trained U, it just stops a loaded one from moving. + self.freeze_mode_head = bool( + latent_enabled and getattr(self._latent_cfg_raw, "freeze_mode_head", False) + ) + if self.freeze_mode_head: + self.latent_encoder.freeze_prior_backbone() + if int(getattr(self, "global_rank", 0)) == 0: + check = self.latent_encoder.prior_backbone_grad_check() + logging.info( + "[freeze-mode-head] u_pathway_params=%d u_pathway_trainable=%d " + "(want 0) q_head_trainable=%d (want >0)", + check["u_pathway_params"], + check["u_pathway_trainable"], + check["q_head_trainable"], + ) + else: + self.freeze_mode_head = False + if self.collective_enabled: + for param in self.model.parameters(): + param.requires_grad_(True) + for param in self.latent_encoder.parameters(): + param.requires_grad_(True) + # CMFM needs the generator and q trainable; U is optional. Re-apply + # the stage-2 freeze here, after the blanket unfreeze, or it is a + # no-op -- q and the collective controller then train against a + # fixed U instead of dragging it along. + if self.freeze_mode_head: + self.latent_encoder.freeze_prior_backbone() + if int(getattr(self, "global_rank", 0)) == 0: + check = self.latent_encoder.prior_backbone_grad_check() + print( + "[freeze-mode-head] after collective unfreeze: " + f"u_pathway_params={check['u_pathway_params']} " + f"u_pathway_trainable={check['u_pathway_trainable']} (want 0) " + f"q_head_trainable={check['q_head_trainable']} (want >0)", + flush=True, + ) + + def _freeze_foundation_model(self): + for param in self.model.parameters(): + param.requires_grad = False + trainable_modules = [ + self.model.embedder.z_node_adapter, + self.model.embedder.z_edge_adapter, + self.model.embedder.disp_node_adapter, + self.model.embedder.disp_edge_adapter, + self.model.film_mlp, + ] + for module in trainable_modules: + if module is not None: + for param in module.parameters(): + param.requires_grad = True + + def _set_frozen_foundation_eval(self): + if not getattr(self, "freeze_foundation", False): + return + self.model.eval() + for module in [ + self.model.embedder.z_node_adapter, + self.model.embedder.z_edge_adapter, + self.model.embedder.disp_node_adapter, + self.model.embedder.disp_edge_adapter, + self.model.film_mlp, + ]: + if module is not None: + module.train() + + def on_train_start(self): + parent_hook = getattr(super(), "on_train_start", None) + if parent_hook is not None: + parent_hook() + if int(getattr(self, "global_rank", 0)) == 0: + lrs = [ + float(group["lr"]) + for optimizer in self.trainer.optimizers + for group in optimizer.param_groups + ] + print(f"[train-start-lr] lrs={lrs}", flush=True) + + def on_train_epoch_start(self): + self._set_frozen_foundation_eval() + if getattr(self, "freeze_mode_head", False): + self.latent_encoder.set_frozen_prior_backbone_eval() + parent_hook = getattr(super(), "on_train_epoch_start", None) + if parent_hook is not None: + return parent_hook() + return None + + def _get_motion_target_cache(self): + if self.motion_target_cache is not None: + return self.motion_target_cache + cache_path = self.motion_target_cache_path + if cache_path in (None, "null", ""): + return None + cache_path = os.path.expanduser(str(cache_path)) + if not os.path.exists(cache_path): + raise FileNotFoundError(f"Missing motion target cache: {cache_path}") + cache = torch.load(cache_path, map_location="cpu", weights_only=False) + require_alignment_version(cache, source=str(cache_path)) + if isinstance(cache, dict) and "motion_targets" in cache: + targets = cache["motion_targets"] + else: + raise ValueError( + f"Unsupported motion target cache format: {cache_path}. " + "Run scripts/extract_shape_fingerprints.py again to create motion_targets." + ) + out = {} + for key, value in targets.items(): + target = { + "local_cov": torch.as_tensor(value["local_cov"], dtype=torch.float32), + "cross_cov": torch.as_tensor(value["cross_cov"], dtype=torch.float32), + "dccm": torch.as_tensor(value.get("dccm", value["cross_cov"]), dtype=torch.float32), + "rmsf": torch.as_tensor(value["rmsf"], dtype=torch.float32), + "res_mask": torch.as_tensor(value.get("res_mask", torch.ones_like(torch.as_tensor(value["rmsf"]))), dtype=torch.float32), + } + for optional_field in [ + "oracle_modes", + "oracle_energy", + "oracle_mean_disp", + "gen_response_trace_anchor", + ]: + if optional_field in value: + target[optional_field] = torch.as_tensor(value[optional_field], dtype=torch.float32) + for name in self._pdb_name_variants(str(key)): + out[name] = target + if len(out) == 0: + raise ValueError(f"Motion target cache is empty: {cache_path}") + self.motion_target_cache = out + return self.motion_target_cache + + @staticmethod + def _pdb_name_variants(name): + variants = {name} + if "_" in name: + variants.add(name.replace("_", "")) + elif len(name) == 5: + variants.add(f"{name[:4]}_{name[4]}") + return variants + + def _lookup_motion_targets(self, pdb_names, device, dtype, num_res): + cache = self._get_motion_target_cache() + if cache is None: + raise ValueError( + "latent.motion_target_cache_path is required for motion-prior training; " + "run base_stages/00_extract_shape_fingerprints.sh first." + ) + rows = [] + missing = [] + required_fields = ["local_cov", "cross_cov", "rmsf"] + optional_fields = ["oracle_mean_disp", "gen_response_trace_anchor"] + needs_oracle_modes = bool(getattr(self._exp_cfg.training, "oracle_condition", False)) or ( + float(getattr(self._exp_cfg.training, "lambda_pca_align", 0.0)) > 0.0 + ) or bool(getattr(self, "collective_basis_from_data", False)) or ( + float(getattr(self._exp_cfg.training, "lambda_md_subspace", 0.0)) > 0.0 + ) or ( + float(getattr(self._exp_cfg.training, "lambda_md_subspace_trace", 0.0)) > 0.0 + ) + if needs_oracle_modes: + optional_fields = ["oracle_modes", "oracle_energy", "oracle_mean_disp"] + for name in pdb_names: + key = str(name) + value = None + resolved_name = None + for variant in self._pdb_name_variants(key): + value = cache.get(variant) + if value is not None: + resolved_name = variant + break + if value is None: + missing.append(key) + continue + if needs_oracle_modes: + missing_oracle = [field for field in ["oracle_modes", "oracle_energy"] if field not in value] + if missing_oracle: + raise ValueError( + f"Motion target cache entry {key} lacks {missing_oracle}; " + "regenerate it with scripts/extract_shape_fingerprints.py before using lambda_pca_align." + ) + if int(value["rmsf"].shape[0]) != int(num_res): + raise ValueError( + f"Motion target length mismatch for {key}: cache {value['rmsf'].shape[0]} vs batch {num_res}" + ) + device_key = (resolved_name, str(device), str(dtype)) + device_value = self.motion_target_device_cache.get(device_key) + if device_value is None: + fields = required_fields + [ + field for field in optional_fields if field in value + ] + device_value = { + field: value[field].to(device=device, dtype=dtype) + for field in fields + } + self.motion_target_device_cache[device_key] = device_value + rows.append(device_value) + if missing: + preview = ", ".join(missing[:10]) + raise KeyError(f"Missing motion targets for {len(missing)} proteins: {preview}") + out = { + field: torch.stack([row[field] for row in rows], dim=0) + for field in required_fields + } + for field in optional_fields: + if all(field in row for row in rows): + out[field] = torch.stack([row[field] for row in rows], dim=0) + return out + + def _equilibrium_spatial_dists(self, pdb_names, trans_equilibrium): + rows = [] + num_res = int(trans_equilibrium.shape[1]) + for name, coords in zip(pdb_names, trans_equilibrium): + key = ( + str(name), + num_res, + str(coords.device), + str(coords.dtype), + ) + distances = self.equilibrium_distance_cache.get(key) + if distances is None: + distances = torch.cdist( + coords.detach().float()[None], coords.detach().float()[None] + )[0] + self.equilibrium_distance_cache[key] = distances + rows.append(distances) + return torch.stack(rows, dim=0) + + def validation_step(self, batch: Any, batch_idx: int, dataloader_idx: int=0): + pdb_name = batch["pdb_name"][0] + + epoch_dir = os.path.join(self._sample_write_dir, f'epoch_{self.current_epoch}') + os.makedirs(epoch_dir, exist_ok=True) + pdb_dir = os.path.join(epoch_dir, pdb_name) + os.makedirs(pdb_dir, exist_ok=True) + + N = batch['seq'].shape[1] + batch_size = self._data_cfg.validation.max_valid_num_res_squared / N**2 + batch_size = max( + 1, + min( + self._data_cfg.validation.max_valid_batch_size, + int(batch_size/5)*5 + ) + ) + self.interpolant.set_device(batch["trans_equilibrium"].device) + # print(self.interpolant._cfg) + sampled_conformations = self._sample_multiple( + batch["trans_equilibrium"], + batch["rotmats_equilibrium"], + batch["seq"], + self.samples_per_valid_protein_per_rank, + batch_size, + self.interpolant, + ) + + + rank = dist.get_rank() + if dist.get_world_size() > 1: + # if multi-gpu, only save npy files and combine in on_validation_epoch_end + # into one pdb file. + samples_path = os.path.join(pdb_dir, f'rank_{rank}_sampled_conformations.npy') + np.save(samples_path, sampled_conformations) + else: + # if single-gpu, save pdb file directly + samples_path = os.path.join(pdb_dir, f'sampled_conformations.pdb') + au.write_prot_to_pdb( + sampled_conformations, + samples_path, + no_indexing=True + ) + + + def on_validation_epoch_end(self): + # wait until all ranks finished validation_step + if dist.is_initialized() and dist.get_world_size() > 1: + dist.barrier() # wait until all ranks wrote their .npy + + if dist.is_initialized() and dist.get_rank() != 0: + return # only rank 0 continues + + # make image saving faster: + matplotlib.use("Agg") # non-interactive, fast, no GUI needed + import matplotlib.pyplot as plt + + folder = os.path.join( + self._sample_write_dir, + f'epoch_{self.current_epoch}', + ) + valid_csv_path = os.path.join(self._sample_write_dir, 'valid.csv') + valid_csv = pd.read_csv(valid_csv_path) + all_pdb_names = valid_csv['name'].values if 'name' in valid_csv else valid_csv['pdb_name'].values + pdb_names = [] + if dist.get_world_size() > 1: + # combine samples that are saved in npy files into one pdb file + for pdb_name in all_pdb_names: + pdb_folder = os.path.join(folder, pdb_name) + if self.trainer.sanity_checking and not os.path.exists(pdb_folder): + continue + pdb_names.append(pdb_name) + + coords = [] + for rank in range(dist.get_world_size()): + samples_path = os.path.join(pdb_folder, f'rank_{rank}_sampled_conformations.npy') + coords.append(np.load(samples_path)) + os.remove(samples_path) + coords = np.concatenate(coords, axis=0) + + samples_path = os.path.join(pdb_folder, f'sampled_conformations.pdb') + au.write_prot_to_pdb( + coords, + samples_path, + no_indexing=True + ) + else: + for pdb_name in all_pdb_names: + pdb_folder = os.path.join(folder, pdb_name) + if self.trainer.sanity_checking and not os.path.exists(pdb_folder): + continue + pdb_names.append(pdb_name) + + + + if self.trainer.sanity_checking or not self._exp_cfg.use_wandb: + return + + metrics_subset = self._data_cfg.validation.metrics_subset + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=UserWarning) + data, metrics_dict, _ = calc_metrics( + pdb_names, + self._data_cfg.validation.valid_xtc_paths, + folder, + 137, + self._data_cfg.loader.num_workers, + metrics_subset=metrics_subset, + use_tqdm=self._exp_cfg.use_tqdm + ) + for key, value in metrics_dict.items(): + self._log_scalar( + f'valid_bbf_metrics/{key}', value, + on_step=False, on_epoch=True, prog_bar=False, + ) + + + af_rmsfs = None + if self._data_cfg.validation.alphaflow_valid_rmsf_path is not None and os.path.exists(self._data_cfg.validation.alphaflow_valid_rmsf_path): + with open(self._data_cfg.validation.alphaflow_valid_rmsf_path, 'r') as f: + af_rmsfs = json.load(f) + else: + af_rmsfs = None + + def _plot_rmsf(pdb_name, ax, md, bbf, af=None, rmsf_type="RMSF"): + rmse = np.sqrt(np.mean((bbf[0] - md[0])**2)) + xs = np.arange(len(md[0])) + ax.plot(xs, md[0], label="MD", c="C0") + ax.fill_between(xs, md[1], md[2], color="C0", alpha=0.5) + ax.plot(xs, bbf[0], label="BBFlow", c="C1") + ax.fill_between(xs, bbf[1], bbf[2], color="C1", alpha=0.5) + if af is not None: + ax.plot(xs, af["rmsf"], label="AlphaFlow", c="C2") + ax.fill_between(xs, af["low"], af["high"], color="C2", alpha=0.5) + ax.set_xlabel("Residue") + ax.set_ylabel(f"{rmsf_type} "+r"[$\AA$]") + ax.legend() + ax.set_title(f"{rmsf_type} {pdb_name}, Epoch {self.current_epoch}, RMSE={rmse:.3f}") + + if self._exp_cfg.use_wandb and "RMSF" in metrics_subset: + SMALL_SIZE = 20 + MEDIUM_SIZE = 24 + BIGGER_SIZE = 28 + plt.rc('font', size=SMALL_SIZE) # controls default text sizes + plt.rc('axes', titlesize=BIGGER_SIZE) # fontsize of the axes title + plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels + plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels + plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels + plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize + plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title + + for pdb_name in pdb_names: + fig = plt.figure(figsize=(10, 5)) + _plot_rmsf( + pdb_name, plt.gca(), + (data[pdb_name]["CA_ref_rmsf"], data[pdb_name]["CA_ref_rmsf_low"], data[pdb_name]["CA_ref_rmsf_high"]), + (data[pdb_name]["CA_model_rmsf"], data[pdb_name]["CA_model_rmsf_low"], data[pdb_name]["CA_model_rmsf_high"]), + af_rmsfs[pdb_name] if af_rmsfs is not None else None, + "RMSF" + ) + wandb.log({f"rmsf_plots/{pdb_name}": wandb.Image(fig)}) + plt.close(fig) + + + if "RMSF" in metrics_subset: + rmses = [] + for pdb_name in pdb_names: + rmse = np.sqrt(np.mean((data[pdb_name]["model_rmsf"] - data[pdb_name]["ref_rmsf"])**2)) + rmses.append(rmse) + self._log_scalar( + f'valid_all/{pdb_name}_rmsf_rmse', rmse, + on_step=False, on_epoch=True, prog_bar=False, + ) + + rmses = np.array(rmses) + self._log_scalar( + f'valid/rmsf_rmse', np.mean(rmses), + on_step=False, on_epoch=True, prog_bar=False, + ) + + + + def _sample_multiple(self, + trans_eq, rotmats_eq, seq, + num_samples, batch_size, + interpolant, + pdb_dir=None + ): + _, N = trans_eq.shape[:2] + diffuse_mask = torch.ones(1, N) + + sample_ids_batches = np.split( + np.arange(num_samples), + np.arange(batch_size, num_samples, batch_size) + ) + + sampled_conformations = [] + + for sample_ids in sample_ids_batches: + B = len(sample_ids) + z = self._sample_prior_z(trans_eq, rotmats_eq, seq, B) + atom37_traj, pred_traj, _ = interpolant.sample( + B, + N, + self.model, + trans_eq.repeat(B, 1, 1), + rotmats_eq.repeat(B, 1, 1, 1), + seq.repeat(B, 1, 1), + z=z, + return_trajectory=not bool( + getattr(self._infer_cfg, "final_only", True) + ) or pdb_dir is not None, + cache_static_features=bool( + getattr(self._infer_cfg, "cache_static_features", True) + ), + ) + + atom37_traj = du.to_numpy(torch.stack(atom37_traj, dim=1)) + pred_traj = du.to_numpy(torch.stack(pred_traj, dim=1)) + # B, T, N, 37, 3 + + # remove the c betas. they are not predicted by the network but rule based and have no real meaning + # Masking CB atoms + # atom37 bb order = ['N', 'CA', 'C', 'CB', 'O'] + atom37_traj[..., 3, :] = 0 + pred_traj[..., 3, :] = 0 + + for i, sample_id in enumerate(sample_ids): + sampled_conformations.append(atom37_traj[i, -1]) + + if pdb_dir is not None: + sample_dir = os.path.join(pdb_dir, f'conf_{sample_id}') + os.makedirs(sample_dir, exist_ok=True) + eu.save_traj( + atom37_traj[i, -1], + np.flip(atom37_traj[i], axis=0), + np.flip(pred_traj[i], axis=0), + du.to_numpy(diffuse_mask)[0], + output_dir=sample_dir, + ) + + sampled_conformations = np.stack(sampled_conformations, axis=0) + return sampled_conformations + + def _zero_condition(self, condition): + if condition is None: + return None + out = {} + for key, value in condition.items(): + if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}: + out[key] = torch.zeros_like(value) + else: + out[key] = value + return out + + def _scale_condition(self, condition, scale): + if condition is None or float(scale) == 1.0: + return condition + out = {} + for key, value in condition.items(): + if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}: + out[key] = value * float(scale) + else: + out[key] = value + return out + + def _shuffle_condition(self, condition, num_res): + if condition is None: + return None + device = next( + (value.device for value in condition.values() if torch.is_tensor(value)), + torch.device("cpu"), + ) + perm = torch.randperm(int(num_res), device=device) + out = {} + for key, value in condition.items(): + if not torch.is_tensor(value): + out[key] = value + elif key in {"node_cond", "disp_node_cond"} and value.ndim >= 3 and value.shape[1] == num_res: + out[key] = value[:, perm, ...] + elif key in {"edge_cond", "disp_edge_cond"} and value.ndim >= 4 and value.shape[1] == num_res and value.shape[2] == num_res: + out[key] = value[:, perm, ...][:, :, perm, ...] + else: + out[key] = value + return out + + def _sample_prior_z(self, trans_eq, rotmats_eq, seq, batch_size): + if not getattr(self, "latent_enabled", False): + return None + device = trans_eq.device + _, num_res = trans_eq.shape[:2] + res_mask = torch.ones(1, num_res, device=device) + infer_cfg = getattr(self, "_infer_cfg", None) + z_per_sample = bool(getattr(infer_cfg, "z_per_sample", False)) if infer_cfg is not None else False + z_per_sample = z_per_sample or bool(getattr(self.latent_encoder, "sample_coefficients", False)) + condition_mode = str(getattr(infer_cfg, "condition_mode", "real")) if infer_cfg is not None else "real" + condition_scale = float(getattr(infer_cfg, "condition_scale", 1.0)) if infer_cfg is not None else 1.0 + # Per-mode tilt, read from the same place as condition_scale. The gain vector is + # fixed per protein from that protein's coefficient covariance, so it has to be + # set after the prior is computed -- see below. Zero leaves the gain unset and + # reproduces every existing result bit for bit. + tilt_alpha = (float(getattr(infer_cfg, "coefficient_tilt_alpha", 0.0) or 0.0) + if infer_cfg is not None else 0.0) + self.latent_encoder._tilt_gain = None + with torch.no_grad(): + # Fix the tilt gain for THIS protein before any sample is drawn: it is derived + # from the protein's own coefficient covariance and must be identical across + # its samples, or the transformed covariance is not G Gamma G and the + # linearised gate no longer describes what the sampler does. + if tilt_alpha != 0.0: + from bbflow.models.collective import mixture_mean_and_covariance + prior_for_tilt, _ = self.latent_encoder.forward_prior( + trans_eq, rotmats_eq, seq, res_mask) + _, cov_for_tilt = mixture_mean_and_covariance( + prior_for_tilt["mixture_logits"], prior_for_tilt["mixture_mu"], + prior_for_tilt["mixture_scale_tril"]) + self.latent_encoder.set_tilt(tilt_alpha, cov_for_tilt) + if z_per_sample: + trans_in = trans_eq.repeat(batch_size, 1, 1) + rot_in = rotmats_eq.repeat(batch_size, 1, 1, 1) + seq_in = seq.repeat(batch_size, 1, 1) + mask_in = res_mask.repeat(batch_size, 1) + z = self.latent_encoder.sample_prior_z(trans_in, rot_in, seq_in, mask_in) + else: + z = self.latent_encoder.sample_prior_z(trans_eq, rotmats_eq, seq, res_mask) + z = self.latent_encoder.repeat_condition(z, batch_size) + if condition_mode == "real": + pass + elif condition_mode == "zero": + z = self._zero_condition(z) + elif condition_mode == "shuffled": + z = self._shuffle_condition(z, num_res) + elif condition_mode in ("disp_only", "mode_only"): + # Channel ablation. The conditioning splits into two groups with + # different gauge behaviour: `node_cond` and `edge_cond` are indexed by + # mode, so they change under U -> U R and carry no consistent meaning + # across proteins, while `disp_node_cond` and `disp_edge_cond` are built + # from the displacement field sum_k c_k u_k and are gauge-invariant. + # Every trained objective constrains U Gamma U^T, which is also + # gauge-invariant -- so an objective can shape it well while the + # generator faces per-mode coordinates whose meaning varies per protein. + # If zeroing the gauge-dependent pair changes nothing, the generator was + # already ignoring them and all four objective failures share one cause. + drop = (("node_cond", "edge_cond") if condition_mode == "disp_only" + else ("disp_node_cond", "disp_edge_cond")) + z = {k: (torch.zeros_like(v) if k in drop and torch.is_tensor(v) else v) + for k, v in z.items()} + else: + raise ValueError(f"Unknown inference.condition_mode={condition_mode}") + z = self._scale_condition(z, condition_scale) + if self.collective_enabled: + z = dict(z) + z["collective_group_index"] = torch.zeros( + batch_size, device=device, dtype=torch.long + ) + return z + + def on_load_checkpoint(self, checkpoint): + super().on_load_checkpoint(checkpoint) + # If using a Gafl checkpoint, don't use weights of node_embedder and edge_embedder + new_state_dict = {} + current_state = self.state_dict() + for k,v in checkpoint["state_dict"].items(): + if 'node_embedder' in k: + continue + if 'edge_embedder' in k: + continue + if k not in current_state: + continue + if current_state[k].shape != v.shape: + continue + new_state_dict[k] = v + for k,v in self.model.state_dict().items(): + if f"model.{k}" not in new_state_dict: + new_state_dict[f"model.{k}"] = v + for k, v in current_state.items(): + if k not in new_state_dict: + new_state_dict[k] = v + checkpoint['state_dict'] = new_state_dict + + if self.reset_optimizer_on_load: + optimizers = self.configure_optimizers() + if isinstance(optimizers, tuple): + optimizers = optimizers[0] + lr_schedulers = optimizers[1] + checkpoint['optimizer_states'] = [o.state_dict() for o in optimizers] + checkpoint['lr_schedulers'] = [s.state_dict() for s in lr_schedulers] + else: + checkpoint['optimizer_states'] = [optimizers.state_dict()] + + if self.reset_epoch: + checkpoint["epoch"] = 0 + checkpoint["global_step"] = 0 + del checkpoint["loops"] + + def _oracle_group_z(self, noisy_batch): + device = noisy_batch["res_mask"].device + num_batch, num_res = noisy_batch["res_mask"].shape[:2] + oracle_targets = self._lookup_motion_targets( + noisy_batch["pdb_name"], + device=device, + dtype=torch.float32, + num_res=num_res, + ) + missing = [field for field in ["oracle_modes", "oracle_energy", "oracle_mean_disp"] if field not in oracle_targets] + if missing: + raise ValueError( + f"Oracle condition training requires {missing} in latent.motion_target_cache_path; " + "rerun base_stages/00_extract_shape_fingerprints.sh with the updated code." + ) + condition = self.latent_encoder.oracle_condition_from_targets( + noisy_batch["trans_1"], + noisy_batch["trans_equilibrium"], + noisy_batch["rotmats_equilibrium"], + noisy_batch["res_mask"], + oracle_targets, + ) + latent_metrics = {} + if self._diagnostic_step(): + latent_metrics.update(self.latent_encoder.motion_metrics(condition, noisy_batch["res_mask"])) + coeff = condition["mode_coefficients"].detach().float() + centered = condition["oracle_centered_disp"].detach().float() + recon = condition["oracle_recon_disp"].detach().float() + mask = noisy_batch["res_mask"].float()[:, :, None] + recon_error = ((centered - recon).square() * mask).sum().sqrt() + recon_denom = (centered.square() * mask).sum().sqrt().clamp_min(1e-8) + latent_metrics.update({ + "oracle_condition_active": noisy_batch["res_mask"].new_ones(()), + "oracle_coeff_abs": coeff.abs().mean(), + "oracle_coeff_std": coeff.std(), + "oracle_recon_rel_error": (recon_error / recon_denom).detach(), + "enm_warmup_active": noisy_batch["res_mask"].new_zeros(()), + }) + motion_loss = noisy_batch["res_mask"].new_zeros(()) + shape_baseline_error = noisy_batch["res_mask"].new_zeros(()) + return ( + condition, + torch.arange(num_batch, device=device, dtype=torch.long), + latent_metrics, + motion_loss, + shape_baseline_error, + ) + + def _motion_loss_weights(self): + training_cfg = self._exp_cfg.training + weights = { + "local_cov_loss": float(getattr(training_cfg, "lambda_local_cov", 1.0)), + "cross_cov_loss": float(getattr(training_cfg, "lambda_cross_cov", 1.0)), + "rmsf_loss": float(getattr(training_cfg, "lambda_rmsf", 0.25)), + } + lambda_pca_align = float(getattr(training_cfg, "lambda_pca_align", 0.0)) + if lambda_pca_align > 0.0: + weights["pca_align_loss"] = lambda_pca_align + return weights + + def _diagnostic_step(self): + interval = int(getattr( + self._exp_cfg.training, "diagnostic_interval_steps", 1 + )) + return interval > 0 and int(self.global_step) % interval == 0 + + def _collective_shared_time(self, batch): + if "group_index" not in batch: + raise ValueError("CMFM training requires grouped batches with group_index") + group_index = batch["group_index"].long() + groups, counts = torch.unique(group_index, sorted=True, return_counts=True) + if torch.any(counts <= self.collective_rank): + raise ValueError( + f"every CMFM group must contain more than rank={self.collective_rank} " + f"particles; observed sizes={counts.detach().cpu().tolist()}" + ) + group_time = self.interpolant.sample_t(int(groups.numel())).float() + time = torch.empty( + group_index.shape[0], 1, device=group_index.device, dtype=torch.float32 + ) + for index, group in enumerate(groups): + time[group_index == group] = group_time[index] + return time + + def _collective_group_prior_condition(self, noisy_batch): + """Evaluate the equilibrium-only prior once per group and broadcast it.""" + if "group_index" not in noisy_batch: + raise ValueError("CMFM training requires group_index in every batch") + group_index = noisy_batch["group_index"].long() + groups, inverse, counts = torch.unique( + group_index, + sorted=True, + return_inverse=True, + return_counts=True, + ) + if torch.any(counts <= self.collective_rank): + raise ValueError( + f"every CMFM group must contain more than rank={self.collective_rank} " + f"particles; observed sizes={counts.detach().cpu().tolist()}" + ) + + pdb_names = noisy_batch.get("pdb_name") + if pdb_names is not None: + group_ids = group_index.detach().cpu().tolist() + if len(pdb_names) != len(group_ids): + raise ValueError("pdb_name must have one entry per CMFM particle") + group_names = {} + for group_id, pdb_name in zip(group_ids, pdb_names): + previous = group_names.setdefault(group_id, pdb_name) + if pdb_name != previous: + raise ValueError( + "every CMFM group must contain particles from one protein; " + f"group={group_id} contains {previous!r} and {pdb_name!r}" + ) + + representative_indices = torch.stack([ + torch.nonzero(group_index == group, as_tuple=False)[0, 0] + for group in groups + ]) + representative_condition, _ = self.latent_encoder.forward_prior( + noisy_batch["trans_equilibrium"].index_select( + 0, + representative_indices, + ), + noisy_batch["rotmats_equilibrium"].index_select( + 0, + representative_indices, + ), + noisy_batch["seq"].index_select(0, representative_indices), + noisy_batch["res_mask"].index_select(0, representative_indices), + ) + + condition = {} + num_groups = int(groups.numel()) + for name, value in representative_condition.items(): + if not torch.is_tensor(value) or value.ndim == 0: + condition[name] = value + continue + if value.shape[0] != num_groups: + raise ValueError( + f"prior condition {name} must have leading group dimension " + f"{num_groups}, got shape={tuple(value.shape)}" + ) + condition[name] = value.index_select(0, inverse) + + if self.collective_basis_from_data: + if pdb_names is None: + raise ValueError( + "collective_basis_from_data needs pdb_name in the batch to " + "look up the cached principal directions" + ) + representative_names = [ + pdb_names[int(index)] for index in representative_indices + ] + targets = self._lookup_motion_targets( + representative_names, + device=group_index.device, + dtype=torch.float32, + num_res=int(noisy_batch["res_mask"].shape[1]), + ) + if "oracle_modes" not in targets or "oracle_energy" not in targets: + raise ValueError( + "collective_basis_from_data requires oracle_modes and " + "oracle_energy in the motion target cache; regenerate it with " + "scripts/extract_shape_fingerprints.py" + ) + rank = self.collective_rank + # oracle_modes are the right singular vectors of the centred MD + # displacements, so each is already unit norm in the flattened 3N + # space and they are sorted by variance -- the same convention the + # q-derived basis used, which makes this a drop-in replacement. + # oracle_energy holds the variances along them, so the target + # covariance is exactly diagonal and needs no estimation from the + # group at all. + basis = targets["oracle_modes"][:, :, :rank, :].contiguous() + energy = targets["oracle_energy"][:, :rank].contiguous() + if basis.shape[2] != rank or energy.shape[1] != rank: + raise ValueError( + f"cached oracle modes provide fewer than collective_rank={rank} " + f"directions: modes={tuple(basis.shape)} energy={tuple(energy.shape)}" + ) + dtype = condition["collective_basis_global"].dtype + condition["collective_basis_global"] = basis.index_select( + 0, inverse + ).to(dtype=dtype) + condition["collective_target_variance"] = energy.index_select( + 0, inverse + ).to(dtype=dtype) + condition["collective_target_covariance"] = torch.diag_embed( + energy + ).index_select(0, inverse).to(dtype=dtype) + # The retained fraction is a property of the q-implied spectrum and + # is meaningless once the basis comes from the data. Report the + # share of MD variance the retained directions carry instead. + total = targets["oracle_energy"].sum(dim=-1).clamp_min(1e-8) + condition["collective_retained_fraction"] = ( + energy.sum(dim=-1) / total + ).index_select(0, inverse).to(dtype=dtype) + return condition + + def _collective_population_covariance(self, condition): + """Second moment in the collective basis, when it is a data quantity. + + Only returned for the data-anchored basis. With the q-derived basis + ``collective_target_covariance`` is the model's own implied variance -- + measured at 2 to 800 times the observed variance along the same + directions -- so normalising by it would put the model's belief on both + sides of the comparison. + """ + if not self.collective_basis_from_data: + return None + return condition.get("collective_target_covariance") + + def _latent_group_z(self, noisy_batch): + self._gen_cov_targets = None + if bool(getattr(self._exp_cfg.training, "oracle_condition", False)): + return self._oracle_group_z(noisy_batch) + device = noisy_batch["res_mask"].device + num_batch, num_res = noisy_batch["res_mask"].shape[:2] + if self.collective_enabled: + prior_condition = self._collective_group_prior_condition(noisy_batch) + else: + prior_condition, _ = self.latent_encoder.forward_prior( + noisy_batch["trans_equilibrium"], + noisy_batch["rotmats_equilibrium"], + noisy_batch["seq"], + noisy_batch["res_mask"], + ) + condition = prior_condition + latent_metrics = {} + if self.collective_enabled: + latent_metrics["collective_retained_fraction"] = prior_condition[ + "collective_retained_fraction" + ].detach().float().mean() + latent_metrics.update({ + "prior_hidden_abs_max": prior_condition[ + "prior_hidden_abs_max" + ].detach().float().amax(), + "prior_raw_mode_abs_max": prior_condition[ + "prior_raw_mode_abs_max" + ].detach().float().amax(), + "prior_raw_mode_rms_min": prior_condition[ + "prior_raw_mode_rms_min" + ].detach().float().amin(), + "prior_raw_mode_rms_max": prior_condition[ + "prior_raw_mode_rms_max" + ].detach().float().amax(), + "prior_mode_norm_min": prior_condition[ + "mode_norm" + ].detach().float().amin(), + "prior_mode_norm_max": prior_condition[ + "mode_norm" + ].detach().float().amax(), + "prior_q_mu_abs_max": prior_condition[ + "mixture_mu" + ].detach().float().abs().amax(), + "prior_q_scale_abs_max": prior_condition[ + "mixture_scale_tril" + ].detach().float().abs().amax(), + "collective_target_variance_min": prior_condition[ + "collective_target_variance" + ].detach().float().amin(), + "collective_target_variance_max": prior_condition[ + "collective_target_variance" + ].detach().float().amax(), + # QR backward is the second suspect: the gauge fixing can stay + # finite in the forward while its Jacobian blows up. + "prior_qr_diag_abs_min": prior_condition[ + "prior_qr_diag_abs_min" + ].detach().float().amin(), + "prior_qr_rel_diag_min": prior_condition[ + "prior_qr_rel_diag_min" + ].detach().float().amin(), + "prior_qr_condition_max": prior_condition[ + "prior_qr_condition" + ].detach().float().amax(), + }) + if self._diagnostic_step(): + latent_metrics.update(self.latent_encoder.motion_metrics(prior_condition, noisy_batch["res_mask"])) + shape_baseline_error = noisy_batch["res_mask"].new_zeros(()) + motion_loss = noisy_batch["res_mask"].new_zeros(()) + q_fit_loss = noisy_batch["res_mask"].new_zeros(()) + mode_recon_loss = noisy_batch["res_mask"].new_zeros(()) + # Must be the pre-gauge modes: u_global is orthonormal by construction, so + # penalising it reports ~0 and leaves the mode head free to collapse -- + # which is exactly what makes the gauge factorisation ill-conditioned. + mode_orth_loss = self.latent_encoder.mode_orthogonality_loss( + prior_condition.get("raw_modes_global", prior_condition["u_global"]), + noisy_batch["res_mask"], + ) + motion_targets = None + + enm_warmup_epochs = int(getattr(self._exp_cfg.training, "enm_warmup_epochs", 0)) + in_enm_warmup = bool(self.motion_loss_enabled and int(self.current_epoch) < enm_warmup_epochs) + if in_enm_warmup: + loss_parts = self.latent_encoder.enm_initialization_loss( + prior_condition, + noisy_batch["trans_equilibrium"], + noisy_batch["res_mask"], + ) + warmup_weight = float(getattr(self._exp_cfg.training, "lambda_enm_warmup", 1.0)) + motion_loss = warmup_weight * loss_parts["enm_warmup_loss"] + latent_metrics.update(loss_parts) + latent_metrics["enm_warmup_active"] = noisy_batch["res_mask"].new_ones(()) + else: + if self.motion_loss_enabled: + motion_targets = self._lookup_motion_targets( + noisy_batch["pdb_name"], + device=device, + dtype=prior_condition["local_cov_pred"].dtype, + num_res=num_res, + ) + self._gen_cov_targets = motion_targets + with torch.autocast(device_type=device.type, enabled=False): + spatial_dists = self._equilibrium_spatial_dists( + noisy_batch["pdb_name"], + noisy_batch["trans_equilibrium"].float(), + ) + loss_parts = self.latent_encoder.motion_recon_loss( + prior_condition, + motion_targets, + noisy_batch["res_mask"], + spatial_dists=spatial_dists, + ) + weights = self._motion_loss_weights() + motion_loss = sum(weight * loss_parts[name] for name, weight in weights.items()) + latent_metrics.update(loss_parts) + if self._diagnostic_step(): + latent_metrics.update(self.latent_encoder.motion_alignment_metrics( + prior_condition, + motion_targets, + noisy_batch["res_mask"], + spatial_dists, + )) + latent_metrics["enm_warmup_active"] = noisy_batch["res_mask"].new_zeros(()) + + if bool(getattr(self._exp_cfg.training, "per_frame_coeff_condition", False)): + mean_disp = None if motion_targets is None else motion_targets.get("oracle_mean_disp") + with torch.autocast(device_type=device.type, enabled=False): + condition, coeff_target = self.latent_encoder.frame_condition_from_projection( + noisy_batch["trans_1"].float(), + noisy_batch["trans_equilibrium"].float(), + noisy_batch["rotmats_equilibrium"], + noisy_batch["res_mask"], + prior_condition, + mean_disp=mean_disp, + ) + q_fit_loss = self.latent_encoder.mixture_nll( + prior_condition, coeff_target.detach() + ) + mode_recon_loss = condition["projection_recon_loss"].float().mean() + centered_recon = condition["projection_recon_rel_error"].detach().float().mean() + latent_metrics.update({ + "mode_recon_loss": mode_recon_loss.detach(), + "q_nll_loss": q_fit_loss.detach(), + "q_nll_per_dim": q_fit_loss.detach() / float(self.latent_encoder.num_modes), + "mode_coeff_abs": coeff_target.detach().float().abs().mean(), + "mode_coeff_std": coeff_target.detach().float().std(), + "mode_recon_rel_error": centered_recon, + "mode_recon_centered_rel_error": centered_recon, + "mode_recon_uncentered_rel_error": condition[ + "projection_uncentered_recon_rel_error" + ].detach().float().mean(), + }) + if self._diagnostic_step(): + # Same reason as mode_orth_loss: measured on u_global these + # collinearity metrics are constant-by-construction. + gram_metrics = self.latent_encoder.mode_gram_diagnostics( + prior_condition.get( + "raw_modes_global", prior_condition["u_global"] + ), + noisy_batch["res_mask"], + ) + latent_metrics.update({ + "mode_gram_min_eig": gram_metrics["mode_gram_min_eig"].detach().float().mean(), + "mode_gram_condition": gram_metrics["mode_gram_condition"].detach().float().mean(), + "mode_max_cosine_abs": gram_metrics["mode_max_cosine_abs"].detach().float().mean(), + }) + + lambda_motion = float(getattr(self._exp_cfg.training, "lambda_motion", 1.0)) + lambda_q = float(getattr(self._exp_cfg.training, "lambda_q", 1.0)) + lambda_mode_orth = float(getattr(self._exp_cfg.training, "lambda_mode_orth", 0.0)) + lambda_mode_recon = float(getattr(self._exp_cfg.training, "lambda_mode_recon", 0.0)) + lambda_md_subspace = float( + getattr(self._exp_cfg.training, "lambda_md_subspace", 0.0) + ) + lambda_md_subspace_trace = float( + getattr(self._exp_cfg.training, "lambda_md_subspace_trace", 0.0) + ) + md_subspace_loss = noisy_batch["res_mask"].new_zeros(()) + if lambda_md_subspace > 0.0 or lambda_md_subspace_trace > 0.0: + # Targets carry the reference eigenbasis; `motion_targets` is already the + # cache row when the motion prior is on, otherwise fetch it here. + subspace_targets = motion_targets + if subspace_targets is None or "oracle_modes" not in subspace_targets: + subspace_targets = self._lookup_motion_targets( + noisy_batch["pdb_name"], + device=device, + dtype=prior_condition["u_global"].dtype, + num_res=num_res, + ) + with torch.autocast(device_type=device.type, enabled=False): + # prior_condition, not the per-frame condition: the quantity to align + # with the reference covariance is q(c | x_eq), which is what inference + # samples from. The per-frame condition carries coefficients read off + # the target frame and is only available during training. + subspace_parts = self.latent_encoder.md_subspace_shape_loss( + prior_condition, + subspace_targets, + noisy_batch["res_mask"], + weight_exp=float( + getattr(self._exp_cfg.training, "md_subspace_weight_exp", 0.0) + ), + ) + md_subspace_loss = ( + lambda_md_subspace * subspace_parts["md_subspace_shape_loss"] + + lambda_md_subspace_trace * subspace_parts["md_subspace_trace_loss"] + ) + latent_metrics.update({ + key: value.detach() for key, value in subspace_parts.items() + }) + latent_regularizer = ( + lambda_motion * motion_loss + + lambda_q * q_fit_loss + + lambda_mode_orth * mode_orth_loss + + lambda_mode_recon * mode_recon_loss + + md_subspace_loss + ) + latent_metrics["motion_loss"] = motion_loss.detach() + latent_metrics["mode_orth_loss"] = mode_orth_loss.detach() + latent_metrics["mode_recon_loss"] = mode_recon_loss.detach() + latent_metrics["latent_regularizer_loss"] = latent_regularizer.detach() + if self.collective_enabled: + if "group_index" not in noisy_batch: + raise ValueError("CMFM training requires group_index in every batch") + group_index = noisy_batch["group_index"].long() + condition = dict(condition) + condition["collective_group_index"] = group_index + else: + group_index = torch.arange(num_batch, device=device, dtype=torch.long) + return ( + condition, + group_index, + latent_metrics, + latent_regularizer, + shape_baseline_error, + ) + + @staticmethod + def _condition_with_scale(condition, scale): + if not isinstance(condition, dict): + return condition * scale + out = {} + for key, value in condition.items(): + if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}: + out[key] = value * scale + else: + out[key] = value + return out + + def _condition_cycle_loss(self, noisy_batch, model_output, condition): + lambda_cycle = float(getattr(self._exp_cfg.training, "lambda_condition_cycle", 0.0)) + zero = model_output["pred_trans"].new_zeros(()) + if lambda_cycle == 0.0 or condition is None or not isinstance(condition, dict): + return zero, {} + required = {"mode_coefficients", "u_global", "projection_mean_disp"} + if any(key not in condition for key in required): + return zero, {} + + device = model_output["pred_trans"].device + with torch.autocast(device_type=device.type, enabled=False): + pred_trans = model_output["pred_trans"].float() + trans_eq = noisy_batch["trans_equilibrium"].to(device=device, dtype=torch.float32) + res_mask = noisy_batch["res_mask"].to(device=device, dtype=torch.float32) + mean_disp = condition["projection_mean_disp"].to(device=device, dtype=torch.float32).detach() + modes = condition["u_global"].to(device=device, dtype=torch.float32).detach() + target_coeff = condition["mode_coefficients"].to(device=device, dtype=torch.float32).detach() + + pred_disp = self.latent_encoder.relative_displacement( + pred_trans, + trans_eq, + res_mask, + ) + pred_centered = pred_disp - mean_disp + pred_coeff = self.latent_encoder.project_displacement_lstsq( + pred_centered, + modes, + res_mask, + ridge=float(getattr(self.latent_encoder, "q_lstsq_ridge", 1e-4)), + detach_modes=True, + ) + diff = pred_coeff - target_coeff + denom = target_coeff.norm(dim=-1).clamp_min(1e-8) + rel_error = diff.norm(dim=-1) / denom + raw_loss = rel_error.mean() + cosine = torch.nn.functional.cosine_similarity( + pred_coeff, + target_coeff, + dim=-1, + eps=1e-8, + ).mean() + + weighted_loss = lambda_cycle * raw_loss + metrics = { + "condition_cycle_loss": raw_loss.detach(), + "condition_cycle_weighted_loss": weighted_loss.detach(), + "condition_cycle_rel_error": rel_error.detach().mean(), + "condition_cycle_cosine": cosine.detach(), + } + return weighted_loss, metrics + + def _initial_generator_response_teacher(self): + if not hasattr(self, "_gen_response_teacher_model"): + self._gen_response_teacher_model = None + if self._gen_response_teacher_model is None: + teacher = copy.deepcopy(self.model) + teacher.eval() + for param in teacher.parameters(): + param.requires_grad_(False) + self._gen_response_teacher_model = teacher + return self._gen_response_teacher_model + + def _generator_response_cov_loss(self, noisy_batch, condition): + """Train generator response shape without rewarding global expansion. + + v2 samples multiple antithetic coefficient perturbations, computes the + generator's central-difference responses, and matches only the + trace-normalized response covariance shape to MD targets. A weak optional + frozen-initial teacher trace anchor keeps response amplitude near the + A30/start checkpoint under the same ``t`` and coefficient perturbations. + """ + lambda_gen = float(getattr(self._exp_cfg.training, "lambda_generator_cov", 0.0)) + zero = noisy_batch["res_mask"].new_zeros(()) + if lambda_gen == 0.0 or condition is None or not isinstance(condition, dict): + return zero, {} + targets = getattr(self, "_gen_cov_targets", None) + if targets is None or "local_cov" not in targets or "rmsf" not in targets: + return zero, {} + required = ("u_global", "mixture_logits", "mixture_mu", "mixture_scale_tril") + if any(key not in condition for key in required): + return zero, {} + use_cross = bool(getattr(self._exp_cfg.training, "generator_cov_use_cross", False)) + if use_cross and "cross_cov" not in targets: + use_cross = False + + # t = 1 is clean, t = 0 is pure noise; mid-high noise is low-to-mid t. + t_min = float(getattr(self._exp_cfg.training, "generator_cov_t_min", 0.1)) + t_max = float(getattr(self._exp_cfg.training, "generator_cov_t_max", 0.6)) + t_vec = torch.squeeze(noisy_batch["t"]).reshape(-1).float() + sample_weight = ((t_vec >= t_min) & (t_vec <= t_max)).to(dtype=t_vec.dtype) + + scale = float(getattr(self._exp_cfg.training, "generator_cov_delta_scale", 1.0)) + num_deltas = int(getattr(self._exp_cfg.training, "generator_cov_num_deltas", 2)) + num_deltas = max(num_deltas, 2) + student_chunk_deltas = int( + getattr(self._exp_cfg.training, "generator_cov_student_chunk_deltas", 1) + ) + student_chunk_deltas = max(1, min(student_chunk_deltas, num_deltas)) + teacher_anchor = bool(getattr(self._exp_cfg.training, "generator_cov_initial_trace_anchor", True)) + teacher_num_deltas = int(getattr(self._exp_cfg.training, "generator_cov_teacher_num_deltas", 1)) + teacher_num_deltas = max(1, min(teacher_num_deltas, num_deltas)) + teacher_reuse_student_delta = bool( + getattr(self._exp_cfg.training, "generator_cov_teacher_reuse_student_delta", True) + ) + teacher_trace_denominator = str( + getattr(self._exp_cfg.training, "generator_cov_teacher_trace_denominator", "teacher") + ) + # "md_trace" (default) anchors the response magnitude to the cached MD trace. + # "teacher_trace" is retained only for reproducing the old runs: the frozen teacher + # is copied at step 0 with zero-initialized condition adapters, so its response to c + # is identically zero and the anchor collapses the student's response to zero. + amplitude_anchor = str( + getattr(self._exp_cfg.training, "generator_cov_amplitude_anchor", "md_trace") + ) + rollout_enabled = bool( + getattr(self._exp_cfg.training, "generator_cov_rollout_calibration", False) + ) + if rollout_enabled and amplitude_anchor == "md_trace": + amplitude_anchor = "rollout_trace" + if not teacher_anchor: + amplitude_anchor = "none" + use_teacher = amplitude_anchor == "teacher_trace" + cached_teacher_trace = targets.get("gen_response_trace_anchor") if use_teacher else None + teacher_model = ( + self._initial_generator_response_teacher() + if use_teacher and cached_teacher_trace is None + else None + ) + with torch.autocast(device_type=noisy_batch["res_mask"].device.type, enabled=False): + logits = condition["mixture_logits"].detach().float() + mu = condition["mixture_mu"].detach().float() + probs = torch.softmax(logits, dim=-1) + mu_bar = torch.einsum("bm,bmk->bk", probs, mu) + + u_global = condition["u_global"].detach() + rotmats_eq = noisy_batch["rotmats_equilibrium"] + res_mask = noisy_batch["res_mask"] + def _concat_conditions(conditions): + out = {} + keys = conditions[0].keys() + local_batch_size = None + for value in conditions[0].values(): + if torch.is_tensor(value) and value.dim() > 0: + local_batch_size = value.shape[0] + break + for key in keys: + value = conditions[0][key] + if ( + local_batch_size is not None + and torch.is_tensor(value) + and value.shape[:1] == (local_batch_size,) + ): + out[key] = torch.cat([cond[key] for cond in conditions], dim=0) + else: + out[key] = value + return out + + def _expand_batch(batch, repeats): + out = {} + local_batch_size = batch["res_mask"].shape[0] + for key, value in batch.items(): + if key == "z": + continue + if torch.is_tensor(value) and value.shape[:1] == (local_batch_size,): + out[key] = torch.cat([value for _ in range(repeats)], dim=0) + elif isinstance(value, (list, tuple)) and len(value) == local_batch_size: + out[key] = list(value) * repeats + else: + out[key] = value + return out + + use_checkpoint = bool(getattr(self._exp_cfg.training, "generator_cov_checkpoint", True)) + trans_eq = noisy_batch["trans_equilibrium"] + conditions = [] + for _ in range(num_deltas): + c_sample, _ = self.latent_encoder.sample_coefficients_from_q(condition) + c_sample = c_sample.detach().float() + delta = (c_sample - mu_bar) * scale + c_plus = mu_bar + delta + c_minus = mu_bar - delta + cond_plus = self.latent_encoder.condition_from_mode_coefficients( + u_global, c_plus, rotmats_eq, res_mask, include_statistics=False + ) + cond_minus = self.latent_encoder.condition_from_mode_coefficients( + u_global, c_minus, rotmats_eq, res_mask, include_statistics=False + ) + conditions.extend([cond_plus, cond_minus]) + + batch_size = res_mask.shape[0] + response_chunks = [] + for start_delta in range(0, num_deltas, student_chunk_deltas): + end_delta = min(num_deltas, start_delta + student_chunk_deltas) + chunk_conditions = conditions[2 * start_delta : 2 * end_delta] + chunk_num_deltas = end_delta - start_delta + merged_condition = _concat_conditions(chunk_conditions) + merged_batch = _expand_batch(noisy_batch, repeats=len(chunk_conditions)) + merged_batch["z"] = merged_condition + + def _pred_trans_merged(z_cond): + probe_batch = dict(merged_batch) + probe_batch["z"] = z_cond + return self.model(probe_batch)["pred_trans"] + + if use_checkpoint: + pred_merged = torch.utils.checkpoint.checkpoint( + _pred_trans_merged, merged_condition, use_reentrant=False + ) + else: + pred_merged = _pred_trans_merged(merged_condition) + + pred_merged = pred_merged.reshape( + chunk_num_deltas, 2, batch_size, *pred_merged.shape[1:] + ) + pred_plus = pred_merged[:, 0].reshape( + chunk_num_deltas * batch_size, *pred_merged.shape[3:] + ) + pred_minus = pred_merged[:, 1].reshape( + chunk_num_deltas * batch_size, *pred_merged.shape[3:] + ) + trans_eq_rep = trans_eq[None].expand( + chunk_num_deltas, -1, -1, -1 + ).reshape(chunk_num_deltas * batch_size, *trans_eq.shape[1:]) + res_mask_rep = res_mask[None].expand( + chunk_num_deltas, -1, -1 + ).reshape(chunk_num_deltas * batch_size, *res_mask.shape[1:]) + disp_plus = self.latent_encoder.relative_displacement( + pred_plus.float(), trans_eq_rep.float(), res_mask_rep + ) + disp_minus = self.latent_encoder.relative_displacement( + pred_minus.float(), trans_eq_rep.float(), res_mask_rep + ) + chunk_response = 0.5 * (disp_plus - disp_minus) + chunk_response = chunk_response.reshape( + chunk_num_deltas, batch_size, *chunk_response.shape[1:] + ) + response_chunks.append(chunk_response) + response_deltas = torch.cat(response_chunks, dim=0) + + def _response_trace(response, mask_value): + resp = response.float() + if resp.dim() == 3: + resp = resp[None] + resp = resp * mask_value[None, :, :, None].float() + local = torch.einsum("sbni,sbnj->bnij", resp, resp) / float(resp.shape[0]) + return ( + torch.diagonal(local, dim1=-2, dim2=-1).sum(dim=-1) + * mask_value.float() + ).sum(dim=-1).clamp_min(1e-8) + + def _trim_residue_dims(value, max_res): + if not torch.is_tensor(value): + return value + if value.dim() >= 2 and value.shape[1] == res_mask.shape[1]: + value = value[:, :max_res, ...] + if value.dim() >= 3 and value.shape[2] == res_mask.shape[1]: + value = value[:, :, :max_res, ...] + return value + + def _index_first_dim(value, example_idx, max_res=None): + if torch.is_tensor(value) and value.shape[:1] == (batch_size,): + value = value.index_select(0, example_idx) + if max_res is not None: + value = _trim_residue_dims(value, max_res) + return value + if isinstance(value, (list, tuple)) and len(value) == batch_size: + return [value[int(i)] for i in example_idx.detach().cpu().tolist()] + return value + + def _slice_condition(cond, example_idx, max_res=None): + out = {} + for key, value in cond.items(): + out[key] = _index_first_dim(value, example_idx, max_res=max_res) + return out + + def _slice_batch(batch, example_idx, max_res=None): + out = {} + for key, value in batch.items(): + if key == "z": + continue + out[key] = _index_first_dim(value, example_idx, max_res=max_res) + return out + + def _rollout_final_pred_trans(probe_batch, steps): + # Faithful mirror of the real inference sampler (interpolant_bbflow.sample): + # the caller has already placed the SHARED prior-noise x0 into + # trans_t/rotmats_t. Integrate the full linspace(min_t, 1, steps+1) grid + # with the exact euler steps inference uses (scalar t_1/d_t), then return + # the final clean pred_trans. This is what makes T_full the real-sampler + # c-response instead of a coarse t->1 continuation of the training state. + rollout_batch = dict(probe_batch) + rollout_batch.pop("trans_sc", None) + rollout_batch["_embedder_static"] = self.model.prepare_inference_static(rollout_batch) + trans_current = rollout_batch["trans_t"] + rotmats_current = rollout_batch["rotmats_t"] + n = trans_current.shape[0] + device = trans_current.device + min_t = float(getattr(self._interpolant_cfg, "min_t", 1e-2)) + ts = torch.linspace(min_t, 1.0, int(steps) + 1, device=device) + was_training = self.model.training + self.model.eval() + try: + t_1 = ts[0] + for t_2 in ts[1:]: + rollout_batch["trans_t"] = trans_current + rollout_batch["rotmats_t"] = rotmats_current + rollout_batch["t"] = torch.ones((n, 1), device=device) * t_1 + model_out = self.model(rollout_batch) + pred_trans_1 = model_out["pred_trans"] + pred_rotmats_1 = model_out["pred_rotmats"] + if self._interpolant_cfg.self_condition: + rollout_batch["trans_sc"] = pred_trans_1.detach() + d_t = t_2 - t_1 + trans_current = self.interpolant._trans_euler_step( + d_t, t_1, pred_trans_1, trans_current + ) + rotmats_current = self.interpolant._rots_euler_step( + d_t, t_1, pred_rotmats_1, rotmats_current + ) + t_1 = t_2 + rollout_batch["trans_t"] = trans_current + rollout_batch["rotmats_t"] = rotmats_current + rollout_batch["t"] = torch.ones((n, 1), device=device) * ts[-1] + model_out = self.model(rollout_batch) + return model_out["pred_trans"] + finally: + self.model.train(was_training) + + rollout_metrics = {} + trace_target_scale = None + if rollout_enabled: + rollout_interval = int( + getattr(self._exp_cfg.training, "generator_cov_rollout_interval_steps", 200) + ) + rollout_interval = max(1, rollout_interval) + should_measure = ( + self._gen_cov_rollout_trace_ratio_ema is None + or int(getattr(self, "global_step", 0)) % rollout_interval == 0 + ) + if should_measure: + # Default matches inference resolution (num_timesteps=20). This is a + # no_grad forward-only measurement on a few proteins once per interval, + # so there is no reason to under-resolve it; a coarse 2-step rollout + # gives a systematically wrong amplification G. + rollout_steps = int( + getattr(self._exp_cfg.training, "generator_cov_rollout_steps", 20) + ) + rollout_steps = max(1, rollout_steps) + rollout_num_deltas = int( + getattr(self._exp_cfg.training, "generator_cov_rollout_num_deltas", 1) + ) + rollout_num_deltas = max(1, min(rollout_num_deltas, num_deltas)) + rollout_max_examples = int( + getattr(self._exp_cfg.training, "generator_cov_rollout_max_examples", 4) + ) + rollout_max_examples = max(1, min(rollout_max_examples, batch_size)) + example_idx = torch.arange( + rollout_max_examples, + device=res_mask.device, + dtype=torch.long, + ) + selected_mask = res_mask.index_select(0, example_idx) + selected_lengths = selected_mask.float().sum(dim=-1) + rollout_max_res = int(selected_lengths.max().detach().cpu().item()) + rollout_max_res = max(1, min(rollout_max_res, res_mask.shape[1])) + with torch.inference_mode(): + rollout_conditions = [ + _slice_condition(cond, example_idx, max_res=rollout_max_res) + for cond in conditions[: 2 * rollout_num_deltas] + ] + rollout_condition = _concat_conditions(rollout_conditions) + rollout_base_batch = _slice_batch( + noisy_batch, + example_idx, + max_res=rollout_max_res, + ) + # Start T_full from SHARED prior noise x0 (the real inference + # start), NOT from the training-time trans_t. trans_t is anchored + # to the ground-truth frame (corrupt_batch interpolates noise<->x_1), + # so rolling from it measures the c-response near the true frame, + # not the free-sampling response inference actually produces. + # Sampling x0 on the sliced base (before expand) makes +delta and + # -delta of the same example share the same x0 (supplement 1). + r_trans0, r_rotmats0 = self.interpolant.sample_from_prior( + rollout_max_examples, + rollout_max_res, + rollout_base_batch["trans_equilibrium"], + rollout_base_batch["rotmats_equilibrium"], + ) + rollout_base_batch = dict(rollout_base_batch) + rollout_base_batch["trans_t"] = r_trans0 + rollout_base_batch["rotmats_t"] = r_rotmats0 + rollout_batch = _expand_batch( + rollout_base_batch, + repeats=len(rollout_conditions), + ) + rollout_batch["z"] = rollout_condition + rollout_pred = _rollout_final_pred_trans(rollout_batch, rollout_steps) + rollout_pred = rollout_pred.reshape( + rollout_num_deltas, 2, rollout_max_examples, *rollout_pred.shape[1:] + ) + rollout_plus = rollout_pred[:, 0].reshape( + rollout_num_deltas * rollout_max_examples, + *rollout_pred.shape[3:], + ) + rollout_minus = rollout_pred[:, 1].reshape( + rollout_num_deltas * rollout_max_examples, + *rollout_pred.shape[3:], + ) + rollout_trans_eq = trans_eq.index_select(0, example_idx) + rollout_trans_eq = rollout_trans_eq[:, :rollout_max_res, :] + rollout_res_mask = res_mask.index_select(0, example_idx)[:, :rollout_max_res] + rollout_trans_eq_rep = rollout_trans_eq[None].expand( + rollout_num_deltas, -1, -1, -1 + ).reshape( + rollout_num_deltas * rollout_max_examples, + *rollout_trans_eq.shape[1:], + ) + rollout_res_mask_rep = rollout_res_mask[None].expand( + rollout_num_deltas, -1, -1 + ).reshape( + rollout_num_deltas * rollout_max_examples, + *rollout_res_mask.shape[1:], + ) + rollout_disp_plus = self.latent_encoder.relative_displacement( + rollout_plus.float(), + rollout_trans_eq_rep.float(), + rollout_res_mask_rep, + ) + rollout_disp_minus = self.latent_encoder.relative_displacement( + rollout_minus.float(), + rollout_trans_eq_rep.float(), + rollout_res_mask_rep, + ) + rollout_response = 0.5 * (rollout_disp_plus - rollout_disp_minus) + rollout_response = rollout_response.reshape( + rollout_num_deltas, + rollout_max_examples, + *rollout_response.shape[1:], + ) + rollout_weight = sample_weight.index_select(0, example_idx) + rollout_mask = rollout_res_mask.float() * rollout_weight[:, None].float() + one_step_trace = _response_trace( + response_deltas[:rollout_num_deltas].index_select(1, example_idx), + rollout_mask, + ) + rollout_trace = _response_trace(rollout_response, rollout_mask) + valid = (rollout_mask.sum(dim=-1) > 0).float() + trace_ratio = (rollout_trace / one_step_trace).clamp_min(1e-8) + ratio_num = (trace_ratio * valid).sum() + ratio_den = valid.sum() + if dist.is_available() and dist.is_initialized(): + ratio_num = ratio_num.detach().clone() + ratio_den = ratio_den.detach().clone() + dist.all_reduce(ratio_num, op=dist.ReduceOp.SUM) + dist.all_reduce(ratio_den, op=dist.ReduceOp.SUM) + if ratio_den.detach().item() > 0: + ratio_value = ratio_num / ratio_den.clamp_min(1.0) + ema_decay = float( + getattr(self._exp_cfg.training, "generator_cov_rollout_ema_decay", 0.9) + ) + ema_decay = min(max(ema_decay, 0.0), 0.999) + if self._gen_cov_rollout_trace_ratio_ema is None: + self._gen_cov_rollout_trace_ratio_ema = ratio_value.detach() + else: + self._gen_cov_rollout_trace_ratio_ema = ( + ema_decay * self._gen_cov_rollout_trace_ratio_ema.to(ratio_value.device) + + (1.0 - ema_decay) * ratio_value.detach() + ) + rollout_metrics["gen_rollout_trace_ratio"] = ratio_value.detach() + rollout_metrics["gen_rollout_trace_measured"] = ratio_value.new_tensor(1.0) + rollout_metrics["gen_rollout_trace_steps"] = ratio_value.new_tensor( + float(rollout_steps) + ) + rollout_metrics["gen_rollout_batch"] = ratio_value.new_tensor( + float(2 * rollout_num_deltas * rollout_max_examples) + ) + rollout_metrics["gen_rollout_num_res"] = ratio_value.new_tensor( + float(rollout_max_res) + ) + if self._gen_cov_rollout_trace_ratio_ema is not None: + ema_ratio = self._gen_cov_rollout_trace_ratio_ema.to(res_mask.device).clamp_min(1e-8) + trace_target_scale = (1.0 / ema_ratio).detach().reshape(1) + rollout_metrics["gen_rollout_trace_ratio_ema"] = ema_ratio.detach() + rollout_metrics["gen_rollout_trace_target_scale"] = trace_target_scale.detach()[0] + else: + trace_target_scale = res_mask.new_tensor([1.0]) + rollout_metrics["gen_rollout_trace_ratio_ema"] = res_mask.new_tensor(1.0) + rollout_metrics["gen_rollout_trace_target_scale"] = res_mask.new_tensor(1.0) + if "gen_rollout_trace_measured" not in rollout_metrics: + rollout_metrics["gen_rollout_trace_measured"] = res_mask.new_tensor(0.0) + + teacher_response_deltas = None + if teacher_model is not None: + with torch.no_grad(): + if teacher_reuse_student_delta: + teacher_conditions = conditions[: 2 * teacher_num_deltas] + else: + teacher_conditions = [] + for _ in range(teacher_num_deltas): + c_sample, _ = self.latent_encoder.sample_coefficients_from_q(condition) + c_sample = c_sample.detach().float() + delta = (c_sample - mu_bar) * scale + c_plus = mu_bar + delta + c_minus = mu_bar - delta + teacher_conditions.append( + self.latent_encoder.condition_from_mode_coefficients( + u_global, c_plus, rotmats_eq, res_mask, include_statistics=False + ) + ) + teacher_conditions.append( + self.latent_encoder.condition_from_mode_coefficients( + u_global, c_minus, rotmats_eq, res_mask, include_statistics=False + ) + ) + teacher_condition = _concat_conditions(teacher_conditions) + teacher_batch = _expand_batch(noisy_batch, repeats=len(teacher_conditions)) + teacher_batch["z"] = teacher_condition + teacher_pred = teacher_model(teacher_batch)["pred_trans"] + teacher_pred = teacher_pred.reshape( + teacher_num_deltas, 2, batch_size, *teacher_pred.shape[1:] + ) + teacher_plus = teacher_pred[:, 0].reshape( + teacher_num_deltas * batch_size, *teacher_pred.shape[3:] + ) + teacher_minus = teacher_pred[:, 1].reshape( + teacher_num_deltas * batch_size, *teacher_pred.shape[3:] + ) + teacher_trans_eq_rep = trans_eq[None].expand( + teacher_num_deltas, -1, -1, -1 + ).reshape(teacher_num_deltas * batch_size, *trans_eq.shape[1:]) + teacher_res_mask_rep = res_mask[None].expand( + teacher_num_deltas, -1, -1 + ).reshape(teacher_num_deltas * batch_size, *res_mask.shape[1:]) + teacher_disp_plus = self.latent_encoder.relative_displacement( + teacher_plus.float(), teacher_trans_eq_rep.float(), teacher_res_mask_rep + ) + teacher_disp_minus = self.latent_encoder.relative_displacement( + teacher_minus.float(), teacher_trans_eq_rep.float(), teacher_res_mask_rep + ) + teacher_response_deltas = 0.5 * (teacher_disp_plus - teacher_disp_minus) + teacher_response_deltas = teacher_response_deltas.reshape( + teacher_num_deltas, batch_size, *teacher_response_deltas.shape[1:] + ) + + losses, metrics = self.latent_encoder.generator_response_cov_loss( + response_deltas, + res_mask=res_mask, + targets=targets, + use_cross=use_cross, + sample_weight=sample_weight, + teacher_response_deltas=teacher_response_deltas, + teacher_trace_anchor=cached_teacher_trace, + teacher_trace_denominator=teacher_trace_denominator, + amplitude_anchor=amplitude_anchor, + trace_target_scale=trace_target_scale, + ) + w_local = float(getattr(self._exp_cfg.training, "lambda_gen_local_shape", 1.0)) + w_cross = float(getattr(self._exp_cfg.training, "lambda_gen_cross_shape", 1.0)) + w_anchor = float(getattr(self._exp_cfg.training, "lambda_gen_trace_anchor", 0.05)) + # Anchor warmup: ramp the amplitude-anchor weight 0 -> full over N epochs. + # Slamming the calibrated anchor to full on epoch 0 drove the condition to MD + # amplitude too fast and collapsed the latent mode geometry (max_cos -> 0.99, + # gram_condition -> 1e13) into a NaN q-head by epoch 3. Ramping lets the latent + # settle before the amplitude drive reaches full. 0 disables the ramp. + anchor_warmup = int(getattr(self._exp_cfg.training, "gen_trace_anchor_warmup_epochs", 0)) + if anchor_warmup > 0: + w_anchor = w_anchor * min( + 1.0, float(getattr(self, "current_epoch", 0)) / float(anchor_warmup) + ) + total = w_local * losses["gen_local_shape_loss"] + if use_cross and "gen_cross_shape_loss" in losses: + total = total + w_cross * losses["gen_cross_shape_loss"] + if "gen_trace_anchor_loss" in losses: + total = total + w_anchor * losses["gen_trace_anchor_loss"] + weighted = lambda_gen * total + out_metrics = {key: value.detach() for key, value in losses.items()} + out_metrics.update(metrics) + out_metrics.update(rollout_metrics) + out_metrics["gen_cov_loss"] = weighted.detach() + return weighted, out_metrics + + def _condition_probe_metrics(self, noisy_batch, model_output, condition): + if condition is None or not isinstance(condition, dict): + return {} + enabled = bool(getattr(self._exp_cfg.training, "epoch_condition_probe", True)) + if not enabled or self._condition_probe_epoch == int(self.current_epoch): + return {} + self._condition_probe_epoch = int(self.current_epoch) + scale = float(getattr(self._exp_cfg.training, "condition_probe_scale", 2.0)) + with torch.no_grad(): + zero_batch = dict(noisy_batch) + zero_batch["z"] = self._condition_with_scale(condition, 0.0) + zero_output = self.model(zero_batch) + scaled_batch = dict(noisy_batch) + scaled_batch["z"] = self._condition_with_scale(condition, scale) + scaled_output = self.model(scaled_batch) + pred = model_output["pred_trans"].detach().float() + denom = pred.abs().mean().clamp_min(1e-8) + zero_delta = (pred - zero_output["pred_trans"].detach().float()).abs().mean() + scaled_delta = (scaled_output["pred_trans"].detach().float() - pred).abs().mean() + return { + "condition_zero_pred_trans_delta": zero_delta.detach(), + "condition_zero_pred_trans_delta_rel": (zero_delta / denom).detach(), + "condition_scaled_pred_trans_delta": scaled_delta.detach(), + "condition_scaled_pred_trans_delta_rel": (scaled_delta / denom).detach(), + } + + def _z_separability(self, z_sample, group_index, groups): + with torch.no_grad(): + z_group, _ = self.latent_encoder._group_mean(z_sample, group_index) + if z_group.shape[0] < 2: + return None + between = torch.pdist(z_group.float(), p=2) + if between.numel() == 0: + return None + within = [] + for group in groups: + members = z_sample[group_index == group] + if members.shape[0] > 1: + within.append(torch.pdist(members.float(), p=2).mean()) + if not within: + return None + within_mean = torch.stack(within).mean().clamp_min(1e-8) + return between.mean() / within_mean + + def on_train_epoch_end(self): + if ( + getattr(self, "latent_enabled", False) + and self.training_epoch_metrics + and getattr(self, "global_rank", 0) == 0 + ): + metric_names = sorted({ + key + for batch_metrics in self.training_epoch_metrics + for key in batch_metrics + }) + train_epoch_dict = {} + for key in metric_names: + values = [ + batch_metrics[key] + for batch_metrics in self.training_epoch_metrics + if key in batch_metrics + ] + train_epoch_dict[key] = float( + torch.stack(values).mean().detach().cpu().item() + ) + train_epoch_dict["epoch"] = int(self.current_epoch) + train_epoch_dict["global_step"] = int(self.global_step) + train_epoch_dict["rank"] = int(self.global_rank) + out_path = os.path.join(self._exp_cfg.checkpointer.dirpath, "latent_train_epoch_metrics.csv") + os.makedirs(os.path.dirname(out_path), exist_ok=True) + pd.DataFrame([train_epoch_dict]).to_csv( + out_path, + mode="a", + header=not os.path.exists(out_path), + index=False, + ) + stage_name = epoch_summary_stage(train_epoch_dict) + # Curated console watch-list: loss + <=5 decision-driving metrics, one per + # line, each tagged with the wanted trend/range. The FULL metric set is + # still written to latent_train_epoch_metrics.csv above; this only trims + # the console noise so the few numbers that decide the run are readable. + _watch = [ + ("official_loss", "want ~0.85 stable; rising = backbone degrading"), + ("mode_max_cosine_abs", "want down <0.9; nearing 1 = about to diverge"), + ("gen_response_abs_mean", "want 0.1~0.5; ->0 = inert / blow-up = over-disperse"), + ("gen_trace_ratio_to_anchor", "want ->1; response amplitude calibrating to MD"), + ("cross_cov_far_corr", "want up 0.1->0.2; PCA-W2 proxy"), + ] + _loss = train_epoch_dict.get("train_loss", float("nan")) + _lines = [f"[epoch {int(self.current_epoch):03d} {stage_name}] loss={_loss:.4g}"] + for _k, _hint in _watch: + if _k in train_epoch_dict and pd.notna(train_epoch_dict[_k]): + _lines.append(f" {_k}={train_epoch_dict[_k]:.4g} [{_hint}]") + print("\n".join(_lines), flush=True) + self.training_epoch_metrics = [] + self._grad_flow_reported = False + return super().on_train_epoch_end() + + # ------------------------------------------------------------------ + # CMFM failure localization + # + # The gradient collapse is only observable per rank and per microbatch: + # the rank-0/every-50-steps log cannot explain a rank-1 step-170 failure, + # and gradient accumulation hides which microbatch poisoned the buffers. + # These helpers record every candidate numerator/denominator and freeze the + # exact failing microbatch to disk. Nothing here clips, skips, or rescales. + # ------------------------------------------------------------------ + + CMFM_NUMERICS_FIELDS = ( + "prior_hidden_abs_max", + "prior_raw_mode_abs_max", + "prior_raw_mode_rms_min", + "prior_raw_mode_rms_max", + "prior_mode_norm_min", + "prior_mode_norm_max", + "prior_q_mu_abs_max", + "prior_q_scale_abs_max", + "prior_qr_diag_abs_min", + "prior_qr_rel_diag_min", + "prior_qr_condition_max", + "collective_target_variance_min", + "collective_target_variance_max", + "collective_retained_fraction", + "collective_observed_target_variance_min", + "collective_observed_target_variance_max", + "collective_covariance_scale_min", + "collective_covariance_inverse_scale_max", + "collective_target_cov_rate_absmax", + "collective_predicted_cov_rate_absmax", + "collective_covariance_error_absmax", + "collective_z_t_absmax", + "collective_z_target_absmax", + "collective_target_velocity_absmax", + "collective_predicted_velocity_absmax", + "collective_update_abs", + "collective_update_absmax", + ) + + def _cmfm_debug_dir(self): + path = os.path.join( + str(self._exp_cfg.trainer.default_root_dir), "cmfm_failure_dumps" + ) + os.makedirs(path, exist_ok=True) + return path + + def _record_cmfm_numerics( + self, + latent_metrics, + official_loss, + shape_recon_loss, + collective_loss, + group_diagnostics, + noisy_batch, + ): + """Append one row per rank per microbatch to cmfm_numerics_rank{r}.csv.""" + microbatch = int(getattr(self, "_cmfm_microbatch_index", 0)) + self._cmfm_microbatch_index = microbatch + 1 + + available = [name for name in self.CMFM_NUMERICS_FIELDS if name in latent_metrics] + values = torch.stack([ + latent_metrics[name].detach().float().reshape(()) for name in available + ] + [ + official_loss.detach().float().reshape(()), + shape_recon_loss.detach().float().reshape(()), + collective_loss.detach().float().reshape(()), + ]).cpu().tolist() + metrics = dict(zip(list(available) + ["official", "latent", "collective"], values)) + for name in self.CMFM_NUMERICS_FIELDS: + metrics.setdefault(name, float("nan")) + + pdb_names = noisy_batch.get("pdb_name") + time_values = noisy_batch["t"].detach().float().reshape(-1) + row = { + "rank": int(self.global_rank), + "epoch": int(self.current_epoch), + "global_step": int(self.global_step), + "microbatch": microbatch, + "num_particles": int(noisy_batch["res_mask"].shape[0]), + "num_res": int(noisy_batch["res_mask"].shape[1]), + "pdb_name": None if pdb_names is None else str(pdb_names[0]), + "t_min": float(time_values.min().item()), + "t_max": float(time_values.max().item()), + "num_groups": len(group_diagnostics), + **metrics, + } + numerics_path = os.path.join( + str(self._exp_cfg.trainer.default_root_dir), + f"cmfm_numerics_rank{int(self.global_rank)}.csv", + ) + pd.DataFrame([row]).to_csv( + numerics_path, + mode="a", + header=not os.path.exists(numerics_path), + index=False, + ) + + message = ( + "[cmfm-numerics] " + f"rank={row['rank']} epoch={row['epoch']} step={row['global_step']} " + f"micro={microbatch} pdb={row['pdb_name']} N={row['num_res']} " + f"t=[{row['t_min']:.4g},{row['t_max']:.4g}] " + f"h_max={metrics['prior_hidden_abs_max']:.4g} " + f"raw_u_max={metrics['prior_raw_mode_abs_max']:.4g} " + f"qr_rel_diag_min={metrics['prior_qr_rel_diag_min']:.4g} " + f"qr_cond={metrics['prior_qr_condition_max']:.4g} " + f"q_target_var=[{metrics['collective_target_variance_min']:.4g}," + f"{metrics['collective_target_variance_max']:.4g}] " + f"obs_target_var=[{metrics['collective_observed_target_variance_min']:.4g}," + f"{metrics['collective_observed_target_variance_max']:.4g}] " + f"cov_scale_min={metrics['collective_covariance_scale_min']:.4g} " + f"cov_rate_absmax={metrics['collective_target_cov_rate_absmax']:.4g} " + f"ctrl_update_absmax={metrics['collective_update_absmax']:.4g} " + f"losses=[official:{metrics['official']:.4g}," + f"latent:{metrics['latent']:.4g}," + f"collective:{metrics['collective']:.4g}]" + ) + interval = int(getattr( + self._exp_cfg.training, "cmfm_numerics_log_interval", 50 + )) + if microbatch < 5 or (interval > 0 and microbatch % interval == 0): + logging.warning(message) + self._cmfm_last_numerics_row = row + self._cmfm_last_numerics_message = message + self._cmfm_last_group_diagnostics = [ + { + key: ( + float(value.detach().float().item()) + if torch.is_tensor(value) else value + ) + for key, value in entry.items() + } + for entry in group_diagnostics + ] + return metrics + + def _stash_cmfm_microbatch(self, noisy_batch, group_index): + """Keep a CPU copy of the current microbatch so a failure can be replayed.""" + if not bool(getattr(self._exp_cfg.training, "cmfm_capture_failure", True)): + self._cmfm_last_microbatch = None + return + tensors = {} + for key, value in noisy_batch.items(): + if key == "z": + continue + if torch.is_tensor(value): + tensors[key] = value.detach().to("cpu").clone() + elif isinstance(value, (list, tuple)) and all( + isinstance(item, str) for item in value + ): + tensors[key] = list(value) + tensors["group_index"] = group_index.detach().to("cpu").clone() + self._cmfm_last_microbatch = tensors + + def _cmfm_grad_guard(self): + """Fail on the first microbatch whose backward produced non-finite grads.""" + if not bool(getattr(self._exp_cfg.training, "cmfm_grad_guard", True)): + return + graded = [ + (name, param.grad.detach()) + for name, param in self.named_parameters() + if param.grad is not None + ] + if not graded: + return + # One device sync for the whole check; the per-parameter walk only runs + # once the step is already known to be lost. + if bool(torch.stack([ + torch.isfinite(grad).all() for _, grad in graded + ]).all()): + return + nonfinite_names = [ + name for name, grad in graded if not bool(torch.isfinite(grad).all()) + ] + + dump_path = self._dump_cmfm_failure(nonfinite_names) + preview = ", ".join(nonfinite_names[:8]) + if len(nonfinite_names) > 8: + preview += f", ... (+{len(nonfinite_names) - 8} more)" + raise FloatingPointError( + "non-finite gradients after backward on a single CMFM microbatch " + f"(rank={self.global_rank}, epoch={self.current_epoch}, " + f"global_step={self.global_step}, " + f"microbatch={int(getattr(self, '_cmfm_microbatch_index', 0)) - 1}, " + f"nonfinite_parameters={len(nonfinite_names)}, [{preview}]); " + f"failure dump written to {dump_path}" + ) + + def _dump_cmfm_failure(self, nonfinite_names): + """Freeze the failing microbatch, its numerics, and the pre-step weights.""" + directory = self._cmfm_debug_dir() + microbatch = int(getattr(self, "_cmfm_microbatch_index", 0)) - 1 + stem = ( + f"rank{int(self.global_rank)}_epoch{int(self.current_epoch)}" + f"_step{int(self.global_step)}_micro{microbatch}" + ) + batch = getattr(self, "_cmfm_last_microbatch", None) + numerics_row = getattr(self, "_cmfm_last_numerics_row", None) + group_diagnostics = getattr(self, "_cmfm_last_group_diagnostics", None) + + grad_summary = [] + for name, param in self.named_parameters(): + if param.grad is None: + continue + grad = param.grad.detach() + finite = torch.isfinite(grad) + grad_summary.append({ + "name": name, + "nonfinite_elements": int((~finite).sum().item()), + "elements": int(grad.numel()), + "finite_absmax": float( + grad[finite].abs().max().item() if bool(finite.any()) else float("nan") + ), + }) + + metadata = { + "rank": int(self.global_rank), + "world_size": int(getattr(self._trainer, "world_size", 1)) + if getattr(self, "_trainer", None) is not None else 1, + "epoch": int(self.current_epoch), + "global_step": int(self.global_step), + "microbatch": microbatch, + "precision": str(getattr(self._exp_cfg.trainer, "precision", "unknown")), + "accumulate_grad_batches": int( + getattr(self._exp_cfg.trainer, "accumulate_grad_batches", 1) + ), + "collective_rank": int(self.collective_rank), + "checkpoint_dir": str( + getattr(self._exp_cfg.checkpointer, "dirpath", "") + ), + "nonfinite_parameter_count": len(nonfinite_names), + "nonfinite_parameters": nonfinite_names, + "numerics": numerics_row, + "group_diagnostics": group_diagnostics, + "grad_summary": grad_summary, + } + if batch is not None: + metadata["pdb_name"] = batch.get("pdb_name") + for key in ("group_index", "conformation_idx", "trajectory_idx", "t"): + if key in batch: + metadata[key] = batch[key].reshape(-1).tolist() + + json_path = os.path.join(directory, f"{stem}.json") + with open(json_path, "w") as handle: + json.dump(metadata, handle, indent=2, default=str) + + full_cfg = getattr(self, "_cfg", None) + payload = { + "metadata": metadata, + "batch": batch, + "config": ( + None if full_cfg is None + else OmegaConf.to_container(full_cfg, resolve=True) + ), + } + if bool(getattr(self._exp_cfg.training, "cmfm_dump_state_dict", True)): + payload["state_dict"] = { + name: tensor.detach().to("cpu").clone() + for name, tensor in self.state_dict().items() + } + dump_path = os.path.join(directory, f"{stem}.pt") + torch.save(payload, dump_path) + logging.error( + "[cmfm-failure] wrote %s and %s (%d non-finite parameter grads)", + dump_path, + json_path, + len(nonfinite_names), + ) + return dump_path + + def cmfm_debug_losses(self, noisy_batch): + """Recompute official/latent/collective for an already-corrupted batch. + + Used by scripts/cmfm_replay_failure.py to backpropagate each component + separately on the captured microbatch. It deliberately mirrors + training_step instead of wrapping it so that no Trainer state is needed. + """ + ( + z, + group_index, + latent_metrics, + latent_regularizer, + _, + ) = self._latent_group_z(noisy_batch) + noisy_batch = dict(noisy_batch) + noisy_batch["z"] = z + model_output = self._run_training_model(noisy_batch) + collective_parts = collective_measure_dynamics_loss( + noisy_batch["trans_t"], + noisy_batch["trans_1"], + model_output["pred_trans"], + noisy_batch["trans_equilibrium"], + noisy_batch["res_mask"], + z["collective_basis_global"], + group_index, + noisy_batch["t"], + t_normalize_clip=float(self._exp_cfg.training.t_normalize_clip), + target_covariance=self._collective_population_covariance(z), + rate_weighted=self.collective_rate_weighted, + ) + group_diagnostics = collective_parts.pop("collective_group_diagnostics", []) + batch_losses = self.loss_fn(noisy_batch, model_output) + official_loss = ( + torch.mean(batch_losses[self._exp_cfg.training.loss]) + + torch.mean(batch_losses["auxiliary_loss"]) + ) + # Sub-losses exposed individually. "official" is a sum of four terms with + # very different numerics (a squared error, an SO(3) log map, and two + # pairwise-distance terms), so attributing a non-finite backward to + # "official" is not yet a location. + official_subcomponents = { + f"official:{name}": torch.mean(value) + for name, value in batch_losses.items() + if torch.is_tensor(value) and value.requires_grad + } + return { + **official_subcomponents, + "official": official_loss, + "latent": float( + getattr(self._exp_cfg.training, "lambda_shape", 1.0) + ) * latent_regularizer, + "collective": float( + getattr(self._exp_cfg.training, "lambda_collective_measure", 0.0) + ) * collective_parts["collective_measure_loss"], + "metrics": { + key: value for key, value in latent_metrics.items() + }, + "collective_parts": collective_parts, + "group_diagnostics": group_diagnostics, + } + + def on_before_optimizer_step(self, optimizer): + parent_hook = getattr(super(), "on_before_optimizer_step", None) + if parent_hook is not None: + parent_hook(optimizer) + if not getattr(self, "latent_enabled", False) or not self.collective_enabled: + return + + training_grads = [ + (name, param.grad.detach()) + for name, param in self.named_parameters() + if param.grad is not None + ] + if not training_grads: + return + all_finite = torch.stack([ + torch.isfinite(grad).all() for _, grad in training_grads + ]).all() + if bool(all_finite): + return + + nonfinite_names = [ + name for name, grad in training_grads + if not bool(torch.isfinite(grad).all()) + ] + preview = ", ".join(nonfinite_names[:8]) + if len(nonfinite_names) > 8: + preview += f", ... (+{len(nonfinite_names) - 8} more)" + raise FloatingPointError( + "non-finite training gradients before optimizer step; refusing to update " + f"corrupted parameters (rank={self.global_rank}, " + f"epoch={self.current_epoch}, global_step={self.global_step}, " + f"parameters=[{preview}])" + ) + + def _grad_norm_for_prefixes(self, prefixes): + total = 0.0 + count = 0 + for name, param in self.named_parameters(): + if not any(name.startswith(prefix) or prefix in name for prefix in prefixes): + continue + if param.grad is None: + continue + total += float(param.grad.detach().float().norm().cpu().item()) + count += 1 + return total, count + + def on_after_backward(self): + parent_hook = getattr(super(), "on_after_backward", None) + if parent_hook is not None: + parent_hook() + if not getattr(self, "latent_enabled", False): + return + if self.collective_enabled: + # Runs on every rank and every microbatch, i.e. before accumulation + # can smear the first bad microbatch across the whole window. + self._cmfm_grad_guard() + if self._grad_flow_reported: + return + if int(getattr(self, "global_step", 0)) != 0 or getattr(self, "global_rank", 0) != 0: + return + if not bool(getattr(self._exp_cfg.training, "grad_flow_check", False)): + return + groups = { + "bbflow_backbone": ["model."], + "prior_template_head": ["latent_encoder.template_"], + "prior_energy_head": ["latent_encoder.energy_out"], + "prior_mixture_head": ["latent_encoder.mixture_"], + "collective_controller": ["model.collective_controller"], + "condition_adapters_film": [ + "model.embedder.z_node_adapter", + "model.embedder.z_edge_adapter", + "model.embedder.disp_node_adapter", + "model.embedder.disp_edge_adapter", + "model.film_mlp", + ], + } + rows = [] + for group_name, prefixes in groups.items(): + norm, count = self._grad_norm_for_prefixes(prefixes) + rows.append(f"{group_name}:grad_norm={norm:.4g}:params_with_grad={count}") + print("[grad-flow-check] " + ", ".join(rows), flush=True) + self._grad_flow_reported = True + def _condition_usage_ranking_loss(self, noisy_batch, z, ell_pos): + """Contrastive 'the generator must USE c'. Same X_t: the correct c must give a + LOWER flow error than a WRONG c (another batch item's c, SAME modes). If the + model ignores c then ell_pos ~= ell_neg and this loss cannot be reduced -> it + forces c to matter. Cost: one extra forward on a fraction of steps (no 20-step + rollout). ell_pos is detached (the main flow loss already trains it); the + gradient here only pushes the wrong-c error UP. Off by default (lambda=0). + + NOTE: this is the single-step 'c is used' signal. It does NOT guarantee the + 20-step endpoint recovers c (that is the drift/terminal-calibration question); + keep measuring c* vs c_hat_20 separately. + """ + lam = float(getattr(self._exp_cfg.training, "lambda_condition_usage", 0.0)) + if lam <= 0.0 or not isinstance(z, dict) or "mode_coefficients" not in z: + return noisy_batch["res_mask"].new_zeros(()) + frac = float(getattr(self._exp_cfg.training, "condition_usage_frac", 0.15)) + B = int(noisy_batch["res_mask"].shape[0]) + if B < 2 or random.random() > frac: + return noisy_batch["res_mask"].new_zeros(()) + perm = torch.roll(torch.arange(B, device=noisy_batch["res_mask"].device), shifts=1) + coeff_neg = z["mode_coefficients"][perm] # wrong coefficients, SAME modes/subspace + with torch.autocast(device_type="cuda", enabled=False): + z_neg = self.latent_encoder.condition_from_mode_coefficients( + z["u_global"].float(), + coeff_neg.float(), + noisy_batch["rotmats_equilibrium"], + noisy_batch["res_mask"], + include_statistics=False, + ) + neg_batch = dict(noisy_batch) + neg_batch["z"] = z_neg + neg_batch.pop("trans_sc", None) # no self-conditioning leakage from the + path + neg_out = self.model(neg_batch) + neg_losses = self.loss_fn(neg_batch, neg_out) + ell_neg = torch.mean( + neg_losses[self._exp_cfg.training.loss] + neg_losses["auxiliary_loss"] + ) + margin = float(getattr(self._exp_cfg.training, "condition_usage_margin", 0.0)) + return lam * torch.clamp(margin + ell_pos.detach() - ell_neg, min=0.0) + + def _run_training_model(self, noisy_batch): + collective_chunk_size = int( + getattr( + self._exp_cfg.training, + "collective_backbone_chunk_size", + 0, + ) + ) + if self.collective_enabled and collective_chunk_size > 0: + return self.model.forward_chunked( + noisy_batch, + chunk_size=collective_chunk_size, + checkpoint_chunks=True, + ) + + use_checkpoint = bool( + self.training + and torch.is_grad_enabled() + and bool(getattr(self._exp_cfg.training, "full_model_activation_checkpoint", False)) + ) + if not use_checkpoint: + return self.model(noisy_batch) + + def model_forward(batch): + return self.model(batch) + + return torch.utils.checkpoint.checkpoint( + model_forward, + noisy_batch, + use_reentrant=False, + ) + + def training_step(self, batch: Any, stage: int): + step_start_time = time.time() + self.interpolant.set_device(batch['res_mask'].device) + # Lightning bf16 autocast wraps training_step; OT/Kabsch/SVD/linalg.det need fp32. + # Keep rigid-body corruption in fp32, but let the learned latent prior + # use the trainer mixed-precision context. Its pairwise message passing + # is checkpointed inside LatentEncoder. + with torch.autocast(device_type="cuda", enabled=False): + shared_time = self._collective_shared_time(batch) if self.collective_enabled else None + noisy_batch = self.interpolant.corrupt_batch(batch, t=shared_time) + + if getattr(self, "latent_enabled", False): + ( + z, + group_index, + latent_metrics, + shape_recon_loss, + shape_baseline_error, + ) = self._latent_group_z(noisy_batch) + else: + z = None + group_index = torch.arange( + noisy_batch["res_mask"].shape[0], + device=noisy_batch["res_mask"].device, + dtype=torch.long, + ) + latent_metrics = {} + shape_recon_loss = noisy_batch["res_mask"].new_zeros(()) + shape_baseline_error = noisy_batch["res_mask"].new_zeros(()) + + if z is not None: + noisy_batch["z"] = z + + log_latent_batch_debug = bool( + getattr(self._exp_cfg.training, "log_latent_batch_debug", False) + ) + should_log_latent_batch = bool( + log_latent_batch_debug + and getattr(self, "global_rank", 0) == 0 + and not getattr(self, "_latent_batch_debug_logged", False) + ) + if should_log_latent_batch: + groups_unique, group_counts = torch.unique( + group_index.detach().cpu(), + sorted=True, + return_counts=True, + ) + logging.info( + "latent batch before forward | rank=%s step=%s B=%s N=%s groups=%s group_sizes=%s precision=%s", + getattr(self, "global_rank", 0), + int(self.global_step), + int(noisy_batch["res_mask"].shape[0]), + int(noisy_batch["res_mask"].shape[1]), + int(groups_unique.numel()), + group_counts.tolist(), + str(getattr(self._exp_cfg.trainer, "precision", "32-true")), + ) + self._latent_batch_debug_logged = True + + if self._interpolant_cfg.self_condition and random.random() > 0.5: + with torch.no_grad(): + model_sc = self._run_training_model(noisy_batch) + noisy_batch['trans_sc'] = model_sc['pred_trans'] + + model_output = self._run_training_model(noisy_batch) + if z is not None: + latent_metrics.update(self._condition_probe_metrics(noisy_batch, model_output, z)) + condition_cycle_loss, condition_cycle_metrics = self._condition_cycle_loss( + noisy_batch, + model_output, + z, + ) + latent_metrics.update(condition_cycle_metrics) + gen_cov_loss, gen_cov_metrics = self._generator_response_cov_loss(noisy_batch, z) + latent_metrics.update(gen_cov_metrics) + if self.collective_enabled: + collective_parts = collective_measure_dynamics_loss( + noisy_batch["trans_t"], + noisy_batch["trans_1"], + model_output["pred_trans"], + noisy_batch["trans_equilibrium"], + noisy_batch["res_mask"], + z["collective_basis_global"], + group_index, + noisy_batch["t"], + t_normalize_clip=float(self._exp_cfg.training.t_normalize_clip), + target_covariance=self._collective_population_covariance(z), + rate_weighted=self.collective_rate_weighted, + ) + collective_loss = collective_parts["collective_measure_loss"] + collective_group_diagnostics = collective_parts.pop( + "collective_group_diagnostics", [] + ) + latent_metrics.update({ + key: value.detach() for key, value in collective_parts.items() + }) + collective_update = model_output["collective_update_global"].detach().float() + latent_metrics["collective_update_abs"] = collective_update.abs().mean() + latent_metrics["collective_update_absmax"] = collective_update.abs().amax() + else: + collective_group_diagnostics = [] + collective_loss = model_output["pred_trans"].new_zeros(()) + batch_losses = self.loss_fn(noisy_batch, model_output) + num_batch = batch_losses['bb_atom_loss'].shape[0] + total_losses = { + k: torch.mean(v) for k,v in batch_losses.items() + } + + official_loss = ( + total_losses[self._exp_cfg.training.loss] + + total_losses['auxiliary_loss'] + ) + condition_usage_loss = self._condition_usage_ranking_loss(noisy_batch, z, official_loss) + train_loss = ( + official_loss + + float(getattr(self._exp_cfg.training, "lambda_shape", 1.0)) * shape_recon_loss + + condition_cycle_loss + + gen_cov_loss + + condition_usage_loss + + float(getattr(self._exp_cfg.training, "lambda_collective_measure", 0.0)) + * collective_loss + ) + + nonfinite_detected = (~torch.isfinite(train_loss)).float() + if self.trainer.world_size > 1: + dist.all_reduce(nonfinite_detected, op=dist.ReduceOp.SUM) + + if nonfinite_detected > 0: + raise FloatingPointError( + "non-finite training loss; refusing to skip a corrupted CMFM step " + f"(rank={self.global_rank}, epoch={self.current_epoch}, " + f"global_step={self.global_step}, " + f"official={official_loss.detach().float().item():.6g}, " + f"latent={shape_recon_loss.detach().float().item():.6g}, " + f"collective={collective_loss.detach().float().item():.6g})" + ) + + if self.collective_enabled: + self._record_cmfm_numerics( + latent_metrics, + official_loss, + shape_recon_loss, + collective_loss, + collective_group_diagnostics, + noisy_batch, + ) + self._stash_cmfm_microbatch(noisy_batch, group_index) + + for k,v in total_losses.items(): + self._log_scalar( + f"train/{k}", v, prog_bar=False, batch_size=num_batch) + + self._log_scalar("train/official_loss", official_loss, prog_bar=False, batch_size=num_batch) + self._log_scalar("train/shape_recon_loss", shape_recon_loss, prog_bar=False, batch_size=num_batch) + self._log_scalar("train/shape_baseline_error", shape_baseline_error, prog_bar=False, batch_size=num_batch) + self._log_scalar("train/condition_usage_loss", condition_usage_loss, prog_bar=False, batch_size=num_batch) + for metric_name, metric_value in latent_metrics.items(): + self._log_scalar(f"train/{metric_name}", metric_value, prog_bar=False, batch_size=num_batch) + + def detached_scalar(value): + if torch.is_tensor(value): + return value.detach().float().mean() + return train_loss.detach().new_tensor(float(value), dtype=torch.float32) + + batch_metrics = { + k: detached_scalar(v) for k, v in total_losses.items() + } + batch_metrics.update({ + "official_loss": detached_scalar(official_loss), + "shape_recon_loss": detached_scalar(shape_recon_loss), + "shape_baseline_error": detached_scalar(shape_baseline_error), + "train_loss": detached_scalar(train_loss), + }) + batch_metrics.update({ + k: detached_scalar(v) for k, v in latent_metrics.items() + }) + + t = torch.squeeze(noisy_batch['t']) + self._log_scalar( + "train/t", t.detach().float().mean(), + prog_bar=False, batch_size=num_batch) + + if self._exp_cfg.training.t_bins > 1 and self._diagnostic_step(): + for loss_name, loss_dict in batch_losses.items(): + stratified_losses = mu.t_stratified_loss( + t, loss_dict, num_bins=self._exp_cfg.training.t_bins, t_interval=self._interpolant_cfg.t_interval, loss_name=loss_name) + batch_metrics.update({ + k: detached_scalar(v) for k, v in stratified_losses.items() + }) + + for k,v in stratified_losses.items(): + self._log_scalar( + f"train/{k}", v, prog_bar=False, batch_size=num_batch) + + self.training_epoch_metrics.append(batch_metrics) + + self._log_scalar( + "train/length", float(batch['res_mask'].shape[1]), prog_bar=False, batch_size=num_batch) + self._log_scalar( + "train/batch_size", float(num_batch), prog_bar=False) + step_time = time.time() - step_start_time + self._log_scalar( + "train/examples_per_second", num_batch / step_time) + self._log_scalar( + "train/loss", train_loss, batch_size=num_batch) + + if self._exp_cfg.use_wandb: + wandb_logs = {} + time_indices = torch.bucketize(noisy_batch["t"].detach().cpu(), self._time_bins) + time_indices_unique, counts = torch.unique(time_indices-1, return_counts=True) + time_indices_unique[time_indices_unique < 0] = 0 + self._time_histogram[time_indices_unique] += counts + wandb_logs["sampled_time_cumulative"] = wandb.Histogram( + np_histogram=(( + (self._time_histogram/self._time_histogram.sum()).numpy(), + self._time_bins.numpy() + )) + ) + time_histogram_step = torch.zeros(self._time_histogram.shape) + time_histogram_step[time_indices_unique] += counts + wandb_logs["sampled_time_per_step"] = wandb.Histogram( + np_histogram=(( + (time_histogram_step/time_histogram_step.sum()).numpy(), + self._time_bins.numpy() + )) + ) + self.logger.experiment.log(wandb_logs) + + return train_loss + + def configure_optimizers(self): + if not getattr(self, "latent_enabled", False): + return super().configure_optimizers() + + params = [p for p in list(self.model.parameters()) + list(self.latent_encoder.parameters()) if p.requires_grad] + if getattr(self, "global_rank", 0) == 0 and bool(getattr(self._exp_cfg.training, "log_optimizer_coverage", True)): + num_params = sum(p.numel() for p in params) + print(f"[optimizer-coverage] trainable_tensors={len(params)} trainable_params={num_params}", flush=True) + if not self._exp_cfg.scheduler.enabled: + return torch.optim.AdamW( + params=params, + **self._exp_cfg.optimizer, + ) + optimizer = torch.optim.AdamW( + params=params, + **self._exp_cfg.optimizer, + ) + scheduler = torch.optim.lr_scheduler.LambdaLR( + optimizer, + lr_lambda=self.lr_lambda + ) + return [optimizer], [scheduler] + + + def predict_step(self, batch, batch_idx): + device = f'cuda:{torch.cuda.current_device()}' + interpolant = InterpolantBBFlow(self._infer_cfg.interpolant) + interpolant.set_device(device) + + pdb_dir = os.path.join(self._output_dir, batch["pdb_name"][0]) + if os.path.exists(os.path.join(pdb_dir, "sampled_conformations.pdb")): + print(f"Skipping {batch['pdb_name']} as it already exists") + return + os.makedirs(pdb_dir, exist_ok=True) + + sample_time_start = datetime.now() + + N = batch["trans_equilibrium"].shape[1] + requested_batch_size = int(self._infer_cfg.samples.batch_size) + batch_size = self._infer_cfg.samples.num_res_squared / N**2 + batch_size = max( + 1, + min( + requested_batch_size, + int(batch_size/5)*5 + ) + ) + if self.collective_enabled: + if batch_size != requested_batch_size: + raise ValueError( + f"CMFM requested joint group size {requested_batch_size}, but the " + f"length-based sampler reduced it to {batch_size} for N={N}. " + "Increase inference.samples.num_res_squared; CMFM does not shrink groups." + ) + if batch_size <= self.collective_rank: + raise ValueError( + f"CMFM inference batch_size={batch_size} must exceed " + f"collective_rank={self.collective_rank}" + ) + if int(self._infer_cfg.samples.samples_per_protein) % batch_size != 0: + raise ValueError( + "CMFM samples_per_protein must be divisible by the joint group size" + ) + + sampled_conformations = self._sample_multiple( + batch["trans_equilibrium"], + batch["rotmats_equilibrium"], + batch["seq"], + self._infer_cfg.samples.samples_per_protein, + batch_size, + interpolant, + pdb_dir=pdb_dir if self._infer_cfg.save_traj else None + ) + + sample_time = (datetime.now()-sample_time_start).total_seconds() + + aatype = batch["seq"][0].argmax(-1).cpu().numpy() + + samples_path = os.path.join(pdb_dir, f'sampled_conformations.pdb') + au.write_prot_to_pdb( + sampled_conformations, + samples_path, + aatype=aatype, + no_indexing=True + ) + + if bool(getattr(self._infer_cfg, "postprocess_bfactors", True)): + confs = mdtraj.load(samples_path) + avg = np.mean(confs.xyz, axis=0) + avg -= np.mean(avg[confs.top.select("name CA")], axis=0, keepdims=True) + avg = mdtraj.Trajectory(avg[None, :, :], confs.top) + confs = confs.superpose(avg) + rmsf = mdtraj.rmsf(confs, avg) + confs.save_pdb(samples_path, bfactors=rmsf) + + + if not self._infer_cfg.single_file: + os.makedirs(os.path.join(pdb_dir, "samples")) + confs = mdtraj.load(samples_path) + for i in range(len(confs)): + single_sample_path = os.path.join(pdb_dir, "samples", f"sample_{i}.pdb") + confs[i].save(single_sample_path) + + os.remove(samples_path) + + + if self._infer_cfg.log_times: + self._print_logger.info(f"Generating time for {batch['pdb_name']} for {self._infer_cfg.samples.samples_per_protein} samples of length {N}: {sample_time}s") + sample_time = (datetime.now()-sample_time_start).total_seconds() + self._print_logger.info(f"Time with pdb saving and plotting: {sample_time}s") diff --git a/bbflow_base/bbflow/models/collective.py b/bbflow_base/bbflow/models/collective.py new file mode 100644 index 0000000000000000000000000000000000000000..9077bafc832b122e1da59b187c5a8a430e5e73b1 --- /dev/null +++ b/bbflow_base/bbflow/models/collective.py @@ -0,0 +1,493 @@ +import torch +import torch.nn as nn + + +def _validate_mixture_shapes(logits, means, scale_tril): + if logits.dim() != 2: + raise ValueError(f"mixture logits must have shape [B, M], got {tuple(logits.shape)}") + if means.dim() != 3: + raise ValueError(f"mixture means must have shape [B, M, K], got {tuple(means.shape)}") + if scale_tril.dim() != 4: + raise ValueError( + f"mixture scales must have shape [B, M, K, K], got {tuple(scale_tril.shape)}" + ) + if means.shape[:2] != logits.shape or scale_tril.shape[:3] != means.shape: + raise ValueError("mixture logits, means, and scale_tril have incompatible shapes") + if scale_tril.shape[-1] != means.shape[-1]: + raise ValueError("mixture scale matrices must be square in coefficient space") + + +def mixture_mean_and_covariance_factor(logits, means, scale_tril): + """Return the mixture mean and an exact factor S such that Cov[c] = S S^T.""" + _validate_mixture_shapes(logits, means, scale_tril) + weights = torch.softmax(logits.float(), dim=-1) + means = means.float() + scale_tril = scale_tril.float() + mixture_mean = torch.einsum("bm,bmk->bk", weights, means) + sqrt_weights = torch.sqrt(weights) + centered_means = means - mixture_mean[:, None, :] + + batch, components, dimensions = means.shape + component_factor = ( + scale_tril * sqrt_weights[..., None, None] + ).permute(0, 2, 1, 3).reshape(batch, dimensions, components * dimensions) + between_component_factor = ( + centered_means * sqrt_weights[..., None] + ).transpose(1, 2) + covariance_factor = torch.cat( + [component_factor, between_component_factor], + dim=-1, + ) + return mixture_mean, covariance_factor + + +def mixture_mean_and_covariance(logits, means, scale_tril): + """Exact first two moments of a full-covariance Gaussian mixture.""" + mixture_mean, covariance_factor = mixture_mean_and_covariance_factor( + logits, + means, + scale_tril, + ) + covariance = covariance_factor @ covariance_factor.transpose(-1, -2) + covariance = 0.5 * (covariance + covariance.transpose(-1, -2)) + return mixture_mean, covariance + + +def physical_low_rank_target( + modes, + res_mask, + coefficient_covariance_factor, + rank, + eps=1e-6, +): + """Map a coefficient covariance factor through U and retain its physical SVD.""" + if modes.dim() != 4 or modes.shape[-1] != 3: + raise ValueError(f"modes must have shape [B, N, K, 3], got {tuple(modes.shape)}") + if res_mask.shape != modes.shape[:2]: + raise ValueError("res_mask must match the [B, N] dimensions of modes") + batch, num_res, num_modes, _ = modes.shape + if ( + coefficient_covariance_factor.dim() != 3 + or coefficient_covariance_factor.shape[:2] != (batch, num_modes) + ): + raise ValueError("coefficient_covariance_factor must have shape [B, K, P]") + if rank < 1 or rank > num_modes: + raise ValueError(f"collective rank must be in [1, {num_modes}], got {rank}") + + with torch.autocast(device_type=modes.device.type, enabled=False): + modes = modes.float() + coefficient_covariance_factor = coefficient_covariance_factor.float() + if not torch.isfinite(modes).all(): + raise FloatingPointError("physical modes contain non-finite values") + if not torch.isfinite(coefficient_covariance_factor).all(): + raise FloatingPointError("q coefficient covariance factor contains non-finite values") + + mask_xyz = res_mask.float()[..., None].expand(-1, -1, 3).reshape(batch, -1) + modes_flat = modes.permute(0, 1, 3, 2).reshape(batch, num_res * 3, num_modes) + modes_flat = modes_flat * mask_xyz[..., None] + physical_factor = modes_flat @ coefficient_covariance_factor + factor_scale = physical_factor.abs().amax(dim=(-2, -1), keepdim=True) + if not torch.isfinite(factor_scale).all(): + raise FloatingPointError("physical covariance factor scale is non-finite") + normalized_factor = physical_factor / factor_scale.clamp_min( + torch.finfo(physical_factor.dtype).tiny + ) + basis_flat, singular_values, _ = torch.linalg.svd( + normalized_factor, + full_matrices=False, + ) + physical_variance = ( + singular_values * factor_scale.reshape(batch, 1) + ).square() + if not torch.isfinite(physical_variance).all(): + raise FloatingPointError("q-implied physical covariance has non-finite variance") + top_evals = physical_variance[:, :rank] + if torch.any(top_evals <= eps).detach().item(): + raise ValueError( + f"physical covariance does not support collective rank={rank}; " + f"minimum retained eigenvalue={top_evals.detach().min().item():.6g}" + ) + basis_flat = basis_flat[:, :, :rank] + basis_flat = basis_flat * mask_xyz[..., None] + basis = basis_flat.reshape(batch, num_res, 3, rank).permute(0, 1, 3, 2) + target_covariance = torch.diag_embed(top_evals) + normalized_variance = singular_values.square() + retained_fraction = normalized_variance[:, :rank].sum( + dim=-1 + ) / normalized_variance.sum(dim=-1).clamp_min(eps) + return { + "collective_basis_global": basis, + "collective_target_covariance": target_covariance, + "collective_target_variance": top_evals, + "collective_retained_fraction": retained_fraction, + } +def masked_centered_displacement(trans, equilibrium, res_mask): + if trans.shape != equilibrium.shape or trans.shape[-1] != 3: + raise ValueError("trans and equilibrium must have matching shape [B, N, 3]") + if res_mask.shape != trans.shape[:2]: + raise ValueError("res_mask must match trans [B, N]") + mask = res_mask.float()[..., None] + displacement = (trans.float() - equilibrium.float()) * mask + center = displacement.sum(dim=1, keepdim=True) / mask.sum( + dim=1, keepdim=True + ).clamp_min(1.0) + return (displacement - center) * mask + + +def project_onto_basis(displacement, basis, res_mask): + if basis.dim() != 4 or basis.shape[:2] != displacement.shape[:2]: + raise ValueError("basis must have shape [B, N, R, 3]") + masked = displacement.float() * res_mask.float()[..., None] + return torch.einsum("bnrd,bnd->br", basis.float(), masked) + + +def _validate_groups(group_index, batch_size, rank): + if group_index.dim() != 1 or group_index.shape[0] != batch_size: + raise ValueError(f"group_index must have shape [{batch_size}]") + groups, counts = torch.unique(group_index, sorted=True, return_counts=True) + if groups.numel() == 0: + raise ValueError("collective control requires at least one group") + if torch.any(counts <= rank): + raise ValueError( + f"every collective group must contain more than rank={rank} particles; " + f"observed sizes={counts.detach().cpu().tolist()}" + ) + return groups + + +def _require_shared_group_value(values, members, name, atol=1e-6, rtol=1e-6): + group_values = values[members] + reference = group_values[:1].expand_as(group_values) + if not torch.allclose(group_values, reference, atol=atol, rtol=rtol): + raise ValueError(f"{name} must be shared by every particle in a collective group") + return group_values[0] + + +class CollectiveMeasureController(nn.Module): + """Particle- and basis-equivariant covariance controller for a finite ensemble.""" + + def __init__(self, rank, hidden_dim=128, output_scale=1.0, eps=1e-6): + super().__init__() + self.rank = int(rank) + self.output_scale = float(output_scale) + self.eps = float(eps) + self.network = nn.Sequential( + nn.Linear(6, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, 1), + ) + nn.init.normal_(self.network[-1].weight, mean=0.0, std=1e-3) + nn.init.zeros_(self.network[-1].bias) + + def forward( + self, + trans_t, + equilibrium, + res_mask, + basis_global, + target_covariance, + group_index, + time, + ): + batch = trans_t.shape[0] + groups = _validate_groups(group_index, batch, self.rank) + if basis_global.shape != ( + batch, + trans_t.shape[1], + self.rank, + 3, + ): + raise ValueError("collective_basis_global has the wrong shape") + if target_covariance.shape != (batch, self.rank, self.rank): + raise ValueError("collective_target_covariance has the wrong shape") + if time.shape[0] != batch: + raise ValueError("time must have one value per particle") + + displacement = masked_centered_displacement(trans_t, equilibrium, res_mask) + coefficients = project_onto_basis(displacement, basis_global, res_mask) + coefficient_update = torch.zeros_like(coefficients) + + for group in groups: + members = group_index == group + _require_shared_group_value( + basis_global, members, "collective_basis_global" + ) + z = coefficients[members] + z_centered = z - z.mean(dim=0) + z_cov = z_centered.transpose(0, 1) @ z_centered / float(z.shape[0] - 1) + + group_target_cov = _require_shared_group_value( + target_covariance, members, "collective_target_covariance" + ).float() + target_std = torch.sqrt( + torch.diagonal(group_target_cov, dim1=-2, dim2=-1).clamp_min(self.eps) + ) + scale_matrix = target_std[:, None] * target_std[None, :] + particle_state = z_centered / target_std + covariance_error = (group_target_cov - z_cov) / scale_matrix.clamp_min( + self.eps + ) + group_time = time[members].reshape(z.shape[0], -1)[:, :1] + if torch.max(torch.abs(group_time - group_time[:1])).detach().item() > 1e-6: + raise ValueError("all particles in a collective group must share the same time") + + covariance_direction = particle_state @ covariance_error + particle_energy = particle_state.square().mean(dim=-1, keepdim=True) + direction_energy = covariance_direction.square().mean(dim=-1, keepdim=True) + direction_scale = torch.sqrt(1.0 + direction_energy) + unit_direction = covariance_direction / direction_scale + covariance_trace = ( + torch.trace(covariance_error) / float(self.rank) + ).reshape(1, 1) + covariance_energy = covariance_error.square().mean().reshape(1, 1) + invariant_features = torch.cat( + [ + torch.log1p(particle_energy), + torch.log1p(direction_energy), + torch.asinh( + (particle_state * covariance_direction).mean( + dim=-1, keepdim=True + ) + ), + torch.asinh(covariance_trace).expand(z.shape[0], -1), + torch.log1p(covariance_energy).expand(z.shape[0], -1), + group_time, + ], + dim=-1, + ) + scalar_gate = torch.tanh( + self.network( + invariant_features.to(dtype=self.network[0].weight.dtype) + ).float() + ) + normalized_velocity = scalar_gate * unit_direction + time_to_endpoint = (1.0 - group_time.float()).clamp_min(0.0) + group_update = ( + normalized_velocity + * target_std + * time_to_endpoint + * self.output_scale + ) + # CMFM changes covariance only; BBFlow remains responsible for the mean. + group_update = group_update - group_update.mean(dim=0, keepdim=True) + coefficient_update[members] = group_update.to(dtype=coefficients.dtype) + + global_update = torch.einsum( + "bnrd,br->bnd", basis_global.float(), coefficient_update.float() + ) + global_update = global_update * res_mask.float()[..., None] + return global_update.to(dtype=trans_t.dtype), coefficients + +def collective_measure_dynamics_loss( + trans_t, + target_trans, + predicted_trans, + equilibrium, + res_mask, + basis_global, + group_index, + time, + t_normalize_clip=0.9, + eps=1e-6, + target_covariance=None, + rate_weighted=True, +): + """Match covariance dynamics while leaving ensemble-mean learning to BBFlow. + + The error matrix is normalized by a single scalar, the group's mean projected + variance ``trace(group_target_cov) / rank``, rather than element-wise by + ``std_i * std_j``. + + The element-wise form was not basis invariant. Under an orthogonal rotation + of the collective basis the error matrix transforms as ``E -> R E R^T``, so + ``||E||_F**2 / trace(C)**2`` is unchanged while ``E_ij / (std_i * std_j)`` + is not: it silently encodes a preference for whichever basis the SVD + happened to return. It also handed the smallest observed direction a weight + of ``1 / var**2``, and the collective basis comes from the q-implied + covariance with no obligation to align with the motion the sampled MD frames + actually show, so that direction is routinely the one estimated from almost + no signal. The relative floor that used to cap this amplification is gone + with it -- with a scalar normalizer a direction with no observed motion + contributes a near-zero ``cov_rate`` and therefore a near-zero term, instead + of diverging. + + The loss remains invariant under a global rescaling of the coordinates, + since numerator and denominator are both quadratic in the displacement. + + ``target_covariance`` supplies the population second moment in the collective + basis, one ``[R, R]`` per particle, shared within a group. When it is given + the normalizer is ``trace/rank`` of that instead of the group's own 8-sample + estimate. Estimating the denominator from the same 8 endpoints as the + numerator breaks the conditional orthogonality that makes the objective + unbiased: the weight ``(R/trace)^2`` falls as the batch's endpoint spread + rises, so batches with large dispersion are systematically down-weighted, a + contraction of order ``1/(G-1)``. A cached population value removes it, and + with a data-derived basis the population value is exact rather than + estimated. + + ``rate_weighted=False`` removes the ``1/tau`` in the velocities, equivalently + multiplying the loss by ``tau^2``. With the division in place the weight + ``tau^-2`` puts 53% of the integrated loss mass in ``t > 0.9`` -- exactly + where the bridge has converged, the true covariance rate has gone to zero and + the estimator is worst. Expanding the objective shows why the division buys + nothing: the shared ``z_t`` cancels in the difference, leaving + ``2 Sym(z~^T r~)/(G-1)`` with ``r`` the endpoint residual, so this is an + endpoint statistic wearing a rate's clothing and the ``t`` weighting is free + to choose. + """ + rank = basis_global.shape[2] + groups = _validate_groups(group_index, trans_t.shape[0], rank) + z_t = project_onto_basis( + masked_centered_displacement(trans_t, equilibrium, res_mask), + basis_global, + res_mask, + ) + z_target = project_onto_basis( + masked_centered_displacement(target_trans, equilibrium, res_mask), + basis_global, + res_mask, + ) + z_pred = project_onto_basis( + masked_centered_displacement(predicted_trans, equilibrium, res_mask), + basis_global, + res_mask, + ) + + clipped_t = torch.minimum( + time.float().reshape(-1, 1), + time.new_full((time.shape[0], 1), float(t_normalize_clip)).float(), + ) + denominator = (1.0 - clipped_t).clamp_min(eps) + target_velocity = (z_target - z_t) / denominator + predicted_velocity = (z_pred - z_t) / denominator + + covariance_losses = [] + mean_errors = [] + covariance_errors = [] + # Localization instrumentation: the empirical covariance normalizer is the + # prime suspect for non-finite backward gradients, so every quantity that + # feeds it is recorded per group. All entries are detached. + group_diagnostics = [] + for group in groups: + members = group_index == group + z = z_t[members] + target_v = target_velocity[members] + predicted_v = predicted_velocity[members] + z_centered = z - z.mean(dim=0) + z_target_group = z_target[members] + z_target_centered = z_target_group - z_target_group.mean(dim=0) + target_v_centered = target_v - target_v.mean(dim=0) + predicted_v_centered = predicted_v - predicted_v.mean(dim=0) + denom = float(z.shape[0] - 1) + + target_cov_rate = ( + z_centered.transpose(0, 1) @ target_v_centered + + target_v_centered.transpose(0, 1) @ z_centered + ) / denom + predicted_cov_rate = ( + z_centered.transpose(0, 1) @ predicted_v_centered + + predicted_v_centered.transpose(0, 1) @ z_centered + ) / denom + + group_target_cov = ( + z_target_centered.transpose(0, 1) @ z_target_centered + ) / denom + target_variance = torch.diagonal( + group_target_cov, dim1=-2, dim2=-1 + ) + mean_variance = target_variance.mean() + if bool((mean_variance <= eps).detach().item()): + # The whole group is static in the collective subspace: there is no + # covariance dynamics to match and no scale to normalize by. + raise ValueError( + "observed target ensemble has no motion in the collective basis; " + f"mean projected variance={mean_variance.detach().item():.6g}" + ) + # Single scalar normalizer: the group's mean projected variance, from the + # cached population value when one is available and from the 8 endpoints + # otherwise. Detached either way so the model cannot lower the loss by + # shrinking the target scale. + if target_covariance is not None: + population = _require_shared_group_value( + target_covariance, members, "collective_target_covariance" + ).float() + covariance_scale = torch.diagonal( + population, dim1=-2, dim2=-1 + ).mean().detach() + if bool((covariance_scale <= eps).detach().item()): + raise ValueError( + "population collective covariance has no variance; " + f"mean diagonal={covariance_scale.detach().item():.6g}" + ) + else: + covariance_scale = mean_variance.detach() + covariance_error = (predicted_cov_rate - target_cov_rate) / covariance_scale + group_loss = covariance_error.square().mean() + if not rate_weighted: + # Undo the 1/tau carried by both velocities. + group_loss = group_loss * denominator[members][0, 0].detach().square() + covariance_losses.append(group_loss) + target_std = torch.sqrt(covariance_scale) + group_diagnostics.append({ + "group": int(group.detach().item()), + "size": int(z.shape[0]), + "observed_target_variance_min": target_variance.detach().min(), + "observed_target_variance_max": target_variance.detach().max(), + "covariance_scale_min": covariance_scale, + # d loss / d z_pred scales like error / covariance_scale. With a + # scalar normalizer this is a single number per group rather than the + # 1 / min(var)^2 blow-up the element-wise form produced. + "covariance_inverse_scale_max": 1.0 / covariance_scale, + "target_cov_rate_absmax": target_cov_rate.detach().abs().max(), + "predicted_cov_rate_absmax": predicted_cov_rate.detach().abs().max(), + "covariance_error_absmax": covariance_error.detach().abs().max(), + "z_t_absmax": z.detach().abs().max(), + "z_target_absmax": z_target_group.detach().abs().max(), + "target_velocity_absmax": target_v.detach().abs().max(), + "predicted_velocity_absmax": predicted_v.detach().abs().max(), + }) + mean_errors.append( + ( + (predicted_v.mean(dim=0) - target_v.mean(dim=0)) + / target_std + ).abs().mean() + ) + covariance_errors.append(covariance_error.abs().mean()) + + covariance_loss = torch.stack(covariance_losses).mean() + parts = { + "collective_measure_loss": covariance_loss, + "collective_cov_dynamics_loss": covariance_loss, + "collective_mean_dynamics_abs_error": torch.stack(mean_errors).mean(), + "collective_cov_dynamics_abs_error": torch.stack(covariance_errors).mean(), + } + parts.update(_aggregate_group_diagnostics(group_diagnostics)) + return parts + + +# Group-level statistics reduced with min (worst normalizer) rather than max. +_MIN_REDUCED_DIAGNOSTICS = ( + "observed_target_variance_min", + "covariance_scale_min", +) + + +def _aggregate_group_diagnostics(group_diagnostics): + """Reduce the per-group localization statistics to logged scalars.""" + if not group_diagnostics: + return {} + tensor_keys = [ + key for key, value in group_diagnostics[0].items() + if torch.is_tensor(value) + ] + aggregated = {} + for key in tensor_keys: + stacked = torch.stack([ + entry[key].detach().float().reshape(()) for entry in group_diagnostics + ]) + reduced = stacked.min() if key in _MIN_REDUCED_DIAGNOSTICS else stacked.max() + aggregated[f"collective_{key}"] = reduced + aggregated["collective_group_diagnostics"] = group_diagnostics + return aggregated diff --git a/bbflow_base/bbflow/models/embedder.py b/bbflow_base/bbflow/models/embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..f725e1c43bc09773d65a23b831ea04419c385af9 --- /dev/null +++ b/bbflow_base/bbflow/models/embedder.py @@ -0,0 +1,463 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import functools as fn +import numpy as np +import torch +import torch.nn as nn +from torch.nn import functional as F + +import gafl.models.utils as mu +from gafl.data import utils as du + +from gafl.models.ipa_pytorch import Linear +from gafl.models.utils import get_index_embedding, get_time_embedding, get_length_embedding + +class MLP(nn.Module): + def __init__(self, c1, c2, num_layers=2, use_layer_norm=True, dropout=0) -> None: + super(MLP, self).__init__() + + self.layers = [] + for _ in range(num_layers-1): + self.layers.append(Linear(c1, c1, init="relu")) + self.layers.append(nn.ReLU()) + self.layers.append(nn.Dropout(dropout)) + self.layers.append(Linear(c1, c1, init="final")) + self.layers = nn.Sequential(*self.layers) + + if c1 != c2: + self.final_layer = nn.Linear(c1, c2) + else: + self.final_layer = nn.Identity() + + self.use_layer_norm = use_layer_norm + if use_layer_norm: + self.layer_norm = nn.LayerNorm(c2) + + def forward(self, x): + x = self.layers(x) + x + x = self.final_layer(x) + if self.use_layer_norm: + x = self.layer_norm(x) + return x + + +def embed_direction(trans, rots, dist_cutoff=np.inf): + """ + Compute the position of the other residues from the + perspective of each residue. + + Args: + trans: [B, N, 3] translation vectors + rots: [B, N, 3, 3] rotation matrices + Returns: + [B, N, N, 3] relative positions from each residue to each other residue + """ + + B, N, _ = trans.shape + device = trans.device + + frames = du.create_rigid(rots, trans) + rel_pos = frames[:,:,None].invert_apply(trans[:,None,:]) + # rel_pos.shape = [B, N, N, 3] + distances = torch.linalg.norm(rel_pos, dim=-1) + rel_pos = rel_pos / (distances[...,None] + 1e-6) + indices = torch.arange(N, device=device) + rel_pos[:, indices, indices, :] = torch.zeros(3, device=device) + if dist_cutoff < np.inf: + # Set all direction vectors to zero if the distance is greater than dist_cutoff + mask = distances > dist_cutoff + rel_pos[mask,:] = 0 + + return rel_pos + + + + +class Embedder(nn.Module): + def __init__(self, model_conf, latent_cfg=None): + super(Embedder, self).__init__() + self.model_conf = model_conf + self.embed_aatype = model_conf.embed.embed_aatype + self.latent_enabled = bool(latent_cfg is not None and getattr(latent_cfg, "enable", False)) + self.inject_embedder = bool( + self.latent_enabled and getattr(latent_cfg, "inject_embedder", True) + ) + self.track_condition_debug = bool( + self.latent_enabled and getattr(latent_cfg, "track_condition_debug", False) + ) + + if "time_embed_dim" in model_conf.embed: + self.time_embed_dim = model_conf.embed.time_embed_dim + else: + self.time_embed_dim = 0 + + if "embed_distogram" in model_conf.embed: + self.embed_distogram = model_conf.embed.embed_distogram + else: + self.embed_distogram = True + + if "embed_self_conditioning" in model_conf.embed: + self.embed_self_conditioning = model_conf.embed.embed_self_conditioning + else: + self.embed_self_conditioning = True + + + length_embed_dim = model_conf.embed.length_embed_dim + + node_dim_in = self.time_embed_dim + length_embed_dim + + edge_dim_in = 2 * self.time_embed_dim + edge_dim_in += 2 * model_conf.node_embed_size + edge_dim_in += self.model_conf.embed.num_bins_distance + if self.embed_distogram: + edge_dim_in += self.model_conf.embed.num_bins_distance + if self.embed_self_conditioning: + edge_dim_in += self.model_conf.embed.num_bins_distance + + self.embed_direction = model_conf.embed.embed_direction + if self.embed_direction: + if hasattr(model_conf.embed, "embed_direction_cutoff") and model_conf.embed.embed_direction_cutoff is not None: + self.embed_direction_cutoff = model_conf.embed.embed_direction_cutoff + else: + self.embed_direction_cutoff = np.inf + edge_dim_in += 3 + + # positional encoding + # if model_conf.embed.index_embed_dim > 0: + if hasattr(model_conf.embed, "index_embed_type"): + self.index_embed_type = model_conf.embed.index_embed_type + self.index_embed_dim = model_conf.embed.index_embed_dim + else: + self.index_embed_dim = model_conf.embed.index_embed_dim + self.index_embed_type = None if self.index_embed_dim == 0 else "full" + + if self.index_embed_type is None or self.index_embed_type == "none": + self.index_embed_type = None + elif self.index_embed_type == "full": + assert self.index_embed_dim > 0, "index_embed_dim must be > 0 if index_embed_type is 'full'." + node_dim_in += self.index_embed_dim + edge_dim_in += self.index_embed_dim + self.linear_relpos = nn.Linear( + self.index_embed_dim, self.index_embed_dim + ) + elif self.index_embed_type == "neighbor": + edge_dim_in += 1 + else: + raise ValueError("index_embed_type must be None/\"none\", 'full' or 'neighbor'.") + + + if self.embed_aatype: + self.aatype_embedding = nn.Linear(21, model_conf.embed.aatype_embed_dim) + node_dim_in += model_conf.embed.aatype_embed_dim + + if self.inject_embedder: + self.latent_dim = int(getattr(latent_cfg, "dim", 16)) + self.num_modes = int(getattr(latent_cfg, "num_modes", self.latent_dim)) + self.node_cond_dim = int(getattr(latent_cfg, "node_cond_dim", self.num_modes)) + self.edge_cond_dim = int(getattr(latent_cfg, "edge_cond_dim", self.num_modes)) + self.z_node_adapter = nn.Sequential( + nn.Linear(self.node_cond_dim, model_conf.node_embed_size), + nn.ReLU(), + nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size), + ) + self.z_edge_adapter = nn.Sequential( + nn.Linear(self.edge_cond_dim, model_conf.edge_embed_size), + nn.ReLU(), + nn.Linear(model_conf.edge_embed_size, model_conf.edge_embed_size), + ) + self.disp_node_adapter = nn.Sequential( + nn.Linear(3, model_conf.node_embed_size), + nn.ReLU(), + nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size), + ) + self.disp_edge_adapter = nn.Sequential( + nn.Linear(1, model_conf.edge_embed_size), + nn.ReLU(), + nn.Linear(model_conf.edge_embed_size, model_conf.edge_embed_size), + ) + nn.init.zeros_(self.z_node_adapter[-1].weight) + nn.init.zeros_(self.z_node_adapter[-1].bias) + nn.init.zeros_(self.z_edge_adapter[-1].weight) + nn.init.zeros_(self.z_edge_adapter[-1].bias) + nn.init.zeros_(self.disp_node_adapter[-1].weight) + nn.init.zeros_(self.disp_node_adapter[-1].bias) + nn.init.zeros_(self.disp_edge_adapter[-1].weight) + nn.init.zeros_(self.disp_edge_adapter[-1].bias) + else: + self.latent_dim = 0 + self.num_modes = 0 + self.node_cond_dim = 0 + self.edge_cond_dim = 0 + self.z_node_adapter = None + self.z_edge_adapter = None + self.disp_node_adapter = None + self.disp_edge_adapter = None + + self.linear_s_p = nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size) + + self.node_embedding = MLP(node_dim_in, model_conf.node_embed_size, num_layers=2) + self.edge_embedding = MLP(edge_dim_in, model_conf.edge_embed_size, num_layers=2) + + + self.timestep_embedder = fn.partial( + get_time_embedding, + embedding_dim=self.time_embed_dim, + ) + self.index_embedder = fn.partial( + get_index_embedding, + embed_size=self.model_conf.embed.index_embed_dim, + ) + self.length_embedder = fn.partial( + get_length_embedding, + embed_size=self.model_conf.embed.length_embed_dim, + max_len=2056 + ) + + def prepare_inference_static(self, input_features): + """Cache O(N^2) features that are constant across ODE timesteps.""" + B, N = input_features["B,N"] + device = input_features["device"] + cache = {} + + if self.embed_aatype: + cache["aatype_embedding"] = self.aatype_embedding(input_features["seq"]) + + cache["length_embedding"] = self.length_embedder( + torch.empty(1, N, device=device) + ).repeat([B, 1, 1]) + + if self.index_embed_type == "full": + seq_idx = torch.arange(N, device=device).repeat(B, 1) + cache["index_node_embedding"] = self.index_embedder(seq_idx) + rel_seq_offset = seq_idx[:, :, None] - seq_idx[:, None, :] + cache["index_edge_embedding"] = self.linear_relpos( + self.index_embedder(rel_seq_offset.reshape([B, N**2])) + ) + elif self.index_embed_type == "neighbor": + neighbors = ( + torch.diag_embed(torch.ones(N - 1, device=device), offset=1) + + torch.diag_embed(torch.ones(N - 1, device=device), offset=-1) + ) + cache["index_edge_embedding"] = ( + neighbors[None].repeat(B, 1, 1).reshape([B, N**2, 1]) + ) + + if self.embed_distogram: + cache["equilibrium_distogram"] = mu.calc_distogram( + input_features["CA_pos"]["trans_equilibrium"], + self.model_conf.embed.min_bin_distance, + self.model_conf.embed.max_bin_distance, + self.model_conf.embed.num_bins_distance, + ).reshape([B, N**2, -1]) + + if self.embed_direction: + cache["direction_embedding"] = embed_direction( + input_features["CA_pos"]["trans_equilibrium"], + input_features["rotmats_equilibrium"], + dist_cutoff=self.embed_direction_cutoff, + ).reshape([B, N**2, -1]) + + if self.inject_embedder: + payload = input_features.get("z") + if isinstance(payload, dict): + node_cond = payload.get("node_cond") + edge_cond = payload.get("edge_cond") + disp_node_cond = payload.get("disp_node_cond") + disp_edge_cond = payload.get("disp_edge_cond") + else: + node_cond = payload + edge_cond = payload + disp_node_cond = None + disp_edge_cond = None + if node_cond is None: + node_cond = torch.zeros(B, N, self.node_cond_dim, device=device) + if edge_cond is None: + edge_cond = torch.zeros(B, N, N, self.edge_cond_dim, device=device) + if disp_node_cond is None: + disp_node_cond = torch.zeros(B, N, 3, device=device) + if disp_edge_cond is None: + disp_edge_cond = torch.zeros(B, N, N, 1, device=device) + if node_cond.dim() == 2: + node_cond = node_cond[:, None, :].expand(B, N, -1) + if edge_cond.dim() == 2: + edge_cond = edge_cond[:, None, None, :].expand(B, N, N, -1) + cache["node_condition_embedding"] = ( + self.z_node_adapter(node_cond) + + self.disp_node_adapter(disp_node_cond) + ) + cache["edge_condition_embedding"] = ( + self.z_edge_adapter(edge_cond) + + self.disp_edge_adapter(disp_edge_cond) + ) + return cache + + def forward(self, input_features): + """ + Args: + t: + [*, ] time step sampled from [0, 1] + fixed_mask: + [*, N_res] mask of fixed (motif) residues + self_conditioning_ca: + [*, N_res, 3] Ca positions of self-conditioning input + rigids: + [*, N_res] Frame object + Returns: + [*, N_res, node_dim] initial node features + [*, N_res, N_res, edge_dim] initial edge features + """ + B, N = input_features["B,N"] + device = input_features["device"] + static = input_features.get("inference_static") + + h_0 = [] + z_0 = [] + + if self.time_embed_dim > 0: + t_embed = self.timestep_embedder(input_features["time"][:,0])[:, None, :].repeat(1, N, 1) + h_0.append(t_embed) + z_0.append(self._cross_concat(t_embed, B, N)) + + if self.embed_aatype: + if static is not None and "aatype_embedding" in static: + h_0.append(static["aatype_embedding"]) + else: + h_0.append(self.aatype_embedding(input_features["seq"])) + + if self.inject_embedder: + z_payload = input_features.get("z", None) + self._last_z_seen = z_payload is not None + if isinstance(z_payload, dict): + node_cond = z_payload.get("node_cond") + edge_cond = z_payload.get("edge_cond") + disp_node_cond = z_payload.get("disp_node_cond") + disp_edge_cond = z_payload.get("disp_edge_cond") + else: + node_cond = z_payload + edge_cond = z_payload + disp_node_cond = None + disp_edge_cond = None + if node_cond is None: + node_cond = torch.zeros(B, N, self.node_cond_dim, device=device) + if edge_cond is None: + edge_cond = torch.zeros(B, N, N, self.edge_cond_dim, device=device) + if disp_node_cond is None: + disp_node_cond = torch.zeros(B, N, 3, device=device) + if disp_edge_cond is None: + disp_edge_cond = torch.zeros(B, N, N, 1, device=device) + if node_cond.dim() == 2: + node_cond = node_cond[:, None, :].expand(B, N, -1) + if edge_cond.dim() == 2: + edge_cond = edge_cond[:, None, None, :].expand(B, N, N, -1) + self._last_z_requires_grad = bool(node_cond.requires_grad or edge_cond.requires_grad or disp_node_cond.requires_grad or disp_edge_cond.requires_grad) + self._last_z_shape = { + "node_cond": tuple(node_cond.shape), + "edge_cond": tuple(edge_cond.shape), + "disp_node_cond": tuple(disp_node_cond.shape), + "disp_edge_cond": tuple(disp_edge_cond.shape), + } + if self.track_condition_debug: + self._last_z_abs_mean = float( + ((node_cond.detach().float().abs().mean() + + edge_cond.detach().float().abs().mean() + + disp_node_cond.detach().float().abs().mean() + + disp_edge_cond.detach().float().abs().mean()) / 4.0).cpu().item() + ) + + for ca_pos_name, ca_pos in input_features["CA_pos"].items(): + if not self.embed_distogram and ca_pos_name == "trans_equilibrium": + continue + if ( + static is not None + and ca_pos_name == "trans_equilibrium" + and "equilibrium_distogram" in static + ): + z_0.append(static["equilibrium_distogram"]) + else: + ca_dgram = mu.calc_distogram( + ca_pos, + self.model_conf.embed.min_bin_distance, + self.model_conf.embed.max_bin_distance, + self.model_conf.embed.num_bins_distance, + ) + z_0.append(ca_dgram.reshape([B, N**2, -1])) + + if self.embed_direction: + if static is not None and "direction_embedding" in static: + z_0.append(static["direction_embedding"]) + else: + direction_embedding = embed_direction( + input_features["CA_pos"]["trans_equilibrium"], + input_features["rotmats_equilibrium"], + dist_cutoff=self.embed_direction_cutoff + ) + z_0.append(direction_embedding.reshape([B, N**2, -1])) + + + # TODO: get_length_embedding expects a tensor of shape [...,N]. + # It ignores elements and just uses .shape[-1] and device. + # Don't want to change it, so we just pass in an empty tensor. + if static is not None and "length_embedding" in static: + length_embedding = static["length_embedding"] + else: + length_embedding = self.length_embedder( + torch.empty(1, N).to(device=device) + ) + length_embedding = length_embedding.repeat([B, 1, 1]) + h_0.append(length_embedding) + + if self.index_embed_type is None: + pass + elif self.index_embed_type == "full": + if static is not None and "index_node_embedding" in static: + h_0.append(static["index_node_embedding"]) + z_0.append(static["index_edge_embedding"]) + else: + seq_idx = torch.arange(N).repeat(B, 1).to(device=device) + h_0.append(self.index_embedder(seq_idx)) + rel_seq_offset = seq_idx[:, :, None] - seq_idx[:, None, :] + rel_seq_offset = rel_seq_offset.reshape([B, N**2]) + z_0.append(self.linear_relpos(self.index_embedder(rel_seq_offset))) + elif self.index_embed_type == "neighbor": + if static is not None and "index_edge_embedding" in static: + z_0.append(static["index_edge_embedding"]) + else: + neighbors = torch.diag_embed(torch.ones(N-1, device=device), offset=1) + \ + torch.diag_embed(torch.ones(N-1, device=device), offset=-1) + neighbors = neighbors[None].repeat(B, 1, 1).reshape([B, N**2])[...,None] + z_0.append(neighbors) + else: + raise ValueError("index_embed_type must be None/'none', 'full' or 'neighbor'.") + + h_0 = torch.cat(h_0, dim=-1) + h_0 = self.node_embedding(h_0) + if self.inject_embedder: + if static is not None and "node_condition_embedding" in static: + h_0 = h_0 + static["node_condition_embedding"].to(dtype=h_0.dtype) + else: + h_0 = h_0 + self.z_node_adapter(node_cond.to(dtype=h_0.dtype)) + h_0 = h_0 + self.disp_node_adapter(disp_node_cond.to(dtype=h_0.dtype)) + + z_0.append(self._cross_concat(self.linear_s_p(h_0), B, N)) + + z_0 = torch.cat(z_0, dim=-1) + z_0 = self.edge_embedding(z_0) + z_0 = z_0.reshape([B, N, N, -1]) + if self.inject_embedder: + if static is not None and "edge_condition_embedding" in static: + z_0 = z_0 + static["edge_condition_embedding"].to(dtype=z_0.dtype) + else: + z_0 = z_0 + self.z_edge_adapter(edge_cond.to(dtype=z_0.dtype)) + z_0 = z_0 + self.disp_edge_adapter(disp_edge_cond.to(dtype=z_0.dtype)) + + return h_0, z_0 + + def _cross_concat(self, feats_1d, B, N): + return torch.cat([ + feats_1d[:, :, None, :].expand(-1, -1, N, -1), + feats_1d[:, None, :, :].expand(-1, N, -1, -1), + ], dim=-1).float().reshape([B, N**2, -1]) + diff --git a/bbflow_base/bbflow/models/latent.py b/bbflow_base/bbflow/models/latent.py new file mode 100644 index 0000000000000000000000000000000000000000..95aef1cdb988afe1ff5fa5e94acb16ee009cc74e --- /dev/null +++ b/bbflow_base/bbflow/models/latent.py @@ -0,0 +1,1834 @@ +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.utils.checkpoint import checkpoint + +from bbflow.data.alignment import kabsch_align +from bbflow.models.collective import ( + mixture_mean_and_covariance, + mixture_mean_and_covariance_factor, + physical_low_rank_target, +) + +class _MotionPriorBlock(nn.Module): + """Single edge/node message passing block for the motion prior.""" + + def __init__(self, hidden_dim): + super().__init__() + self.edge_norm = nn.LayerNorm(3 * hidden_dim) + self.node_norm = nn.LayerNorm(2 * hidden_dim) + self.edge_update = nn.Sequential( + nn.Linear(3 * hidden_dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + ) + self.node_update = nn.Sequential( + nn.Linear(2 * hidden_dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + ) + + def forward(self, node_state, edge_state, pair_mask): + pair_mask = pair_mask[..., None] + masked_edge = edge_state * pair_mask + + src = node_state[:, :, None, :].expand(-1, -1, node_state.shape[1], -1) + dst = node_state[:, None, :, :].expand(-1, node_state.shape[1], -1, -1) + + edge_input = torch.cat([masked_edge, src, dst], dim=-1) + edge_state = edge_state + self.edge_update(self.edge_norm(edge_input)) + edge_state = edge_state * pair_mask + + node_mask = pair_mask.squeeze(-1).sum(dim=2).clamp_min(1.0)[..., None] + incoming = (edge_state * pair_mask).sum(dim=2) / node_mask + outgoing = (edge_state * pair_mask).sum(dim=1) / node_mask + node_input = torch.cat([incoming, outgoing], dim=-1) + node_state = node_state + self.node_update(self.node_norm(node_input)) + return node_state, edge_state + + +class LatentEncoder(nn.Module): + """Equilibrium-conditioned template-mode motion prior. + + The prior predicts K global template motion fields from x_eq. Each mode has a + shared template generated by omega/v/center plus signed per-residue participation + and a small local-frame residual. The resulting modes reconstruct local/cross + covariance targets and provide node/edge conditions for BBFlow adapters. + """ + + def __init__(self, latent_cfg): + super().__init__() + self.dim = int(getattr(latent_cfg, "dim", 16)) + self.num_modes = int(getattr(latent_cfg, "num_modes", 8)) + self.node_cond_dim = self.num_modes + self.edge_cond_dim = self.num_modes + self.z_stochastic = False + hidden_dim = int(getattr(latent_cfg, "motion_hidden_dim", 128)) + dist_bins = int(getattr(latent_cfg, "motion_dist_bins", 16)) + self.register_buffer("dist_centers", torch.linspace(0.0, 40.0, dist_bins)) + self.dist_width = float(getattr(latent_cfg, "motion_dist_width", 4.0)) + # Raised 1e-6 -> 1e-4 (norm floor 1e-3 -> 1e-2): bounds how far a collapsing + # mode's normalization can amplify in the forward, hardening against overflow + # in the u^4 covariance terms under bf16. + self.mode_norm_eps = float(getattr(latent_cfg, "mode_norm_eps", 1e-4)) + # Relative ridge on the mode Gram before the gauge factorisation. It caps + # the gauge backward at ~1/sqrt(ridge) times the input scale; the forward + # deviation from exact orthonormality is of order the ridge itself. + self.mode_gauge_ridge = float(getattr(latent_cfg, "mode_gauge_ridge", 1e-6)) + self.cross_cov_near_distance = float(getattr(latent_cfg, "cross_cov_near_distance", 12.0)) + self.pca_align_top_m = int(getattr(latent_cfg, "pca_align_top_m", 2)) + if bool(getattr(latent_cfg, "use_enm_features", False)): + raise ValueError("ENM cannot be used as a forward feature; use experiment.training.enm_warmup_epochs for ENM initialization only.") + self.use_enm_features = False + self.enm_num_modes = int(getattr(latent_cfg, "enm_num_modes", self.num_modes)) + self.enm_cutoff = float(getattr(latent_cfg, "enm_cutoff", 12.0)) + self.enm_eps = float(getattr(latent_cfg, "enm_eps", 1e-6)) + self.mixture_components = int(getattr(latent_cfg, "mixture_components", 2)) + self.q_lstsq_ridge = float(getattr(latent_cfg, "q_lstsq_ridge", 1e-4)) + self.q_cholesky_jitter = float(getattr(latent_cfg, "q_cholesky_jitter", 1e-4)) + self.q_detach_projection = bool(getattr(latent_cfg, "q_detach_projection", True)) + self.q_detach_shared_encoder = bool( + getattr(latent_cfg, "q_detach_shared_encoder", False) + ) + self.sample_coefficients = bool(getattr(latent_cfg, "sample_coefficients", False)) + # Inference-time only; 0.0 is exactly the current behaviour. Set from the + # inference config so no training path is affected. + self.coefficient_tilt_alpha = float(getattr(latent_cfg, "coefficient_tilt_alpha", 0.0) or 0.0) + self.energy_from_q = bool(getattr(latent_cfg, "energy_from_q", False)) + self.energy_from_q_full_cov = bool(getattr(latent_cfg, "energy_from_q_full_cov", False)) + self.collective_enabled = bool(getattr(latent_cfg, "collective_enable", False)) + self.collective_rank = int(getattr(latent_cfg, "collective_rank", 4)) + self.collective_spectrum_eps = float( + getattr(latent_cfg, "collective_spectrum_eps", 1e-6) + ) + if self.collective_enabled and not (1 <= self.collective_rank <= self.num_modes): + raise ValueError( + f"collective_rank must be in [1, {self.num_modes}], " + f"got {self.collective_rank}" + ) + tril = torch.tril_indices(self.num_modes, self.num_modes) + self.register_buffer("mixture_tril_rows", tril[0], persistent=False) + self.register_buffer("mixture_tril_cols", tril[1], persistent=False) + + # The scalar prior encoder must be rotation-invariant. Vector quantities + # are recovered later as weighted sums of coordinates or local-frame + # residuals; feeding raw coordinates/rotations here breaks equivariance. + node_in = 1 + 21 + dist_bins + pair_in = dist_bins + self.prior_node_mlp = nn.Sequential( + nn.Linear(node_in, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + ) + self.prior_pair_mlp = nn.Sequential( + nn.Linear(pair_in, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + ) + self.motion_message_passing_layers = int(getattr(latent_cfg, "motion_message_passing_layers", 4)) + self.activation_checkpoint = bool( + getattr(latent_cfg, "activation_checkpoint", False) + ) + self.prior_message_passing_layers = nn.ModuleList( + [_MotionPriorBlock(hidden_dim) for _ in range(self.motion_message_passing_layers)] + ) + self.prior_update = nn.Sequential( + nn.Linear(2 * hidden_dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + ) + self.energy_out = nn.Sequential( + nn.Linear(hidden_dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, self.num_modes), + ) + self.template_residual_scale = float(getattr(latent_cfg, "template_residual_scale", 0.1)) + self.template_remove_rotation = bool(getattr(latent_cfg, "template_remove_rotation", True)) + self.template_center_logits = nn.Linear(hidden_dim, self.num_modes) + self.template_omega_logits = nn.Linear(hidden_dim, self.num_modes) + self.template_velocity_logits = nn.Linear(hidden_dim, self.num_modes) + self.template_participation = nn.Linear(hidden_dim, self.num_modes) + self.template_residual = nn.Linear(hidden_dim, self.num_modes * 3) + self.mixture_logits_out = nn.Linear(hidden_dim, self.mixture_components) + self.mixture_mu_out = nn.Linear(hidden_dim, self.mixture_components * self.num_modes) + self.mixture_tril_out = nn.Linear( + hidden_dim, + self.mixture_components * (self.num_modes * (self.num_modes + 1) // 2), + ) + + @staticmethod + def _masked_mean(x, mask): + denom = mask.sum(dim=1, keepdim=True).clamp_min(1.0) + return (x * mask[..., None]).sum(dim=1) / denom + + @staticmethod + def _masked_std(x, mask): + mean = LatentEncoder._masked_mean(x[..., None], mask).squeeze(-1) + denom = mask.sum(dim=1).clamp_min(1.0) + var = (((x - mean[:, None]) ** 2) * mask).sum(dim=1) / denom + return torch.sqrt(var.clamp_min(1e-12)) + + @staticmethod + def _nonfinite_summary(value): + value = value.detach().float() + finite = torch.isfinite(value) + finite_values = value[finite] + finite_abs_max = ( + finite_values.abs().max().item() if finite_values.numel() else float("nan") + ) + return ( + f"shape={tuple(value.shape)} " + f"nan={int(torch.isnan(value).sum().item())} " + f"posinf={int(torch.isposinf(value).sum().item())} " + f"neginf={int(torch.isneginf(value).sum().item())} " + f"finite_abs_max={finite_abs_max:.6g}" + ) + + @classmethod + def _require_finite(cls, name, value): + if not bool(torch.isfinite(value).all()): + raise FloatingPointError( + f"{name} contains non-finite values; {cls._nonfinite_summary(value)}" + ) + + @staticmethod + def align_to_reference(trans, ref_trans, res_mask): + return kabsch_align(trans, ref_trans, res_mask) + + @staticmethod + def relative_displacement(trans, ref_trans, res_mask): + aligned = LatentEncoder.align_to_reference(trans, ref_trans, res_mask) + if ref_trans.dim() == 2: + ref_trans = ref_trans.unsqueeze(0).expand_as(aligned) + return aligned - ref_trans + + @staticmethod + def _group_mean(x, group_index): + groups = torch.unique(group_index, sorted=True) + pooled = [] + for group in groups: + pooled.append(x[group_index == group].mean(dim=0)) + return torch.stack(pooled, dim=0), groups + + def _pair_rbf(self, trans_eq, res_mask): + with torch.autocast(device_type=trans_eq.device.type, enabled=False): + trans = trans_eq.float() + dists = torch.cdist(trans, trans) + centers = self.dist_centers.to(device=trans_eq.device, dtype=torch.float32) + rbf = torch.exp(-((dists[..., None] - centers) / self.dist_width) ** 2) + pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :] + return rbf.to(dtype=trans_eq.dtype), pair_mask.to(dtype=trans_eq.dtype) + + def _pair_distance_features(self, trans_eq, res_mask): + rbf, pair_mask = self._pair_rbf(trans_eq, res_mask) + denom = pair_mask.sum(dim=2, keepdim=True).clamp_min(1.0) + return (rbf * pair_mask[..., None]).sum(dim=2) / denom + + def _enm_modes_and_weights_single(self, coords, mask): + valid = mask.bool() + n_total = coords.shape[0] + out = coords.new_zeros(n_total, self.enm_num_modes, 3, dtype=torch.float32) + weights = coords.new_zeros(self.enm_num_modes, dtype=torch.float32) + coords_valid = coords[valid].float() + n_valid = coords_valid.shape[0] + if n_valid < 3: + return out, weights + + diff = coords_valid[:, None, :] - coords_valid[None, :, :] + dist = torch.linalg.norm(diff, dim=-1).clamp_min(self.enm_eps) + contact = (dist < self.enm_cutoff) & (~torch.eye(n_valid, device=coords.device, dtype=torch.bool)) + if not contact.any(): + return out, weights + + unit = diff / dist[..., None] + outer = unit[..., :, None] * unit[..., None, :] + off_diag = -outer * contact[..., None, None].float() + h_blocks = off_diag.clone() + diag_blocks = -off_diag.sum(dim=1) + idx = torch.arange(n_valid, device=coords.device) + h_blocks[idx, idx] = diag_blocks + hessian = h_blocks.permute(0, 2, 1, 3).reshape(3 * n_valid, 3 * n_valid) + hessian = 0.5 * (hessian + hessian.transpose(0, 1)) + + evals, evecs = torch.linalg.eigh(hessian.float()) + start = min(6, evecs.shape[1]) + stop = min(start + self.enm_num_modes, evecs.shape[1]) + if stop <= start: + return out, weights + modes = evecs[:, start:stop].reshape(n_valid, 3, stop - start).permute(0, 2, 1).contiguous() + inv_evals = 1.0 / evals[start:stop].float().clamp_min(self.enm_eps) + inv_evals = inv_evals / inv_evals.mean().clamp_min(self.enm_eps) + + flat = modes.reshape(modes.shape[0], modes.shape[1], 3) + for mode_idx in range(modes.shape[1]): + values = flat[:, mode_idx, :].reshape(-1) + max_idx = values.abs().argmax() + sign = torch.sign(values[max_idx]).clamp_min(0.0) * 2.0 - 1.0 + modes[:, mode_idx, :] = modes[:, mode_idx, :] * sign + out[valid, :modes.shape[1], :] = modes + weights[:modes.shape[1]] = inv_evals + return out, weights + + def _enm_modes_single(self, coords, mask): + modes, _ = self._enm_modes_and_weights_single(coords, mask) + return modes + + def _enm_modes_batch(self, trans_eq, res_mask): + modes = [] + with torch.no_grad(), torch.autocast(device_type=trans_eq.device.type, enabled=False): + for coords, mask in zip(trans_eq.float(), res_mask.float()): + modes.append(self._enm_modes_single(coords, mask)) + return torch.stack(modes, dim=0).to(device=trans_eq.device, dtype=torch.float32) + + def _enm_modes_and_weights_batch(self, trans_eq, res_mask): + modes = [] + weights = [] + with torch.no_grad(), torch.autocast(device_type=trans_eq.device.type, enabled=False): + for coords, mask in zip(trans_eq.float(), res_mask.float()): + mode, weight = self._enm_modes_and_weights_single(coords, mask) + modes.append(mode) + weights.append(weight) + return ( + torch.stack(modes, dim=0).to(device=trans_eq.device, dtype=torch.float32), + torch.stack(weights, dim=0).to(device=trans_eq.device, dtype=torch.float32), + ) + + def _enm_motion_targets(self, trans_eq, res_mask): + modes, energy = self._enm_modes_and_weights_batch(trans_eq, res_mask) + if modes.shape[2] < self.num_modes: + pad = modes.new_zeros(modes.shape[0], modes.shape[1], self.num_modes - modes.shape[2], 3) + modes = torch.cat([modes, pad], dim=2) + energy = torch.cat([energy, energy.new_zeros(energy.shape[0], self.num_modes - energy.shape[1])], dim=1) + modes = modes[:, :, : self.num_modes, :] + energy = energy[:, : self.num_modes] + mask = res_mask.float() + local_cov = torch.einsum("bk,bnki,bnkj->bnij", energy, modes, modes) * mask[:, :, None, None] + cross_cov = torch.einsum("bk,bikd,bjkd->bij", energy, modes, modes) * mask[:, :, None] * mask[:, None, :] + rmsf = torch.sqrt(torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)) * mask + return { + "enm_modes": modes, + "enm_energy": energy, + "local_cov": local_cov, + "cross_cov": cross_cov, + "rmsf": rmsf, + } + def _enm_node_features(self, trans_eq, rotmats_eq, res_mask): + del rotmats_eq + enm_global = self._enm_modes_batch(trans_eq, res_mask) + enm_mag = torch.linalg.norm(enm_global, dim=-1) * res_mask.float()[:, :, None] + return enm_mag.to(dtype=trans_eq.dtype) + + def _enm_pair_features(self, trans_eq, res_mask): + enm_global = self._enm_modes_batch(trans_eq, res_mask) + enm_pair = torch.einsum("bikd,bjkd->bijk", enm_global, enm_global) + pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :] + return (enm_pair * pair_mask[..., None]).to(dtype=trans_eq.dtype) + + def _equilibrium_node_feature_segments(self, trans_eq, rotmats_eq, seq, res_mask): + center = self._masked_mean(trans_eq, res_mask) + centered = trans_eq - center[:, None, :] + radius = torch.linalg.norm(centered, dim=-1, keepdim=True) + dist_feat = self._pair_distance_features(trans_eq, res_mask).to(dtype=trans_eq.dtype) + segments = [ + ("radius_from_center", radius), + ("sequence_onehot", seq), + ("pair_distance_rbf_mean", dist_feat), + ] + return segments + + def _equilibrium_node_features(self, trans_eq, rotmats_eq, seq, res_mask): + segments = self._equilibrium_node_feature_segments(trans_eq, rotmats_eq, seq, res_mask) + return torch.cat([tensor for _, tensor in segments], dim=-1) + + def prior_feature_breakdown(self, trans_eq, rotmats_eq, seq, res_mask): + segments = self._equilibrium_node_feature_segments(trans_eq, rotmats_eq, seq, res_mask) + rows = [] + start = 0 + for name, tensor in segments: + dim = int(tensor.shape[-1]) + end = start + dim + valid = tensor[res_mask.bool()] + rows.append({ + "name": name, + "start": start, + "end": end, + "dim": dim, + "shape": list(tensor.shape), + "mean_abs": float(valid.detach().float().abs().mean().cpu().item()) if valid.numel() else 0.0, + "std": float(valid.detach().float().std().cpu().item()) if valid.numel() > 1 else 0.0, + }) + start = end + node_features = torch.cat([tensor for _, tensor in segments], dim=-1) + expected_dim = int(self.prior_node_mlp[0].in_features) + return { + "segments": rows, + "total_dim": int(node_features.shape[-1]), + "expected_prior_node_in": expected_dim, + "matches_prior_node_in": int(node_features.shape[-1]) == expected_dim, + "order": [name for name, _ in segments], + } + + def _encode_equilibrium(self, trans_eq, rotmats_eq, seq, res_mask): + node_features = self._equilibrium_node_features(trans_eq, rotmats_eq, seq, res_mask) + node_state = self.prior_node_mlp(node_features) + pair_rbf, pair_mask = self._pair_rbf(trans_eq, res_mask) + pair_features = pair_rbf + edge_state = self.prior_pair_mlp(pair_features.to(dtype=node_state.dtype)) + pair_mask = pair_mask.to(dtype=node_state.dtype) + for block in self.prior_message_passing_layers: + if self.training and self.activation_checkpoint and torch.is_grad_enabled(): + def block_forward(node_state_, edge_state_, pair_mask_, block_=block): + return block_(node_state_, edge_state_, pair_mask_) + + node_state, edge_state = checkpoint( + block_forward, + node_state, + edge_state, + pair_mask, + use_reentrant=False, + preserve_rng_state=False, + ) + else: + node_state, edge_state = block(node_state, edge_state, pair_mask) + denom = pair_mask.sum(dim=2, keepdim=True).clamp_min(1.0) + pair_context = (edge_state * pair_mask[..., None]).sum(dim=2) / denom + return self.prior_update(torch.cat([node_state, pair_context], dim=-1)) + + @staticmethod + def _masked_mode_softmax(logits, res_mask): + mask = res_mask.bool()[:, None, :] + logits = logits.float().masked_fill(~mask, -1e9) + return torch.softmax(logits, dim=-1) + + @staticmethod + def _global_to_local(u_global, rotmats_eq): + return torch.einsum("bnij,bnki->bnkj", rotmats_eq.float(), u_global.float()) + + @staticmethod + def _rotation_design(coords): + x, y, z = coords.unbind(dim=-1) + zeros = torch.zeros_like(x) + return torch.stack([ + torch.stack([zeros, z, -y], dim=-1), + torch.stack([-z, zeros, x], dim=-1), + torch.stack([y, -x, zeros], dim=-1), + ], dim=-2) + def _fit_rigid_motion(self, u_global, centered_coords, res_mask): + mask = res_mask.float() + translation = (u_global.float() * mask[:, :, None, None]).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)[:, None, None] + centered = (u_global.float() - translation[:, None, :, :]) * mask[:, :, None, None] + eye = torch.eye(3, device=u_global.device, dtype=torch.float32) + omega_out = [] + rigid_out = [] + coords = centered_coords.float() + for batch_idx in range(u_global.shape[0]): + valid = res_mask[batch_idx].bool() + if valid.sum() < 3: + omega_out.append(u_global.new_zeros(self.num_modes, 3)) + rigid_out.append(centered[batch_idx]) + continue + design = self._rotation_design(coords[batch_idx, valid]).reshape(-1, 3).float() + gram = design.transpose(0, 1) @ design + 1e-4 * eye + mode_omegas = [] + mode_rigid = [] + for mode_idx in range(self.num_modes): + target = centered[batch_idx, valid, mode_idx].reshape(-1).float() + rhs = (design.transpose(0, 1) @ target.float()).float() + omega = torch.linalg.solve(gram, rhs) + rigid = (design @ omega).reshape(-1, 3) + full = centered[batch_idx, :, mode_idx].clone() + full[valid] = centered[batch_idx, valid, mode_idx] - rigid + mode_omegas.append(omega) + mode_rigid.append(full) + omega_out.append(torch.stack(mode_omegas, dim=0)) + rigid_out.append(torch.stack(mode_rigid, dim=1)) + return translation, torch.stack(omega_out, dim=0), torch.stack(rigid_out, dim=0) + + def _remove_rigid_component(self, u_global, centered_coords, res_mask): + translation, _, cleaned = self._fit_rigid_motion(u_global, centered_coords, res_mask) + del translation + return cleaned * res_mask.float()[:, :, None, None] + def _mixture_params(self, pooled): + logits = self.mixture_logits_out(pooled) + mu = self.mixture_mu_out(pooled).reshape( + pooled.shape[0], self.mixture_components, self.num_modes + ) + raw_tril = self.mixture_tril_out(pooled).reshape( + pooled.shape[0], + self.mixture_components, + self.num_modes * (self.num_modes + 1) // 2, + ) + scale_tril = raw_tril.new_zeros( + pooled.shape[0], self.mixture_components, self.num_modes, self.num_modes + ) + rows = self.mixture_tril_rows.to(device=raw_tril.device) + cols = self.mixture_tril_cols.to(device=raw_tril.device) + scale_tril[:, :, rows, cols] = raw_tril + diag = torch.diagonal(scale_tril, dim1=-2, dim2=-1) + scale_tril = scale_tril - torch.diag_embed(diag) + scale_tril = scale_tril + torch.diag_embed(F.softplus(diag) + self.q_cholesky_jitter) + return { + "mixture_logits": logits, + "mixture_log_probs": F.log_softmax(logits.float(), dim=-1).to(dtype=logits.dtype), + "mixture_mu": mu, + "mixture_scale_tril": scale_tril, + } + + @staticmethod + def _mixture_entropy(logits): + probs = torch.softmax(logits.float(), dim=-1) + return -(probs * probs.clamp_min(1e-8).log()).sum(dim=-1) + + @staticmethod + def mixture_second_moment(condition): + logits = condition["mixture_logits"].float() + mu = condition["mixture_mu"].float() + scale_tril = condition["mixture_scale_tril"].float() + probs = torch.softmax(logits, dim=-1) + cov = torch.einsum("bmik,bmjk->bmij", scale_tril, scale_tril) + second = cov + torch.einsum("bmi,bmj->bmij", mu, mu) + return torch.einsum("bm,bmij->bij", probs, second) + + def mixture_nll(self, condition, coefficients): + coefficients = coefficients.float() + logits = condition["mixture_logits"].float() + mu = condition["mixture_mu"].float() + scale_tril = condition["mixture_scale_tril"].float() + diff = coefficients[:, None, :] - mu + solved = torch.linalg.solve_triangular( + scale_tril, + diff[..., None], + upper=False, + ).squeeze(-1) + maha = solved.square().sum(dim=-1) + logdet = torch.diagonal(scale_tril, dim1=-2, dim2=-1).clamp_min(1e-8).log().sum(dim=-1) + normalizer = self.num_modes * math.log(2.0 * math.pi) + comp_log_prob = -0.5 * (normalizer + maha) - logdet + log_prob = torch.logsumexp(F.log_softmax(logits, dim=-1) + comp_log_prob, dim=-1) + return -log_prob.mean() + + def sample_coefficients_from_q(self, condition): + logits = condition["mixture_logits"].float() + mu = condition["mixture_mu"].float() + scale_tril = condition["mixture_scale_tril"].float() + component = torch.distributions.Categorical(logits=logits).sample() + batch = torch.arange(logits.shape[0], device=logits.device) + selected_mu = mu[batch, component] + selected_scale = scale_tril[batch, component] + eps = torch.randn_like(selected_mu) + coeff = selected_mu + torch.einsum("bij,bj->bi", selected_scale, eps) + return coeff.to(dtype=condition["u_global"].dtype), component + + def _condition_from_modes(self, u_global, rotmats_eq, res_mask, h, extra=None): + mask = res_mask.float()[:, :, None] + mode_norm = torch.sqrt( + ((u_global.float().square().sum(dim=-1) * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)).clamp_min(self.mode_norm_eps) + ) + raw_modes_global = u_global + u_global, qr_diagnostics = self._masked_orthonormalize_modes( + u_global, res_mask, return_diagnostics=True + ) + u_local = self._global_to_local(u_global, rotmats_eq) + pooled = self._masked_mean(h, res_mask) + q_pooled = pooled.detach() if self.q_detach_shared_encoder else pooled + mixture = self._mixture_params(q_pooled) + q_second_moment = self.mixture_second_moment(mixture) + raw_energy = F.softplus(self.energy_out(pooled)) + 1e-6 + if self.energy_from_q or self.energy_from_q_full_cov: + energy = torch.diagonal(q_second_moment, dim1=-2, dim2=-1).clamp_min(1e-8) + energy = energy + raw_energy * 0.0 + else: + energy = raw_energy + sqrt_energy = torch.sqrt(energy).to(dtype=u_local.dtype) + node_cond = torch.linalg.norm(u_global.float(), dim=-1).to(dtype=u_local.dtype) * sqrt_energy[:, None, :] + disp_global = torch.einsum("bk,bnkd->bnd", sqrt_energy.float(), u_global.float()) + disp_local = torch.einsum("bnij,bni->bnj", rotmats_eq.float(), disp_global) + disp_local = disp_local * res_mask.float()[:, :, None] + disp_edge_cond = torch.einsum("bid,bjd->bij", disp_global, disp_global)[:, :, :, None] + pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :] + disp_edge_cond = disp_edge_cond * pair_mask[:, :, :, None] + dot = torch.einsum("bikd,bjkd->bijk", u_global.float(), u_global.float()) + edge_cond = dot.to(dtype=u_local.dtype) * energy[:, None, None, :].to(dtype=u_local.dtype) + if self.energy_from_q_full_cov: + local_cov_pred = torch.einsum( + "bkl,bnki,bnlj->bnij", + q_second_moment, + u_global.float(), + u_global.float(), + ) + cross_cov_pred = torch.einsum( + "bkl,bikd,bjld->bij", + q_second_moment, + u_global.float(), + u_global.float(), + ) + else: + local_cov_pred = torch.einsum("bk,bnki,bnkj->bnij", energy.float(), u_global.float(), u_global.float()) + cross_cov_pred = edge_cond.float().sum(dim=-1) + rmsf_pred = torch.sqrt(torch.diagonal(local_cov_pred, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)) + condition = { + "node_cond": node_cond, + "edge_cond": edge_cond, + "disp_node_cond": disp_local.to(dtype=rotmats_eq.dtype), + "disp_edge_cond": disp_edge_cond.to(dtype=rotmats_eq.dtype), + "u_local": u_local.to(dtype=rotmats_eq.dtype), + "u_global": u_global.to(dtype=rotmats_eq.dtype), + "energy": energy.to(dtype=rotmats_eq.dtype), + "mode_norm": mode_norm.to(dtype=rotmats_eq.dtype), + "local_cov_pred": local_cov_pred.to(dtype=rotmats_eq.dtype), + "cross_cov_pred": cross_cov_pred.to(dtype=rotmats_eq.dtype), + "rmsf_pred": rmsf_pred.to(dtype=rotmats_eq.dtype), + "q_second_moment": q_second_moment.to(dtype=rotmats_eq.dtype), + # Pre-gauge modes. mode_orthogonality_loss has to run on these: the + # gauge output is orthonormal by construction, so measuring it there + # reports ~0 no matter how collinear the mode head has become. + "raw_modes_global": raw_modes_global, + } + condition.update(qr_diagnostics) + condition.update(mixture) + if self.collective_enabled: + # CMFM treats the q-implied physical measure as a fixed target for this + # step. Build its covariance from the exact GMM factor instead of the + # cancellation-prone E[cc^T] - E[c]E[c]^T route. + with torch.no_grad(): + _, coefficient_covariance_factor = mixture_mean_and_covariance_factor( + mixture["mixture_logits"].detach(), + mixture["mixture_mu"].detach(), + mixture["mixture_scale_tril"].detach(), + ) + collective_target = physical_low_rank_target( + u_global.detach(), + res_mask, + coefficient_covariance_factor, + rank=self.collective_rank, + eps=self.collective_spectrum_eps, + ) + condition.update({ + key: value.to(dtype=rotmats_eq.dtype) + for key, value in collective_target.items() + }) + + if extra: + condition.update(extra) + return condition + + def _masked_orthonormalize_modes( + self, + modes, + res_mask, + return_diagnostics=False, + ridge=None, + ): + """Fix the mode gauge with a masked orthonormal basis of unit per-residue norm. + + Implemented as a ridge-regularised Cholesky-QR rather than + ``torch.linalg.qr``. Both produce the same positive-diagonal-R factor, so + the forward value is unchanged for well-conditioned modes, but their + backwards differ where it matters: QR backward carries ``1 / r_ii`` and + is unbounded as the raw mode head becomes collinear, while here the ridge + caps ``||L^-1||`` at ``1 / sqrt(ridge * mean_column_energy)``. The ridge + is relative to the modes' own scale, so the gauge stays equivariant under + a global rescaling of the coordinates. + + ``return_diagnostics`` additionally reports the conditioning that used to + be invisible in the training log. + """ + modes = modes.float() + batch, num_res, num_modes, spatial_dim = modes.shape + if spatial_dim != 3 or res_mask.shape != (batch, num_res): + raise ValueError("modes and res_mask have incompatible shapes") + + mask_xyz = res_mask.bool()[..., None].expand(-1, -1, 3).reshape(batch, -1) + valid_residues = res_mask.float().sum(dim=-1) + if torch.any(valid_residues * 3 < num_modes).detach().item(): + raise ValueError("not enough valid coordinates to orthonormalize all modes") + + modes_flat = modes.permute(0, 1, 3, 2).reshape(batch, num_res * 3, num_modes) + modes_flat = modes_flat * mask_xyz[..., None] + + # The factorization runs in float64. Cholesky-QR forms A^T A, which + # squares the condition number: a mode head aligned to MD's steep + # spectrum reaches cond(A) ~ 2e3 in normal operation, so cond(A^T A) + # ~ 4e6. Forming that in float32 carries a rounding error of about + # eps * lambda_max = 1.2e-7 * lambda_max, only ~8x below the relative + # ridge of 1e-6 * lambda_max, and once it crosses the smallest + # eigenvalue goes negative and `cholesky` fails outright on a Gram that + # is mathematically positive definite. K is 8, so the whole solve is + # negligible next to the rest of the forward and float64 removes the + # failure mode instead of papering over it with a larger ridge. + modes_flat = modes_flat.double() + + gram = modes_flat.transpose(-1, -2) @ modes_flat + gram = 0.5 * (gram + gram.transpose(-1, -2)) + mean_energy = ( + torch.diagonal(gram, dim1=-2, dim2=-1).mean(dim=-1, keepdim=True) + ).clamp_min(torch.finfo(gram.dtype).tiny) + if ridge is None: + ridge = self.mode_gauge_ridge + ridge_value = float(ridge) * mean_energy + identity = torch.eye(num_modes, device=gram.device, dtype=gram.dtype) + try: + cholesky_factor = torch.linalg.cholesky( + gram + ridge_value[..., None] * identity + ) + except torch._C._LinAlgError: + # float64 should make this unreachable; escalating once rather than + # dying keeps an unattended multi-day run alive if some batch still + # lands on the boundary. Loud on purpose -- if this fires the gauge + # is being held up by the ridge and the run's mode diagnostics + # should not be trusted at face value. + ridge_value = ridge_value * 1e3 + print( + "[cmfm-numerics] masked orthonormalization Cholesky failed at " + f"ridge={float(ridge):.3g}; retrying at {float(ridge) * 1e3:.3g}. " + "Raw Gram is at the edge of positive definiteness.", + flush=True, + ) + cholesky_factor = torch.linalg.cholesky( + gram + ridge_value[..., None] * identity + ) + + # Kept as an outright failure, not a clamp: a Gram this degenerate means + # the mode head has collapsed and the gauge is meaningless, ridge or not. + diagonal = torch.diagonal(cholesky_factor, dim1=-2, dim2=-1) + input_scale = torch.linalg.vector_norm( + modes_flat, dim=-2 + ).amax(dim=-1, keepdim=True).clamp_min(torch.finfo(gram.dtype).tiny) + relative_diagonal = diagonal.abs() / input_scale + if torch.any(relative_diagonal <= 1e-6).detach().item(): + raise ValueError( + "template modes are rank deficient before masked orthonormalization; " + f"minimum relative Cholesky diagonal=" + f"{relative_diagonal.detach().min().item():.6g}" + ) + + # q = modes_flat @ L^-T, i.e. the Q of a QR with positive diagonal R = L^T. + q = torch.linalg.solve_triangular( + cholesky_factor.transpose(-1, -2), + modes_flat, + upper=True, + left=False, + ).to(dtype=modes.dtype) + q = q * torch.sqrt(valid_residues)[:, None, None] + q = q * mask_xyz[..., None] + basis = q.reshape(batch, num_res, 3, num_modes).permute(0, 1, 3, 2) + if not return_diagnostics: + return basis + + with torch.no_grad(): + singular_values = torch.linalg.svdvals(cholesky_factor.detach()) + gauge_condition = singular_values[:, 0] / singular_values[:, -1].clamp_min( + torch.finfo(singular_values.dtype).tiny + ) + # Cast back from the float64 factorization: these are stacked with + # float32 metrics downstream. + diagnostics = { + "prior_qr_diag_abs_min": diagonal.detach().abs().amin(dim=-1), + "prior_qr_rel_diag_min": relative_diagonal.detach().amin(dim=-1), + "prior_qr_condition": gauge_condition, + "prior_gauge_ridge": ridge_value.detach().reshape(batch), + } + diagnostics = { + key: value.to(dtype=modes.dtype) + for key, value in diagnostics.items() + } + return basis, diagnostics + + def set_tilt(self, alpha, coeff_cov): + """Fix the per-mode gain vector for one protein, from its coefficient covariance. + + Computed once per protein and then applied unchanged to every sample, so the + transformed coefficient covariance is exactly `G Gamma G` and the linearised gate + evaluates the same transform the sampler applies. A per-sample renormalisation + such as `||c||/||Gc|| * Gc` would look equivalent but is not: its covariance is not + `G Gamma G`, so the gate and the experiment would be measuring different things. + + Modes are ranked by their marginal variance under `q` -- fixed per protein, not + per sample. Ranking within each sample by `|c_k|` implements no modal + redistribution at all: under an exchangeable coefficient distribution every fixed + mode keeps its marginal variance and the transform only pushes individual samples + toward coordinate axes, amplifying whichever coordinate drew large. + + The gains are renormalised so `tr(G Gamma G) == tr(Gamma)`. That fixes the + coefficient energy; it does NOT fix the conditioning payload, because `edge_cond` + and `disp_edge_cond` are quadratic in the coefficients, so concentrating a fixed + `tr(Gamma)` raises terms in `c^4`. `alpha` is therefore not orthogonal to + `condition_scale` and any effect may still be partly amplitude-mediated. + """ + alpha = float(alpha or 0.0) + if alpha == 0.0 or coeff_cov is None: + self._tilt_gain = None + return None + gamma = coeff_cov.detach().float() + if gamma.dim() == 3: + gamma = gamma[0] + k = gamma.shape[-1] + var = torch.diagonal(gamma) + order = torch.argsort(var, descending=True) + rank = torch.empty(k, device=gamma.device, dtype=gamma.dtype) + rank[order] = torch.arange(1, k + 1, device=gamma.device, dtype=gamma.dtype) + g = rank ** (-alpha) + tilted = g[:, None] * gamma * g[None, :] + scale = (torch.diagonal(gamma).sum() + / torch.diagonal(tilted).sum().clamp_min(1e-30)).sqrt() + self._tilt_gain = (g * scale).detach() + return self._tilt_gain + + def _tilt_coefficients(self, coefficients): + gain = getattr(self, "_tilt_gain", None) + if gain is None: + return coefficients + return coefficients * gain.to(coefficients.device, coefficients.dtype) + + def condition_from_mode_coefficients( + self, + u_global, + coefficients, + rotmats_eq, + res_mask, + extra=None, + include_statistics=True, + ): + """Build a sample-specific condition from fixed modes and per-frame coefficients. + + Per-frame training uses signed mode coordinates c* from the current MD frame, + giving d_i = sum_k c*_k U_k[i] rather than a static sqrt(energy) field. + """ + mask = res_mask.float()[:, :, None] + u_global = u_global.float() + coefficients = coefficients.float() + coefficients = self._tilt_coefficients(coefficients) + mode_norm = torch.sqrt( + ((u_global.square().sum(dim=-1) * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)).clamp_min(self.mode_norm_eps) + ) + # Stop-gradient on the gauge norm (same 1/mode_norm^2 explosion as above). + # Detaching in BOTH the division and the compensating multiply leaves the + # forward product coeff*u_global identical while removing the runaway gradient. + mode_norm_sg = mode_norm.detach() + u_global = u_global / mode_norm_sg[:, None, :, None] + coefficients = coefficients * mode_norm_sg + u_local = self._global_to_local(u_global, rotmats_eq) + coeff_abs = coefficients.abs().to(dtype=u_local.dtype) + node_cond = torch.linalg.norm(u_global, dim=-1).to(dtype=u_local.dtype) * coeff_abs[:, None, :] + disp_global = torch.einsum("bk,bnkd->bnd", coefficients, u_global) + disp_local = torch.einsum("bnij,bni->bnj", rotmats_eq.float(), disp_global) + disp_local = disp_local * res_mask.float()[:, :, None] + pair_mask = res_mask.float()[:, :, None] * res_mask.float()[:, None, :] + disp_edge_cond = torch.einsum("bid,bjd->bij", disp_global, disp_global)[:, :, :, None] + disp_edge_cond = disp_edge_cond * pair_mask[:, :, :, None] + dot = torch.einsum("bikd,bjkd->bijk", u_global, u_global) + edge_cond = dot.to(dtype=u_local.dtype) * coefficients.square()[:, None, None, :].to(dtype=u_local.dtype) + energy = coefficients.square() + condition = { + "node_cond": node_cond, + "edge_cond": edge_cond, + "disp_node_cond": disp_local.to(dtype=rotmats_eq.dtype), + "disp_edge_cond": disp_edge_cond.to(dtype=rotmats_eq.dtype), + "u_local": u_local.to(dtype=rotmats_eq.dtype), + "u_global": u_global.to(dtype=rotmats_eq.dtype), + "energy": energy.to(dtype=rotmats_eq.dtype), + "mode_coefficients": coefficients.to(dtype=rotmats_eq.dtype), + "mode_norm": mode_norm.to(dtype=rotmats_eq.dtype), + } + if include_statistics: + local_cov_pred = torch.einsum( + "bk,bnki,bnkj->bnij", energy, u_global, u_global + ) + condition.update({ + "local_cov_pred": local_cov_pred.to(dtype=rotmats_eq.dtype), + "cross_cov_pred": edge_cond.float().sum(dim=-1).to(dtype=rotmats_eq.dtype), + "rmsf_pred": torch.sqrt( + torch.diagonal(local_cov_pred, dim1=-2, dim2=-1) + .sum(dim=-1) + .clamp_min(1e-8) + ).to(dtype=rotmats_eq.dtype), + }) + if extra: + condition.update(extra) + return condition + + def oracle_condition_from_targets(self, trans_1, trans_eq, rotmats_eq, res_mask, targets): + modes = targets["oracle_modes"].to(device=trans_eq.device, dtype=torch.float32) + mean_disp = targets.get("oracle_mean_disp") + if mean_disp is None: + mean_disp = torch.zeros_like(trans_eq, dtype=torch.float32) + else: + mean_disp = mean_disp.to(device=trans_eq.device, dtype=torch.float32) + disp = self.relative_displacement(trans_1.float(), trans_eq.float(), res_mask) + centered_disp = (disp - mean_disp) * res_mask.float()[:, :, None] + coefficients = self.project_displacement_to_modes(centered_disp, modes, res_mask) + recon = torch.einsum("bk,bnkd->bnd", coefficients.float(), modes.float()) + return self.condition_from_mode_coefficients( + modes, + coefficients, + rotmats_eq, + res_mask, + extra={ + "oracle_centered_disp": centered_disp.to(dtype=rotmats_eq.dtype), + "oracle_recon_disp": recon.to(dtype=rotmats_eq.dtype), + }, + ) + + def frame_condition_from_projection( + self, + trans_1, + trans_eq, + rotmats_eq, + res_mask, + prior_condition, + mean_disp=None, + ): + """Project the frame's centered fluctuation onto predicted motion modes. + + Motion covariance targets are centered over MD time, so the coefficient + target must remove the same per-protein mean displacement. The solve uses + detached modes by default, while flow loss still reaches the original modes + through the reconstructed generator condition. + """ + raw_disp = self.relative_displacement(trans_1.float(), trans_eq.float(), res_mask) + mask = res_mask.float()[:, :, None] + if mean_disp is None: + raise ValueError( + "per-frame mode projection requires oracle_mean_disp in the motion-target cache; " + "regenerate the cache or use one that contains centered MD targets" + ) + mean_disp = mean_disp.to(device=raw_disp.device, dtype=raw_disp.dtype) + disp = (raw_disp - mean_disp) * mask + coefficients = self.project_displacement_lstsq( + disp, + prior_condition["u_global"], + res_mask, + ridge=self.q_lstsq_ridge, + detach_modes=self.q_detach_projection, + ) + recon_objective = self.projection_reconstruction_objective( + disp, + prior_condition["u_global"], + coefficients, + res_mask, + ridge=self.q_lstsq_ridge, + ) + recon = recon_objective["recon"] + uncentered_error = ((raw_disp - recon).square() * mask).sum(dim=(1, 2)).sqrt() + uncentered_denom = (raw_disp.square() * mask).sum(dim=(1, 2)).sqrt().clamp_min(1e-8) + passthrough = { + key: prior_condition[key] + for key in [ + "mixture_logits", + "mixture_log_probs", + "mixture_mu", + "mixture_scale_tril", + "collective_basis_global", + "collective_target_covariance", + "collective_target_variance", + "collective_retained_fraction", + ] + if key in prior_condition + } + condition = self.condition_from_mode_coefficients( + prior_condition["u_global"], + coefficients, + rotmats_eq, + res_mask, + extra=passthrough, + include_statistics=False, + ) + condition["projection_uncentered_target_disp"] = raw_disp.to(dtype=rotmats_eq.dtype) + condition["projection_mean_disp"] = mean_disp.to(dtype=rotmats_eq.dtype) + condition["projection_target_disp"] = disp.to(dtype=rotmats_eq.dtype) + condition["projection_recon_disp"] = recon.to(dtype=rotmats_eq.dtype) + condition["projection_recon_loss"] = recon_objective["loss"].to(dtype=rotmats_eq.dtype) + condition["projection_recon_rel_error"] = recon_objective["rel_error"].to(dtype=rotmats_eq.dtype) + condition["projection_uncentered_recon_rel_error"] = ( + uncentered_error / uncentered_denom + ).to(dtype=rotmats_eq.dtype) + return condition, coefficients + + def _mode_predictions(self, h, trans_eq, rotmats_eq, res_mask): + center = self._masked_mean(trans_eq.float(), res_mask) + centered = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None] + + residual_local = torch.tanh(self.template_residual(h).reshape(h.shape[0], h.shape[1], self.num_modes, 3)) + residual_global = torch.einsum("bnij,bnkj->bnki", rotmats_eq.float(), residual_local.float()) + residual_global = self.template_residual_scale * residual_global + + center_logits = self.template_center_logits(h).transpose(1, 2) + omega_logits = self.template_omega_logits(h).transpose(1, 2) + velocity_logits = self.template_velocity_logits(h).transpose(1, 2) + center_weights = self._masked_mode_softmax(center_logits, res_mask) + omega_weights = self._masked_mode_softmax(omega_logits, res_mask) + velocity_weights = self._masked_mode_softmax(velocity_logits, res_mask) + + mode_center = torch.einsum("bkn,bnd->bkd", center_weights, centered) + omega = torch.einsum("bkn,bnd->bkd", omega_weights, centered) + velocity = torch.einsum("bkn,bnd->bkd", velocity_weights, centered) + participation = self.template_participation(h) + + rel = centered[:, :, None, :] - mode_center[:, None, :, :] + base = torch.cross(omega[:, None, :, :].expand_as(rel), rel, dim=-1) + velocity[:, None, :, :] + u_global = participation[..., None].float() * base + residual_global + if not bool(torch.isfinite(u_global).all()): + components = { + "hidden": h, + "residual_local": residual_local, + "center_logits": center_logits, + "omega_logits": omega_logits, + "velocity_logits": velocity_logits, + "participation": participation, + "base": base, + "raw_modes": u_global, + } + details = "; ".join( + f"{name}: {self._nonfinite_summary(value)}" + for name, value in components.items() + if not bool(torch.isfinite(value).all()) + ) + raise FloatingPointError( + f"raw template modes contain non-finite values; {details}" + ) + u_global = self._remove_rigid_component(u_global, centered, res_mask) + self._require_finite("rigid-cleaned template modes", u_global) + raw_mode_rms = torch.sqrt( + ( + (u_global.square().sum(dim=-1) * res_mask.float()[:, :, None]).sum(dim=1) + / res_mask.float().sum(dim=1, keepdim=True).clamp_min(1.0) + ).clamp_min(0.0) + ) + extra = { + "template_center": mode_center.to(dtype=rotmats_eq.dtype), + "template_omega": omega.to(dtype=rotmats_eq.dtype), + "template_velocity": velocity.to(dtype=rotmats_eq.dtype), + "template_participation": participation.to(dtype=rotmats_eq.dtype), + "template_residual_global": residual_global.to(dtype=rotmats_eq.dtype), + "prior_hidden_abs_max": ( + h.float().abs() * res_mask.float()[..., None] + ).amax(dim=(1, 2)), + "prior_raw_mode_abs_max": u_global.abs().amax(dim=(1, 2, 3)), + "prior_raw_mode_rms_min": raw_mode_rms.amin(dim=-1), + "prior_raw_mode_rms_max": raw_mode_rms.amax(dim=-1), + } + return self._condition_from_modes(u_global, rotmats_eq, res_mask, h, extra=extra) + + def forward_prior(self, trans_eq, rotmats_eq, seq, res_mask): + if self.collective_enabled: + # CMFM evaluates one equilibrium representative per particle group. + # Keeping this small prior path in fp32 prevents bf16 corruption of h + # from reaching the physical mode basis; the particle backbone remains + # mixed precision and still dominates memory and runtime. + with torch.autocast(device_type=trans_eq.device.type, enabled=False): + h = self._encode_equilibrium( + trans_eq.float(), + rotmats_eq.float(), + seq.float(), + res_mask.float(), + ) + self._require_finite("equilibrium prior hidden state", h) + condition = self._mode_predictions( + h, + trans_eq.float(), + rotmats_eq.float(), + res_mask.float(), + ) + return condition, None + + h = self._encode_equilibrium(trans_eq, rotmats_eq, seq, res_mask) + # Mode construction and its small linear-algebra problems must remain fp32 + # because CUDA linalg does not support bf16 consistently. + with torch.autocast(device_type=trans_eq.device.type, enabled=False): + condition = self._mode_predictions( + h.float(), + trans_eq.float(), + rotmats_eq, + res_mask, + ) + return condition, None + + def _prior_backbone_modules(self): + """Every module that participates in computing u_global: the shared trunk + (h) plus the template_* heads that turn h into modes. Deliberately excludes + mixture_*/energy_out, which read the same trunk's pooled features but do + NOT feed back into u_global.""" + return [ + self.prior_node_mlp, + self.prior_pair_mlp, + self.prior_message_passing_layers, + self.prior_update, + self.template_center_logits, + self.template_omega_logits, + self.template_velocity_logits, + self.template_participation, + self.template_residual, + ] + + def freeze_prior_backbone(self): + """Stage-2 entry point: freeze everything U depends on (trunk + template + heads). Freezing ONLY the template_* linears is not enough -- if the shared + trunk keeps training (e.g. via q's gradient), h drifts and u_global drifts + with it even though the template weights are frozen. Freezing the whole + pathway makes u_global (and therefore c* = Proj_U(D)) a fixed target, which + is the point of the two-stage split. mixture_*/energy_out are left + trainable so q can still be fit/refined on top of the frozen features.""" + for module in self._prior_backbone_modules(): + for param in module.parameters(): + param.requires_grad = False + + def set_frozen_prior_backbone_eval(self): + for module in self._prior_backbone_modules(): + module.eval() + + def prior_backbone_grad_check(self): + """Diagnostic: count trainable params in the U-pathway vs the q/energy + heads, so 'U frozen in stage 2' is verifiable at runtime, not assumed.""" + frozen_params = sum( + p.numel() for m in self._prior_backbone_modules() for p in m.parameters() + ) + frozen_trainable = sum( + p.numel() for m in self._prior_backbone_modules() for p in m.parameters() if p.requires_grad + ) + q_modules = [self.mixture_logits_out, self.mixture_mu_out, self.mixture_tril_out, self.energy_out] + q_trainable = sum(p.numel() for m in q_modules for p in m.parameters() if p.requires_grad) + return { + "u_pathway_params": frozen_params, + "u_pathway_trainable": frozen_trainable, + "q_head_trainable": q_trainable, + } + + def sample_prior_z(self, trans_eq, rotmats_eq, seq, res_mask): + condition, _ = self.forward_prior(trans_eq, rotmats_eq, seq, res_mask) + if not self.sample_coefficients: + return condition + coefficients, component = self.sample_coefficients_from_q(condition) + sampled = self.condition_from_mode_coefficients( + condition["u_global"], + coefficients, + rotmats_eq, + res_mask, + extra={ + key: condition[key] + for key in [ + "mixture_logits", + "mixture_log_probs", + "mixture_mu", + "mixture_scale_tril", + "collective_basis_global", + "collective_target_covariance", + "collective_target_variance", + "collective_retained_fraction", + ] + if key in condition + }, + ) + sampled["sampled_mixture_component"] = component + return sampled + @staticmethod + def repeat_condition(condition, batch_size): + repeated = {} + for key, value in condition.items(): + if torch.is_tensor(value): + repeated[key] = value.repeat(batch_size, *([1] * (value.dim() - 1))) + else: + repeated[key] = value + return repeated + + @staticmethod + def compute_motion_targets(frames_group, x_eq, res_mask, num_modes=8): + """Offline targets from full MD: covariance targets plus oracle PCA modes.""" + with torch.no_grad(): + disp = LatentEncoder.relative_displacement( + frames_group.float(), + x_eq.float(), + res_mask, + ) + if res_mask.dim() == 1: + mask = res_mask.float() + else: + mask = res_mask[0].float() + valid = mask.bool() + disp_centered = disp - disp.mean(dim=0, keepdim=True) + denom = float(max(disp_centered.shape[0] - 1, 1)) + local_cov = torch.einsum("tni,tnj->nij", disp_centered, disp_centered) / denom + cross_cov = torch.einsum("tnd,tmd->nm", disp_centered, disp_centered) / denom + rmsf = torch.sqrt(torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8)) + local_var = torch.diagonal(local_cov, dim1=-2, dim2=-1).sum(dim=-1).clamp_min(1e-8) + dccm = cross_cov / torch.sqrt(local_var[:, None] * local_var[None, :]).clamp_min(1e-8) + local_cov = local_cov * mask[:, None, None] + cross_cov = cross_cov * mask[:, None] * mask[None, :] + dccm = dccm * mask[:, None] * mask[None, :] + rmsf = rmsf * mask + oracle_modes, oracle_energy = LatentEncoder.pca_modes_from_centered_displacement( + disp_centered, + mask, + num_modes=num_modes, + ) + return { + "local_cov": local_cov.detach().cpu(), + "cross_cov": cross_cov.detach().cpu(), + "dccm": dccm.detach().cpu(), + "rmsf": rmsf.detach().cpu(), + "res_mask": mask.detach().cpu(), + "oracle_modes": oracle_modes.detach().cpu(), + "oracle_energy": oracle_energy.detach().cpu(), + "oracle_mean_disp": (disp.mean(dim=0) * mask[:, None]).detach().cpu(), + "num_res": torch.tensor(int(valid.sum().item()), dtype=torch.long), + } + + @staticmethod + def pca_modes_from_centered_displacement(disp_centered, res_mask, num_modes=8): + mask = res_mask.float() + flat = (disp_centered.float() * mask[None, :, None]).reshape(disp_centered.shape[0], -1) + flat = flat - flat.mean(dim=0, keepdim=True) + if flat.shape[0] < 2 or flat.abs().sum() <= 0: + return ( + disp_centered.new_zeros(disp_centered.shape[1], num_modes, 3), + disp_centered.new_zeros(num_modes), + ) + _, singular_values, vh = torch.linalg.svd(flat, full_matrices=False) + take = min(num_modes, vh.shape[0]) + modes = disp_centered.new_zeros(disp_centered.shape[1], num_modes, 3) + modes[:, :take, :] = vh[:take].reshape(take, disp_centered.shape[1], 3).permute(1, 0, 2) + energy = disp_centered.new_zeros(num_modes) + energy[:take] = singular_values[:take].square() / float(max(flat.shape[0] - 1, 1)) + return modes * mask[:, None, None], energy + + @staticmethod + def project_displacement_to_modes(centered_disp, modes, res_mask): + mask = res_mask.float()[:, :, None, None] + modes = modes.float() * mask + disp = centered_disp.float() * res_mask.float()[:, :, None] + numerator = torch.einsum("bnd,bnkd->bk", disp, modes) + denom = modes.square().sum(dim=(1, 3)).clamp_min(1e-8) + return numerator / denom + + @staticmethod + def mode_orthogonality_loss(modes, res_mask): + """Scale-invariant squared cosine penalty over distinct mode pairs.""" + basis = modes.float() * res_mask.float()[:, :, None, None] + gram = torch.einsum("bnkd,bnld->bkl", basis, basis) + norms = torch.diagonal(gram, dim1=-2, dim2=-1).clamp_min(1e-8).sqrt() + # Cosine similarity is scale invariant only when gradients also flow + # through its norm. Detaching this denominator creates a false radial + # gradient that rewards shrinking the raw modes. + denom = norms[:, :, None] * norms[:, None, :] + cosine = gram / denom + eye = torch.eye(gram.shape[-1], device=gram.device, dtype=gram.dtype)[None] + offdiag = 1.0 - eye + return (cosine.square() * offdiag).sum() / ( + offdiag.sum() * gram.shape[0] + ).clamp_min(1.0) + + @staticmethod + def mode_gram_diagnostics(modes, res_mask): + """Measure mode collinearity after masking, without changing the modes.""" + basis = modes.detach().float() * res_mask.float()[:, :, None, None] + gram = torch.einsum("bnkd,bnld->bkl", basis, basis) + eigvals = torch.linalg.eigvalsh(gram.float()) + min_eig = eigvals[:, 0].clamp_min(0.0) + max_eig = eigvals[:, -1].clamp_min(0.0) + condition = max_eig / min_eig.clamp_min(1e-12) + + norms = torch.diagonal(gram, dim1=-2, dim2=-1).clamp_min(1e-12).sqrt() + cosine = gram / (norms[:, :, None] * norms[:, None, :]) + eye = torch.eye(gram.shape[-1], device=gram.device, dtype=torch.bool)[None] + max_cosine = cosine.abs().masked_fill(eye, 0.0).amax(dim=(1, 2)) + return { + "mode_gram_min_eig": min_eig, + "mode_gram_max_eig": max_eig, + "mode_gram_condition": condition, + "mode_max_cosine_abs": max_cosine, + } + + @staticmethod + def project_displacement_lstsq(displacement, modes, res_mask, ridge=1e-4, detach_modes=True): + basis = modes.float() + if detach_modes: + basis = basis.detach() + mask = res_mask.float() + basis = basis * mask[:, :, None, None] + disp = displacement.float() * mask[:, :, None] + gram = torch.einsum("bnkd,bnld->bkl", basis, basis) + rhs = torch.einsum("bnd,bnkd->bk", disp, basis) + eye = torch.eye(modes.shape[2], device=modes.device, dtype=gram.dtype)[None] + # Relative (Levenberg-Marquardt) ridge: an absolute `ridge` (e.g. 1e-4) is + # numerically swallowed in float32 once the unnormalized modes make the gram + # scale large (mode-norm gauge -> gram entries up to ~1e13), leaving a + # near-collinear batch element singular and crashing torch.linalg.solve. + # Scaling the damping by the mean diagonal keeps it effective at every gauge. + scale = torch.diagonal(gram, dim1=-2, dim2=-1).mean(dim=-1).clamp_min(1e-8) + gram = gram.float() + rhs = rhs.float() + coeff = torch.linalg.solve( + gram + (float(ridge) * scale)[:, None, None] * eye, rhs[..., None] + ).squeeze(-1) + return coeff + + @staticmethod + def projection_reconstruction_objective( + displacement, + modes, + coefficients, + res_mask, + ridge=1e-4, + eps=1e-8, + ): + """Evaluate the ridge least-squares value with stop-gradient coefficients.""" + mask = res_mask.float()[:, :, None] + disp = displacement.float() * mask + basis = modes.float() * mask[:, :, None] + coefficients_for_recon = coefficients.detach().float() + recon = torch.einsum( + "bk,bnkd->bnd", coefficients_for_recon, basis + ) + residual_sq = ((disp - recon).square() * mask).sum(dim=(1, 2)) + target_sq = (disp.square() * mask).sum(dim=(1, 2)).clamp_min(float(eps)) + ridge_sq = float(ridge) * coefficients_for_recon.square().sum(dim=-1) + return { + "loss": (residual_sq + ridge_sq) / target_sq, + "rel_error": torch.sqrt(residual_sq / target_sq), + "recon": recon, + } + + @staticmethod + def _masked_corr(pred, target, mask): + pred = pred.float()[mask.bool()] + target = target.float()[mask.bool()] + if pred.numel() < 2: + return pred.new_zeros(()) + pred = pred - pred.mean() + target = target - target.mean() + denom = pred.norm() * target.norm() + if denom <= 1e-8: + return pred.new_zeros(()) + return (pred * target).sum() / denom + + @staticmethod + def _top_abs_sign_agree(pred, target, mask, fraction=0.1): + pred = pred.float()[mask.bool()] + target = target.float()[mask.bool()] + if pred.numel() == 0: + return pred.new_zeros(()) + k = max(1, int(round(float(pred.numel()) * fraction))) + k = min(k, pred.numel()) + idx = torch.topk(target.abs(), k=k, largest=True).indices + return (torch.sign(pred[idx]) == torch.sign(target[idx])).float().mean() + + def motion_alignment_metrics(self, condition, targets, res_mask, spatial_dists): + with torch.no_grad(): + mask = res_mask.float() + pair_mask = mask[:, :, None] * mask[:, None, :] + eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None] + offdiag_mask = pair_mask * (1.0 - eye) + spatial_dists = spatial_dists.to(device=mask.device, dtype=condition["cross_cov_pred"].dtype) + near_mask = offdiag_mask * (spatial_dists <= self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype) + far_mask = offdiag_mask * (spatial_dists > self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype) + pred = condition["cross_cov_pred"].detach().float() + target = targets["cross_cov"].to(device=pred.device, dtype=pred.dtype) + return { + "cross_cov_corr_all": self._masked_corr(pred, target, offdiag_mask), + "cross_cov_near_corr": self._masked_corr(pred, target, near_mask), + "cross_cov_far_corr": self._masked_corr(pred, target, far_mask), + "cross_cov_near_top10_sign_agree": self._top_abs_sign_agree(pred, target, near_mask), + "cross_cov_far_top10_sign_agree": self._top_abs_sign_agree(pred, target, far_mask), + "cross_cov_near_pred_abs_mean": (pred.abs() * near_mask).sum() / near_mask.sum().clamp_min(1.0), + "cross_cov_near_true_abs_mean": (target.abs() * near_mask).sum() / near_mask.sum().clamp_min(1.0), + "cross_cov_far_pred_abs_mean": (pred.abs() * far_mask).sum() / far_mask.sum().clamp_min(1.0), + "cross_cov_far_true_abs_mean": (target.abs() * far_mask).sum() / far_mask.sum().clamp_min(1.0), + } + + def rigid_component_metrics(self, condition, trans_eq, res_mask): + with torch.no_grad(): + center = self._masked_mean(trans_eq.float(), res_mask) + coords = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None] + translation, omega, _ = self._fit_rigid_motion(condition["u_global"], coords, res_mask) + translation = translation.float() + omega = omega.float() + return { + "rigid_translation_abs_mean": translation.abs().mean(), + "rigid_translation_abs_max": translation.abs().max(), + "rigid_rotation_omega_abs_mean": omega.abs().mean(), + "rigid_rotation_omega_abs_max": omega.abs().max(), + } + + @staticmethod + def _mode_subspace_basis(u_global, res_mask): + mask = res_mask.float()[:, :, None, None] + u = (u_global.float() * mask).permute(0, 2, 1, 3).reshape(u_global.shape[0], u_global.shape[2], -1) + bases = [] + for sample in u: + matrix = sample.transpose(0, 1) + q, _ = torch.linalg.qr(matrix.float(), mode="reduced") + bases.append(q) + return torch.stack(bases, dim=0) + + @staticmethod + def _mode_subspace_loss(pred_modes, target_modes, res_mask): + pred_basis = LatentEncoder._mode_subspace_basis(pred_modes, res_mask) + target_basis = LatentEncoder._mode_subspace_basis(target_modes, res_mask) + overlap = torch.matmul(pred_basis.transpose(-1, -2), target_basis).square().sum(dim=(-1, -2)) + num_modes = pred_basis.shape[-1] + normalized_overlap = (overlap / float(max(num_modes, 1))).clamp(0.0, 1.0) + return 1.0 - normalized_overlap.mean(), normalized_overlap.mean().detach() + + @staticmethod + def _masked_flat_modes(modes, res_mask): + mask = res_mask.float()[:, :, None, None] + modes = modes.float() * mask + return modes.permute(0, 2, 1, 3).reshape(modes.shape[0], modes.shape[2], -1) + + def md_subspace_shape_loss(self, condition, targets, res_mask, eps=1e-8, weight_exp=0.0): + """Match the model's implied covariance to MD's, in MD's own eigenbasis. + + No sampling enters. ``Cov[c]`` is closed form under the mixture, ``U`` is the + encoder output, and the reference eigenvectors ``V`` and variances ``beta`` are + precomputed from the full trajectory. The group of ``G`` conformations that the + collective objective needs in order to *estimate* a covariance is therefore not + required: what it was estimating from 8 samples is already known exactly from + ~10^4. The ``G < k`` rank deficiency that forced the rank-4 restriction does not + arise either, since no sample covariance is inverted or square-rooted. + + With ``V`` orthonormal, ``M = V^T U`` and ``A = M Cov[c] M^T`` is the model's + covariance expressed in the reference eigenbasis, against the diagonal target + ``B = diag(beta)``. + + The residual is normalised by the norm of the target, so the loss is 1.0 when the + model produces no covariance and approaches 0 as ``A`` approaches ``B``. It is + scale sensitive -- dilating the model rescales ``Cov[c]`` -- so it does not carry + the dilation invariance that made the covariance-entry correlation useless as an + optimisation target. + + ``md_subspace_diag_sq`` and ``md_subspace_offdiag_sq`` are reported separately and + in absolute terms: the off-diagonal part is the eigenvector misalignment and the + diagonal part is the variance error, and a ratio between them moves whenever + either does, so the share is not reported. + """ + u_global = condition["u_global"].float() + modes = targets["oracle_modes"].to(device=u_global.device).float() + energy = targets["oracle_energy"].to(device=u_global.device).float() + + mask = res_mask.float()[:, :, None, None] + u_global = u_global * mask + modes = modes * mask + + # Stored reference modes are unit norm, but masking removes weight; the + # projection below assumes orthonormal columns. + mode_norm = modes.square().sum(dim=(1, 3)).clamp_min(eps).sqrt() + modes = modes / mode_norm[:, None, :, None] + + projection = torch.einsum("bnrd,bnkd->brk", modes, u_global) + _, coeff_cov = mixture_mean_and_covariance( + condition["mixture_logits"], + condition["mixture_mu"], + condition["mixture_scale_tril"], + ) + implied = projection @ coeff_cov @ projection.transpose(1, 2) + + target_var = energy.clamp_min(eps) + # `weight_exp` is applied on both sides, so the residual is weighted by + # `beta**(2*weight_exp)`. + # + # -0.25 the local quadratic approximation to the Bures metric. It weights + # every direction by its *relative* error, which up-weights the small + # eigenvalues -- directions 9-12 here -- and down-weights the leading + # ones by the same factor. + # 0.00 plain Frobenius: absolute error, dominated by the largest eigenvalues. + # +0.25 emphasises the leading directions further still. + # + # The evaluation is an absolute W2 restricted to the leading principal + # directions, so it is dominated by the largest eigenvalues. Bures weighting + # therefore spends the objective on precisely the directions the score cannot + # see, and the measured symptom matches: the generated ensembles carry 0.403 of + # the reference's 0.552 variance in the top two directions while exceeding it + # overall. Default is unweighted. + weight = target_var.pow(float(weight_exp)) if weight_exp != 0.0 else None + residual = (implied - torch.diag_embed(target_var)) + if weight is not None: + residual = residual * weight[:, :, None] * weight[:, None, :] + # Divide by the norm of the (identically weighted) target, so the loss is + # exactly 1.0 when the model produces no covariance at all and falls toward 0 + # as A approaches B. That fixes the scale for any `weight_exp` and for any + # protein, which is what makes a single lambda meaningful: without it the + # magnitude tracks the spectrum and lambda has to be re-guessed per + # configuration. The previous version ran with the term roughly 100x + # official_loss, which is how an auxiliary objective ends up steering the + # backbone. + weighted_target = target_var if weight is None else target_var * weight.square() + denom = weighted_target.square().sum(dim=-1).clamp_min(eps) + shape_loss = (residual.square().sum(dim=(1, 2)) / denom).mean() + + implied_trace = torch.diagonal(implied, dim1=-2, dim2=-1).sum(dim=-1) + target_trace = target_var.sum(dim=-1).clamp_min(eps) + trace_loss = ((implied_trace / target_trace) - 1.0).square().mean() + + with torch.no_grad(): + diag = torch.diagonal(residual, dim1=-2, dim2=-1) + diag_sq = diag.square().sum(dim=-1) + offdiag_sq = residual.square().sum(dim=(1, 2)) - diag_sq + # Absolute, not the ratio. The share moves whenever *either* part moves, so a + # trace term shrinking the diagonal inflates it even with the off-diagonal + # error flat -- the same defect that made the covariance-entry correlation + # useless. Read these two independently. + variance_ratio = (implied_trace / target_trace).mean() + + # Direction only: mean squared cosine of the principal angles between + # span(U) and span(V). Orthonormalise U first, since its columns are neither + # unit norm nor mutually orthogonal. Amplitude cannot move this. + num_modes = u_global.shape[2] + u_flat = u_global.permute(0, 2, 1, 3).reshape(u_global.shape[0], num_modes, -1) + q_basis, _ = torch.linalg.qr(u_flat.transpose(1, 2)) + v_flat = modes.permute(0, 2, 1, 3).reshape(modes.shape[0], modes.shape[2], -1) + cosines = torch.bmm(v_flat, q_basis) + span_overlap = ( + cosines.square().sum(dim=(1, 2)) / float(min(modes.shape[2], num_modes)) + ).mean() + + # The floor this family imposes, independent of Cov[c]: + # inf_{Gamma >= 0} W2^2(M Gamma M^T, B) / tr B = tr((I - P_M) B) / tr B + # with P_M the projector onto range(M). No choice of q can beat it, so a + # shape loss stalling near this value means the modes, not the mixture, are + # the binding constraint. It is identically zero whenever M has full row + # rank -- with as many reference modes as model modes that is the generic + # case, and the number only becomes informative once the cache carries more + # reference directions than the model has. + left, sing, _ = torch.linalg.svd(projection, full_matrices=False) + keep = (sing > sing[..., :1].clamp_min(eps) * 1e-6).to(left.dtype) + left = left * keep[:, None, :] + proj_diag = left.square().sum(dim=-1) + floor = ( + ((1.0 - proj_diag) * target_var).sum(dim=-1) / target_trace + ).clamp_min(0.0).sqrt().mean() + + return { + "md_subspace_shape_loss": shape_loss, + "md_subspace_trace_loss": trace_loss, + "md_subspace_variance_ratio": variance_ratio, + "md_subspace_diag_sq": diag_sq.mean(), + "md_subspace_offdiag_sq": offdiag_sq.mean(), + "md_subspace_span_overlap": span_overlap, + "md_subspace_floor": floor, + } + + def pca_alignment_loss(self, condition, targets, res_mask, top_m=2): + """Favor assigning high predicted energy to modes aligned with MD top PCs.""" + pred_modes = condition["u_global"].float() + target_modes = targets["oracle_modes"].to( + device=pred_modes.device, + dtype=torch.float32, + ) + top_m = int(max(1, min(top_m, pred_modes.shape[2], target_modes.shape[2]))) + target_modes = target_modes[:, :, :top_m, :] + + pred_flat = F.normalize(self._masked_flat_modes(pred_modes, res_mask), dim=-1, eps=1e-8) + target_basis = self._mode_subspace_basis(target_modes, res_mask) + mode_overlap = torch.matmul(pred_flat, target_basis).square().sum(dim=-1).clamp(0.0, 1.0) + + energy = condition["energy"].float().clamp_min(1e-8) + weights = energy / energy.sum(dim=-1, keepdim=True).clamp_min(1e-8) + weighted_overlap = (weights * mode_overlap).sum(dim=-1) + pca_align_loss = 1.0 - weighted_overlap.mean() + + with torch.no_grad(): + order = torch.argsort(energy, dim=-1, descending=True) + top1_overlap = mode_overlap.gather(1, order[:, :1]).mean() + best_overlap = mode_overlap.max(dim=-1).values.mean() + top_idx = order[:, :top_m] + gather_idx = top_idx[:, None, :, None].expand(-1, pred_modes.shape[1], -1, pred_modes.shape[-1]) + pred_top_modes = pred_modes.gather(2, gather_idx) + _, top_subspace_overlap = self._mode_subspace_loss(pred_top_modes, target_modes, res_mask) + + return { + "pca_align_loss": pca_align_loss, + "pca_align_weighted_overlap": weighted_overlap.detach().mean(), + "pca_align_best_overlap": best_overlap, + "pca_align_top_energy_overlap": top1_overlap, + "pca_align_top_energy_subspace_overlap": top_subspace_overlap, + } + + def enm_initialization_loss(self, condition, trans_eq, res_mask): + """Warmup loss that aligns only the ENM direction subspace. + + ENM is used only as an initialization target. It is not an input feature + and does not appear in the mode forward formula. The projection loss is + invariant to per-mode sign flips and rotations inside a near-degenerate + ENM subspace, unlike ordered mode-by-mode cosine matching. + """ + targets = self._enm_motion_targets(trans_eq, res_mask) + target_modes = targets["enm_modes"].to(device=condition["u_global"].device, dtype=torch.float32) + center = self._masked_mean(trans_eq.float(), res_mask) + centered = (trans_eq.float() - center[:, None, :]) * res_mask.float()[:, :, None] + if self.template_remove_rotation: + target_modes = self._remove_rigid_component(target_modes, centered, res_mask) + subspace_loss, subspace_overlap = self._mode_subspace_loss( + condition["u_global"].float(), + target_modes, + res_mask, + ) + with torch.autocast(device_type=trans_eq.device.type, enabled=False): + spatial_dists = torch.cdist(trans_eq.float(), trans_eq.float()) + align = self.motion_alignment_metrics(condition, targets, res_mask, spatial_dists) + metrics = { + "enm_warmup_loss": subspace_loss, + "enm_warmup_subspace_loss": subspace_loss.detach(), + "enm_warmup_subspace_overlap": subspace_overlap, + } + metrics.update({f"enm_warmup_{key}": value for key, value in align.items()}) + + return metrics + def motion_recon_loss(self, condition, targets, res_mask, spatial_dists=None): + mask = res_mask.float() + pair_mask = mask[:, :, None] * mask[:, None, :] + eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None] + offdiag_mask = pair_mask * (1.0 - eye) + local_mask = mask[..., None, None] + + local_target = targets["local_cov"].to(condition["local_cov_pred"].device, condition["local_cov_pred"].dtype) + cross_target = targets["cross_cov"].to(condition["cross_cov_pred"].device, condition["cross_cov_pred"].dtype) + rmsf_target = targets["rmsf"].to(condition["rmsf_pred"].device, condition["rmsf_pred"].dtype) + + local_diff = (condition["local_cov_pred"] - local_target) * local_mask + local_denom = ((local_target * local_mask).square().sum() / local_mask.sum().clamp_min(1.0)).clamp_min(1e-6) + local_cov_loss = (local_diff.square().sum() / local_mask.sum().clamp_min(1.0)) / local_denom + + if spatial_dists is None: + raise ValueError("spatial_dists is required for near/far cross-cov diagnostics") + spatial_dists = spatial_dists.to(device=mask.device, dtype=condition["cross_cov_pred"].dtype) + near_mask = offdiag_mask * (spatial_dists <= self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype) + far_mask = offdiag_mask * (spatial_dists > self.cross_cov_near_distance).to(dtype=offdiag_mask.dtype) + + cross_diff = (condition["cross_cov_pred"] - cross_target) * offdiag_mask + cross_denom = ((cross_target * offdiag_mask).square().sum() / offdiag_mask.sum().clamp_min(1.0)).clamp_min(1e-6) + cross_cov_loss = (cross_diff.square().sum() / offdiag_mask.sum().clamp_min(1.0)) / cross_denom + + near_diff = (condition["cross_cov_pred"] - cross_target) * near_mask + near_denom = ((cross_target * near_mask).square().sum() / near_mask.sum().clamp_min(1.0)).clamp_min(1e-6) + cross_cov_near_loss = (near_diff.square().sum() / near_mask.sum().clamp_min(1.0)) / near_denom + + far_diff = (condition["cross_cov_pred"] - cross_target) * far_mask + far_denom = ((cross_target * far_mask).square().sum() / far_mask.sum().clamp_min(1.0)).clamp_min(1e-6) + cross_cov_far_loss = (far_diff.square().sum() / far_mask.sum().clamp_min(1.0)) / far_denom + + rmsf_diff = (condition["rmsf_pred"] - rmsf_target) * mask + rmsf_denom = ((rmsf_target * mask).square().sum() / mask.sum().clamp_min(1.0)).clamp_min(1e-6) + rmsf_loss = (rmsf_diff.square().sum() / mask.sum().clamp_min(1.0)) / rmsf_denom + + losses = { + "local_cov_loss": local_cov_loss, + "cross_cov_loss": cross_cov_loss, + "cross_cov_near_loss": cross_cov_near_loss, + "cross_cov_far_loss": cross_cov_far_loss, + "rmsf_loss": rmsf_loss, + } + if "oracle_modes" in targets: + losses.update(self.pca_alignment_loss( + condition, + targets, + res_mask, + top_m=int(getattr(self, "pca_align_top_m", 2)), + )) + return losses + + def generator_response_cov_loss( + self, + response_deltas, + res_mask, + targets, + use_cross=False, + sample_weight=None, + teacher_response_deltas=None, + teacher_trace_anchor=None, + teacher_trace_denominator="teacher", + amplitude_anchor="teacher_trace", + trace_target_scale=None, + ): + """Match generator response shape without rewarding global expansion. + + ``response_deltas`` has shape ``(S, B, N, 3)`` and contains antithetic + central-difference responses for S independent coefficient perturbations. + The loss first averages ``d d^T`` over S and then normalizes by total + response trace before comparing to MD covariance. This avoids the v1 + shortcut where a single rank-1 sample, or a globally amplified response, + can reduce the generator-response objective. + + If ``teacher_response_deltas`` is provided, a weak trace anchor keeps the + current response norm near the frozen initial/A30 response under the same + ``t`` and coefficient perturbations. This anchor does not assume that + one-step trace equals the 20-step inference ensemble trace. + """ + with torch.autocast(device_type=res_mask.device.type, enabled=False): + d = response_deltas.float() + if d.dim() == 3: + d = d[None] + mask = res_mask.float() + if sample_weight is not None: + mask = mask * sample_weight.float().to(mask.device)[:, None] + d = d * mask[None, :, :, None] + + local_target = targets["local_cov"].to(device=d.device, dtype=d.dtype) + target_mask = res_mask.float().to(device=d.device, dtype=d.dtype) + local_mask = mask[:, :, None, None] + target_local_mask = target_mask[:, :, None, None] + + local_sample = torch.einsum("sbni,sbnj->bnij", d, d) / float(d.shape[0]) + trace_sample = ( + torch.diagonal(local_sample, dim1=-2, dim2=-1).sum(dim=-1) * mask + ).sum(dim=-1).clamp_min(1e-8) + trace_target = ( + torch.diagonal(local_target, dim1=-2, dim2=-1).sum(dim=-1) * target_mask + ).sum(dim=-1).clamp_min(1e-8) + local_sample_norm = local_sample / trace_sample[:, None, None, None] + local_target_norm = local_target / trace_target[:, None, None, None] + local_diff = (local_sample_norm - local_target_norm) * local_mask + local_denom = ( + (local_target_norm * target_local_mask).square().sum() + / target_local_mask.sum().clamp_min(1.0) + ).clamp_min(1e-8) + local_shape_loss = ( + local_diff.square().sum() / local_mask.sum().clamp_min(1.0) + ) / local_denom + + losses = { + "gen_local_shape_loss": local_shape_loss, + } + metrics = { + "gen_response_abs_mean": d.detach().abs().mean(), + "gen_response_trace_mean": trace_sample.detach().mean(), + "gen_response_active_frac": ( + mask.sum() / res_mask.float().sum().clamp_min(1.0) + ).detach(), + } + + anchor_trace = None + if amplitude_anchor in ("md_trace", "rollout_trace"): + # Anchor the response magnitude to the MD ensemble's own trace. + # trace_target is already computed above for the shape normalization, + # so this needs no teacher and no extra forwards. + # "rollout_trace" divides the MD trace by a detached no-grad + # rollout-measured trace amplification factor before anchoring. + # + # The "teacher_trace" anchor below is unusable in this codebase: the frozen + # teacher is deep-copied from the model at step 0, where every condition + # adapter (embedder z_*/disp_* adapters and bbflow_model film_mlp) is + # zero-initialized so that a warm-started model reproduces vanilla BBFlow. + # The teacher's response to c is therefore identically zero forever, so + # teacher_trace pins to the 1e-8 clamp floor and log(trace_sample/1e-8)^2 + # drives the student's response to zero -- the opposite of the anchor's + # purpose. A model that ignores c cannot calibrate a response to c. + anchor_trace = trace_target + if trace_target_scale is not None: + scale = trace_target_scale.to(device=d.device, dtype=d.dtype) + anchor_trace = anchor_trace * scale.reshape(-1)[0].clamp_min(1e-8) + elif amplitude_anchor != "none" and ( + teacher_response_deltas is not None or teacher_trace_anchor is not None + ): + if teacher_trace_anchor is not None: + teacher_trace = teacher_trace_anchor.to(device=d.device, dtype=d.dtype) + if teacher_trace.dim() > 1: + teacher_trace = teacher_trace.reshape(teacher_trace.shape[0], -1).mean(dim=-1) + teacher_trace = teacher_trace.reshape(-1).clamp_min(1e-8) + else: + teacher_d = teacher_response_deltas.float() + if teacher_d.dim() == 3: + teacher_d = teacher_d[None] + teacher_d = teacher_d.to(device=d.device, dtype=d.dtype) * mask[None, :, :, None] + if teacher_trace_denominator == "teacher": + teacher_denom = float(teacher_d.shape[0]) + elif teacher_trace_denominator == "student": + teacher_denom = float(d.shape[0]) + elif teacher_trace_denominator == "none": + teacher_denom = 1.0 + else: + raise ValueError( + "teacher_trace_denominator must be one of " + f"'teacher', 'student', or 'none'; got {teacher_trace_denominator!r}" + ) + teacher_local = ( + torch.einsum("sbni,sbnj->bnij", teacher_d, teacher_d) + / teacher_denom + ) + teacher_trace = ( + torch.diagonal(teacher_local, dim1=-2, dim2=-1).sum(dim=-1) * mask + ).sum(dim=-1).clamp_min(1e-8) + anchor_trace = teacher_trace + + if anchor_trace is not None: + valid = (mask.sum(dim=-1) > 0).to(dtype=d.dtype) + trace_ratio = (trace_sample / anchor_trace).clamp_min(1e-8) + trace_loss = (trace_ratio.log().square() * valid).sum() / valid.sum().clamp_min(1.0) + losses["gen_trace_anchor_loss"] = trace_loss + # Ratio to whichever amplitude anchor is active (MD trace or teacher trace). + # Healthy value is ~1; orders of magnitude away means the anchor is broken. + metrics["gen_trace_ratio_to_teacher"] = ( + (trace_sample.detach() / anchor_trace.detach()).clamp_min(1e-8) + * valid + ).sum() / valid.sum().clamp_min(1.0) + metrics["gen_trace_ratio_to_anchor"] = metrics["gen_trace_ratio_to_teacher"] + metrics["gen_trace_anchor_mean"] = anchor_trace.detach().mean() + + if use_cross: + pair_mask = mask[:, :, None] * mask[:, None, :] + target_pair_mask = target_mask[:, :, None] * target_mask[:, None, :] + eye = torch.eye(mask.shape[1], device=mask.device, dtype=pair_mask.dtype)[None] + offdiag_mask = pair_mask * (1.0 - eye) + target_offdiag_mask = target_pair_mask * (1.0 - eye) + cross_target = targets["cross_cov"].to(device=d.device, dtype=d.dtype) + cross_sample = torch.einsum("sbnd,sbmd->bnm", d, d) / float(d.shape[0]) + cross_sample_norm = cross_sample / trace_sample[:, None, None] + cross_target_norm = cross_target / trace_target[:, None, None] + cross_diff = (cross_sample_norm - cross_target_norm) * offdiag_mask + cross_denom = ( + (cross_target_norm * target_offdiag_mask).square().sum() + / target_offdiag_mask.sum().clamp_min(1.0) + ).clamp_min(1e-8) + cross_shape_loss = ( + cross_diff.square().sum() / offdiag_mask.sum().clamp_min(1.0) + ) / cross_denom + losses["gen_cross_shape_loss"] = cross_shape_loss + return losses, metrics + + def motion_metrics(self, condition, res_mask): + with torch.no_grad(): + mask = res_mask.float() + energy = condition["energy"].float() + energy_sum = energy.sum(dim=-1).clamp_min(1e-8) + prob = energy / energy_sum[:, None] + entropy = -(prob * prob.clamp_min(1e-8).log()).sum(dim=-1) + effective_modes = torch.exp(entropy) + u_flat = condition["u_global"].float().permute(0, 2, 1, 3).reshape(condition["u_global"].shape[0], condition["u_global"].shape[2], -1) + u_flat = F.normalize(u_flat, dim=-1) + if self.num_modes > 1: + cos = torch.matmul(u_flat, u_flat.transpose(-1, -2)) + eye = torch.eye(self.num_modes, device=cos.device, dtype=torch.bool)[None].expand_as(cos) + mode_cosine_abs = cos.masked_select(~eye).abs().mean() + else: + mode_cosine_abs = energy.new_zeros(()) + metrics = { + "latent_energy_mean": energy.mean(), + "latent_energy_std": energy.std(), + "latent_effective_modes": effective_modes.mean(), + "latent_mode_cosine_abs": mode_cosine_abs, + "latent_node_cond_abs": condition["node_cond"].detach().abs().mean(), + "latent_edge_cond_abs": condition["edge_cond"].detach().abs().mean(), + "latent_u_global_abs": condition["u_global"].detach().abs().mean(), + "latent_u_position_std": (condition["u_global"].detach().float() * mask[:, :, None, None]).std(), + } + if "template_participation" in condition: + metrics.update({ + "latent_template_participation_abs": condition["template_participation"].detach().float().abs().mean(), + "latent_template_omega_abs": condition["template_omega"].detach().float().abs().mean(), + "latent_template_velocity_abs": condition["template_velocity"].detach().float().abs().mean(), + "latent_template_residual_abs": condition["template_residual_global"].detach().float().abs().mean(), + }) + if "mixture_logits" in condition: + diag = torch.diagonal(condition["mixture_scale_tril"].detach().float(), dim1=-2, dim2=-1) + metrics.update({ + "q_mixture_entropy": self._mixture_entropy(condition["mixture_logits"].detach()).mean(), + "q_mu_abs": condition["mixture_mu"].detach().float().abs().mean(), + "q_scale_diag_mean": diag.mean(), + "q_scale_diag_std": diag.std(), + }) + return metrics diff --git a/bbflow_base/code_exports/a30_redesign_source_20260719/MANIFEST_A30_REDESIGN.txt b/bbflow_base/code_exports/a30_redesign_source_20260719/MANIFEST_A30_REDESIGN.txt new file mode 100644 index 0000000000000000000000000000000000000000..e07bda5068bf689dc50ceef64a20c31997234470 --- /dev/null +++ b/bbflow_base/code_exports/a30_redesign_source_20260719/MANIFEST_A30_REDESIGN.txt @@ -0,0 +1,68 @@ +A30 redesign source package (2026-07-19) +========================================= + +Included local files +-------------------- +Core A30/latent/condition: +- bbflow/models/latent.py +- bbflow/models/bbflow_module.py +- bbflow/models/embedder.py +- bbflow/models/bbflow_model.py + +Sampling/inference/training entry points: +- bbflow/data/interpolant_bbflow.py +- experiments/train.py +- experiments/inference.py +- base_stages/00_train_final_mog_ddp.sh +- configs/train.yaml +- configs/inference.yaml +- configs/experiment/default.yaml + +Handoff / experiment records: +- docs/HANDOFF_2026-07-17.txt +- docs/experiment_trace_2026-07-05.md +- docs/protein_project_conversation_record_2026-07-13.txt (if present) + +Why these files +--------------- +- latent.py: mode generation/normalization, MoG q-head, coefficient sampling, latent/motion losses. +- bbflow_module.py: A30 condition construction/use, training losses, freeze logic, generator-response code, sampling/predict entry. +- embedder.py: z_node_adapter, z_edge_adapter, disp_node_adapter, disp_edge_adapter definitions and injection calls. +- bbflow_model.py: film_mlp definition and FiLM application. +- interpolant_bbflow.py: BBFlow sampling wrapper and condition use during sampling. +- train.py/inference.py: warm-start/loading/config resolution; strict=False paths. +- 00_train_final_mog_ddp.sh: actual A30/final MoG training launcher and Hydra overrides. + +Server-only files still needed from GAFL +---------------------------------------- +Local workspace does NOT contain the sibling GAFL repository. On the server, copy these files into the package before sending to Claude: + +1. /home/wangyusong/LD-FPG-main/gafl/gafl/data/interpolant.py + Required because bbflow_module/interpolant call _trans_euler_step and _rots_euler_step there. + +2. /home/wangyusong/LD-FPG-main/gafl/gafl/models/gafl/cfa.py + Required because OOM and main attention-like compute path occurred here; important for speed/memory redesign. + +3. Optional but useful if Claude wants full GAFL model context: + /home/wangyusong/LD-FPG-main/gafl/gafl/models/gafl/*.py + /home/wangyusong/LD-FPG-main/gafl/gafl/data/*.py + +A30 resolved config still needed from server +-------------------------------------------- +A30 run directory from records: +/data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_energy_from_q_diag_orth1_recon0_30ep_3gpu_20260707_165355 + +Copy at least: +- config.yaml +- latent_train_epoch_metrics.csv +- last.ckpt path only if Claude needs checkpoint metadata; do not send huge ckpt unless requested. + +Server commands to add missing files +------------------------------------ +cd ~/LD-FPG-main +PKG=/data/shared/wangyusong/atals/bbflow_official_reproduction/code_exports/a30_redesign_source_20260719 +mkdir -p "$PKG/gafl/gafl/data" "$PKG/gafl/gafl/models/gafl" "$PKG/a30_run" +cp gafl/gafl/data/interpolant.py "$PKG/gafl/gafl/data/interpolant.py" +cp gafl/gafl/models/gafl/cfa.py "$PKG/gafl/gafl/models/gafl/cfa.py" +cp /data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_energy_from_q_diag_orth1_recon0_30ep_3gpu_20260707_165355/config.yaml "$PKG/a30_run/config.yaml" +cp /data/shared/wangyusong/atals/bbflow_official_reproduction/outputs/checkpoints/bbflow_base_energy_from_q_diag_orth1_recon0_30ep_3gpu_20260707_165355/latent_train_epoch_metrics.csv "$PKG/a30_run/latent_train_epoch_metrics.csv" 2>/dev/null || true diff --git a/bbflow_base/dataset_csv/ATLAS_split/ATLAS_test.csv b/bbflow_base/dataset_csv/ATLAS_split/ATLAS_test.csv new file mode 100644 index 0000000000000000000000000000000000000000..c32d0ab2bd95aef0e0374fd17208a2a71305c563 --- /dev/null +++ b/bbflow_base/dataset_csv/ATLAS_split/ATLAS_test.csv @@ -0,0 +1,83 @@ +name,pdb_path +6o2vA,./datasets/ATLAS/6o2vA/6o2vA.pdb +7eadA,./datasets/ATLAS/7eadA/7eadA.pdb +6uofA,./datasets/ATLAS/6uofA/6uofA.pdb +6lusA,./datasets/ATLAS/6lusA/6lusA.pdb +6qj0A,./datasets/ATLAS/6qj0A/6qj0A.pdb +6j56A,./datasets/ATLAS/6j56A/6j56A.pdb +7ec1A,./datasets/ATLAS/7ec1A/7ec1A.pdb +6xdsA,./datasets/ATLAS/6xdsA/6xdsA.pdb +6xrxA,./datasets/ATLAS/6xrxA/6xrxA.pdb +6q9cB,./datasets/ATLAS/6q9cB/6q9cB.pdb +6rrvA,./datasets/ATLAS/6rrvA/6rrvA.pdb +7laoA,./datasets/ATLAS/7laoA/7laoA.pdb +6l4lA,./datasets/ATLAS/6l4lA/6l4lA.pdb +7asgA,./datasets/ATLAS/7asgA/7asgA.pdb +6ktyA,./datasets/ATLAS/6ktyA/6ktyA.pdb +6vjgA,./datasets/ATLAS/6vjgA/6vjgA.pdb +6smsA,./datasets/ATLAS/6smsA/6smsA.pdb +6l3rE,./datasets/ATLAS/6l3rE/6l3rE.pdb +7qsuA,./datasets/ATLAS/7qsuA/7qsuA.pdb +7p46A,./datasets/ATLAS/7p46A/7p46A.pdb +7e2sA,./datasets/ATLAS/7e2sA/7e2sA.pdb +6pxzB,./datasets/ATLAS/6pxzB/6pxzB.pdb +6ovkR,./datasets/ATLAS/6ovkR/6ovkR.pdb +6ndwB,./datasets/ATLAS/6ndwB/6ndwB.pdb +6pceB,./datasets/ATLAS/6pceB/6pceB.pdb +7p41D,./datasets/ATLAS/7p41D/7p41D.pdb +6h86A,./datasets/ATLAS/6h86A/6h86A.pdb +7jflC,./datasets/ATLAS/7jflC/7jflC.pdb +6iahA,./datasets/ATLAS/6iahA/6iahA.pdb +6y2xA,./datasets/ATLAS/6y2xA/6y2xA.pdb +7nmqA,./datasets/ATLAS/7nmqA/7nmqA.pdb +6xb3H,./datasets/ATLAS/6xb3H/6xb3H.pdb +6jwhA,./datasets/ATLAS/6jwhA/6jwhA.pdb +6l4pB,./datasets/ATLAS/6l4pB/6l4pB.pdb +6jptA,./datasets/ATLAS/6jptA/6jptA.pdb +7a66B,./datasets/ATLAS/7a66B/7a66B.pdb +6okdC,./datasets/ATLAS/6okdC/6okdC.pdb +6in7A,./datasets/ATLAS/6in7A/6in7A.pdb +7onnA,./datasets/ATLAS/7onnA/7onnA.pdb +6onoC,./datasets/ATLAS/6onoC/6onoC.pdb +6d7yA,./datasets/ATLAS/6d7yA/6d7yA.pdb +6oddB,./datasets/ATLAS/6oddB/6oddB.pdb +6p5xB,./datasets/ATLAS/6p5xB/6p5xB.pdb +6tgkC,./datasets/ATLAS/6tgkC/6tgkC.pdb +7dmnA,./datasets/ATLAS/7dmnA/7dmnA.pdb +7lp1A,./datasets/ATLAS/7lp1A/7lp1A.pdb +6l34A,./datasets/ATLAS/6l34A/6l34A.pdb +7nedA,./datasets/ATLAS/7nedA/7nedA.pdb +7s86A,./datasets/ATLAS/7s86A/7s86A.pdb +6l8sA,./datasets/ATLAS/6l8sA/6l8sA.pdb +7bwfB,./datasets/ATLAS/7bwfB/7bwfB.pdb +7aexA,./datasets/ATLAS/7aexA/7aexA.pdb +6d7yB,./datasets/ATLAS/6d7yB/6d7yB.pdb +6e7eA,./datasets/ATLAS/6e7eA/6e7eA.pdb +7k7pB,./datasets/ATLAS/7k7pB/7k7pB.pdb +7buyA,./datasets/ATLAS/7buyA/7buyA.pdb +6yhuB,./datasets/ATLAS/6yhuB/6yhuB.pdb +6h49A,./datasets/ATLAS/6h49A/6h49A.pdb +7aqxA,./datasets/ATLAS/7aqxA/7aqxA.pdb +7c45A,./datasets/ATLAS/7c45A/7c45A.pdb +6gusA,./datasets/ATLAS/6gusA/6gusA.pdb +6q9cA,./datasets/ATLAS/6q9cA/6q9cA.pdb +7n0jE,./datasets/ATLAS/7n0jE/7n0jE.pdb +6o6yA,./datasets/ATLAS/6o6yA/6o6yA.pdb +6zslB,./datasets/ATLAS/6zslB/6zslB.pdb +7rm7A,./datasets/ATLAS/7rm7A/7rm7A.pdb +6ypiA,./datasets/ATLAS/6ypiA/6ypiA.pdb +6ro6A,./datasets/ATLAS/6ro6A/6ro6A.pdb +7mf4A,./datasets/ATLAS/7mf4A/7mf4A.pdb +7jrqA,./datasets/ATLAS/7jrqA/7jrqA.pdb +7wabA,./datasets/ATLAS/7wabA/7wabA.pdb +5znjA,./datasets/ATLAS/5znjA/5znjA.pdb +6pnvA,./datasets/ATLAS/6pnvA/6pnvA.pdb +6rwtA,./datasets/ATLAS/6rwtA/6rwtA.pdb +6oz1A,./datasets/ATLAS/6oz1A/6oz1A.pdb +6nl2A,./datasets/ATLAS/6nl2A/6nl2A.pdb +6p5hA,./datasets/ATLAS/6p5hA/6p5hA.pdb +6q10A,./datasets/ATLAS/6q10A/6q10A.pdb +6jv8A,./datasets/ATLAS/6jv8A/6jv8A.pdb +6lrdA,./datasets/ATLAS/6lrdA/6lrdA.pdb +6tlyA,./datasets/ATLAS/6tlyA/6tlyA.pdb +7la6A,./datasets/ATLAS/7la6A/7la6A.pdb diff --git a/bbflow_base/dataset_csv/ATLAS_split/ATLAS_train.csv b/bbflow_base/dataset_csv/ATLAS_split/ATLAS_train.csv new file mode 100644 index 0000000000000000000000000000000000000000..81739577202cd701d3b4b9a8ad667873ed8a1bf1 --- /dev/null +++ b/bbflow_base/dataset_csv/ATLAS_split/ATLAS_train.csv @@ -0,0 +1,1271 @@ +name,modeled_seq_len,folder,num_conformations +4ue8B,38,./datasets/ATLAS/4ue8B,1001 +3tvjI,38,./datasets/ATLAS/3tvjI,1001 +3a1gB,40,./datasets/ATLAS/3a1gB,1001 +2erlA,40,./datasets/ATLAS/2erlA,1001 +5w5cA,40,./datasets/ATLAS/5w5cA,1001 +4jnuB,40,./datasets/ATLAS/4jnuB,1001 +1fd3A,41,./datasets/ATLAS/1fd3A,1001 +3vejB,41,./datasets/ATLAS/3vejB,1001 +1j8eA,44,./datasets/ATLAS/1j8eA,1001 +3l32A,45,./datasets/ATLAS/3l32A,1001 +1ab1A,46,./datasets/ATLAS/1ab1A,1001 +4j8cA,46,./datasets/ATLAS/4j8cA,1001 +5exhC,47,./datasets/ATLAS/5exhC,1001 +2z7fI,50,./datasets/ATLAS/2z7fI,1001 +1ptqA,50,./datasets/ATLAS/1ptqA,1001 +3im3A,50,./datasets/ATLAS/3im3A,1001 +2wqiD,51,./datasets/ATLAS/2wqiD,1001 +2xf7A,51,./datasets/ATLAS/2xf7A,1001 +2gkrI,51,./datasets/ATLAS/2gkrI,1001 +2hbaA,52,./datasets/ATLAS/2hbaA,1001 +2b9dA,52,./datasets/ATLAS/2b9dA,1001 +3kz5E,52,./datasets/ATLAS/3kz5E,1001 +1tgrA,52,./datasets/ATLAS/1tgrA,1001 +1fs1A,53,./datasets/ATLAS/1fs1A,1001 +1nh2B,53,./datasets/ATLAS/1nh2B,1001 +1bq8A,54,./datasets/ATLAS/1bq8A,1001 +4jquB,54,./datasets/ATLAS/4jquB,1001 +5kkoD,55,./datasets/ATLAS/5kkoD,1001 +1bx7A,55,./datasets/ATLAS/1bx7A,1001 +3zoqC,56,./datasets/ATLAS/3zoqC,1001 +3mmyD,56,./datasets/ATLAS/3mmyD,1001 +4e5rA,56,./datasets/ATLAS/4e5rA,1001 +4aqrD,57,./datasets/ATLAS/4aqrD,1001 +1kntA,58,./datasets/ATLAS/1kntA,1001 +3mcbB,58,./datasets/ATLAS/3mcbB,1001 +2y20A,58,./datasets/ATLAS/2y20A,1001 +4npdA,58,./datasets/ATLAS/4npdA,1001 +2fmaA,59,./datasets/ATLAS/2fmaA,1001 +3lpeB,59,./datasets/ATLAS/3lpeB,1001 +1bxyA,60,./datasets/ATLAS/1bxyA,1001 +4xo1A,60,./datasets/ATLAS/4xo1A,1001 +1uptD,60,./datasets/ATLAS/1uptD,1001 +1l2pA,61,./datasets/ATLAS/1l2pA,1001 +3shgB,61,./datasets/ATLAS/3shgB,1001 +4e1pA,61,./datasets/ATLAS/4e1pA,1001 +1dtdB,61,./datasets/ATLAS/1dtdB,1001 +1i2tA,61,./datasets/ATLAS/1i2tA,1001 +1z7kB,62,./datasets/ATLAS/1z7kB,1001 +3c05A,62,./datasets/ATLAS/3c05A,1001 +3pf6A,62,./datasets/ATLAS/3pf6A,1001 +5e5yC,63,./datasets/ATLAS/5e5yC,1001 +2btiA,63,./datasets/ATLAS/2btiA,1001 +2xeuA,64,./datasets/ATLAS/2xeuA,1001 +2oxlB,64,./datasets/ATLAS/2oxlB,1001 +2db7A,64,./datasets/ATLAS/2db7A,1001 +1uoyA,64,./datasets/ATLAS/1uoyA,1001 +5i8jA,64,./datasets/ATLAS/5i8jA,1001 +2f60K,64,./datasets/ATLAS/2f60K,1001 +1ojhC,65,./datasets/ATLAS/1ojhC,1001 +2p58A,65,./datasets/ATLAS/2p58A,1001 +3zr8X,65,./datasets/ATLAS/3zr8X,1001 +2pw8I,65,./datasets/ATLAS/2pw8I,1001 +3ka5A,65,./datasets/ATLAS/3ka5A,1001 +2xz2A,66,./datasets/ATLAS/2xz2A,1001 +1pcfC,66,./datasets/ATLAS/1pcfC,1001 +1yu5X,67,./datasets/ATLAS/1yu5X,1001 +3zrgB,67,./datasets/ATLAS/3zrgB,1001 +2rjwA,67,./datasets/ATLAS/2rjwA,1001 +2yztA,67,./datasets/ATLAS/2yztA,1001 +4h4nA,67,./datasets/ATLAS/4h4nA,1001 +6c62C,68,./datasets/ATLAS/6c62C,1001 +1vbwA,68,./datasets/ATLAS/1vbwA,1001 +2j7zA,68,./datasets/ATLAS/2j7zA,1001 +4qx8B,68,./datasets/ATLAS/4qx8B,1001 +1l2wI,69,./datasets/ATLAS/1l2wI,1001 +5b1nA,69,./datasets/ATLAS/5b1nA,1001 +5l87A,69,./datasets/ATLAS/5l87A,1001 +2e6xA,69,./datasets/ATLAS/2e6xA,1001 +1q2hA,69,./datasets/ATLAS/1q2hA,1001 +4f98A,69,./datasets/ATLAS/4f98A,1001 +2ad6D,69,./datasets/ATLAS/2ad6D,1001 +4eo1A,70,./datasets/ATLAS/4eo1A,1001 +1whzA,70,./datasets/ATLAS/1whzA,1001 +3d2qA,70,./datasets/ATLAS/3d2qA,1001 +1j2lA,70,./datasets/ATLAS/1j2lA,1001 +1utgA,70,./datasets/ATLAS/1utgA,1001 +3ghdA,70,./datasets/ATLAS/3ghdA,1001 +2g7oA,70,./datasets/ATLAS/2g7oA,1001 +1h02B,70,./datasets/ATLAS/1h02B,1001 +3ipfA,71,./datasets/ATLAS/3ipfA,1001 +3dgpB,71,./datasets/ATLAS/3dgpB,1001 +4zmkA,71,./datasets/ATLAS/4zmkA,1001 +2b97A,71,./datasets/ATLAS/2b97A,1001 +3cjsB,72,./datasets/ATLAS/3cjsB,1001 +1wq6A,72,./datasets/ATLAS/1wq6A,1001 +4f87A,72,./datasets/ATLAS/4f87A,1001 +3zdmA,72,./datasets/ATLAS/3zdmA,1001 +2w8xA,72,./datasets/ATLAS/2w8xA,1001 +1ailA,73,./datasets/ATLAS/1ailA,1001 +4rgiA,73,./datasets/ATLAS/4rgiA,1001 +1ctfA,74,./datasets/ATLAS/1ctfA,1001 +1ok0A,74,./datasets/ATLAS/1ok0A,1001 +1l9lA,74,./datasets/ATLAS/1l9lA,1001 +1hc9B,74,./datasets/ATLAS/1hc9B,1001 +2pstX,74,./datasets/ATLAS/2pstX,1001 +5b5iB,74,./datasets/ATLAS/5b5iB,1001 +3dsoA,74,./datasets/ATLAS/3dsoA,1001 +5nirA,74,./datasets/ATLAS/5nirA,1001 +5h1nB,74,./datasets/ATLAS/5h1nB,1001 +5um3A,75,./datasets/ATLAS/5um3A,1001 +5jx1A,75,./datasets/ATLAS/5jx1A,1001 +5yghA,76,./datasets/ATLAS/5yghA,1001 +3u5vA,76,./datasets/ATLAS/3u5vA,1001 +1xg0A,76,./datasets/ATLAS/1xg0A,1001 +4o66D,76,./datasets/ATLAS/4o66D,1001 +3g28A,77,./datasets/ATLAS/3g28A,1001 +1egwB,77,./datasets/ATLAS/1egwB,1001 +4zyaA,77,./datasets/ATLAS/4zyaA,1001 +1t8kA,77,./datasets/ATLAS/1t8kA,1001 +1vccA,77,./datasets/ATLAS/1vccA,1001 +3kdeC,77,./datasets/ATLAS/3kdeC,1001 +4ksnC,78,./datasets/ATLAS/4ksnC,1001 +3ig9C,78,./datasets/ATLAS/3ig9C,1001 +4iajB,78,./datasets/ATLAS/4iajB,1001 +5k6dB,78,./datasets/ATLAS/5k6dB,1001 +1y0nA,78,./datasets/ATLAS/1y0nA,1001 +1xmkA,79,./datasets/ATLAS/1xmkA,1001 +1pbyC,79,./datasets/ATLAS/1pbyC,1001 +2zfzD,79,./datasets/ATLAS/2zfzD,1001 +1wqjB,80,./datasets/ATLAS/1wqjB,1001 +3bqpB,80,./datasets/ATLAS/3bqpB,1001 +2dlbA,80,./datasets/ATLAS/2dlbA,1001 +3a1gA,80,./datasets/ATLAS/3a1gA,1001 +1zt5A,80,./datasets/ATLAS/1zt5A,1001 +3bpjB,80,./datasets/ATLAS/3bpjB,1001 +3t4rA,81,./datasets/ATLAS/3t4rA,1001 +3nrlB,81,./datasets/ATLAS/3nrlB,1001 +4gipA,81,./datasets/ATLAS/4gipA,1001 +4ytwC,81,./datasets/ATLAS/4ytwC,1001 +2hnuA,81,./datasets/ATLAS/2hnuA,1001 +3laeA,81,./datasets/ATLAS/3laeA,1001 +5j2lB,81,./datasets/ATLAS/5j2lB,1001 +1uhaA,82,./datasets/ATLAS/1uhaA,1001 +3fblA,82,./datasets/ATLAS/3fblA,1001 +3nisB,82,./datasets/ATLAS/3nisB,1001 +3bzlD,83,./datasets/ATLAS/3bzlD,1001 +2i5uA,83,./datasets/ATLAS/2i5uA,1001 +3a39A,83,./datasets/ATLAS/3a39A,1001 +2bw3B,84,./datasets/ATLAS/2bw3B,1001 +1w53A,84,./datasets/ATLAS/1w53A,1001 +2a6sB,84,./datasets/ATLAS/2a6sB,1001 +2rjiA,84,./datasets/ATLAS/2rjiA,1001 +3pesA,85,./datasets/ATLAS/3pesA,1001 +3ov5A,85,./datasets/ATLAS/3ov5A,1001 +5by8B,85,./datasets/ATLAS/5by8B,1001 +3v3lA,85,./datasets/ATLAS/3v3lA,1001 +4myyA,85,./datasets/ATLAS/4myyA,1001 +1f9pA,85,./datasets/ATLAS/1f9pA,1001 +3hglA,85,./datasets/ATLAS/3hglA,1001 +4v1gB,86,./datasets/ATLAS/4v1gB,1001 +2i9xA,87,./datasets/ATLAS/2i9xA,1001 +3tbnA,87,./datasets/ATLAS/3tbnA,1001 +3jtzA,88,./datasets/ATLAS/3jtzA,1001 +1krnA,88,./datasets/ATLAS/1krnA,1001 +3l9aX,88,./datasets/ATLAS/3l9aX,1001 +1pchA,88,./datasets/ATLAS/1pchA,1001 +4jo7A,89,./datasets/ATLAS/4jo7A,1001 +3rjsA,89,./datasets/ATLAS/3rjsA,1001 +5ezuA,89,./datasets/ATLAS/5ezuA,1001 +2cg7A,90,./datasets/ATLAS/2cg7A,1001 +5hubA,90,./datasets/ATLAS/5hubA,1001 +2y1yA,90,./datasets/ATLAS/2y1yA,1001 +4u5hG,90,./datasets/ATLAS/4u5hG,1001 +1u84A,90,./datasets/ATLAS/1u84A,1001 +1b2sF,90,./datasets/ATLAS/1b2sF,1001 +3mx7A,90,./datasets/ATLAS/3mx7A,1001 +1u07A,90,./datasets/ATLAS/1u07A,1001 +1ef1D,90,./datasets/ATLAS/1ef1D,1001 +2ftxA,90,./datasets/ATLAS/2ftxA,1001 +1b2sE,90,./datasets/ATLAS/1b2sE,1001 +1x6iA,91,./datasets/ATLAS/1x6iA,1001 +2gpiA,91,./datasets/ATLAS/2gpiA,1001 +3c0fB,91,./datasets/ATLAS/3c0fB,1001 +1x6jA,91,./datasets/ATLAS/1x6jA,1001 +2ygsA,92,./datasets/ATLAS/2ygsA,1001 +2xdgA,92,./datasets/ATLAS/2xdgA,1001 +6avjB,92,./datasets/ATLAS/6avjB,1001 +2qwoB,92,./datasets/ATLAS/2qwoB,1001 +1fk5A,93,./datasets/ATLAS/1fk5A,1001 +2nqwA,93,./datasets/ATLAS/2nqwA,1001 +4a56A,93,./datasets/ATLAS/4a56A,1001 +2y4xB,93,./datasets/ATLAS/2y4xB,1001 +3x0gA,93,./datasets/ATLAS/3x0gA,1001 +2cwyA,94,./datasets/ATLAS/2cwyA,1001 +3ajfA,94,./datasets/ATLAS/3ajfA,1001 +1dfuP,94,./datasets/ATLAS/1dfuP,1001 +3vc8B,94,./datasets/ATLAS/3vc8B,1001 +4ndtA,94,./datasets/ATLAS/4ndtA,1001 +2fe5A,94,./datasets/ATLAS/2fe5A,1001 +3b4qB,94,./datasets/ATLAS/3b4qB,1001 +4xqmA,94,./datasets/ATLAS/4xqmA,1001 +3txsC,94,./datasets/ATLAS/3txsC,1001 +3lblA,95,./datasets/ATLAS/3lblA,1001 +4mmjA,95,./datasets/ATLAS/4mmjA,1001 +2qskA,95,./datasets/ATLAS/2qskA,1001 +3ofgB,95,./datasets/ATLAS/3ofgB,1001 +3zzoA,95,./datasets/ATLAS/3zzoA,1001 +3ipjA,95,./datasets/ATLAS/3ipjA,1001 +3cw3A,96,./datasets/ATLAS/3cw3A,1001 +2x5gA,96,./datasets/ATLAS/2x5gA,1001 +3mhsB,96,./datasets/ATLAS/3mhsB,1001 +4ykdA,96,./datasets/ATLAS/4ykdA,1001 +1mk0A,97,./datasets/ATLAS/1mk0A,1001 +3onjA,97,./datasets/ATLAS/3onjA,1001 +2x5hB,97,./datasets/ATLAS/2x5hB,1001 +4pz1A,98,./datasets/ATLAS/4pz1A,1001 +1lriA,98,./datasets/ATLAS/1lriA,1001 +5v0mA,98,./datasets/ATLAS/5v0mA,1001 +2aibA,98,./datasets/ATLAS/2aibA,1001 +2oy9B,98,./datasets/ATLAS/2oy9B,1001 +4rp5A,98,./datasets/ATLAS/4rp5A,1001 +4z8qB,98,./datasets/ATLAS/4z8qB,1001 +1jo0A,98,./datasets/ATLAS/1jo0A,1001 +1tovA,98,./datasets/ATLAS/1tovA,1001 +2p9xD,99,./datasets/ATLAS/2p9xD,1001 +2wpqC,99,./datasets/ATLAS/2wpqC,1001 +2ccqA,99,./datasets/ATLAS/2ccqA,1001 +3po8A,100,./datasets/ATLAS/3po8A,1001 +3wx4A,100,./datasets/ATLAS/3wx4A,1001 +5ol4A,100,./datasets/ATLAS/5ol4A,1001 +2o4tA,100,./datasets/ATLAS/2o4tA,1001 +5h6xA,100,./datasets/ATLAS/5h6xA,1001 +2xrhA,100,./datasets/ATLAS/2xrhA,1001 +3fpuA,100,./datasets/ATLAS/3fpuA,1001 +1g2rA,100,./datasets/ATLAS/1g2rA,1001 +2ebbA,101,./datasets/ATLAS/2ebbA,1001 +3hmsA,101,./datasets/ATLAS/3hmsA,1001 +2gh0D,101,./datasets/ATLAS/2gh0D,1001 +3ic3B,101,./datasets/ATLAS/3ic3B,1001 +2bo1A,101,./datasets/ATLAS/2bo1A,1001 +4ebgA,101,./datasets/ATLAS/4ebgA,1001 +3czzB,101,./datasets/ATLAS/3czzB,1001 +3luuA,101,./datasets/ATLAS/3luuA,1001 +2oyaB,102,./datasets/ATLAS/2oyaB,1001 +4ew5A,102,./datasets/ATLAS/4ew5A,1001 +1uz3A,102,./datasets/ATLAS/1uz3A,1001 +5v03B,102,./datasets/ATLAS/5v03B,1001 +4wlrB,102,./datasets/ATLAS/4wlrB,1001 +1qw2A,102,./datasets/ATLAS/1qw2A,1001 +4b6iD,102,./datasets/ATLAS/4b6iD,1001 +5z42A,102,./datasets/ATLAS/5z42A,1001 +2oxoA,103,./datasets/ATLAS/2oxoA,1001 +5nohA,103,./datasets/ATLAS/5nohA,1001 +4qb0A,103,./datasets/ATLAS/4qb0A,1001 +3e7hA,103,./datasets/ATLAS/3e7hA,1001 +2gibB,103,./datasets/ATLAS/2gibB,1001 +2b1yA,104,./datasets/ATLAS/2b1yA,1001 +3fybA,104,./datasets/ATLAS/3fybA,1001 +1d4tA,104,./datasets/ATLAS/1d4tA,1001 +5e3eA,104,./datasets/ATLAS/5e3eA,1001 +2nmlA,104,./datasets/ATLAS/2nmlA,1001 +3o79A,105,./datasets/ATLAS/3o79A,1001 +1jyoF,105,./datasets/ATLAS/1jyoF,1001 +2qtdA,105,./datasets/ATLAS/2qtdA,1001 +4gn0A,105,./datasets/ATLAS/4gn0A,1001 +1pucA,105,./datasets/ATLAS/1pucA,1001 +5cyzC,105,./datasets/ATLAS/5cyzC,1001 +1kptA,105,./datasets/ATLAS/1kptA,1001 +3fn2B,106,./datasets/ATLAS/3fn2B,1001 +3l1eA,106,./datasets/ATLAS/3l1eA,1001 +4obiA,106,./datasets/ATLAS/4obiA,1001 +7fd1A,106,./datasets/ATLAS/7fd1A,1001 +3fp5A,106,./datasets/ATLAS/3fp5A,1001 +2pspB,106,./datasets/ATLAS/2pspB,1001 +2vm5A,106,./datasets/ATLAS/2vm5A,1001 +3ol3A,107,./datasets/ATLAS/3ol3A,1001 +3lyyA,107,./datasets/ATLAS/3lyyA,1001 +1i4mA,108,./datasets/ATLAS/1i4mA,1001 +1o4kA,108,./datasets/ATLAS/1o4kA,1001 +1j0pA,108,./datasets/ATLAS/1j0pA,1001 +2vkpB,109,./datasets/ATLAS/2vkpB,1001 +2fhzA,109,./datasets/ATLAS/2fhzA,1001 +3e0zA,109,./datasets/ATLAS/3e0zA,1001 +5palA,109,./datasets/ATLAS/5palA,1001 +2qsaA,109,./datasets/ATLAS/2qsaA,1001 +3l4hA,109,./datasets/ATLAS/3l4hA,1001 +5hqhA,109,./datasets/ATLAS/5hqhA,1001 +2j6bA,109,./datasets/ATLAS/2j6bA,1001 +3uebE,110,./datasets/ATLAS/3uebE,1001 +2pu9A,110,./datasets/ATLAS/2pu9A,1001 +3cyiA,110,./datasets/ATLAS/3cyiA,1001 +4goqB,110,./datasets/ATLAS/4goqB,1001 +1wq8A,110,./datasets/ATLAS/1wq8A,1001 +3g98B,111,./datasets/ATLAS/3g98B,1001 +2rffA,111,./datasets/ATLAS/2rffA,1001 +1m9zA,111,./datasets/ATLAS/1m9zA,1001 +5x1eD,111,./datasets/ATLAS/5x1eD,1001 +4y7sA,111,./datasets/ATLAS/4y7sA,1001 +1vyiA,112,./datasets/ATLAS/1vyiA,1001 +1n8uA,112,./datasets/ATLAS/1n8uA,1001 +4ftfA,112,./datasets/ATLAS/4ftfA,1001 +3bn0A,112,./datasets/ATLAS/3bn0A,1001 +1qauA,112,./datasets/ATLAS/1qauA,1001 +1z21A,112,./datasets/ATLAS/1z21A,1001 +4jmuA,112,./datasets/ATLAS/4jmuA,1001 +5vapA,112,./datasets/ATLAS/5vapA,1001 +4cv7A,113,./datasets/ATLAS/4cv7A,1001 +5n6yC,113,./datasets/ATLAS/5n6yC,1001 +2vh3A,113,./datasets/ATLAS/2vh3A,1001 +1lslA,113,./datasets/ATLAS/1lslA,1001 +5el3B,113,./datasets/ATLAS/5el3B,1001 +2p6vA,114,./datasets/ATLAS/2p6vA,1001 +3enuA,114,./datasets/ATLAS/3enuA,1001 +2pyqB,114,./datasets/ATLAS/2pyqB,1001 +2iayA,114,./datasets/ATLAS/2iayA,1001 +3agnA,114,./datasets/ATLAS/3agnA,1001 +4hwxA,114,./datasets/ATLAS/4hwxA,1001 +2nwvA,114,./datasets/ATLAS/2nwvA,1001 +2fipA,115,./datasets/ATLAS/2fipA,1001 +3mwzA,115,./datasets/ATLAS/3mwzA,1001 +3qflA,115,./datasets/ATLAS/3qflA,1001 +2es9A,115,./datasets/ATLAS/2es9A,1001 +3fkcA,116,./datasets/ATLAS/3fkcA,1001 +3mxzA,116,./datasets/ATLAS/3mxzA,1001 +1yozB,116,./datasets/ATLAS/1yozB,1001 +3emiA,116,./datasets/ATLAS/3emiA,1001 +2xu8B,116,./datasets/ATLAS/2xu8B,1001 +3rmqA,116,./datasets/ATLAS/3rmqA,1001 +1rlkA,117,./datasets/ATLAS/1rlkA,1001 +3nrwA,117,./datasets/ATLAS/3nrwA,1001 +1dptA,117,./datasets/ATLAS/1dptA,1001 +2fb6A,117,./datasets/ATLAS/2fb6A,1001 +2y39A,118,./datasets/ATLAS/2y39A,1001 +2cyjA,118,./datasets/ATLAS/2cyjA,1001 +5xbcB,118,./datasets/ATLAS/5xbcB,1001 +3p4hA,118,./datasets/ATLAS/3p4hA,1001 +1f3uG,118,./datasets/ATLAS/1f3uG,1001 +3ju3A,118,./datasets/ATLAS/3ju3A,1001 +5dpoA,119,./datasets/ATLAS/5dpoA,1001 +1njhA,119,./datasets/ATLAS/1njhA,1001 +4oxwA,119,./datasets/ATLAS/4oxwA,1001 +3t7zA,119,./datasets/ATLAS/3t7zA,1001 +3fpnA,119,./datasets/ATLAS/3fpnA,1001 +3nufA,119,./datasets/ATLAS/3nufA,1001 +3kz7A,119,./datasets/ATLAS/3kz7A,1001 +1by2A,119,./datasets/ATLAS/1by2A,1001 +2igpA,120,./datasets/ATLAS/2igpA,1001 +3e9vA,120,./datasets/ATLAS/3e9vA,1001 +1xtyB,120,./datasets/ATLAS/1xtyB,1001 +1iktA,120,./datasets/ATLAS/1iktA,1001 +3t92A,121,./datasets/ATLAS/3t92A,1001 +1u6tA,121,./datasets/ATLAS/1u6tA,1001 +4tshA,121,./datasets/ATLAS/4tshA,1001 +4oe9B,121,./datasets/ATLAS/4oe9B,1001 +4wrpA,122,./datasets/ATLAS/4wrpA,1001 +1jifA,122,./datasets/ATLAS/1jifA,1001 +1whiA,122,./datasets/ATLAS/1whiA,1001 +3c1qB,123,./datasets/ATLAS/3c1qB,1001 +5bs1B,123,./datasets/ATLAS/5bs1B,1001 +5bnhA,123,./datasets/ATLAS/5bnhA,1001 +2qjzA,123,./datasets/ATLAS/2qjzA,1001 +3c9pA,123,./datasets/ATLAS/3c9pA,1001 +1m8sA,124,./datasets/ATLAS/1m8sA,1001 +4csbA,124,./datasets/ATLAS/4csbA,1001 +1bgfA,124,./datasets/ATLAS/1bgfA,1001 +3pkzA,124,./datasets/ATLAS/3pkzA,1001 +3bwuD,125,./datasets/ATLAS/3bwuD,1001 +2qudA,125,./datasets/ATLAS/2qudA,1001 +2qhqB,125,./datasets/ATLAS/2qhqB,1001 +3klrA,125,./datasets/ATLAS/3klrA,1001 +2fj8A,125,./datasets/ATLAS/2fj8A,1001 +2x5rA,127,./datasets/ATLAS/2x5rA,1001 +1g6gA,127,./datasets/ATLAS/1g6gA,1001 +1ez3B,127,./datasets/ATLAS/1ez3B,1001 +1ijxC,127,./datasets/ATLAS/1ijxC,1001 +2f6eA,127,./datasets/ATLAS/2f6eA,1001 +2hngA,127,./datasets/ATLAS/2hngA,1001 +2fygA,128,./datasets/ATLAS/2fygA,1001 +1doiA,128,./datasets/ATLAS/1doiA,1001 +3ehgA,128,./datasets/ATLAS/3ehgA,1001 +1sf9A,128,./datasets/ATLAS/1sf9A,1001 +4f55A,128,./datasets/ATLAS/4f55A,1001 +3a7lA,128,./datasets/ATLAS/3a7lA,1001 +1ijtA,128,./datasets/ATLAS/1ijtA,1001 +2fi9A,128,./datasets/ATLAS/2fi9A,1001 +1dd3B,128,./datasets/ATLAS/1dd3B,1001 +1cpqA,129,./datasets/ATLAS/1cpqA,1001 +3l2aA,129,./datasets/ATLAS/3l2aA,1001 +3ushB,129,./datasets/ATLAS/3ushB,1001 +1cuoA,129,./datasets/ATLAS/1cuoA,1001 +1lr0A,129,./datasets/ATLAS/1lr0A,1001 +1mscA,129,./datasets/ATLAS/1mscA,1001 +2w0gA,129,./datasets/ATLAS/2w0gA,1001 +3fkeA,129,./datasets/ATLAS/3fkeA,1001 +2hy5A,130,./datasets/ATLAS/2hy5A,1001 +2cx7A,130,./datasets/ATLAS/2cx7A,1001 +3daiA,130,./datasets/ATLAS/3daiA,1001 +1m5qI,130,./datasets/ATLAS/1m5qI,1001 +2wb6A,130,./datasets/ATLAS/2wb6A,1001 +2hu9A,130,./datasets/ATLAS/2hu9A,1001 +1seiA,130,./datasets/ATLAS/1seiA,1001 +1jyoB,130,./datasets/ATLAS/1jyoB,1001 +1a62A,130,./datasets/ATLAS/1a62A,1001 +1wnaA,131,./datasets/ATLAS/1wnaA,1001 +5o5sA,131,./datasets/ATLAS/5o5sA,1001 +5wx9A,131,./datasets/ATLAS/5wx9A,1001 +1u7kD,131,./datasets/ATLAS/1u7kD,1001 +2vzcA,131,./datasets/ATLAS/2vzcA,1001 +2gc4B,131,./datasets/ATLAS/2gc4B,1001 +1c52A,131,./datasets/ATLAS/1c52A,1001 +3oblB,132,./datasets/ATLAS/3oblB,1001 +5dblA,132,./datasets/ATLAS/5dblA,1001 +2e8eA,132,./datasets/ATLAS/2e8eA,1001 +4zi3D,133,./datasets/ATLAS/4zi3D,1001 +4cv4A,133,./datasets/ATLAS/4cv4A,1001 +3v0rA,133,./datasets/ATLAS/3v0rA,1001 +3ga3A,133,./datasets/ATLAS/3ga3A,1001 +2e5yB,133,./datasets/ATLAS/2e5yB,1001 +1ve0A,134,./datasets/ATLAS/1ve0A,1001 +2y7bA,134,./datasets/ATLAS/2y7bA,1001 +3lq9A,134,./datasets/ATLAS/3lq9A,1001 +2p6hB,134,./datasets/ATLAS/2p6hB,1001 +5b3pA,134,./datasets/ATLAS/5b3pA,1001 +2vacA,134,./datasets/ATLAS/2vacA,1001 +4zdsB,134,./datasets/ATLAS/4zdsB,1001 +5iqjC,134,./datasets/ATLAS/5iqjC,1001 +4q0yA,134,./datasets/ATLAS/4q0yA,1001 +2pagA,135,./datasets/ATLAS/2pagA,1001 +2w0iA,135,./datasets/ATLAS/2w0iA,1001 +1gqvA,135,./datasets/ATLAS/1gqvA,1001 +3fm2A,135,./datasets/ATLAS/3fm2A,1001 +1r9fA,136,./datasets/ATLAS/1r9fA,1001 +2lisA,136,./datasets/ATLAS/2lisA,1001 +1j5uA,136,./datasets/ATLAS/1j5uA,1001 +4rr9A,136,./datasets/ATLAS/4rr9A,1001 +5opzA,137,./datasets/ATLAS/5opzA,1001 +2qq4B,138,./datasets/ATLAS/2qq4B,1001 +2ofzA,138,./datasets/ATLAS/2ofzA,1001 +5ii7A,138,./datasets/ATLAS/5ii7A,1001 +2endA,138,./datasets/ATLAS/2endA,1001 +3d7aB,138,./datasets/ATLAS/3d7aB,1001 +2gecA,139,./datasets/ATLAS/2gecA,1001 +5btzA,139,./datasets/ATLAS/5btzA,1001 +2in8A,139,./datasets/ATLAS/2in8A,1001 +2v6aO,140,./datasets/ATLAS/2v6aO,1001 +5djeB,140,./datasets/ATLAS/5djeB,1001 +3m7aA,140,./datasets/ATLAS/3m7aA,1001 +2onfB,140,./datasets/ATLAS/2onfB,1001 +2w9yA,140,./datasets/ATLAS/2w9yA,1001 +1ifgA,140,./datasets/ATLAS/1ifgA,1001 +1hufA,140,./datasets/ATLAS/1hufA,1001 +2g64A,140,./datasets/ATLAS/2g64A,1001 +2nukA,141,./datasets/ATLAS/2nukA,1001 +3apaA,141,./datasets/ATLAS/3apaA,1001 +3g0mA,141,./datasets/ATLAS/3g0mA,1001 +5en2C,141,./datasets/ATLAS/5en2C,1001 +2j6aA,141,./datasets/ATLAS/2j6aA,1001 +1vr8A,142,./datasets/ATLAS/1vr8A,1001 +1tzwA,142,./datasets/ATLAS/1tzwA,1001 +2dt4A,143,./datasets/ATLAS/2dt4A,1001 +3inoA,143,./datasets/ATLAS/3inoA,1001 +2yvqA,143,./datasets/ATLAS/2yvqA,1001 +1qddA,144,./datasets/ATLAS/1qddA,1001 +2fzpA,144,./datasets/ATLAS/2fzpA,1001 +1jkeC,145,./datasets/ATLAS/1jkeC,1001 +3kbyA,145,./datasets/ATLAS/3kbyA,1001 +2xppA,145,./datasets/ATLAS/2xppA,1001 +2pv4A,145,./datasets/ATLAS/2pv4A,1001 +3mswA,145,./datasets/ATLAS/3mswA,1001 +2w6kA,145,./datasets/ATLAS/2w6kA,1001 +2qevA,145,./datasets/ATLAS/2qevA,1001 +2jekA,145,./datasets/ATLAS/2jekA,1001 +2yskA,145,./datasets/ATLAS/2yskA,1001 +3omdB,145,./datasets/ATLAS/3omdB,1001 +2p84A,145,./datasets/ATLAS/2p84A,1001 +2wzoA,146,./datasets/ATLAS/2wzoA,1001 +3fh2A,146,./datasets/ATLAS/3fh2A,1001 +4exoA,146,./datasets/ATLAS/4exoA,1001 +6anzA,146,./datasets/ATLAS/6anzA,1001 +2v0uA,146,./datasets/ATLAS/2v0uA,1001 +2jddA,146,./datasets/ATLAS/2jddA,1001 +5eqzA,146,./datasets/ATLAS/5eqzA,1001 +4q7oB,146,./datasets/ATLAS/4q7oB,1001 +1nl1A,147,./datasets/ATLAS/1nl1A,1001 +1dk8A,147,./datasets/ATLAS/1dk8A,1001 +1earA,147,./datasets/ATLAS/1earA,1001 +1rk8B,147,./datasets/ATLAS/1rk8B,1001 +2w56A,147,./datasets/ATLAS/2w56A,1001 +1yocB,147,./datasets/ATLAS/1yocB,1001 +1wpuA,147,./datasets/ATLAS/1wpuA,1001 +2gc4L,147,./datasets/ATLAS/2gc4L,1001 +2w86A,147,./datasets/ATLAS/2w86A,1001 +1ng6A,148,./datasets/ATLAS/1ng6A,1001 +3zfnA,148,./datasets/ATLAS/3zfnA,1001 +5x1eB,148,./datasets/ATLAS/5x1eB,1001 +2d28C,149,./datasets/ATLAS/2d28C,1001 +2eo4A,149,./datasets/ATLAS/2eo4A,1001 +3o0gD,149,./datasets/ATLAS/3o0gD,1001 +2wcuA,149,./datasets/ATLAS/2wcuA,1001 +4wheA,150,./datasets/ATLAS/4wheA,1001 +3oxpA,150,./datasets/ATLAS/3oxpA,1001 +4xb6E,150,./datasets/ATLAS/4xb6E,1001 +2y1qA,150,./datasets/ATLAS/2y1qA,1001 +1z2uA,150,./datasets/ATLAS/1z2uA,1001 +5jakA,151,./datasets/ATLAS/5jakA,1001 +1rssA,151,./datasets/ATLAS/1rssA,1001 +3iiuM,151,./datasets/ATLAS/3iiuM,1001 +2vnlA,151,./datasets/ATLAS/2vnlA,1001 +3a0yB,152,./datasets/ATLAS/3a0yB,1001 +1ouwC,152,./datasets/ATLAS/1ouwC,1001 +1dvoA,152,./datasets/ATLAS/1dvoA,1001 +2op6A,152,./datasets/ATLAS/2op6A,1001 +1ntvA,152,./datasets/ATLAS/1ntvA,1001 +4xb4A,152,./datasets/ATLAS/4xb4A,1001 +2glzB,153,./datasets/ATLAS/2glzB,1001 +2prvA,153,./datasets/ATLAS/2prvA,1001 +3pvhA,153,./datasets/ATLAS/3pvhA,1001 +2bk9A,153,./datasets/ATLAS/2bk9A,1001 +3jubA,153,./datasets/ATLAS/3jubA,1001 +2ejnB,153,./datasets/ATLAS/2ejnB,1001 +5c8qB,154,./datasets/ATLAS/5c8qB,1001 +1md6A,154,./datasets/ATLAS/1md6A,1001 +3cy4A,154,./datasets/ATLAS/3cy4A,1001 +5t2pB,155,./datasets/ATLAS/5t2pB,1001 +2oebA,155,./datasets/ATLAS/2oebA,1001 +5m1mA,155,./datasets/ATLAS/5m1mA,1001 +3h2dB,155,./datasets/ATLAS/3h2dB,1001 +1o1xA,155,./datasets/ATLAS/1o1xA,1001 +3vnbA,155,./datasets/ATLAS/3vnbA,1001 +4m62S,155,./datasets/ATLAS/4m62S,1001 +2ox7B,155,./datasets/ATLAS/2ox7B,1001 +5e7xA,155,./datasets/ATLAS/5e7xA,1001 +4qn8B,155,./datasets/ATLAS/4qn8B,1001 +3gmvX,156,./datasets/ATLAS/3gmvX,1001 +3oi8A,156,./datasets/ATLAS/3oi8A,1001 +1dwkA,156,./datasets/ATLAS/1dwkA,1001 +3qraA,157,./datasets/ATLAS/3qraA,1001 +5mduA,157,./datasets/ATLAS/5mduA,1001 +3ii2A,157,./datasets/ATLAS/3ii2A,1001 +2vy8A,157,./datasets/ATLAS/2vy8A,1001 +1v4pC,157,./datasets/ATLAS/1v4pC,1001 +2zzdE,157,./datasets/ATLAS/2zzdE,1001 +3owtB,157,./datasets/ATLAS/3owtB,1001 +2z0xA,158,./datasets/ATLAS/2z0xA,1001 +3imkA,158,./datasets/ATLAS/3imkA,1001 +3lurB,158,./datasets/ATLAS/3lurB,1001 +1zd7B,159,./datasets/ATLAS/1zd7B,1001 +1fm4A,159,./datasets/ATLAS/1fm4A,1001 +2pcnA,161,./datasets/ATLAS/2pcnA,1001 +3f4mA,161,./datasets/ATLAS/3f4mA,1001 +5eg7A,161,./datasets/ATLAS/5eg7A,1001 +2hq4A,161,./datasets/ATLAS/2hq4A,1001 +2qnlA,162,./datasets/ATLAS/2qnlA,1001 +2cfeA,162,./datasets/ATLAS/2cfeA,1001 +3gqhA,163,./datasets/ATLAS/3gqhA,1001 +1t9iB,163,./datasets/ATLAS/1t9iB,1001 +5uc0A,163,./datasets/ATLAS/5uc0A,1001 +2aj7A,163,./datasets/ATLAS/2aj7A,1001 +5xctB,163,./datasets/ATLAS/5xctB,1001 +3on9A,163,./datasets/ATLAS/3on9A,1001 +3fcnA,164,./datasets/ATLAS/3fcnA,1001 +1tt8A,164,./datasets/ATLAS/1tt8A,1001 +1b8dK,164,./datasets/ATLAS/1b8dK,1001 +3vgpA,164,./datasets/ATLAS/3vgpA,1001 +5gglA,164,./datasets/ATLAS/5gglA,1001 +1n2mA,165,./datasets/ATLAS/1n2mA,1001 +3n4iB,165,./datasets/ATLAS/3n4iB,1001 +4a1kA,165,./datasets/ATLAS/4a1kA,1001 +2wfrA,165,./datasets/ATLAS/2wfrA,1001 +3n4jA,165,./datasets/ATLAS/3n4jA,1001 +2xvsA,166,./datasets/ATLAS/2xvsA,1001 +3lasB,166,./datasets/ATLAS/3lasB,1001 +3l51B,166,./datasets/ATLAS/3l51B,1001 +1xo7B,166,./datasets/ATLAS/1xo7B,1001 +2fp1A,166,./datasets/ATLAS/2fp1A,1001 +1rylA,167,./datasets/ATLAS/1rylA,1001 +2gkpA,167,./datasets/ATLAS/2gkpA,1001 +3hvvA,167,./datasets/ATLAS/3hvvA,1001 +3mmhB,167,./datasets/ATLAS/3mmhB,1001 +3eyeA,168,./datasets/ATLAS/3eyeA,1001 +5gv0A,168,./datasets/ATLAS/5gv0A,1001 +1xeoA,168,./datasets/ATLAS/1xeoA,1001 +2zcaB,169,./datasets/ATLAS/2zcaB,1001 +1btkA,169,./datasets/ATLAS/1btkA,1001 +2rkqA,169,./datasets/ATLAS/2rkqA,1001 +2ed6A,170,./datasets/ATLAS/2ed6A,1001 +5kvkA,170,./datasets/ATLAS/5kvkA,1001 +2nsaA,170,./datasets/ATLAS/2nsaA,1001 +1xvgE,170,./datasets/ATLAS/1xvgE,1001 +2xseA,170,./datasets/ATLAS/2xseA,1001 +3gwiA,170,./datasets/ATLAS/3gwiA,1001 +5vu3B,170,./datasets/ATLAS/5vu3B,1001 +3rt4A,171,./datasets/ATLAS/3rt4A,1001 +2imsA,171,./datasets/ATLAS/2imsA,1001 +3wurB,171,./datasets/ATLAS/3wurB,1001 +3nl9A,171,./datasets/ATLAS/3nl9A,1001 +1wpbA,172,./datasets/ATLAS/1wpbA,1001 +5g38A,172,./datasets/ATLAS/5g38A,1001 +1koeA,172,./datasets/ATLAS/1koeA,1001 +5cofA,173,./datasets/ATLAS/5cofA,1001 +2vriA,174,./datasets/ATLAS/2vriA,1001 +5ef9A,174,./datasets/ATLAS/5ef9A,1001 +2o74F,174,./datasets/ATLAS/2o74F,1001 +4o6gA,174,./datasets/ATLAS/4o6gA,1001 +2au7A,175,./datasets/ATLAS/2au7A,1001 +2xolB,176,./datasets/ATLAS/2xolB,1001 +2p12A,176,./datasets/ATLAS/2p12A,1001 +1rl6A,177,./datasets/ATLAS/1rl6A,1001 +3nr1A,178,./datasets/ATLAS/3nr1A,1001 +2ia1A,178,./datasets/ATLAS/2ia1A,1001 +1k8kE,178,./datasets/ATLAS/1k8kE,1001 +2znrA,178,./datasets/ATLAS/2znrA,1001 +1jwqA,179,./datasets/ATLAS/1jwqA,1001 +3qc7A,179,./datasets/ATLAS/3qc7A,1001 +4koqA,180,./datasets/ATLAS/4koqA,1001 +2igiA,180,./datasets/ATLAS/2igiA,1001 +2q2gA,180,./datasets/ATLAS/2q2gA,1001 +2ot9A,180,./datasets/ATLAS/2ot9A,1001 +1im5A,180,./datasets/ATLAS/1im5A,1001 +2dwkA,180,./datasets/ATLAS/2dwkA,1001 +2yvoA,182,./datasets/ATLAS/2yvoA,1001 +3jv1A,182,./datasets/ATLAS/3jv1A,1001 +3vorA,182,./datasets/ATLAS/3vorA,1001 +2y3wA,182,./datasets/ATLAS/2y3wA,1001 +3k5jA,183,./datasets/ATLAS/3k5jA,1001 +3g5kD,183,./datasets/ATLAS/3g5kD,1001 +1ypyA,184,./datasets/ATLAS/1ypyA,1001 +4o6qA,184,./datasets/ATLAS/4o6qA,1001 +3molB,184,./datasets/ATLAS/3molB,1001 +2y44A,184,./datasets/ATLAS/2y44A,1001 +2i9wA,184,./datasets/ATLAS/2i9wA,1001 +2at8X,184,./datasets/ATLAS/2at8X,1001 +4oieA,185,./datasets/ATLAS/4oieA,1001 +2b0aA,186,./datasets/ATLAS/2b0aA,1001 +1v7rA,186,./datasets/ATLAS/1v7rA,1001 +4u9bA,187,./datasets/ATLAS/4u9bA,1001 +1xhkB,187,./datasets/ATLAS/1xhkB,1001 +5cflA,187,./datasets/ATLAS/5cflA,1001 +1jhsA,188,./datasets/ATLAS/1jhsA,1001 +3h0nA,188,./datasets/ATLAS/3h0nA,1001 +1u55A,188,./datasets/ATLAS/1u55A,1001 +2h1tB,188,./datasets/ATLAS/2h1tB,1001 +4qxoA,188,./datasets/ATLAS/4qxoA,1001 +4hfvA,190,./datasets/ATLAS/4hfvA,1001 +3h8tA,191,./datasets/ATLAS/3h8tA,1001 +2pfxA,191,./datasets/ATLAS/2pfxA,1001 +3dzaA,191,./datasets/ATLAS/3dzaA,1001 +3frrA,191,./datasets/ATLAS/3frrA,1001 +3h93A,192,./datasets/ATLAS/3h93A,1001 +3rlkA,192,./datasets/ATLAS/3rlkA,1001 +4qmdA,193,./datasets/ATLAS/4qmdA,1001 +1juvA,193,./datasets/ATLAS/1juvA,1001 +3lgbB,194,./datasets/ATLAS/3lgbB,1001 +2bmoB,194,./datasets/ATLAS/2bmoB,1001 +4byzA,194,./datasets/ATLAS/4byzA,1001 +4xb6F,194,./datasets/ATLAS/4xb6F,1001 +2bbrA,195,./datasets/ATLAS/2bbrA,1001 +1qhvA,195,./datasets/ATLAS/1qhvA,1001 +1j8rA,196,./datasets/ATLAS/1j8rA,1001 +5gw6A,196,./datasets/ATLAS/5gw6A,1001 +4ke2C,196,./datasets/ATLAS/4ke2C,1001 +4dlhB,197,./datasets/ATLAS/4dlhB,1001 +3jz9A,197,./datasets/ATLAS/3jz9A,1001 +1ocyA,198,./datasets/ATLAS/1ocyA,1001 +4g6dB,198,./datasets/ATLAS/4g6dB,1001 +4alzA,198,./datasets/ATLAS/4alzA,1001 +2gs5A,198,./datasets/ATLAS/2gs5A,1001 +6fy5A,198,./datasets/ATLAS/6fy5A,1001 +3o3xA,198,./datasets/ATLAS/3o3xA,1001 +3it4C,199,./datasets/ATLAS/3it4C,1001 +1pp0C,199,./datasets/ATLAS/1pp0C,1001 +3lwxA,199,./datasets/ATLAS/3lwxA,1001 +2wawA,199,./datasets/ATLAS/2wawA,1001 +2gwmA,200,./datasets/ATLAS/2gwmA,1001 +3nkeB,200,./datasets/ATLAS/3nkeB,1001 +2q9rA,200,./datasets/ATLAS/2q9rA,1001 +2it2B,200,./datasets/ATLAS/2it2B,1001 +2bfwA,200,./datasets/ATLAS/2bfwA,1001 +5ij2B,201,./datasets/ATLAS/5ij2B,1001 +3wvzA,201,./datasets/ATLAS/3wvzA,1001 +2ovjA,201,./datasets/ATLAS/2ovjA,1001 +5o9eA,201,./datasets/ATLAS/5o9eA,1001 +2id6A,202,./datasets/ATLAS/2id6A,1001 +1r8mE,203,./datasets/ATLAS/1r8mE,1001 +4hfqB,203,./datasets/ATLAS/4hfqB,1001 +1ugpA,203,./datasets/ATLAS/1ugpA,1001 +1chdA,203,./datasets/ATLAS/1chdA,1001 +2imfA,203,./datasets/ATLAS/2imfA,1001 +2rciA,204,./datasets/ATLAS/2rciA,1001 +1dowA,205,./datasets/ATLAS/1dowA,1001 +2bkoA,205,./datasets/ATLAS/2bkoA,1001 +2nnuA,205,./datasets/ATLAS/2nnuA,1001 +1ix9A,205,./datasets/ATLAS/1ix9A,1001 +2vfkA,205,./datasets/ATLAS/2vfkA,1001 +2fb5A,205,./datasets/ATLAS/2fb5A,1001 +3it4B,205,./datasets/ATLAS/3it4B,1001 +5w2fA,206,./datasets/ATLAS/5w2fA,1001 +1k7jA,206,./datasets/ATLAS/1k7jA,1001 +4ywkA,206,./datasets/ATLAS/4ywkA,1001 +1xkrA,206,./datasets/ATLAS/1xkrA,1001 +2vfxC,206,./datasets/ATLAS/2vfxC,1001 +2amhA,207,./datasets/ATLAS/2amhA,1001 +1h2eA,207,./datasets/ATLAS/1h2eA,1001 +4gehA,207,./datasets/ATLAS/4gehA,1001 +2vi1A,207,./datasets/ATLAS/2vi1A,1001 +4lpqA,207,./datasets/ATLAS/4lpqA,1001 +1z0bA,207,./datasets/ATLAS/1z0bA,1001 +4ervA,207,./datasets/ATLAS/4ervA,1001 +1s9uA,207,./datasets/ATLAS/1s9uA,1001 +2o7oA,207,./datasets/ATLAS/2o7oA,1001 +1nf8A,207,./datasets/ATLAS/1nf8A,1001 +2p3pB,207,./datasets/ATLAS/2p3pB,1001 +1wd5A,208,./datasets/ATLAS/1wd5A,1001 +5x1uB,208,./datasets/ATLAS/5x1uB,1001 +4dokA,208,./datasets/ATLAS/4dokA,1001 +5ja5A,209,./datasets/ATLAS/5ja5A,1001 +4zavA,209,./datasets/ATLAS/4zavA,1001 +1wbeA,209,./datasets/ATLAS/1wbeA,1001 +1j77A,209,./datasets/ATLAS/1j77A,1001 +1qnxA,209,./datasets/ATLAS/1qnxA,1001 +4ddpA,210,./datasets/ATLAS/4ddpA,1001 +3boeA,210,./datasets/ATLAS/3boeA,1001 +1w2wA,211,./datasets/ATLAS/1w2wA,1001 +2pu3A,211,./datasets/ATLAS/2pu3A,1001 +2vrsC,211,./datasets/ATLAS/2vrsC,1001 +3b49A,211,./datasets/ATLAS/3b49A,1001 +1qcsA,211,./datasets/ATLAS/1qcsA,1001 +4lq4A,211,./datasets/ATLAS/4lq4A,1001 +4jgiA,211,./datasets/ATLAS/4jgiA,1001 +2abkA,211,./datasets/ATLAS/2abkA,1001 +5a5yA,212,./datasets/ATLAS/5a5yA,1001 +3f0oB,212,./datasets/ATLAS/3f0oB,1001 +1ojqA,212,./datasets/ATLAS/1ojqA,1001 +1cojA,212,./datasets/ATLAS/1cojA,1001 +4h9nC,212,./datasets/ATLAS/4h9nC,1001 +3f0pA,212,./datasets/ATLAS/3f0pA,1001 +5a67A,212,./datasets/ATLAS/5a67A,1001 +3gnuP,213,./datasets/ATLAS/3gnuP,1001 +4wt3A,213,./datasets/ATLAS/4wt3A,1001 +1sdiA,213,./datasets/ATLAS/1sdiA,1001 +3claA,213,./datasets/ATLAS/3claA,1001 +3jsyB,213,./datasets/ATLAS/3jsyB,1001 +3fhfA,214,./datasets/ATLAS/3fhfA,1001 +4b2fA,214,./datasets/ATLAS/4b2fA,1001 +4qtqA,214,./datasets/ATLAS/4qtqA,1001 +1vajA,214,./datasets/ATLAS/1vajA,1001 +3st1A,214,./datasets/ATLAS/3st1A,1001 +3mqzA,215,./datasets/ATLAS/3mqzA,1001 +3da8A,215,./datasets/ATLAS/3da8A,1001 +1dzfA,215,./datasets/ATLAS/1dzfA,1001 +5t76A,215,./datasets/ATLAS/5t76A,1001 +2ov9C,216,./datasets/ATLAS/2ov9C,1001 +4fhrB,216,./datasets/ATLAS/4fhrB,1001 +3kbbA,216,./datasets/ATLAS/3kbbA,1001 +4dolA,217,./datasets/ATLAS/4dolA,1001 +2wnpF,217,./datasets/ATLAS/2wnpF,1001 +4a3pA,217,./datasets/ATLAS/4a3pA,1001 +1c1kA,217,./datasets/ATLAS/1c1kA,1001 +4cbeA,218,./datasets/ATLAS/4cbeA,1001 +4wzgA,218,./datasets/ATLAS/4wzgA,1001 +4ea9A,220,./datasets/ATLAS/4ea9A,1001 +5iffA,220,./datasets/ATLAS/5iffA,1001 +3e8tA,220,./datasets/ATLAS/3e8tA,1001 +5a0nA,220,./datasets/ATLAS/5a0nA,1001 +2hqkA,221,./datasets/ATLAS/2hqkA,1001 +2nugB,221,./datasets/ATLAS/2nugB,1001 +4fchB,221,./datasets/ATLAS/4fchB,1001 +1xtaA,221,./datasets/ATLAS/1xtaA,1001 +2ahnA,222,./datasets/ATLAS/2ahnA,1001 +3m4rA,222,./datasets/ATLAS/3m4rA,1001 +4adnB,222,./datasets/ATLAS/4adnB,1001 +1oisA,223,./datasets/ATLAS/1oisA,1001 +2hxmA,223,./datasets/ATLAS/2hxmA,1001 +1kopA,223,./datasets/ATLAS/1kopA,1001 +4ljoA,223,./datasets/ATLAS/4ljoA,1001 +1h99A,224,./datasets/ATLAS/1h99A,1001 +2dtrA,226,./datasets/ATLAS/2dtrA,1001 +1zn6A,227,./datasets/ATLAS/1zn6A,1001 +4n67A,227,./datasets/ATLAS/4n67A,1001 +5imuA,227,./datasets/ATLAS/5imuA,1001 +2c9iD,228,./datasets/ATLAS/2c9iD,1001 +2pbkB,228,./datasets/ATLAS/2pbkB,1001 +3ti2A,228,./datasets/ATLAS/3ti2A,1001 +1aolA,228,./datasets/ATLAS/1aolA,1001 +1t61E,229,./datasets/ATLAS/1t61E,1001 +3u9gA,229,./datasets/ATLAS/3u9gA,1001 +3o6pA,229,./datasets/ATLAS/3o6pA,1001 +1zosC,230,./datasets/ATLAS/1zosC,1001 +4m0qA,230,./datasets/ATLAS/4m0qA,1001 +5klhA,231,./datasets/ATLAS/5klhA,1001 +1d2tA,231,./datasets/ATLAS/1d2tA,1001 +1fx4A,231,./datasets/ATLAS/1fx4A,1001 +3ooiA,232,./datasets/ATLAS/3ooiA,1001 +3gkjA,232,./datasets/ATLAS/3gkjA,1001 +1k7cA,233,./datasets/ATLAS/1k7cA,1001 +2f5tX,233,./datasets/ATLAS/2f5tX,1001 +1y6iA,233,./datasets/ATLAS/1y6iA,1001 +2jftA,234,./datasets/ATLAS/2jftA,1001 +1fczA,235,./datasets/ATLAS/1fczA,1001 +1qwzA,235,./datasets/ATLAS/1qwzA,1001 +1qb7A,236,./datasets/ATLAS/1qb7A,1001 +4bgpA,236,./datasets/ATLAS/4bgpA,1001 +6fswA,236,./datasets/ATLAS/6fswA,1001 +2z0jE,237,./datasets/ATLAS/2z0jE,1001 +3bk5A,237,./datasets/ATLAS/3bk5A,1001 +3lktQ,238,./datasets/ATLAS/3lktQ,1001 +1hw1B,239,./datasets/ATLAS/1hw1B,1001 +4p5aA,239,./datasets/ATLAS/4p5aA,1001 +4bt9B,239,./datasets/ATLAS/4bt9B,1001 +2r31A,239,./datasets/ATLAS/2r31A,1001 +1t95A,240,./datasets/ATLAS/1t95A,1001 +3milA,240,./datasets/ATLAS/3milA,1001 +3nclA,241,./datasets/ATLAS/3nclA,1001 +1ql0B,241,./datasets/ATLAS/1ql0B,1001 +5j3tB,242,./datasets/ATLAS/5j3tB,1001 +3etoA,242,./datasets/ATLAS/3etoA,1001 +1vk1A,242,./datasets/ATLAS/1vk1A,1001 +3kvdD,242,./datasets/ATLAS/3kvdD,1001 +4iu3B,243,./datasets/ATLAS/4iu3B,1001 +4ct7A,243,./datasets/ATLAS/4ct7A,1001 +2pmkA,243,./datasets/ATLAS/2pmkA,1001 +3aa6B,244,./datasets/ATLAS/3aa6B,1001 +2x9oA,244,./datasets/ATLAS/2x9oA,1001 +3lyfD,245,./datasets/ATLAS/3lyfD,1001 +1ah7A,245,./datasets/ATLAS/1ah7A,1001 +2pqxA,245,./datasets/ATLAS/2pqxA,1001 +3rv1B,246,./datasets/ATLAS/3rv1B,1001 +3nqiA,246,./datasets/ATLAS/3nqiA,1001 +2oezB,247,./datasets/ATLAS/2oezB,1001 +4j4rA,248,./datasets/ATLAS/4j4rA,1001 +3i94A,248,./datasets/ATLAS/3i94A,1001 +4mzvA,248,./datasets/ATLAS/4mzvA,1001 +1lfpA,249,./datasets/ATLAS/1lfpA,1001 +3g3sB,249,./datasets/ATLAS/3g3sB,1001 +5wvoC,250,./datasets/ATLAS/5wvoC,1001 +2i5vO,251,./datasets/ATLAS/2i5vO,1001 +3nyyA,252,./datasets/ATLAS/3nyyA,1001 +3v68A,252,./datasets/ATLAS/3v68A,1001 +2d1lA,253,./datasets/ATLAS/2d1lA,1001 +2wn3C,254,./datasets/ATLAS/2wn3C,1001 +2phnA,254,./datasets/ATLAS/2phnA,1001 +2v4nA,254,./datasets/ATLAS/2v4nA,1001 +3dhaA,254,./datasets/ATLAS/3dhaA,1001 +3c8wC,255,./datasets/ATLAS/3c8wC,1001 +3dd6A,255,./datasets/ATLAS/3dd6A,1001 +4rswB,255,./datasets/ATLAS/4rswB,1001 +5ftwA,256,./datasets/ATLAS/5ftwA,1001 +4v23A,256,./datasets/ATLAS/4v23A,1001 +2qdxA,257,./datasets/ATLAS/2qdxA,1001 +2vmcA,257,./datasets/ATLAS/2vmcA,1001 +4cfiA,258,./datasets/ATLAS/4cfiA,1001 +2xjqA,258,./datasets/ATLAS/2xjqA,1001 +3dnhB,258,./datasets/ATLAS/3dnhB,1001 +3a1uA,258,./datasets/ATLAS/3a1uA,1001 +3lvuD,258,./datasets/ATLAS/3lvuD,1001 +1oh9A,258,./datasets/ATLAS/1oh9A,1001 +2jc5A,259,./datasets/ATLAS/2jc5A,1001 +1qgiA,259,./datasets/ATLAS/1qgiA,1001 +2wr8A,259,./datasets/ATLAS/2wr8A,1001 +1v7zF,260,./datasets/ATLAS/1v7zF,1001 +2fosA,260,./datasets/ATLAS/2fosA,1001 +2wkxA,261,./datasets/ATLAS/2wkxA,1001 +3rkgA,261,./datasets/ATLAS/3rkgA,1001 +2z4uA,261,./datasets/ATLAS/2z4uA,1001 +2rbkA,261,./datasets/ATLAS/2rbkA,1001 +1llnA,262,./datasets/ATLAS/1llnA,1001 +5heeB,262,./datasets/ATLAS/5heeB,1001 +2qiaA,262,./datasets/ATLAS/2qiaA,1001 +1r5lA,262,./datasets/ATLAS/1r5lA,1001 +1ig3A,263,./datasets/ATLAS/1ig3A,1001 +2gg2A,263,./datasets/ATLAS/2gg2A,1001 +1dj0B,264,./datasets/ATLAS/1dj0B,1001 +1pv5A,264,./datasets/ATLAS/1pv5A,1001 +2z6rA,265,./datasets/ATLAS/2z6rA,1001 +2wbfX,265,./datasets/ATLAS/2wbfX,1001 +5v7mA,265,./datasets/ATLAS/5v7mA,1001 +2p54A,267,./datasets/ATLAS/2p54A,1001 +1wuiS,267,./datasets/ATLAS/1wuiS,1001 +3ho6A,267,./datasets/ATLAS/3ho6A,1001 +1ssqD,267,./datasets/ATLAS/1ssqD,1001 +3ijwA,268,./datasets/ATLAS/3ijwA,1001 +3hlzB,269,./datasets/ATLAS/3hlzB,1001 +3m66A,270,./datasets/ATLAS/3m66A,1001 +5lpaA,270,./datasets/ATLAS/5lpaA,1001 +2xmxA,271,./datasets/ATLAS/2xmxA,1001 +2i2fA,272,./datasets/ATLAS/2i2fA,1001 +1h8eG,272,./datasets/ATLAS/1h8eG,1001 +1tdzA,272,./datasets/ATLAS/1tdzA,1001 +3lx5A,272,./datasets/ATLAS/3lx5A,1001 +3dffA,273,./datasets/ATLAS/3dffA,1001 +3d4iA,273,./datasets/ATLAS/3d4iA,1001 +1kgqA,274,./datasets/ATLAS/1kgqA,1001 +2v9mA,274,./datasets/ATLAS/2v9mA,1001 +2gkeA,274,./datasets/ATLAS/2gkeA,1001 +4yxpA,275,./datasets/ATLAS/4yxpA,1001 +2v27A,275,./datasets/ATLAS/2v27A,1001 +1dciC,275,./datasets/ATLAS/1dciC,1001 +2r2dA,276,./datasets/ATLAS/2r2dA,1001 +1k5nA,276,./datasets/ATLAS/1k5nA,1001 +4phrA,277,./datasets/ATLAS/4phrA,1001 +2pq8A,278,./datasets/ATLAS/2pq8A,1001 +3rxyA,278,./datasets/ATLAS/3rxyA,1001 +1bkpA,278,./datasets/ATLAS/1bkpA,1001 +1t7vA,278,./datasets/ATLAS/1t7vA,1001 +4gk9A,279,./datasets/ATLAS/4gk9A,1001 +2dt8A,280,./datasets/ATLAS/2dt8A,1001 +2zwdA,281,./datasets/ATLAS/2zwdA,1001 +4omfB,281,./datasets/ATLAS/4omfB,1001 +4xb6H,281,./datasets/ATLAS/4xb6H,1001 +1yqeA,282,./datasets/ATLAS/1yqeA,1001 +5oh5A,283,./datasets/ATLAS/5oh5A,1001 +3fo8D,283,./datasets/ATLAS/3fo8D,1001 +2i7cC,283,./datasets/ATLAS/2i7cC,1001 +2vg3C,284,./datasets/ATLAS/2vg3C,1001 +5jcaS,284,./datasets/ATLAS/5jcaS,1001 +4lzhA,285,./datasets/ATLAS/4lzhA,1001 +3ohgA,285,./datasets/ATLAS/3ohgA,1001 +3f7wA,288,./datasets/ATLAS/3f7wA,1001 +2p2vA,288,./datasets/ATLAS/2p2vA,1001 +1vzyB,291,./datasets/ATLAS/1vzyB,1001 +3t7hB,291,./datasets/ATLAS/3t7hB,1001 +4gsjA,291,./datasets/ATLAS/4gsjA,1001 +4p7xA,292,./datasets/ATLAS/4p7xA,1001 +1fxoG,293,./datasets/ATLAS/1fxoG,1001 +2fefB,294,./datasets/ATLAS/2fefB,1001 +1nnhA,294,./datasets/ATLAS/1nnhA,1001 +1lc3A,294,./datasets/ATLAS/1lc3A,1001 +2rkuA,294,./datasets/ATLAS/2rkuA,1001 +3q1nA,294,./datasets/ATLAS/3q1nA,1001 +5njlA,295,./datasets/ATLAS/5njlA,1001 +1hq0A,295,./datasets/ATLAS/1hq0A,1001 +3ltiA,296,./datasets/ATLAS/3ltiA,1001 +4g75A,297,./datasets/ATLAS/4g75A,1001 +1vkmC,297,./datasets/ATLAS/1vkmC,1001 +2w39A,298,./datasets/ATLAS/2w39A,1001 +3g5tA,299,./datasets/ATLAS/3g5tA,1001 +1rqjA,299,./datasets/ATLAS/1rqjA,1001 +1wlgB,299,./datasets/ATLAS/1wlgB,1001 +2v4bB,300,./datasets/ATLAS/2v4bB,1001 +3p3gA,300,./datasets/ATLAS/3p3gA,1001 +2ii1D,301,./datasets/ATLAS/2ii1D,1001 +1d3yB,301,./datasets/ATLAS/1d3yB,1001 +1wf3A,301,./datasets/ATLAS/1wf3A,1001 +5dmuA,301,./datasets/ATLAS/5dmuA,1001 +1mlwA,301,./datasets/ATLAS/1mlwA,1001 +3bl9A,301,./datasets/ATLAS/3bl9A,1001 +3b9qA,302,./datasets/ATLAS/3b9qA,1001 +4ngdA,302,./datasets/ATLAS/4ngdA,1001 +1q74C,303,./datasets/ATLAS/1q74C,1001 +2ixmA,303,./datasets/ATLAS/2ixmA,1001 +5ktsA,304,./datasets/ATLAS/5ktsA,1001 +2gnoA,305,./datasets/ATLAS/2gnoA,1001 +2blnB,305,./datasets/ATLAS/2blnB,1001 +4p3xA,305,./datasets/ATLAS/4p3xA,1001 +2h2zA,306,./datasets/ATLAS/2h2zA,1001 +2wsiA,306,./datasets/ATLAS/2wsiA,1001 +1zdyA,307,./datasets/ATLAS/1zdyA,1001 +5w53B,307,./datasets/ATLAS/5w53B,1001 +2hyvA,308,./datasets/ATLAS/2hyvA,1001 +2o6xA,310,./datasets/ATLAS/2o6xA,1001 +1ntyA,311,./datasets/ATLAS/1ntyA,1001 +2v05A,311,./datasets/ATLAS/2v05A,1001 +1xkgA,312,./datasets/ATLAS/1xkgA,1001 +1q8fA,313,./datasets/ATLAS/1q8fA,1001 +3hdjB,313,./datasets/ATLAS/3hdjB,1001 +1hyeA,313,./datasets/ATLAS/1hyeA,1001 +5exeC,314,./datasets/ATLAS/5exeC,1001 +3letB,314,./datasets/ATLAS/3letB,1001 +1zpeA,314,./datasets/ATLAS/1zpeA,1001 +4ehxA,315,./datasets/ATLAS/4ehxA,1001 +1qlmA,316,./datasets/ATLAS/1qlmA,1001 +5iz3B,316,./datasets/ATLAS/5iz3B,1001 +4gvqC,316,./datasets/ATLAS/4gvqC,1001 +4z9pA,317,./datasets/ATLAS/4z9pA,1001 +2ie6A,318,./datasets/ATLAS/2ie6A,1001 +3q0iA,318,./datasets/ATLAS/3q0iA,1001 +1nijA,318,./datasets/ATLAS/1nijA,1001 +1zxxA,319,./datasets/ATLAS/1zxxA,1001 +1ig0B,319,./datasets/ATLAS/1ig0B,1001 +4o87A,320,./datasets/ATLAS/4o87A,1001 +1ys1X,320,./datasets/ATLAS/1ys1X,1001 +3e4wB,320,./datasets/ATLAS/3e4wB,1001 +1yoeA,322,./datasets/ATLAS/1yoeA,1001 +1r6wA,322,./datasets/ATLAS/1r6wA,1001 +2yxnA,322,./datasets/ATLAS/2yxnA,1001 +1v9mA,323,./datasets/ATLAS/1v9mA,1001 +1tagA,324,./datasets/ATLAS/1tagA,1001 +1rm6B,324,./datasets/ATLAS/1rm6B,1001 +3aprE,325,./datasets/ATLAS/3aprE,1001 +4xb5A,326,./datasets/ATLAS/4xb5A,1001 +2q7xA,326,./datasets/ATLAS/2q7xA,1001 +1nnsA,326,./datasets/ATLAS/1nnsA,1001 +3kefB,326,./datasets/ATLAS/3kefB,1001 +1y7tB,327,./datasets/ATLAS/1y7tB,1001 +3im1A,328,./datasets/ATLAS/3im1A,1001 +5muyB,328,./datasets/ATLAS/5muyB,1001 +4epiA,330,./datasets/ATLAS/4epiA,1001 +3wwhA,330,./datasets/ATLAS/3wwhA,1001 +1mskA,331,./datasets/ATLAS/1mskA,1001 +5op0B,331,./datasets/ATLAS/5op0B,1001 +2wltA,332,./datasets/ATLAS/2wltA,1001 +2ppvA,332,./datasets/ATLAS/2ppvA,1001 +3bjdB,332,./datasets/ATLAS/3bjdB,1001 +2x49A,333,./datasets/ATLAS/2x49A,1001 +3mfdA,334,./datasets/ATLAS/3mfdA,1001 +1n7zA,334,./datasets/ATLAS/1n7zA,1001 +1wx1B,335,./datasets/ATLAS/1wx1B,1001 +1zswA,338,./datasets/ATLAS/1zswA,1001 +3dpgB,338,./datasets/ATLAS/3dpgB,1001 +4mp8A,339,./datasets/ATLAS/4mp8A,1001 +5ce9A,339,./datasets/ATLAS/5ce9A,1001 +4xduA,340,./datasets/ATLAS/4xduA,1001 +1uxyA,340,./datasets/ATLAS/1uxyA,1001 +3lpcA,340,./datasets/ATLAS/3lpcA,1001 +2uxyA,341,./datasets/ATLAS/2uxyA,1001 +3ezuA,342,./datasets/ATLAS/3ezuA,1001 +3gs9A,342,./datasets/ATLAS/3gs9A,1001 +2rdiA,342,./datasets/ATLAS/2rdiA,1001 +4m37A,343,./datasets/ATLAS/4m37A,1001 +1vbiA,344,./datasets/ATLAS/1vbiA,1001 +3sfvB,344,./datasets/ATLAS/3sfvB,1001 +2bjqA,345,./datasets/ATLAS/2bjqA,1001 +1z1lA,345,./datasets/ATLAS/1z1lA,1001 +3c2qB,345,./datasets/ATLAS/3c2qB,1001 +2oblA,347,./datasets/ATLAS/2oblA,1001 +3ib5A,348,./datasets/ATLAS/3ib5A,1001 +2cxiB,348,./datasets/ATLAS/2cxiB,1001 +1ux6A,350,./datasets/ATLAS/1ux6A,1001 +5ukiA,351,./datasets/ATLAS/5ukiA,1001 +5ws1A,352,./datasets/ATLAS/5ws1A,1001 +3se9G,353,./datasets/ATLAS/3se9G,1001 +3tgtA,353,./datasets/ATLAS/3tgtA,1001 +4ltyA,354,./datasets/ATLAS/4ltyA,1001 +4cdpA,354,./datasets/ATLAS/4cdpA,1001 +1xknA,355,./datasets/ATLAS/1xknA,1001 +1xszA,356,./datasets/ATLAS/1xszA,1001 +1l5oA,356,./datasets/ATLAS/1l5oA,1001 +1m15A,357,./datasets/ATLAS/1m15A,1001 +1ka1A,357,./datasets/ATLAS/1ka1A,1001 +3m5qA,357,./datasets/ATLAS/3m5qA,1001 +4gv2A,357,./datasets/ATLAS/4gv2A,1001 +3hfwA,357,./datasets/ATLAS/3hfwA,1001 +5l0sA,357,./datasets/ATLAS/5l0sA,1001 +3bqkA,360,./datasets/ATLAS/3bqkA,1001 +3qc5X,360,./datasets/ATLAS/3qc5X,1001 +3q1cA,360,./datasets/ATLAS/3q1cA,1001 +3oyvA,361,./datasets/ATLAS/3oyvA,1001 +1kewA,361,./datasets/ATLAS/1kewA,1001 +2ra8A,362,./datasets/ATLAS/2ra8A,1001 +1rgzA,363,./datasets/ATLAS/1rgzA,1001 +1m7vA,363,./datasets/ATLAS/1m7vA,1001 +5g68A,363,./datasets/ATLAS/5g68A,1001 +3becA,363,./datasets/ATLAS/3becA,1001 +3bptA,363,./datasets/ATLAS/3bptA,1001 +2ozlA,365,./datasets/ATLAS/2ozlA,1001 +2hgxB,365,./datasets/ATLAS/2hgxB,1001 +1fn9A,365,./datasets/ATLAS/1fn9A,1001 +1gqeA,365,./datasets/ATLAS/1gqeA,1001 +3d1gA,366,./datasets/ATLAS/3d1gA,1001 +3eojA,366,./datasets/ATLAS/3eojA,1001 +1iuqA,367,./datasets/ATLAS/1iuqA,1001 +1jq5A,370,./datasets/ATLAS/1jq5A,1001 +4jjaA,371,./datasets/ATLAS/4jjaA,1001 +3gqvA,371,./datasets/ATLAS/3gqvA,1001 +4rnzA,371,./datasets/ATLAS/4rnzA,1001 +5kwbA,371,./datasets/ATLAS/5kwbA,1001 +4xpzA,372,./datasets/ATLAS/4xpzA,1001 +5j47A,372,./datasets/ATLAS/5j47A,1001 +3eqxA,373,./datasets/ATLAS/3eqxA,1001 +2jhfB,374,./datasets/ATLAS/2jhfB,1001 +3ikwA,374,./datasets/ATLAS/3ikwA,1001 +4eziA,377,./datasets/ATLAS/4eziA,1001 +1iomA,377,./datasets/ATLAS/1iomA,1001 +4xglA,379,./datasets/ATLAS/4xglA,1001 +1lj5A,379,./datasets/ATLAS/1lj5A,1001 +3m6zA,380,./datasets/ATLAS/3m6zA,1001 +2pnwA,380,./datasets/ATLAS/2pnwA,1001 +1u6rB,380,./datasets/ATLAS/1u6rB,1001 +3m7dA,380,./datasets/ATLAS/3m7dA,1001 +1yu0A,381,./datasets/ATLAS/1yu0A,1001 +3lduA,385,./datasets/ATLAS/3lduA,1001 +1rrmA,386,./datasets/ATLAS/1rrmA,1001 +2rijA,387,./datasets/ATLAS/2rijA,1001 +1r0kA,388,./datasets/ATLAS/1r0kA,1001 +1qxoA,388,./datasets/ATLAS/1qxoA,1001 +3wa1A,389,./datasets/ATLAS/3wa1A,1001 +4limA,391,./datasets/ATLAS/4limA,1001 +5hkxA,392,./datasets/ATLAS/5hkxA,1001 +4ghnA,393,./datasets/ATLAS/4ghnA,1001 +3h1wA,393,./datasets/ATLAS/3h1wA,1001 +1g38A,393,./datasets/ATLAS/1g38A,1001 +1svbA,395,./datasets/ATLAS/1svbA,1001 +4kk7A,395,./datasets/ATLAS/4kk7A,1001 +1io1A,398,./datasets/ATLAS/1io1A,1001 +3twzA,399,./datasets/ATLAS/3twzA,1001 +3ot9B,399,./datasets/ATLAS/3ot9B,1001 +1ru4A,400,./datasets/ATLAS/1ru4A,1001 +1dljA,402,./datasets/ATLAS/1dljA,1001 +1gpjA,404,./datasets/ATLAS/1gpjA,1001 +3h1dA,405,./datasets/ATLAS/3h1dA,1001 +4s39A,406,./datasets/ATLAS/4s39A,1001 +2au3A,407,./datasets/ATLAS/2au3A,1001 +3ll7A,410,./datasets/ATLAS/3ll7A,1001 +5n0nA,410,./datasets/ATLAS/5n0nA,1001 +5n0sA,410,./datasets/ATLAS/5n0sA,1001 +1s9rA,410,./datasets/ATLAS/1s9rA,1001 +1lwdB,413,./datasets/ATLAS/1lwdB,1001 +3o04A,413,./datasets/ATLAS/3o04A,1001 +16pkA,415,./datasets/ATLAS/16pkA,1001 +1o75A,415,./datasets/ATLAS/1o75A,1001 +4af1A,416,./datasets/ATLAS/4af1A,1001 +5ngdB,417,./datasets/ATLAS/5ngdB,1001 +3mm6A,418,./datasets/ATLAS/3mm6A,1001 +1zjcA,418,./datasets/ATLAS/1zjcA,1001 +5erqA,419,./datasets/ATLAS/5erqA,1001 +5ertA,419,./datasets/ATLAS/5ertA,1001 +5gofA,422,./datasets/ATLAS/5gofA,1001 +2e7uA,424,./datasets/ATLAS/2e7uA,1001 +3d3yA,425,./datasets/ATLAS/3d3yA,1001 +2pa6B,427,./datasets/ATLAS/2pa6B,1001 +3msuB,427,./datasets/ATLAS/3msuB,1001 +3bznA,431,./datasets/ATLAS/3bznA,1001 +1vclA,432,./datasets/ATLAS/1vclA,1001 +1f20A,435,./datasets/ATLAS/1f20A,1001 +5h2dA,435,./datasets/ATLAS/5h2dA,1001 +2yjgA,436,./datasets/ATLAS/2yjgA,1001 +1mv8C,436,./datasets/ATLAS/1mv8C,1001 +3h5qA,436,./datasets/ATLAS/3h5qA,1001 +3zl8A,437,./datasets/ATLAS/3zl8A,1001 +3hxwA,441,./datasets/ATLAS/3hxwA,1001 +1hbnE,442,./datasets/ATLAS/1hbnE,1001 +4k2mA,443,./datasets/ATLAS/4k2mA,1001 +4qbuA,444,./datasets/ATLAS/4qbuA,1001 +2yclA,445,./datasets/ATLAS/2yclA,1001 +3vkwA,446,./datasets/ATLAS/3vkwA,1001 +4y93A,446,./datasets/ATLAS/4y93A,1001 +2bf6A,449,./datasets/ATLAS/2bf6A,1001 +5njcD,450,./datasets/ATLAS/5njcD,1001 +2rkvA,451,./datasets/ATLAS/2rkvA,1001 +2jlqA,451,./datasets/ATLAS/2jlqA,1001 +3lk7A,451,./datasets/ATLAS/3lk7A,1001 +4tkxL,452,./datasets/ATLAS/4tkxL,1001 +2gwnA,452,./datasets/ATLAS/2gwnA,1001 +2cb5A,453,./datasets/ATLAS/2cb5A,1001 +3a3dB,453,./datasets/ATLAS/3a3dB,1001 +2gg6A,455,./datasets/ATLAS/2gg6A,1001 +2vlfB,456,./datasets/ATLAS/2vlfB,1001 +1ewfA,456,./datasets/ATLAS/1ewfA,1001 +2ex2A,458,./datasets/ATLAS/2ex2A,1001 +3bhgA,459,./datasets/ATLAS/3bhgA,1001 +5b1qB,459,./datasets/ATLAS/5b1qB,1001 +2wyaA,460,./datasets/ATLAS/2wyaA,1001 +2pmbC,462,./datasets/ATLAS/2pmbC,1001 +1p5gX,463,./datasets/ATLAS/1p5gX,1001 +2xz3A,463,./datasets/ATLAS/2xz3A,1001 +1vdkB,466,./datasets/ATLAS/1vdkB,1001 +3ilwA,470,./datasets/ATLAS/3ilwA,1001 +3pt1A,471,./datasets/ATLAS/3pt1A,1001 +5muxB,472,./datasets/ATLAS/5muxB,1001 +3danA,473,./datasets/ATLAS/3danA,1001 +2jh3B,474,./datasets/ATLAS/2jh3B,1001 +1tezB,474,./datasets/ATLAS/1tezB,1001 +1u09A,476,./datasets/ATLAS/1u09A,1001 +4wywA,481,./datasets/ATLAS/4wywA,1001 +3ip4A,485,./datasets/ATLAS/3ip4A,1001 +1u8vC,490,./datasets/ATLAS/1u8vC,1001 +5hz7A,490,./datasets/ATLAS/5hz7A,1001 +2incA,491,./datasets/ATLAS/2incA,1001 +5txrB,491,./datasets/ATLAS/5txrB,1001 +3a2qA,493,./datasets/ATLAS/3a2qA,1001 +3b4wA,495,./datasets/ATLAS/3b4wA,1001 +4kctB,499,./datasets/ATLAS/4kctB,1001 +1eswA,500,./datasets/ATLAS/1eswA,1001 +2d5bA,500,./datasets/ATLAS/2d5bA,1001 +2qcuB,501,./datasets/ATLAS/2qcuB,1001 +3e2dA,502,./datasets/ATLAS/3e2dA,1001 +1gweA,503,./datasets/ATLAS/1gweA,1001 +4zacD,503,./datasets/ATLAS/4zacD,1001 +2yp8A,503,./datasets/ATLAS/2yp8A,1001 +3kd4A,506,./datasets/ATLAS/3kd4A,1001 +1v0wA,506,./datasets/ATLAS/1v0wA,1001 +4za9A,508,./datasets/ATLAS/4za9A,1001 +3holA,509,./datasets/ATLAS/3holA,1001 +6b1zA,511,./datasets/ATLAS/6b1zA,1001 +1o98A,511,./datasets/ATLAS/1o98A,1001 +2qp2A,511,./datasets/ATLAS/2qp2A,1001 +2ehqA,516,./datasets/ATLAS/2ehqA,1001 +1hp1A,516,./datasets/ATLAS/1hp1A,1001 +4djaA,518,./datasets/ATLAS/4djaA,1001 +4fc2B,521,./datasets/ATLAS/4fc2B,1001 +6eofA,522,./datasets/ATLAS/6eofA,1001 +4na5A,522,./datasets/ATLAS/4na5A,1001 +3jszA,525,./datasets/ATLAS/3jszA,1001 +1sx3A,525,./datasets/ATLAS/1sx3A,1001 +4mb5A,528,./datasets/ATLAS/4mb5A,1001 +5h7wB,529,./datasets/ATLAS/5h7wB,1001 +1wuiL,534,./datasets/ATLAS/1wuiL,1001 +1llfB,534,./datasets/ATLAS/1llfB,1001 +3ni2A,536,./datasets/ATLAS/3ni2A,1001 +3djlA,541,./datasets/ATLAS/3djlA,1001 +3do6A,543,./datasets/ATLAS/3do6A,1001 +2dkaA,544,./datasets/ATLAS/2dkaA,1001 +3crvA,551,./datasets/ATLAS/3crvA,1001 +1gntA,553,./datasets/ATLAS/1gntA,1001 +1uwkB,557,./datasets/ATLAS/1uwkB,1001 +3igzB,561,./datasets/ATLAS/3igzB,1001 +4ubpC,570,./datasets/ATLAS/4ubpC,1001 +2b7rA,571,./datasets/ATLAS/2b7rA,1001 +2ad6A,571,./datasets/ATLAS/2ad6A,1001 +1fehA,574,./datasets/ATLAS/1fehA,1001 +2py5A,575,./datasets/ATLAS/2py5A,1001 +6ao8A,580,./datasets/ATLAS/6ao8A,1001 +2hhvA,580,./datasets/ATLAS/2hhvA,1001 +1xwlA,580,./datasets/ATLAS/1xwlA,1001 +5oriA,583,./datasets/ATLAS/5oriA,1001 +5oswA,583,./datasets/ATLAS/5oswA,1001 +1f5nA,592,./datasets/ATLAS/1f5nA,1001 +1g7sA,594,./datasets/ATLAS/1g7sA,1001 +4d71A,596,./datasets/ATLAS/4d71A,1001 +2x96A,598,./datasets/ATLAS/2x96A,1001 +1o0sA,605,./datasets/ATLAS/1o0sA,1001 +1ikpA,613,./datasets/ATLAS/1ikpA,1001 +1b25D,619,./datasets/ATLAS/1b25D,1001 +4yalA,622,./datasets/ATLAS/4yalA,1001 +3g06A,622,./datasets/ATLAS/3g06A,1001 +1g9gA,629,./datasets/ATLAS/1g9gA,1001 +3l84A,632,./datasets/ATLAS/3l84A,1001 +5j72A,638,./datasets/ATLAS/5j72A,1001 +4cjnA,642,./datasets/ATLAS/4cjnA,1001 +1jnrC,643,./datasets/ATLAS/1jnrC,1001 +4z3xA,653,./datasets/ATLAS/4z3xA,1001 +3wkxA,669,./datasets/ATLAS/3wkxA,1001 +3ju4A,670,./datasets/ATLAS/3ju4A,1001 +5jbgA,680,./datasets/ATLAS/5jbgA,1001 +2xf2A,688,./datasets/ATLAS/2xf2A,1001 +3wolA,698,./datasets/ATLAS/3wolA,1001 +5ltjA,714,./datasets/ATLAS/5ltjA,1001 +5m45K,717,./datasets/ATLAS/5m45K,1001 +2e7zA,727,./datasets/ATLAS/2e7zA,1001 +1oaoC,729,./datasets/ATLAS/1oaoC,1001 +2b0tA,738,./datasets/ATLAS/2b0tA,1001 +5ul3A,744,./datasets/ATLAS/5ul3A,1001 +3eh1A,751,./datasets/ATLAS/3eh1A,1001 +1c96A,753,./datasets/ATLAS/1c96A,1001 +1h16A,759,./datasets/ATLAS/1h16A,1001 +3vthA,761,./datasets/ATLAS/3vthA,1001 +3p5pA,764,./datasets/ATLAS/3p5pA,1001 +4oj6C,776,./datasets/ATLAS/4oj6C,1001 +4ys0A,824,./datasets/ATLAS/4ys0A,1001 +3pzwA,839,./datasets/ATLAS/3pzwA,1001 +4h9mA,840,./datasets/ATLAS/4h9mA,1001 +2qmjA,870,./datasets/ATLAS/2qmjA,1001 +4v4eM,875,./datasets/ATLAS/4v4eM,1001 +5kdwB,885,./datasets/ATLAS/5kdwB,1001 +2b3yA,888,./datasets/ATLAS/2b3yA,1001 +3ebhA,889,./datasets/ATLAS/3ebhA,1001 +5kdvA,891,./datasets/ATLAS/5kdvA,1001 +2vccA,891,./datasets/ATLAS/2vccA,1001 +3nciA,903,./datasets/ATLAS/3nciA,1001 +3l4pA,907,./datasets/ATLAS/3l4pA,1001 +1vlbA,907,./datasets/ATLAS/1vlbA,1001 +1tg7A,971,./datasets/ATLAS/1tg7A,1001 +1gteD,1025,./datasets/ATLAS/1gteD,1001 +4aygB,1039,./datasets/ATLAS/4aygB,1001 +6j33B,1053,./datasets/ATLAS/6j33B,1001 +2po4A,1104,./datasets/ATLAS/2po4A,1001 +5vz0A,1144,./datasets/ATLAS/5vz0A,1001 +6qfkA,1357,./datasets/ATLAS/6qfkA,1001 +6supA,2128,./datasets/ATLAS/6supA,1001 + diff --git a/bbflow_base/dataset_csv/ATLAS_split/ATLAS_validation.csv b/bbflow_base/dataset_csv/ATLAS_split/ATLAS_validation.csv new file mode 100644 index 0000000000000000000000000000000000000000..9d944c8c5313595a431d9c2248b9ef427536f19e --- /dev/null +++ b/bbflow_base/dataset_csv/ATLAS_split/ATLAS_validation.csv @@ -0,0 +1,40 @@ +name,pdb_path +5nazA,./datasets/ATLAS/5nazA/5nazA.pdb +5w4aB,./datasets/ATLAS/5w4aB/5w4aB.pdb +5wfyA,./datasets/ATLAS/5wfyA/5wfyA.pdb +5yrvI,./datasets/ATLAS/5yrvI/5yrvI.pdb +5z51A,./datasets/ATLAS/5z51A/5z51A.pdb +5zmoA,./datasets/ATLAS/5zmoA/5zmoA.pdb +6a9aA,./datasets/ATLAS/6a9aA/6a9aA.pdb +6atgC,./datasets/ATLAS/6atgC/6atgC.pdb +6bm5A,./datasets/ATLAS/6bm5A/6bm5A.pdb +6bwqA,./datasets/ATLAS/6bwqA/6bwqA.pdb +6cb7A,./datasets/ATLAS/6cb7A/6cb7A.pdb +6crkG,./datasets/ATLAS/6crkG/6crkG.pdb +6dlmA,./datasets/ATLAS/6dlmA/6dlmA.pdb +6e33A,./datasets/ATLAS/6e33A/6e33A.pdb +6eu8A,./datasets/ATLAS/6eu8A/6eu8A.pdb +6fc0B,./datasets/ATLAS/6fc0B/6fc0B.pdb +6gfxC,./datasets/ATLAS/6gfxC/6gfxC.pdb +6hj6A,./datasets/ATLAS/6hj6A/6hj6A.pdb +6irxA,./datasets/ATLAS/6irxA/6irxA.pdb +6mdwA,./datasets/ATLAS/6mdwA/6mdwA.pdb +5ok6A,./datasets/ATLAS/5ok6A/5ok6A.pdb +5w82E,./datasets/ATLAS/5w82E/5w82E.pdb +5ydnA,./datasets/ATLAS/5ydnA/5ydnA.pdb +5z1nA,./datasets/ATLAS/5z1nA/5z1nA.pdb +5zlqA,./datasets/ATLAS/5zlqA/5zlqA.pdb +6a02A,./datasets/ATLAS/6a02A/6a02A.pdb +6as3A,./datasets/ATLAS/6as3A/6as3A.pdb +6bk4A,./datasets/ATLAS/6bk4A/6bk4A.pdb +6bn0A,./datasets/ATLAS/6bn0A/6bn0A.pdb +6c0hA,./datasets/ATLAS/6c0hA/6c0hA.pdb +6ckaB,./datasets/ATLAS/6ckaB/6ckaB.pdb +6dgkB,./datasets/ATLAS/6dgkB/6dgkB.pdb +6dnmA,./datasets/ATLAS/6dnmA/6dnmA.pdb +6e5yA,./datasets/ATLAS/6e5yA/6e5yA.pdb +6f45D,./datasets/ATLAS/6f45D/6f45D.pdb +6fubB,./datasets/ATLAS/6fubB/6fubB.pdb +6hemA,./datasets/ATLAS/6hemA/6hemA.pdb +6idxA,./datasets/ATLAS/6idxA/6idxA.pdb +6mbgA,./datasets/ATLAS/6mbgA/6mbgA.pdb \ No newline at end of file diff --git a/bbflow_base/experiments/__pycache__/inference.cpython-39.pyc b/bbflow_base/experiments/__pycache__/inference.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8de814efd80f5e04a529edbdf52363912352a46e Binary files /dev/null and b/bbflow_base/experiments/__pycache__/inference.cpython-39.pyc differ diff --git a/bbflow_base/experiments/__pycache__/train.cpython-311.pyc b/bbflow_base/experiments/__pycache__/train.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1fbb435cdc4970eabefbe83bcdb3d5c6cbdeb68 Binary files /dev/null and b/bbflow_base/experiments/__pycache__/train.cpython-311.pyc differ diff --git a/bbflow_base/experiments/__pycache__/train.cpython-39.pyc b/bbflow_base/experiments/__pycache__/train.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcd588af3ce05908436880767a24cbd08ec228d0 Binary files /dev/null and b/bbflow_base/experiments/__pycache__/train.cpython-39.pyc differ diff --git a/bbflow_base/experiments/inference.py b/bbflow_base/experiments/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..6bbf1f98c5d34767a0c14131ed686c79ffac70db --- /dev/null +++ b/bbflow_base/experiments/inference.py @@ -0,0 +1,189 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""DDP inference script.""" +import os +import time +import numpy as np +import hydra +import torch +from torch.utils.data import DataLoader +from typing import Optional +from pathlib import Path +import pandas as pd +from pytorch_lightning import Trainer +from omegaconf import DictConfig, OmegaConf +import logging + +from gafl import experiment_utils as eu + +from bbflow.models.bbflow_module import BBFlowModule +from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb + +log = eu.get_pylogger(__name__) +logging.getLogger('MDAnalysis.analysis.base').setLevel(logging.WARNING) +logging.getLogger('MDAnalysis.analysis.align').setLevel(logging.WARNING) +torch.set_float32_matmul_precision('high') + +class Sampler: + + def __init__(self, cfg: DictConfig): + """Initialize sampler. + + Args: + cfg: inference config. + """ + ckpt_path = cfg.inference.ckpt_path + assert os.path.isfile(ckpt_path), f'Checkpoint path {ckpt_path} does not exist!' + ckpt_dir = os.path.dirname(ckpt_path) + cfg_path = os.path.join(ckpt_dir, 'config.yaml') + assert os.path.isfile(cfg_path), f'Config file {cfg_path} does not exist!' + ckpt_cfg = OmegaConf.load(os.path.join(ckpt_dir, 'config.yaml')) + + # Set-up config. + OmegaConf.set_struct(cfg, False) + OmegaConf.set_struct(ckpt_cfg, False) + cfg = OmegaConf.merge(cfg, ckpt_cfg) + cfg.experiment.checkpointer.dirpath = './' + cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior + # both only necessary if prior != pure_noise + cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional + cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot + cfg.model.embed = ckpt_cfg.model.embed + + self._cfg = cfg + self._ckpt_cfg = ckpt_cfg + self._infer_cfg = cfg.inference + self._samples_cfg = self._infer_cfg.samples + self._rng = np.random.default_rng(self._infer_cfg.seed) + + # Set-up directories to write results to + if self._infer_cfg.use_ckpt_name_in_outpath: + self._ckpt_name = '/'.join(ckpt_path.replace('.ckpt', '').split('/')[-3:]) + self._output_dir = os.path.join( + self._infer_cfg.output_dir, + self._ckpt_name, + self._infer_cfg.name, + ) + else: + self._output_dir = os.path.join( + self._infer_cfg.output_dir, + self._infer_cfg.name, + ) + os.makedirs(self._output_dir, exist_ok=True) + config_path = os.path.join(self._output_dir, 'config.yaml') + with open(config_path, 'w') as f: + OmegaConf.save(config=self._cfg, f=f) + log.info(f'Saving inference config to {config_path}') + + self._flow_module = self.load_module(ckpt_path) + self._flow_module.eval() + self._flow_module._infer_cfg = self._infer_cfg + self._flow_module._samples_cfg = self._samples_cfg + self._flow_module._output_dir = self._output_dir + + def load_module(self, ckpt_path): + # Keep the module on CPU until Lightning assigns one copy to each DDP rank. + ckpt = torch.load(ckpt_path, map_location='cpu') + module = BBFlowModule(self._cfg) + current_state = module.state_dict() + checkpoint_state = ckpt["state_dict"] + compatible_state = { + k: v for k, v in checkpoint_state.items() + if k in current_state and current_state[k].shape == v.shape + } + missing, unexpected = module.load_state_dict(compatible_state, strict=False) + collective_enabled = bool( + hasattr(self._cfg, "latent") + and getattr(self._cfg.latent, "collective_enable", False) + ) + dropped = [ + key for key, value in checkpoint_state.items() + if key not in current_state or current_state[key].shape != value.shape + ] + if collective_enabled and (missing or unexpected or dropped): + raise ValueError( + "CMFM inference requires an exact checkpoint/config match: " + f"missing={missing}, unexpected={unexpected}, dropped={dropped}" + ) + if unexpected or dropped: + log.warning( + f"Ignored {len(unexpected)} unexpected and {len(dropped)} incompatible checkpoint tensors" + ) + return module + + def run_sampling(self): + visible_device_count = torch.cuda.device_count() + requested_devices = int(self._infer_cfg.num_gpus) + if visible_device_count < requested_devices: + raise RuntimeError( + f"Requested {requested_devices} CUDA device(s), but PyTorch sees " + f"{visible_device_count}. Check CUDA_VISIBLE_DEVICES." + ) + devices = list(range(requested_devices)) + device_names = [torch.cuda.get_device_name(i) for i in devices] + log.info(f"Using devices: {devices} ({device_names})") + # eval_dataset = eu.LengthDataset(self._samples_cfg) + + if self._infer_cfg.csv_path is not None: + csv = pd.read_csv(self._infer_cfg.csv_path) + # randomly subsample proteins if num_proteins is set + if self._infer_cfg.num_proteins is not None: + csv = csv.sample( + n=self._infer_cfg.num_proteins, + random_state=self._infer_cfg.seed, + ).reset_index(drop=True) + dataset = PDBDatasetBBFlowFromPdb( + csv, + sort=self._infer_cfg.sort, + min_length=0 if self._infer_cfg.min_length is None else self._infer_cfg.min_length, + max_length=np.inf if self._infer_cfg.max_length is None else self._infer_cfg.max_length, + ) + else: + raise ValueError('No csv path provided') + + log.info(f"Sampling {self._infer_cfg.samples.samples_per_protein} conformations per Protein for {len(dataset)} proteins.") + + dataloader = DataLoader( + dataset, + batch_size=1, + shuffle=False, + num_workers=int(getattr(self._infer_cfg, "num_workers", 2)), + prefetch_factor=None if int(getattr(self._infer_cfg, "num_workers", 2)) == 0 else 2, + persistent_workers=int(getattr(self._infer_cfg, "num_workers", 2)) > 0, + ) + + trainer = Trainer( + accelerator="gpu", + strategy="ddp" if requested_devices > 1 else "auto", + devices=devices, + precision=str(getattr( + self._infer_cfg, + "precision", + self._cfg.experiment.trainer.precision, + )), + enable_progress_bar=self._infer_cfg.use_tqdm, + ) + + hashtagline = '#' * 80 + log.info(f'\n\n{hashtagline}\n' + f'Starting inference run: {self._infer_cfg.name}\nSaving results to {self._output_dir}\n{hashtagline}\n') + + trainer.predict(self._flow_module, dataloaders=dataloader) + + +@hydra.main(version_base=None, config_path="../configs", config_name="inference") +def run(cfg: DictConfig) -> None: + + # Read model checkpoint. + log.info(f'Starting inference with {cfg.inference.num_gpus} GPUs') + start_time = time.time() + sampler = Sampler(cfg) + sampler.run_sampling() + elapsed_time = time.time() - start_time + log.info(f'Finished in {elapsed_time:.2f}s') + +if __name__ == '__main__': + run() diff --git a/bbflow_base/experiments/train.py b/bbflow_base/experiments/train.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7dc7c5b2686d5b4c1fc5f0451abfb9db5b0e4 --- /dev/null +++ b/bbflow_base/experiments/train.py @@ -0,0 +1,239 @@ +# Copyright (c) 2025 Max Planck Institute for Polymer Research +# Copyright (c) 2024 HITS gGmbH +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import os +import torch + +# import torch.multiprocessing as mp +# mp.set_start_method('spawn', force=True) + +import hydra +from omegaconf import DictConfig, OmegaConf + +# Pytorch lightning imports +import pytorch_lightning as pl +from pytorch_lightning import LightningDataModule, LightningModule, Trainer +from pytorch_lightning.loggers.wandb import WandbLogger +from pytorch_lightning.trainer import Trainer +from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor +import wandb +import logging + +from gafl import experiment_utils as eu + +from bbflow.models.bbflow_module import BBFlowModule +from bbflow.data.pdb_dataloader_bbflow import PdbDataModuleBBFlow + +from packaging import version + + +log = eu.get_pylogger(__name__) +torch.set_float32_matmul_precision('high') + + +class Experiment: + + def __init__(self, *, cfg: DictConfig): + os.makedirs(cfg.experiment.checkpointer.dirpath, exist_ok=True) + self._cfg = cfg + self._data_cfg = cfg.data + self._exp_cfg = cfg.experiment + + self.create_data_module() + self.create_module() + + def create_module(self): + self._model: LightningModule = BBFlowModule(self._cfg) + + def create_data_module(self): + latent_cfg = self._cfg.latent if hasattr(self._cfg, "latent") else None + self._datamodule: LightningDataModule = PdbDataModuleBBFlow( + self._data_cfg, + training_cfg=self._exp_cfg.training, + latent_cfg=latent_cfg, + ) + + def train(self): + callbacks = [] + if self._exp_cfg.debug: + log.info("Debug mode.") + logger = None + self._exp_cfg.num_devices = 1 + self._data_cfg.loader.num_workers = 0 + else: + if self._exp_cfg.use_wandb: + logger = WandbLogger( + **self._exp_cfg.wandb, + ) + else: + logger = False + + # Checkpoint directory. + ckpt_dir = self._exp_cfg.checkpointer.dirpath + os.makedirs(ckpt_dir, exist_ok=True) + log.info(f"Checkpoints saved to {ckpt_dir}") + + # Model checkpoints. A periodic checkpointer only refreshes last.ckpt when + # its own interval fires, so with every_n_epochs=5 last.ckpt is a byte-for-byte + # copy of the newest periodic file and an interrupted run silently loses up to + # four epochs of training. Hand last.ckpt to a second writer that runs every + # epoch and keeps nothing else; the periodic one stops writing it. + ckpt_cfg = dict(self._exp_cfg.checkpointer) + every_n_epochs = int(ckpt_cfg.get("every_n_epochs", 1) or 1) + if every_n_epochs > 1 and bool(ckpt_cfg.get("save_last", False)): + ckpt_cfg["save_last"] = False + callbacks.append(ModelCheckpoint(**ckpt_cfg)) + callbacks.append(ModelCheckpoint( + dirpath=ckpt_cfg["dirpath"], + save_last=True, + save_top_k=0, + every_n_epochs=1, + save_on_train_epoch_end=True, + )) + else: + callbacks.append(ModelCheckpoint(**ckpt_cfg)) + callbacks.append(eu.ValidationCallback(self._exp_cfg.first_val_epoch)) + + scheduler_cfg = self._exp_cfg.get("scheduler") + if scheduler_cfg is not None and scheduler_cfg.get("enabled", False) and logger is not None: + lr_monitor = LearningRateMonitor(logging_interval='epoch') + callbacks.append(lr_monitor) + + # Save config + cfg_path = os.path.join(ckpt_dir, 'config.yaml') + with open(cfg_path, 'w') as f: + OmegaConf.save(config=self._cfg, f=f.name) + cfg_dict = OmegaConf.to_container(self._cfg, resolve=True) + flat_cfg = dict(eu.flatten_dict(cfg_dict)) + if self._exp_cfg.use_wandb and isinstance(logger.experiment.config, wandb.sdk.wandb_config.Config): + logger.experiment.config.update(flat_cfg) + + visible_device_count = torch.cuda.device_count() + requested_devices = int(self._exp_cfg.num_devices) + if visible_device_count < requested_devices: + raise RuntimeError( + f"Requested {requested_devices} CUDA device(s), but PyTorch sees " + f"{visible_device_count}. Check CUDA_VISIBLE_DEVICES." + ) + devices = list(range(requested_devices)) + device_names = [torch.cuda.get_device_name(i) for i in devices] + log.info(f"Using devices: {devices} ({device_names})") + + trainer_kwargs = dict( + **self._exp_cfg.trainer, + callbacks=callbacks, + logger=logger, + enable_progress_bar=self._exp_cfg.use_tqdm, + enable_model_summary=True, + devices=devices, + ) + + # the `replace_sampler_ddp` flag is deprecated in newer versions of PL + PL_VERSION = version.parse(pl.__version__) + if PL_VERSION >= version.parse("2.3.0"): + trainer_kwargs["use_distributed_sampler"] = False + else: + trainer_kwargs["replace_sampler_ddp"] = False + + trainer = Trainer( + **trainer_kwargs + ) + + fit_ckpt_path = self._exp_cfg.warm_start + model_only_warm_start = bool( + getattr(self._exp_cfg, "model_only_warm_start", False) + ) + if fit_ckpt_path is not None and model_only_warm_start: + ckpt = torch.load(fit_ckpt_path, map_location="cpu", weights_only=False) + if "state_dict" not in ckpt: + raise ValueError(f"Warm-start checkpoint has no state_dict: {fit_ckpt_path}") + raw_state = ckpt["state_dict"] + # Load into the LightningModule, not just ``self._model.model``. + # ``latent_encoder`` is an attribute of the module (bbflow_module.py + # builds ``self.model`` and ``self.latent_encoder`` side by side), so + # its keys carry no ``model.`` prefix. Filtering them against + # ``self._model.model.state_dict()`` silently dropped every mode-head + # tensor while the foundation weights still produced a healthy-looking + # count -- a stage-1 warm start appeared to work and trained the mode + # head from scratch anyway. Matching against the full module state + # resolves ``model.*`` and ``latent_encoder.*`` in one pass. + current_state = self._model.state_dict() + compatible_state = { + key: value for key, value in raw_state.items() + if key in current_state and current_state[key].shape == value.shape + } + if not compatible_state: + raise ValueError( + f"No compatible BBFlow model tensors found in {fit_ckpt_path}" + ) + missing, unexpected = self._model.load_state_dict( + compatible_state, strict=False + ) + # Reported per top-level submodule: an all-or-nothing total is exactly + # what hid the dropped mode head. + loaded_by_prefix = {} + for key in compatible_state: + loaded_by_prefix.setdefault(key.split(".")[0], 0) + loaded_by_prefix[key.split(".")[0]] += 1 + log.info( + "Loaded warm start weights into model only: " + f"{len(compatible_state)} tensors {loaded_by_prefix}, " + f"missing={len(missing)}, unexpected={len(unexpected)}. " + "Optimizer/scheduler start fresh." + ) + fit_ckpt_path = None + elif fit_ckpt_path is not None: + ckpt = torch.load(fit_ckpt_path, map_location="cpu", weights_only=False) + if "pytorch-lightning_version" not in ckpt: + model_ckpt = ckpt["state_dict"] + model_ckpt = {k.replace("model.", ""): v for k, v in model_ckpt.items()} + current_state = self._model.model.state_dict() + compatible_state = { + k: v for k, v in model_ckpt.items() + if k in current_state and current_state[k].shape == v.shape + } + missing, unexpected = self._model.model.load_state_dict(compatible_state, strict=False) + log.info( + "Loaded non-Lightning warm start into model only: " + f"{len(compatible_state)} tensors, missing={len(missing)}, unexpected={len(unexpected)}" + ) + fit_ckpt_path = None + + trainer.fit( + model=self._model, + datamodule=self._datamodule, + ckpt_path=fit_ckpt_path + ) + +@hydra.main(version_base=None, config_path="../configs", config_name="train.yaml") +def main(cfg: DictConfig): + + if cfg.experiment.warm_start is not None and cfg.experiment.warm_start_cfg_override: + # Loads warm start config. + warm_start_cfg_path = os.path.join( + os.path.dirname(cfg.experiment.warm_start), 'config.yaml') + warm_start_cfg = OmegaConf.load(warm_start_cfg_path) + + # Warm start config may not have latest fields in the base config. + # Add these fields to the warm start config. + OmegaConf.set_struct(cfg.model, False) + OmegaConf.set_struct(warm_start_cfg.model, False) + cfg.model = OmegaConf.merge(cfg.model, warm_start_cfg.model) + OmegaConf.set_struct(cfg.model, True) + log.info(f'Loaded warm start config from {warm_start_cfg_path}') + + # Ensure that all processes write to the same output directory. + if int(os.environ.get("LOCAL_RANK", 0)) == 0: + base_output_dir = cfg.experiment.checkpointer.dirpath + else: + base_output_dir = os.environ.get("HYDRA_OUTPUT_DIR", cfg.experiment.checkpointer.dirpath) + os.environ['HYDRA_OUTPUT_DIR'] = base_output_dir + cfg.experiment.checkpointer.dirpath = base_output_dir + + exp = Experiment(cfg=cfg) + exp.train() + +if __name__ == "__main__": + main() diff --git a/bbflow_base/models/bbflow-0.1/config.yaml b/bbflow_base/models/bbflow-0.1/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3d8bd5e38a1d8ff97992f87193fa3cdfb10f0ded --- /dev/null +++ b/bbflow_base/models/bbflow-0.1/config.yaml @@ -0,0 +1,178 @@ +data: + dataset: + seed: 123 + min_num_res: 0 + max_num_res: 730 + subset: null + split_path: ${experiment.checkpointer.dirpath} + train_csv_path: ../datasets/BBFlow/train/alphaflow_atlas_train_full_traj.csv + valid_csv_paths: + - ../datasets/BBFlow/validation/ATLAS_valid.csv + valid_dataset_names: + - ATLAS_valid + test_csv_path: ../datasets/BBFlow/test/alphaflow_atlas_test.csv + validation: + metrics_subset: + - RMSD + - RMSF + - Ramachandran-W2 + - DCCM + - RMWD + - PCA-W2 + - Cosine Sim + - Weak Transient Contacts + valid_xtc_paths: + - ../datasets/ATLAS/ATLAS_valid_xtc/ + alphaflow_valid_pdb_paths: + - ../datasets/ATLAS/alphaflow_valid_pdb/ + alphaflow_valid_rmsf_path: ${experiment.checkpointer.dirpath}/alphaflow_rmsf.json + alphaflow_valid_local_rmsf_path: ${experiment.checkpointer.dirpath}/alphaflow_local_rmsf.json + samples_per_valid_protein: 10 + max_valid_batch_size: 100 + max_valid_num_res_squared: 2900000 + loader: + num_workers: 8 + prefetch_factor: 10 + sampler: + max_batch_size: 100 + max_num_res_squared: 250000 + max_conformations: 20 +experiment: + debug: false + use_wandb: true + use_tqdm: false + seed: 123 + num_devices: 2 + warm_start: null + warm_start_cfg_override: true + use_swa: false + first_val_epoch: 40 + reset_epoch: false + batch_ot: + enabled: true + cost: kabsch + noise_per_sample: 1 + training: + min_plddt_mask: null + loss: se3_vf_loss + bb_atom_scale: 0.1 + trans_scale: 0.1 + translation_loss_weight: 2.0 + t_normalize_clip: 0.9 + rotation_loss_weights: 1.0 + aux_loss_weight: 1.0 + aux_loss_t_pass: 0.25 + t_bins: 4 + wandb: + name: rt02_noDir + project: bbflow + save_dir: outputs/ + tags: [] + optimizer: + lr: 0.0001 + reset_optimizer_on_load: false + warmup_lr: false + warmup_lr_factor: 0.01 + trainer: + overfit_batches: 0 + min_epochs: 1 + max_epochs: 250 + accelerator: gpu + log_every_n_steps: 1 + deterministic: false + strategy: ddp + check_val_every_n_epoch: 1 + default_root_dir: outputs/ + accumulate_grad_batches: 1 + checkpointer: + dirpath: outputs/ckpt/bbflow/rt02_noDir/2025-01-17_23-55-20 + save_last: true + save_on_train_epoch_end: true + filename: epoch:{epoch:03d} + every_n_epochs: 1 + save_top_k: -1 + auto_insert_metric_name: false + checkpointer2: null + profiler: + enabled: false + modules: null + profile: + use_cuda: true + with_stack: false + stats: + group_by_stack_n: 0 + group_by_input_shapes: false + prefixes: + - 'layer_0::' + - 'layer_1::' + sort_by: cpu_time_total + scheduler: + enabled: false +interpolant: + use_tqdm: ${experiment.use_tqdm} + batch_ot: intra + prior: conditional + prior_conditional: + gamma_trans: 0.2 + gamma_rots: 0.2 + min_t: 0.01 + t_interval: + - 0.0 + - 1.0 + rots: + distribution: uniform + train_schedule: linear + sample_schedule: exp + exp_rate: 10 + trans: + train_schedule: linear + sample_schedule: linear + sampling: + num_timesteps: 20 + self_condition: ${model.edge_features.self_condition} + noise_res_scaling_power: 0.0 + noise_scale: 1.0 + t_sampling_focus: 0.0 +model: + node_embed_size: 240 + edge_embed_size: 120 + embed: + index_embed_dim: 128 + time_embed_dim: 128 + embed_aatype: true + aatype_embed_dim: 128 + length_embed_dim: 16 + embed_self_conditioning: true + num_bins_distance: 22 + min_bin_distance: 1.0e-05 + max_bin_distance: 20.0 + embed_distogram: true + embed_direction: false + node_features: + c_s: ${model.node_embed_size} + c_pos_emb: 120 + c_timestep_emb: 120 + embed_diffuse_mask: false + max_num_res: 2000 + timestep_int: 1000 + edge_features: + single_bias_transition_n: 2 + c_s: ${model.node_embed_size} + c_p: ${model.edge_embed_size} + relpos_k: 64 + use_rbf: true + num_rbf: 32 + feat_dim: 64 + num_bins: 22 + self_condition: true + embed_breaks: true + gfa: + c_s: ${model.node_embed_size} + c_z: ${model.edge_embed_size} + c_hidden: 120 + no_heads: 8 + no_qk_points: 8 + no_v_points: 8 + seq_tfmr_num_heads: 4 + seq_tfmr_num_layers: 2 + num_blocks: 6