data_transfer / bbflow_base /bbflow /data /pdb_dataloader_bbflow.py
hanghang214's picture
Add files using upload-large-folder tool
9e6e56b verified
Raw History Blame Contribute Delete
24.9 kB
# 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)