PersonalBPNet 0.7.0__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.
@@ -0,0 +1,117 @@
1
+ # losses.py
2
+ # Authors: adamyhe <adamyhe@gmail.com>
3
+
4
+ """
5
+ This module contains the losses used by BNBPNet for training.
6
+ """
7
+
8
+ import torch
9
+ from bpnetlite.losses import MNLLLoss, log1pMSELoss, _mixture_loss
10
+
11
+
12
+ def _mixture_loss_masked(
13
+ y, y_hat_logits, y_hat_logcounts, count_loss_weight, labels=None, mask=None
14
+ ):
15
+ """A modified version of the _mixture_loss function from bpnetlite to allow
16
+ for masking out specified positions from the loss calculation.
17
+
18
+ Parameters
19
+ ----------
20
+ y: torch.Tensor, shape=(n, ..., L)
21
+ A tensor with `n` examples and `L` possible categories.
22
+ True labels.
23
+
24
+ y_hat_logits: torch.Tensor, shape=(n, ..., L)
25
+ A tensor with `n` examples and `L` possible categories.
26
+ Predicted logits from the profile head.
27
+
28
+ y_hat_logcounts: torch.Tensor, shape=(n, ...)
29
+ A tensor with `n` examples and `L` possible categories.
30
+ Predicted log counts from the count head.
31
+
32
+ count_loss_weight: float
33
+ The weight of the count loss component of the mixture loss.
34
+
35
+ labels: torch.Tensor, shape=(n, ..., L)
36
+ A tensor with `n` examples and `L` possible categories.
37
+
38
+ mask: torch.Tensor, shape=(n, L) or None
39
+ A boolean tensor with `n` examples and `L` possible categories.
40
+ Positions where `mask[i, j] == True` will be masked out.
41
+
42
+ Returns
43
+ -------
44
+ profile_loss: torch.Tensor, shape=(n, ...)
45
+ The profile loss component of the mixture loss.
46
+
47
+ count_loss: torch.Tensor, shape=(n, ...)
48
+ The count loss component of the mixture loss.
49
+
50
+ loss: torch.Tensor, shape=(n, ...)
51
+ The mixture loss.
52
+ """
53
+
54
+ if mask is None:
55
+ return _mixture_loss(y, y_hat_logits, y_hat_logcounts, count_loss_weight, labels)
56
+
57
+ y_counts = y.sum(dim=(-1, -2)).reshape(y.shape[0], 1)
58
+
59
+ # Calculate the profile and count losses
60
+ if labels is not None:
61
+ profile_loss = MNLLLoss_masked(
62
+ y_hat_logits[labels == 1], y[labels == 1], mask[labels == 1]
63
+ ).mean()
64
+ else:
65
+ profile_loss = MNLLLoss_masked(y_hat_logits, y, mask).mean()
66
+
67
+ count_loss = log1pMSELoss(y_hat_logcounts, y_counts).mean()
68
+
69
+ # Mix losses together
70
+ loss = profile_loss + count_loss_weight * count_loss
71
+
72
+ return profile_loss, count_loss, loss
73
+
74
+
75
+ def MNLLLoss_masked(logits, true_counts, mask=None):
76
+ """A wrapper function for MNLLLoss that allows for masking out specified
77
+ positions from the loss calculation.
78
+
79
+ Parameters
80
+ ----------
81
+ logits: torch.Tensor, shape=(n, ..., L)
82
+ A tensor with `n` examples and `L` possible categories.
83
+
84
+ true_counts: torch.Tensor, shape=(n, ..., L)
85
+ A tensor with `n` examples and `L` possible categories.
86
+
87
+ mask: torch.Tensor, shape=(n, L)
88
+ A boolean tensor with `n` examples and `L` possible categories.
89
+ Positions where `mask[i, j] == True` will be masked out.
90
+
91
+ Returns
92
+ -------
93
+ loss: torch.Tensor, shape=(n, ...)
94
+ The multinomial log likelihood loss of the true counts given the
95
+ predicted probabilities
96
+ """
97
+ loss = 0
98
+ for logits_i, true_counts_i, mask_i in zip(logits, true_counts, mask):
99
+ # Repeat mask to match logits shape
100
+ mask_i = (
101
+ mask_i.repeat(logits_i.shape[0], 1)
102
+ if len(mask_i.shape) < len(logits_i.shape)
103
+ else mask_i
104
+ )
105
+ # First mask out positions
106
+ logits_i = torch.masked_select(logits_i, mask_i)[None, ...]
107
+ true_counts_i = torch.masked_select(true_counts_i, mask_i)[None, ...]
108
+ # Then flatten and log softmax
109
+ logits_i = logits_i.reshape(logits_i.shape[0], -1)
110
+ true_counts_i = true_counts_i.reshape(true_counts_i.shape[0], -1)
111
+ logps_i = torch.nn.functional.log_softmax(logits_i, dim=-1)
112
+ # Ensure correct shape, since MNLLLoss expects N, ..., L
113
+ if logps_i.shape < logits_i.shape:
114
+ logps_i = logps_i.unsqueeze(dim=-1)
115
+ true_counts_i = true_counts_i.unsqueeze(dim=-1)
116
+ loss += MNLLLoss(logps_i, true_counts_i).mean()
117
+ return loss / len(logits)
@@ -0,0 +1,276 @@
1
+ # personal_bpnet.py
2
+ # Author: Adam He <adamyhe@gmail.com>
3
+
4
+ """
5
+ A subclass of bpnetlite.bpnet.BPNet that redoes the validation loop to work with a
6
+ PyTorch DataLoader, rather than having to load the whole validation set into memory
7
+ at once. Also, the model checkpoints save the optimizer state dict and epoch number
8
+ in addition to the model state dict, so that training can be resumed from a
9
+ checkpoint. The architecture (and therefore state_dict) is identical to BPNet, so
10
+ PersonalBPNet weights can be loaded directly into a standard BPNet instance (and
11
+ vice versa), as long as the same init arguments are used.
12
+ """
13
+
14
+ import time
15
+
16
+ import numpy as np
17
+ import torch
18
+ from bpnetlite.bpnet import BPNet
19
+ from bpnetlite.losses import _mixture_loss
20
+ from bpnetlite.performance import calculate_performance_measures, pearson_corr
21
+ from tangermeme.predict import predict
22
+
23
+
24
+ class PersonalBPNet(BPNet):
25
+ """
26
+ A basic BPNet model with stranded profile and total count prediction.
27
+
28
+ Identical architecture to `bpnetlite.bpnet.BPNet`, but with a `fit()` method that
29
+ accepts a PyTorch DataLoader for validation data (instead of fixed tensors), which
30
+ significantly improves the memory footprint of the validation step, and that
31
+ checkpoints the optimizer state dict and epoch number alongside the model weights
32
+ to support resuming training. Note that random data augmentations (jittering,
33
+ reverse complement) should be turned off to return a fixed validation dataset.
34
+
35
+ See `bpnetlite.bpnet.BPNet` for the model architecture and the meaning of the
36
+ constructor parameters. Defaults for `n_outputs`, `n_control_tracks`, and
37
+ `trimming` differ from BPNet's to match this project's typical use case
38
+ (single-output, no controls).
39
+ """
40
+
41
+ def __init__(
42
+ self, *args, n_outputs=1, n_control_tracks=0, n_layers=8, trimming=None, **kwargs
43
+ ):
44
+ super().__init__(
45
+ *args,
46
+ n_outputs=n_outputs,
47
+ n_control_tracks=n_control_tracks,
48
+ n_layers=n_layers,
49
+ trimming=trimming if trimming is not None else 2**n_layers,
50
+ **kwargs,
51
+ )
52
+
53
+ def fit(
54
+ self,
55
+ training_data,
56
+ optimizer,
57
+ scheduler=None,
58
+ valid_data=None,
59
+ max_epochs=100,
60
+ batch_size=64,
61
+ validation_iter=100,
62
+ early_stopping=None,
63
+ dtype=torch.bfloat16,
64
+ device="cuda",
65
+ verbose=True,
66
+ ):
67
+ """Fit the model to data and validate it periodically.
68
+
69
+ This method controls the training of a BPNet model. It will fit the
70
+ model to examples generated by the `training_data` DataLoader object
71
+ and, if validation data is provided, will periodically validate the
72
+ model against it and return those values. The periodicity can be
73
+ controlled using the `validation_iter` parameter.
74
+
75
+ Two versions of the model will be saved: the best model found during
76
+ training according to the validation measures, and the final model
77
+ at the end of training. Additionally, a log will be saved of the
78
+ training and validation statistics, e.g. time and performance.
79
+
80
+ Parameters
81
+ ----------
82
+ training_data: torch.utils.data.DataLoader
83
+ A generator that produces examples to train on. If n_control_tracks
84
+ is greater than 0, must product two inputs, otherwise must produce
85
+ only one input.
86
+
87
+ optimizer: torch.optim.Optimizer
88
+ An optimizer to control the training of the model.
89
+
90
+ scheduler: torch.optim.lr_scheduler._LRScheduler or None
91
+ A scheduler to control the learning rate of the optimizer. Optional.
92
+
93
+ valid_data: torch.utils.data.DataLoader
94
+ A generator that produces examples to earlystop on. If n_control_tracks
95
+ is greater than 0, must product two inputs, otherwise must produce
96
+ only one input.
97
+
98
+ max_epochs: int
99
+ The maximum number of epochs to train for, as measured by the
100
+ number of times that `training_data` is exhausted. Default is 100.
101
+
102
+ batch_size: int
103
+ The number of examples to include in each batch. Default is 64.
104
+
105
+ validation_iter: int
106
+ The number of batches to train on before validating against the
107
+ entire validation set. When the validation set is large, this
108
+ enables the total validating time to be small compared to the
109
+ training time by only validating periodically. Default is 100.
110
+
111
+ early_stopping: int or None
112
+ Whether to stop training early. If None, continue training until
113
+ max_epochs is reached. If an integer, continue training until that
114
+ number of `validation_iter` ticks has been hit without improvement
115
+ in performance. Default is None.
116
+
117
+ verbose: bool
118
+ Whether to print out the training and evaluation statistics during
119
+ training. Default is True.
120
+ """
121
+
122
+ iteration = 0
123
+ early_stop_count = 0
124
+ best_loss = float("inf")
125
+ self.logger.start()
126
+
127
+ for epoch in range(max_epochs):
128
+ tic = time.time()
129
+
130
+ for data in training_data:
131
+ if len(data) == 4:
132
+ X, X_ctl, y, labels = data
133
+ X_ctl = torch.abs(X_ctl).to(device).float()
134
+ else:
135
+ X, y, labels = data
136
+ X_ctl = None
137
+
138
+ X = X.to(device).float()
139
+ y = torch.abs(y).to(device)
140
+
141
+ # Clear the optimizer and set the model to training mode
142
+ optimizer.zero_grad()
143
+ self.train()
144
+
145
+ # Run forward pass
146
+ with torch.autocast(device_type=device, dtype=dtype):
147
+ y_hat_logits, y_hat_logcounts = self(X, X_ctl)
148
+ training_profile_loss_, training_count_loss_, loss = _mixture_loss(
149
+ y, y_hat_logits, y_hat_logcounts, self.count_loss_weight, labels
150
+ )
151
+ loss.backward()
152
+ optimizer.step()
153
+
154
+ # Report measures if desired
155
+ if verbose and iteration % validation_iter == 0:
156
+ train_time = time.time() - tic
157
+
158
+ with torch.no_grad():
159
+ self.eval()
160
+
161
+ tic = time.time()
162
+
163
+ # Initialize lists to store validation statistics
164
+ profile_corr = []
165
+ valid_mnll = []
166
+ valid_mse = []
167
+ pred_counts = []
168
+ obs_counts = []
169
+
170
+ # Loop over the validation data
171
+ for data in valid_data:
172
+ if len(data) == 3:
173
+ X_val, X_ctl_val, y_val = data
174
+ X_ctl_val = (torch.abs(X_ctl_val),)
175
+ else:
176
+ X_val, y_val = data
177
+ X_ctl_val = None
178
+
179
+ y_val = torch.abs(y_val)
180
+ y_profile, y_counts = predict(
181
+ self,
182
+ X_val,
183
+ args=X_ctl_val,
184
+ batch_size=batch_size,
185
+ device=device,
186
+ dtype=dtype,
187
+ )
188
+ obs_counts.append(y_val.sum(dim=(-2, -1)).reshape(-1, 1))
189
+ pred_counts.append(y_counts)
190
+
191
+ z = y_profile.shape
192
+ y_profile = y_profile.reshape(y_profile.shape[0], -1)
193
+ y_profile = torch.nn.functional.log_softmax(
194
+ y_profile, dim=-1
195
+ )
196
+ y_profile = y_profile.reshape(*z)
197
+
198
+ measures = calculate_performance_measures(
199
+ y_profile,
200
+ y_val,
201
+ y_counts,
202
+ kernel_sigma=7,
203
+ kernel_width=81,
204
+ measures=[
205
+ "profile_mnll",
206
+ "profile_pearson",
207
+ "count_mse",
208
+ ],
209
+ )
210
+ profile_corr.append(measures["profile_pearson"])
211
+ valid_mnll.append(measures["profile_mnll"])
212
+ valid_mse.append(measures["count_mse"])
213
+
214
+ # Other metrics can be calculated in the loop, but
215
+ # count_corr needs to be calculated by storing the
216
+ # counts and then calculating the correlation at the end
217
+ count_corr = pearson_corr(
218
+ torch.cat(pred_counts).squeeze(),
219
+ torch.log(torch.cat(obs_counts).squeeze() + 1),
220
+ )
221
+
222
+ # Concatenate the lists of validation measures
223
+ profile_corr = torch.cat(profile_corr)
224
+ valid_mnll = torch.cat(valid_mnll)
225
+ valid_mse = torch.cat(valid_mse)
226
+ valid_loss = (
227
+ valid_mnll.mean() + self.count_loss_weight * valid_mse.mean()
228
+ )
229
+
230
+ valid_time = time.time() - tic
231
+
232
+ self.logger.add(
233
+ [
234
+ epoch,
235
+ iteration,
236
+ train_time,
237
+ valid_time,
238
+ training_profile_loss_.item(),
239
+ training_count_loss_.item(),
240
+ measures["profile_mnll"].mean().item(),
241
+ np.nan_to_num(profile_corr).mean(),
242
+ np.nan_to_num(count_corr).mean(),
243
+ measures["count_mse"].mean().item(),
244
+ (valid_loss < best_loss).item(),
245
+ ]
246
+ )
247
+
248
+ self.logger.save("{}.log".format(self.name))
249
+
250
+ # Save the model if it is the best so far
251
+ if valid_loss < best_loss:
252
+ torch.save(self.state_dict(), f"{self.name}.torch")
253
+ torch.save(
254
+ {
255
+ "early_stop_count": early_stop_count,
256
+ "epoch": epoch,
257
+ "optimizer_state_dict": optimizer.state_dict(),
258
+ },
259
+ f"{self.name}.checkpoint.torch",
260
+ )
261
+ best_loss = valid_loss
262
+ early_stop_count = 0
263
+ else:
264
+ early_stop_count += 1
265
+
266
+ if early_stopping is not None and early_stop_count >= early_stopping:
267
+ break
268
+
269
+ iteration += 1
270
+
271
+ if early_stopping is not None and early_stop_count >= early_stopping:
272
+ break
273
+ if scheduler is not None:
274
+ scheduler.step()
275
+
276
+ torch.save(self, "{}.final.torch".format(self.name))
@@ -0,0 +1,256 @@
1
+ # clipnet_pytorch.py
2
+ # Author: Adam He <adamyhe@gmail.com>
3
+
4
+ """
5
+ An implementation of ProCapNet as a subclass of bpnetlite.bpnet.BPNet. Its forward pass
6
+ is the same as BPNet, but implements a masked profile loss function as described in the
7
+ ProCapNet paper. Because the forward pass is the same, ProCapNet models can also be
8
+ loaded using the bpnetlite.bpnet.BPNet class (provided you pass in the same init args).
9
+ """
10
+
11
+ import time
12
+
13
+ import numpy as np
14
+ import torch
15
+ from bpnetlite.bpnet import BPNet
16
+ from bpnetlite.logging import Logger
17
+ from bpnetlite.performance import calculate_performance_measures
18
+ from tangermeme.predict import predict
19
+
20
+ from .losses import _mixture_loss_masked
21
+
22
+
23
+ class ProCapNet(BPNet):
24
+ def __init__(
25
+ self,
26
+ *args,
27
+ n_filters=512,
28
+ n_outputs=2,
29
+ n_control_tracks=0,
30
+ count_loss_weight=100,
31
+ verbose=True,
32
+ **kwargs,
33
+ ):
34
+ super().__init__(
35
+ *args,
36
+ n_filters=n_filters,
37
+ n_outputs=n_outputs,
38
+ n_control_tracks=n_control_tracks,
39
+ count_loss_weight=count_loss_weight,
40
+ **kwargs,
41
+ )
42
+ self.logger = Logger(
43
+ [
44
+ "Epoch",
45
+ "Iteration",
46
+ "Training Time",
47
+ "Validation Time",
48
+ "Training MNLL",
49
+ "Training Count MSE",
50
+ "Validation MNLL",
51
+ "Validation Count MSE",
52
+ "Validation Profile JSD",
53
+ "Validation Count Pearson",
54
+ "Saved?",
55
+ ],
56
+ verbose=verbose,
57
+ )
58
+
59
+ def fit(
60
+ self,
61
+ training_data,
62
+ optimizer,
63
+ scheduler=None,
64
+ X_valid=None,
65
+ X_ctl_valid=None,
66
+ y_valid=None,
67
+ y_has_mask=True,
68
+ max_epochs=100,
69
+ batch_size=64,
70
+ dtype="float32",
71
+ device="cuda",
72
+ early_stopping=None,
73
+ ):
74
+ """Fit the model to data and validate it periodically.
75
+
76
+ This method controls the training of a BPNet model. It will fit the
77
+ model to examples generated by the `training_data` DataLoader object
78
+ and, if validation data is provided, will validate the model against
79
+ it at the end of each epoch and return those values.
80
+
81
+ Two versions of the model will be saved: the best model found during
82
+ training according to the validation measures, and the final model
83
+ at the end of training. Additionally, a log will be saved of the
84
+ training and validation statistics, e.g. time and performance.
85
+
86
+ Parameters
87
+ ----------
88
+ training_data: torch.utils.data.DataLoader
89
+ A generator that produces examples to train on. If n_control_tracks
90
+ is greater than 0, must product two inputs, otherwise must produce
91
+ only one input.
92
+
93
+ optimizer: torch.optim.Optimizer
94
+ An optimizer to control the training of the model.
95
+
96
+ scheduler: torch.optim.lr_scheduler, optional
97
+ An optional learning rate scheduler which changes the learning rate
98
+ across batches. If None, do not use a scheduler. Default is None.
99
+
100
+ X_valid: torch.tensor or None, shape=(n, 4, 2114)
101
+ A block of sequences to validate on periodically. If None, do not
102
+ perform validation. Default is None.
103
+
104
+ X_ctl_valid: torch.tensor or None, shape=(n, n_control_tracks, 2114)
105
+ A block of control sequences to validate on periodically. If
106
+ n_control_tracks is None, pass in None. Default is None.
107
+
108
+ y_valid: torch.tensor or None, shape=(n, n_outputs, 1000)
109
+ A block of signals to validate against. Must be provided if
110
+ X_valid is also provided. Default is None.
111
+
112
+ y_has_mask: bool
113
+ Whether the output y tracks will contain a boolean mask for excluding
114
+ positions from profile loss calculations. The final output track
115
+ will be treated as a boolean mask, whereas the other tracks will be
116
+ processed as normal. Default is True.
117
+
118
+ max_epochs: int
119
+ The maximum number of epochs to train for, as measured by the
120
+ number of times that `training_data` is exhausted. Default is 100.
121
+
122
+ batch_size: int, optional
123
+ The number of examples to include in each batch. Default is 64.
124
+
125
+ dtype: str or torch.dtype
126
+ The torch.dtype to use when training. Usually, this will be torch.float32
127
+ or torch.bfloat16. Default is torch.float32.
128
+
129
+ device: str
130
+ The device to use for training and inference. Typically, this will be
131
+ 'cuda' but can be anything supported by torch. Default is 'cuda'.
132
+
133
+ early_stopping: int or None, optional
134
+ Whether to stop training early. If None, continue training until
135
+ max_epochs is reached. If an integer, continue training until that
136
+ number of epochs has been hit without improvement in performance.
137
+ Default is None.
138
+ """
139
+
140
+ if y_valid is not None and y_has_mask:
141
+ y_valid = y_valid[:, : self.n_outputs, :]
142
+
143
+ if X_ctl_valid is not None:
144
+ X_ctl_valid = (X_ctl_valid,)
145
+
146
+ dtype = getattr(torch, dtype) if isinstance(dtype, str) else dtype
147
+
148
+ iteration = 0
149
+ early_stop_count = 0
150
+ best_loss = float("inf")
151
+ self.logger.start()
152
+
153
+ for epoch in range(max_epochs):
154
+ tic = time.time()
155
+
156
+ for data in training_data:
157
+ X, y, labels = data[0], data[-2], data[-1]
158
+ if y_has_mask:
159
+ mask = y[:, -1, :] == 1
160
+ else:
161
+ mask = None
162
+ y = y[:, : self.n_outputs, :]
163
+ X_ctl = data[1].to(device) if len(data) == 4 else None
164
+
165
+ X = X.to(device).float()
166
+ y = y.to(device)
167
+
168
+ # Clear the optimizer and set the model to training mode
169
+ optimizer.zero_grad()
170
+ self.train()
171
+
172
+ # Make one training step
173
+ with torch.autocast(device_type=device, dtype=dtype):
174
+ y_hat_logits, y_hat_logcounts = self(X, X_ctl)
175
+
176
+ training_profile_loss_, training_count_loss_, loss = (
177
+ _mixture_loss_masked(
178
+ y,
179
+ y_hat_logits,
180
+ y_hat_logcounts,
181
+ self.count_loss_weight,
182
+ labels,
183
+ mask.to(device) if mask is not None else None,
184
+ )
185
+ )
186
+
187
+ loss.backward()
188
+ torch.nn.utils.clip_grad_norm_(self.parameters(), 1)
189
+ optimizer.step()
190
+
191
+ iteration += 1
192
+
193
+ train_time = time.time() - tic
194
+
195
+ # Validate the model at the end of the epoch
196
+ with torch.no_grad():
197
+ self.eval()
198
+ tic = time.time()
199
+
200
+ y_hat_logits, y_hat_logcounts = predict(
201
+ self,
202
+ X_valid,
203
+ args=X_ctl_valid,
204
+ batch_size=batch_size,
205
+ dtype=dtype,
206
+ device=device,
207
+ )
208
+
209
+ valid_profile_loss, valid_count_loss, valid_loss = _mixture_loss_masked(
210
+ y_valid, y_hat_logits, y_hat_logcounts, self.count_loss_weight, labels=None, mask=None
211
+ )
212
+
213
+ measures = calculate_performance_measures(
214
+ y_hat_logits,
215
+ y_valid,
216
+ y_hat_logcounts,
217
+ kernel_sigma=7,
218
+ kernel_width=81,
219
+ measures=["profile_jsd", "count_pearson"],
220
+ )
221
+
222
+ valid_profile_jsd = np.nan_to_num(measures["profile_jsd"])
223
+ valid_count_corr = np.nan_to_num(measures["count_pearson"])
224
+ valid_time = time.time() - tic
225
+
226
+ self.logger.add(
227
+ [
228
+ epoch,
229
+ iteration,
230
+ train_time,
231
+ valid_time,
232
+ training_profile_loss_.item(),
233
+ training_count_loss_.item(),
234
+ valid_profile_loss.item(),
235
+ valid_count_loss.item(),
236
+ valid_profile_jsd.mean(),
237
+ valid_count_corr.mean(),
238
+ (valid_loss < best_loss).item(),
239
+ ]
240
+ )
241
+
242
+ self.logger.save("{}.log".format(self.name))
243
+
244
+ if valid_loss < best_loss:
245
+ torch.save(self.state_dict(), "{}.torch".format(self.name))
246
+ best_loss = valid_loss
247
+ early_stop_count = -1
248
+
249
+ if scheduler is not None:
250
+ scheduler.step(valid_loss)
251
+
252
+ early_stop_count += 1
253
+ if early_stopping is not None and early_stop_count >= early_stopping:
254
+ break
255
+
256
+ torch.save(self.state_dict(), "{}.final.torch".format(self.name))