gReLU 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. gReLU-1.0.1.dist-info/LICENSE.txt +21 -0
  2. gReLU-1.0.1.dist-info/METADATA +106 -0
  3. gReLU-1.0.1.dist-info/RECORD +58 -0
  4. gReLU-1.0.1.dist-info/WHEEL +5 -0
  5. gReLU-1.0.1.dist-info/top_level.txt +1 -0
  6. grelu/__init__.py +16 -0
  7. grelu/data/__init__.py +0 -0
  8. grelu/data/augment.py +227 -0
  9. grelu/data/dataset.py +1013 -0
  10. grelu/data/preprocess.py +710 -0
  11. grelu/data/utils.py +63 -0
  12. grelu/design.py +287 -0
  13. grelu/interpret/__init__.py +0 -0
  14. grelu/interpret/motifs.py +319 -0
  15. grelu/interpret/score.py +390 -0
  16. grelu/io/__init__.py +136 -0
  17. grelu/io/bed.py +97 -0
  18. grelu/io/bigwig.py +98 -0
  19. grelu/io/fasta.py +48 -0
  20. grelu/io/genome.py +93 -0
  21. grelu/io/meme.py +115 -0
  22. grelu/lightning/__init__.py +1097 -0
  23. grelu/lightning/losses.py +77 -0
  24. grelu/lightning/metrics.py +146 -0
  25. grelu/model/__init__.py +0 -0
  26. grelu/model/blocks.py +761 -0
  27. grelu/model/heads.py +135 -0
  28. grelu/model/layers.py +399 -0
  29. grelu/model/models.py +692 -0
  30. grelu/model/position.py +80 -0
  31. grelu/model/trunks/__init__.py +338 -0
  32. grelu/model/trunks/borzoi.py +166 -0
  33. grelu/model/trunks/enformer.py +277 -0
  34. grelu/model/trunks/explainn.py +119 -0
  35. grelu/resources/__init__.py +138 -0
  36. grelu/resources/__pycache__/__init__.cpython-310.pyc +0 -0
  37. grelu/resources/blacklists/encode/hg19-blacklist.v2.bed +834 -0
  38. grelu/resources/blacklists/encode/hg38-blacklist.v2.bed +636 -0
  39. grelu/resources/blacklists/encode/mm10-blacklist.v2.bed +3435 -0
  40. grelu/resources/blacklists/mito_combined/hg19.full.blacklist.bed +902 -0
  41. grelu/resources/blacklists/mito_combined/hg19_mm10_c.full.blacklist.bed +1425 -0
  42. grelu/resources/blacklists/mito_combined/hg38.full.blacklist.bed +820 -0
  43. grelu/resources/blacklists/mito_combined/mm10.full.blacklist.bed +523 -0
  44. grelu/resources/blacklists/mito_combined/mm9.full.blacklist.bed +3415 -0
  45. grelu/resources/meme/JASPAR2022_CORE_non-redundant_pfms_meme.txt +32224 -0
  46. grelu/resources/meme/jvierstra_consensus_pwms.meme +10405 -0
  47. grelu/sequence/__init__.py +0 -0
  48. grelu/sequence/format.py +428 -0
  49. grelu/sequence/metrics.py +105 -0
  50. grelu/sequence/mutate.py +252 -0
  51. grelu/sequence/utils.py +452 -0
  52. grelu/transforms/__init__.py +0 -0
  53. grelu/transforms/label_transforms.py +50 -0
  54. grelu/transforms/prediction_transforms.py +248 -0
  55. grelu/transforms/seq_transforms.py +132 -0
  56. grelu/utils.py +153 -0
  57. grelu/variant.py +389 -0
  58. grelu/visualize.py +740 -0
@@ -0,0 +1,1097 @@
1
+ """
2
+ The LightningModel class.
3
+ """
4
+
5
+ import warnings
6
+ from collections import defaultdict
7
+ from datetime import datetime
8
+ from typing import Callable, List, Optional, Tuple, Union
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ import pytorch_lightning as pl
13
+ import torch
14
+ from einops import rearrange
15
+ from pytorch_lightning.callbacks import ModelCheckpoint
16
+ from pytorch_lightning.loggers import CSVLogger, WandbLogger
17
+ from torch import Tensor, nn, optim
18
+ from torch.utils.data import DataLoader
19
+ from torchmetrics import AUROC, Accuracy, AveragePrecision, MetricCollection
20
+
21
+ import grelu.model.models
22
+ from grelu.data.dataset import (
23
+ ISMDataset,
24
+ LabeledSeqDataset,
25
+ MotifScanDataset,
26
+ PatternMarginalizeDataset,
27
+ VariantDataset,
28
+ VariantMarginalizeDataset,
29
+ )
30
+ from grelu.lightning.losses import PoissonMultinomialLoss
31
+ from grelu.lightning.metrics import MSE, BestF1, PearsonCorrCoef
32
+ from grelu.model.heads import ConvHead
33
+ from grelu.sequence.format import strings_to_one_hot
34
+ from grelu.utils import get_aggfunc, get_compare_func, make_list
35
+
36
+ default_train_params = {
37
+ "task": "binary", # binary, multiclass, or regression
38
+ "lr": 1e-4,
39
+ "optimizer": "adam",
40
+ "batch_size": 512,
41
+ "num_workers": 1,
42
+ "devices": "cpu",
43
+ "logger": None,
44
+ "save_dir": ".",
45
+ "max_epochs": 1,
46
+ "checkpoint": True,
47
+ "loss": "bce",
48
+ "clip": 0,
49
+ "pos_weight": None,
50
+ "class_weights": None,
51
+ "total_weight": None,
52
+ }
53
+
54
+
55
+ class LightningModel(pl.LightningModule):
56
+ """
57
+ Wrapper for predictive sequence models
58
+
59
+ Args:
60
+ model_params: Dictionary of parameters specifying model architecture
61
+ train_params: Dictionary specifying training parameters
62
+ data_params: Dictionary specifying parameters of the training data.
63
+ This is empty by default and will be filled at the time of
64
+ training.
65
+ """
66
+
67
+ def __init__(
68
+ self, model_params: dict, train_params: dict = {}, data_params: dict = {}
69
+ ) -> None:
70
+ super().__init__()
71
+
72
+ self.save_hyperparameters(ignore=["model"])
73
+
74
+ # Add default training parameters
75
+ for key in default_train_params.keys():
76
+ if key not in train_params:
77
+ train_params[key] = default_train_params[key]
78
+ if key in ["loss", "task", "optimizer"]:
79
+ train_params[key] = train_params[key].lower()
80
+
81
+ # Save params
82
+ self.model_params = model_params
83
+ self.train_params = train_params
84
+ self.data_params = data_params
85
+
86
+ # Build model
87
+ self.build_model()
88
+
89
+ # Set up loss function
90
+ self.initialize_loss()
91
+
92
+ # Set up activation function
93
+ self.initialize_activation()
94
+
95
+ # Inititalize metrics
96
+ self.initialize_metrics()
97
+
98
+ # Initialize prediction transform
99
+ self.reset_transform()
100
+
101
+ def build_model(self) -> None:
102
+ """
103
+ Build a model from parameter dictionary
104
+ """
105
+ model_type = self.model_params["model_type"]
106
+ if hasattr(grelu.model.models, model_type):
107
+ self.model = getattr(grelu.model.models, model_type)
108
+ else:
109
+ raise Exception("Unknown model type")
110
+
111
+ self.model = self.model(
112
+ **{k: v for k, v in self.model_params.items() if k not in ["model_type"]}
113
+ )
114
+
115
+ def initialize_loss(self) -> None:
116
+ """
117
+ Create the specified loss function.
118
+ """
119
+ # Losses always accept logits i.e. pre-activation values
120
+ # Regression loss: Poisson or MSE
121
+ if self.train_params["task"] == "regression":
122
+ if self.train_params["loss"] == "poisson":
123
+ self.loss = nn.PoissonNLLLoss(log_input=True, full=True)
124
+ elif self.train_params["loss"] == "poisson_multinomial":
125
+ self.loss = PoissonMultinomialLoss(
126
+ total_weight=self.train_params["total_weight"], log_input=True
127
+ )
128
+ elif self.train_params["loss"] == "mse":
129
+ self.loss = nn.MSELoss()
130
+ else:
131
+ raise Exception("Regression losses: poisson, poisson_multinomial, MSE")
132
+
133
+ # Binary: Binary cross-entropy loss
134
+ elif self.train_params["task"] == "binary":
135
+ if self.train_params["loss"] == "bce":
136
+ pos_weight = self.train_params["pos_weight"]
137
+ if pos_weight is not None:
138
+ pos_weight = Tensor(pos_weight).unsqueeze(1)
139
+ self.loss = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
140
+ else:
141
+ raise Exception("Binary losses: bce")
142
+
143
+ # Multiclass: Cross-entropy loss
144
+ elif self.train_params["task"] == "multiclass":
145
+ weight = self.train_params["class_weights"]
146
+ if weight is not None:
147
+ weight = Tensor(weight)
148
+ self.loss = nn.CrossEntropyLoss(weight=weight)
149
+ else:
150
+ raise Exception("Task is not allowed")
151
+
152
+ def initialize_activation(self) -> None:
153
+ """
154
+ Add a task-specific activation function to the model.
155
+ """
156
+ # Regression
157
+ if self.train_params["task"] == "regression":
158
+ if self.train_params["loss"] == "poisson":
159
+ self.activation = torch.exp
160
+ elif self.train_params["loss"] == "mse":
161
+ self.activation = nn.Identity()
162
+ else:
163
+ raise Exception("Regression losses: poisson, MSE")
164
+
165
+ # Binary
166
+ elif self.train_params["task"] == "binary":
167
+ self.activation = torch.sigmoid
168
+
169
+ # Multiclass
170
+ elif self.train_params["task"] == "multiclass":
171
+ self.activation = nn.Softmax(dim=1)
172
+ else:
173
+ raise Exception("Defined tasks: regression, binary and multiclass")
174
+
175
+ def initialize_metrics(self):
176
+ """
177
+ Initialize the appropriate metrics for the given task.
178
+ """
179
+ # Regression:
180
+ if self.train_params["task"] == "regression":
181
+ metrics = MetricCollection(
182
+ {
183
+ "mse": MSE(num_outputs=self.model.head.n_tasks, average=False),
184
+ "pearson": PearsonCorrCoef(
185
+ num_outputs=self.model.head.n_tasks, average=False
186
+ ),
187
+ }
188
+ )
189
+
190
+ # Binary classification
191
+ elif self.train_params["task"] == "binary":
192
+ if self.model.head.n_tasks == 1:
193
+ metrics = MetricCollection(
194
+ {
195
+ "accuracy": Accuracy("binary", average=None),
196
+ "avgprec": AveragePrecision("binary", average=None),
197
+ "auroc": AUROC("binary", average=None),
198
+ "best_f1": BestF1(
199
+ num_labels=self.model.head.n_tasks, average=False
200
+ ),
201
+ }
202
+ )
203
+ else:
204
+ metrics = MetricCollection(
205
+ {
206
+ "accuracy": Accuracy(
207
+ task="multilabel",
208
+ num_labels=self.model.head.n_tasks,
209
+ average=None,
210
+ ),
211
+ "avgprec": AveragePrecision(
212
+ "multilabel",
213
+ num_labels=self.model.head.n_tasks,
214
+ average=None,
215
+ ),
216
+ "auroc": AUROC(
217
+ "multilabel",
218
+ num_labels=self.model.head.n_tasks,
219
+ average=None,
220
+ ),
221
+ "best_f1": BestF1(
222
+ num_labels=self.model.head.n_tasks, average=False
223
+ ),
224
+ }
225
+ )
226
+
227
+ # Multiclass
228
+ elif self.train_params["task"] == "multiclass":
229
+ metrics = MetricCollection(
230
+ {
231
+ "accuracy": Accuracy(
232
+ task="multiclass",
233
+ num_classes=self.model.head.n_tasks,
234
+ average=None,
235
+ ),
236
+ "avgprec": AveragePrecision(
237
+ "multiclass", num_classes=self.model.head.n_tasks, average=None
238
+ ),
239
+ "auroc": AUROC(
240
+ "multiclass", num_classes=self.model.head.n_tasks, average=None
241
+ ),
242
+ }
243
+ )
244
+ else:
245
+ raise Exception("Defined tasks: regression, binary and multiclass")
246
+
247
+ self.val_metrics = metrics.clone(prefix="val_")
248
+ self.test_metrics = metrics.clone(prefix="test_")
249
+ self.val_losses = []
250
+ self.test_losses = []
251
+
252
+ def update_metrics(self, metrics: dict, y_hat: Tensor, y: Tensor) -> None:
253
+ """
254
+ Update metrics after each pass
255
+ """
256
+ if self.train_params["task"] == "binary":
257
+ metrics.update(y_hat, y.type(torch.long))
258
+ elif self.train_params["task"] == "multiclass":
259
+ metrics.update(y_hat, y.type(torch.long).argmax(axis=1))
260
+ else:
261
+ metrics.update(y_hat, y)
262
+
263
+ def format_input(self, x: Union[Tuple[Tensor, Tensor], Tensor]) -> Tensor:
264
+ """
265
+ Extract the one-hot encoded sequence from the input
266
+ """
267
+ # if x is a tuple of sequence, label, return the sequence
268
+ if isinstance(x, Tensor):
269
+ if x.ndim == 3:
270
+ return x
271
+ else:
272
+ return x.unsqueeze(0)
273
+ elif isinstance(x, Tuple):
274
+ return x[0]
275
+ else:
276
+ raise Exception("Cannot perform forward pass on the given input format.")
277
+
278
+ def forward(
279
+ self,
280
+ x: Union[Tuple[Tensor, Tensor], Tensor, str, List[str]],
281
+ logits: bool = False,
282
+ ) -> Tensor:
283
+ """
284
+ Forward pass
285
+ """
286
+ # Format the input as a one-hot encoded tensor
287
+ x = self.format_input(x)
288
+
289
+ # Run the model
290
+ x = self.model(x)
291
+
292
+ # forward() produces prediction (e.g. post-activation)
293
+ # unless logits=True, which is used in loss functions
294
+ if not logits:
295
+ x = self.activation(x)
296
+
297
+ # Apply transform
298
+ x = self.transform(x)
299
+ return x
300
+
301
+ def training_step(self, batch: Tensor, batch_idx: int) -> Tensor:
302
+ x, y = batch
303
+ logits = self.forward(x, logits=True)
304
+ loss = self.loss(logits, y)
305
+ self.log(
306
+ "train_loss",
307
+ loss,
308
+ logger=self.train_params["logger"] is not None,
309
+ on_step=True,
310
+ on_epoch=True,
311
+ prog_bar=True,
312
+ )
313
+ return loss
314
+
315
+ def validation_step(self, batch: Tensor, batch_idx: int) -> Tensor:
316
+ x, y = batch
317
+ logits = self.forward(x, logits=True)
318
+ loss = self.loss(logits, y)
319
+ y_hat = self.activation(logits)
320
+ self.log(
321
+ "val_loss",
322
+ loss,
323
+ logger=self.train_params["logger"] is not None,
324
+ on_step=False,
325
+ on_epoch=True,
326
+ )
327
+ self.update_metrics(self.val_metrics, y_hat, y)
328
+ self.val_losses.append(loss)
329
+ return loss
330
+
331
+ def on_validation_epoch_end(self):
332
+ """
333
+ Calculate metrics for entire validation set
334
+ """
335
+ # Compute metrics
336
+ val_metrics = self.val_metrics.compute()
337
+ mean_val_metrics = {k: v.mean() for k, v in val_metrics.items()}
338
+ # Compute loss
339
+ losses = torch.stack(self.val_losses)
340
+ mean_losses = torch.mean(losses)
341
+ # Log or print
342
+ if self.train_params["logger"] is None:
343
+ print(mean_val_metrics)
344
+ print(f"validation loss: {mean_losses}")
345
+ else:
346
+ self.log_dict(mean_val_metrics)
347
+ self.log("val_loss", mean_losses)
348
+
349
+ def test_step(self, batch: Tensor, batch_idx: int) -> Tensor:
350
+ """
351
+ Calculate metrics after a single test step
352
+ """
353
+ x, y = batch
354
+ logits = self.forward(x, logits=True)
355
+ loss = self.loss(logits, y)
356
+ y_hat = self.activation(logits)
357
+ self.log("test_loss", loss, logger=True, on_step=False, on_epoch=True)
358
+ self.update_metrics(self.test_metrics, y_hat, y)
359
+ self.test_losses.append(loss)
360
+ return loss
361
+
362
+ def on_test_epoch_end(self) -> None:
363
+ """
364
+ Calculate metrics for entire test set
365
+ """
366
+ self.computed_test_metrics = self.test_metrics.compute()
367
+ self.log_dict({k: v.mean() for k, v in self.computed_test_metrics.items()})
368
+ losses = torch.stack(self.test_losses)
369
+ self.log("test_loss", torch.mean(losses))
370
+
371
+ def configure_optimizers(self) -> None:
372
+ """
373
+ Configure oprimizer for training
374
+ """
375
+ if self.train_params["optimizer"] == "adam":
376
+ return optim.Adam(self.parameters(), lr=self.train_params["lr"])
377
+ elif self.train_params["optimizer"] == "sgd":
378
+ return optim.SGD(
379
+ self.parameters(), lr=self.train_params["lr"], momentum=0.9
380
+ )
381
+ else:
382
+ raise Exception("Unknown optimizer")
383
+
384
+ def count_params(self) -> int:
385
+ """
386
+ Number of gradient enabled parameters in the model
387
+ """
388
+ return sum(p.numel() for p in self.model.parameters() if p.requires_grad)
389
+
390
+ def parse_devices(
391
+ self, devices: Union[str, int, List[int]]
392
+ ) -> Tuple[str, Union[str, List[int]]]:
393
+ """
394
+ Parses the devices argument and returns a tuple of accelerator and devices.
395
+
396
+ Args:
397
+ devices: Either "cpu" or an integer or list of integers representing the indices
398
+ of the GPUs for training.
399
+
400
+ Returns:
401
+ A tuple of accelerator and devices.
402
+ """
403
+ if devices == "cpu":
404
+ accelerator = "cpu"
405
+ devices = "auto"
406
+ else:
407
+ accelerator = "gpu"
408
+ devices = make_list(devices)
409
+ return accelerator, devices
410
+
411
+ def parse_logger(self) -> str:
412
+ """
413
+ Parses the name of the logger supplied in train_params.
414
+ """
415
+ if "name" not in self.train_params:
416
+ self.train_params["name"] = datetime.now().strftime("%Y_%d_%m_%H_%M")
417
+ if self.train_params["logger"] == "wandb":
418
+ logger = WandbLogger(
419
+ name=self.train_params["name"],
420
+ log_model=True,
421
+ save_dir=self.train_params["save_dir"],
422
+ )
423
+ elif self.train_params["logger"] == "csv":
424
+ logger = CSVLogger(
425
+ name=self.train_params["name"], save_dir=self.train_params["save_dir"]
426
+ )
427
+ elif self.train_params["logger"] is None:
428
+ logger = None
429
+ else:
430
+ raise NotImplementedError
431
+ return logger
432
+
433
+ def add_transform(self, prediction_transform: Callable) -> None:
434
+ """
435
+ Add a prediction transform
436
+ """
437
+ if prediction_transform is not None:
438
+ self.transform = prediction_transform
439
+
440
+ def reset_transform(self) -> None:
441
+ """
442
+ Remove a prediction transform
443
+ """
444
+ self.transform = nn.Identity()
445
+
446
+ def make_train_loader(
447
+ self,
448
+ dataset: Callable,
449
+ batch_size: Optional[int] = None,
450
+ num_workers: Optional[int] = None,
451
+ ) -> Callable:
452
+ """
453
+ Make dataloader for training
454
+ """
455
+ assert isinstance(dataset, LabeledSeqDataset)
456
+ return DataLoader(
457
+ dataset,
458
+ batch_size=batch_size or self.train_params["batch_size"],
459
+ shuffle=True,
460
+ num_workers=num_workers or self.train_params["num_workers"],
461
+ )
462
+
463
+ def make_test_loader(
464
+ self,
465
+ dataset: Callable,
466
+ batch_size: Optional[int] = None,
467
+ num_workers: Optional[int] = None,
468
+ ) -> Callable:
469
+ """
470
+ Make dataloader for validation and testing
471
+ """
472
+ assert isinstance(dataset, LabeledSeqDataset)
473
+ return DataLoader(
474
+ dataset,
475
+ batch_size=batch_size or self.train_params["batch_size"],
476
+ shuffle=False,
477
+ num_workers=num_workers or self.train_params["num_workers"],
478
+ )
479
+
480
+ def make_predict_loader(
481
+ self,
482
+ dataset: Callable,
483
+ batch_size: Optional[int] = None,
484
+ num_workers: Optional[int] = None,
485
+ ) -> Callable:
486
+ """
487
+ Make dataloader for prediction
488
+ """
489
+ if isinstance(dataset, LabeledSeqDataset):
490
+ dataset.predict = True
491
+ return DataLoader(
492
+ dataset,
493
+ batch_size=batch_size or self.train_params["batch_size"],
494
+ shuffle=False,
495
+ num_workers=num_workers or self.train_params["num_workers"],
496
+ )
497
+
498
+ def train_on_dataset(
499
+ self,
500
+ train_dataset: Callable,
501
+ val_dataset: Callable,
502
+ checkpoint_path: Optional[str] = None,
503
+ ):
504
+ """
505
+ Train model and optionally log metrics to wandb.
506
+
507
+ Args:
508
+ train_dataset (Dataset): Dataset object that yields training examples
509
+ val_dataset (Dataset) : Dataset object that yields training examples
510
+ checkpoint_path (str): Path to model checkpoint from which to resume training.
511
+ The optimizer will be set to its checkpointed state.
512
+
513
+ Returns:
514
+ PyTorch Lightning Trainer
515
+ """
516
+ torch.set_float32_matmul_precision("medium")
517
+
518
+ # Checkpointing
519
+ if self.train_params["checkpoint"] is True:
520
+ checkpoint_callbacks = [
521
+ ModelCheckpoint(monitor="val_loss", mode="min", save_last=True)
522
+ ]
523
+ elif isinstance(self.train_params["checkpoint"], dict):
524
+ checkpoint_callbacks = [ModelCheckpoint(**self.train_params["checkpoint"])]
525
+ else:
526
+ raise Exception("Checkpoint type must be a bool or dict")
527
+
528
+ # Get device
529
+ accelerator, devices = self.parse_devices(self.train_params["devices"])
530
+
531
+ # Set up logging
532
+ logger = self.parse_logger()
533
+
534
+ # Set up trainer
535
+ trainer = pl.Trainer(
536
+ max_epochs=self.train_params["max_epochs"],
537
+ accelerator=accelerator,
538
+ devices=devices,
539
+ logger=logger,
540
+ callbacks=checkpoint_callbacks,
541
+ default_root_dir=self.train_params["save_dir"],
542
+ gradient_clip_val=self.train_params["clip"],
543
+ )
544
+
545
+ # Make dataloaders
546
+ train_dataloader = self.make_train_loader(train_dataset)
547
+ val_dataloader = self.make_test_loader(val_dataset)
548
+
549
+ if checkpoint_path is None:
550
+ # First validation pass
551
+ trainer.validate(model=self, dataloaders=val_dataloader)
552
+
553
+ # Add data parameters
554
+ self.data_params["tasks"] = train_dataset.tasks.reset_index(
555
+ names="name"
556
+ ).to_dict(orient="list")
557
+
558
+ for attr, value in self._get_dataset_attrs(train_dataset):
559
+ self.data_params["train_" + attr] = value
560
+
561
+ for attr, value in self._get_dataset_attrs(val_dataset):
562
+ self.data_params["val_" + attr] = value
563
+
564
+ # Training
565
+ trainer.fit(
566
+ model=self,
567
+ train_dataloaders=train_dataloader,
568
+ val_dataloaders=val_dataloader,
569
+ ckpt_path=checkpoint_path,
570
+ )
571
+ return trainer
572
+
573
+ def _get_dataset_attrs(self, dataset: Callable) -> None:
574
+ """
575
+ Read data parameters from a dataset object
576
+ """
577
+ for attr in dir(dataset):
578
+ if not attr.startswith("_") and not attr.isupper():
579
+ value = getattr(dataset, attr)
580
+ if (
581
+ (attr == "chroms")
582
+ or (isinstance(value, str))
583
+ or (isinstance(value, int))
584
+ or (isinstance(value, float))
585
+ or (value is None)
586
+ ):
587
+ yield attr, value
588
+
589
+ def change_head(
590
+ self,
591
+ n_tasks: int,
592
+ final_pool_func: str,
593
+ ) -> None:
594
+ """
595
+ Build a new head with the desired number of tasks
596
+ """
597
+ in_channels = self.model.head.in_channels
598
+ self.model.head = ConvHead(
599
+ n_tasks=n_tasks,
600
+ in_channels=in_channels,
601
+ act_func=None,
602
+ pool_func=final_pool_func,
603
+ norm=False,
604
+ )
605
+ self.model_params["n_tasks"] = n_tasks
606
+ self.model_params["final_pool_func"] = final_pool_func
607
+
608
+ self.initialize_metrics()
609
+
610
+ def tune_on_dataset(
611
+ self,
612
+ train_dataset: Callable,
613
+ val_dataset: Callable,
614
+ final_act_func: Optional[str] = None,
615
+ final_pool_func: Optional[str] = None,
616
+ freeze_embedding: bool = False,
617
+ ):
618
+ """
619
+ Fine-tune a pretrained model on a new dataset.
620
+
621
+ Args:
622
+ train_dataset: Dataset object that yields training examples
623
+ val_dataset: Dataset object that yields training examples
624
+ final_act_func: Name of the final activation layer
625
+ final_pool_func: Name of the final pooling layer
626
+ freeze_embedding: If True, all the embedding layers of the pretrained
627
+ model will be frozen and only the head will be trained.
628
+
629
+ Returns:
630
+ PyTorch Lightning Trainer
631
+ """
632
+ # Move train data parameters
633
+ self.base_data_params = self.data_params.copy()
634
+ self.data_params = {}
635
+
636
+ # Make new model head
637
+ self.change_head(
638
+ n_tasks=train_dataset.n_tasks,
639
+ final_pool_func=final_pool_func,
640
+ )
641
+
642
+ # Freeze the model embedding layers if needed
643
+ if freeze_embedding:
644
+ for param in self.model.embedding.parameters():
645
+ param.requires_grad = False
646
+
647
+ # Train new model
648
+ return self.train_on_dataset(train_dataset, val_dataset)
649
+
650
+ def on_save_checkpoint(self, checkpoint: dict) -> None:
651
+ checkpoint["hyper_parameters"]["data_params"] = self.data_params
652
+
653
+ def predict_on_seqs(
654
+ self,
655
+ x: Union[str, List[str]],
656
+ device: Union[str, int] = "cpu",
657
+ ) -> np.ndarray:
658
+ """
659
+ A simple function to return model predictions directly
660
+ on a batch of a single batch of sequences in string
661
+ format.
662
+
663
+ Args:
664
+ x: DNA sequences as a string or list of strings.
665
+ device: Index of the device to use
666
+
667
+ Returns:
668
+ A numpy array of predictions.
669
+ """
670
+ x = strings_to_one_hot(x, add_batch_axis=True)
671
+ x = x.to(device)
672
+ self.model = self.model.eval().to(device)
673
+ preds = self.forward(x).detach().cpu().numpy()
674
+ self.model = self.model.cpu()
675
+ return preds
676
+
677
+ def predict_on_dataset(
678
+ self,
679
+ dataset: Callable,
680
+ devices: Union[int, str, List[int]] = "cpu",
681
+ num_workers: int = 1,
682
+ batch_size: int = 256,
683
+ augment_aggfunc: Union[str, Callable] = "mean",
684
+ compare_func: Optional[Union[str, Callable]] = None,
685
+ return_df: bool = False,
686
+ ):
687
+ """
688
+ Predict for a dataset of sequences or variants
689
+
690
+ Args:
691
+ dataset: Dataset object that yields one-hot encoded sequences
692
+ devices: Device IDs to use
693
+ num_workers: Number of workers for data loader
694
+ batch_size: Batch size for data loader
695
+ augment_aggfunc: Return the average prediction across all augmented
696
+ versions of a sequence
697
+ compare_func: Return the alt/ref difference for variants
698
+ return_df: Return the predictions as a Pandas dataframe
699
+
700
+ Returns:
701
+ Model predictions as a numpy array or dataframe
702
+ """
703
+ torch.set_float32_matmul_precision("medium")
704
+ dataloader = self.make_predict_loader(
705
+ dataset,
706
+ num_workers=num_workers,
707
+ batch_size=batch_size,
708
+ )
709
+ accelerator, devices = self.parse_devices(devices)
710
+ trainer = pl.Trainer(accelerator=accelerator, devices=devices, logger=None)
711
+
712
+ # Predict
713
+ preds = torch.concat(trainer.predict(self, dataloader))
714
+
715
+ # Reshape predictions
716
+ preds = rearrange(
717
+ preds,
718
+ "(b n a) t l -> b n a t l",
719
+ n=dataset.n_augmented,
720
+ a=dataset.n_alleles,
721
+ )
722
+
723
+ # Convert predictions to numpy array
724
+ preds = preds.detach().cpu().numpy()
725
+
726
+ # ISM or Motif Scanning
727
+ if (isinstance(dataset, ISMDataset)) or (isinstance(dataset, MotifScanDataset)):
728
+ return preds
729
+
730
+ else:
731
+ # Flip predictions for reverse complemented sequences
732
+ if (dataset.rc) and (preds.shape[-1] > 1):
733
+ preds[:, dataset.n_augmented // 2 :, :, :, :] = np.flip(
734
+ preds[:, dataset.n_augmented // 2 :, :, :, :], axis=-1
735
+ )
736
+
737
+ # Compare the predictions for two alleles
738
+ if (
739
+ (isinstance(dataset, VariantDataset))
740
+ or (isinstance(dataset, VariantMarginalizeDataset))
741
+ or (isinstance(dataset, PatternMarginalizeDataset))
742
+ ):
743
+ if compare_func is not None:
744
+ assert preds.shape[2] == 2
745
+ preds = get_compare_func(compare_func)(
746
+ preds[:, :, 1, :, :], preds[:, :, 0, :, :]
747
+ ) # BNTL
748
+
749
+ # Combine predictions for augmented sequences
750
+ if augment_aggfunc is not None:
751
+ preds = get_aggfunc(augment_aggfunc)(preds, axis=1) # B T L
752
+
753
+ return preds
754
+
755
+ else:
756
+ # Regular sequences
757
+ preds = preds.squeeze(2) # B N T L
758
+ if augment_aggfunc is not None:
759
+ preds = get_aggfunc(augment_aggfunc)(preds, axis=1) # B T L
760
+ elif preds.shape[1] == 1:
761
+ preds = preds.squeeze(1)
762
+
763
+ # Make dataframe
764
+ if return_df:
765
+ if (preds.ndim == 3) and (preds.shape[-1] == 1):
766
+ preds = pd.DataFrame(
767
+ preds.squeeze(-1), columns=self.data_params["tasks"]["name"]
768
+ )
769
+ else:
770
+ warnings.warn(
771
+ "Cannot produce dataframe output."
772
+ + "Either output length > 1 or augmented sequences are not aggregated."
773
+ )
774
+
775
+ return preds
776
+
777
+ def test_on_dataset(
778
+ self,
779
+ dataset: Callable,
780
+ devices: Union[str, int, List[int]] = "cpu",
781
+ num_workers: int = 1,
782
+ batch_size: int = 256,
783
+ ):
784
+ """
785
+ Run test loop for a dataset
786
+
787
+ Args:
788
+ dataset: Dataset object that yields one-hot encoded sequences
789
+ devices: Device IDs to use for inference
790
+ num_workers: Number of workers for data loader
791
+ batch_size: Batch size for data loader
792
+
793
+ Returns:
794
+ Dataframe containing all calculated metrics on the test set.
795
+ """
796
+ torch.set_float32_matmul_precision("medium")
797
+ dataloader = self.make_test_loader(
798
+ dataset,
799
+ num_workers=num_workers,
800
+ batch_size=batch_size,
801
+ )
802
+ accelerator, devices = self.parse_devices(devices)
803
+ trainer = pl.Trainer(accelerator=accelerator, devices=devices, logger=None)
804
+ self.test_metrics.reset()
805
+ trainer.test(model=self, dataloaders=dataloader, verbose=True)
806
+
807
+ metric_dict = {
808
+ k: v.detach().cpu().numpy() for k, v in self.computed_test_metrics.items()
809
+ }
810
+ self.test_metrics.reset()
811
+ return pd.DataFrame(metric_dict, index=self.data_params["tasks"]["name"])
812
+
813
+ def embed_on_dataset(
814
+ self,
815
+ dataset: Callable,
816
+ devices: Union[str, int, List[int]] = "cpu",
817
+ num_workers: int = 1,
818
+ batch_size: int = 256,
819
+ ):
820
+ """
821
+ Return embeddings for a dataset of sequences
822
+
823
+ Args:
824
+ dataset: Dataset object that yields one-hot encoded sequences
825
+ devices: Device IDs to use
826
+ num_workers: Number of workers for data loader
827
+ batch_size: Batch size for data loader
828
+
829
+ Returns:
830
+ Numpy array of shape (B, T, L) containing embeddings.
831
+ """
832
+ torch.set_float32_matmul_precision("medium")
833
+
834
+ # Make dataloader
835
+ dataloader = self.make_predict_loader(
836
+ dataset, num_workers=num_workers, batch_size=batch_size
837
+ )
838
+
839
+ # Get device
840
+ orig_device = self.device
841
+ device = self.parse_devices(devices)[0]
842
+ if isinstance(device, list):
843
+ device = device[0]
844
+ warnings.warn(
845
+ f"embed_on_dataset currently only uses a single GPU: {device}"
846
+ )
847
+ self.to(device)
848
+
849
+ # Get embeddings
850
+ preds = []
851
+ self.model = self.model.eval()
852
+ for batch in iter(dataloader):
853
+ batch = batch.to(device)
854
+ preds.append(self.model.embedding(batch).detach().cpu())
855
+
856
+ # Return to original device
857
+ self.to(orig_device)
858
+ return torch.vstack(preds).numpy()
859
+
860
+ def get_task_idxs(
861
+ self,
862
+ tasks: Union[int, str, List[int], List[str]],
863
+ key: str = "name",
864
+ invert: bool = False,
865
+ ) -> Union[int, List[int]]:
866
+ """
867
+ Given a task name or metadata entry, get the task index
868
+ If integers are provided, return them unchanged
869
+
870
+ Args:
871
+ tasks: A string corresponding to a task name or metadata entry,
872
+ or an integer indicating the index of a task, or a list of strings/integers
873
+ key: key to model.data_params["tasks"] in which the relevant task data is
874
+ stored. "name" will be used by default.
875
+ invert: Get indices for all tasks except those listed in tasks
876
+
877
+ Returns:
878
+ The index or indices of the corresponding task(s) in the model's
879
+ output.
880
+ """
881
+ # If a string is provided, extract the index
882
+ if isinstance(tasks, str):
883
+ return self.data_params["tasks"][key].index(tasks)
884
+ # If an integer is provided, return it as the index
885
+ elif isinstance(tasks, int):
886
+ return tasks
887
+ # If a list is provided, return teh index for each element
888
+ elif isinstance(tasks, list):
889
+ return [self.get_task_idxs(task) for task in tasks]
890
+ else:
891
+ raise TypeError("Input must be a list, string or integer")
892
+ if invert:
893
+ return [
894
+ i
895
+ for i in range(self.model_params["n_tasks"])
896
+ if i not in make_list(tasks)
897
+ ]
898
+
899
+ def input_coord_to_output_bin(
900
+ self,
901
+ input_coord: int,
902
+ start_pos: int = 0,
903
+ ) -> int:
904
+ """
905
+ Given the position of a base in the input, get the index of the corresponding bin
906
+ in the model's prediction.
907
+
908
+ Args:
909
+ input_coord: Genomic coordinate of the input position
910
+ start_pos: Genomic coordinate of the first base in the input sequence
911
+
912
+ Returns:
913
+ Index of the output bin containing the given position.
914
+
915
+ """
916
+ output_bin = (input_coord - start_pos) / self.data_params[
917
+ "train_bin_size"
918
+ ] - self.model_params["crop_len"]
919
+ return int(np.floor(output_bin))
920
+
921
+ def output_bin_to_input_coord(
922
+ self,
923
+ output_bin: int,
924
+ return_pos: str = "start",
925
+ start_pos: int = 0,
926
+ ) -> int:
927
+ """
928
+ Given the index of a bin in the output, get its corresponding
929
+ start or end coordinate.
930
+
931
+ Args:
932
+ output_bin: Index of the bin in the model's output
933
+ return_pos: "start" or "end"
934
+ start_pos: Genomic coordinate of the first base in the input sequence
935
+
936
+ Returns:
937
+ Genomic coordinate corresponding to the start (if return_pos = start)
938
+ or end (if return_pos=end) of the bin.
939
+
940
+ """
941
+ start = (output_bin + self.model_params["crop_len"]) * self.data_params[
942
+ "train_bin_size"
943
+ ]
944
+ if return_pos == "start":
945
+ return start + start_pos
946
+ elif return_pos == "end":
947
+ return start + self.data_params["train_bin_size"] + start_pos
948
+ else:
949
+ raise NotImplementedError
950
+
951
+ def input_intervals_to_output_intervals(
952
+ self,
953
+ intervals: pd.DataFrame,
954
+ ) -> pd.DataFrame:
955
+ """
956
+ Given a dataframe containing intervals corresponding to the
957
+ input sequences, return a dataframe containing intervals corresponding
958
+ to the model output.
959
+
960
+ Args:
961
+ intervals: A dataframe of genomic intervals
962
+
963
+ Returns:
964
+ A dataframe containing the genomic intervals corresponding
965
+ to the model output from each input interval.
966
+ """
967
+ output_intervals = intervals.copy()
968
+ crop_coords = self.model_params["crop_len"] * self.data_params["train_bin_size"]
969
+ output_intervals["start"] = intervals.start + crop_coords
970
+ output_intervals["end"] = intervals.end - crop_coords
971
+ return output_intervals
972
+
973
+ def input_intervals_to_output_bins(
974
+ self, intervals: pd.DataFrame, start_pos: int = 0
975
+ ) -> None:
976
+ """
977
+ Given a dataframe of genomic intervals, add columns indicating
978
+ the indices of output bins that overlap the start and end of each interval.
979
+
980
+ Args:
981
+ intervals: A dataframe of genomic intervals
982
+ start_pos: The start position of the sequence input to the model.
983
+
984
+ Returns:start and end indices of the output bins corresponding
985
+ to each input interval.
986
+ """
987
+ return pd.DataFrame(
988
+ {
989
+ "start": intervals.start.apply(
990
+ self.input_coord_to_output_bin, args=(start_pos,)
991
+ ),
992
+ "end": intervals.end.apply(
993
+ self.input_coord_to_output_bin, args=(start_pos,)
994
+ )
995
+ + 1,
996
+ }
997
+ )
998
+
999
+
1000
+ class LightningModelEnsemble(pl.LightningModule):
1001
+ """
1002
+ Combine multiple LightningModel objects into a single object.
1003
+ When predict_on_dataset is used, it will return the concatenated
1004
+ predictions from all the models in the order in which they were supplied.
1005
+
1006
+ Args:
1007
+ models (list): A list of multiple LightningModel objects
1008
+ model_names (list): A name for each model. This will be prefixed
1009
+ to the names of the individual tasks predicted by the model.
1010
+ If not supplied, the models will be named "model0", "model1", etc.
1011
+ """
1012
+
1013
+ def __init__(self, models: list, model_names: Optional[List[str]] = None) -> None:
1014
+ super().__init__()
1015
+
1016
+ # Save models
1017
+ self.models = [model for model in models]
1018
+
1019
+ # Save model names
1020
+ self.model_names = model_names or [f"model{i}" for i in range(len(self.models))]
1021
+
1022
+ # Save their task metadata
1023
+ self.model_params = {
1024
+ "n_tasks": sum([model.model_params["n_tasks"] for model in self.models])
1025
+ }
1026
+ self.data_params = {"tasks": defaultdict(list)}
1027
+ self._combine_tasks()
1028
+
1029
+ def _combine_tasks(self) -> None:
1030
+ """
1031
+ Combine the task metadata of all the sub-models into self.data_params["tasks"]
1032
+ """
1033
+ # List all available keys
1034
+ task_keys = set(self.models[0].data_params["tasks"].keys())
1035
+ for model in self.models[1:]:
1036
+ task_keys = task_keys.intersection(model.data_params["tasks"].keys())
1037
+
1038
+ # Collect task metadata for each key
1039
+ for key in task_keys:
1040
+ for name, model in zip(self.model_names, self.models):
1041
+ self.data_params["tasks"][key].extend(
1042
+ ["_".join([name, x]) for x in model.data_params["tasks"][key]]
1043
+ )
1044
+ assert (
1045
+ len(set(self.data_params["tasks"][key])) == self.model_params["n_tasks"]
1046
+ )
1047
+
1048
+ def forward(self, x: Tensor) -> Tensor:
1049
+ """
1050
+ Forward Pass.
1051
+ """
1052
+ return torch.cat([model(x) for model in self.models], axis=1) # B, T, L
1053
+
1054
+ def predict_on_dataset(self, dataset: Callable, **kwargs) -> np.ndarray:
1055
+ """
1056
+ This will return the concatenated predictions from all the
1057
+ constituent models, in the order in which they were supplied.
1058
+ Predictions will be concatenated along the task axis.
1059
+ """
1060
+ return np.concatenate(
1061
+ [model.predict_on_dataset(dataset, **kwargs) for model in self.models],
1062
+ axis=-2,
1063
+ )
1064
+
1065
+ def get_task_idxs(
1066
+ self, tasks: Union[str, int, List[str], List[int]], key: str = "name"
1067
+ ) -> Union[int, List[int]]:
1068
+ """
1069
+ Return the task index given the name of the task. Note that task
1070
+ names should be supplied with a prefix indicating the model number,
1071
+ so for instance if you want the predictions from the second model
1072
+ on astrocytes, the task name would be "{name of second model}_astrocytes".
1073
+ If model names were not supplied to __init__, the task name would
1074
+ be "model1_astrocytes".
1075
+
1076
+ Args:
1077
+ tasks: A string corresponding to a task name or metadata entry,
1078
+ or an integer indicating the index of a task, or a list of strings/integers
1079
+ key: key to model.data_params["tasks"] in which the relevant task data is
1080
+ stored. "name" will be used by default.
1081
+
1082
+ Returns: An integer or list of integers representing the indices of the
1083
+ tasks in the model output.
1084
+ """
1085
+ # If a string is provided, extract the index
1086
+ if isinstance(tasks, str):
1087
+ return self.data_params["tasks"][key].index(tasks)
1088
+
1089
+ # If an integer is provided, return it as the index
1090
+ elif isinstance(tasks, int):
1091
+ return tasks
1092
+
1093
+ # If a list is provided, return the index for each element
1094
+ elif isinstance(tasks, list):
1095
+ return [self.get_task_idxs(task) for task in tasks]
1096
+ else:
1097
+ raise TypeError("Input must be a list, string or integer")