Reference¶
liquidsig package¶
liquidsig.models.transformer_deconv module¶
Transformer-based deconvolution model for cfRNA tissue proportion estimation.
This module implements a transformer architecture specifically designed for deconvolution tasks, using attention mechanisms to learn relationships between gene expression patterns and tissue proportions.
- class TransformerDeconvolver(use_mixed_precision=True)¶
Bases:
objectTransformer-based deconvolution implementation.
- Parameters:
use_mixed_precision (bool)
- fine_tune_with_auxiliary_data(expression_data, auxiliary_data, auxiliary_targets, proportions=None, learning_rate=1e-05, n_epochs=50, batch_size=32, auxiliary_weight=0.1, wandb_logger=None)¶
Fine-tune the model with auxiliary lab data (delegated to AuxiliaryTrainer).
- Return type:
Dict[str,float]- Parameters:
expression_data (ndarray)
auxiliary_data (Dict[str, ndarray])
auxiliary_targets (List[str])
proportions (ndarray | None)
learning_rate (float)
n_epochs (int)
batch_size (int)
auxiliary_weight (float)
- property gene_symbols: List[str] | None¶
Gene symbols the model was trained on (read-only). Returns None if not loaded.
- property hierarchical_structure: HierarchicalStructure | None¶
Hierarchical structure (tissue->cell mapping) (read-only). Returns None if not loaded.
- load_model(filepath)¶
Load a trained model and scaler from file.
- Parameters:
filepath (
str) – Path to the saved model checkpoint- Return type:
None
- property model¶
The trained model (read-only). Returns None if not loaded.
- property model_architecture: str | None¶
Architecture name of the loaded model (read-only). Returns None if not loaded.
- predict(expression_df)¶
Predict tissue and cell-type proportions from CPM-normalized expression data.
- Parameters:
expression_df (
DataFrame) – DataFrame with genes as columns, single sample as row. Must be CPM-normalized (sums ~100K-1M for filtered genes).- Return type:
Dict[str,Any]- Returns:
Dictionary with structure:
{ 'tissue_proportions': DataFrame with tissue predictions, 'conditional_cell_proportions': Dict[tissue_name -> DataFrame], 'cell_type_proportions': DataFrame with global cell predictions }
- Raises:
ValueError – If input data appears to be incorrectly normalized
- predict_with_auxiliary(expression_df)¶
Predict tissue proportions and auxiliary targets (delegated to AuxiliaryTrainer).
- Return type:
DataFrame- Parameters:
expression_df (DataFrame)
- save_model(filepath)¶
Save model, scaler, and metadata to file.
- Parameters:
filepath (
str) – Path to save the model checkpoint- Return type:
None
- property scaler¶
The scaler used for input normalization (read-only). Returns None if not loaded.
- property tissues: List[str] | None¶
Tissue types the model predicts (read-only). Returns None if not loaded.
- train(architecture, model_config, training_config, tissue_archetypes_path, cell_archetypes_path, torch_compile=True, use_wandb=False, wandb_project='liquidsig-training')¶
Train transformer deconvolution model.
- Return type:
Dict[str,Any]- Parameters:
architecture (str)
model_config (ModelConfig)
training_config (TrainingConfig)
tissue_archetypes_path (str)
cell_archetypes_path (str)
torch_compile (bool)
use_wandb (bool)
wandb_project (str)
liquidsig.models.config module¶
Configuration classes for transformer-based deconvolution models.
- class ArchetypeConfig(target_gene_count=3500, marker_gene_specificity_threshold=0.5, use_two_track_filtering=False, tissue_track_budget=0.7, cell_track_budget=0.3, cell_track_min_tissue_fc=2.0, cell_track_min_cell_fc=10.0, use_cell_level_augmentation=True, cell_augmentation_weight=0.3)¶
Bases:
objectArchetype filtering and enhancement configuration.
- Parameters:
target_gene_count (int)
marker_gene_specificity_threshold (float)
use_two_track_filtering (bool)
tissue_track_budget (float)
cell_track_budget (float)
cell_track_min_tissue_fc (float)
cell_track_min_cell_fc (float)
use_cell_level_augmentation (bool)
cell_augmentation_weight (float)
-
cell_augmentation_weight:
float= 0.3¶
-
cell_track_budget:
float= 0.3¶
-
cell_track_min_cell_fc:
float= 10.0¶
-
cell_track_min_tissue_fc:
float= 2.0¶
- filter_to_marker_genes = True¶
-
marker_gene_specificity_threshold:
float= 0.5¶
-
target_gene_count:
int= 3500¶
-
tissue_track_budget:
float= 0.7¶
-
use_cell_level_augmentation:
bool= True¶
-
use_two_track_filtering:
bool= False¶
- class ConfigManager¶
Bases:
objectManages configuration profiles for model training.
- classmethod get_available_profiles()¶
Get list of available profile names.
- Return type:
list[str]- Returns:
List of profile names that can be used with get_profile_config()
- static get_profile_config(profile_name, model_override=None, training_override=None)¶
Get configuration for a specific profile with optional overrides.
- Parameters:
profile_name (
str) – Name of the profile to loadmodel_override (
Optional[dict]) – Optional dict to override model config fieldstraining_override (
Optional[dict]) – Optional dict to override training config fields
- Return type:
tuple[ModelConfig,TrainingConfig]- Returns:
Tuple of (ModelConfig, TrainingConfig)
- class LRSchedulerConfig(warmup_epochs=10, plateau_patience=30, plateau_factor=0.5, min_learning_rate=1e-07)¶
Bases:
objectLearning rate scheduler configuration.
- Parameters:
warmup_epochs (int)
plateau_patience (int)
plateau_factor (float)
min_learning_rate (float)
-
min_learning_rate:
float= 1e-07¶
-
plateau_factor:
float= 0.5¶
-
plateau_patience:
int= 30¶
-
warmup_epochs:
int= 10¶
- class ModelConfig(d_model=256, n_heads=8, n_encoder_layers=4, n_decoder_layers=2, n_tissue_decoder_layers=2, n_cell_decoder_layers=4, dim_feedforward=1024, dropout=0.05, auxiliary_targets=None, top_k=100, chunked_top_k=True, tissue_weight=0.5, cell_weight=25.0, consistency_weight=1.0, encoder_type='module', n_modules=100, module_attention=False, n_latents=128, latent_layers=4)¶
Bases:
objectModel architecture configuration.
Note: n_encoder_layers and n_decoder_layers are the primary layer count parameters. The n_tissue_decoder_layers and n_cell_decoder_layers provide finer control for hierarchical models.
- Parameters:
d_model (int)
n_heads (int)
n_encoder_layers (int)
n_decoder_layers (int)
n_tissue_decoder_layers (int)
n_cell_decoder_layers (int)
dim_feedforward (int)
dropout (float)
auxiliary_targets (List[str] | None)
top_k (int | None)
chunked_top_k (bool)
tissue_weight (float)
cell_weight (float)
consistency_weight (float)
encoder_type (str)
n_modules (int)
module_attention (bool)
n_latents (int)
latent_layers (int)
-
auxiliary_targets:
Optional[List[str]] = None¶
-
cell_weight:
float= 25.0¶
-
chunked_top_k:
bool= True¶
-
consistency_weight:
float= 1.0¶
-
d_model:
int= 256¶
-
dim_feedforward:
int= 1024¶
-
dropout:
float= 0.05¶
-
encoder_type:
str= 'module'¶
- classmethod from_profile(profile='default')¶
Load configuration from a named profile.
- Return type:
- Parameters:
profile (str)
-
latent_layers:
int= 4¶
-
module_attention:
bool= False¶
-
n_cell_decoder_layers:
int= 4¶
-
n_decoder_layers:
int= 2¶
-
n_encoder_layers:
int= 4¶
-
n_heads:
int= 8¶
-
n_latents:
int= 128¶
-
n_modules:
int= 100¶
-
n_tissue_decoder_layers:
int= 2¶
-
tissue_weight:
float= 0.5¶
- to_wandb_dict()¶
Return model config as a dictionary for wandb logging.
- Return type:
Dict[str,object]
-
top_k:
Optional[int] = 100¶
- class ProfileDict¶
Bases:
TypedDictType for profile configuration dictionaries.
-
model:
ModelConfig¶
-
training:
TrainingConfig¶
-
model:
- class TrainingConfig(training_mode='sparse', n_synthetic_samples=1000, n_validation_samples=200, training_noise_level=0.0, tissue_dirichlet_alpha=0.5, cell_dirichlet_alpha=0.2, learning_rate=0.0001, weight_decay=1e-06, batch_size=32, accumulation_steps=8, epochs=100, patience=10, lr_scheduler=<factory>, input_dropout_rate=0.0, use_mixed_precision=True, debug_level=0, archetypes=<factory>, use_ontology=True, ontology_similarity_method='jaccard', ontology_weight=0.05, ontology_similarity_threshold=0.5)¶
Bases:
objectTraining hyperparameters configuration.
- Parameters:
training_mode (Literal['sparse', 'dense', 'mixed', 'fixed_validation'])
n_synthetic_samples (int)
n_validation_samples (int)
training_noise_level (float)
tissue_dirichlet_alpha (float)
cell_dirichlet_alpha (float)
learning_rate (float)
weight_decay (float)
batch_size (int)
accumulation_steps (int)
epochs (int)
patience (int)
lr_scheduler (LRSchedulerConfig)
input_dropout_rate (float)
use_mixed_precision (bool)
debug_level (int)
archetypes (ArchetypeConfig)
use_ontology (bool)
ontology_similarity_method (Literal['jaccard', 'path'])
ontology_weight (float)
ontology_similarity_threshold (float)
-
accumulation_steps:
int= 8¶
-
archetypes:
ArchetypeConfig¶
-
batch_size:
int= 32¶
-
cell_dirichlet_alpha:
float= 0.2¶
-
debug_level:
int= 0¶
-
epochs:
int= 100¶
-
input_dropout_rate:
float= 0.0¶
-
learning_rate:
float= 0.0001¶
-
lr_scheduler:
LRSchedulerConfig¶
-
n_synthetic_samples:
int= 1000¶
-
n_validation_samples:
int= 200¶
-
ontology_similarity_method:
Literal['jaccard','path'] = 'jaccard'¶
-
ontology_similarity_threshold:
float= 0.5¶
-
ontology_weight:
float= 0.05¶
-
patience:
int= 10¶
-
tissue_dirichlet_alpha:
float= 0.5¶
- to_wandb_dict()¶
Return training config as a dictionary for wandb logging.
- Return type:
Dict[str,object]
-
training_mode:
Literal['sparse','dense','mixed','fixed_validation'] = 'sparse'¶
-
training_noise_level:
float= 0.0¶
-
use_mixed_precision:
bool= True¶
-
use_ontology:
bool= True¶
-
weight_decay:
float= 1e-06¶