Documentation for the model

model description

scprint.model.model

Classes:

Name Description
scPrint

scPrint

Bases: LightningModule, PyTorchModelHubMixin

scPRINT transformer for single cell biology and the inference of Gene Regulatory networks

Parameters:
  • genes (list) –

    List of gene names the model will work with.

  • precpt_gene_emb (array, default: None ) –

    Gene embeddings of size (len(genes), d_model). Should be in the same order as the genes. Defaults to None.

  • gene_pos_enc (list, default: None ) –

    Gene position encoding of the same size as genes. Provides a location value for each gene in genes. Defaults to None.

  • d_model (int, default: 256 ) –

    Dimension of the model. Defaults to 512.

  • nhead (int, default: 4 ) –

    Number of heads in the multihead attention models. Defaults to 8.

  • d_hid (int) –

    Dimension of the feedforward network model. Defaults to 512.

  • nlayers (int, default: 8 ) –

    Number of layers in the transformer model. Defaults to 6.

  • expr_encoder_layers (int, default: 2 ) –

    Number of layers in the expression encoder. Defaults to 2.

  • layers_cls (list[int], default: [] ) –

    List specifying the number of layers in the classifier. Defaults to [].

  • classes (Dict[str, int], default: {} ) –

    Classes to predict with the number of classes for each. Defaults to {}.

  • labels_hierarchy (Dict[str, Dict[int, list[int]]], default: {} ) –

    Class hierarchy for classes with hierarchical classes. Defaults to {}.

  • dropout (float, default: 0.1 ) –

    Dropout value. Defaults to 0.2.

  • transformer (str, default: 'flash' ) –

    Transformer type to use. One of "linear", "flash", "flashsparse", "scprint". Defaults to "fast".

  • domain_spec_batchnorm (str, default: 'None' ) –

    Whether to apply domain-specific batch normalization. Defaults to "None".

  • expr_emb_style (str, default: 'continuous' ) –

    Style of input embedding. One of "continuous", "binned_pos", "cont_pos". Defaults to "continuous".

  • mvc_decoder (str, default: 'None' ) –

    Style of MVC decoder. One of "None", "inner product", "concat query", "sum query". Defaults to "None".

  • pred_embedding (list[str], default: [] ) –

    List of classes to use for plotting embeddings. Defaults to [].

  • cell_emb_style (str, default: 'cls' ) –

    Style of cell embedding. One of "cls", "avg-pool", "w-pool". Defaults to "cls".

  • freeze_embeddings (bool, default: True ) –

    Whether to freeze the embeddings during training. Defaults to True.

  • label_decoders (Optional[Dict[str, Dict[int, str]]], default: None ) –

    Label decoders to use for plotting the UMAP during validations. Defaults to None.

  • zinb (bool, default: True ) –

    Whether to use Zero-Inflated Negative Binomial distribution. Defaults to True.

  • use_metacell_token (bool, default: False ) –

    Whether to use a metacell token. Defaults to False.

  • **flash_attention_kwargs (dict, default: {} ) –

    Additional keyword arguments for the model. see @flashformer.py

Notes

for other parameters of the model that are not part of its class definition, see @trainer.trainer.py

Raises:
  • ValueError

    If the expr_emb_style is not one of "continuous", "binned_pos", "cont_pos".

Methods:

Name Description
configure_optimizers

@see pl.LightningModule

forward

forward also called on self(), a full forward pass on the model

log_adata

log_adata will log an adata from predictions.

on_fit_start

@see pl.LightningModule

on_predict_epoch_end

@see pl.LightningModule will

on_predict_epoch_start

@see pl.LightningModule

on_validation_epoch_end

@see pl.LightningModule

optimizer_step

@see pl.LightningModule

predict_step

embed given gene expression, encode the gene embedding and cell embedding.

training_step

training_step defines the train loop. It is independent of forward

validation_step

validation_step defines the validation loop. It is independent of forward

Source code in scprint/model/model.py
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def __init__(
    self,
    genes: list,
    organisms: list = ["NCBITaxon:9606"],
    d_model: int = 256,
    nhead: int = 4,
    nlayers: int = 8,
    precpt_gene_emb: Optional[str] = None,
    gene_pos_enc: Optional[list] = None,
    normalization: str = "sum",
    attn_bias: str = "none",
    expr_encoder_layers: int = 2,
    transformer: str = "flash",  # "performer", "flash", "normal", "crisscross"
    expr_emb_style: str = "continuous",  # "binned_pos", "cont_pos"
    domain_spec_batchnorm: str = "None",
    n_input_bins: int = 0,
    num_batch_labels: int = 0,
    mvc_decoder: str = "None",
    pred_embedding: list[str] = [],
    layers_cls: list[int] = [],
    classes: Dict[str, int] = {},
    labels_hierarchy: Dict[str, Dict[int, list[int]]] = {},
    label_decoders: Optional[Dict[str, Dict[int, str]]] = None,
    compress_class_dim: Optional[Dict[str, int]] = None,
    cell_emb_style: str = "cls",
    cell_specific_blocks: bool = False,
    depth_atinput: bool = True,
    freeze_embeddings: bool = True,
    zinb: bool = True,
    dropout: float = 0.1,
    use_metacell_token: bool = False,
    lr: float = 0.0001,
    **flash_attention_kwargs,
):
    """
    scPRINT transformer for single cell biology and the inference of Gene Regulatory networks

    Args:
        genes (list): List of gene names the model will work with.
        precpt_gene_emb (np.array, optional): Gene embeddings of size (len(genes), d_model). Should be in the same order as the genes. Defaults to None.
        gene_pos_enc (list, optional): Gene position encoding of the same size as genes. Provides a location value for each gene in genes. Defaults to None.
        d_model (int, optional): Dimension of the model. Defaults to 512.
        nhead (int, optional): Number of heads in the multihead attention models. Defaults to 8.
        d_hid (int, optional): Dimension of the feedforward network model. Defaults to 512.
        nlayers (int, optional): Number of layers in the transformer model. Defaults to 6.
        expr_encoder_layers (int, optional): Number of layers in the expression encoder. Defaults to 2.
        layers_cls (list[int], optional): List specifying the number of layers in the classifier. Defaults to [].
        classes (Dict[str, int], optional): Classes to predict with the number of classes for each. Defaults to {}.
        labels_hierarchy (Dict[str, Dict[int, list[int]]], optional): Class hierarchy for classes with hierarchical classes. Defaults to {}.
        dropout (float, optional): Dropout value. Defaults to 0.2.
        transformer (str, optional): Transformer type to use. One of "linear", "flash", "flashsparse", "scprint". Defaults to "fast".
        domain_spec_batchnorm (str, optional): Whether to apply domain-specific batch normalization. Defaults to "None".
        expr_emb_style (str, optional): Style of input embedding. One of "continuous", "binned_pos", "cont_pos". Defaults to "continuous".
        mvc_decoder (str, optional): Style of MVC decoder. One of "None", "inner product", "concat query", "sum query". Defaults to "None".
        pred_embedding (list[str], optional): List of classes to use for plotting embeddings. Defaults to [].
        cell_emb_style (str, optional): Style of cell embedding. One of "cls", "avg-pool", "w-pool". Defaults to "cls".
        freeze_embeddings (bool, optional): Whether to freeze the embeddings during training. Defaults to True.
        label_decoders (Optional[Dict[str, Dict[int, str]]], optional): Label decoders to use for plotting the UMAP during validations. Defaults to None.
        zinb (bool, optional): Whether to use Zero-Inflated Negative Binomial distribution. Defaults to True.
        use_metacell_token (bool, optional): Whether to use a metacell token. Defaults to False.
        **flash_attention_kwargs (dict): Additional keyword arguments for the model. see @flashformer.py

    Notes:
        for other parameters of the model that are not part of its class definition, see @trainer.trainer.py

    Raises:
        ValueError: If the expr_emb_style is not one of "continuous", "binned_pos", "cont_pos".
    """
    super().__init__()
    self.save_hyperparameters()
    # training flags
    self.do_denoise = True
    self.noise = [0.6]
    self.do_cce = False
    self.cce_temp = 0.2
    self.lr = 0.0001
    self.cce_scale = 0.1
    self.do_ecs = False
    self.ecs_threshold = 0.4
    self.ecs_scale = 0.1
    self.do_mvc = False
    self.mvc_scale = 1.0
    self.class_embd_diss_scale = 0.1
    self.do_adv_cls = False
    self.adv_class_scale = 0.1
    self.do_cls = False
    self.mean_attn_tot = None
    self.mean_attn_tot_c = 0
    self.do_adv_batch = False
    self.run_full_forward = True
    self.class_scale = 1
    self.zinb_and_mse = False
    self.do_next_tp = False
    self.do_generate = False
    self.var_context_length = False
    self.mask_ratio = []
    self.warmup_duration = 500
    self.weight_decay = 0.01
    self.optim = "adamW"
    self.fused_adam = False
    self.lr_reduce_patience = 2
    self.lr_reduce_factor = 0.6
    self.test_every = 20
    self.lr_reduce_monitor = "val_loss"
    self.name = ""
    self.set_step = None
    self.lrfinder_steps = 0
    self.doplot = True
    self.get_attention_layer = []
    self.embs = None
    self.pred_log_adata = True
    self.predict_depth_mult = 3
    self.predict_mode = "none"
    self.keep_all_cls_pred = False
    self.cell_separation = True

    self.depth_atinput = depth_atinput
    self.attn = utils.Attention(
        len(genes),
        additional_tokens=(
            len(classes) + (2 if self.depth_atinput else 1)
            if not cell_specific_blocks
            else 0
        ),
    )
    self.tf_masker = WeightedMasker(genes, inv_weight=0.05)
    # should be stored somehow
    self.d_model = d_model
    self.normalization = normalization
    self.organisms = organisms
    self.attn_bias = attn_bias
    self.nlayers = nlayers
    self.gene_pos_enc = gene_pos_enc
    self.use_metacell_token = use_metacell_token
    self.mvc_decoder = mvc_decoder
    self.domain_spec_batchnorm = domain_spec_batchnorm
    # need to store
    self.n_input_bins = n_input_bins
    self.transformer = transformer
    self.label_counts = classes
    self.classes = list(classes.keys())

    if cell_emb_style not in ["cls", "avg-pool", "w-pool"]:
        raise ValueError(f"Unknown cell_emb_style: {cell_emb_style}")
    self.cell_emb_style = cell_emb_style

    self.label_decoders = label_decoders
    self.pred_embedding = pred_embedding
    self.genes = genes
    self.vocab = {i: n for i, n in enumerate(genes)}
    self.expr_emb_style = expr_emb_style
    if self.expr_emb_style not in ["category", "continuous", "none"]:
        raise ValueError(
            f"expr_emb_style should be one of category, continuous, scaling, "
            f"got {expr_emb_style}"
        )
    self.labels_hierarchy = labels_hierarchy
    self.hparams["labels_hierarchy"] = self.labels_hierarchy
    self.hparams["classes"] = self.classes
    self.hparams["label_decoders"] = self.label_decoders
    self.hparams["label_counts"] = self.label_counts
    self.hparams["gene_pos_enc"] = self.gene_pos_enc
    self.hparams["genes"] = self.genes

    self.mat_labels_hierarchy = {}
    for k, v in labels_hierarchy.items():
        tens = torch.zeros((len(v), classes[k]))
        for k2, v2 in v.items():
            tens[k2 - classes[k], v2] = 1
        self.mat_labels_hierarchy[k] = tens.to(bool)

    # encoder
    # gene encoder
    if precpt_gene_emb is not None:
        embeddings = pd.read_parquet(precpt_gene_emb).loc[self.genes]
        if len(embeddings) == 0:
            raise ValueError(
                f"the gene embeddings file {precpt_gene_emb} does not contain any of the genes given to the model"
            )
        elif len(embeddings) < len(self.genes):
            print(
                "Warning: only a subset of the genes available in the embeddings file."
            )
            print("number of genes: ", len(embeddings))
        sembeddings = torch.nn.AdaptiveAvgPool1d(d_model)(
            torch.tensor(embeddings.values)
        )

        self.gene_encoder = encoders.GeneEncoder(
            len(self.vocab), d_model, weights=sembeddings, freeze=freeze_embeddings
        )
    else:
        self.gene_encoder = encoders.GeneEncoder(len(self.vocab), d_model)

    # Value Encoder, NOTE: the scaling style is also handled in _encode method
    if expr_emb_style in ["continuous", "full_pos"]:
        self.expr_encoder = encoders.ContinuousValueEncoder(
            d_model, dropout, layers=expr_encoder_layers
        )
    elif expr_emb_style == "binned_pos":
        assert n_input_bins > 0
        self.expr_encoder = encoders.CategoryValueEncoder(n_input_bins, d_model)
    else:
        self.expr_encoder = torch.nn.Identity()

    # Positional Encoding
    if self.gene_pos_enc is not None:
        max_len = max(gene_pos_enc)
        token_to_pos = {token: pos for token, pos in enumerate(self.gene_pos_enc)}
        self.pos_encoder = encoders.PositionalEncoding(
            d_model, max_len=max_len, token_to_pos=token_to_pos
        )

    self.cell_embs_count = (
        len(self.classes)
        + (2 if self.depth_atinput else 1)
        + (1 if self.use_metacell_token else 0)
    )
    # Class Encoder
    # always have [base_cell_emb, time_embedding, depth_embedding] + any other class info
    # base cell embedding will store other cell specific information
    self.class_encoder = encoders.CategoryValueEncoder(
        self.cell_embs_count
        - (1 if self.depth_atinput else 0)
        - (1 if self.use_metacell_token else 0),
        d_model,
    )
    # self.time_encoder = encoders.ContinuousValueEncoder(d_model, dropout)
    if self.depth_atinput:
        self.depth_encoder = encoders.ContinuousValueEncoder(
            d_model, dropout, layers=expr_encoder_layers
        )

    if self.use_metacell_token:
        self.metacell_encoder = encoders.CategoryValueEncoder(2, d_model)
    # compute tensor for mat_labels_hierarchy
    for i in ["strict_loading", "optim", "weight_decay", "d_hid", "edge_dim"]:
        if i in flash_attention_kwargs:
            flash_attention_kwargs.pop(i)
    # Transformer
    # Linear
    if transformer == "linear":
        # linear transformer using the fast transformer package
        # self.transformer = FastTransformerEncoder(
        #    d_model, nhead, d_hid, nlayers, dropout, "linear"
        # )
        raise NotImplementedError("Linear transformer is not implemented")
    # regular or flash
    else:
        self.transformer = FlashTransformer(
            d_model=d_model,
            nhead=nhead,
            dropout=dropout,
            nlayers=nlayers,
            cross_attn=cell_specific_blocks,
            use_flash_attn=(transformer == "flash"),
            **flash_attention_kwargs,
        )
    if cell_specific_blocks:
        self.cell_transformer = FlashTransformer(
            d_model=d_model,
            nhead=nhead,
            nlayers=6,
            dropout=dropout,
            cross_attn=True,
            use_flash_attn=(transformer == "flash"),
            **flash_attention_kwargs,
        )
    else:
        self.cell_transformer = None

    # decoders
    # expression
    self.expr_decoder = decoders.ExprDecoder(
        d_model,
        nfirst_tokens_to_skip=self.cell_embs_count,
        dropout=dropout,
        zinb=zinb,
        use_depth=not self.depth_atinput,
    )
    # cls decoder
    self.cls_decoders = torch.nn.ModuleDict()
    # should be a very simple classifier for most things
    # (maybe scale with the number of classes) should be 1 layer...
    for clss, n_cls in classes.items():
        self.cls_decoders[clss] = decoders.ClsDecoder(
            d_model, n_cls, layers=layers_cls, dropout=dropout
        )

    # Batch effect correction via adversarial training on batch classes
    if num_batch_labels > 0:
        self.grad_reverse_discriminator_loss = loss.AdversarialDiscriminatorLoss(
            d_model,
            n_cls=num_batch_labels,
        )
    else:
        self.grad_reverse_discriminator_loss = None

    # expression decoder from batch embbedding
    if mvc_decoder != "None":
        self.mvc_decoder = decoders.MVCDecoder(
            d_model,
            arch_style=mvc_decoder,
            zinb=zinb,
        )
    else:
        self.mvc_decoder = None

    self.apply(
        partial(
            utils._init_weights,
            n_layer=nlayers,
        )
    )
    for i, dec in self.cls_decoders.items():
        torch.nn.init.constant_(dec.out_layer.bias, -0.13)

    if compress_class_dim is not None:
        self.bottleneck_mlps = torch.nn.ModuleDict()
        for k, v in compress_class_dim.items():
            self.bottleneck_mlps[k] = fsq.FSQ(levels=[2] * v, dim=self.d_model)
    else:
        self.bottleneck_mlps = None

configure_optimizers

@see pl.LightningModule

Source code in scprint/model/model.py
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
def configure_optimizers(self):
    """@see pl.LightningModule"""
    # https://pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam
    # not working because of poor weight decay implem
    if self.optim == "adam":
        optimizer = optim.Adam(
            self.parameters(),
            lr=self.hparams.lr,
            betas=(0.9, 0.999),
            eps=1e-08,
            weight_decay=self.weight_decay,
            amsgrad=False,
            fused=self.fused_adam,
        )
    elif self.optim == "adamW":
        optimizer = optim.AdamW(
            self.parameters(),
            lr=self.hparams.lr,
            betas=(0.9, 0.999),
            eps=1e-08,
            weight_decay=self.weight_decay,
            amsgrad=False,
            fused=self.fused_adam,
        )
    elif self.optim == "galore":
        raise NotImplementedError("Galore optimizer not implemented")
        # param_groups = [
        #    {
        #        "params": [
        #            v for k, v in self.named_parameters() if "transformer" not in k
        #        ]
        #    },
        #    {
        #        "params": [
        #            v for k, v in self.named_parameters() if "transformer" in k
        #        ],
        #        "rank": 128,
        #        "update_proj_gap": 200,
        #        "scale": 0.25,
        #        "proj_type": "std",
        #    },
        # ]
        # optimizer = GaLoreAdamW(param_groups, lr=self.hparams.lr)
    else:
        raise ValueError(f"Unknown optimizer: {self.optim}")
    if self.lr_reduce_monitor is None:
        print("no lr reduce factor")
        return [optimizer]
    lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(
        optimizer,
        mode="min",
        patience=self.lr_reduce_patience,
        factor=self.lr_reduce_factor,
        verbose=True,
    )
    lr_dict = {
        "scheduler": lr_scheduler,
        # The unit of the scheduler's step size, could also be 'step'.
        # 'epoch' updates the scheduler on epoch end whereas 'step'
        # updates it after a optimizer update.
        "interval": "epoch",
        # How many epochs/steps should pass between calls to
        # `scheduler.step()`. 1 corresponds to updating the learning
        # rate after every epoch/step.
        "frequency": 1,
        # Metric to to monitor for schedulers like `ReduceLROnPlateau`
        "monitor": self.lr_reduce_monitor,
    }
    self.lrfinder_steps = 0
    for val in self.trainer.callbacks:
        if type(val) is _LRCallback:
            self.lrfinder_steps = val.num_training
        if type(val) is LearningRateFinder:
            self.lrfinder_steps = val._num_training_steps
    return [optimizer], [lr_dict]

forward

forward also called on self(), a full forward pass on the model

Parameters:
  • gene_pos (Tensor) –

    A tensor of shape (minibatch, seq_len) representing the genes used for each cell in the minibatch.

  • expression (Tensor, default: None ) –

    A tensor of shape (minibatch, seq_len) representing the expression levels of genes in the minibatch. Defaults to None.

  • mask (Tensor, default: None ) –

    A tensor of shape (minibatch, seq_len) used to mask certain elements in the sequence during the forward pass. Defaults to None.

  • req_depth (Tensor, default: None ) –

    A tensor of shape (minibatch,) representing the full depth of each sequence in the minibatch. Defaults to None.

  • depth_mult (Tensor, default: None ) –

    A tensor of shape (minibatch,) representing the depth multiplier for each sequence in the minibatch. Defaults to None.

  • timepoint (Tensor, default: None ) –

    A tensor of shape (minibatch,) representing the timepoint associated with each sequence in the minibatch. Defaults to None.

  • get_gene_emb (bool, default: False ) –

    A flag indicating whether to return the gene embeddings. If True, the gene embeddings are included in the output. Defaults to False.

  • do_sample (bool, default: False ) –

    A flag indicating whether to sample the expression levels. If True, the expression levels are sampled during the forward pass. Defaults to False.

  • get_attention_layer (list, default: [] ) –

    A list indicating which attention layers to return. If not empty, the specified attention layers are included in the output. Defaults to [].

Returns:
  • dict of output Tensors: A dictionary containing the output tensors from the forward pass. The keys of the dictionary depend on the input flags (get_gene_emb, do_sample, get_attention_layer). at minima, the dictionary codntains the following: - "mean": the mean expression levels - "zero_logits": the logits for zero-inflated expression levels - "disp": the dispersion parameter - "cell_embs": the cell embeddings per class - "cell_emb": the main cell embedding - "cls_output": the output of the classifier

Source code in scprint/model/model.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
def forward(
    self,
    gene_pos: Tensor,
    expression: Optional[Tensor] = None,
    mask: Optional[Tensor] = None,
    req_depth: Optional[Tensor] = None,
    timepoint: Optional[Tensor] = None,  # (new_minibatch_of_nxt_cells,)
    get_gene_emb: bool = False,
    metacell_token: Optional[Tensor] = None,  # (minibatch, 1)
    depth_mult: Optional[Tensor] = None,
    do_sample: bool = False,
    do_mvc: bool = False,
    do_class: bool = False,
    get_attention_layer: list = [],
):
    """
    forward also called on self(), a full forward pass on the model

    Args:
        gene_pos (Tensor): A tensor of shape (minibatch, seq_len)
            representing the genes used for each cell in the minibatch.
        expression (Tensor, optional): A tensor of shape (minibatch, seq_len)
            representing the expression levels of genes in the minibatch. Defaults to None.
        mask (Tensor, optional): A tensor of shape (minibatch, seq_len)
            used to mask certain elements in the sequence during the forward pass. Defaults to None.
        req_depth (Tensor, optional): A tensor of shape (minibatch,)
            representing the full depth of each sequence in the minibatch. Defaults to None.
        depth_mult (Tensor, optional): A tensor of shape (minibatch,)
            representing the depth multiplier for each sequence in the minibatch. Defaults to None.
        timepoint (Tensor, optional): A tensor of shape (minibatch,)
            representing the timepoint associated with each sequence in the minibatch. Defaults to None.
        get_gene_emb (bool, optional): A flag indicating whether to return the gene embeddings.
            If True, the gene embeddings are included in the output. Defaults to False.
        do_sample (bool, optional): A flag indicating whether to sample the expression levels.
            If True, the expression levels are sampled during the forward pass. Defaults to False.
        get_attention_layer (list, optional): A list indicating which attention layers to return.
            If not empty, the specified attention layers are included in the output. Defaults to [].

    Returns:
        dict of output Tensors: A dictionary containing the output tensors from the forward pass.
            The keys of the dictionary depend on the input flags (get_gene_emb, do_sample, get_attention_layer).
            at minima, the dictionary codntains the following:
            - "mean": the mean expression levels
            - "zero_logits": the logits for zero-inflated expression levels
            - "disp": the dispersion parameter
            - "cell_embs": the cell embeddings per class
            - "cell_emb": the main cell embedding
            - "cls_output": the output of the classifier
    """
    encoding = self._encoder(
        gene_pos,
        expression,
        mask,
        req_depth=req_depth if self.depth_atinput else None,
        timepoint=timepoint,
        metacell_token=metacell_token,
    )
    if self.attn_bias != "none":
        if not hasattr(self, "nbias"):
            bias_path = os.path.join(
                Path(FILEDIR).parent.parent, "data", "bias_sparse.npz"
            )
            self.nbias = torch.Tensor(load_npz(bias_path).todense()).to(
                device=gene_pos.device, dtype=torch.float16
            )
        num = self.cell_embs_count if not self.cell_transformer else 0
        bias = torch.zeros(
            (
                gene_pos.shape[0],
                gene_pos.shape[1] + num,
                gene_pos.shape[1] + num,
            ),
            device=gene_pos.device,
            dtype=torch.float16,
        )
        # fade slowly through the iterations
        fade_factor = 400 / (400 + self.trainer.global_step)
        # bias[:, num:, :num] = -10_000  # do not pay attention to the cls embeddings
        bias[:, num:, num:] = (
            self.nbias[gene_pos[:, :, None], gene_pos[:, None, :]] * fade_factor
        )
    if self.cell_transformer:
        cell_encoding = encoding[:, : self.cell_embs_count, :]
        encoding = encoding[:, self.cell_embs_count :, :]
    transformer_output = self.transformer(
        encoding,
        return_qkv=get_attention_layer,
        bias=bias if self.attn_bias != "none" else None,
        bias_layer=list(range(self.nlayers - 1)),
    )
    if len(get_attention_layer) > 0:
        transformer_output, qkvs = transformer_output
    if self.cell_transformer:
        cell_output = self.cell_transformer(cell_encoding, x_kv=transformer_output)
        transformer_output = torch.cat([cell_output, transformer_output], dim=1)
    # if not provided we will mult by the current expression sum
    depth_mult = expression.sum(1) if depth_mult is None else depth_mult
    res = self._decoder(
        transformer_output,
        depth_mult,
        get_gene_emb,
        do_sample,
        do_mvc,
        do_class,
        req_depth=req_depth if not self.depth_atinput else None,
    )
    return (res, qkvs) if len(get_attention_layer) > 0 else res

log_adata

log_adata will log an adata from predictions. It will log to tensorboard and wandb if available

see @utils.log_adata

Source code in scprint/model/model.py
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
def log_adata(self, gtclass=None, name=""):
    """
    log_adata will log an adata from predictions.
    It will log to tensorboard and wandb if available

    see @utils.log_adata
    """
    try:
        mdir = self.logger.save_dir if self.logger.save_dir is not None else "/tmp"
    except:
        mdir = "data/"
    if not os.path.exists(mdir):
        os.makedirs(mdir)
    adata, fig = utils.make_adata(
        self.embs,
        self.classes,
        self.pred if not self.keep_all_cls_pred else None,
        self.attn.get(),
        self.global_step,
        self.label_decoders,
        self.labels_hierarchy,
        gtclass,
        self.name + "_" + name + "_" + str(self.global_rank),
        mdir,
        self.doplot,
    )
    if self.doplot:
        try:
            self.logger.experiment.add_figure(fig)
        except:
            print("couldn't log to tensorboard")
        try:
            self.logger.log_image(key="umaps", images=[fig])
        except:
            print("couldn't log to wandb")

    return adata

on_fit_start

@see pl.LightningModule

Source code in scprint/model/model.py
773
774
775
776
777
778
779
def on_fit_start(self):
    """@see pl.LightningModule"""
    if type(self.transformer) is FlashTransformer:
        for encoder_layers in self.transformer.blocks:
            encoder_layers.set_seq_parallel(True)
    for k, v in self.mat_labels_hierarchy.items():
        self.mat_labels_hierarchy[k] = v.to(self.device)

on_predict_epoch_end

@see pl.LightningModule will

Source code in scprint/model/model.py
1564
1565
1566
1567
1568
1569
1570
def on_predict_epoch_end(self):
    """@see pl.LightningModule will"""
    if self.pos.shape[0] < 100:
        return
    if self.pred_log_adata:
        print("adding on disk")
        return self.log_adata(name="predict_part_" + str(self.counter))

on_predict_epoch_start

@see pl.LightningModule

Source code in scprint/model/model.py
1347
1348
1349
1350
1351
1352
1353
1354
1355
def on_predict_epoch_start(self):
    """@see pl.LightningModule"""
    self.embs = None
    self.attn.data = None
    self.attn.attn = None
    self.counter = 0
    if type(self.transformer) is FlashTransformer:
        for encoder_layers in self.transformer.blocks:
            encoder_layers.set_seq_parallel(False)

on_validation_epoch_end

@see pl.LightningModule

Source code in scprint/model/model.py
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
def on_validation_epoch_end(self):
    """@see pl.LightningModule"""
    self.embs = self.all_gather(self.embs).view(-1, self.embs.shape[-1])
    self.info = self.all_gather(self.info).view(-1, self.info.shape[-1])
    self.pred = (
        self.all_gather(self.pred).view(-1, self.pred.shape[-1])
        if self.pred is not None
        else None
    )
    self.pos = self.all_gather(self.pos).view(-1, self.pos.shape[-1])
    if self.trainer.state.stage != "sanity_check":
        if self.trainer.is_global_zero:
            print("logging anndata")
            sch = self.lr_schedulers()
            sch.step(self.trainer.callback_metrics["val_loss"])
            # run the test function on specific dataset
            self.log_adata(
                gtclass=self.info, name="validation_part_" + str(self.counter)
            )
            if (self.current_epoch + 1) % self.test_every == 0:
                self.on_test_epoch_end()
            # Synchronize all processes with a timeout
        if torch.distributed.is_initialized():
            # Set a timeout that's longer than your test typically takes
            # Write rank to file for debugging
            self.trainer.strategy.barrier()

optimizer_step

@see pl.LightningModule

Source code in scprint/model/model.py
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_closure):
    """@see pl.LightningModule"""
    # update params
    # manually warm up lr without a scheduler
    # making sure that we don't do this during lrfinder
    lr_scale = None
    prev_lr = None
    if (
        self.trainer.global_step < self.warmup_duration + self.lrfinder_steps
    ) and self.lrfinder_steps <= self.trainer.global_step:
        for i, pg in enumerate(optimizer.param_groups):
            lr_scale = min(
                1.0, float(self.trainer.global_step + 1) / self.warmup_duration
            )
            prev_lr = pg["lr"]
            pg["lr"] = lr_scale * self.hparams.lr
    for i, pg in enumerate(optimizer.param_groups):
        # if pg["lr"] < 2e-5:
        #    pg["lr"] = 2e-5
        self.log("lr_" + str(i), pg["lr"])
    if optimizer.param_groups[0]["lr"] > self.hparams.lr:
        print(optimizer.param_groups[0]["lr"], self.hparams.lr)
        print(lr_scale, self.warmup_duration, self.trainer.global_step, prev_lr)
        if prev_lr is not None:
            pg["lr"] = prev_lr
        else:
            raise ValueError("OPTIMIZER HAS INCREASED LR. WHYY?")

    optimizer.step(closure=optimizer_closure)

predict_step

embed given gene expression, encode the gene embedding and cell embedding.

Returns:
  • Tensor

    description

Source code in scprint/model/model.py
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
def predict_step(self, batch, batch_idx):
    """
    embed given gene expression, encode the gene embedding and cell embedding.

    Args:
        batch @see training_step

    Returns:
        Tensor: _description_
    """
    return self._predict(
        batch["genes"],
        batch["x"],
        batch["depth"],
        self.predict_mode,
        self.pred_embedding,
        self.get_attention_layer,
        self.predict_depth_mult,
    )

training_step

training_step defines the train loop. It is independent of forward

@see pl.LightningModule

Returns:
  • _type_

    description

Source code in scprint/model/model.py
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
def training_step(
    self,
    batch: Dict[str, Tensor],
    batch_idx,
):
    """
    training_step defines the train loop. It is independent of forward

    @see pl.LightningModule

    Returns:
        _type_: _description_
    """
    total_loss, losses = self._full_training(
        batch=batch,
        do_denoise=self.do_denoise,
        noise=self.noise,
        do_next_tp=self.do_next_tp,
        do_cce=self.do_cce,
        cce_temp=self.cce_temp,
        do_ecs=self.do_ecs,
        do_mvc=self.do_mvc,
        do_adv_cls=self.do_adv_cls,
        do_adv_batch=self.do_adv_batch,
        do_cls=self.do_cls,
        do_generate=self.do_generate,
        run_full_forward=self.run_full_forward,
        mask_ratio=self.mask_ratio,
    )

    self.log("train_loss", total_loss, prog_bar=True, sync_dist=True)
    self.log_dict(losses, prog_bar=True, sync_dist=True)
    return total_loss

validation_step

validation_step defines the validation loop. It is independent of forward @see pl.LightningModule

Parameters:
  • batch (list[Tensor]) –

    @see training_step

Source code in scprint/model/model.py
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
def validation_step(
    self,
    batch,
    batch_idx,
):
    """
    validation_step defines the validation loop. It is independent of forward
    @see pl.LightningModule

    Args:
        batch (list[Tensor]): @see training_step
    """
    val_loss, losses = self._full_training(
        batch=batch,
        do_denoise=self.do_denoise,
        noise=self.noise,
        do_next_tp=self.do_next_tp,
        do_cce=self.do_cce,
        cce_temp=self.cce_temp,
        do_ecs=self.do_ecs,
        do_mvc=self.do_mvc,
        do_adv_cls=self.do_adv_cls,
        do_adv_batch=self.do_adv_batch,
        do_cls=self.do_cls,
        do_generate=self.do_generate,
        run_full_forward=self.run_full_forward,
        mask_ratio=self.mask_ratio,
    )
    expression = batch["x"]
    gene_pos = batch["genes"]
    depth = batch["depth"]
    metacell_token = batch.get("is_meta", None)
    # TODO: make this faster by only calling val loss
    if self.embs is not None:
        if self.embs.shape[0] < 100_000:
            self.info = torch.cat([self.info, batch["class"]])
            self._predict(
                gene_pos,
                expression,
                depth,
                pred_embedding=self.pred_embedding,
                max_size_in_mem=120_000,
                metacell_token=metacell_token,
            )
    else:
        self.info = batch["class"]
        self._predict(
            gene_pos,
            expression,
            depth,
            pred_embedding=self.pred_embedding,
            max_size_in_mem=120_000,
            metacell_token=metacell_token,
        )
    self.log("val_loss", val_loss, sync_dist=True)
    self.log_dict(losses, sync_dist=True)
    return val_loss

losses

scprint.model.loss

Classes:

Name Description
AdversarialDiscriminatorLoss

Functions:

Name Description
classification

Computes the classification loss for a given batch of predictions and ground truth labels.

contrastive_loss

Computes NT-Xent loss (InfoNCE) between two sets of vectors.

criterion_neg_log_bernoulli

Compute the negative log-likelihood of Bernoulli distribution

ecs

ecs Computes the similarity of cell embeddings based on a threshold.

grad_reverse

grad_reverse Reverses the gradient of the input tensor.

masked_mae

Compute the masked MAE loss between input and target.

masked_mse

Compute the masked MSE loss between input and target.

masked_nb

Compute the masked negative binomial loss between input and target.

masked_relative_error

Compute the masked relative error between input and target.

mse

Compute the MSE loss between input and target.

nb

Computes the negative binomial (NB) loss.

nb_dist

nb_dist Computes the negative binomial distribution.

within_sample

Compute dissimilarity between embeddings within each sample

zinb

Computes zero-inflated negative binomial (ZINB) loss.

AdversarialDiscriminatorLoss

Bases: Module

Discriminator for the adversarial training for batch correction.

Parameters:
  • d_model (int) –

    The size of the input tensor.

  • n_cls (int) –

    The number of classes.

  • nlayers (int, default: 3 ) –

    The number of layers in the discriminator. Defaults to 3.

  • activation (callable, default: LeakyReLU ) –

    The activation function. Defaults to nn.LeakyReLU.

  • reverse_grad (bool, default: True ) –

    Whether to reverse the gradient. Defaults

Methods:

Name Description
forward

Args:

Source code in scprint/model/loss.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def __init__(
    self,
    d_model: int,
    n_cls: int,
    nlayers: int = 3,
    activation: callable = nn.LeakyReLU,
    reverse_grad: bool = True,
):
    """
    Discriminator for the adversarial training for batch correction.

    Args:
        d_model (int): The size of the input tensor.
        n_cls (int): The number of classes.
        nlayers (int, optional): The number of layers in the discriminator. Defaults to 3.
        activation (callable, optional): The activation function. Defaults to nn.LeakyReLU.
        reverse_grad (bool, optional): Whether to reverse the gradient. Defaults
    """
    super().__init__()
    # module list
    self.decoder = nn.ModuleList()
    for _ in range(nlayers - 1):
        self.decoder.append(nn.Linear(d_model, d_model))
        self.decoder.append(nn.LayerNorm(d_model))
        self.decoder.append(activation())
    self.out_layer = nn.Linear(d_model, n_cls)
    self.reverse_grad = reverse_grad

forward

Parameters:
  • x (Tensor) –

    Tensor, shape [batch_size, embsize]

Source code in scprint/model/loss.py
337
338
339
340
341
342
343
344
345
346
347
def forward(self, x: Tensor, batch_labels: Tensor) -> Tensor:
    """
    Args:
        x: Tensor, shape [batch_size, embsize]
    """
    if self.reverse_grad:
        x = grad_reverse(x, lambd=1.0)
    for layer in self.decoder:
        x = layer(x)
    x = self.out_layer(x)
    return F.cross_entropy(x, batch_labels)

classification

Computes the classification loss for a given batch of predictions and ground truth labels.

Parameters:
  • clsname (str) –

    The name of the label.

  • pred (Tensor) –

    The predicted logits for the batch.

  • cl (Tensor) –

    The ground truth labels for the batch.

  • maxsize (int) –

    The number of possible labels.

  • labels_hierarchy (dict, default: {} ) –

    The hierarchical structure of the labels. Defaults to {}.

Raises:
  • ValueError

    If the clsname is not found in the labels_hierarchy dictionary.

Returns:
  • Tensor( Tensor ) –

    The computed binary cross entropy loss for the given batch.

Source code in scprint/model/loss.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def classification(
    clsname: str,
    pred: torch.Tensor,
    cl: torch.Tensor,
    maxsize: int,
    labels_hierarchy: Optional[Dict[str, Dict[int, list[int]]]] = {},
) -> torch.Tensor:
    """
    Computes the classification loss for a given batch of predictions and ground truth labels.

    Args:
        clsname (str): The name of the label.
        pred (Tensor): The predicted logits for the batch.
        cl (Tensor): The ground truth labels for the batch.
        maxsize (int): The number of possible labels.
        labels_hierarchy (dict, optional): The hierarchical structure of the labels. Defaults to {}.

    Raises:
        ValueError: If the clsname is not found in the labels_hierarchy dictionary.

    Returns:
        Tensor: The computed binary cross entropy loss for the given batch.
    """
    newcl = torch.zeros(
        (cl.shape[0], maxsize), device=cl.device
    )  # batchsize * n_labels
    # if we don't know the label we set the weight to 0 else to 1
    valid_indices = (cl != -1) & (cl < maxsize)
    valid_cl = cl[valid_indices]
    newcl[valid_indices, valid_cl] = 1

    weight = torch.ones_like(newcl, device=cl.device)
    weight[cl == -1, :] = 0
    inv = cl >= maxsize
    # if we have non leaf values, we don't know so we don't compute grad and set weight to 0
    # and add labels that won't be counted but so that we can still use them
    if inv.any():
        if clsname in labels_hierarchy.keys():
            clhier = labels_hierarchy[clsname]

            inv_weight = weight[inv]
            # we set the weight of the elements that are not leaf to 0
            # i.e. the elements where we will compute the max
            inv_weight[clhier[cl[inv] - maxsize]] = 0
            weight[inv] = inv_weight

            addnewcl = torch.ones(
                weight.shape[0], device=pred.device
            )  # no need to set the other to 0 as the weight of the loss is set to 0
            addweight = torch.zeros(weight.shape[0], device=pred.device)
            addweight[inv] = 1
            # computing hierarchical labels and adding them to cl
            addpred = pred.clone()
            # we only keep the elements where we need to compute the max,
            # for the rest we set them to -inf, so that they won't have any impact on the max()
            inv_addpred = addpred[inv]
            inv_addpred[inv_weight.to(bool)] = torch.finfo(pred.dtype).min
            addpred[inv] = inv_addpred

            # differentiable max
            addpred = torch.logsumexp(addpred, dim=-1)

            # we add the new labels to the cl
            newcl = torch.cat([newcl, addnewcl.unsqueeze(1)], dim=1)
            pred = torch.cat([pred, addpred.unsqueeze(1)], dim=1)
            weight = torch.cat([weight, addweight.unsqueeze(1)], dim=1)
        else:
            raise ValueError("need to use labels_hierarchy for this usecase")

    myloss = torch.nn.functional.binary_cross_entropy_with_logits(
        pred, target=newcl, weight=weight
    )
    return myloss

contrastive_loss

Computes NT-Xent loss (InfoNCE) between two sets of vectors.

Parameters:
  • x (Tensor) –

    Tensor of shape [batch_size, feature_dim]

  • y (Tensor) –

    Tensor of shape [batch_size, feature_dim]

  • temperature (float, default: 0.1 ) –

    Temperature parameter to scale the similarities. Lower values make the model more confident/selective. Typical values are between 0.1 and 0.5.

Returns:
  • Tensor( Tensor ) –

    NT-Xent loss value

Note
  • Assumes x[i] and y[i] are positive pairs
  • All other combinations are considered negative pairs
  • Uses cosine similarity scaled by temperature
Source code in scprint/model/loss.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def contrastive_loss(x: Tensor, y: Tensor, temperature: float = 0.1) -> Tensor:
    """
    Computes NT-Xent loss (InfoNCE) between two sets of vectors.

    Args:
        x: Tensor of shape [batch_size, feature_dim]
        y: Tensor of shape [batch_size, feature_dim]
        temperature: Temperature parameter to scale the similarities.
            Lower values make the model more confident/selective.
            Typical values are between 0.1 and 0.5.

    Returns:
        Tensor: NT-Xent loss value

    Note:
        - Assumes x[i] and y[i] are positive pairs
        - All other combinations are considered negative pairs
        - Uses cosine similarity scaled by temperature
    """
    # Check input dimensions
    assert x.shape == y.shape, "Input tensors must have the same shape"
    batch_size = x.shape[0]

    # Compute cosine similarity matrix
    # x_unsqueeze: [batch_size, 1, feature_dim]
    # y_unsqueeze: [1, batch_size, feature_dim]
    # -> similarities: [batch_size, batch_size]
    similarities = (
        F.cosine_similarity(x.unsqueeze(1), y.unsqueeze(0), dim=2) / temperature
    )

    # The positive pairs are on the diagonal
    labels = torch.arange(batch_size, device=x.device)

    # Cross entropy loss
    return F.cross_entropy(similarities, labels)

criterion_neg_log_bernoulli

Compute the negative log-likelihood of Bernoulli distribution

Source code in scprint/model/loss.py
149
150
151
152
153
154
155
156
def criterion_neg_log_bernoulli(input: Tensor, target: Tensor, mask: Tensor) -> Tensor:
    """
    Compute the negative log-likelihood of Bernoulli distribution
    """
    mask = mask.float()
    bernoulli = torch.distributions.Bernoulli(probs=input)
    masked_log_probs = bernoulli.log_prob((target > 0).float()) * mask
    return -masked_log_probs.sum() / mask.sum()

ecs

ecs Computes the similarity of cell embeddings based on a threshold.

Parameters:
  • cell_emb (Tensor) –

    A tensor representing cell embeddings.

  • ecs_threshold (float, default: 0.5 ) –

    A threshold for determining similarity. Defaults to 0.5.

Returns:
  • Tensor( Tensor ) –

    A tensor representing the mean of 1 minus the square of the difference between the cosine similarity and the threshold.

Source code in scprint/model/loss.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def ecs(cell_emb: Tensor, ecs_threshold: float = 0.5) -> Tensor:
    """
    ecs Computes the similarity of cell embeddings based on a threshold.

    Args:
        cell_emb (Tensor): A tensor representing cell embeddings.
        ecs_threshold (float, optional): A threshold for determining similarity. Defaults to 0.5.

    Returns:
        Tensor: A tensor representing the mean of 1 minus the square of the difference between the cosine similarity and the threshold.
    """
    # Here using customized cosine similarity instead of F.cosine_similarity
    # to avoid the pytorch issue of similarity larger than 1.0, pytorch # 78064
    # normalize the embedding
    cell_emb_normed = F.normalize(cell_emb, p=2, dim=1)
    cos_sim = torch.mm(cell_emb_normed, cell_emb_normed.t())

    # mask out diagnal elements
    mask = torch.eye(cos_sim.size(0)).bool().to(cos_sim.device)
    cos_sim = cos_sim.masked_fill(mask, 0.0)
    # only optimize positive similarities
    cos_sim = F.relu(cos_sim)
    return torch.mean(1 - (cos_sim - ecs_threshold) ** 2)

grad_reverse

grad_reverse Reverses the gradient of the input tensor.

Parameters:
  • x (Tensor) –

    The input tensor whose gradient is to be reversed.

  • lambd (float, default: 1.0 ) –

    The scaling factor for the reversed gradient. Defaults to 1.0.

Returns:
  • Tensor( Tensor ) –

    The input tensor with its gradient reversed during the backward pass.

Source code in scprint/model/loss.py
361
362
363
364
365
366
367
368
369
370
371
372
def grad_reverse(x: Tensor, lambd: float = 1.0) -> Tensor:
    """
    grad_reverse Reverses the gradient of the input tensor.

    Args:
        x (Tensor): The input tensor whose gradient is to be reversed.
        lambd (float, optional): The scaling factor for the reversed gradient. Defaults to 1.0.

    Returns:
        Tensor: The input tensor with its gradient reversed during the backward pass.
    """
    return GradReverse.apply(x, lambd)

masked_mae

Compute the masked MAE loss between input and target. MAE = mean absolute error

Source code in scprint/model/loss.py
35
36
37
38
39
40
41
42
def masked_mae(input: Tensor, target: Tensor, mask: Tensor) -> Tensor:
    """
    Compute the masked MAE loss between input and target.
    MAE = mean absolute error
    """
    mask = mask.float()
    loss = F.l1_loss(input * mask, target * mask, reduction="sum")
    return loss / mask.sum()

masked_mse

Compute the masked MSE loss between input and target.

Source code in scprint/model/loss.py
26
27
28
29
30
31
32
def masked_mse(input: Tensor, target: Tensor, mask: Tensor) -> Tensor:
    """
    Compute the masked MSE loss between input and target.
    """
    mask = mask.float()
    loss = F.mse_loss(input * mask, target * mask, reduction="sum")
    return loss / mask.sum()

masked_nb

Compute the masked negative binomial loss between input and target.

Source code in scprint/model/loss.py
45
46
47
48
49
50
51
52
def masked_nb(input: Tensor, target: Tensor, mask: Tensor) -> Tensor:
    """
    Compute the masked negative binomial loss between input and target.
    """
    mask = mask.float()
    nb = torch.distributions.NegativeBinomial(total_count=target, probs=input)
    masked_log_probs = nb.log_prob(target) * mask
    return -masked_log_probs.sum() / mask.sum()

masked_relative_error

Compute the masked relative error between input and target.

Source code in scprint/model/loss.py
159
160
161
162
163
164
165
166
167
def masked_relative_error(
    input: Tensor, target: Tensor, mask: torch.LongTensor
) -> Tensor:
    """
    Compute the masked relative error between input and target.
    """
    assert mask.any()
    loss = torch.abs(input[mask] - target[mask]) / (target[mask] + 1e-6)
    return loss.mean()

mse

Compute the MSE loss between input and target.

Source code in scprint/model/loss.py
15
16
17
18
19
20
21
22
23
def mse(input: Tensor, target: Tensor) -> Tensor:
    """
    Compute the MSE loss between input and target.
    """
    input = torch.log2(input + 1)
    input = (input / torch.sum(input, dim=1, keepdim=True)) * 10000
    target = torch.log2(target + 1)
    target = target / torch.sum(target, dim=1, keepdim=True) * 10000
    return F.mse_loss(input, target, reduction="mean")

nb

Computes the negative binomial (NB) loss.

This function was adapted from scvi-tools.

Parameters:
  • target (Tensor) –

    Ground truth data.

  • mu (Tensor) –

    Means of the negative binomial distribution (must have positive support).

  • theta (Tensor) –

    Inverse dispersion parameter (must have positive support).

  • eps (float, default: 1e-08 ) –

    Numerical stability constant. Defaults to 1e-8.

Returns:
  • Tensor

    NB loss value.

Source code in scprint/model/loss.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def nb(target: Tensor, mu: Tensor, theta: Tensor, eps=1e-8):
    """
    Computes the negative binomial (NB) loss.

    This function was adapted from scvi-tools.

    Args:
        target (Tensor): Ground truth data.
        mu (Tensor): Means of the negative binomial distribution (must have positive support).
        theta (Tensor): Inverse dispersion parameter (must have positive support).
        eps (float, optional): Numerical stability constant. Defaults to 1e-8.

    Returns:
        Tensor: NB loss value.
    """
    if theta.ndimension() == 1:
        theta = theta.view(1, theta.size(0))

    log_theta_mu_eps = torch.log(theta + mu + eps)
    res = (
        theta * (torch.log(theta + eps) - log_theta_mu_eps)
        + target * (torch.log(mu + eps) - log_theta_mu_eps)
        + torch.lgamma(target + theta)
        - torch.lgamma(theta)
        - torch.lgamma(target + 1)
    )

    return -res.mean()

nb_dist

nb_dist Computes the negative binomial distribution.

Parameters:
  • x (Tensor) –

    Torch Tensor of observed data.

  • mu (Tensor) –

    Torch Tensor of means of the negative binomial distribution (must have positive support).

  • theta (Tensor) –

    Torch Tensor of inverse dispersion parameter (must have positive support).

  • eps (float, default: 1e-08 ) –

    Numerical stability constant. Defaults to 1e-8.

Returns:
  • Tensor

    Negative binomial loss value.

Source code in scprint/model/loss.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def nb_dist(x: Tensor, mu: Tensor, theta: Tensor, eps=1e-8):
    """
    nb_dist Computes the negative binomial distribution.

    Args:
        x (Tensor): Torch Tensor of observed data.
        mu (Tensor): Torch Tensor of means of the negative binomial distribution (must have positive support).
        theta (Tensor): Torch Tensor of inverse dispersion parameter (must have positive support).
        eps (float, optional): Numerical stability constant. Defaults to 1e-8.

    Returns:
        Tensor: Negative binomial loss value.
    """
    loss = -NegativeBinomial(mu=mu, theta=theta).log_prob(x)
    return loss

within_sample

Compute dissimilarity between embeddings within each sample using a combination of cosine and L2 distance

Source code in scprint/model/loss.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
def within_sample(cell_embs):
    """
    Compute dissimilarity between embeddings within each sample
    using a combination of cosine and L2 distance
    """
    batch_size, num_embeddings, emb_dim = cell_embs.shape

    # Normalize embeddings for cosine similarity
    cell_embs_norm = F.normalize(cell_embs, p=2, dim=-1)

    # Compute pairwise cosine similarities
    cos_sim = torch.bmm(cell_embs_norm, cell_embs_norm.transpose(1, 2))

    # Compute pairwise L2 distances (normalized by embedding dimension)
    l2_dist = torch.cdist(cell_embs, cell_embs, p=2) / np.sqrt(emb_dim)

    # Create mask for pairs (excluding self-similarity)
    mask = 1 - torch.eye(num_embeddings, device=cos_sim.device)
    mask = mask.unsqueeze(0).expand(batch_size, -1, -1)

    # Combine losses:
    # - High cosine similarity should be penalized
    # - Small L2 distance should be penalized
    cos_loss = (cos_sim * mask).pow(2).mean()
    l2_loss = 1.0 / (l2_dist * mask + 1e-3).mean()

    return 0.5 * cos_loss + 0.5 * l2_loss

zinb

Computes zero-inflated negative binomial (ZINB) loss.

This function was modified from scvi-tools.

Parameters:
  • target (Tensor) –

    Torch Tensor of ground truth data.

  • mu (Tensor) –

    Torch Tensor of means of the negative binomial (must have positive support).

  • theta (Tensor) –

    Torch Tensor of inverse dispersion parameter (must have positive support).

  • pi (Tensor) –

    Torch Tensor of logits of the dropout parameter (real support).

  • eps (float, default: 1e-08 ) –

    Numerical stability constant. Defaults to 1e-8.

Returns:
  • Tensor

    ZINB loss value.

Source code in scprint/model/loss.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def zinb(
    target: Tensor,
    mu: Tensor,
    theta: Tensor,
    pi: Tensor,
    eps=1e-8,
):
    """
    Computes zero-inflated negative binomial (ZINB) loss.

    This function was modified from scvi-tools.

    Args:
        target (Tensor): Torch Tensor of ground truth data.
        mu (Tensor): Torch Tensor of means of the negative binomial (must have positive support).
        theta (Tensor): Torch Tensor of inverse dispersion parameter (must have positive support).
        pi (Tensor): Torch Tensor of logits of the dropout parameter (real support).
        eps (float, optional): Numerical stability constant. Defaults to 1e-8.

    Returns:
        Tensor: ZINB loss value.
    """
    #  uses log(sigmoid(x)) = -softplus(-x)
    softplus_pi = F.softplus(-pi)
    # eps to make it positive support and taking the log
    log_theta_mu_eps = torch.log(theta + mu + eps)
    pi_theta_log = -pi + theta * (torch.log(theta + eps) - log_theta_mu_eps)

    case_zero = F.softplus(pi_theta_log) - softplus_pi
    mul_case_zero = torch.mul((target < eps).type(torch.float32), case_zero)

    case_non_zero = (
        -softplus_pi
        + pi_theta_log
        + target * (torch.log(mu + eps) - log_theta_mu_eps)
        + torch.lgamma(target + theta)
        - torch.lgamma(theta)
        - torch.lgamma(target + 1)
    )
    mul_case_non_zero = torch.mul((target > eps).type(torch.float32), case_non_zero)

    res = mul_case_zero + mul_case_non_zero
    # we want to minize the loss but maximize the log likelyhood
    return -res.mean()

utils

scprint.model.utils

Classes:

Name Description
Attention
WeightedMasker

Functions:

Name Description
downsample_profile

This function downsamples the expression profile of a given single cell RNA matrix.

make_adata

This function creates an AnnData object from the given input parameters.

simple_masker

Randomly mask a batch of data.

test

Test the given model on the full set of benchmarks and save the results to JSON files.

zinb_sample

zinb_sample This function generates a sample from a Zero-Inflated Negative Binomial (ZINB) distribution.

Attention

Initialize the Attention class.

Parameters:
  • gene_dim (int) –

    The dimension of the gene.

  • additional_tokens (int, default: 0 ) –

    The number of additional tokens to add.

  • comp_attn (bool, default: False ) –

    Whether to compute attention or it is precomputed

  • apply_softmax (bool, default: False ) –

    Whether to apply softmax to the attention.

  • sum_heads (bool, default: True ) –

    Whether to sum the heads.

Methods:

Name Description
add_attn

Aggregate the attention or data based on the comp_attn flag.

add_qk

Add data to the internal storage.

get

Get the aggregated attention or data.

Source code in scprint/model/utils.py
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
def __init__(
    self,
    gene_dim: int,
    comp_attn: bool = False,
    apply_softmax: bool = False,
    sum_heads: bool = True,
    additional_tokens: int = 0,
):
    """
    Initialize the Attention class.

    Args:
        gene_dim (int): The dimension of the gene.
        additional_tokens (int): The number of additional tokens to add.
        comp_attn (bool): Whether to compute attention or it is precomputed
        apply_softmax (bool): Whether to apply softmax to the attention.
        sum_heads (bool): Whether to sum the heads.
    """
    self.data: Optional[Tensor] = None
    self.gene_dim: int = gene_dim
    self.additional_tokens: int = additional_tokens
    self.div: Optional[Tensor] = None
    self.apply_softmax: bool = apply_softmax
    self.sum_heads: bool = sum_heads
    self.comp_attn: bool = True

add_attn

Aggregate the attention or data based on the comp_attn flag.

Parameters:
  • x (List[Tensor]) –

    List of tensors to aggregate. Tensor of size (batch, seq_len, 2, heads, emb)

  • pos (Tensor) –

    Position tensor.

Source code in scprint/model/utils.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
def add_attn(
    self, x: List[Tensor], pos: Tensor, expr: Optional[Tensor] = None
) -> None:
    """
    Aggregate the attention or data based on the comp_attn flag.

    Args:
        x (List[Tensor]): List of tensors to aggregate. Tensor of size (batch, seq_len, 2, heads, emb)
        pos (Tensor): Position tensor.
    """
    if self.data is None:
        self.data = torch.zeros(
            [
                self.gene_dim + self.additional_tokens,
                self.gene_dim + self.additional_tokens,
                len(x) * x[0].shape[3],
            ],
            device=pos.device,
            dtype=torch.float32,
        )
        self.div = torch.zeros(1, device=pos.device, dtype=torch.float32)

    for i, elem in enumerate(x):
        batch, seq_len, _, heads, _ = elem.shape
        if self.apply_softmax:
            attn = torch.nn.functional.softmax(
                elem[:, :, 0, :, :].permute(0, 2, 1, 3)
                @ elem[:, :, 1, :, :].permute(0, 2, 3, 1),
                dim=-1,
            )
            if expr is not None:
                attn = attn * (expr > 0).float()
            self.data[:, :, heads * i : heads * (i + 1)] += (
                attn.sum(0).permute(1, 2, 0) / batch
            )
        else:
            self.data[:, :, heads * i : heads * (i + 1)] += (
                elem[:, :, 0, :, :].permute(0, 2, 1, 3)
                @ elem[:, :, 1, :, :].permute(0, 2, 3, 1)
            ).sum(0).permute(1, 2, 0) / batch
    self.div += 1

add_qk

Add data to the internal storage.

Parameters:
  • x (List[Tensor]) –

    List of tensors to add.

  • pos (Tensor) –

    Position tensor.

Source code in scprint/model/utils.py
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
def add_qk(
    self, x: List[Tensor], pos: Tensor, expr: Optional[Tensor] = None
) -> None:
    """
    Add data to the internal storage.

    Args:
        x (List[Tensor]): List of tensors to add.
        pos (Tensor): Position tensor.
    """
    if self.data is None:
        self.data = torch.zeros(
            [len(x), self.gene_dim + self.additional_tokens] + list(x[0].shape[2:]),
            device=pos.device,
        )
        self.div = torch.zeros(
            self.gene_dim + self.additional_tokens, device=pos.device
        )
    for i in range(x[0].shape[0]):
        loc = torch.cat(
            [
                torch.arange(self.additional_tokens, device=pos.device),
                pos[i] + self.additional_tokens,
            ]
        ).int()
        for j in range(len(x)):
            self.data[j, loc, :, :, :] += x[j][i]
        self.div[loc] += 1

get

Get the aggregated attention or data.

Returns:
  • Optional[ndarray]

    Optional[np.ndarray]: The aggregated attention or data.

Source code in scprint/model/utils.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
def get(self) -> Optional[np.ndarray]:
    """
    Get the aggregated attention or data.

    Returns:
        Optional[np.ndarray]: The aggregated attention or data.
    """
    if self.comp_attn:
        if self.data is None:
            return None
        # shape is (layers, genes, qkv, heads, emb)
        return self.data / self.div.view(1, self.div.shape[0], 1, 1, 1)
    else:
        if self.data is None:
            return None
        self.data.div_(self.div)
        return self.data

WeightedMasker

Randomly mask a batch of data.

Parameters:
  • genes (list[str]) –

    The list of genes the model might see.

  • TFs (list[str], default: fileToList(FILEDIR + '/../../data/main/TFs.txt') ) –

    The list of TFs the model can drop.

  • inv_weight (float, default: 0.2 ) –

    How likely it is to drop a non TF compared to a TF.

Returns:
  • torch.Tensor: A tensor of masked data.

Source code in scprint/model/utils.py
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
def __init__(
    self,
    genes: list[str],
    TFs: list[str] = utils.fileToList(FILEDIR + "/../../data/main/TFs.txt"),
    inv_weight: float = 0.2,
):
    """
    Randomly mask a batch of data.

    Args:
        genes (list[str]): The list of genes the model might see.
        TFs (list[str]): The list of TFs the model can drop.
        inv_weight (float): How likely it is to drop a non TF compared to a TF.

    Returns:
        torch.Tensor: A tensor of masked data.
    """
    TFs = set(TFs)
    self.weights = torch.tensor(
        [1 if gene in TFs else inv_weight for gene in genes]
    )
    self.max_to_drop = (self.weights == inv_weight).sum()
    self.inv_weight = inv_weight

downsample_profile

This function downsamples the expression profile of a given single cell RNA matrix.

The noise is applied based on the renoise parameter, the total counts of the matrix, and the number of genes. The function first calculates the noise threshold (scaler) based on the renoise parameter. It then generates an initial matrix count by applying a Poisson distribution to a random tensor scaled by the total counts and the number of genes. The function then models the sampling zeros by applying a Poisson distribution to a random tensor scaled by the noise threshold, the total counts, and the number of genes. The function also models the technical zeros by generating a random tensor and comparing it to the noise threshold. The final matrix count is calculated by subtracting the sampling zeros from the initial matrix count and multiplying by the technical zeros. The function ensures that the final matrix count is not less than zero by taking the maximum of the final matrix count and a tensor of zeros. The function returns the final matrix count.

Parameters:
  • mat (Tensor) –

    The input matrix.

  • dropout (float) –

    The renoise parameter.

Returns:
  • torch.Tensor: The matrix count after applying noise.

Source code in scprint/model/utils.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
def downsample_profile(mat: Tensor, dropout: float, method="new", randsamp=False):
    """
    This function downsamples the expression profile of a given single cell RNA matrix.

    The noise is applied based on the renoise parameter,
    the total counts of the matrix, and the number of genes. The function first calculates the noise
    threshold (scaler) based on the renoise parameter. It then generates an initial matrix count by
    applying a Poisson distribution to a random tensor scaled by the total counts and the number of genes.
    The function then models the sampling zeros by applying a Poisson distribution to a random tensor
    scaled by the noise threshold, the total counts, and the number of genes. The function also models
    the technical zeros by generating a random tensor and comparing it to the noise threshold. The final
    matrix count is calculated by subtracting the sampling zeros from the initial matrix count and
    multiplying by the technical zeros. The function ensures that the final matrix count is not less
    than zero by taking the maximum of the final matrix count and a tensor of zeros. The function
    returns the final matrix count.

    Args:
        mat (torch.Tensor): The input matrix.
        dropout (float): The renoise parameter.

    Returns:
        torch.Tensor: The matrix count after applying noise.
    """
    # Randomly drop on average N counts to each element of expression using a heavy tail Gaussian distribution
    # here we try to get the scale of the distribution so as to remove the right number of counts from each gene
    # https://genomebiology.biomedcentral.com/articles/10.1186/s13059-022-02601-5#:~:text=Zero%20measurements%20in%20scRNA%2Dseq,generation%20of%20scRNA%2Dseq%20data.
    if randsamp:
        dropout = torch.rand(mat.shape, device=mat.device) * dropout
    if method == "old":
        totcounts = mat.sum(1)
        batch = mat.shape[0]
        ngenes = mat.shape[1]
        tnoise = 1 - (1 - dropout) ** (1 / 2)
        # we model the sampling zeros (dropping 30% of the reads)
        res = torch.poisson(
            torch.rand((batch, ngenes)).to(device=mat.device)
            * ((tnoise * totcounts.unsqueeze(1)) / (0.5 * ngenes))
        ).int()
        # we model the technical zeros (dropping 50% of the genes)
        drop = (torch.rand((batch, ngenes)) > tnoise).int().to(device=mat.device)

        mat = (mat - res) * drop
        return torch.maximum(mat, torch.Tensor([[0]]).to(device=mat.device)).int()
    elif method == "jules":
        scaler = (1 - dropout) ** (1 / 2)
        notdrop = (
            torch.rand(
                mat.shape,
                device=mat.device,
            )
            < scaler
        ).int()
        notdrop[mat == 0] = 0
        # apply the dropout after the poisson, right?
        return notdrop * torch.poisson(mat * scaler)
    elif method == "new":
        batch = mat.shape[0]
        ngenes = mat.shape[1]
        dropout = dropout * 1.1
        # we model the sampling zeros (dropping 30% of the reads)
        res = torch.poisson((mat * (dropout / 2))).int()
        # we model the technical zeros (dropping 50% of the genes)
        notdrop = (
            torch.rand((batch, ngenes), device=mat.device) >= (dropout / 2)
        ).int()
        mat = (mat - res) * notdrop
        return torch.maximum(
            mat, torch.zeros((1, 1), device=mat.device, dtype=torch.int)
        )
    else:
        raise ValueError(f"method {method} not recognized")

make_adata

This function creates an AnnData object from the given input parameters.

Parameters:
  • embs (Tensor) –

    Embeddings of the cells. The shape of the tensor is (n_cells, n_features).

  • labels (list) –

    List of labels for the predicted classes.

  • pred (Tensor, default: None ) –

    Predicted labels. The shape of the tensor is (n_cells, n_classes). Default is None.

  • attention (Tensor, default: None ) –

    Attention weights. Default is None.

  • step (int, default: 0 ) –

    Step number for storing the AnnData without overwriting others. Default is 0.

  • label_decoders (dict, default: None ) –

    Dictionary to map class codes to class names. Default is None.

  • labels_hierarchy (dict, default: {} ) –

    Dictionary representing the hierarchy of labels. Default is {}.

  • gtclass (Tensor, default: None ) –

    Ground truth class. Default is None.

  • name (str, default: '' ) –

    Name of the AnnData object. Default is an empty string.

  • mdir (str, default: '/tmp' ) –

    Directory to save the AnnData object. Default is "/tmp".

  • doplot (bool, default: True ) –

    Whether to generate plots. Default is True.

Returns:
  • anndata.AnnData: The created AnnData object.

Source code in scprint/model/utils.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def make_adata(
    embs: Tensor,
    labels: List[str],
    pred: Tensor = None,
    attention: Optional[Tensor] = None,
    step: int = 0,
    label_decoders: Optional[Dict] = None,
    labels_hierarchy: Dict = {},
    gtclass: Optional[Tensor] = None,
    name: str = "",
    mdir: str = "/tmp",
    doplot: bool = True,
):
    """
    This function creates an AnnData object from the given input parameters.

    Args:
        embs (torch.Tensor): Embeddings of the cells. The shape of the tensor is (n_cells, n_features).
        labels (list): List of labels for the predicted classes.
        pred (torch.Tensor, optional): Predicted labels. The shape of the tensor is (n_cells, n_classes). Default is None.
        attention (torch.Tensor, optional): Attention weights. Default is None.
        step (int, optional): Step number for storing the AnnData without overwriting others. Default is 0.
        label_decoders (dict, optional): Dictionary to map class codes to class names. Default is None.
        labels_hierarchy (dict, optional): Dictionary representing the hierarchy of labels. Default is {}.
        gtclass (torch.Tensor, optional): Ground truth class. Default is None.
        name (str, optional): Name of the AnnData object. Default is an empty string.
        mdir (str, optional): Directory to save the AnnData object. Default is "/tmp".
        doplot (bool, optional): Whether to generate plots. Default is True.

    Returns:
        anndata.AnnData: The created AnnData object.
    """
    colname = ["pred_" + i for i in labels]
    if pred is not None:
        obs = np.array(pred.to(device="cpu", dtype=torch.int32))
        # label decoders is not cls_decoders. one is a dict to map class codes (ints)
        # to class names the other is the module the predict the class
        if label_decoders is not None:
            obs = np.array(
                [
                    [label_decoders[labels[i]][n] for n in name]
                    for i, name in enumerate(obs.T)
                ]
            ).T

        if gtclass is not None:
            colname += labels
            nobs = np.array(gtclass.to(device="cpu", dtype=torch.int32))
            if label_decoders is not None:
                nobs = np.array(
                    [
                        [label_decoders[labels[i]][n] for n in name]
                        for i, name in enumerate(nobs.T)
                    ]
                ).T
            obs = np.hstack([obs, nobs])

        adata = AnnData(
            np.array(embs.to(device="cpu", dtype=torch.float32)),
            obs=pd.DataFrame(
                obs,
                columns=colname,
            ),
        )
        accuracy = {}
        for label in labels:
            if gtclass is not None:
                tr = translate(adata.obs[label].tolist(), label)
                if tr is not None:
                    adata.obs["conv_" + label] = adata.obs[label].replace(tr)
            tr = translate(adata.obs["pred_" + label].tolist(), label)
            if tr is not None:
                adata.obs["conv_pred_" + label] = adata.obs["pred_" + label].replace(tr)
            res = []
            if label_decoders is not None and gtclass is not None:
                class_topred = label_decoders[label].values()
                if label in labels_hierarchy:
                    cur_labels_hierarchy = {
                        label_decoders[label][k]: [label_decoders[label][i] for i in v]
                        for k, v in labels_hierarchy[label].items()
                    }
                else:
                    cur_labels_hierarchy = {}
                for pred, true in adata.obs[["pred_" + label, label]].values:
                    if pred == true:
                        res.append(True)
                        continue
                    if len(labels_hierarchy) > 0:
                        if true in cur_labels_hierarchy:
                            res.append(pred in cur_labels_hierarchy[true])
                        elif true not in class_topred:
                            raise ValueError(
                                f"true label {true} not in available classes"
                            )
                        elif true != "unknown":
                            res.append(False)
                    elif true not in class_topred:
                        raise ValueError(f"true label {true} not in available classes")
                    elif true != "unknown":
                        res.append(False)
                    else:
                        pass
                accuracy["pred_" + label] = sum(res) / len(res) if len(res) > 0 else 0
        adata.obs = adata.obs.astype("category")
    else:
        adata = AnnData(
            np.array(embs.to(device="cpu", dtype=torch.float32)),
        )
    if False:
        adata.varm["Qs"] = (
            attention[:, :, 0, :, :]
            .permute(1, 3, 0, 2)
            .view(
                attention.shape[0],
                attention.shape[1],
                attention.shape[3] * attention.shape[4],
            )
            .detach()
            .cpu()
            .numpy()
        )
        adata.varm["Ks"] = (
            attention[:, :, 1, :, :]
            .permute(1, 3, 0, 2)
            .view(
                attention.shape[0],
                attention.shape[1],
                attention.shape[3] * attention.shape[4],
            )
            .detach()
            .cpu()
            .numpy()
        )
    print(adata)
    if doplot and adata.shape[0] > 100 and pred is not None:
        sc.pp.neighbors(adata, use_rep="X")
        sc.tl.umap(adata)
        sc.tl.leiden(adata, key_added="sprint_leiden")
        if gtclass is not None:
            color = [
                i
                for pair in zip(
                    [
                        "conv_" + i if "conv_" + i in adata.obs.columns else i
                        for i in labels
                    ],
                    [
                        (
                            "conv_pred_" + i
                            if "conv_pred_" + i in adata.obs.columns
                            else "pred_" + i
                        )
                        for i in labels
                    ],
                )
                for i in pair
            ]
            fig, axs = plt.subplots(
                int(len(color) / 2), 2, figsize=(24, len(color) * 4)
            )
            plt.subplots_adjust(wspace=1)
            if len(color) > 2:
                for i, col in enumerate(color):
                    sc.pl.umap(
                        adata,
                        color=col,
                        ax=axs[i // 2, i % 2],
                        show=False,
                    )
                    acc = ""
                    if "pred_" in col and col.split("conv_")[-1] in accuracy:
                        acc = " (accuracy: {:.2f})".format(
                            accuracy[col.split("conv_")[-1]]
                        )
                    axs[i // 2, i % 2].set_title(col + " UMAP" + acc)
                    if "cell_type" in col:
                        axs[i // 2, i % 2].legend(fontsize="x-small")
                    axs[i // 2, i % 2].set_xlabel("UMAP1")
                    axs[i // 2, i % 2].set_ylabel("UMAP2")
            else:
                for i, col in enumerate(color):
                    sc.pl.umap(
                        adata,
                        color=col,
                        ax=axs[i % 2],
                        show=False,
                    )
                    acc = ""
                    if "pred_" in col and col.split("conv_")[-1] in accuracy:
                        acc = " (accuracy: {:.2f})".format(
                            accuracy[col.split("conv_")[-1]]
                        )
                    axs[i % 2].set_title(col + " UMAP" + acc)
                    if "cell_type" in col:
                        axs[i % 2].legend(fontsize="x-small")
                    axs[i % 2].set_xlabel("UMAP1")
                    axs[i % 2].set_ylabel("UMAP2")
        else:
            color = [
                (
                    "conv_pred_" + i
                    if "conv_pred_" + i in adata.obs.columns
                    else "pred_" + i
                )
                for i in labels
            ]
            if len(color) > 1:
                fig, axs = plt.subplots(len(color), 1, figsize=(16, len(color) * 8))
                for i, col in enumerate(color):
                    sc.pl.umap(
                        adata,
                        color=col,
                        ax=axs[i],
                        show=False,
                    )
                    acc = ""
                    if "pred_" in col and col.split("conv_")[-1] in accuracy:
                        acc = " (accuracy: {:.2f})".format(
                            accuracy[col.split("conv_")[-1]]
                        )
                    axs[i].set_title(col + " UMAP" + acc)
                    axs[i].set_xlabel("UMAP1")
                    axs[i].set_ylabel("UMAP2")
            else:
                fig = sc.pl.umap(adata, color=color, show=False, return_fig=True)
        plt.show()
    else:
        fig = None
    adata.write(mdir + "/step_" + str(step) + "_" + name + ".h5ad")
    return adata, fig

simple_masker

Randomly mask a batch of data.

Parameters:
  • shape (list[int]) –

    The shape of the data.

  • mask_ratio (float, default: 0.15 ) –

    The ratio of genes to mask, default to 0.15.

Returns:
  • Tensor

    torch.Tensor: A tensor of masked data.

Source code in scprint/model/utils.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
def simple_masker(
    shape: list[int],
    mask_ratio: float = 0.15,
) -> torch.Tensor:
    """
    Randomly mask a batch of data.

    Args:
        shape (list[int]): The shape of the data.
        mask_ratio (float): The ratio of genes to mask, default to 0.15.

    Returns:
        torch.Tensor: A tensor of masked data.
    """
    return torch.rand(shape) < mask_ratio

test

Test the given model on the full set of benchmarks and save the results to JSON files.

Parameters:
  • model (Module) –

    The model to be tested.

  • name (str) –

    The name to be used for the output JSON files.

  • filedir (str) –

    The directory where the data files are located.

Returns:
  • None

    None

Source code in scprint/model/utils.py
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
def test(
    model: torch.nn.Module, name: str, filedir: str, do_class: bool = True
) -> None:
    """
    Test the given model on the full set of benchmarks and save the results to JSON files.

    Args:
        model (torch.nn.Module): The model to be tested.
        name (str): The name to be used for the output JSON files.
        filedir (str): The directory where the data files are located.

    Returns:
        None
    """
    metrics = {}
    res = embbed_task.default_benchmark(
        model, default_dataset="lung", do_class=do_class, coarse=False
    )
    f = open("metrics_" + name + ".json", "a")
    f.write(json.dumps({"embed_lung": res}, indent=4))
    f.close()
    metrics.update(
        {
            "emb_lung/scib": float(res["scib"]["Total"]),
            "emb_lung/ct_class": float(
                res["classif"]["cell_type_ontology_term_id"]["accuracy"]
                if do_class
                else 0
            ),
        }
    )
    print(metrics)
    res = embbed_task.default_benchmark(
        model, default_dataset="pancreas", do_class=do_class, coarse=False
    )
    f = open("metrics_" + name + ".json", "a")
    f.write(json.dumps({"embed_panc": res}, indent=4))
    f.close()
    metrics.update(
        {
            "emb_panc/scib": float(res["scib"]["Total"]),
            "emb_panc/ct_class": float(
                res["classif"]["cell_type_ontology_term_id"]["accuracy"]
                if do_class
                else 0
            ),
        }
    )
    print(metrics)
    gc.collect()
    res = denoise_task.default_benchmark(
        model, filedir + "/../../data/gNNpgpo6gATjuxTE7CCp.h5ad"
    )
    metrics.update(
        {
            "denoise/reco2full_vs_noisy2full": float(
                res["reco2full"] - res["noisy2full"]
            ),
        }
    )
    gc.collect()
    print(metrics)
    f = open("metrics_" + name + ".json", "a")
    f.write(json.dumps({"denoise": res}, indent=4))
    f.close()
    res = grn_task.default_benchmark(
        model, "gwps", batch_size=32 if model.d_model <= 512 else 8
    )
    f = open("metrics_" + name + ".json", "a")
    f.write(json.dumps({"grn_gwps": res}, default=lambda o: str(o), indent=4))
    f.close()
    metrics.update(
        {
            "grn_gwps/auprc_self": float(res["self"]["auprc"]),
            "grn_gwps/epr_self": float(res["self"]["epr"]),
            "grn_gwps/auprc_omni": float(res["omni"]["auprc"]),
            "grn_gwps/epr_omni": float(res["omni"]["epr"]),
            "grn_gwps/auprc": float(res["mean"]["auprc"]),
            "grn_gwps/epr": float(res["mean"]["epr"]),
        }
    )
    print(metrics)
    gc.collect()
    res = grn_task.default_benchmark(
        model, "sroy", batch_size=32 if model.d_model <= 512 else 8
    )
    f = open("metrics_" + name + ".json", "a")
    f.write(json.dumps({"grn_sroy": res}, default=lambda o: str(o), indent=4))
    f.close()
    metrics.update(
        {
            "grn_sroy/auprc_self": float(
                np.mean(
                    [
                        i["auprc"]
                        for k, i in res.items()
                        if k.startswith("self_")
                        and not any(
                            x in k for x in ["chip_", "ko_", "classifier", "_base"]
                        )
                    ]
                )
            ),
            "grn_sroy/epr_self": float(
                np.mean(
                    [
                        i["epr"]
                        for k, i in res.items()
                        if k.startswith("self_")
                        and not any(
                            x in k for x in ["chip_", "ko_", "classifier", "_base"]
                        )
                    ]
                )
            ),
            "grn_sroy/auprc_omni": float(
                np.mean(
                    [
                        i["auprc"]
                        for k, i in res.items()
                        if k.startswith("omni_")
                        and not any(
                            x in k for x in ["chip_", "ko_", "classifier", "_base"]
                        )
                    ]
                )
            ),
            "grn_sroy/epr_omni": float(
                np.mean(
                    [
                        i["epr"]
                        for k, i in res.items()
                        if k.startswith("omni_")
                        and not any(
                            x in k for x in ["chip_", "ko_", "classifier", "_base"]
                        )
                    ]
                )
            ),
            "grn_sroy/auprc": float(
                np.mean(
                    [
                        i["auprc"]
                        for k, i in res.items()
                        if k.startswith("mean_")
                        and not any(
                            x in k for x in ["chip_", "ko_", "classifier", "_base"]
                        )
                    ]
                )
            ),
            "grn_sroy/epr": float(
                np.mean(
                    [
                        i["epr"]
                        for k, i in res.items()
                        if k.startswith("mean_")
                        and not any(
                            x in k for x in ["chip_", "ko_", "classifier", "_base"]
                        )
                    ]
                )
            ),
        }
    )
    print(metrics)
    gc.collect()
    res = grn_task.default_benchmark(
        model,
        filedir + "/../../data/yBCKp6HmXuHa0cZptMo7.h5ad",
        batch_size=32 if model.d_model <= 512 else 8,
        cell_types=[
            "kidney distal convoluted tubule epithelial cell",
            "kidney loop of Henle thick ascending limb epithelial cell",
            "kidney collecting duct principal cell",
            "mesangial cell",
            "blood vessel smooth muscle cell",
            "podocyte",
            "macrophage",
            "leukocyte",
            "kidney interstitial fibroblast",
            "endothelial cell",
        ],
    )
    f = open("metrics_" + name + ".json", "a")
    f.write(json.dumps({"grn_omni": res}, default=lambda o: str(o), indent=4))
    f.close()
    metrics.update(
        {
            "grn_omni/auprc_class": float(
                np.mean([i["auprc"] for k, i in res.items() if "_class" in k])
            ),
            "grn_omni/epr_class": float(
                np.mean([i["epr"] for k, i in res.items() if "_class" in k])
            ),
            "grn_omni/tf_enr_class": float(
                np.sum(
                    [i.get("TF_enr", False) for k, i in res.items() if "_class" in k]
                )
            ),
            "grn_omni/tf_targ_enr_class": float(
                np.mean(
                    [
                        i["significant_enriched_TFtargets"]
                        for k, i in res.items()
                        if "_class" in k
                    ]
                )
            ),
            "grn_omni/auprc": float(
                np.mean([i["auprc"] for k, i in res.items() if "_mean" in k])
            ),
            "grn_omni/epr": float(
                np.mean([i["epr"] for k, i in res.items() if "_mean" in k])
            ),
            "grn_omni/tf_enr": float(
                np.sum([i.get("TF_enr", False) for k, i in res.items() if "_mean" in k])
            ),
            "grn_omni/tf_targ_enr": float(
                np.mean(
                    [
                        i["significant_enriched_TFtargets"]
                        for k, i in res.items()
                        if "_mean" in k
                    ]
                )
            ),
            # 'grn_omni/ct': res['classif']['cell_type_ontology_term_id']['accuracy'],
        }
    )
    return metrics

zinb_sample

zinb_sample This function generates a sample from a Zero-Inflated Negative Binomial (ZINB) distribution.

Parameters:
  • mu (Tensor) –

    The mean of the Negative Binomial (NB) distribution.

  • theta (Tensor) –

    The dispersion parameter of the NB distribution.

  • zi_probs (Tensor) –

    The zero-inflation probabilities.

  • sample_shape (Size, default: Size([]) ) –

    The output shape. Defaults to torch.Size([]).

Returns:
  • torch.Tensor: A sample from the ZINB distribution.

Source code in scprint/model/utils.py
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
def zinb_sample(
    mu: torch.Tensor,
    theta: torch.Tensor,
    zi_probs: torch.Tensor,
    sample_shape: torch.Size = torch.Size([]),
):
    """
    zinb_sample This function generates a sample from a Zero-Inflated Negative Binomial (ZINB) distribution.

    Args:
        mu (torch.Tensor): The mean of the Negative Binomial (NB) distribution.
        theta (torch.Tensor): The dispersion parameter of the NB distribution.
        zi_probs (torch.Tensor): The zero-inflation probabilities.
        sample_shape (torch.Size, optional): The output shape. Defaults to torch.Size([]).

    Returns:
        torch.Tensor: A sample from the ZINB distribution.
    """
    concentration = theta
    rate = theta / mu
    # Important remark: Gamma is parametrized by the rate = 1/scale!
    gamma_d = Gamma(concentration=concentration, rate=rate)
    p_means = gamma_d.sample(sample_shape)

    # Clamping as distributions objects can have buggy behaviors when
    # their parameters are too high
    l_train = torch.clamp(p_means, max=1e8)
    samp = Poisson(l_train).sample()  # Shape : (n_samples, n_cells_batch, n_vars)
    is_zero = torch.rand_like(samp) <= zi_probs
    samp_ = torch.where(is_zero, torch.zeros_like(samp), samp)
    return samp_

encoder and decoder modules

scprint.model.encoders

Classes:

Name Description
CategoryValueEncoder
ContinuousValueEncoder
DPositionalEncoding

The PositionalEncoding module applies a positional encoding to a sequence of vectors.

GeneEncoder
PositionalEncoding

CategoryValueEncoder

Bases: Module

Encodes categorical values into a vector using an embedding layer and layer normalization.

Parameters:
  • num_embeddings (int) –

    The number of possible values.

  • embedding_dim (int) –

    The dimension of the output vectors.

  • padding_idx (int, default: None ) –

    The index of the padding token. Defaults to None.

Returns:
  • torch.Tensor: A tensor representing the encoded categorical values.

Note: not used in the current version of scprint.

Source code in scprint/model/encoders.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def __init__(
    self,
    num_embeddings: int,
    embedding_dim: int,
    padding_idx: Optional[int] = None,
):
    """
    Encodes categorical values into a vector using an embedding layer and layer normalization.

    Args:
        num_embeddings (int): The number of possible values.
        embedding_dim (int): The dimension of the output vectors.
        padding_idx (int, optional): The index of the padding token. Defaults to None.

    Returns:
        torch.Tensor: A tensor representing the encoded categorical values.

    Note: not used in the current version of scprint.
    """
    super(CategoryValueEncoder, self).__init__()
    self.embedding = nn.Embedding(
        num_embeddings, embedding_dim, padding_idx=padding_idx
    )

ContinuousValueEncoder

Bases: Module

Encode real number values to a vector using neural nets projection.

Parameters:
  • d_model (int) –

    The dimension of the input vectors.

  • dropout (float, default: 0.1 ) –

    The dropout rate to apply to the output of the positional encoding.

  • max_value (int, default: 100000 ) –

    The maximum value of the input. Defaults to 100_000.

  • layers (int, default: 1 ) –

    The number of layers in the encoder. Defaults to 1.

  • size (int, default: 1 ) –

    The size of the input. Defaults to 1.

Returns:
  • torch.Tensor: A tensor representing the encoded continuous values.

Methods:

Name Description
forward

Args:

Source code in scprint/model/encoders.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def __init__(
    self,
    d_model: int,
    dropout: float = 0.1,
    max_value: int = 100_000,
    layers: int = 1,
    size: int = 1,
):
    """
    Encode real number values to a vector using neural nets projection.

    Args:
        d_model (int): The dimension of the input vectors.
        dropout (float, optional): The dropout rate to apply to the output of the positional encoding.
        max_value (int, optional): The maximum value of the input. Defaults to 100_000.
        layers (int, optional): The number of layers in the encoder. Defaults to 1.
        size (int, optional): The size of the input. Defaults to 1.

    Returns:
        torch.Tensor: A tensor representing the encoded continuous values.
    """
    super(ContinuousValueEncoder, self).__init__()
    self.max_value = max_value
    self.encoder = nn.ModuleList()
    # self.mask_value = nn.Embedding(1, d_model)
    self.encoder.append(nn.Linear(size, d_model))
    for _ in range(layers - 1):
        self.encoder.append(nn.LayerNorm(d_model))
        self.encoder.append(nn.ReLU())
        self.encoder.append(nn.Dropout(p=dropout))
        self.encoder.append(nn.Linear(d_model, d_model))

forward

Parameters:
  • x (Tensor) –

    Tensor, shape [batch_size, seq_len]

Source code in scprint/model/encoders.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def forward(self, x: Tensor, mask: Tensor = None) -> Tensor:
    """
    Args:
        x: Tensor, shape [batch_size, seq_len]
    """
    # expand last dimension
    x = x.unsqueeze(-1)
    # use the mask embedding when x=-1
    # mask = (x == -1).float()
    x = torch.clamp(x, min=0, max=self.max_value)
    for val in self.encoder:
        x = val(x)
    if mask is not None:
        x = x.masked_fill_(mask.unsqueeze(-1), 0)
        # x = x.masked_fill_(mask.unsqueeze(-1), self.mask_value(0))
    return x

DPositionalEncoding

Bases: Module

The PositionalEncoding module applies a positional encoding to a sequence of vectors. This is necessary for the Transformer model, which does not have any inherent notion of position in a sequence. The positional encoding is added to the input embeddings and allows the model to attend to positions in the sequence.

Parameters:
  • d_model (int) –

    The dimension of the input vectors.

  • dropout (float) –

    The dropout rate to apply to the output of the positional encoding.

  • max_len (int) –

    The maximum length of a sequence that this module can handle.

Note: not used in the current version of scprint.

Methods:

Name Description
forward

Args:

Source code in scprint/model/encoders.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def __init__(
    self,
    d_model: int,
    max_len_x: int,
    max_len_y: int,
    maxvalue_x=10000.0,
    maxvalue_y=10000.0,
):
    super(DPositionalEncoding, self).__init__()
    position2 = torch.arange(max_len_y).unsqueeze(1)
    position1 = torch.arange(max_len_x).unsqueeze(1)

    half_n = d_model // 2

    div_term2 = torch.exp(
        torch.arange(0, half_n, 2) * (-math.log(maxvalue_y) / d_model)
    )
    div_term1 = torch.exp(
        torch.arange(0, half_n, 2) * (-math.log(maxvalue_x) / d_model)
    )
    pe1 = torch.zeros(max_len_x, 1, d_model)
    pe2 = torch.zeros(max_len_y, 1, d_model)
    pe1[:, 0, 0:half_n:2] = torch.sin(position1 * div_term1)
    pe1[:, 0, 1:half_n:2] = torch.cos(position1 * div_term1)
    pe2[:, 0, half_n::2] = torch.sin(position2 * div_term2)
    pe2[:, 0, 1 + half_n :: 2] = torch.cos(position2 * div_term2)
    # https://github.com/tatp22/multidim-positional-encoding/blob/master/positional_encodings/torch_encodings.py
    self.register_buffer("pe1", pe1)
    self.register_buffer("pe2", pe2)

forward

Parameters:
  • x (Tensor) –

    Tensor, shape [seq_len, batch_size, embedding_dim]

Source code in scprint/model/encoders.py
151
152
153
154
155
156
157
158
def forward(self, x: Tensor, pos_x: Tensor, pos_y: Tensor) -> Tensor:
    """
    Args:
        x: Tensor, shape [seq_len, batch_size, embedding_dim]
    """
    x = x + self.pe1[pos_x]
    x = x + self.pe2[pos_y]
    return x

GeneEncoder

Bases: Module

Encodes gene sequences into a continuous vector space using an embedding layer.

The output is then normalized using a LayerNorm.

Parameters:
  • num_embeddings (int) –

    The number of possible values.

  • embedding_dim (int) –

    The dimension of the output vectors.

  • padding_idx (int, default: None ) –

    The index of the padding token. Defaults to None.

  • weights (Tensor, default: None ) –

    The initial weights for the embedding layer. Defaults to None.

  • dropout (float) –

    The dropout rate to apply to the output of the positional encoding. Defaults to 0.1.

  • freeze (bool, default: False ) –

    Whether to freeze the weights of the embedding layer. Defaults to False.

Note: not used in the current version of scprint.

Source code in scprint/model/encoders.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def __init__(
    self,
    num_embeddings: int,
    embedding_dim: int,
    padding_idx: Optional[int] = None,
    weights: Optional[Tensor] = None,
    freeze: bool = False,
):
    """
    Encodes gene sequences into a continuous vector space using an embedding layer.

    The output is then normalized using a LayerNorm.

    Args:
        num_embeddings (int): The number of possible values.
        embedding_dim (int): The dimension of the output vectors.
        padding_idx (int, optional): The index of the padding token. Defaults to None.
        weights (Tensor, optional): The initial weights for the embedding layer. Defaults to None.
        dropout (float, optional): The dropout rate to apply to the output of the positional encoding. Defaults to 0.1.
        freeze (bool, optional): Whether to freeze the weights of the embedding layer. Defaults to False.

    Note: not used in the current version of scprint.
    """
    super(GeneEncoder, self).__init__()
    self.embedding = nn.Embedding(
        num_embeddings, embedding_dim, padding_idx=padding_idx, _freeze=freeze
    )

    if weights is not None:
        # concat a zero vector to the weight
        # this is to make the embedding of the padding token to be zero
        # weights = torch.cat(
        #    [torch.Tensor(weights), torch.zeros(1, embedding_dim)], dim=0
        # )
        self.embedding.weight.data.copy_(torch.Tensor(weights))

PositionalEncoding

Bases: Module

The PositionalEncoding module applies a positional encoding to a sequence of vectors. This is necessary for the Transformer model, which does not have any inherent notion of position in a sequence. The positional encoding is added to the input embeddings and allows the model to attend to positions in the sequence.

Parameters:
  • d_model (int) –

    The dimension of the input vectors.

  • dropout (float) –

    The dropout rate to apply to the output of the positional encoding.

  • max_len (int) –

    The maximum length of a sequence that this module can handle.

Note: not used in the current version of scprint.

Methods:

Name Description
forward

Args:

Source code in scprint/model/encoders.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def __init__(
    self,
    d_model: int,
    max_len: int,
    token_to_pos: dict[str, int],  # [token, pos]
    maxval=10000.0,
):
    """
    The PositionalEncoding module applies a positional encoding to a sequence of vectors.
    This is necessary for the Transformer model, which does not have any inherent notion of
    position in a sequence. The positional encoding is added to the input embeddings and
    allows the model to attend to positions in the sequence.

    Args:
        d_model (int): The dimension of the input vectors.
        dropout (float, optional): The dropout rate to apply to the output of the positional encoding.
        max_len (int, optional): The maximum length of a sequence that this module can handle.

    Note: not used in the current version of scprint.
    """
    super(PositionalEncoding, self).__init__()
    position = torch.arange(max_len).unsqueeze(1)

    # Create a dictionary to convert token to position

    div_term = torch.exp(
        torch.arange(0, d_model, 2) * (-math.log(maxval) / d_model)
    )
    pe = torch.zeros(max_len, 1, d_model)
    pe[:, 0, 0::2] = torch.sin(position * div_term)
    pe[:, 0, 1::2] = torch.cos(position * div_term)
    # we reorder them and map them to gene_id (position)
    arr = []
    for _, v in token_to_pos.items():
        arr.append(pe[v - 1].numpy())
    pe = torch.Tensor(np.array(arr))
    # Remove the unnecessary middle dimension since pe should be [m, d]
    # pe = pe.squeeze(1)
    self.register_buffer("pe", pe)

forward

Parameters:
  • x

    Tensor, shape [seq_len, batch_size, embedding_dim]

Source code in scprint/model/encoders.py
91
92
93
94
95
96
97
98
def forward(self, gene_pos: Tensor) -> Tensor:
    """
    Args:
        x: Tensor, shape [seq_len, batch_size, embedding_dim]
    """
    return torch.index_select(self.pe, 0, gene_pos.reshape(-1)).reshape(
        gene_pos.shape + (-1,)
    )

scprint.model.decoders

Classes:

Name Description
ClsDecoder
ExprDecoder
GraphSDEExprDecoder
MVCDecoder

ClsDecoder

Bases: Module

ClsDecoder Decoder for classification task.

Parameters:
  • d_model (int) –

    int, dimension of the input.

  • n_cls (int) –

    int, number of classes.

  • layers (list[int], default: [256, 128] ) –

    list[int], list of hidden layers.

  • activation (Callable, default: ReLU ) –

    nn.Module, activation function.

  • dropout (float, default: 0.1 ) –

    float, dropout rate.

Returns:
  • Tensor, shape [batch_size, n_cls]

Methods:

Name Description
forward

Args:

Source code in scprint/model/decoders.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def __init__(
    self,
    d_model: int,
    n_cls: int,
    layers: list[int] = [256, 128],
    activation: Callable = nn.ReLU,
    dropout: float = 0.1,
):
    """
    ClsDecoder Decoder for classification task.

    Args:
        d_model: int, dimension of the input.
        n_cls: int, number of classes.
        layers: list[int], list of hidden layers.
        activation: nn.Module, activation function.
        dropout: float, dropout rate.

    Returns:
        Tensor, shape [batch_size, n_cls]
    """
    super(ClsDecoder, self).__init__()
    # module list
    layers = [d_model] + layers
    self.decoder = nn.Sequential()
    for i, l in enumerate(layers[1:]):
        self.decoder.append(nn.Linear(layers[i], l))
        self.decoder.append(nn.LayerNorm(l))
        self.decoder.append(activation())
        self.decoder.append(nn.Dropout(dropout))
    self.out_layer = nn.Linear(layers[-1], n_cls)

forward

Parameters:
  • x (Tensor) –

    Tensor, shape [batch_size, embsize]

Source code in scprint/model/decoders.py
235
236
237
238
239
240
241
def forward(self, x: Tensor) -> Tensor:
    """
    Args:
        x: Tensor, shape [batch_size, embsize]
    """
    x = self.decoder(x)
    return self.out_layer(x)

ExprDecoder

Bases: Module

ExprDecoder Decoder for the gene expression prediction.

Will output the mean, variance and zero logits, parameters of a zero inflated negative binomial distribution.

Parameters:
  • d_model (int) –

    The dimension of the model. This is the size of the input feature vector.

  • nfirst_tokens_to_skip (int, default: 0 ) –

    The number of initial labels to skip in the sequence. Defaults to 0.

  • dropout (float, default: 0.1 ) –

    The dropout rate applied during training to prevent overfitting. Defaults to 0.1.

  • zinb (bool, default: True ) –

    Whether to use a zero inflated negative binomial distribution. Defaults to True.

Methods:

Name Description
forward

x is the output of the transformer, (batch, seq_len, d_model)

Source code in scprint/model/decoders.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def __init__(
    self,
    d_model: int,
    nfirst_tokens_to_skip: int = 0,
    dropout: float = 0.1,
    zinb: bool = True,
    use_depth: bool = False,
):
    """
    ExprDecoder Decoder for the gene expression prediction.

    Will output the mean, variance and zero logits, parameters of a zero inflated negative binomial distribution.

    Args:
        d_model (int): The dimension of the model. This is the size of the input feature vector.
        nfirst_tokens_to_skip (int, optional): The number of initial labels to skip in the sequence. Defaults to 0.
        dropout (float, optional): The dropout rate applied during training to prevent overfitting. Defaults to 0.1.
        zinb (bool, optional): Whether to use a zero inflated negative binomial distribution. Defaults to True.
    """
    super(ExprDecoder, self).__init__()
    self.nfirst_tokens_to_skip = nfirst_tokens_to_skip
    self.fc = nn.Sequential(
        nn.Linear(d_model if not use_depth else d_model + 1, d_model),
        nn.LayerNorm(d_model),
        nn.LeakyReLU(),
        nn.Dropout(dropout),
        nn.Linear(d_model, d_model),
        nn.LayerNorm(d_model),
        nn.LeakyReLU(),
    )
    self.pred_var_zero = nn.Linear(d_model, 3 if zinb else 1)
    self.zinb = zinb

forward

x is the output of the transformer, (batch, seq_len, d_model)

Source code in scprint/model/decoders.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def forward(
    self, x: Tensor, req_depth: Optional[Tensor] = None
) -> Dict[str, Tensor]:
    """x is the output of the transformer, (batch, seq_len, d_model)"""
    # we don't do it on the labels
    x = x[:, self.nfirst_tokens_to_skip :, :]
    if req_depth is not None:
        x = torch.cat(
            [x, req_depth.unsqueeze(1).unsqueeze(-1).expand(-1, x.shape[1], -1)],
            dim=-1,
        )
    x = self.fc(x)
    if self.zinb:
        pred_value, var_value, zero_logits = self.pred_var_zero(x).split(
            1, dim=-1
        )  # (batch, seq_len)
        # The sigmoid function is used to map the zero_logits to a probability between 0 and 1.
        return dict(
            mean=F.softmax(pred_value.squeeze(-1), dim=-1),
            disp=torch.exp(torch.clamp(var_value.squeeze(-1), max=15)),
            zero_logits=zero_logits.squeeze(-1),
        )
    else:
        pred_value = self.pred_var_zero(x)
        return dict(mean=F.softmax(pred_value.squeeze(-1), dim=-1))

GraphSDEExprDecoder

Bases: Module

Initialize the ExprNeuralSDEDecoder module.

Parameters:
  • d_model (int) –

    The dimension of the model.

  • drift (Module) –

    The drift component of the SDE.

  • diffusion (Module) –

    The diffusion component of the SDE.

Source code in scprint/model/decoders.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
def __init__(self, d_model: int, drift: nn.Module, diffusion: nn.Module):
    """
    Initialize the ExprNeuralSDEDecoder module.

    Args:
        d_model (int): The dimension of the model.
        drift (nn.Module): The drift component of the SDE.
        diffusion (nn.Module): The diffusion component of the SDE.
    """
    super().__init__()
    self.d_model = d_model
    self.drift = drift
    self.diffusion = diffusion

MVCDecoder

Bases: Module

MVCDecoder Decoder for the masked value prediction for cell embeddings.

Will use the gene embeddings with the cell embeddings to predict the mean, variance and zero logits

Parameters:
  • d_model

    obj:int): dimension of the gene embedding.

  • arch_style

    obj:str): architecture style of the decoder, choice from 1. "inner product" or 2. "cell product" 3. "concat query" or 4. "sum query".

  • query_activation

    obj:nn.Module): activation function for the query vectors. Defaults to nn.Sigmoid.

  • hidden_activation

    obj:nn.Module): activation function for the hidden layers. Defaults to nn.PReLU.

Methods:

Name Description
forward

Args:

Source code in scprint/model/decoders.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def __init__(
    self,
    d_model: int,
    arch_style: str = "inner product",
    tot_labels: int = 1,
    query_activation: nn.Module = nn.Sigmoid,
    hidden_activation: nn.Module = nn.PReLU,
    zinb: bool = True,
) -> None:
    """
    MVCDecoder Decoder for the masked value prediction for cell embeddings.

    Will use the gene embeddings with the cell embeddings to predict the mean, variance and zero logits

    Args:
        d_model (:obj:`int`): dimension of the gene embedding.
        arch_style (:obj:`str`): architecture style of the decoder, choice from
            1. "inner product" or 2. "cell product" 3. "concat query" or 4. "sum query".
        query_activation (:obj:`nn.Module`): activation function for the query
            vectors. Defaults to nn.Sigmoid.
        hidden_activation (:obj:`nn.Module`): activation function for the hidden
            layers. Defaults to nn.PReLU.
    """
    super(MVCDecoder, self).__init__()
    if arch_style == "inner product":
        self.gene2query = nn.Linear(d_model, d_model)
        self.norm = nn.LayerNorm(d_model)
        self.query_activation = query_activation()
        self.pred_var_zero = nn.Linear(
            d_model, d_model * (3 if zinb else 1), bias=False
        )
    elif arch_style == "concat query":
        self.gene2query = nn.Linear(d_model, d_model)
        self.query_activation = query_activation()
        self.fc1 = nn.Linear(d_model * (1 + tot_labels), d_model // 2)
        self.hidden_activation = hidden_activation()
        self.fc2 = nn.Linear(d_model // 2, (3 if zinb else 1))
    elif arch_style == "sum query":
        self.gene2query = nn.Linear(d_model, d_model)
        self.query_activation = query_activation()
        self.fc1 = nn.Linear(d_model, 64)
        self.hidden_activation = hidden_activation()
        self.fc2 = nn.Linear(64, (3 if zinb else 1))
    else:
        raise ValueError(f"Unknown arch_style: {arch_style}")

    self.arch_style = arch_style
    self.do_detach = arch_style.endswith("detach")
    self.d_model = d_model
    self.zinb = zinb

forward

Parameters:
  • cell_emb (Tensor) –

    Tensor, shape (batch, embsize=d_model)

  • gene_embs (Tensor) –

    Tensor, shape (batch, seq_len, embsize=d_model)

Source code in scprint/model/decoders.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def forward(
    self,
    cell_emb: Tensor,
    gene_embs: Tensor,
) -> Union[Tensor, Dict[str, Tensor]]:
    """
    Args:
        cell_emb: Tensor, shape (batch, embsize=d_model)
        gene_embs: Tensor, shape (batch, seq_len, embsize=d_model)
    """
    if self.arch_style == "inner product":
        query_vecs = self.query_activation(self.norm(self.gene2query(gene_embs)))
        if self.zinb:
            pred, var, zero_logits = self.pred_var_zero(query_vecs).split(
                self.d_model, dim=-1
            )
        else:
            pred = self.pred_var_zero(query_vecs)
        cell_emb = cell_emb.unsqueeze(2)
        if self.zinb:
            pred, var, zero_logits = (
                torch.bmm(pred, cell_emb).squeeze(2),
                torch.bmm(var, cell_emb).squeeze(2),
                torch.bmm(zero_logits, cell_emb).squeeze(2),
            )
        else:
            pred = torch.bmm(pred, cell_emb).squeeze(2)
        # zero logits need to based on the cell_emb, because of input exprs
    elif self.arch_style == "concat query":
        query_vecs = self.query_activation(self.gene2query(gene_embs))
        # expand cell_emb to (batch, seq_len, embsize)
        cell_emb = cell_emb.unsqueeze(1).expand(-1, gene_embs.shape[1], -1)

        h = self.hidden_activation(
            self.fc1(torch.cat([cell_emb, query_vecs], dim=2))
        )
        if self.zinb:
            pred, var, zero_logits = self.fc2(h).split(1, dim=-1)
        else:
            pred = self.fc2(h)
    elif self.arch_style == "sum query":
        query_vecs = self.query_activation(self.gene2query(gene_embs))
        cell_emb = cell_emb.unsqueeze(1)

        h = self.hidden_activation(self.fc1(cell_emb + query_vecs))
        if self.zinb:
            pred, var, zero_logits = self.fc2(h).split(1, dim=-1)
        else:
            pred = self.fc2(h)
    if self.zinb:
        return dict(
            mvc_mean=F.softmax(pred, dim=-1),
            mvc_disp=torch.exp(torch.clamp(var, max=15)),
            mvc_zero_logits=zero_logits,
        )
    else:
        return dict(mvc_mean=F.softmax(pred, dim=-1))