data_modules.py 17.7 KB
Newer Older
1
import copy
2
3
4
5
from functools import partial
import json
import logging
import os
6
import pickle
7
8
9
from typing import Optional, Sequence

import ml_collections as mlc
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
10
import numpy as np
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import pytorch_lightning as pl
import torch
from torch.utils.data import RandomSampler

from openfold.data import (
    data_pipeline,
    feature_pipeline,
    mmcif_parsing,
    templates,
)
from openfold.utils.tensor_utils import tensor_tree_map, dict_multimap


class OpenFoldSingleDataset(torch.utils.data.Dataset):
    def __init__(self,
        data_dir: str,
        alignment_dir: str, 
        template_mmcif_dir: str,
        max_template_date: str,
        config: mlc.ConfigDict,
        kalign_binary_path: str = '/usr/bin/kalign',
        mapping_path: Optional[str] = None,
        max_template_hits: int = 4,
        template_release_dates_cache_path: Optional[str] = None,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
35
        shuffle_top_k_prefiltered: Optional[int] = None,
36
        mode: str = "train", 
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
37
        _output_raw: bool = False,
38
39
40
41
42
43
44
45
46
47
48
    ):
        """
            Args:
                data_dir:
                    A path to a directory containing mmCIF files (in train
                    mode) or FASTA files (in inference mode).
                alignment_dir:
                    A path to a directory containing only data in the format 
                    output by an AlignmentRunner 
                    (defined in openfold.features.alignment_runner).
                    I.e. a directory of directories named {PDB_ID}_{CHAIN_ID}
49
50
                    or simply {PDB_ID}, each containing .a3m, .sto, and .hhr
                    files.
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
51
52
                template_mmcif_dir:
                    Path to a directory containing template mmCIF files.
53
54
                config:
                    A dataset config object. See openfold.config
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
55
56
                kalign_binary_path:
                    Path to kalign binary.
57
58
59
60
61
                mapping_path:
                    A json file containing a mapping from consecutive numerical
                    ids to sample names (matching the directories in data_dir).
                    Samples not in this mapping are ignored. Can be used to 
                    implement the various training-time filters described in
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
                    the AlphaFold supplement.
                max_template_hits:
                    An upper bound on how many templates are considered. During
                    training, the templates ultimately used are subsampled
                    from this total quantity.
                template_release_dates_cache_path:
                    Path to the output of scripts/generate_mmcif_cache.
                shuffle_top_k_prefiltered:
                    Whether to uniformly shuffle the top k template hits before
                    parsing max_template_hits of them. Can be used to
                    approximate DeepMind's training-time template subsampling
                    scheme much more performantly.
                mode:
                    "train", "val", or "predict"
76
77
78
79
80
81
        """
        super(OpenFoldSingleDataset, self).__init__()
        self.data_dir = data_dir
        self.alignment_dir = alignment_dir
        self.config = config
        self.mode = mode
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
82
        self._output_raw = _output_raw
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99

        valid_modes = ["train", "val", "predict"]
        if(mode not in valid_modes):
            raise ValueError(f'mode must be one of {valid_modes}')

        if(mapping_path is None):
            self.mapping = {
                str(i):os.path.splitext(name)[0] 
                for i, name in enumerate(os.listdir(alignment_dir))
            }
        else:
            with open(mapping_path, 'r') as fp:
                self.mapping = json.load(fp)

        if(template_release_dates_cache_path is None):
            logging.warning(
                "Template release dates cache does not exist. Remember to run "
100
                "scripts/generate_mmcif_cache.py before running OpenFold"
101
102
103
104
105
106
107
108
109
            )

        template_featurizer = templates.TemplateHitFeaturizer(
            mmcif_dir=template_mmcif_dir,
            max_template_date=max_template_date,
            max_hits=max_template_hits,
            kalign_binary_path=kalign_binary_path,
            release_dates_path=template_release_dates_cache_path,
            obsolete_pdbs_path=None,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
110
            _shuffle_top_k_prefiltered=shuffle_top_k_prefiltered,
111
112
113
114
115
116
        )

        self.data_pipeline = data_pipeline.DataPipeline(
            template_featurizer=template_featurizer,
        )

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
117
        if(not self._output_raw):
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
            self.feature_pipeline = feature_pipeline.FeaturePipeline(config) 

    def _parse_mmcif(self, path, file_id, chain_id, alignment_dir):
        with open(path, 'r') as f:
            mmcif_string = f.read()

        mmcif_object = mmcif_parsing.parse(
            file_id=file_id, mmcif_string=mmcif_string
        )

        # Crash if an error is encountered. Any parsing errors should have
        # been dealt with at the alignment stage.
        if(mmcif_object.mmcif_object is None):
            raise list(mmcif_object.errors.values())[0]

        mmcif_object = mmcif_object.mmcif_object

        data = self.data_pipeline.process_mmcif(
            mmcif=mmcif_object,
            alignment_dir=alignment_dir,
            chain_id=chain_id,
        )

        return data
    
    def __getitem__(self, idx):
        name = self.mapping[str(idx)]
        alignment_dir = os.path.join(self.alignment_dir, name)

        if(self.mode == 'train' or self.mode == 'val'):
            spl = name.rsplit('_', 1)
            if(len(spl) == 2):
                file_id, chain_id = spl
            else:
                file_id, = spl
                chain_id = None

Gustaf's avatar
Gustaf committed
155
156
            path = os.path.join(self.data_dir, file_id)
            if(os.path.exists(path + ".cif")):
157
                data = self._parse_mmcif(
Gustaf's avatar
Gustaf committed
158
159
160
161
162
                    path + ".cif", file_id, chain_id, alignment_dir
                )
            elif(os.path.exists(path + ".core")):
                data = self.data_pipeline.process_core(
                    path + ".core", alignment_dir
163
164
165
166
                )
            else:
                # Try to search for a distillation PDB file instead
                data = self.data_pipeline.process_pdb(
Gustaf's avatar
Gustaf committed
167
                    pdb_path=path + ".pdb",
168
169
170
171
172
173
174
175
176
                    alignment_dir=alignment_dir
                )
        else:
            path = os.path.join(name, name + ".fasta")
            data = self.data_pipeline.process_fasta(
                fasta_path=feats,
                alignment_dir=alignment_dir,
            )

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
177
        if(self._output_raw):
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
            return data

        feats = self.feature_pipeline.process_features(
            data, self.mode, "unclamped" 
        )

        return feats

    def __len__(self):
        return len(self.mapping.keys()) 


def looped_sequence(sequence):
    while True:
        for x in sequence:
            yield x


class OpenFoldDataset(torch.utils.data.IterableDataset):
    """
        The Dataset is written to accommodate the requirement that proteins are
        sampled from the distillation set with some probability p
        and from the PDB set with probability (1 - p). Proteins are sampled
        from both sets without replacement, and as soon as either set is
        emptied, it is refilled. The Dataset therefore has an arbitrary length.
        Nevertheless, for compatibility with various PyTorch Lightning
        functionalities, it is possible to specify an epoch length. This length
        has no effect on the output of the Dataset.
    """
    def __init__(self,
        datasets: Sequence[OpenFoldSingleDataset],
        probabilities: Sequence[int],
        epoch_len: int,
    ):
        self.datasets = datasets
        self.samplers = [
            looped_sequence(RandomSampler(d)) for d in datasets
        ]
        self.batch_size = batch_size
        self.epoch_len = epoch_len

        self.distr = torch.distributions.categorical.Categorical(
            probs=torch.tensor(probabilities),
        )

    def __iter__(self):
        return self

    def __next__(self):
        dataset_idx = self.distr.sample()
        sampler = self.samplers[dataset_idx]
        element_idx = next(sampler)
        return self.datasets[dataset_idx][element_idx] 

    def __len__(self):
        return self.epoch_len


class OpenFoldBatchCollator:
    def __init__(self, config, generator, stage="train"):
        self.config = config
        self.generator = generator
        self.stage = stage
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
241
242
        self.feature_pipeline = feature_pipeline.FeaturePipeline(config)
        self._prep_batch_properties_probs()
243
        
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    def _prep_batch_properties_probs(self):
        keyed_probs = []
        stage_cfg = self.config[self.stage]

        max_iters = self.config.common.max_recycling_iters
        if(stage_cfg.supervised):
            clamp_prob = self.config.supervised.clamp_prob
            keyed_probs.append(
                ("use_clamped_fape", [1 - clamp_prob, clamp_prob])
            ) 
            if(self.config.supervised.uniform_recycling):
                recycling_probs = [
                    1. / (max_iters + 1) for _ in range(max_iters + 1)
                ]
                keyed_probs.append(
                    ("no_recycling_iters", recycling_probs)
                )
        else:
            recycling_probs = [
                0. for _ in range(max_iters + 1)
            ]
            recycling_probs[-1] = 1.
            keyed_probs.append(
                ("no_recycling_iters", recycling_probs)
            )
269

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
270
271
272
273
274
275
276
277
278
        keys, probs = zip(*keyed_probs)
        max_len = max([len(p) for p in probs])
        padding = [[0.] * (max_len - len(p)) for p in probs] 
        
        self.prop_keys = keys
        self.prop_probs_tensor = torch.tensor(
            [p + pad for p, pad in zip(probs, padding)],
            dtype=torch.float32,
        )
279

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
280
281
282
283
284
    def _add_batch_properties(self, raw_prots):
        samples = torch.multinomial(
            self.prop_probs_tensor,
            num_samples=1, # 1 per row
            replacement=True,
285
            generator=self.generator
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
286
287
288
289
290
291
        )

        for i, key in enumerate(self.prop_keys):
            sample = samples[i][0]
            for prot in raw_prots:
                prot[key] = np.array(sample, dtype=np.float32)
292

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
293
294
    def __call__(self, raw_prots):
        self._add_batch_properties(raw_prots)
295
296
297
        processed_prots = []
        for prot in raw_prots:
            features = self.feature_pipeline.process_features(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
298
                prot, self.stage
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
            )
            processed_prots.append(features)

        stack_fn = partial(torch.stack, dim=0)
        return dict_multimap(stack_fn, processed_prots) 


class OpenFoldDataModule(pl.LightningDataModule):
    def __init__(self,
        config: mlc.ConfigDict,
        template_mmcif_dir: str,
        max_template_date: str,
        train_data_dir: Optional[str] = None,
        train_alignment_dir: Optional[str] = None,
        distillation_data_dir: Optional[str] = None,
        distillation_alignment_dir: Optional[str] = None,
        val_data_dir: Optional[str] = None,
        val_alignment_dir: Optional[str] = None,
        predict_data_dir: Optional[str] = None,
        predict_alignment_dir: Optional[str] = None,
        kalign_binary_path: str = '/usr/bin/kalign',
        train_mapping_path: Optional[str] = None,
        distillation_mapping_path: Optional[str] = None,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
322
323
        template_release_dates_cache_path: Optional[str] = None,
        batch_seed: Optional[int] = None,
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
        **kwargs
    ):
        super(OpenFoldDataModule, self).__init__()

        self.config = config
        self.template_mmcif_dir = template_mmcif_dir
        self.max_template_date = max_template_date
        self.train_data_dir = train_data_dir
        self.train_alignment_dir = train_alignment_dir
        self.distillation_data_dir = distillation_data_dir
        self.distillation_alignment_dir = distillation_alignment_dir
        self.val_data_dir = val_data_dir
        self.val_alignment_dir = val_alignment_dir
        self.predict_data_dir = predict_data_dir
        self.predict_alignment_dir = predict_alignment_dir
        self.kalign_binary_path = kalign_binary_path
        self.train_mapping_path = train_mapping_path
        self.distillation_mapping_path = distillation_mapping_path
        self.template_release_dates_cache_path = (
            template_release_dates_cache_path
        )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
345
        self.batch_seed = batch_seed
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368

        if(self.train_data_dir is None and self.predict_data_dir is None):
            raise ValueError(
                'At least one of train_data_dir or predict_data_dir must be '
                'specified'
            )

        self.training_mode = self.train_data_dir is not None

        if(self.training_mode and self.train_alignment_dir is None):
            raise ValueError(
                'In training mode, train_alignment_dir must be specified'
            )
        elif(not self.training_mode and self.predict_alingment_dir is None):
            raise ValueError(
                'In inference mode, predict_alignment_dir must be specified'
            )      
        elif(val_data_dir is not None and val_alignment_dir is None):
            raise ValueError(
                'If val_data_dir is specified, val_alignment_dir must '
                'be specified as well'
        )

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
369
370
371
372
    def setup(self, stage: Optional[str] = None):
        if(stage is None):
            stage = "train"

373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
        # Most of the arguments are the same for the three datasets 
        dataset_gen = partial(OpenFoldSingleDataset,
            template_mmcif_dir=self.template_mmcif_dir,
            max_template_date=self.max_template_date,
            config=self.config,
            kalign_binary_path=self.kalign_binary_path,
            template_release_dates_cache_path=
                self.template_release_dates_cache_path,
        )

        if(self.training_mode):        
            self.train_dataset = dataset_gen(
                data_dir=self.train_data_dir,
                alignment_dir=self.train_alignment_dir,
                mapping_path=self.train_mapping_path,
                max_template_hits=self.config.train.max_template_hits,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
389
390
                shuffle_top_k_prefiltered=
                    self.config.train.shuffle_top_k_prefiltered,
391
                mode="train",
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
392
                _output_raw=True,
393
394
395
396
397
398
399
400
401
            )

            if(self.distillation_data_dir is not None):
                distillation_dataset = dataset_gen(
                    data_dir=self.distillation_data_dir,
                    alignment_dir=self.distillation_alignment_dir,
                    mapping_path=self.distillation_mapping_path,
                    max_template_hits=self.train.max_template_hits,
                    mode="train",
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
402
                    _output_raw=True,
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
                )

                d_prob = self.config.train.distillation_prob
                self.train_dataset = OpenFoldDataset(
                    datasets=[self.train_dataset, distillation_dataset],
                    probabilities=[1 - d_prob, d_prob],
                    epoch_len=(
                        self.train_dataset.len() + distillation_dataset.len()
                    ),
                )
    
            if(self.val_data_dir is not None):
                self.val_dataset = dataset_gen(
                    data_dir=self.val_data_dir,
                    alignment_dir=self.val_alignment_dir,
                    mapping_path=None,
                    max_template_hits=self.config.eval.max_template_hits,
                    mode="eval",
                )
422
423
            else:
                self.val_dataset = None
424
425
426
427
428
429
430
431
432
433
434
435
        else:           
            self.predict_dataset = dataset_gen(
                data_dir=self.predict_data_dir,
                alignment_dir=self.predict_alignment_dir,
                mapping_path=None,
                max_template_hits=self.config.predict.max_template_hits,
                mode="predict",
            )

    def _gen_batch_collator(self, stage):
        """ We want each process to use the same batch collation seed """
        generator = torch.Generator()
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
436
437
        if(self.batch_seed is not None):
            generator = generator.manual_seed(self.batch_seed)
438
439
440
441
442
443
444
445
446
447
448
449
450
451
        collate_fn = OpenFoldBatchCollator(
            self.config, generator, stage
        )
        return collate_fn

    def train_dataloader(self):
        return torch.utils.data.DataLoader(
            self.train_dataset,
            batch_size=self.config.data_module.data_loaders.batch_size,
            num_workers=self.config.data_module.data_loaders.num_workers,
            collate_fn=self._gen_batch_collator("train"),
        )

    def val_dataloader(self):
452
453
454
455
456
457
458
459
460
        if(self.val_dataset is not None):
            return torch.utils.data.DataLoader(
                self.val_dataset,
                batch_size=self.config.data_module.data_loaders.batch_size,
                num_workers=self.config.data_module.data_loaders.num_workers,
                collate_fn=self._gen_batch_collator("eval")
            )

        return None
461
462
463
464
465
466

    def predict_dataloader(self):
        return torch.utils.data.DataLoader(
            self.predict_dataset,
            batch_size=self.config.data_module.data_loaders.batch_size,
            num_workers=self.config.data_module.data_loaders.num_workers,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
467
            collate_fn=self._gen_batch_collator("predict")
468
        )
469
470
471
472
473


class DummyDataset(torch.utils.data.Dataset):
    def __init__(self, batch_path):
        with open(batch_path, "rb") as f:
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
474
            self.batch = pickle.load(f)
475
476
477
478
479
480
481
482
483

    def __getitem__(self, idx):
        return copy.deepcopy(self.batch)

    def __len__(self):
        return 1000


class DummyDataLoader(pl.LightningDataModule):
484
    def __init__(self, batch_path):
485
        super().__init__()
486
        self.dataset = DummyDataset(batch_path)
487
488
489

    def train_dataloader(self):
        return torch.utils.data.DataLoader(self.dataset)