File size: 7,654 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
# Copyright (c) 2025 Max Planck Institute for Polymer Research
# Copyright (c) 2024 HITS gGmbH
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

"""DDP inference script."""
import os
import time
import numpy as np
import hydra
import torch
from torch.utils.data import DataLoader
from typing import Optional
from pathlib import Path
import pandas as pd
from pytorch_lightning import Trainer
from omegaconf import DictConfig, OmegaConf
import logging

from gafl import experiment_utils as eu

from bbflow.models.bbflow_module import BBFlowModule
from bbflow.data.pdb_dataloader_bbflow import PDBDatasetBBFlowFromPdb

log = eu.get_pylogger(__name__)
logging.getLogger('MDAnalysis.analysis.base').setLevel(logging.WARNING)
logging.getLogger('MDAnalysis.analysis.align').setLevel(logging.WARNING)
torch.set_float32_matmul_precision('high')

class Sampler:

    def __init__(self, cfg: DictConfig):
        """Initialize sampler.

        Args:
            cfg: inference config.
        """
        ckpt_path = cfg.inference.ckpt_path
        assert os.path.isfile(ckpt_path), f'Checkpoint path {ckpt_path} does not exist!'
        ckpt_dir = os.path.dirname(ckpt_path)
        cfg_path = os.path.join(ckpt_dir, 'config.yaml')
        assert os.path.isfile(cfg_path), f'Config file {cfg_path} does not exist!'
        ckpt_cfg = OmegaConf.load(os.path.join(ckpt_dir, 'config.yaml'))

        # Set-up config.
        OmegaConf.set_struct(cfg, False)
        OmegaConf.set_struct(ckpt_cfg, False)
        cfg = OmegaConf.merge(cfg, ckpt_cfg)
        cfg.experiment.checkpointer.dirpath = './'
        cfg.inference.interpolant.prior = ckpt_cfg.interpolant.prior
        # both only necessary if prior != pure_noise
        cfg.inference.interpolant.prior_conditional = ckpt_cfg.interpolant.prior_conditional
        cfg.inference.interpolant.batch_ot = ckpt_cfg.interpolant.batch_ot
        cfg.model.embed = ckpt_cfg.model.embed

        self._cfg = cfg
        self._ckpt_cfg = ckpt_cfg
        self._infer_cfg = cfg.inference
        self._samples_cfg = self._infer_cfg.samples
        self._rng = np.random.default_rng(self._infer_cfg.seed)

        # Set-up directories to write results to
        if self._infer_cfg.use_ckpt_name_in_outpath:
            self._ckpt_name = '/'.join(ckpt_path.replace('.ckpt', '').split('/')[-3:])
            self._output_dir = os.path.join(
                self._infer_cfg.output_dir,
                self._ckpt_name,
                self._infer_cfg.name,
            )
        else:
            self._output_dir = os.path.join(
                self._infer_cfg.output_dir,
                self._infer_cfg.name,
            )
        os.makedirs(self._output_dir, exist_ok=True)
        config_path = os.path.join(self._output_dir, 'config.yaml')
        with open(config_path, 'w') as f:
            OmegaConf.save(config=self._cfg, f=f)
        log.info(f'Saving inference config to {config_path}')

        self._flow_module = self.load_module(ckpt_path)
        self._flow_module.eval()
        self._flow_module._infer_cfg = self._infer_cfg
        self._flow_module._samples_cfg = self._samples_cfg
        self._flow_module._output_dir = self._output_dir

    def load_module(self, ckpt_path):
        # Keep the module on CPU until Lightning assigns one copy to each DDP rank.
        ckpt = torch.load(ckpt_path, map_location='cpu')
        module = BBFlowModule(self._cfg)
        current_state = module.state_dict()
        checkpoint_state = ckpt["state_dict"]
        compatible_state = {
            k: v for k, v in checkpoint_state.items()
            if k in current_state and current_state[k].shape == v.shape
        }
        missing, unexpected = module.load_state_dict(compatible_state, strict=False)
        collective_enabled = bool(
            hasattr(self._cfg, "latent")
            and getattr(self._cfg.latent, "collective_enable", False)
        )
        dropped = [
            key for key, value in checkpoint_state.items()
            if key not in current_state or current_state[key].shape != value.shape
        ]
        if collective_enabled and (missing or unexpected or dropped):
            raise ValueError(
                "CMFM inference requires an exact checkpoint/config match: "
                f"missing={missing}, unexpected={unexpected}, dropped={dropped}"
            )
        if unexpected or dropped:
            log.warning(
                f"Ignored {len(unexpected)} unexpected and {len(dropped)} incompatible checkpoint tensors"
            )
        return module

    def run_sampling(self):
        visible_device_count = torch.cuda.device_count()
        requested_devices = int(self._infer_cfg.num_gpus)
        if visible_device_count < requested_devices:
            raise RuntimeError(
                f"Requested {requested_devices} CUDA device(s), but PyTorch sees "
                f"{visible_device_count}. Check CUDA_VISIBLE_DEVICES."
            )
        devices = list(range(requested_devices))
        device_names = [torch.cuda.get_device_name(i) for i in devices]
        log.info(f"Using devices: {devices} ({device_names})")
        # eval_dataset = eu.LengthDataset(self._samples_cfg)
        
        if self._infer_cfg.csv_path is not None:
            csv = pd.read_csv(self._infer_cfg.csv_path)
            # randomly subsample proteins if num_proteins is set
            if self._infer_cfg.num_proteins is not None:
                csv = csv.sample(
                    n=self._infer_cfg.num_proteins,
                    random_state=self._infer_cfg.seed,
                ).reset_index(drop=True)
            dataset = PDBDatasetBBFlowFromPdb(
                csv, 
                sort=self._infer_cfg.sort,
                min_length=0 if self._infer_cfg.min_length is None else self._infer_cfg.min_length,
                max_length=np.inf if self._infer_cfg.max_length is None else self._infer_cfg.max_length,
            )
        else:
            raise ValueError('No csv path provided')
        
        log.info(f"Sampling {self._infer_cfg.samples.samples_per_protein} conformations per Protein for {len(dataset)} proteins.")
        
        dataloader = DataLoader(
            dataset,
            batch_size=1,
            shuffle=False,
            num_workers=int(getattr(self._infer_cfg, "num_workers", 2)),
            prefetch_factor=None if int(getattr(self._infer_cfg, "num_workers", 2)) == 0 else 2,
            persistent_workers=int(getattr(self._infer_cfg, "num_workers", 2)) > 0,
        )

        trainer = Trainer(
            accelerator="gpu",
            strategy="ddp" if requested_devices > 1 else "auto",
            devices=devices,
            precision=str(getattr(
                self._infer_cfg,
                "precision",
                self._cfg.experiment.trainer.precision,
            )),
            enable_progress_bar=self._infer_cfg.use_tqdm,
        )

        hashtagline = '#' * 80
        log.info(f'\n\n{hashtagline}\n'
                 f'Starting inference run: {self._infer_cfg.name}\nSaving results to {self._output_dir}\n{hashtagline}\n')
        
        trainer.predict(self._flow_module, dataloaders=dataloader)


@hydra.main(version_base=None, config_path="../configs", config_name="inference")
def run(cfg: DictConfig) -> None:

    # Read model checkpoint.
    log.info(f'Starting inference with {cfg.inference.num_gpus} GPUs')
    start_time = time.time()
    sampler = Sampler(cfg)
    sampler.run_sampling()
    elapsed_time = time.time() - start_time
    log.info(f'Finished in {elapsed_time:.2f}s')

if __name__ == '__main__':
    run()