File size: 10,508 Bytes
9e6e56b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | # Copyright (c) 2025 Max Planck Institute for Polymer Research
# Copyright (c) 2024 HITS gGmbH
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
import torch
# import torch.multiprocessing as mp
# mp.set_start_method('spawn', force=True)
import hydra
from omegaconf import DictConfig, OmegaConf
# Pytorch lightning imports
import pytorch_lightning as pl
from pytorch_lightning import LightningDataModule, LightningModule, Trainer
from pytorch_lightning.loggers.wandb import WandbLogger
from pytorch_lightning.trainer import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor
import wandb
import logging
from gafl import experiment_utils as eu
from bbflow.models.bbflow_module import BBFlowModule
from bbflow.data.pdb_dataloader_bbflow import PdbDataModuleBBFlow
from packaging import version
log = eu.get_pylogger(__name__)
torch.set_float32_matmul_precision('high')
class Experiment:
def __init__(self, *, cfg: DictConfig):
os.makedirs(cfg.experiment.checkpointer.dirpath, exist_ok=True)
self._cfg = cfg
self._data_cfg = cfg.data
self._exp_cfg = cfg.experiment
self.create_data_module()
self.create_module()
def create_module(self):
self._model: LightningModule = BBFlowModule(self._cfg)
def create_data_module(self):
latent_cfg = self._cfg.latent if hasattr(self._cfg, "latent") else None
self._datamodule: LightningDataModule = PdbDataModuleBBFlow(
self._data_cfg,
training_cfg=self._exp_cfg.training,
latent_cfg=latent_cfg,
)
def train(self):
callbacks = []
if self._exp_cfg.debug:
log.info("Debug mode.")
logger = None
self._exp_cfg.num_devices = 1
self._data_cfg.loader.num_workers = 0
else:
if self._exp_cfg.use_wandb:
logger = WandbLogger(
**self._exp_cfg.wandb,
)
else:
logger = False
# Checkpoint directory.
ckpt_dir = self._exp_cfg.checkpointer.dirpath
os.makedirs(ckpt_dir, exist_ok=True)
log.info(f"Checkpoints saved to {ckpt_dir}")
# Model checkpoints. A periodic checkpointer only refreshes last.ckpt when
# its own interval fires, so with every_n_epochs=5 last.ckpt is a byte-for-byte
# copy of the newest periodic file and an interrupted run silently loses up to
# four epochs of training. Hand last.ckpt to a second writer that runs every
# epoch and keeps nothing else; the periodic one stops writing it.
ckpt_cfg = dict(self._exp_cfg.checkpointer)
every_n_epochs = int(ckpt_cfg.get("every_n_epochs", 1) or 1)
if every_n_epochs > 1 and bool(ckpt_cfg.get("save_last", False)):
ckpt_cfg["save_last"] = False
callbacks.append(ModelCheckpoint(**ckpt_cfg))
callbacks.append(ModelCheckpoint(
dirpath=ckpt_cfg["dirpath"],
save_last=True,
save_top_k=0,
every_n_epochs=1,
save_on_train_epoch_end=True,
))
else:
callbacks.append(ModelCheckpoint(**ckpt_cfg))
callbacks.append(eu.ValidationCallback(self._exp_cfg.first_val_epoch))
scheduler_cfg = self._exp_cfg.get("scheduler")
if scheduler_cfg is not None and scheduler_cfg.get("enabled", False) and logger is not None:
lr_monitor = LearningRateMonitor(logging_interval='epoch')
callbacks.append(lr_monitor)
# Save config
cfg_path = os.path.join(ckpt_dir, 'config.yaml')
with open(cfg_path, 'w') as f:
OmegaConf.save(config=self._cfg, f=f.name)
cfg_dict = OmegaConf.to_container(self._cfg, resolve=True)
flat_cfg = dict(eu.flatten_dict(cfg_dict))
if self._exp_cfg.use_wandb and isinstance(logger.experiment.config, wandb.sdk.wandb_config.Config):
logger.experiment.config.update(flat_cfg)
visible_device_count = torch.cuda.device_count()
requested_devices = int(self._exp_cfg.num_devices)
if visible_device_count < requested_devices:
raise RuntimeError(
f"Requested {requested_devices} CUDA device(s), but PyTorch sees "
f"{visible_device_count}. Check CUDA_VISIBLE_DEVICES."
)
devices = list(range(requested_devices))
device_names = [torch.cuda.get_device_name(i) for i in devices]
log.info(f"Using devices: {devices} ({device_names})")
trainer_kwargs = dict(
**self._exp_cfg.trainer,
callbacks=callbacks,
logger=logger,
enable_progress_bar=self._exp_cfg.use_tqdm,
enable_model_summary=True,
devices=devices,
)
# the `replace_sampler_ddp` flag is deprecated in newer versions of PL
PL_VERSION = version.parse(pl.__version__)
if PL_VERSION >= version.parse("2.3.0"):
trainer_kwargs["use_distributed_sampler"] = False
else:
trainer_kwargs["replace_sampler_ddp"] = False
trainer = Trainer(
**trainer_kwargs
)
fit_ckpt_path = self._exp_cfg.warm_start
model_only_warm_start = bool(
getattr(self._exp_cfg, "model_only_warm_start", False)
)
if fit_ckpt_path is not None and model_only_warm_start:
ckpt = torch.load(fit_ckpt_path, map_location="cpu", weights_only=False)
if "state_dict" not in ckpt:
raise ValueError(f"Warm-start checkpoint has no state_dict: {fit_ckpt_path}")
raw_state = ckpt["state_dict"]
# Load into the LightningModule, not just ``self._model.model``.
# ``latent_encoder`` is an attribute of the module (bbflow_module.py
# builds ``self.model`` and ``self.latent_encoder`` side by side), so
# its keys carry no ``model.`` prefix. Filtering them against
# ``self._model.model.state_dict()`` silently dropped every mode-head
# tensor while the foundation weights still produced a healthy-looking
# count -- a stage-1 warm start appeared to work and trained the mode
# head from scratch anyway. Matching against the full module state
# resolves ``model.*`` and ``latent_encoder.*`` in one pass.
current_state = self._model.state_dict()
compatible_state = {
key: value for key, value in raw_state.items()
if key in current_state and current_state[key].shape == value.shape
}
if not compatible_state:
raise ValueError(
f"No compatible BBFlow model tensors found in {fit_ckpt_path}"
)
missing, unexpected = self._model.load_state_dict(
compatible_state, strict=False
)
# Reported per top-level submodule: an all-or-nothing total is exactly
# what hid the dropped mode head.
loaded_by_prefix = {}
for key in compatible_state:
loaded_by_prefix.setdefault(key.split(".")[0], 0)
loaded_by_prefix[key.split(".")[0]] += 1
log.info(
"Loaded warm start weights into model only: "
f"{len(compatible_state)} tensors {loaded_by_prefix}, "
f"missing={len(missing)}, unexpected={len(unexpected)}. "
"Optimizer/scheduler start fresh."
)
fit_ckpt_path = None
elif fit_ckpt_path is not None:
ckpt = torch.load(fit_ckpt_path, map_location="cpu", weights_only=False)
if "pytorch-lightning_version" not in ckpt:
model_ckpt = ckpt["state_dict"]
model_ckpt = {k.replace("model.", ""): v for k, v in model_ckpt.items()}
current_state = self._model.model.state_dict()
compatible_state = {
k: v for k, v in model_ckpt.items()
if k in current_state and current_state[k].shape == v.shape
}
missing, unexpected = self._model.model.load_state_dict(compatible_state, strict=False)
log.info(
"Loaded non-Lightning warm start into model only: "
f"{len(compatible_state)} tensors, missing={len(missing)}, unexpected={len(unexpected)}"
)
fit_ckpt_path = None
trainer.fit(
model=self._model,
datamodule=self._datamodule,
ckpt_path=fit_ckpt_path
)
@hydra.main(version_base=None, config_path="../configs", config_name="train.yaml")
def main(cfg: DictConfig):
if cfg.experiment.warm_start is not None and cfg.experiment.warm_start_cfg_override:
# Loads warm start config.
warm_start_cfg_path = os.path.join(
os.path.dirname(cfg.experiment.warm_start), 'config.yaml')
warm_start_cfg = OmegaConf.load(warm_start_cfg_path)
# Warm start config may not have latest fields in the base config.
# Add these fields to the warm start config.
OmegaConf.set_struct(cfg.model, False)
OmegaConf.set_struct(warm_start_cfg.model, False)
cfg.model = OmegaConf.merge(cfg.model, warm_start_cfg.model)
OmegaConf.set_struct(cfg.model, True)
log.info(f'Loaded warm start config from {warm_start_cfg_path}')
# Ensure that all processes write to the same output directory.
if int(os.environ.get("LOCAL_RANK", 0)) == 0:
base_output_dir = cfg.experiment.checkpointer.dirpath
else:
base_output_dir = os.environ.get("HYDRA_OUTPUT_DIR", cfg.experiment.checkpointer.dirpath)
os.environ['HYDRA_OUTPUT_DIR'] = base_output_dir
cfg.experiment.checkpointer.dirpath = base_output_dir
exp = Experiment(cfg=cfg)
exp.train()
if __name__ == "__main__":
main()
|