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:
ModuleDual-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:
- 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"→ useadata.obs.index"var"→ useadata.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 intochunk_<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:
- Returns:
tuple[pandas.DataFrame, dict[str, Path]] A tuple containing: - DataFrame with two columns:
token- obs or var label (string)embedding- 1-Dnumpy.ndarrayof floats
Path mapping from original links to actual file locations
- get_sentence_embedding_dimension()#
Returns the dimension of the final sentence embedding.
- Return type:
- 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 toregister_initial_embeddings.
- Return type:
- 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 Dataset –
id_colhas the token strings,
emb_colholds 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:
- 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.
- tokenize(texts, *, padding=True, **tok_kwargs)#
Tokenize texts and/or omics identifiers.
- Parameters:
- Return type:
- 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#
The name of the configuration file used to save the module's configuration. |
|
A list of keys used to save the module's configuration. |
|
A set of keyword arguments that can be passed to the forward method of the module. |
|
Get the type of omics data representation registered with this model. |
|
Get the input dimension of registered data. |
|
Whether to save the module's configuration in the root directory of the model or in a subdirectory named after the module. |
|
Convenience property returning the underlying processor object, which includes the text tokenizer and omics data processor. |
|
Methods table#
|
Add a child module to the current module. |
|
Apply |
|
Casts all floating point parameters and buffers to |
|
Return an iterator over module buffers. |
|
Return an iterator over immediate children modules. |
|
Compile this Module's forward using |
|
Move all model parameters and buffers to the CPU. |
|
Move all model parameters and buffers to the GPU. |
|
Casts all floating point parameters and buffers to |
|
Set the module in evaluation mode. |
Return the extra representation of the module. |
|
|
Casts all floating point parameters and buffers to |
|
Embed a batch and maintain original ordering. |
|
Return the buffer given by |
Returns a dictionary of the configuration parameters of the module. |
|
Return any extra state to include in the module's state_dict. |
|
|
Download all embedding chunks referenced in hf_dataset and return in a format suitable for registration. |
|
Return the parameter given by |
Returns the dimension of the final sentence embedding. |
|
|
Return the submodule given by |
|
Casts all floating point parameters and buffers to |
|
Move all model parameters and buffers to the IPU. |
|
Loads the model from disk. |
|
Load the configuration of the module from a model checkpoint. |
|
A utility function to load a directory from a model checkpoint. |
|
A utility function to load a file from a model checkpoint. |
|
Copy parameters and buffers from |
|
A utility function to load the PyTorch weights of a model from a checkpoint. |
|
Return an iterator over all modules in the network. |
|
Move all model parameters and buffers to the MTIA. |
|
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself. |
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself. |
|
|
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself. |
|
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself. |
|
Return an iterator over module parameters. |
|
Return a copy ready for SentenceTransformerTrainer. |
|
Register tokens with Gaussian-random vectors instead of real embeddings. |
|
Register a backward hook on the module. |
|
Add a buffer to the module. |
|
Register a forward hook on the module. |
|
Register a forward pre-hook on the module. |
|
Register a backward hook on the module. |
|
Register a backward pre-hook on the module. |
|
Add gene / sample tokens and their initial embeddings to the encoder. |
Register a post-hook to be run after module's |
|
Register a pre-hook to be run before module's |
|
|
Alias for |
|
Add a parameter to the module. |
Register a post-hook for the |
|
Register a pre-hook for the |
|
|
Change if autograd should record operations on parameters in this module. |
|
Saves the model configuration and state dict, excluding the omics embedding matrix. |
|
Save the configuration of the module to a JSON file. |
|
Save the PyTorch weights of the module to disk. |
|
Set extra state contained in the loaded |
|
Set the submodule given by |
|
Return a dictionary containing references to the whole state of the module. |
|
Move and/or cast the parameters and buffers. |
|
Move the parameters and buffers to the specified device without copying storage. |
|
Tokenize texts and/or omics identifiers. |
|
Set the module in training mode. |
|
Casts all parameters and buffers to |
|
Move all model parameters and buffers to the XPU. |
|
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:
- 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
fnrecursively 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
bfloat16datatype. :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.
- 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 totorch.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
doubledatatype. :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:
- MMContextEncoder.float()#
Casts all floating point parameters and buffers to
floatdatatype. :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:
- 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
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Return type:
- Args:
- target: The fully-qualified string name of the buffer
to look for. (See
get_submodulefor 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_keysclass variable.- 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’sstate_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:
- 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"→ useadata.obs.index"var"→ useadata.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 intochunk_<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:
- Returns:
tuple[pandas.DataFrame, dict[str, Path]] A tuple containing: - DataFrame with two columns:
token- obs or var label (string)embedding- 1-Dnumpy.ndarrayof floats
Path mapping from original links to actual file locations
- MMContextEncoder.get_parameter(target)#
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Return type:
- Args:
- target: The fully-qualified string name of the Parameter
to look for. (See
get_submodulefor 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:
- Returns:
int The dimension of the final sentence embedding.
- MMContextEncoder.get_submodule(target)#
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat 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.ModuleA.Awhich has a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves 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_submoduleshould always be used.- Return type:
- 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
halfdatatype. :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.
- 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_nameclass 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 loginor theHF_TOKENenvironment 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:
- 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 loginor theHF_TOKENenvironment 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.
- 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 loginor theHF_TOKENenvironment 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_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dictunlessget_swap_module_params_on_conversion()isTrue.- Args:
- state_dict (dict): a dict containing parameters and
persistent buffers.
- strict (bool, optional): whether to strictly enforce that the keys
in
state_dictmatch the keys returned by this module’sstate_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
Truepreserves properties of the Tensors in the state dict. The only exception is therequires_gradfield ofDefault: ``False`
- Returns:
NamedTuplewithmissing_keysandunexpected_keysfields:- 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
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- 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.safetensorsfile or apytorch_model.binfile, 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 loginor theHF_TOKENenvironment 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.safetensorsfile nor apytorch_model.binfile is found in the model checkpoint in the
subfolder.
- ValueError: If neither a
- 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
modelargument.
- 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,
lwill 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.
- 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.
- 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,
lwill 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.
- 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.
- 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 toregister_initial_embeddings.
- Return type:
- 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_meanis 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 settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Return type:
- 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. IfNone, the buffer is not included in the module’sstate_dict.- persistent (bool): whether the buffer is part of this module’s
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_kwargsisFalseor 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 theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven 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 providedhookwill be firedbefore all existing
forwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:False- with_kwargs (bool): If
True, thehookwill be passed the kwargs given to the forward function. Default:
False- always_call (bool): If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:
False
- with_kwargs (bool): If
- 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_kwargsis 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 theforward. 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_kwargsis 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
hookwill be fired beforeall existing
forward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:False- with_kwargs (bool): If true, the
hookwill be passed the kwargs given to the forward function. Default:
False
- with_kwargs (bool): If true, the
- 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_inputandgrad_outputare 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 ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor 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:
RemovableHandleWarning
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
hookwill be fired beforeall existing
backwardhooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.Module. Note that globalbackwardhooks registered withregister_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_outputis 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 ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor 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:
RemovableHandleWarning
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
hookwill be fired beforeall existing
backward_prehooks on thistorch.nn.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.Module. Note that globalbackward_prehooks registered withregister_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 Dataset –
id_colhas the token strings,
emb_colholds 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:
- 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
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=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:
- MMContextEncoder.register_parameter(name, param)#
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Return type:
- 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 ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_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_dictinplace.
- 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_dictcall 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_gradattributes 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.
- MMContextEncoder.save_config(output_path, filename=None)#
Save the configuration of the module to a JSON file.
- Return type:
- 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_nameclass 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:
- 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 thestate_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within itsstate_dict.- Return type:
- Args:
state (dict): Extra state from the
state_dict
- MMContextEncoder.set_submodule(target, module, strict=False)#
Set the submodule given by
targetif it exists, otherwise throw an error. :rtype:NoneNote
If
strictis set toFalse(default), the method will replace an existing submodule or create a new submodule if the parent module exists. Ifstrictis set toTrue, 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.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(3, 3, 3) ) (linear): Linear(3, 3) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To override the
Conv2dwith a new submoduleLinear, you could callset_submodule("net_b.net_c.conv", nn.Linear(1, 1))wherestrictcould beTrueorFalseTo add a new submodule
Conv2dto the existingnet_bmodule, you would callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1)).In the above if you set
strict=Trueand callset_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True), an AttributeError will be raised becausenet_bdoes not have a submodule namedconv.- 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 submoduleor 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
targetstring is empty or ifmoduleis not an instance ofnn.Module. AttributeError: If at any point along the path resulting fromthe
targetstring the (sub)path resolves to a non-existent attribute name or an object that is not an instance ofnn.Module.
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
Noneare 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 fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas 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
OrderedDictwill 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
Tensors 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 complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis 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)
- device (
- 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.
- device (
- Returns:
Module: self
- MMContextEncoder.tokenize(texts, *, padding=True, **tok_kwargs)#
Tokenize texts and/or omics identifiers.
- Parameters:
- Return type:
- 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.
- mode (bool): whether to set training mode (
- 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.Optimizerfor more context.- Return type:
- Args:
- set_to_none (bool): instead of setting to zero, set the grads to None.
See
torch.optim.Optimizer.zero_grad()for details.