Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- bbflow_base/base_stages/00_extract_shape_fingerprints.shAdded+33
- bbflow_base/base_stages/00_train_base_ddp.shAdded+155
- bbflow_base/base_stages/00_train_base_pure_ddp.shAdded+92
- bbflow_base/base_stages/00_train_base_pure_then_probe_ddp.shAdded+30
- bbflow_base/base_stages/00_train_final_mog_ddp.shAdded+239
- bbflow_base/base_stages/01_train_control_baseline_ddp.shAdded+84
- bbflow_base/base_stages/02_diagnose_z.shAdded+22
- bbflow_base/base_stages/03_diagnose_film.shAdded+46
- bbflow_base/base_stages/04_fit_template_upper_bound.shAdded+48
- bbflow_base/base_stages/05_probe_sample_condition.shAdded+50
- bbflow_base/base_stages/06_probe_condition_ensemble_cov.shAdded+48
- bbflow_base/base_stages/07_probe_condition_quality_vs_md.shAdded+59
- bbflow_base/base_stages/08_eval_long_finetune_downstream.shAdded+175
- bbflow_base/base_stages/10_train_cmfm_ddp.shAdded+91
- bbflow_base/base_stages/11_infer_cmfm.shAdded+39
- bbflow_base/base_stages/13_train_md_subspace_ddp.shAdded+136
- bbflow_base/base_stages/13_train_md_subspace_ddp.sh.bakAdded+136
- bbflow_base/base_stages/14_serial_diagnose_then_train.shAdded+93
- bbflow_base/base_stages/99_preflight_base.shAdded+102
- bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-310.pycAdded
- bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-311.pycAdded
- bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-39.pycAdded
- bbflow_base/bbflow/analysis/__pycache__/utils.cpython-310.pycAdded
- bbflow_base/bbflow/analysis/__pycache__/utils.cpython-311.pycAdded
- bbflow_base/bbflow/analysis/analyse_bbflow.pyAdded+1007
- bbflow_base/bbflow/analysis/utils.pyAdded+114
- bbflow_base/bbflow/data/__pycache__/alignment.cpython-310.pycAdded
- bbflow_base/bbflow/data/__pycache__/alignment.cpython-311.pycAdded
- bbflow_base/bbflow/data/__pycache__/alignment.cpython-39.pycAdded
- bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-310.pycAdded
- bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-311.pycAdded
- bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-39.pycAdded
- bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-310.pycAdded
- bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-311.pycAdded
- bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-39.pycAdded
- bbflow_base/bbflow/data/__pycache__/utils.cpython-310.pycAdded
- bbflow_base/bbflow/data/__pycache__/utils.cpython-311.pycAdded
- bbflow_base/bbflow/data/alignment.pyAdded+60
- bbflow_base/bbflow/data/interpolant_bbflow.pyAdded+318
- bbflow_base/bbflow/data/pdb_dataloader_bbflow.pyAdded+590
- bbflow_base/bbflow/data/utils.pyAdded+115
- bbflow_base/bbflow/deployment/__pycache__/bbflow.cpython-39.pycAdded
- bbflow_base/bbflow/deployment/__pycache__/utils.cpython-39.pycAdded
- bbflow_base/bbflow/deployment/bbflow.pyAdded+311
- bbflow_base/bbflow/deployment/cmd_line_entry.pyAdded+228
- bbflow_base/bbflow/deployment/utils.pyAdded+149
- bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-310.pycAdded
- bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-311.pycAdded
- bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-39.pycAdded
- bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-310.pycAdded
123456789101112131415161718192021222324252627282930313233#!/usr/bin/env bashset -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"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155#!/usr/bin/env bashset -eset -uset -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"fiBASE_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"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/usr/bin/env bashset -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"fiBASE_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"123456789101112131415161718192021222324252627282930#!/usr/bin/env bashset -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}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239#!/usr/bin/env bashset -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"fiBASE_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=trueelse FORCE_GROUPED_BATCH=falsefiPRECISION="${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 2fiDIAGNOSTIC_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"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384#!/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"12345678910111213141516171819202122#!/usr/bin/env bashset -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 cuda12345678910111213141516171819202122232425262728293031323334353637383940414243444546
#!/usr/bin/env bashset -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}]"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#!/usr/bin/env bashset -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"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#!/usr/bin/env bashset -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}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#!/usr/bin/env bashset -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"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859#!/usr/bin/env bashset -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"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175#!/usr/bin/env bashset -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 2fi
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 jsonimport sysfrom 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"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091#!/usr/bin/env bashset -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"fiBASE_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"fiFINGERPRINT_CACHE="${FINGERPRINT_CACHE:-${DEFAULT_FINGERPRINT_CACHE}}"
if [[ ! -f "${BASE_CKPT}" ]]; then echo "Missing official BBFlow checkpoint: ${BASE_CKPT}" >&2 exit 2fiif [[ ! -f "${FINGERPRINT_CACHE}" ]]; then echo "Missing K8 motion-target cache: ${FINGERPRINT_CACHE}" >&2 exit 2fi
export RUN_DIRexport BASE_CKPTexport FINGERPRINT_CACHEexport GPU_IDS="${GPU_IDS:-0,1,2}"export NUM_DEVICES="${NUM_DEVICES:-3}"export NUM_MODES=8export MIXTURE_COMPONENTS=2export 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=trueexport Q_DETACH_SHARED_ENCODER=trueexport 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=trueexport LAMBDA_GENERATOR_COV=0.0export LAMBDA_CONDITION_CYCLE=0.0export LAMBDA_MOTION=1.0export LAMBDA_Q=1.0export LAMBDA_MODE_ORTH=1.0export LAMBDA_MODE_RECON=0.0export VALID_SAMPLES_PER_PROTEIN="${VALID_SAMPLES_PER_PROTEIN:-6}"export EPOCH_CONDITION_PROBE=falseexport 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.sh123456789101112131415161718192021222324252627282930313233343536373839#!/usr/bin/env bashset -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 2fiif [[ ! -f "${TEST_CSV}" ]]; then echo "Missing test CSV: ${TEST_CSV}" >&2 exit 2fi
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=20123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136#!/usr/bin/env bashset -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<k singularity forced.## * lambda_md_subspace matches the q-implied covariance to the reference one in the# reference eigenbasis. Closed form, no sampling, scale sensitive.## * lambda_local_cov and lambda_cross_cov go to zero. Those fit covariance entries in# the residue basis, which does not pin the eigenvectors -- two ellipses can agree# entrywise and be rotated relative to one another. The subspace loss replaces them.## * lambda_rmsf stays, and is raised from 0.25 to 1.0. The subspace loss only# constrains the part of U lying inside the reference subspace; amplitude outside it# is unconstrained, and that is precisely what the K=2 evaluation metric cannot see.# The subspace audit of the previous checkpoint measured the damage: total variance# 1.62x MD's, and outside MD's top 10 directions 3.6x MD's, while inside the top 2 --# the only place the score looks -- it is actually 27% low. rmsf is the one enabled# term that reaches the outside variance, so 0.25 was leaving it essentially free.## Nothing is deleted from the codebase: the collective path is disabled by config, so# reverting is a matter of flipping these values back.
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/mdsubspace_$(date +%Y%m%d_%H%M%S)}"
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"fiBASE_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"fiFINGERPRINT_CACHE="${FINGERPRINT_CACHE:-${DEFAULT_FINGERPRINT_CACHE}}"
if [[ ! -f "${BASE_CKPT}" ]]; then echo "Missing official BBFlow checkpoint: ${BASE_CKPT}" >&2 exit 2fiif [[ ! -f "${FINGERPRINT_CACHE}" ]]; then echo "Missing motion-target cache: ${FINGERPRINT_CACHE}" >&2 exit 2fi
# 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_CACHEexport GPU_IDS="${GPU_IDS:-0,1,2}"export NUM_DEVICES="${NUM_DEVICES:-3}"export NUM_MODES=8export MIXTURE_COMPONENTS=2
# No grouping: 00_ derives FORCE_GROUPED_BATCH from this being zero.export ENSEMBLE_GROUP_SIZE=0export 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=trueexport FREEZE_FOUNDATION="${FREEZE_FOUNDATION:-false}"export FREEZE_MODE_HEAD=false # U is what the subspace loss is meant to moveexport MODEL_ONLY_WARM_START=true
export LAMBDA_GENERATOR_COV="${LAMBDA_GENERATOR_COV:-0.0}"export LAMBDA_CONDITION_CYCLE=0.0export LAMBDA_MODE_RECON=0.0export LAMBDA_MOTION=1.0 # gate for motion_recon; per-term weights belowexport LAMBDA_Q=1.0export 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.sh123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136#!/usr/bin/env bashset -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<k singularity forced.## * lambda_md_subspace matches the q-implied covariance to the reference one in the# reference eigenbasis. Closed form, no sampling, scale sensitive.## * lambda_local_cov and lambda_cross_cov go to zero. Those fit covariance entries in# the residue basis, which does not pin the eigenvectors -- two ellipses can agree# entrywise and be rotated relative to one another. The subspace loss replaces them.## * lambda_rmsf stays, and is raised from 0.25 to 1.0. The subspace loss only# constrains the part of U lying inside the reference subspace; amplitude outside it# is unconstrained, and that is precisely what the K=2 evaluation metric cannot see.# The subspace audit of the previous checkpoint measured the damage: total variance# 1.62x MD's, and outside MD's top 10 directions 3.6x MD's, while inside the top 2 --# the only place the score looks -- it is actually 27% low. rmsf is the one enabled# term that reaches the outside variance, so 0.25 was leaving it essentially free.## Nothing is deleted from the codebase: the collective path is disabled by config, so# reverting is a matter of flipping these values back.
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/mdsubspace_$(date +%Y%m%d_%H%M%S)}"
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"fiBASE_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"fiFINGERPRINT_CACHE="${FINGERPRINT_CACHE:-${DEFAULT_FINGERPRINT_CACHE}}"
if [[ ! -f "${BASE_CKPT}" ]]; then echo "Missing official BBFlow checkpoint: ${BASE_CKPT}" >&2 exit 2fiif [[ ! -f "${FINGERPRINT_CACHE}" ]]; then echo "Missing motion-target cache: ${FINGERPRINT_CACHE}" >&2 exit 2fi
# 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_CACHEexport GPU_IDS="${GPU_IDS:-0,1,2}"export NUM_DEVICES="${NUM_DEVICES:-3}"export NUM_MODES=8export MIXTURE_COMPONENTS=2
# No grouping: 00_ derives FORCE_GROUPED_BATCH from this being zero.export ENSEMBLE_GROUP_SIZE=0export 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=trueexport FREEZE_FOUNDATION="${FREEZE_FOUNDATION:-false}"export FREEZE_MODE_HEAD=false # U is what the subspace loss is meant to moveexport MODEL_ONLY_WARM_START=true
export LAMBDA_GENERATOR_COV="${LAMBDA_GENERATOR_COV:-0.0}"export LAMBDA_CONDITION_CYCLE=0.0export LAMBDA_MODE_RECON=0.0export LAMBDA_MOTION=1.0 # gate for motion_recon; per-term weights belowexport LAMBDA_Q=1.0export 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.sh123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293#!/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 auditechoecho "[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=10echoecho "[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}"); fidoneif [[ ${#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. trainingechoecho "[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]}"
echoecho "=============================================================="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 "=============================================================="123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102#!/usr/bin/env bashset -eset -uset -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"fiBASE_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"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007# Copyright (c) 2025 Max Planck Institute for Polymer Research# Licensed under the MIT license.
import numpy as npimport warningsimport pandas as pdimport scipy.statsimport osimport functoolsfrom sklearn.decomposition import PCAfrom scipy.stats import bootstrapimport mdtrajfrom tqdm import tqdmfrom datetime import datetimeimport pandas as pdimport numpy as npfrom multiprocessing import Poolfrom scipy.optimize import linear_sum_assignmentimport MDAnalysis as mdaimport warningsimport 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 outdef _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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114# 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 npimport osimport refrom Bio import PDB
from openfold.utils import rigid_utilsfrom gafl.data import proteinfrom gafl.analysis.utils import write_prot_to_pdb, get_pdb_lengthfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318# Copyright (c) 2025 Max Planck Institute for Polymer Research# Copyright (c) 2024 HITS gGmbH# Copyright (c) Microsoft Corporation.# Licensed under the MIT license.
import torchimport numpy as npfrom scipy.spatial.transform import Rotationimport osimport contextlibfrom scipy.optimize import linear_sum_assignmentfrom sklearn.metrics import pairwise_distancesfrom tqdm.auto import tqdmimport pandas as pdimport loggingfrom torch.utils.data.distributed import dist
from gafl.data import so3_utilsfrom gafl.data import utils as dufrom gafl.data import all_atomfrom 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 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590# 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115# Copyright (c) 2025 Max Planck Institute for Polymer Research# Licensed under the MIT license.
from pathlib import Pathfrom typing import List, Tuple, Dict, Anyimport torchimport numpy as npimport mdtrajimport osfrom tqdm.auto import tqdm
from openfold.data.data_transforms import atom37_to_framesfrom openfold.utils.rigid_utils import Rigid
from gafl.data.residue_constants import restype_order
# from bbflow.analysis.analyse_bbflow import calc_aligned_rmsffrom bbflow.analysis.analyse_bbflow import _calc_rmsf, _align_topsimport 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 rmsfs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311# Copyright (c) 2025 Max Planck Institute for Polymer Research# Licensed under the MIT license.
import osimport timeimport numpy as npimport hydraimport torchfrom torch.utils.data import DataLoaderimport GPUtilimport subprocessfrom typing import Optionalfrom pathlib import Pathimport pandas as pdfrom pytorch_lightning import Trainerimport warningsimport loggingfrom typing import Unionfrom pathlib import Pathfrom tqdm.auto import tqdm
from omegaconf import DictConfig, OmegaConffrom 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 eufrom gafl.data import utils as dufrom bbflow.analysis import utils as aufrom bbflow.deployment.utils import estimate_max_batchsize, recursive_update, ckpt_path_from_tag
from bbflow.models.bbflow_module import BBFlowModulefrom 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 )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228# Copyright (c) 2025 Max Planck Institute for Polymer Research# Licensed under the MIT license.
from bbflow.deployment.bbflow import BBFlowfrom argparse import ArgumentParserfrom pathlib import Pathfrom 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}."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149# Copyright (c) 2025 Max Planck Institute for Polymer Research# Licensed under the MIT license.
import numpy as npfrom pathlib import Pathfrom typing import Unionimport loggingimport requestsfrom 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_pathbbflow_base/base_stages/00_extract_shape_fingerprints.shAdded+33
bbflow_base/base_stages/00_train_base_ddp.shAdded+155
bbflow_base/base_stages/00_train_base_pure_ddp.shAdded+92
bbflow_base/base_stages/00_train_base_pure_then_probe_ddp.shAdded+30
bbflow_base/base_stages/00_train_final_mog_ddp.shAdded+239
bbflow_base/base_stages/01_train_control_baseline_ddp.shAdded+84
bbflow_base/base_stages/02_diagnose_z.shAdded+22
bbflow_base/base_stages/03_diagnose_film.shAdded+46
bbflow_base/base_stages/04_fit_template_upper_bound.shAdded+48
bbflow_base/base_stages/05_probe_sample_condition.shAdded+50
bbflow_base/base_stages/06_probe_condition_ensemble_cov.shAdded+48
bbflow_base/base_stages/07_probe_condition_quality_vs_md.shAdded+59
bbflow_base/base_stages/08_eval_long_finetune_downstream.shAdded+175
bbflow_base/base_stages/10_train_cmfm_ddp.shAdded+91
bbflow_base/base_stages/11_infer_cmfm.shAdded+39
bbflow_base/base_stages/13_train_md_subspace_ddp.shAdded+136
bbflow_base/base_stages/13_train_md_subspace_ddp.sh.bakAdded+136
bbflow_base/base_stages/14_serial_diagnose_then_train.shAdded+93
bbflow_base/base_stages/99_preflight_base.shAdded+102
bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-310.pycAdded
bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-311.pycAdded
bbflow_base/bbflow/analysis/__pycache__/analyse_bbflow.cpython-39.pycAdded
bbflow_base/bbflow/analysis/__pycache__/utils.cpython-310.pycAdded
bbflow_base/bbflow/analysis/__pycache__/utils.cpython-311.pycAdded
bbflow_base/bbflow/analysis/analyse_bbflow.pyAdded+1007
bbflow_base/bbflow/analysis/utils.pyAdded+114
bbflow_base/bbflow/data/__pycache__/alignment.cpython-310.pycAdded
bbflow_base/bbflow/data/__pycache__/alignment.cpython-311.pycAdded
bbflow_base/bbflow/data/__pycache__/alignment.cpython-39.pycAdded
bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-310.pycAdded
bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-311.pycAdded
bbflow_base/bbflow/data/__pycache__/interpolant_bbflow.cpython-39.pycAdded
bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-310.pycAdded
bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-311.pycAdded
bbflow_base/bbflow/data/__pycache__/pdb_dataloader_bbflow.cpython-39.pycAdded
bbflow_base/bbflow/data/__pycache__/utils.cpython-310.pycAdded
bbflow_base/bbflow/data/__pycache__/utils.cpython-311.pycAdded
bbflow_base/bbflow/data/alignment.pyAdded+60
bbflow_base/bbflow/data/interpolant_bbflow.pyAdded+318
bbflow_base/bbflow/data/pdb_dataloader_bbflow.pyAdded+590
bbflow_base/bbflow/data/utils.pyAdded+115
bbflow_base/bbflow/deployment/__pycache__/bbflow.cpython-39.pycAdded
bbflow_base/bbflow/deployment/__pycache__/utils.cpython-39.pycAdded
bbflow_base/bbflow/deployment/bbflow.pyAdded+311
bbflow_base/bbflow/deployment/cmd_line_entry.pyAdded+228
bbflow_base/bbflow/deployment/utils.pyAdded+149
bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-310.pycAdded
bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-311.pycAdded
bbflow_base/bbflow/models/__pycache__/bbflow_model.cpython-39.pycAdded
bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-310.pycAdded