File size: 24,900 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
241
242
243
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
# 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)