mmcontext.models.mmcontextencoder.MMContextEncoder

Contents

mmcontext.models.mmcontextencoder.MMContextEncoder#

class mmcontext.models.mmcontextencoder.MMContextEncoder(text_encoder_name, omics_embedding=None, *, adapter_hidden_dim=None, adapter_output_dim=None, freeze_text_encoder=False, unfreeze_last_n_layers=0, processor=None, registered_data_origin='unregistered', registered_input_dim=None, output_token_embeddings=False, train_lookup=False, pooling_mode='mean')#

Bases: Module

Dual-tower encoder that acts as its own tokenizer.

Can be initialized in three modes: 1. Text-only mode: Only processes text inputs 2. Bimodal mode with preloaded omics embeddings 3. Bimodal mode that will be completed later via register_initial_embeddings

The adapter layers can be optionally included for dimensionality reduction. Adapters are applied at the token level, and pooling is performed using SentenceTransformers Pooling module for better compatibility.

Parameters:
  • text_encoder_name (str | nn.Module) – Name of HuggingFace model or a pre-initialized model

  • omics_embedding (Optional[np.ndarray], optional) – Precomputed embeddings for omics data. If None, the model starts as text-only and can be extended via register_initial_embeddings.

  • adapter_hidden_dim (int or None, optional) – Hidden dimension of the adapter layers. If None, no adapter is used.

  • adapter_output_dim (int or None, optional) – Output dimension of the adapter layers. If None, no adapter is used. If adapter_hidden_dim is provided but this is None, output_dim will match the text encoder’s hidden dimension.

  • freeze_text_encoder (bool, optional) – Whether to freeze the text encoder weights. Defaults to False.

  • unfreeze_last_n_layers (int, optional) – Number of layers to unfreeze from the end of the text encoder. Only applies if freeze_text_encoder is True.

  • processor (MMContextProcessor | None, optional) – Pre-initialized processor. If None, one will be created.

  • registered_data_origin (str | None, optional) – Type of omics data representation. Must be one of: [“unregistered”, “pca”, “hvg”, “scvi_fm”, “geneformer”]. Defaults to “unregistered”.

  • registered_input_dim (int | None, optional) – Input dimension of registered data. Required when loading a model that was previously registered with data to initialize adapters correctly.

  • output_token_embeddings (bool, optional) – Whether to include token embeddings in the output. Defaults to False. When using SentenceTransformers. Training such a model is slower, but allows to continue working with the token embeddings.

  • train_lookup (bool, optional) – Whether to train the lookup table. Defaults to False, as we have precomputed representations in the lookup, that we don’t want to modify at this point.

  • pooling_mode (str, optional) – Pooling strategy to use. Defaults to “mean”. Options: “mean”, “cls”, “max”, etc. See SentenceTransformers Pooling documentation for all options.

forward(features)#

Embed a batch and maintain original ordering.

New architecture: 1. Get token embeddings from encoders 2. Apply adapters at token level (if enabled) 3. Use SentenceTransformers Pooling for sentence embeddings 4. Optionally return token embeddings

Parameters:

features (dict) – Output of tokenize method, containing text features and optionally omics features.

Return type:

Tensor | dict[str, Tensor]

Returns:

torch.Tensor or dict If return_tensor=True in features, returns a tensor of sentence embeddings directly. Otherwise, dict with ‘sentence_embedding’ and optionally ‘token_embeddings’.

Raises:

RuntimeError – If omics features are provided but the model hasn’t been initialized with omics capabilities.

static get_initial_embeddings(hf_dataset, *, layer_key=None, axis='obs', download_dir='../../data/downloaded_chunks', extract_zip=True, overwrite=False, link_column='share_link')#

Download all embedding chunks referenced in hf_dataset and return in a format suitable for registration.

This assumes the dataset has a column (specified by link_column) in each split, which contains either share links to Nextcloud files or local file paths. For URLs, the function will download and optionally extract the files. For local paths, they are used directly without downloading.

Parameters:
  • hf_dataset (DatasetDict | Dataset) – A Hugging Face :pyclass:`~datasets.DatasetDict` that contains one or more splits and a link/path column in each split.

  • layer_key (Optional[str] (default: None)) – Name of the embedding to pull – * .obsm[layer_key] if axis=”obs” * .varm[layer_key] if axis=”var”

  • axis (Literal['obs', 'var'] (default: "obs")) – "obs" → use adata.obs.index "var" → use adata.var.index.

  • download_dir (str | Path (default: "../../data/downloaded_chunks")) – Local root folder where downloaded chunk files (ZIPs or extracted stores) will be materialized. Ignored for local paths.

  • extract_zip (bool (default: True)) – If True unpack Nextcloud ZIP downloads into chunk_<n>.zarr/. If False keep the ZIP and let Zarr’s zip-store backend read it directly (requires Zarr ≥ 2.16). Only applies to downloaded files.

  • overwrite (bool (default: False)) – Re-download / re-extract even if the target already exists. Only applies to downloaded files.

  • link_column (str (default: "share_link")) – Column name that stores the share links or local paths.

Return type:

tuple[DataFrame, dict[str, Path]]

Returns:

tuple[pandas.DataFrame, dict[str, Path]] A tuple containing: - DataFrame with two columns:

  • token - obs or var label (string)

  • embedding - 1-D numpy.ndarray of floats

  • Path mapping from original links to actual file locations

get_sentence_embedding_dimension()#

Returns the dimension of the final sentence embedding.

Return type:

int

Returns:

int The dimension of the final sentence embedding.

classmethod load(model_name_or_path, subfolder='', token=None, cache_folder=None, revision=None, local_files_only=False, safe_serialization=True, **kwargs)#

Loads the model from disk.

Parameters:
  • model_name_or_path (str) – Path to the model directory or the name of the model on Hugging Face.

  • subfolder (str, optional) – The subfolder within the model directory to load from. Defaults to ‘’.

  • token (bool | str | None, optional) – Token for authentication. Defaults to None.

  • cache_folder (str | None, optional) – Cache folder for the model files. Defaults to None.

  • revision (str | None, optional) – Revision of the model to load. Defaults to None.

  • local_files_only (bool, optional) – Whether to only load local files. Defaults to False.

  • safe_serialization (bool, optional) – If True, expects safetensors format; else a PyTorch bin.

Returns:

MMContextEncoder The loaded model instance, ready for data registration.

prepare_ds(ds, primary_cell_sentence_col, *, prefix=True, caption_col='caption', positive_col='positive', label_col='label', negative_prefix='negative', index_col='sample_idx', keep_index_col=False)#

Return a copy ready for SentenceTransformerTrainer.

Parameters:
  • ds (HFDataset | DatasetDict) – Input dataset to prepare

  • primary_cell_sentence_col (str) – Column containing cell/sample representations. References one of the cell_sentence columns in the dataset, that you want to process. These will be tokenized by the omics part of the model, if prefix=True, or by the text part of the model, if prefix=False. These will be the primary output columns. For multiplets, negative samples will be chosen from this column, if they are sample indices. Other negatives are captions and are not modified. If prefix=True, these will be prefixed with the processor’s prefix.

  • prefix (bool, optional) – Whether to add the processor’s prefix to primary_cell_sentence_col. If False, only subsetting is performed.

  • caption_col (str, optional) – Name of the caption column for pairs

  • positive_col (str, optional) – Name of the positive column for multiplets

  • label_col (str, optional) – Name of the label column for pairs

  • negative_prefix (str, optional) – Prefix for negative columns in multiplets

  • index_col (str, optional) – Name of the index column for HFDataset. Only if index_col is provided, it will be left in the output.

  • keep_index_col (bool, optional) – Whether to keep the index column in the output. Defaults to False. Is needed for the embedding workflow.

Return type:

Dataset | DatasetDict

Returns:

HFDataset | DatasetDict Processed dataset with appropriate columns and optional prefixes

random_initial_embeddings(tokens, *, dim=64, rng_seed=None, id_col='token', data_origin='random')#

Register tokens with Gaussian-random vectors instead of real embeddings.

Parameters:
  • tokens (Sequence[str] | DataFrame | Dataset | DatasetDict | Mapping[str, Any]) –

    • List/tuple of token strings or

    • A pandas / HF dataset / mapping containing a column or key named

    id_col. Any duplicates are collapsed.

  • dim (int (default: 64)) – Embedding dimensionality for every generated vector.

  • rng_seed (Optional[int] (default: None)) – Reproducible seed. If None → numpy default RNG.

  • id_col (str (default: "token")) – Column/key that holds the token strings when tokens is a table.

  • data_origin (str (default: "random")) – Passed straight through to register_initial_embeddings.

Return type:

dict[str, int]

register_initial_embeddings(data, data_origin, *, id_col='token', emb_col='embedding', return_added=False)#

Add gene / sample tokens and their initial embeddings to the encoder.

Parameters:
  • data (DataFrame | Dataset | Mapping[str, Sequence[float]]) –

    • pandas.DataFrame / HF Datasetid_col has the token strings,

    emb_col holds a vector (np.ndarray, list, or tuple). • Mapping{token_str: embedding_vector}.#

  • data_origin (str) – Tag describing how the numeric representation was generated ("pca", "hvg", "scvi_fm", "geneformer" …).

  • id_col (str (default: "token")) – Column names for DataFrame / HF-Dataset input.

  • emb_col (str | None (default: "embedding")) – Column names for DataFrame / HF-Dataset input.

  • return_added (bool (default: False)) – If True, return a dictionary of the newly added tokens and their corresponding indices in the omics embedding matrix.

Return type:

dict[str, int]

Returns:

dict Only the new tokens inserted this call, e.g. {"EGFR": 12345, "KRAS": 12346}.

save(output_path, safe_serialization=True, **kwargs)#

Saves the model configuration and state dict, excluding the omics embedding matrix.

Parameters:
  • output_path (str) – Directory to save model files.

  • safe_serialization (bool, optional) – If True, use safetensors; else use torch.save.

Return type:

None

tokenize(texts, *, padding=True, **tok_kwargs)#

Tokenize texts and/or omics identifiers.

Parameters:
  • texts (sequence of str) – Texts and/or omics identifiers.

  • padding (str or bool, optional) – Forwarded to the underlying HF tokenizer (default: True).

  • **tok_kwargs – Additional keyword args forwarded to the tokenizer.

Return type:

dict[str, Tensor]

Returns:

dict Tokenized features compatible with the forward method.

VALID_DATA_ORIGINS = ['unregistered', 'pca', 'hvg', 'scvi_fm', 'geneformer', 'random']#
config_keys = ['text_encoder_name', 'adapter_hidden_dim', 'adapter_output_dim', 'freeze_text_encoder', 'unfreeze_last_n_layers', 'registered_data_origin', 'registered_input_dim', 'output_token_embeddings', 'train_lookup', 'pooling_mode']#

A list of keys used to save the module’s configuration. These keys are used to save the module’s configuration when saving the model to disk.

property registered_data_origin#

Get the type of omics data representation registered with this model.

property registered_input_dim#

Get the input dimension of registered data.

property tokenizer#

Convenience property returning the underlying processor object, which includes the text tokenizer and omics data processor.

Attributes table#

T_destination

VALID_DATA_ORIGINS

call_super_init

config_file_name

The name of the configuration file used to save the module's configuration.

config_keys

A list of keys used to save the module's configuration.

dump_patches

forward_kwargs

A set of keyword arguments that can be passed to the forward method of the module.

registered_data_origin

Get the type of omics data representation registered with this model.

registered_input_dim

Get the input dimension of registered data.

save_in_root

Whether to save the module's configuration in the root directory of the model or in a subdirectory named after the module.

tokenizer

Convenience property returning the underlying processor object, which includes the text tokenizer and omics data processor.

training

Methods table#

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

forward(features)

Embed a batch and maintain original ordering.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_config_dict()

Returns a dictionary of the configuration parameters of the module.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_initial_embeddings(hf_dataset, *[, ...])

Download all embedding chunks referenced in hf_dataset and return in a format suitable for registration.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_sentence_embedding_dimension()

Returns the dimension of the final sentence embedding.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load(model_name_or_path[, subfolder, token, ...])

Loads the model from disk.

load_config(model_name_or_path[, subfolder, ...])

Load the configuration of the module from a model checkpoint.

load_dir_path(model_name_or_path[, ...])

A utility function to load a directory from a model checkpoint.

load_file_path(model_name_or_path, filename)

A utility function to load a file from a model checkpoint.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

load_torch_weights(model_name_or_path[, ...])

A utility function to load the PyTorch weights of a model from a checkpoint.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

prepare_ds(ds, primary_cell_sentence_col, *)

Return a copy ready for SentenceTransformerTrainer.

random_initial_embeddings(tokens, *[, dim, ...])

Register tokens with Gaussian-random vectors instead of real embeddings.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_initial_embeddings(data, data_origin, *)

Add gene / sample tokens and their initial embeddings to the encoder.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

save(output_path[, safe_serialization])

Saves the model configuration and state dict, excluding the omics embedding matrix.

save_config(output_path[, filename])

Save the configuration of the module to a JSON file.

save_torch_weights(output_path[, ...])

Save the PyTorch weights of the module to disk.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

tokenize(texts, *[, padding])

Tokenize texts and/or omics identifiers.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

Attributes#

MMContextEncoder.T_destination = ~T_destination#
MMContextEncoder.VALID_DATA_ORIGINS = ['unregistered', 'pca', 'hvg', 'scvi_fm', 'geneformer', 'random']#
MMContextEncoder.call_super_init = False#
MMContextEncoder.config_file_name = 'config.json'#

The name of the configuration file used to save the module’s configuration. This file is used to initialize the module when loading it from a pre-trained model.

MMContextEncoder.config_keys = ['text_encoder_name', 'adapter_hidden_dim', 'adapter_output_dim', 'freeze_text_encoder', 'unfreeze_last_n_layers', 'registered_data_origin', 'registered_input_dim', 'output_token_embeddings', 'train_lookup', 'pooling_mode']#

A list of keys used to save the module’s configuration. These keys are used to save the module’s configuration when saving the model to disk.

MMContextEncoder.dump_patches = False#
MMContextEncoder.forward_kwargs = {}#

A set of keyword arguments that can be passed to the forward method of the module. These arguments are used to pass additional information from the model’s encode method to the module’s forward method.

MMContextEncoder.registered_data_origin#

Get the type of omics data representation registered with this model.

MMContextEncoder.registered_input_dim#

Get the input dimension of registered data.

MMContextEncoder.save_in_root = False#

Whether to save the module’s configuration in the root directory of the model or in a subdirectory named after the module.

MMContextEncoder.tokenizer#

Convenience property returning the underlying processor object, which includes the text tokenizer and omics data processor.

MMContextEncoder.training#

Methods#

MMContextEncoder.add_module(name, module)#

Add a child module to the current module.

The module can be accessed as an attribute using the given name.

Return type:

None

Args:
name (str): name of the child module. The child module can be

accessed from this module using the given name

module (Module): child module to be added to the module.

MMContextEncoder.apply(fn)#

Apply fn recursively to every submodule (as returned by .children()) as well as self.

Typical use includes initializing the parameters of a model (see also torch.nn.init).

Return type:

TypeVar(T, bound= Module)

Args:

fn (Module -> None): function to be applied to each submodule

Returns:

Module: self

Example:

>>> @torch.no_grad()
>>> def init_weights(m):
>>>     print(m)
>>>     if type(m) == nn.Linear:
>>>         m.weight.fill_(1.0)
>>>         print(m.weight)
>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
>>> net.apply(init_weights)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
MMContextEncoder.bfloat16()#

Casts all floating point parameters and buffers to bfloat16 datatype. :rtype: TypeVar(T, bound= Module)

Note

This method modifies the module in-place.

Returns:

Module: self

MMContextEncoder.buffers(recurse=True)#

Return an iterator over module buffers.

Return type:

Iterator[Tensor]

Args:
recurse (bool): if True, then yields buffers of this module

and all submodules. Otherwise, yields only buffers that are direct members of this module.

Yields:

torch.Tensor: module buffer

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for buf in model.buffers():
>>>     print(type(buf), buf.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
MMContextEncoder.children()#

Return an iterator over immediate children modules.

Return type:

Iterator[Module]

Yields:

Module: a child module

MMContextEncoder.compile(*args, **kwargs)#

Compile this Module’s forward using torch.compile().

This Module’s __call__ method is compiled and all arguments are passed as-is to torch.compile().

See torch.compile() for details on the arguments for this function.

MMContextEncoder.cpu()#

Move all model parameters and buffers to the CPU. :rtype: TypeVar(T, bound= Module)

Note

This method modifies the module in-place.

Returns:

Module: self

MMContextEncoder.cuda(device=None)#

Move all model parameters and buffers to the GPU.

This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on GPU while being optimized. :rtype: TypeVar(T, bound= Module)

Note

This method modifies the module in-place.

Args:
device (int, optional): if specified, all parameters will be

copied to that device

Returns:

Module: self

MMContextEncoder.double()#

Casts all floating point parameters and buffers to double datatype. :rtype: TypeVar(T, bound= Module)

Note

This method modifies the module in-place.

Returns:

Module: self

MMContextEncoder.eval()#

Set the module in evaluation mode.

This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e. whether they are affected, e.g. Dropout, BatchNorm, etc.

This is equivalent with self.train(False).

See Locally disabling gradient computation for a comparison between .eval() and several similar mechanisms that may be confused with it.

Return type:

TypeVar(T, bound= Module)

Returns:

Module: self

MMContextEncoder.extra_repr()#

Return the extra representation of the module.

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

Return type:

str

MMContextEncoder.float()#

Casts all floating point parameters and buffers to float datatype. :rtype: TypeVar(T, bound= Module)

Note

This method modifies the module in-place.

Returns:

Module: self

MMContextEncoder.forward(features)#

Embed a batch and maintain original ordering.

New architecture: 1. Get token embeddings from encoders 2. Apply adapters at token level (if enabled) 3. Use SentenceTransformers Pooling for sentence embeddings 4. Optionally return token embeddings

Parameters:

features (dict) – Output of tokenize method, containing text features and optionally omics features.

Return type:

Tensor | dict[str, Tensor]

Returns:

torch.Tensor or dict If return_tensor=True in features, returns a tensor of sentence embeddings directly. Otherwise, dict with ‘sentence_embedding’ and optionally ‘token_embeddings’.

Raises:

RuntimeError – If omics features are provided but the model hasn’t been initialized with omics capabilities.

MMContextEncoder.get_buffer(target)#

Return the buffer given by target if it exists, otherwise throw an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Return type:

Tensor

Args:
target: The fully-qualified string name of the buffer

to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns:

torch.Tensor: The buffer referenced by target

Raises:
AttributeError: If the target string references an invalid

path or resolves to something that is not a buffer

MMContextEncoder.get_config_dict()#

Returns a dictionary of the configuration parameters of the module.

These parameters are used to save the module’s configuration when saving the model to disk, and again used to initialize the module when loading it from a pre-trained model. The keys used in the dictionary are defined in the config_keys class variable.

Return type:

dict[str, Any]

Returns:

dict[str, Any]: A dictionary of the configuration parameters of the module.

MMContextEncoder.get_extra_state()#

Return any extra state to include in the module’s state_dict.

Implement this and a corresponding set_extra_state() for your module if you need to store extra state. This function is called when building the module’s state_dict().

Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.

Return type:

Any

Returns:

object: Any extra state to store in the module’s state_dict

static MMContextEncoder.get_initial_embeddings(hf_dataset, *, layer_key=None, axis='obs', download_dir='../../data/downloaded_chunks', extract_zip=True, overwrite=False, link_column='share_link')#

Download all embedding chunks referenced in hf_dataset and return in a format suitable for registration.

This assumes the dataset has a column (specified by link_column) in each split, which contains either share links to Nextcloud files or local file paths. For URLs, the function will download and optionally extract the files. For local paths, they are used directly without downloading.

Parameters:
  • hf_dataset (DatasetDict | Dataset) – A Hugging Face :pyclass:`~datasets.DatasetDict` that contains one or more splits and a link/path column in each split.

  • layer_key (Optional[str] (default: None)) – Name of the embedding to pull – * .obsm[layer_key] if axis=”obs” * .varm[layer_key] if axis=”var”

  • axis (Literal['obs', 'var'] (default: "obs")) – "obs" → use adata.obs.index "var" → use adata.var.index.

  • download_dir (str | Path (default: "../../data/downloaded_chunks")) – Local root folder where downloaded chunk files (ZIPs or extracted stores) will be materialized. Ignored for local paths.

  • extract_zip (bool (default: True)) – If True unpack Nextcloud ZIP downloads into chunk_<n>.zarr/. If False keep the ZIP and let Zarr’s zip-store backend read it directly (requires Zarr ≥ 2.16). Only applies to downloaded files.

  • overwrite (bool (default: False)) – Re-download / re-extract even if the target already exists. Only applies to downloaded files.

  • link_column (str (default: "share_link")) – Column name that stores the share links or local paths.

Return type:

tuple[DataFrame, dict[str, Path]]

Returns:

tuple[pandas.DataFrame, dict[str, Path]] A tuple containing: - DataFrame with two columns:

  • token - obs or var label (string)

  • embedding - 1-D numpy.ndarray of floats

  • Path mapping from original links to actual file locations

MMContextEncoder.get_parameter(target)#

Return the parameter given by target if it exists, otherwise throw an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Return type:

Parameter

Args:
target: The fully-qualified string name of the Parameter

to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns:

torch.nn.Parameter: The Parameter referenced by target

Raises:
AttributeError: If the target string references an invalid

path or resolves to something that is not an nn.Parameter

MMContextEncoder.get_sentence_embedding_dimension()#

Returns the dimension of the final sentence embedding.

Return type:

int

Returns:

int The dimension of the final sentence embedding.

MMContextEncoder.get_submodule(target)#

Return the submodule given by target if it exists, otherwise throw an error.

For example, let’s say you have an nn.Module A that looks like this:

A(
    (net_b): Module(
        (net_c): Module(
            (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2))
        )
        (linear): Linear(in_features=100, out_features=200, bias=True)
    )
)

(The diagram shows an nn.Module A. A which has a nested submodule net_b, which itself has two submodules net_c and linear. net_c then has a submodule conv.)

To check whether or not we have the linear submodule, we would call get_submodule("net_b.linear"). To check whether we have the conv submodule, we would call get_submodule("net_b.net_c.conv").

The runtime of get_submodule is bounded by the degree of module nesting in target. A query against named_modules achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists, get_submodule should always be used.

Return type:

Module

Args:
target: The fully-qualified string name of the submodule

to look for. (See above example for how to specify a fully-qualified string.)

Returns:

torch.nn.Module: The submodule referenced by target

Raises:
AttributeError: If at any point along the path resulting from

the target string the (sub)path resolves to a non-existent attribute name or an object that is not an instance of nn.Module.

MMContextEncoder.half()#

Casts all floating point parameters and buffers to half datatype. :rtype: TypeVar(T, bound= Module)

Note

This method modifies the module in-place.

Returns:

Module: self

MMContextEncoder.ipu(device=None)#

Move all model parameters and buffers to the IPU.

This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on IPU while being optimized. :rtype: TypeVar(T, bound= Module)

Note

This method modifies the module in-place.

Arguments:
device (int, optional): if specified, all parameters will be

copied to that device

Returns:

Module: self

classmethod MMContextEncoder.load(model_name_or_path, subfolder='', token=None, cache_folder=None, revision=None, local_files_only=False, safe_serialization=True, **kwargs)#

Loads the model from disk.

Parameters:
  • model_name_or_path (str) – Path to the model directory or the name of the model on Hugging Face.

  • subfolder (str, optional) – The subfolder within the model directory to load from. Defaults to ‘’.

  • token (bool | str | None, optional) – Token for authentication. Defaults to None.

  • cache_folder (str | None, optional) – Cache folder for the model files. Defaults to None.

  • revision (str | None, optional) – Revision of the model to load. Defaults to None.

  • local_files_only (bool, optional) – Whether to only load local files. Defaults to False.

  • safe_serialization (bool, optional) – If True, expects safetensors format; else a PyTorch bin.

Returns:

MMContextEncoder The loaded model instance, ready for data registration.

classmethod MMContextEncoder.load_config(model_name_or_path, subfolder='', config_filename=None, token=None, cache_folder=None, revision=None, local_files_only=False)#

Load the configuration of the module from a model checkpoint. The checkpoint can be either a local directory or a model id on Hugging Face. The configuration is loaded from a JSON file, which contains the parameters used to initialize the module.

Return type:

dict[str, Any]

Args:

model_name_or_path (str): The path to the model directory or the name of the model on Hugging Face. subfolder (str, optional): The subfolder within the model directory to load from, e.g. "1_Pooling".

Defaults to "".

config_filename (str | None, optional): The name of the configuration file to load.

If None, uses the default configuration file name defined in the config_file_name class variable. Defaults to None.

token (bool | str | None, optional): The token to use for authentication when loading from Hugging Face.

If None, tries to use a token saved using huggingface-cli login or the HF_TOKEN environment variable. Defaults to None.

cache_folder (str | None, optional): The folder to use for caching the model files.

If None, uses the default cache folder for Hugging Face, ~/.cache/huggingface. Defaults to None.

revision (str | None, optional): The revision of the model to load.

If None, uses the latest revision. Defaults to None.

local_files_only (bool, optional): Whether to only load local files. Defaults to False.

Returns:

dict[str, Any]: A dictionary of the configuration parameters of the module.

static MMContextEncoder.load_dir_path(model_name_or_path, subfolder='', token=None, cache_folder=None, revision=None, local_files_only=False)#

A utility function to load a directory from a model checkpoint. The checkpoint can be either a local directory or a model id on Hugging Face.

Return type:

str

Args:

model_name_or_path (str): The path to the model directory or the name of the model on Hugging Face. subfolder (str, optional): The subfolder within the model directory to load from, e.g. "1_Pooling".

Defaults to "".

token (bool | str | None, optional): The token to use for authentication when loading from Hugging Face.

If None, tries to use a token saved using huggingface-cli login or the HF_TOKEN environment variable. Defaults to None.

cache_folder (str | None, optional): The folder to use for caching the model files.

If None, uses the default cache folder for Hugging Face, ~/.cache/huggingface. Defaults to None.

revision (str | None, optional): The revision of the model to load.

If None, uses the latest revision. Defaults to None.

local_files_only (bool, optional): Whether to only load local files. Defaults to False.

Returns:

str: The path to the loaded directory.

static MMContextEncoder.load_file_path(model_name_or_path, filename, subfolder='', token=None, cache_folder=None, revision=None, local_files_only=False)#

A utility function to load a file from a model checkpoint. The checkpoint can be either a local directory or a model id on Hugging Face. The file is loaded from the specified subfolder within the model directory.

Return type:

str | None

Args:

model_name_or_path (str): The path to the model directory or the name of the model on Hugging Face. filename (str): The name of the file to load. subfolder (str, optional): The subfolder within the model directory to load from, e.g. "1_Pooling".

Defaults to "".

token (bool | str | None, optional): The token to use for authentication when loading from Hugging Face.

If None, tries to use a token saved using huggingface-cli login or the HF_TOKEN environment variable. Defaults to None.

cache_folder (str | None, optional): The folder to use for caching the model files.

If None, uses the default cache folder for Hugging Face, ~/.cache/huggingface. Defaults to None.

revision (str | None, optional): The revision of the model to load.

If None, uses the latest revision. Defaults to None.

local_files_only (bool, optional): Whether to only load local files. Defaults to False.

Returns:

str | None: The path to the loaded file, or None if the file was not found.

MMContextEncoder.load_state_dict(state_dict, strict=True, assign=False)#

Copy parameters and buffers from state_dict into this module and its descendants.

If strict is True, then the keys of state_dict must exactly match the keys returned by this module’s state_dict() function.

Warning

If assign is True the optimizer must be created after the call to load_state_dict unless get_swap_module_params_on_conversion() is True.

Args:
state_dict (dict): a dict containing parameters and

persistent buffers.

strict (bool, optional): whether to strictly enforce that the keys

in state_dict match the keys returned by this module’s state_dict() function. Default: True

assign (bool, optional): When set to False, the properties of the tensors

in the current module are preserved whereas setting it to True preserves properties of the Tensors in the state dict. The only exception is the requires_grad field of Default: ``False`

Returns:
NamedTuple with missing_keys and unexpected_keys fields:
  • missing_keys is a list of str containing any keys that are expected

    by this module but missing from the provided state_dict.

  • unexpected_keys is a list of str containing the keys that are not

    expected by this module but present in the provided state_dict.

Note:

If a parameter or buffer is registered as None and its corresponding key exists in state_dict, load_state_dict() will raise a RuntimeError.

classmethod MMContextEncoder.load_torch_weights(model_name_or_path, subfolder='', token=None, cache_folder=None, revision=None, local_files_only=False, model=None)#

A utility function to load the PyTorch weights of a model from a checkpoint. The checkpoint can be either a local directory or a model id on Hugging Face. The weights are loaded from either a model.safetensors file or a pytorch_model.bin file, depending on which one is available. This method either loads the weights into the model or returns the weights as a state dictionary.

Args:

model_name_or_path (str): The path to the model directory or the name of the model on Hugging Face. subfolder (str, optional): The subfolder within the model directory to load from, e.g. "2_Dense".

Defaults to "".

token (bool | str | None, optional): The token to use for authentication when loading from Hugging Face.

If None, tries to use a token saved using huggingface-cli login or the HF_TOKEN environment variable. Defaults to None.

cache_folder (str | None, optional): The folder to use for caching the model files.

If None, uses the default cache folder for Hugging Face, ~/.cache/huggingface. Defaults to None.

revision (str | None, optional): The revision of the model to load.

If None, uses the latest revision. Defaults to None.

local_files_only (bool, optional): Whether to only load local files. Defaults to False. model (Self | None, optional): The model to load the weights into. If None, returns the weights as a state

dictionary. Defaults to None.

Raises:
ValueError: If neither a model.safetensors file nor a pytorch_model.bin file is found in the model

checkpoint in the subfolder.

Returns:
Self | dict[str, torch.Tensor]: The model with the loaded weights or the weights as a state dictionary,

depending on the value of the model argument.

MMContextEncoder.modules()#

Return an iterator over all modules in the network.

Return type:

Iterator[Module]

Yields:

Module: a module in the network

Note:

Duplicate modules are returned only once. In the following example, l will be returned only once.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.modules()):
...     print(idx, '->', m)

0 -> Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
1 -> Linear(in_features=2, out_features=2, bias=True)
MMContextEncoder.mtia(device=None)#

Move all model parameters and buffers to the MTIA.

This also makes associated parameters and buffers different objects. So it should be called before constructing the optimizer if the module will live on MTIA while being optimized. :rtype: TypeVar(T, bound= Module)

Note

This method modifies the module in-place.

Arguments:
device (int, optional): if specified, all parameters will be

copied to that device

Returns:

Module: self

MMContextEncoder.named_buffers(prefix='', recurse=True, remove_duplicate=True)#

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

Return type:

Iterator[tuple[str, Tensor]]

Args:

prefix (str): prefix to prepend to all buffer names. recurse (bool, optional): if True, then yields buffers of this module

and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.

remove_duplicate (bool, optional): whether to remove the duplicated buffers in the result. Defaults to True.

Yields:

(str, torch.Tensor): Tuple containing the name and buffer

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, buf in self.named_buffers():
>>>     if name in ['running_var']:
>>>         print(buf.size())
MMContextEncoder.named_children()#

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

Return type:

Iterator[tuple[str, Module]]

Yields:

(str, Module): Tuple containing a name and child module

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, module in model.named_children():
>>>     if name in ['conv4', 'conv5']:
>>>         print(module)
MMContextEncoder.named_modules(memo=None, prefix='', remove_duplicate=True)#

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

Args:

memo: a memo to store the set of modules already added to the result prefix: a prefix that will be added to the name of the module remove_duplicate: whether to remove the duplicated module instances in the result

or not

Yields:

(str, Module): Tuple of name and module

Note:

Duplicate modules are returned only once. In the following example, l will be returned only once.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.named_modules()):
...     print(idx, '->', m)

0 -> ('', Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
))
1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
MMContextEncoder.named_parameters(prefix='', recurse=True, remove_duplicate=True)#

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

Return type:

Iterator[tuple[str, Parameter]]

Args:

prefix (str): prefix to prepend to all parameter names. recurse (bool): if True, then yields parameters of this module

and all submodules. Otherwise, yields only parameters that are direct members of this module.

remove_duplicate (bool, optional): whether to remove the duplicated

parameters in the result. Defaults to True.

Yields:

(str, Parameter): Tuple containing the name and parameter

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for name, param in self.named_parameters():
>>>     if name in ['bias']:
>>>         print(param.size())
MMContextEncoder.parameters(recurse=True)#

Return an iterator over module parameters.

This is typically passed to an optimizer.

Return type:

Iterator[Parameter]

Args:
recurse (bool): if True, then yields parameters of this module

and all submodules. Otherwise, yields only parameters that are direct members of this module.

Yields:

Parameter: module parameter

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> for param in model.parameters():
>>>     print(type(param), param.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
MMContextEncoder.prepare_ds(ds, primary_cell_sentence_col, *, prefix=True, caption_col='caption', positive_col='positive', label_col='label', negative_prefix='negative', index_col='sample_idx', keep_index_col=False)#

Return a copy ready for SentenceTransformerTrainer.

Parameters:
  • ds (HFDataset | DatasetDict) – Input dataset to prepare

  • primary_cell_sentence_col (str) – Column containing cell/sample representations. References one of the cell_sentence columns in the dataset, that you want to process. These will be tokenized by the omics part of the model, if prefix=True, or by the text part of the model, if prefix=False. These will be the primary output columns. For multiplets, negative samples will be chosen from this column, if they are sample indices. Other negatives are captions and are not modified. If prefix=True, these will be prefixed with the processor’s prefix.

  • prefix (bool, optional) – Whether to add the processor’s prefix to primary_cell_sentence_col. If False, only subsetting is performed.

  • caption_col (str, optional) – Name of the caption column for pairs

  • positive_col (str, optional) – Name of the positive column for multiplets

  • label_col (str, optional) – Name of the label column for pairs

  • negative_prefix (str, optional) – Prefix for negative columns in multiplets

  • index_col (str, optional) – Name of the index column for HFDataset. Only if index_col is provided, it will be left in the output.

  • keep_index_col (bool, optional) – Whether to keep the index column in the output. Defaults to False. Is needed for the embedding workflow.

Return type:

Dataset | DatasetDict

Returns:

HFDataset | DatasetDict Processed dataset with appropriate columns and optional prefixes

MMContextEncoder.random_initial_embeddings(tokens, *, dim=64, rng_seed=None, id_col='token', data_origin='random')#

Register tokens with Gaussian-random vectors instead of real embeddings.

Parameters:
  • tokens (Sequence[str] | DataFrame | Dataset | DatasetDict | Mapping[str, Any]) –

    • List/tuple of token strings or

    • A pandas / HF dataset / mapping containing a column or key named

    id_col. Any duplicates are collapsed.

  • dim (int (default: 64)) – Embedding dimensionality for every generated vector.

  • rng_seed (Optional[int] (default: None)) – Reproducible seed. If None → numpy default RNG.

  • id_col (str (default: "token")) – Column/key that holds the token strings when tokens is a table.

  • data_origin (str (default: "random")) – Passed straight through to register_initial_embeddings.

Return type:

dict[str, int]

MMContextEncoder.register_backward_hook(hook)#

Register a backward hook on the module.

This function is deprecated in favor of register_full_backward_hook() and the behavior of this function will change in future versions.

Return type:

RemovableHandle

Returns:
torch.utils.hooks.RemovableHandle:

a handle that can be used to remove the added hook by calling handle.remove()

MMContextEncoder.register_buffer(name, tensor, persistent=True)#

Add a buffer to the module.

This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s running_mean is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by setting persistent to False. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’s state_dict.

Buffers can be accessed as attributes using given names.

Return type:

None

Args:
name (str): name of the buffer. The buffer can be accessed

from this module using the given name

tensor (Tensor or None): buffer to be registered. If None, then operations

that run on buffers, such as cuda, are ignored. If None, the buffer is not included in the module’s state_dict.

persistent (bool): whether the buffer is part of this module’s

state_dict.

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> self.register_buffer('running_mean', torch.zeros(num_features))
MMContextEncoder.register_forward_hook(hook, *, prepend=False, with_kwargs=False, always_call=False)#

Register a forward hook on the module.

The hook will be called every time after forward() has computed an output.

If with_kwargs is False or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to the forward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called after forward() is called. The hook should have the following signature:

hook(module, args, output) -> None or modified output

If with_kwargs is True, the forward hook will be passed the kwargs given to the forward function and be expected to return the output possibly modified. The hook should have the following signature:

hook(module, args, kwargs, output) -> None or modified output
Return type:

RemovableHandle

Args:

hook (Callable): The user defined hook to be registered. prepend (bool): If True, the provided hook will be fired

before all existing forward hooks on this torch.nn.Module. Otherwise, the provided hook will be fired after all existing forward hooks on this torch.nn.Module. Note that global forward hooks registered with register_module_forward_hook() will fire before all hooks registered by this method. Default: False

with_kwargs (bool): If True, the hook will be passed the

kwargs given to the forward function. Default: False

always_call (bool): If True the hook will be run regardless of

whether an exception is raised while calling the Module. Default: False

Returns:
torch.utils.hooks.RemovableHandle:

a handle that can be used to remove the added hook by calling handle.remove()

MMContextEncoder.register_forward_pre_hook(hook, *, prepend=False, with_kwargs=False)#

Register a forward pre-hook on the module.

The hook will be called every time before forward() is invoked.

If with_kwargs is false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to the forward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:

hook(module, args) -> None or modified input

If with_kwargs is true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:

hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
Return type:

RemovableHandle

Args:

hook (Callable): The user defined hook to be registered. prepend (bool): If true, the provided hook will be fired before

all existing forward_pre hooks on this torch.nn.Module. Otherwise, the provided hook will be fired after all existing forward_pre hooks on this torch.nn.Module. Note that global forward_pre hooks registered with register_module_forward_pre_hook() will fire before all hooks registered by this method. Default: False

with_kwargs (bool): If true, the hook will be passed the kwargs

given to the forward function. Default: False

Returns:
torch.utils.hooks.RemovableHandle:

a handle that can be used to remove the added hook by calling handle.remove()

MMContextEncoder.register_full_backward_hook(hook, prepend=False)#

Register a backward hook on the module.

The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:

hook(module, grad_input, grad_output) -> tuple(Tensor) or None

The grad_input and grad_output are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place of grad_input in subsequent computations. grad_input will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries in grad_input and grad_output will be None for all non-Tensor arguments.

For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function. :rtype: RemovableHandle

Warning

Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.

Args:

hook (Callable): The user-defined hook to be registered. prepend (bool): If true, the provided hook will be fired before

all existing backward hooks on this torch.nn.Module. Otherwise, the provided hook will be fired after all existing backward hooks on this torch.nn.Module. Note that global backward hooks registered with register_module_full_backward_hook() will fire before all hooks registered by this method.

Returns:
torch.utils.hooks.RemovableHandle:

a handle that can be used to remove the added hook by calling handle.remove()

MMContextEncoder.register_full_backward_pre_hook(hook, prepend=False)#

Register a backward pre-hook on the module.

The hook will be called every time the gradients for the module are computed. The hook should have the following signature:

hook(module, grad_output) -> tuple[Tensor] or None

The grad_output is a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place of grad_output in subsequent computations. Entries in grad_output will be None for all non-Tensor arguments.

For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function. :rtype: RemovableHandle

Warning

Modifying inputs inplace is not allowed when using backward hooks and will raise an error.

Args:

hook (Callable): The user-defined hook to be registered. prepend (bool): If true, the provided hook will be fired before

all existing backward_pre hooks on this torch.nn.Module. Otherwise, the provided hook will be fired after all existing backward_pre hooks on this torch.nn.Module. Note that global backward_pre hooks registered with register_module_full_backward_pre_hook() will fire before all hooks registered by this method.

Returns:
torch.utils.hooks.RemovableHandle:

a handle that can be used to remove the added hook by calling handle.remove()

MMContextEncoder.register_initial_embeddings(data, data_origin, *, id_col='token', emb_col='embedding', return_added=False)#

Add gene / sample tokens and their initial embeddings to the encoder.

Parameters:
  • data (DataFrame | Dataset | Mapping[str, Sequence[float]]) –

    • pandas.DataFrame / HF Datasetid_col has the token strings,

    emb_col holds a vector (np.ndarray, list, or tuple). • Mapping{token_str: embedding_vector}.#

  • data_origin (str) – Tag describing how the numeric representation was generated ("pca", "hvg", "scvi_fm", "geneformer" …).

  • id_col (str (default: "token")) – Column names for DataFrame / HF-Dataset input.

  • emb_col (str | None (default: "embedding")) – Column names for DataFrame / HF-Dataset input.

  • return_added (bool (default: False)) – If True, return a dictionary of the newly added tokens and their corresponding indices in the omics embedding matrix.

Return type:

dict[str, int]

Returns:

dict Only the new tokens inserted this call, e.g. {"EGFR": 12345, "KRAS": 12346}.

MMContextEncoder.register_load_state_dict_post_hook(hook)#

Register a post-hook to be run after module’s load_state_dict() is called.

It should have the following signature::

hook(module, incompatible_keys) -> None

The module argument is the current module that this hook is registered on, and the incompatible_keys argument is a NamedTuple consisting of attributes missing_keys and unexpected_keys. missing_keys is a list of str containing the missing keys and unexpected_keys is a list of str containing the unexpected keys.

The given incompatible_keys can be modified inplace if needed.

Note that the checks performed when calling load_state_dict() with strict=True are affected by modifications the hook makes to missing_keys or unexpected_keys, as expected. Additions to either set of keys will result in an error being thrown when strict=True, and clearing out both missing and unexpected keys will avoid an error.

Returns:
torch.utils.hooks.RemovableHandle:

a handle that can be used to remove the added hook by calling handle.remove()

MMContextEncoder.register_load_state_dict_pre_hook(hook)#

Register a pre-hook to be run before module’s load_state_dict() is called.

It should have the following signature::

hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950

Arguments:
hook (Callable): Callable hook that will be invoked before

loading the state dict.

MMContextEncoder.register_module(name, module)#

Alias for add_module().

Return type:

None

MMContextEncoder.register_parameter(name, param)#

Add a parameter to the module.

The parameter can be accessed as an attribute using given name.

Return type:

None

Args:
name (str): name of the parameter. The parameter can be accessed

from this module using the given name

param (Parameter or None): parameter to be added to the module. If

None, then operations that run on parameters, such as cuda, are ignored. If None, the parameter is not included in the module’s state_dict.

MMContextEncoder.register_state_dict_post_hook(hook)#

Register a post-hook for the state_dict() method.

It should have the following signature::

hook(module, state_dict, prefix, local_metadata) -> None

The registered hooks can modify the state_dict inplace.

MMContextEncoder.register_state_dict_pre_hook(hook)#

Register a pre-hook for the state_dict() method.

It should have the following signature::

hook(module, prefix, keep_vars) -> None

The registered hooks can be used to perform pre-processing before the state_dict call is made.

MMContextEncoder.requires_grad_(requires_grad=True)#

Change if autograd should record operations on parameters in this module.

This method sets the parameters’ requires_grad attributes in-place.

This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).

See Locally disabling gradient computation for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.

Return type:

TypeVar(T, bound= Module)

Args:
requires_grad (bool): whether autograd should record operations on

parameters in this module. Default: True.

Returns:

Module: self

MMContextEncoder.save(output_path, safe_serialization=True, **kwargs)#

Saves the model configuration and state dict, excluding the omics embedding matrix.

Parameters:
  • output_path (str) – Directory to save model files.

  • safe_serialization (bool, optional) – If True, use safetensors; else use torch.save.

Return type:

None

MMContextEncoder.save_config(output_path, filename=None)#

Save the configuration of the module to a JSON file.

Return type:

None

Args:

output_path (str): The path to the directory where the configuration file should be saved. filename (str | None, optional): The name of the configuration file. If None, uses the default configuration

file name defined in the config_file_name class variable. Defaults to None.

Returns:

None

MMContextEncoder.save_torch_weights(output_path, safe_serialization=True)#

Save the PyTorch weights of the module to disk.

Return type:

None

Args:

output_path (str): The path to the directory where the weights should be saved. safe_serialization (bool, optional): Whether to use the safetensors format for saving the model weights.

Defaults to True.

Returns:

None

MMContextEncoder.set_extra_state(state)#

Set extra state contained in the loaded state_dict.

This function is called from load_state_dict() to handle any extra state found within the state_dict. Implement this function and a corresponding get_extra_state() for your module if you need to store extra state within its state_dict.

Return type:

None

Args:

state (dict): Extra state from the state_dict

MMContextEncoder.set_submodule(target, module, strict=False)#

Set the submodule given by target if it exists, otherwise throw an error. :rtype: None

Note

If strict is set to False (default), the method will replace an existing submodule or create a new submodule if the parent module exists. If strict is set to True, the method will only attempt to replace an existing submodule and throw an error if the submodule does not exist.

For example, let’s say you have an nn.Module A that looks like this:

A(
    (net_b): Module(
        (net_c): Module(
            (conv): Conv2d(3, 3, 3)
        )
        (linear): Linear(3, 3)
    )
)

(The diagram shows an nn.Module A. A has a nested submodule net_b, which itself has two submodules net_c and linear. net_c then has a submodule conv.)

To override the Conv2d with a new submodule Linear, you could call set_submodule("net_b.net_c.conv", nn.Linear(1, 1)) where strict could be True or False

To add a new submodule Conv2d to the existing net_b module, you would call set_submodule("net_b.conv", nn.Conv2d(1, 1, 1)).

In the above if you set strict=True and call set_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True), an AttributeError will be raised because net_b does not have a submodule named conv.

Args:
target: The fully-qualified string name of the submodule

to look for. (See above example for how to specify a fully-qualified string.)

module: The module to set the submodule to. strict: If False, the method will replace an existing submodule

or create a new submodule if the parent module exists. If True, the method will only attempt to replace an existing submodule and throw an error if the submodule doesn’t already exist.

Raises:

ValueError: If the target string is empty or if module is not an instance of nn.Module. AttributeError: If at any point along the path resulting from

the target string the (sub)path resolves to a non-existent attribute name or an object that is not an instance of nn.Module.

MMContextEncoder.share_memory()#

See torch.Tensor.share_memory_().

Return type:

TypeVar(T, bound= Module)

MMContextEncoder.state_dict(*args, destination=None, prefix='', keep_vars=False)#

Return a dictionary containing references to the whole state of the module.

Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to None are not included.

Note

The returned object is a shallow copy. It contains references to the module’s parameters and buffers.

Warning

Currently state_dict() also accepts positional arguments for destination, prefix and keep_vars in order. However, this is being deprecated and keyword arguments will be enforced in future releases.

Warning

Please avoid the use of argument destination as it is not designed for end-users.

Args:
destination (dict, optional): If provided, the state of module will

be updated into the dict and the same object is returned. Otherwise, an OrderedDict will be created and returned. Default: None.

prefix (str, optional): a prefix added to parameter and buffer

names to compose the keys in state_dict. Default: ''.

keep_vars (bool, optional): by default the Tensor s

returned in the state dict are detached from autograd. If it’s set to True, detaching will not be performed. Default: False.

Returns:
dict:

a dictionary containing a whole state of the module

Example:

>>> # xdoctest: +SKIP("undefined vars")
>>> module.state_dict().keys()
['bias', 'weight']
MMContextEncoder.to(*args, **kwargs)#

Move and/or cast the parameters and buffers.

This can be called as

to(device=None, dtype=None, non_blocking=False)
mmcontext.models.mmcontextencoder.to(dtype, non_blocking=False)
mmcontext.models.mmcontextencoder.to(tensor, non_blocking=False)
mmcontext.models.mmcontextencoder.to(memory_format=torch.channels_last)

Its signature is similar to torch.Tensor.to(), but only accepts floating point or complex dtypes. In addition, this method will only cast the floating point or complex parameters and buffers to dtype (if given). The integral parameters and buffers will be moved device, if that is given, but with dtypes unchanged. When non_blocking is set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.

See below for examples.

Note

This method modifies the module in-place.

Args:
device (torch.device): the desired device of the parameters

and buffers in this module

dtype (torch.dtype): the desired floating point or complex dtype of

the parameters and buffers in this module

tensor (torch.Tensor): Tensor whose dtype and device are the desired

dtype and device for all parameters and buffers in this module

memory_format (torch.memory_format): the desired memory

format for 4D parameters and buffers in this module (keyword only argument)

Returns:

Module: self

Examples:

>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]], dtype=torch.float64)
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16)

>>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
>>> linear.weight
Parameter containing:
tensor([[ 0.3741+0.j,  0.2382+0.j],
        [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
>>> linear(torch.ones(3, 2, dtype=torch.cdouble))
tensor([[0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
MMContextEncoder.to_empty(*, device, recurse=True)#

Move the parameters and buffers to the specified device without copying storage.

Return type:

TypeVar(T, bound= Module)

Args:
device (torch.device): The desired device of the parameters

and buffers in this module.

recurse (bool): Whether parameters and buffers of submodules should

be recursively moved to the specified device.

Returns:

Module: self

MMContextEncoder.tokenize(texts, *, padding=True, **tok_kwargs)#

Tokenize texts and/or omics identifiers.

Parameters:
  • texts (sequence of str) – Texts and/or omics identifiers.

  • padding (str or bool, optional) – Forwarded to the underlying HF tokenizer (default: True).

  • **tok_kwargs – Additional keyword args forwarded to the tokenizer.

Return type:

dict[str, Tensor]

Returns:

dict Tokenized features compatible with the forward method.

MMContextEncoder.train(mode=True)#

Set the module in training mode.

This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e., whether they are affected, e.g. Dropout, BatchNorm, etc.

Return type:

TypeVar(T, bound= Module)

Args:
mode (bool): whether to set training mode (True) or evaluation

mode (False). Default: True.

Returns:

Module: self

MMContextEncoder.type(dst_type)#

Casts all parameters and buffers to dst_type. :rtype: TypeVar(T, bound= Module)

Note

This method modifies the module in-place.

Args:

dst_type (type or string): the desired type

Returns:

Module: self

MMContextEncoder.xpu(device=None)#

Move all model parameters and buffers to the XPU.

This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized. :rtype: TypeVar(T, bound= Module)

Note

This method modifies the module in-place.

Arguments:
device (int, optional): if specified, all parameters will be

copied to that device

Returns:

Module: self

MMContextEncoder.zero_grad(set_to_none=True)#

Reset gradients of all model parameters.

See similar function under torch.optim.Optimizer for more context.

Return type:

None

Args:
set_to_none (bool): instead of setting to zero, set the grads to None.

See torch.optim.Optimizer.zero_grad() for details.