pertlens 0.1.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.
- pertlens/__init__.py +67 -0
- pertlens/api.py +515 -0
- pertlens/data.py +211 -0
- pertlens/engine.py +199 -0
- pertlens/evaluation.py +323 -0
- pertlens/kre.py +153 -0
- pertlens/losses.py +117 -0
- pertlens/masking.py +33 -0
- pertlens/mce.py +186 -0
- pertlens/pipeline.py +249 -0
- pertlens/utils.py +89 -0
- pertlens-0.1.0.dist-info/METADATA +123 -0
- pertlens-0.1.0.dist-info/RECORD +15 -0
- pertlens-0.1.0.dist-info/WHEEL +5 -0
- pertlens-0.1.0.dist-info/top_level.txt +1 -0
pertlens/__init__.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from .mce import MaskedContextEncoder, ScalarEncoder, DoseEncoder
|
|
2
|
+
from .data import (
|
|
3
|
+
PertLensDataset,
|
|
4
|
+
build_pertlens_loader,
|
|
5
|
+
split_train_val_arrays,
|
|
6
|
+
make_pert_labels,
|
|
7
|
+
normalize_perturbations,
|
|
8
|
+
)
|
|
9
|
+
from .kre import (
|
|
10
|
+
gaussian_kernel,
|
|
11
|
+
kernel_ridge_regression,
|
|
12
|
+
kernel_ridge_regression_eq,
|
|
13
|
+
predict_krr,
|
|
14
|
+
fit_kre_per_gene,
|
|
15
|
+
predict_kre_per_gene,
|
|
16
|
+
)
|
|
17
|
+
from .api import (
|
|
18
|
+
train_mce,
|
|
19
|
+
fit_kre,
|
|
20
|
+
predict_pertlens,
|
|
21
|
+
load_mce,
|
|
22
|
+
)
|
|
23
|
+
from .pipeline import PertLens
|
|
24
|
+
from .losses import compute_mce_loss, response_kernel_geometry_matching_loss
|
|
25
|
+
from .evaluation import (
|
|
26
|
+
compute_metrics_adamson,
|
|
27
|
+
convert_to_serializable,
|
|
28
|
+
mean_expr_to_torch,
|
|
29
|
+
compute_metrics_sciplex3,
|
|
30
|
+
compute_metrics_pbmc,
|
|
31
|
+
)
|
|
32
|
+
from .utils import compress_by_perturbation
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
# MCE
|
|
36
|
+
"MaskedContextEncoder",
|
|
37
|
+
"ScalarEncoder",
|
|
38
|
+
"DoseEncoder",
|
|
39
|
+
"PertLens",
|
|
40
|
+
# data
|
|
41
|
+
"PertLensDataset",
|
|
42
|
+
"build_pertlens_loader",
|
|
43
|
+
"split_train_val_arrays",
|
|
44
|
+
"make_pert_labels",
|
|
45
|
+
"normalize_perturbations",
|
|
46
|
+
"compress_by_perturbation",
|
|
47
|
+
# KRE
|
|
48
|
+
"gaussian_kernel",
|
|
49
|
+
"kernel_ridge_regression",
|
|
50
|
+
"kernel_ridge_regression_eq",
|
|
51
|
+
"predict_krr",
|
|
52
|
+
"fit_kre_per_gene",
|
|
53
|
+
"predict_kre_per_gene",
|
|
54
|
+
# end-to-end API
|
|
55
|
+
"train_mce",
|
|
56
|
+
"fit_kre",
|
|
57
|
+
"predict_pertlens",
|
|
58
|
+
"load_mce",
|
|
59
|
+
"compute_mce_loss",
|
|
60
|
+
"response_kernel_geometry_matching_loss",
|
|
61
|
+
# evaluation
|
|
62
|
+
"compute_metrics_adamson",
|
|
63
|
+
"convert_to_serializable",
|
|
64
|
+
"mean_expr_to_torch",
|
|
65
|
+
"compute_metrics_sciplex3",
|
|
66
|
+
"compute_metrics_pbmc",
|
|
67
|
+
]
|
pertlens/api.py
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import torch
|
|
5
|
+
from tqdm.auto import trange
|
|
6
|
+
|
|
7
|
+
from .data import (
|
|
8
|
+
build_pertlens_loader,
|
|
9
|
+
normalize_perturbations,
|
|
10
|
+
split_train_val_arrays,
|
|
11
|
+
)
|
|
12
|
+
from .engine import evaluate_masked_loss, train_one_epoch
|
|
13
|
+
from .kre import fit_kre_per_gene, predict_kre_per_gene
|
|
14
|
+
from .losses import validate_bridge_config
|
|
15
|
+
from .mce import MaskedContextEncoder
|
|
16
|
+
from .utils import (
|
|
17
|
+
ensure_dir,
|
|
18
|
+
get_device,
|
|
19
|
+
load_checkpoint,
|
|
20
|
+
save_checkpoint,
|
|
21
|
+
set_seed,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _infer_perturbation_config(perturbations):
|
|
26
|
+
n_perts = len(perturbations)
|
|
27
|
+
first_array = perturbations["P1"]
|
|
28
|
+
if hasattr(first_array, "shape"):
|
|
29
|
+
perturbation_dim = first_array.shape[1]
|
|
30
|
+
else:
|
|
31
|
+
perturbation_dim = len(first_array[0])
|
|
32
|
+
return perturbation_dim, n_perts
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _perturbations_to_torch(perturbations, device=None):
|
|
36
|
+
tensor_perturbations = {}
|
|
37
|
+
for pert_key, array in perturbations.items():
|
|
38
|
+
tensor = torch.as_tensor(array, dtype=torch.float32)
|
|
39
|
+
if device is not None:
|
|
40
|
+
tensor = tensor.to(device)
|
|
41
|
+
tensor_perturbations[pert_key] = tensor
|
|
42
|
+
return tensor_perturbations
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def train_mce(
|
|
46
|
+
x_ctrl_train,
|
|
47
|
+
perturbations_train,
|
|
48
|
+
x_true_train,
|
|
49
|
+
x_ctrl_val=None,
|
|
50
|
+
perturbations_val=None,
|
|
51
|
+
x_true_val=None,
|
|
52
|
+
dose_train=None,
|
|
53
|
+
dose_val=None,
|
|
54
|
+
val_fraction=0.1,
|
|
55
|
+
stratify_val=True,
|
|
56
|
+
save_dir=None,
|
|
57
|
+
save_name="best_mce.pt",
|
|
58
|
+
seed=42,
|
|
59
|
+
device=None,
|
|
60
|
+
# model
|
|
61
|
+
encoder_class=None,
|
|
62
|
+
d_model=128,
|
|
63
|
+
n_heads=4,
|
|
64
|
+
n_layers=2,
|
|
65
|
+
dropout=0.2,
|
|
66
|
+
logvar_min=-4.0,
|
|
67
|
+
logvar_max=4.0,
|
|
68
|
+
use_dose=False,
|
|
69
|
+
dose_n_freqs=32,
|
|
70
|
+
# training
|
|
71
|
+
batch_size=8,
|
|
72
|
+
num_workers=0,
|
|
73
|
+
epochs=1000,
|
|
74
|
+
lr=3e-4,
|
|
75
|
+
weight_decay=1e-3,
|
|
76
|
+
grad_clip=1.0,
|
|
77
|
+
min_mask_ratio=0.6,
|
|
78
|
+
max_mask_ratio=1.0,
|
|
79
|
+
all_mask_prob=0.4,
|
|
80
|
+
lambda_mse=0.25,
|
|
81
|
+
lambda_dir=0.2,
|
|
82
|
+
verbose=True,
|
|
83
|
+
progress_bar=True,
|
|
84
|
+
print_best=False,
|
|
85
|
+
lambda_bridge=0.01,
|
|
86
|
+
bridge_n_genes=256,
|
|
87
|
+
bridge_seed=42,
|
|
88
|
+
bridge_eps=1e-8,
|
|
89
|
+
):
|
|
90
|
+
"""Train the MCE with masked reconstruction and RKGM loss."""
|
|
91
|
+
validate_bridge_config(lambda_bridge, bridge_n_genes, bridge_eps)
|
|
92
|
+
set_seed(seed)
|
|
93
|
+
device = get_device(device)
|
|
94
|
+
bridge_generator = None
|
|
95
|
+
if lambda_bridge > 0:
|
|
96
|
+
bridge_generator = torch.Generator(device="cpu").manual_seed(bridge_seed)
|
|
97
|
+
|
|
98
|
+
perturbations_train = normalize_perturbations(perturbations_train)
|
|
99
|
+
perturbation_dim, n_perts = _infer_perturbation_config(
|
|
100
|
+
perturbations_train
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
val_provided = (
|
|
104
|
+
x_ctrl_val is not None
|
|
105
|
+
and perturbations_val is not None
|
|
106
|
+
and x_true_val is not None
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
if not val_provided:
|
|
110
|
+
if val_fraction is not None and val_fraction > 0:
|
|
111
|
+
if verbose:
|
|
112
|
+
print(
|
|
113
|
+
f"[PertLens] No validation set provided. "
|
|
114
|
+
f"Splitting {val_fraction:.0%} of training data as validation."
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
split_result = split_train_val_arrays(
|
|
118
|
+
x_ctrl=x_ctrl_train,
|
|
119
|
+
perturbations=perturbations_train,
|
|
120
|
+
x_true=x_true_train,
|
|
121
|
+
dose=dose_train,
|
|
122
|
+
val_fraction=val_fraction,
|
|
123
|
+
seed=seed,
|
|
124
|
+
stratify_by_pert=stratify_val,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
x_ctrl_train = split_result[0]
|
|
128
|
+
perturbations_train = split_result[1]
|
|
129
|
+
x_true_train = split_result[2]
|
|
130
|
+
x_ctrl_val = split_result[3]
|
|
131
|
+
perturbations_val = split_result[4]
|
|
132
|
+
x_true_val = split_result[5]
|
|
133
|
+
|
|
134
|
+
if dose_train is not None and len(split_result) >= 8:
|
|
135
|
+
dose_train = split_result[6]
|
|
136
|
+
dose_val = split_result[7]
|
|
137
|
+
|
|
138
|
+
val_provided = True
|
|
139
|
+
else:
|
|
140
|
+
if verbose:
|
|
141
|
+
print("[PertLens] No validation set will be used.")
|
|
142
|
+
|
|
143
|
+
if val_provided:
|
|
144
|
+
perturbations_val = normalize_perturbations(perturbations_val)
|
|
145
|
+
|
|
146
|
+
n_genes = x_ctrl_train.shape[1]
|
|
147
|
+
|
|
148
|
+
if verbose:
|
|
149
|
+
print("[PertLens] MCE training data summary:")
|
|
150
|
+
print(f" train x_ctrl: {x_ctrl_train.shape}")
|
|
151
|
+
print(f" train x_true: {x_true_train.shape}")
|
|
152
|
+
print(f" perturbation_dim: {perturbation_dim}")
|
|
153
|
+
print(f" n_perts: {n_perts}")
|
|
154
|
+
if val_provided:
|
|
155
|
+
print(f" val x_ctrl: {x_ctrl_val.shape}")
|
|
156
|
+
print(f" val x_true: {x_true_val.shape}")
|
|
157
|
+
print(f" n_genes: {n_genes}")
|
|
158
|
+
print(f" device: {device}")
|
|
159
|
+
print(f" d_model: {d_model}")
|
|
160
|
+
|
|
161
|
+
train_loader = build_pertlens_loader(
|
|
162
|
+
x_ctrl=x_ctrl_train,
|
|
163
|
+
perturbations=perturbations_train,
|
|
164
|
+
x_true=x_true_train,
|
|
165
|
+
dose=dose_train,
|
|
166
|
+
batch_size=batch_size,
|
|
167
|
+
shuffle=True,
|
|
168
|
+
num_workers=num_workers,
|
|
169
|
+
pin_memory=(device == "cuda"),
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
if val_provided:
|
|
173
|
+
val_loader = build_pertlens_loader(
|
|
174
|
+
x_ctrl=x_ctrl_val,
|
|
175
|
+
perturbations=perturbations_val,
|
|
176
|
+
x_true=x_true_val,
|
|
177
|
+
dose=dose_val,
|
|
178
|
+
batch_size=batch_size,
|
|
179
|
+
shuffle=False,
|
|
180
|
+
num_workers=num_workers,
|
|
181
|
+
pin_memory=(device == "cuda"),
|
|
182
|
+
)
|
|
183
|
+
else:
|
|
184
|
+
val_loader = None
|
|
185
|
+
|
|
186
|
+
model_kwargs = {
|
|
187
|
+
"n_genes": n_genes,
|
|
188
|
+
"perturbation_dim": perturbation_dim,
|
|
189
|
+
"n_perts": n_perts,
|
|
190
|
+
"d_model": d_model,
|
|
191
|
+
"n_heads": n_heads,
|
|
192
|
+
"n_layers": n_layers,
|
|
193
|
+
"dropout": dropout,
|
|
194
|
+
"logvar_min": logvar_min,
|
|
195
|
+
"logvar_max": logvar_max,
|
|
196
|
+
"use_dose": use_dose,
|
|
197
|
+
"dose_n_freqs": dose_n_freqs,
|
|
198
|
+
}
|
|
199
|
+
model_cls = encoder_class if encoder_class is not None else MaskedContextEncoder
|
|
200
|
+
if encoder_class is not None:
|
|
201
|
+
model_kwargs.pop("n_perts", None)
|
|
202
|
+
model = model_cls(**model_kwargs).to(device)
|
|
203
|
+
|
|
204
|
+
optimizer = torch.optim.AdamW(
|
|
205
|
+
model.parameters(),
|
|
206
|
+
lr=lr,
|
|
207
|
+
weight_decay=weight_decay,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
config = {
|
|
211
|
+
"model_kwargs": model_kwargs,
|
|
212
|
+
"training": {
|
|
213
|
+
"seed": seed,
|
|
214
|
+
"batch_size": batch_size,
|
|
215
|
+
"num_workers": num_workers,
|
|
216
|
+
"epochs": epochs,
|
|
217
|
+
"lr": lr,
|
|
218
|
+
"weight_decay": weight_decay,
|
|
219
|
+
"grad_clip": grad_clip,
|
|
220
|
+
"min_mask_ratio": min_mask_ratio,
|
|
221
|
+
"max_mask_ratio": max_mask_ratio,
|
|
222
|
+
"all_mask_prob": all_mask_prob,
|
|
223
|
+
"lambda_mse": lambda_mse,
|
|
224
|
+
"lambda_dir": lambda_dir,
|
|
225
|
+
"lambda_bridge": lambda_bridge,
|
|
226
|
+
"bridge_n_genes": bridge_n_genes,
|
|
227
|
+
"bridge_seed": bridge_seed,
|
|
228
|
+
"bridge_eps": bridge_eps,
|
|
229
|
+
"val_fraction": val_fraction,
|
|
230
|
+
"stratify_val": stratify_val,
|
|
231
|
+
"progress_bar": progress_bar,
|
|
232
|
+
"print_best": print_best,
|
|
233
|
+
},
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
history = []
|
|
237
|
+
best_score = float("inf")
|
|
238
|
+
best_path = None
|
|
239
|
+
best_epoch = None
|
|
240
|
+
|
|
241
|
+
if save_dir is not None:
|
|
242
|
+
ensure_dir(save_dir)
|
|
243
|
+
best_path = os.path.join(save_dir, save_name)
|
|
244
|
+
|
|
245
|
+
epoch_iter = trange(
|
|
246
|
+
1,
|
|
247
|
+
epochs + 1,
|
|
248
|
+
desc="[PertLens] Training MCE",
|
|
249
|
+
disable=not progress_bar,
|
|
250
|
+
leave=True,
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
for epoch in epoch_iter:
|
|
254
|
+
train_logs = train_one_epoch(
|
|
255
|
+
model=model,
|
|
256
|
+
dataloader=train_loader,
|
|
257
|
+
optimizer=optimizer,
|
|
258
|
+
device=device,
|
|
259
|
+
min_mask_ratio=min_mask_ratio,
|
|
260
|
+
max_mask_ratio=max_mask_ratio,
|
|
261
|
+
all_mask_prob=all_mask_prob,
|
|
262
|
+
lambda_mse=lambda_mse,
|
|
263
|
+
lambda_dir=lambda_dir,
|
|
264
|
+
grad_clip=grad_clip,
|
|
265
|
+
lambda_bridge=lambda_bridge,
|
|
266
|
+
bridge_n_genes=bridge_n_genes,
|
|
267
|
+
bridge_eps=bridge_eps,
|
|
268
|
+
bridge_generator=bridge_generator,
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
if val_loader is not None:
|
|
272
|
+
val_logs = evaluate_masked_loss(
|
|
273
|
+
model=model,
|
|
274
|
+
dataloader=val_loader,
|
|
275
|
+
device=device,
|
|
276
|
+
mask_ratio=1.0,
|
|
277
|
+
lambda_mse=lambda_mse,
|
|
278
|
+
lambda_dir=lambda_dir,
|
|
279
|
+
)
|
|
280
|
+
score = val_logs["loss"]
|
|
281
|
+
else:
|
|
282
|
+
val_logs = {}
|
|
283
|
+
score = train_logs.get("loss_base", train_logs["loss"])
|
|
284
|
+
|
|
285
|
+
epoch_record = {
|
|
286
|
+
"epoch": epoch,
|
|
287
|
+
"train": train_logs,
|
|
288
|
+
"val": val_logs,
|
|
289
|
+
}
|
|
290
|
+
history.append(epoch_record)
|
|
291
|
+
|
|
292
|
+
postfix = {"train": f"{train_logs['loss']:.4f}"}
|
|
293
|
+
if "loss_bridge" in train_logs:
|
|
294
|
+
postfix["bridge"] = f"{train_logs['loss_bridge']:.4f}"
|
|
295
|
+
postfix["bridge_genes"] = f"{train_logs['bridge_genes']:.0f}"
|
|
296
|
+
if val_loader is not None:
|
|
297
|
+
postfix["val"] = f"{val_logs['loss']:.4f}"
|
|
298
|
+
postfix["best"] = (
|
|
299
|
+
f"{best_score:.4f}" if best_score < float("inf") else "inf"
|
|
300
|
+
)
|
|
301
|
+
epoch_iter.set_postfix(postfix)
|
|
302
|
+
|
|
303
|
+
if score < best_score:
|
|
304
|
+
best_score = score
|
|
305
|
+
best_epoch = epoch
|
|
306
|
+
if best_path is not None:
|
|
307
|
+
save_checkpoint(
|
|
308
|
+
path=best_path,
|
|
309
|
+
model=model,
|
|
310
|
+
optimizer=optimizer,
|
|
311
|
+
epoch=epoch,
|
|
312
|
+
config=config,
|
|
313
|
+
history=history,
|
|
314
|
+
)
|
|
315
|
+
if print_best:
|
|
316
|
+
msg = (
|
|
317
|
+
f"[PertLens] Epoch {epoch:03d}: saved best MCE "
|
|
318
|
+
f"with score={best_score:.6f} -> {best_path}"
|
|
319
|
+
)
|
|
320
|
+
if progress_bar:
|
|
321
|
+
epoch_iter.write(msg)
|
|
322
|
+
elif verbose:
|
|
323
|
+
print(msg)
|
|
324
|
+
|
|
325
|
+
if verbose and not progress_bar:
|
|
326
|
+
bridge_str = (
|
|
327
|
+
f" | bridge={train_logs['loss_bridge']:.6f}"
|
|
328
|
+
f" | bridge_genes={train_logs['bridge_genes']:.1f}"
|
|
329
|
+
f" | bridge_active={train_logs['bridge_active']:.2f}"
|
|
330
|
+
if "loss_bridge" in train_logs else ""
|
|
331
|
+
)
|
|
332
|
+
val_str = (
|
|
333
|
+
f"val_loss={val_logs['loss']:.6f}"
|
|
334
|
+
if val_loader is not None
|
|
335
|
+
else ""
|
|
336
|
+
)
|
|
337
|
+
print(
|
|
338
|
+
f"[PertLens] Epoch {epoch:03d} | "
|
|
339
|
+
f"train_loss={train_logs['loss']:.6f} | {val_str} | "
|
|
340
|
+
f"best={best_score:.6f}{bridge_str}"
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
if best_path is not None and os.path.exists(best_path):
|
|
344
|
+
ckpt = load_checkpoint(best_path, map_location=device)
|
|
345
|
+
model.load_state_dict(ckpt["model_state"])
|
|
346
|
+
model.eval()
|
|
347
|
+
if verbose:
|
|
348
|
+
print(f"[PertLens] Loaded best MCE from {best_path}")
|
|
349
|
+
print(
|
|
350
|
+
f"[PertLens] Best epoch: {best_epoch}, "
|
|
351
|
+
f"Best score: {best_score:.6f}"
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
return model, history
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def fit_kre(
|
|
358
|
+
mce,
|
|
359
|
+
x_ctrl_train,
|
|
360
|
+
perturbations_train,
|
|
361
|
+
x_true_train,
|
|
362
|
+
dose_train=None,
|
|
363
|
+
lambda_=0.001,
|
|
364
|
+
sigma=20.0,
|
|
365
|
+
use_eq=False,
|
|
366
|
+
batch_size=8,
|
|
367
|
+
device=None,
|
|
368
|
+
verbose=True,
|
|
369
|
+
):
|
|
370
|
+
"""Extract fully masked MCE features and fit one KRE model per gene."""
|
|
371
|
+
device = get_device(device)
|
|
372
|
+
mce = mce.to(device)
|
|
373
|
+
mce.eval()
|
|
374
|
+
perturbations_train = normalize_perturbations(perturbations_train)
|
|
375
|
+
|
|
376
|
+
n_train = x_ctrl_train.shape[0]
|
|
377
|
+
|
|
378
|
+
if verbose:
|
|
379
|
+
print("[PertLens] Extracting MCE features for KRE fitting...")
|
|
380
|
+
|
|
381
|
+
x_ctrl_t = torch.as_tensor(x_ctrl_train, dtype=torch.float32)
|
|
382
|
+
perturbations_t = _perturbations_to_torch(perturbations_train)
|
|
383
|
+
|
|
384
|
+
if dose_train is not None:
|
|
385
|
+
dose_t = torch.as_tensor(
|
|
386
|
+
np.asarray(dose_train).flatten(), dtype=torch.float32
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
all_features = []
|
|
390
|
+
|
|
391
|
+
with torch.no_grad():
|
|
392
|
+
for start in range(0, n_train, batch_size):
|
|
393
|
+
end = min(start + batch_size, n_train)
|
|
394
|
+
xb = x_ctrl_t[start:end].to(device)
|
|
395
|
+
|
|
396
|
+
perturbations_batch = {
|
|
397
|
+
pert_key: tensor[start:end].to(device)
|
|
398
|
+
for pert_key, tensor in perturbations_t.items()
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
feat_kwargs = dict(
|
|
402
|
+
x_ctrl=xb,
|
|
403
|
+
perturbations=perturbations_batch,
|
|
404
|
+
)
|
|
405
|
+
if dose_train is not None:
|
|
406
|
+
feat_kwargs["dose"] = dose_t[start:end].to(device).unsqueeze(-1)
|
|
407
|
+
|
|
408
|
+
h = mce.extract_features(**feat_kwargs)
|
|
409
|
+
all_features.append(h.detach().cpu().numpy())
|
|
410
|
+
|
|
411
|
+
features_train = np.concatenate(all_features, axis=0)
|
|
412
|
+
|
|
413
|
+
method_name = "KRE-up" if use_eq else "KRE"
|
|
414
|
+
if verbose:
|
|
415
|
+
print(f"[PertLens] Feature shape: {features_train.shape}")
|
|
416
|
+
print(
|
|
417
|
+
f"[PertLens] Fitting {method_name} per gene "
|
|
418
|
+
f"(lambda={lambda_}, sigma={sigma})..."
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
kre_models = fit_kre_per_gene(
|
|
422
|
+
features=features_train,
|
|
423
|
+
expressions=np.asarray(x_true_train),
|
|
424
|
+
lambda_=lambda_,
|
|
425
|
+
sigma=sigma,
|
|
426
|
+
use_eq=use_eq,
|
|
427
|
+
verbose=verbose,
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
return kre_models, features_train
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def predict_pertlens(
|
|
434
|
+
mce,
|
|
435
|
+
kre_models,
|
|
436
|
+
x_ctrl,
|
|
437
|
+
perturbations,
|
|
438
|
+
dose=None,
|
|
439
|
+
batch_size=8,
|
|
440
|
+
device=None,
|
|
441
|
+
verbose=True,
|
|
442
|
+
):
|
|
443
|
+
"""Predict responses by applying the frozen MCE followed by KRE."""
|
|
444
|
+
device = get_device(device)
|
|
445
|
+
mce = mce.to(device)
|
|
446
|
+
mce.eval()
|
|
447
|
+
perturbations = normalize_perturbations(perturbations)
|
|
448
|
+
|
|
449
|
+
n_test = x_ctrl.shape[0]
|
|
450
|
+
|
|
451
|
+
if verbose:
|
|
452
|
+
print(f"[PertLens] Extracting MCE features for {n_test} test samples...")
|
|
453
|
+
|
|
454
|
+
x_ctrl_t = torch.as_tensor(x_ctrl, dtype=torch.float32)
|
|
455
|
+
perturbations_t = _perturbations_to_torch(perturbations)
|
|
456
|
+
|
|
457
|
+
if dose is not None:
|
|
458
|
+
dose_t = torch.as_tensor(np.asarray(dose).flatten(), dtype=torch.float32)
|
|
459
|
+
|
|
460
|
+
all_features = []
|
|
461
|
+
|
|
462
|
+
with torch.no_grad():
|
|
463
|
+
for start in range(0, n_test, batch_size):
|
|
464
|
+
end = min(start + batch_size, n_test)
|
|
465
|
+
xb = x_ctrl_t[start:end].to(device)
|
|
466
|
+
|
|
467
|
+
perturbations_batch = {
|
|
468
|
+
pert_key: tensor[start:end].to(device)
|
|
469
|
+
for pert_key, tensor in perturbations_t.items()
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
feat_kwargs = dict(
|
|
473
|
+
x_ctrl=xb,
|
|
474
|
+
perturbations=perturbations_batch,
|
|
475
|
+
)
|
|
476
|
+
if dose is not None:
|
|
477
|
+
feat_kwargs["dose"] = dose_t[start:end].to(device).unsqueeze(-1)
|
|
478
|
+
|
|
479
|
+
h = mce.extract_features(**feat_kwargs)
|
|
480
|
+
all_features.append(h.detach().cpu().numpy())
|
|
481
|
+
|
|
482
|
+
features_test = np.concatenate(all_features, axis=0)
|
|
483
|
+
|
|
484
|
+
if verbose:
|
|
485
|
+
print(f"[PertLens] Feature shape: {features_test.shape}")
|
|
486
|
+
print("[PertLens] Predicting with KRE...")
|
|
487
|
+
|
|
488
|
+
x_pred = predict_kre_per_gene(kre_models, features_test)
|
|
489
|
+
|
|
490
|
+
return x_pred
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def load_mce(checkpoint_path, device=None, encoder_class=None):
|
|
494
|
+
"""Instantiate an MCE from a checkpoint and load its state strictly.
|
|
495
|
+
|
|
496
|
+
``encoder_class`` may be supplied when loading a compatible alternative
|
|
497
|
+
encoder, such as one used in an ablation experiment. The checkpoint must
|
|
498
|
+
contain the model configuration and matching state-dictionary keys.
|
|
499
|
+
"""
|
|
500
|
+
device = get_device(device)
|
|
501
|
+
ckpt = load_checkpoint(checkpoint_path, map_location=device)
|
|
502
|
+
|
|
503
|
+
if "config" not in ckpt or ckpt["config"] is None:
|
|
504
|
+
raise ValueError(
|
|
505
|
+
"Checkpoint does not contain config. "
|
|
506
|
+
"Please make sure it was saved by train_mce()."
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
model_kwargs = ckpt["config"]["model_kwargs"]
|
|
510
|
+
model_cls = encoder_class if encoder_class is not None else MaskedContextEncoder
|
|
511
|
+
mce = model_cls(**model_kwargs).to(device)
|
|
512
|
+
mce.load_state_dict(ckpt["model_state"], strict=True)
|
|
513
|
+
mce.eval()
|
|
514
|
+
|
|
515
|
+
return mce, ckpt
|