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,294 @@
1
+ # clipnet_pytorch.py
2
+ # Author: Adam He <adamyhe@gmail.com>
3
+
4
+ """
5
+ CLIPNET: a subclass of PersonalBPNet (itself a subclass of bpnetlite.bpnet.BPNet)
6
+ that adds batch normalization after each convolutional and linear layer, which was
7
+ used in the original CLIPNET TensorFlow implementation and appears to improve
8
+ performance. Inherits PersonalBPNet's DataLoader-based fit() unchanged.
9
+
10
+ Also includes PauseNet, a transfer learning wrapper around CLIPNET (or any
11
+ BPNet-like model) for fine-tuning to a single scalar phenotype per locus.
12
+ """
13
+
14
+ import time
15
+
16
+ import numpy as np
17
+ import torch
18
+ from bpnetlite.bpnet import CountWrapper
19
+ from bpnetlite.logging import Logger
20
+ from bpnetlite.losses import log1pMSELoss
21
+ from bpnetlite.performance import pearson_corr
22
+ from tangermeme.predict import predict
23
+
24
+ from .personal_bpnet import PersonalBPNet
25
+
26
+
27
+ class CLIPNET(PersonalBPNet):
28
+ """
29
+ A basic BPNet model with stranded profile and total count prediction.
30
+
31
+ Identical to `PersonalBPNet` (and therefore `bpnetlite.bpnet.BPNet`), except that
32
+ a batch normalization layer follows each convolutional and linear layer. See
33
+ `PersonalBPNet`/`bpnetlite.bpnet.BPNet` for the model architecture, the meaning
34
+ of the constructor parameters, and the DataLoader-based `fit()` method, which is
35
+ inherited unchanged. Defaults for `n_filters`, `n_outputs`, and `trimming` are
36
+ set to match the pretrained CLIPNET weights (2114 bp in, 1000 bp out).
37
+ """
38
+
39
+ def __init__(
40
+ self, *args, n_filters=512, n_outputs=2, trimming=(2114 - 1000) // 2, **kwargs
41
+ ):
42
+ super().__init__(
43
+ *args, n_filters=n_filters, n_outputs=n_outputs, trimming=trimming, **kwargs
44
+ )
45
+ self.ibn = torch.nn.BatchNorm1d(self.n_filters)
46
+ self.rbn = torch.nn.ModuleList(
47
+ [torch.nn.BatchNorm1d(self.n_filters) for _ in range(self.n_layers)]
48
+ )
49
+ self.pbn = torch.nn.BatchNorm1d(self.n_outputs)
50
+ self.cbn = torch.nn.BatchNorm1d(1)
51
+
52
+ def forward(self, X, X_ctl=None):
53
+ """A forward pass of the model.
54
+
55
+ This method takes in a nucleotide sequence X, a corresponding
56
+ per-position value from a control track, and a per-locus value
57
+ from the control track and makes predictions for the profile
58
+ and for the counts. This per-locus value is usually the
59
+ log(sum(X_ctl_profile)+1) when the control is an experimental
60
+ read track but can also be the output from another model.
61
+
62
+ Parameters
63
+ ----------
64
+ X: torch.tensor, shape=(batch_size, 4, length)
65
+ The one-hot encoded batch of sequences.
66
+
67
+ X_ctl: torch.tensor or None, shape=(batch_size, n_strands, length)
68
+ A value representing the signal of the control at each position in
69
+ the sequence. If no controls, pass in None. Default is None.
70
+
71
+ Returns
72
+ -------
73
+ y_profile: torch.tensor, shape=(batch_size, n_strands, out_length)
74
+ The output predictions for each strand trimmed to the output
75
+ length.
76
+
77
+ y_counts: torch.tensor, shape=(batch_size, 1)
78
+ The output predictions for the total counts.
79
+ """
80
+
81
+ start, end = self.trimming, X.shape[2] - self.trimming
82
+
83
+ X = self.irelu(self.ibn(self.iconv(X)))
84
+ for i in range(self.n_layers):
85
+ X_conv = self.rrelus[i](self.rbn[i](self.rconvs[i](X)))
86
+ X = torch.add(X, X_conv)
87
+
88
+ if X_ctl is None:
89
+ X_w_ctl = X
90
+ else:
91
+ X_w_ctl = torch.cat([X, X_ctl], dim=1)
92
+
93
+ # profile prediction
94
+ y_profile = self.pbn(self.fconv(X_w_ctl))[:, :, start:end]
95
+
96
+ # counts prediction
97
+ X = torch.mean(X[:, :, start - 37 : end + 37], dim=2)
98
+ if X_ctl is not None:
99
+ X_ctl = torch.sum(X_ctl[:, :, start - 37 : end + 37], dim=(1, 2))
100
+ X_ctl = X_ctl.unsqueeze(-1)
101
+ X = torch.cat([X, torch.log(X_ctl + 1)], dim=-1)
102
+
103
+ y_counts = self.cbn(self.linear(X).reshape(X.shape[0], 1))
104
+
105
+ return y_profile, y_counts
106
+
107
+
108
+ class PauseNet(CountWrapper):
109
+ """
110
+ A class for transfer learning a CLIPNET model (or any BPNet-like model) to a
111
+ single scalar phenotype per input. The base model's counts-head linear layer
112
+ (and batch normalization layer, if present) are replaced with newly initialized
113
+ ones, which remain trainable regardless of `base_trainable`. By default, the
114
+ rest of the network is also trainable; set `base_trainable=False` to freeze it.
115
+ """
116
+
117
+ def __init__(
118
+ self,
119
+ base_model,
120
+ base_trainable=True,
121
+ n_filters=None,
122
+ output_bias=True,
123
+ name=None,
124
+ verbose=True,
125
+ ):
126
+ super().__init__(base_model)
127
+ self.name = name or "pausenet"
128
+ self.base_trainable = base_trainable
129
+
130
+ if not self.base_trainable:
131
+ for param in self.model.parameters():
132
+ param.requires_grad = False
133
+
134
+ # Replace the base model's counts head with a freshly initialized one.
135
+ # Defaults to the base model's existing linear layer width (which already
136
+ # accounts for control tracks, if any) unless explicitly overridden.
137
+ if n_filters is None:
138
+ n_filters = self.model.linear.in_features
139
+ self.model.linear = torch.nn.Linear(n_filters, 1, bias=output_bias)
140
+ for param in self.model.linear.parameters():
141
+ param.requires_grad = True
142
+
143
+ if hasattr(self.model, "cbn"):
144
+ self.model.cbn = torch.nn.BatchNorm1d(1)
145
+ for param in self.model.cbn.parameters():
146
+ param.requires_grad = True
147
+
148
+ self.logger = Logger(
149
+ [
150
+ "Epoch",
151
+ "Iteration",
152
+ "Training Time",
153
+ "Validation Time",
154
+ "Training MSE",
155
+ "Validation Pearson",
156
+ "Validation MSE",
157
+ "Saved?",
158
+ ],
159
+ verbose=verbose,
160
+ )
161
+
162
+ def fit(
163
+ self,
164
+ training_data,
165
+ optimizer,
166
+ scheduler=None,
167
+ valid_data=None,
168
+ max_epochs=100,
169
+ batch_size=64,
170
+ validation_iter=100,
171
+ early_stopping=None,
172
+ device="cuda",
173
+ verbose=True,
174
+ ):
175
+ iteration = 0
176
+ early_stop_count = 0
177
+ best_loss = float("inf")
178
+ self.logger.start()
179
+
180
+ for epoch in range(max_epochs):
181
+ tic = time.time()
182
+
183
+ for data in training_data:
184
+ if len(data) == 4:
185
+ X, X_ctl, y, _ = data
186
+ X_ctl = X_ctl.to(device)
187
+ else:
188
+ X, y, _ = data
189
+ X_ctl = None
190
+
191
+ X, y = X.to(device), y.to(device)
192
+
193
+ # Clear the optimizer and set the model to training mode
194
+ optimizer.zero_grad()
195
+ self.train()
196
+
197
+ # Run forward pass
198
+ y_pred = self(X, X_ctl)
199
+
200
+ # Calculate loss
201
+ loss = log1pMSELoss(y_pred, torch.abs(y)).mean()
202
+
203
+ # Extract the loss for logging
204
+ loss_ = loss.item()
205
+
206
+ # Update the model
207
+ loss.backward()
208
+ optimizer.step()
209
+
210
+ # Report measures if desired
211
+ if verbose and iteration % validation_iter == 0:
212
+ train_time = time.time() - tic
213
+
214
+ with torch.no_grad():
215
+ self.eval()
216
+
217
+ tic = time.time()
218
+
219
+ # Initialize lists to store validation statistics
220
+ valid_mse = []
221
+ pred_val = []
222
+ obs_val = []
223
+
224
+ # Loop over the validation data
225
+ for data in valid_data:
226
+ if len(data) == 4:
227
+ X_val, X_ctl_val, y_val, _ = data
228
+ X_ctl_val = (X_ctl_val,)
229
+ else:
230
+ X_val, y_val, _ = data
231
+ X_ctl_val = None
232
+
233
+ y_val = torch.abs(y_val)
234
+ y_pred = predict(
235
+ self,
236
+ X_val,
237
+ args=X_ctl_val,
238
+ batch_size=batch_size,
239
+ device=device,
240
+ )
241
+ obs_val.append(y_val)
242
+ pred_val.append(y_pred)
243
+ valid_mse.append(log1pMSELoss(y_val, y_pred))
244
+
245
+ val_corr = pearson_corr(
246
+ torch.cat(pred_val).squeeze(),
247
+ torch.log(torch.cat(obs_val).squeeze() + 1),
248
+ )
249
+ valid_loss = torch.cat(valid_mse).mean()
250
+
251
+ valid_time = time.time() - tic
252
+
253
+ self.logger.add(
254
+ [
255
+ epoch,
256
+ iteration,
257
+ train_time,
258
+ valid_time,
259
+ loss_,
260
+ np.nan_to_num(val_corr).item(),
261
+ valid_loss.item(),
262
+ (valid_loss < best_loss).item(),
263
+ ]
264
+ )
265
+
266
+ self.logger.save(f"{self.name}.log")
267
+
268
+ # Save the model if it is the best so far
269
+ if valid_loss < best_loss:
270
+ torch.save(self.state_dict(), f"{self.name}.torch")
271
+ torch.save(
272
+ {
273
+ "early_stop_count": early_stop_count,
274
+ "epoch": epoch,
275
+ "optimizer_state_dict": optimizer.state_dict(),
276
+ },
277
+ f"{self.name}.checkpoint.torch",
278
+ )
279
+ best_loss = valid_loss
280
+ early_stop_count = 0
281
+ else:
282
+ early_stop_count += 1
283
+
284
+ if early_stopping is not None and early_stop_count >= early_stopping:
285
+ break
286
+
287
+ iteration += 1
288
+
289
+ if early_stopping is not None and early_stop_count >= early_stopping:
290
+ break
291
+ if scheduler is not None:
292
+ scheduler.step()
293
+
294
+ torch.save(self, f"{self.name}.final.torch")
@@ -0,0 +1,357 @@
1
+ # clipnet_tensorflow.py
2
+ # Author: Adam He <adamyhe@gmail.com>
3
+
4
+ """
5
+ A class for importing CLIPNET models trained in TensorFlow into PyTorch.
6
+ """
7
+
8
+ import torch
9
+
10
+
11
+ def _namer(prefix, suffix):
12
+ """
13
+ A small helper function to make fetching names from h5 files easier.
14
+ """
15
+ return f"{prefix}{suffix}/{prefix}{suffix}"
16
+
17
+
18
+ def _convert_w(x):
19
+ """
20
+ A small helper function to make loading weight parameters easier.
21
+ """
22
+ return torch.nn.Parameter(torch.tensor(x[:]).permute(2, 1, 0))
23
+
24
+
25
+ def _convert_b(x):
26
+ """
27
+ A small helper function to make loading bias parameters easier.
28
+ """
29
+ return torch.nn.Parameter(torch.tensor(x[:]))
30
+
31
+
32
+ def _get_tf_same_padding(kernel_size, dilation=1):
33
+ """
34
+ Returns the left and right padding for a given kernel size and dilation.
35
+ Necessary to reproduce TensorFlow's "same" padding in PyTorch.
36
+ """
37
+ total_pad = (kernel_size - 1) * dilation
38
+ pad_left = total_pad // 2
39
+ pad_right = total_pad - pad_left
40
+ return pad_left, pad_right
41
+
42
+
43
+ class AsymmetricPad(torch.nn.Module):
44
+ """
45
+ This layer manually injects asymmetric padding into a convolutional layer.
46
+ Set the padding on the convolutional layer to 0 and use this layer to
47
+ inject asymmetric padding. This reproduces TensorFlow's "same" padding in PyTorch.
48
+ """
49
+
50
+ def __init__(self, kernel_size, dilation=1):
51
+ super(AsymmetricPad, self).__init__()
52
+ self.kernel_size = kernel_size
53
+ self.dilation = dilation
54
+
55
+ def forward(self, x):
56
+ pad_left, pad_right = _get_tf_same_padding(self.kernel_size, self.dilation)
57
+ pad_layer = torch.nn.ConstantPad1d((pad_left, pad_right), 0)
58
+ return pad_layer(x)
59
+
60
+
61
+ class TwoHotToOneHot(torch.nn.Module):
62
+ """
63
+ A small wrapper to allow models trained on TwoHot data to be used on OneHot data.
64
+ """
65
+
66
+ def __init__(self, model):
67
+ super(TwoHotToOneHot, self).__init__()
68
+ self.model = model
69
+
70
+ def forward(self, X, X_ctl=None):
71
+ return self.model(X * 2, X_ctl)
72
+
73
+
74
+ class CLIPNET_TF(torch.nn.Module):
75
+ """
76
+ This is a reference implementation for CLIPNET models. It exactly matches the
77
+ architecture in the main CLIPNET TensorFlow repository and contains a method
78
+ for converting the TensorFlow weights to PyTorch. Note that this architecture
79
+ differs from the one found in clipnet_pytorch.py, which is a complete rewrite
80
+ in PyTorch and takes a lot more cues from ProCapNet/BPNet.
81
+
82
+ Parameters
83
+ ----------
84
+ counts_head_only : bool
85
+ If True, create a model with only the counts head.
86
+ Set to load "PauseNet" models, which only predict a single scalar.
87
+ """
88
+
89
+ def __init__(self, counts_head_only=False):
90
+ super(CLIPNET_TF, self).__init__()
91
+ self.n_layers = 9
92
+ self.counts_head_only = counts_head_only
93
+
94
+ self.input = torch.nn.Identity()
95
+ self.ibnorm = torch.nn.BatchNorm1d(4)
96
+ self.iconv = torch.nn.Conv1d(4, 64, kernel_size=8, padding=0)
97
+ self.ibn = torch.nn.BatchNorm1d(64)
98
+ self.irelu = torch.nn.ELU(alpha=1)
99
+ self.imp = torch.nn.MaxPool1d(2)
100
+
101
+ self.sconv = torch.nn.Conv1d(32, 128, kernel_size=4, padding=0)
102
+ self.sbnorm = torch.nn.BatchNorm1d(64)
103
+ self.srelu = torch.nn.ReLU()
104
+ self.smp = torch.nn.MaxPool1d(2)
105
+
106
+ self.rconv = torch.nn.Conv1d(64, 64, kernel_size=1, padding=0)
107
+ self.rpads = torch.nn.ModuleList(
108
+ [AsymmetricPad(kernel_size=3, dilation=2**i) for i in range(self.n_layers)]
109
+ )
110
+ self.rconvs = torch.nn.ModuleList(
111
+ [
112
+ torch.nn.Conv1d(64, 64, kernel_size=3, padding=0, dilation=2**i)
113
+ for i in range(self.n_layers)
114
+ ]
115
+ )
116
+ self.rbnorms = torch.nn.ModuleList(
117
+ [torch.nn.BatchNorm1d(64) for i in range(self.n_layers)]
118
+ )
119
+ self.rrelus = torch.nn.ModuleList(
120
+ [torch.nn.ReLU() for i in range(self.n_layers)]
121
+ )
122
+ self.skipbnorms = torch.nn.ModuleList(
123
+ [torch.nn.BatchNorm1d(64) for i in range(self.n_layers)]
124
+ )
125
+ self.skiprelus = torch.nn.ModuleList(
126
+ [torch.nn.ReLU() for i in range(self.n_layers)]
127
+ )
128
+ self.skipmp = torch.nn.MaxPool1d(2)
129
+
130
+ if not self.counts_head_only:
131
+ self.plinear = torch.nn.Linear(7872, 1000)
132
+ self.pbnorm = torch.nn.BatchNorm1d(1000)
133
+ self.prelu = torch.nn.ReLU()
134
+
135
+ self.cavgpool = torch.nn.AdaptiveAvgPool1d(1)
136
+ self.clinear = torch.nn.Linear(64, 1)
137
+ self.cbnorm = torch.nn.BatchNorm1d(1)
138
+ self.crelu = torch.nn.ReLU()
139
+
140
+ def forward(self, X, X_ctl=None):
141
+ """
142
+ A forward pass of the model.
143
+
144
+ This method takes in a nucleotide sequence X and makes predictions
145
+ for the profile and for the counts.
146
+
147
+ Parameters
148
+ ----------
149
+ X: torch.tensor, shape=(batch_size, 4, length)
150
+ The two-hot encoded batch of sequences.
151
+ X_ctl: None
152
+ Should be None for compatibility with BPNet wrappers.
153
+
154
+ Returns
155
+ -------
156
+ y_profile: torch.tensor, shape=(batch_size, out_length * n_strands)
157
+ The output predictions for each strand.
158
+ y_counts: torch.tensor, shape=(batch_size, 1)
159
+ The output predictions for the counts (in RPM scale).
160
+ """
161
+ # input
162
+ X = self.input(X)
163
+ X = self.ibnorm(X)
164
+ # Apply first convolutional layer
165
+ X = self.iconv(X)
166
+ X = self.ibn(X)
167
+ X = self.irelu(X)
168
+ X = self.imp(X)
169
+ # Apply second convolutional layer
170
+ X = self.sconv(X)
171
+ X = self.sbnorm(X)
172
+ X = self.srelu(X)
173
+ X = self.smp(X)
174
+ # Apply third convolutional layer (for shape compatibility)
175
+ X = self.rconv(X)
176
+ # Apply dilated residual layers
177
+ for i in range(self.n_layers):
178
+ # Dilated convolution
179
+ X_conv = self.rpads[i](X)
180
+ X_conv = self.rconvs[i](X_conv)
181
+ X_conv = self.rbnorms[i](X_conv)
182
+ X_conv = self.rrelus[i](X_conv)
183
+ # Skip connection
184
+ X = torch.add(X, X_conv)
185
+ X = self.skipbnorms[i](X)
186
+ X = self.skiprelus[i](X)
187
+ # Max pooling after residual layers
188
+ X = self.skipmp(X)
189
+ # Count prediction
190
+ y_counts = self.cavgpool(X).squeeze(-1)
191
+ y_counts = self.clinear(y_counts)
192
+ y_counts = self.cbnorm(y_counts)
193
+ y_counts = self.crelu(y_counts)
194
+ if self.counts_head_only:
195
+ return y_counts
196
+ else:
197
+ # Profile prediction
198
+ # We need to manually permute and flatten since the pytorch
199
+ # conv layers output a tensor of shape (batch, channels, steps), but
200
+ # the linear weights expect a tensor of shape (batch, steps, channels)
201
+ y_profile = X.permute(0, 2, 1).reshape(X.shape[0], -1)
202
+ y_profile = self.plinear(y_profile)
203
+ y_profile = self.pbnorm(y_profile)
204
+ y_profile = self.prelu(y_profile)
205
+ return y_profile, y_counts
206
+
207
+ @classmethod
208
+ def from_tf(cls, filename, counts_head_only=False):
209
+ """Loads a model from the CLIPNET TensorFlow format.
210
+
211
+ Note that this method does not require the installation of TensorFlow and
212
+ differs in architecture from the PyTorch implementation in this repository.
213
+ Notably, CLIPNET_TF models take in 1000 bp sequence inputs and yield 500 bp
214
+ predictions.
215
+
216
+ See https://github.com/Danko-Lab/clipnet for more details.
217
+
218
+ Parameters
219
+ ----------
220
+ filename: str
221
+ The name of the h5 file that stores the trained model parameters.
222
+ counts_head_only: bool
223
+ Use this flag to load a model with only the counts head. This is mostly
224
+ used for "PauseNet" models, which trim the profile head and fine-tune
225
+ the counts head.
226
+
227
+ Returns
228
+ -------
229
+ model: CLIPNET_TF
230
+ A CLIPNET tensorflow model compatible with this repository in PyTorch.
231
+ """
232
+ import h5py
233
+
234
+ h5 = h5py.File(filename, "r")
235
+ w = h5["model_weights"]
236
+ k, b, mm, mv = "kernel:0", "bias:0", "moving_mean:0", "moving_variance:0"
237
+
238
+ model = CLIPNET_TF(counts_head_only=counts_head_only)
239
+
240
+ ibnorm = _namer("batch_normalization", "")
241
+ model.ibnorm.weight.data = _convert_b(w[ibnorm]["gamma:0"])
242
+ model.ibnorm.bias.data = _convert_b(w[ibnorm]["beta:0"])
243
+ model.ibnorm.running_mean = _convert_b(w[ibnorm][mm])
244
+ model.ibnorm.running_var = _convert_b(w[ibnorm][mv])
245
+ model.ibnorm.running_mean.requires_grad = False
246
+ model.ibnorm.running_var.requires_grad = False
247
+ model.ibnorm.eps = 0.001
248
+ model.ibnorm.momentum = 0.99
249
+
250
+ iconv = _namer("conv1d", "")
251
+ model.iconv.weight.data = _convert_w(w[iconv][k])
252
+ model.iconv.bias.data = _convert_b(w[iconv][b])
253
+
254
+ ibn = _namer("batch_normalization", "_1")
255
+ model.ibn.weight.data = _convert_b(w[ibn]["gamma:0"])
256
+ model.ibn.bias.data = _convert_b(w[ibn]["beta:0"])
257
+ model.ibn.running_mean = _convert_b(w[ibn][mm])
258
+ model.ibn.running_var = _convert_b(w[ibn][mv])
259
+ model.ibn.running_mean.requires_grad = False
260
+ model.ibn.running_var.requires_grad = False
261
+ model.ibn.eps = 0.001
262
+ model.ibn.momentum = 0.99
263
+
264
+ sconv = _namer("conv1d", "_1")
265
+ model.sconv.weight.data = _convert_w(w[sconv][k])
266
+ model.sconv.bias.data = _convert_b(w[sconv][b])
267
+
268
+ sbn = _namer("batch_normalization", "_2")
269
+ model.sbnorm.weight.data = _convert_b(w[sbn]["gamma:0"])
270
+ model.sbnorm.bias.data = _convert_b(w[sbn]["beta:0"])
271
+ model.sbnorm.running_mean = _convert_b(w[sbn][mm])
272
+ model.sbnorm.running_var = _convert_b(w[sbn][mv])
273
+ model.sbnorm.running_mean.requires_grad = False
274
+ model.sbnorm.running_var.requires_grad = False
275
+ model.sbnorm.eps = 0.001
276
+ model.sbnorm.momentum = 0.99
277
+
278
+ rconv = _namer("conv1d", "_2")
279
+ model.rconv.weight.data = _convert_w(w[rconv][k])
280
+ model.rconv.bias.data = _convert_b(w[rconv][b])
281
+
282
+ for i in range(1, 9 + 1):
283
+ rconv = _namer("conv1d", f"_{i + 2}")
284
+ model.rconvs[i - 1].weight.data = _convert_w(w[rconv][k])
285
+ model.rconvs[i - 1].bias.data = _convert_b(w[rconv][b])
286
+
287
+ rbn = _namer("batch_normalization", f"_{(2 * i - 1) + 2}")
288
+ model.rbnorms[i - 1].weight.data = _convert_b(w[rbn]["gamma:0"])
289
+ model.rbnorms[i - 1].bias.data = _convert_b(w[rbn]["beta:0"])
290
+ model.rbnorms[i - 1].running_mean = _convert_b(w[rbn][mm])
291
+ model.rbnorms[i - 1].running_var = _convert_b(w[rbn][mv])
292
+ model.rbnorms[i - 1].running_mean.requires_grad = False
293
+ model.rbnorms[i - 1].running_var.requires_grad = False
294
+ model.rbnorms[i - 1].eps = 0.001
295
+ model.rbnorms[i - 1].momentum = 0.99
296
+
297
+ skipbn = _namer("batch_normalization", f"_{(2 * i - 1) + 3}")
298
+ model.skipbnorms[i - 1].weight.data = _convert_b(w[skipbn]["gamma:0"])
299
+ model.skipbnorms[i - 1].bias.data = _convert_b(w[skipbn]["beta:0"])
300
+ model.skipbnorms[i - 1].running_mean = _convert_b(w[skipbn][mm])
301
+ model.skipbnorms[i - 1].running_var = _convert_b(w[skipbn][mv])
302
+ model.skipbnorms[i - 1].running_mean.requires_grad = False
303
+ model.skipbnorms[i - 1].running_var.requires_grad = False
304
+ model.skipbnorms[i - 1].eps = 0.001
305
+ model.skipbnorms[i - 1].momentum = 0.99
306
+
307
+ if counts_head_only:
308
+ clinear = _namer("new_dense", "")
309
+ model.clinear.weight.data = torch.nn.Parameter(
310
+ torch.tensor(w[clinear][k][:].T)
311
+ )
312
+ model.clinear.bias.data = _convert_b(w[clinear][b])
313
+
314
+ cbn = _namer("new_batch_normalization", "")
315
+ model.cbnorm.weight.data = _convert_b(w[cbn]["gamma:0"])
316
+ model.cbnorm.bias.data = _convert_b(w[cbn]["beta:0"])
317
+ model.cbnorm.running_mean = _convert_b(w[cbn][mm])
318
+ model.cbnorm.running_var = _convert_b(w[cbn][mv])
319
+ model.cbnorm.running_mean.requires_grad = False
320
+ model.cbnorm.running_var.requires_grad = False
321
+ model.cbnorm.eps = 0.001
322
+ model.cbnorm.momentum = 0.99
323
+
324
+ else:
325
+ plinear = _namer("dense", "")
326
+ model.plinear.weight.data = torch.nn.Parameter(
327
+ torch.tensor(w[plinear][k][:].T)
328
+ )
329
+ model.plinear.bias.data = _convert_b(w[plinear][b])
330
+
331
+ pbn = _namer("batch_normalization", "_21")
332
+ model.pbnorm.weight.data = _convert_b(w[pbn]["gamma:0"])
333
+ model.pbnorm.bias.data = _convert_b(w[pbn]["beta:0"])
334
+ model.pbnorm.running_mean = _convert_b(w[pbn][mm])
335
+ model.pbnorm.running_var = _convert_b(w[pbn][mv])
336
+ model.pbnorm.running_mean.requires_grad = False
337
+ model.pbnorm.running_var.requires_grad = False
338
+ model.pbnorm.eps = 0.001
339
+ model.pbnorm.momentum = 0.99
340
+
341
+ clinear = _namer("dense", "_1")
342
+ model.clinear.weight.data = torch.nn.Parameter(
343
+ torch.tensor(w[clinear][k][:].T)
344
+ )
345
+ model.clinear.bias.data = _convert_b(w[clinear][b])
346
+
347
+ cbn = _namer("batch_normalization", "_22")
348
+ model.cbnorm.weight.data = _convert_b(w[cbn]["gamma:0"])
349
+ model.cbnorm.bias.data = _convert_b(w[cbn]["beta:0"])
350
+ model.cbnorm.running_mean = _convert_b(w[cbn][mm])
351
+ model.cbnorm.running_var = _convert_b(w[cbn][mv])
352
+ model.cbnorm.running_mean.requires_grad = False
353
+ model.cbnorm.running_var.requires_grad = False
354
+ model.cbnorm.eps = 0.001
355
+ model.cbnorm.momentum = 0.99
356
+
357
+ return model