turep 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.
- turep/__init__.py +43 -0
- turep/_fanvae.py +300 -0
- turep/_fanvi.py +529 -0
- turep/_ffadvae.py +396 -0
- turep/_ffadvi.py +1067 -0
- turep/_focalmixin.py +203 -0
- turep/_model_loader.py +56 -0
- turep/_prediction.py +400 -0
- turep-0.1.0.dist-info/METADATA +117 -0
- turep-0.1.0.dist-info/RECORD +13 -0
- turep-0.1.0.dist-info/WHEEL +5 -0
- turep-0.1.0.dist-info/licenses/LICENSE +21 -0
- turep-0.1.0.dist-info/top_level.txt +1 -0
turep/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Top-level package exports for turep.
|
|
2
|
+
|
|
3
|
+
This module defines the public API for model classes, loss helpers, and
|
|
4
|
+
prediction utilities.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._fanvae import FANVAE
|
|
8
|
+
from ._fanvi import FANVI
|
|
9
|
+
from ._focalmixin import FocalLoss, FocalLossClassificationMixin, focal_loss
|
|
10
|
+
from ._model_loader import load_model
|
|
11
|
+
from ._prediction import (
|
|
12
|
+
get_top_clonotype,
|
|
13
|
+
predict_tr,
|
|
14
|
+
predict_tr_pretrained,
|
|
15
|
+
predict_tr_spatial,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
from ._ffadvae import FFADVAE
|
|
20
|
+
from ._ffadvi import FFADVI
|
|
21
|
+
except ModuleNotFoundError as exc:
|
|
22
|
+
if exc.name == "fadvi":
|
|
23
|
+
FFADVAE = None
|
|
24
|
+
FFADVI = None
|
|
25
|
+
else:
|
|
26
|
+
raise
|
|
27
|
+
|
|
28
|
+
__version__ = "0.1.0"
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"FANVAE",
|
|
32
|
+
"FANVI",
|
|
33
|
+
"FFADVAE",
|
|
34
|
+
"FFADVI",
|
|
35
|
+
"FocalLoss",
|
|
36
|
+
"FocalLossClassificationMixin",
|
|
37
|
+
"focal_loss",
|
|
38
|
+
"load_model",
|
|
39
|
+
"predict_tr",
|
|
40
|
+
"predict_tr_pretrained",
|
|
41
|
+
"predict_tr_spatial",
|
|
42
|
+
"get_top_clonotype",
|
|
43
|
+
]
|
turep/_fanvae.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""FANVAE module: scANVAE architecture with focal-loss classification support."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Sequence
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
from scvi import REGISTRY_KEYS
|
|
10
|
+
from scvi.module import SCANVAE
|
|
11
|
+
from scvi.module._classifier import Classifier
|
|
12
|
+
from scvi.module._utils import broadcast_labels
|
|
13
|
+
from scvi.module.base import LossOutput, auto_move_data
|
|
14
|
+
from torch.distributions import Categorical, Distribution, Normal
|
|
15
|
+
from torch.distributions import kl_divergence as kl
|
|
16
|
+
from torch.nn import functional as F
|
|
17
|
+
|
|
18
|
+
from ._focalmixin import FocalLossClassificationMixin
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class FANVAE(SCANVAE, FocalLossClassificationMixin):
|
|
22
|
+
"""scANVAE-based module extended with focal-loss classification.
|
|
23
|
+
|
|
24
|
+
This class reuses the scvi-tools ``SCANVAE`` architecture and augments the
|
|
25
|
+
classification objective through ``FocalLossClassificationMixin`` to better
|
|
26
|
+
handle imbalanced labels.
|
|
27
|
+
|
|
28
|
+
Parameters
|
|
29
|
+
----------
|
|
30
|
+
n_input
|
|
31
|
+
Number of input features (typically genes).
|
|
32
|
+
n_batch
|
|
33
|
+
Number of batches.
|
|
34
|
+
n_labels
|
|
35
|
+
Number of supervised labels.
|
|
36
|
+
n_hidden
|
|
37
|
+
Hidden-layer width.
|
|
38
|
+
n_latent
|
|
39
|
+
Latent-space dimensionality.
|
|
40
|
+
n_layers
|
|
41
|
+
Number of hidden layers.
|
|
42
|
+
focal_alpha
|
|
43
|
+
Class weighting term in focal loss.
|
|
44
|
+
focal_gamma
|
|
45
|
+
Focusing parameter in focal loss.
|
|
46
|
+
focal_reduction
|
|
47
|
+
Reduction strategy for focal loss.
|
|
48
|
+
**vae_kwargs
|
|
49
|
+
Additional keyword arguments forwarded to ``SCANVAE``.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
n_input: int,
|
|
55
|
+
n_batch: int = 0,
|
|
56
|
+
n_labels: int = 0,
|
|
57
|
+
n_hidden: int = 128,
|
|
58
|
+
n_latent: int = 10,
|
|
59
|
+
n_layers: int = 1,
|
|
60
|
+
use_expansion: bool = False,
|
|
61
|
+
n_continuous_cov: int = 0,
|
|
62
|
+
n_cats_per_cov: Iterable[int] | None = None,
|
|
63
|
+
dropout_rate: float = 0.1,
|
|
64
|
+
dispersion: Literal["gene", "gene-batch", "gene-label", "gene-cell"] = "gene",
|
|
65
|
+
log_variational: bool = True,
|
|
66
|
+
gene_likelihood: Literal["zinb", "nb"] = "zinb",
|
|
67
|
+
use_observed_lib_size: bool = True,
|
|
68
|
+
y_prior: torch.Tensor | None = None,
|
|
69
|
+
labels_groups: Sequence[int] = None,
|
|
70
|
+
use_labels_groups: bool = False,
|
|
71
|
+
linear_classifier: bool = False,
|
|
72
|
+
classifier_parameters: dict | None = None,
|
|
73
|
+
use_batch_norm: Literal["encoder", "decoder", "none", "both"] = "both",
|
|
74
|
+
use_layer_norm: Literal["encoder", "decoder", "none", "both"] = "none",
|
|
75
|
+
focal_alpha: float | torch.Tensor = 1.0,
|
|
76
|
+
focal_gamma: float = 2.0,
|
|
77
|
+
focal_reduction: str = "mean",
|
|
78
|
+
**vae_kwargs,
|
|
79
|
+
):
|
|
80
|
+
super().__init__(
|
|
81
|
+
n_input,
|
|
82
|
+
n_hidden=n_hidden,
|
|
83
|
+
n_latent=n_latent,
|
|
84
|
+
n_labels=n_labels,
|
|
85
|
+
n_layers=n_layers,
|
|
86
|
+
n_continuous_cov=n_continuous_cov,
|
|
87
|
+
n_cats_per_cov=n_cats_per_cov,
|
|
88
|
+
dropout_rate=dropout_rate,
|
|
89
|
+
n_batch=n_batch,
|
|
90
|
+
dispersion=dispersion,
|
|
91
|
+
log_variational=log_variational,
|
|
92
|
+
gene_likelihood=gene_likelihood,
|
|
93
|
+
use_observed_lib_size=use_observed_lib_size,
|
|
94
|
+
use_batch_norm=use_batch_norm,
|
|
95
|
+
use_layer_norm=use_layer_norm,
|
|
96
|
+
y_prior=y_prior,
|
|
97
|
+
labels_groups=labels_groups,
|
|
98
|
+
use_labels_groups=use_labels_groups,
|
|
99
|
+
linear_classifier=linear_classifier,
|
|
100
|
+
classifier_parameters=classifier_parameters,
|
|
101
|
+
**vae_kwargs,
|
|
102
|
+
)
|
|
103
|
+
self.focal_alpha = focal_alpha
|
|
104
|
+
self.focal_gamma = focal_gamma
|
|
105
|
+
self.focal_reduction = focal_reduction
|
|
106
|
+
self.use_expansion = use_expansion
|
|
107
|
+
|
|
108
|
+
classifier_parameters = classifier_parameters or {}
|
|
109
|
+
use_batch_norm_encoder = use_batch_norm == "encoder" or use_batch_norm == "both"
|
|
110
|
+
use_layer_norm_encoder = use_layer_norm == "encoder" or use_layer_norm == "both"
|
|
111
|
+
cls_parameters = {
|
|
112
|
+
"n_layers": 0 if linear_classifier else n_layers,
|
|
113
|
+
"n_hidden": 0 if linear_classifier else n_hidden,
|
|
114
|
+
"dropout_rate": dropout_rate,
|
|
115
|
+
"logits": True,
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
n_classifier_input = n_latent + 1 if use_expansion else n_latent
|
|
119
|
+
self.classifier = Classifier(
|
|
120
|
+
n_classifier_input,
|
|
121
|
+
n_labels=n_labels,
|
|
122
|
+
use_batch_norm=use_batch_norm_encoder,
|
|
123
|
+
use_layer_norm=use_layer_norm_encoder,
|
|
124
|
+
**cls_parameters,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
@auto_move_data
|
|
128
|
+
def classify(
|
|
129
|
+
self,
|
|
130
|
+
x: torch.Tensor,
|
|
131
|
+
expansion: torch.Tensor | None = None,
|
|
132
|
+
batch_index: torch.Tensor | None = None,
|
|
133
|
+
cont_covs: torch.Tensor | None = None,
|
|
134
|
+
cat_covs: torch.Tensor | None = None,
|
|
135
|
+
use_posterior_mean: bool = True,
|
|
136
|
+
) -> torch.Tensor:
|
|
137
|
+
"""Forward pass through the encoder and classifier.
|
|
138
|
+
|
|
139
|
+
Parameters
|
|
140
|
+
----------
|
|
141
|
+
x
|
|
142
|
+
Tensor of shape ``(n_obs, n_vars)``.
|
|
143
|
+
expansion
|
|
144
|
+
Tensor of shape ``(n_obs, 1)`` denoting T cell clonal expansion.
|
|
145
|
+
If ``use_expansion`` is ``False``, this argument is ignored.
|
|
146
|
+
batch_index
|
|
147
|
+
Tensor of shape ``(n_obs,)`` denoting batch indices.
|
|
148
|
+
cont_covs
|
|
149
|
+
Tensor of shape ``(n_obs, n_continuous_covariates)``.
|
|
150
|
+
cat_covs
|
|
151
|
+
Tensor of shape ``(n_obs, n_categorical_covariates)``.
|
|
152
|
+
use_posterior_mean
|
|
153
|
+
Whether to use the posterior mean of the latent distribution for
|
|
154
|
+
classification.
|
|
155
|
+
|
|
156
|
+
Returns
|
|
157
|
+
-------
|
|
158
|
+
Tensor of shape ``(n_obs, n_labels)`` denoting logit scores per label.
|
|
159
|
+
"""
|
|
160
|
+
if self.log_variational:
|
|
161
|
+
x = torch.log1p(x)
|
|
162
|
+
|
|
163
|
+
if cont_covs is not None and self.encode_covariates:
|
|
164
|
+
encoder_input = torch.cat((x, cont_covs), dim=-1)
|
|
165
|
+
else:
|
|
166
|
+
encoder_input = x
|
|
167
|
+
if cat_covs is not None and self.encode_covariates:
|
|
168
|
+
categorical_input = torch.split(cat_covs, 1, dim=1)
|
|
169
|
+
else:
|
|
170
|
+
categorical_input = ()
|
|
171
|
+
|
|
172
|
+
qz, z = self.z_encoder(encoder_input, batch_index, *categorical_input)
|
|
173
|
+
z = qz.loc if use_posterior_mean else z
|
|
174
|
+
z_expansion = (
|
|
175
|
+
torch.cat([z, expansion], dim=-1)
|
|
176
|
+
if (self.use_expansion and expansion is not None)
|
|
177
|
+
else z
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
if self.use_labels_groups:
|
|
181
|
+
w_g = self.classifier_groups(z_expansion)
|
|
182
|
+
unw_y = self.classifier(z_expansion)
|
|
183
|
+
w_y = torch.zeros_like(unw_y)
|
|
184
|
+
for i, group_index in enumerate(self.groups_index):
|
|
185
|
+
unw_y_g = unw_y[:, group_index]
|
|
186
|
+
w_y[:, group_index] = unw_y_g / (unw_y_g.sum(dim=-1, keepdim=True) + 1e-8)
|
|
187
|
+
w_y[:, group_index] *= w_g[:, [i]]
|
|
188
|
+
else:
|
|
189
|
+
w_y = self.classifier(z_expansion)
|
|
190
|
+
return w_y
|
|
191
|
+
|
|
192
|
+
def loss(
|
|
193
|
+
self,
|
|
194
|
+
tensors: dict[str, torch.Tensor],
|
|
195
|
+
inference_outputs: dict[str, torch.Tensor | Distribution | None],
|
|
196
|
+
generative_ouputs: dict[str, Distribution | None],
|
|
197
|
+
kl_weight: float = 1.0,
|
|
198
|
+
labelled_tensors: dict[str, torch.Tensor] | None = None,
|
|
199
|
+
classification_ratio: float | None = None,
|
|
200
|
+
):
|
|
201
|
+
"""Compute the loss."""
|
|
202
|
+
px: Distribution = generative_ouputs["px"]
|
|
203
|
+
qz1: torch.Tensor = inference_outputs["qz"]
|
|
204
|
+
z1: torch.Tensor = inference_outputs["z"]
|
|
205
|
+
x: torch.Tensor = tensors[REGISTRY_KEYS.X_KEY]
|
|
206
|
+
batch_index: torch.Tensor = tensors[REGISTRY_KEYS.BATCH_KEY]
|
|
207
|
+
|
|
208
|
+
ys, z1s = broadcast_labels(z1, n_broadcast=self.n_labels)
|
|
209
|
+
qz2, z2 = self.encoder_z2_z1(z1s, ys)
|
|
210
|
+
pz1_m, pz1_v = self.decoder_z1_z2(z2, ys)
|
|
211
|
+
reconst_loss = -px.log_prob(x).sum(-1)
|
|
212
|
+
|
|
213
|
+
# KL Divergence
|
|
214
|
+
mean = torch.zeros_like(qz2.loc)
|
|
215
|
+
scale = torch.ones_like(qz2.scale)
|
|
216
|
+
|
|
217
|
+
kl_divergence_z2 = kl(qz2, Normal(mean, scale)).sum(dim=-1)
|
|
218
|
+
loss_z1_unweight = -Normal(pz1_m, torch.sqrt(pz1_v)).log_prob(z1s).sum(dim=-1)
|
|
219
|
+
loss_z1_weight = qz1.log_prob(z1).sum(dim=-1)
|
|
220
|
+
|
|
221
|
+
if not self.use_expansion:
|
|
222
|
+
probs = self.classifier(z1)
|
|
223
|
+
if self.classifier.logits:
|
|
224
|
+
probs = F.softmax(probs, dim=-1)
|
|
225
|
+
else:
|
|
226
|
+
z1_expansion = torch.cat([z1, tensors["expansion"]], dim=-1)
|
|
227
|
+
probs = self.classifier(z1_expansion)
|
|
228
|
+
if self.classifier.logits:
|
|
229
|
+
probs = F.softmax(probs, dim=-1)
|
|
230
|
+
|
|
231
|
+
if z1.ndim == 2:
|
|
232
|
+
loss_z1_unweight_ = loss_z1_unweight.view(self.n_labels, -1).t()
|
|
233
|
+
kl_divergence_z2_ = kl_divergence_z2.view(self.n_labels, -1).t()
|
|
234
|
+
else:
|
|
235
|
+
loss_z1_unweight_ = torch.transpose(
|
|
236
|
+
loss_z1_unweight.view(z1.shape[0], self.n_labels, -1), -1, -2
|
|
237
|
+
)
|
|
238
|
+
kl_divergence_z2_ = torch.transpose(
|
|
239
|
+
kl_divergence_z2.view(z1.shape[0], self.n_labels, -1), -1, -2
|
|
240
|
+
)
|
|
241
|
+
reconst_loss += loss_z1_weight + (loss_z1_unweight_ * probs).sum(dim=-1)
|
|
242
|
+
kl_divergence = (kl_divergence_z2_ * probs).sum(dim=-1)
|
|
243
|
+
kl_divergence += kl(
|
|
244
|
+
Categorical(probs=probs),
|
|
245
|
+
Categorical(
|
|
246
|
+
probs=(
|
|
247
|
+
self.y_prior.repeat(probs.size(0), probs.size(1), 1)
|
|
248
|
+
if len(probs.size()) == 3
|
|
249
|
+
else self.y_prior.repeat(probs.size(0), 1)
|
|
250
|
+
)
|
|
251
|
+
),
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
if not self.use_observed_lib_size:
|
|
255
|
+
ql = inference_outputs["ql"]
|
|
256
|
+
(
|
|
257
|
+
local_library_log_means,
|
|
258
|
+
local_library_log_vars,
|
|
259
|
+
) = self._compute_local_library_params(batch_index)
|
|
260
|
+
|
|
261
|
+
kl_divergence_l = kl(
|
|
262
|
+
ql,
|
|
263
|
+
Normal(local_library_log_means, torch.sqrt(local_library_log_vars)),
|
|
264
|
+
).sum(dim=1)
|
|
265
|
+
else:
|
|
266
|
+
kl_divergence_l = torch.zeros_like(kl_divergence)
|
|
267
|
+
|
|
268
|
+
kl_divergence += kl_divergence_l
|
|
269
|
+
|
|
270
|
+
loss = torch.mean(reconst_loss + kl_divergence * kl_weight)
|
|
271
|
+
|
|
272
|
+
# a payload to be used during autotune
|
|
273
|
+
if self.extra_payload_autotune:
|
|
274
|
+
extra_metrics_payload = {
|
|
275
|
+
"z": inference_outputs["z"],
|
|
276
|
+
"batch": tensors[REGISTRY_KEYS.BATCH_KEY],
|
|
277
|
+
"labels": tensors[REGISTRY_KEYS.LABELS_KEY],
|
|
278
|
+
}
|
|
279
|
+
else:
|
|
280
|
+
extra_metrics_payload = {}
|
|
281
|
+
|
|
282
|
+
if labelled_tensors is not None:
|
|
283
|
+
ce_loss, true_labels, logits = self.focal_classification_loss(labelled_tensors)
|
|
284
|
+
|
|
285
|
+
loss += ce_loss * classification_ratio
|
|
286
|
+
return LossOutput(
|
|
287
|
+
loss=loss,
|
|
288
|
+
reconstruction_loss=reconst_loss,
|
|
289
|
+
kl_local=kl_divergence,
|
|
290
|
+
classification_loss=ce_loss,
|
|
291
|
+
true_labels=true_labels,
|
|
292
|
+
logits=logits,
|
|
293
|
+
extra_metrics=extra_metrics_payload,
|
|
294
|
+
)
|
|
295
|
+
return LossOutput(
|
|
296
|
+
loss=loss,
|
|
297
|
+
reconstruction_loss=reconst_loss,
|
|
298
|
+
kl_local=kl_divergence,
|
|
299
|
+
extra_metrics=extra_metrics_payload,
|
|
300
|
+
)
|