Parametric Base#
base
#
| CLASS | DESCRIPTION |
|---|---|
Parametric |
Abstract base class for parametric methods using neural networks. |
Classes#
Parametric(model: ModelType | dict[str, ModelType], device: Literal['cuda', 'cpu'] = 'cuda', store_loss_context: bool = False, optimizer_fn: type[torch.optim.Optimizer] | str | None = None, optimizer_kwargs: dict | None = None, lr_scheduler_fn: Any | str | None = None, lr_scheduler_kwargs: dict | None = None, *args, **kwargs)
#
Bases: ABC, LightningModule
Abstract base class for parametric methods using neural networks.
This class provides a unified interface for parametric machine learning techniques that learn embeddings and transformations through neural network optimization. It integrates with PyTorch Lightning for distributed training, automatic logging, and model management, etc.
The class serves as a foundation for methods such as SpectralMap, Autoencoder, and other parametric dimensionality reduction techniques. It handles model parsing, device management, optimizer configuration, and provides standardized training and evaluation interfaces.
Features:
- Automatic model parsing and device placement.
- PyTorch Lightning integration for scalable training.
- Standardized scoring and evaluation interfaces.
- Optimizer and scheduler configuration.
- Training status tracking for model validation.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Neural network model(s) for the parametric method. Single model neural network architecture (
Model dictionary ( Dictionary of multiple named models for multi-model architectures
(e.g., autoencoders). Keys are model names ("encoder", "decoder", etc.)
and values are model specifications in any format supported above.
Example:
TYPE:
|
device
|
Computation device. Falls back to "cpu" if CUDA is not available.
TYPE:
|
store_loss_context
|
Whether to store the loss context dictionary for metric extraction in callbacks. When enabled, the
TYPE:
|
optimizer_fn
|
Optimizer specification for training.
When specified, this parameter takes priority over the legacy
TYPE:
|
optimizer_kwargs
|
Keyword arguments for optimizer instantiation. Only used when
TYPE:
|
lr_scheduler_fn
|
Learning rate scheduler specification.
TYPE:
|
lr_scheduler_kwargs
|
Keyword arguments for scheduler instantiation. Special keys "monitor" and "interval" control PyTorch Lightning
scheduler configuration. Defaults:
TYPE:
|
*args
|
Additional arguments passed to parent classes.
TYPE:
|
**kwargs
|
Additional arguments passed to parent classes.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
model |
Primary parsed neural network model on the specified device. For multi-model architectures, this is the first model from the dictionary.
TYPE:
|
model_dict |
Dictionary of all parsed models on the specified device. For single-model initialization, contains {'model': model}.
TYPE:
|
is_trained |
Training status flag. Set to True after successful training completion.
TYPE:
|
optimizer_kwargs |
Configuration dictionary for optimizer and learning rate scheduler.
TYPE:
|
loss_context |
Loss context dictionary containing intermediate computation results.
Only populated when
TYPE:
|
Notes
This is an abstract base class that requires subclasses to implement:
loss(X, weights=None, target=None): Loss computation methodtraining_step(batch, batch_idx): PyTorch Lightning training stepforward_step(X): Forward pass computation stepscore_step(X, weights=None, target=None): Scoring computation step
The score method is only available after training (is_trained=True).
Use score_step for evaluation without training status checks.
| METHOD | DESCRIPTION |
|---|---|
add_transform |
Add a transformation to the model. |
loss |
Abstract method for loss computation. |
training_step |
Abstract method for PyTorch Lightning training step. |
forward_step |
Abstract method for forward pass computation. |
score_step |
Abstract method for score calculation without training validation. |
forward |
Main forward pass method. |
score |
Score the trained model performance. |
configure_optimizers |
Configure optimizer and learning rate scheduler for PyTorch Lightning. |
validation_step |
Validation step during training. |
test_step |
Test step during evaluation. |
predict_step |
Prediction step for inference. |
predict |
Predict method for inference on raw input data. Can be used |
fit |
Fit the parametric model using PyTorch Lightning. |
parse_model |
Parse and prepare model for training. |
parse_model_dict |
Parse and prepare multiple models for training. |
save_model |
Save model to file with optional TorchScript tracing. |
load_model |
Load model from file. |
from_pretrained |
Load pretrained model from checkpoint. |
on_train_end |
PyTorch Lightning hook called at the end of training. |
on_fit_end |
PyTorch Lightning hook called at the end of fit (training + |
log_training_metrics |
Standardized training/validation metric logging. |
log_metrics_dict |
Log a dictionary of metrics with flexible naming and automatic tensor |
Source code in spectre/parametric/base.py
Attributes#
is_trained: bool
property
writable
#
Check if model has been trained.
in_features: int
property
#
Get number of input features.
out_features: int
property
#
Get number of output features.
optimizer_kwargs: dict
property
writable
#
Get optimizer configuration.
Functions#
add_transform(transform: Any, name: str) -> None
#
Add a transformation to the model.
| PARAMETER | DESCRIPTION |
|---|---|
transform
|
Transformation to add (e.g., data preprocessing, embedding alignment).
TYPE:
|
name
|
Name of the transformation.
TYPE:
|
Source code in spectre/parametric/base.py
loss(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> torch.Tensor | tuple[torch.Tensor, ...]
abstractmethod
#
Abstract method for loss computation.
This method must be implemented by subclasses to define the specific loss function for the parametric technique (e.g., spectral loss, reconstruction loss, regularized loss, etc.).
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data tensor.
TYPE:
|
weights
|
Sample weights for weighted loss computation.
TYPE:
|
target
|
Target values for supervised learning.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor | tuple[Tensor, ...]
|
Scalar loss value for optimization. |
Source code in spectre/parametric/base.py
training_step(batch: DataBatch, batch_idx: int) -> torch.Tensor
abstractmethod
#
Abstract method for PyTorch Lightning training step.
This method defines how a single training batch is processed during training. It should compute the loss and optionally log metrics for monitoring.
| PARAMETER | DESCRIPTION |
|---|---|
batch
|
Batch of data containing 'data', 'weights', and optionally 'target'.
TYPE:
|
batch_idx
|
Index of the current batch within the epoch.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Scalar training loss for backpropagation. |
Notes
Implementations should use self.log() for metric tracking and call
self.loss() for loss computation.
Source code in spectre/parametric/base.py
forward_step(X: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, ...]
abstractmethod
#
Abstract method for forward pass computation.
This method defines the forward transformation applied to input data. It should implement the core computation of the parametric technique (e.g., encoding, dimensionality reduction, prediction).
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data tensor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor | tuple[Tensor, ...]
|
Transformed output tensor. |
Notes
This method is used by both forward() and during loss computation. It
should be differentiable for gradient-based optimization.
Source code in spectre/parametric/base.py
score_step(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> torch.Tensor
abstractmethod
#
Abstract method for score calculation without training validation.
This method must be implemented by subclasses to define the specific performance metric for the parametric technique (e.g., reconstruction error, clustering quality, embedding preservation, etc.).
Unlike score(), this method does not require training status
validation and can be used for intermediate evaluation during training
or for pre-trained models.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data for evaluation.
TYPE:
|
weights
|
Sample weights for weighted scoring metrics.
TYPE:
|
target
|
Target values for supervised evaluation metrics.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Performance score. Higher values typically indicate better performance, but the interpretation depends on the specific metric implementation. |
Source code in spectre/parametric/base.py
forward(X: torch.Tensor) -> torch.Tensor
#
Main forward pass method.
Performs the complete forward transformation by calling the abstract
forward_step method implemented by subclasses.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data tensor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Transformed output tensor. |
Notes
This method serves as the standard PyTorch torch.nn.Module forward
interface and delegates the actual computation to forward_step.
Source code in spectre/parametric/base.py
score(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> torch.Tensor
#
Score the trained model performance.
Evaluates the model using the scoring metric defined by the specific
parametric technique. This method requires the model to be trained
(is_trained=True) and performs evaluation in no-gradient mode.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data for evaluation.
TYPE:
|
weights
|
Sample weights for weighted scoring.
TYPE:
|
target
|
Target values for supervised evaluation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Model performance score. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If the model has not been trained ( |
Notes
This method enforces training validation and wraps score_step with
torch.no_grad() for efficient evaluation. Use score_step directly
for evaluation without training status checks.
Source code in spectre/parametric/base.py
configure_optimizers() -> torch.optim.Optimizer | dict
#
Configure optimizer and learning rate scheduler for PyTorch Lightning.
Supports two configuration modes:
- Using
optimizer_fnparameter in__init__ - Using
optimizer_kwargsproperty
| RETURNS | DESCRIPTION |
|---|---|
Optimizer or dict
|
If no scheduler is configured, returns the optimizer directly. If scheduler is configured, returns dict with "optimizer" and "lr_scheduler" keys for PyTorch Lightning. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the specified optimizer name is not found in |
Examples:
Configure via optimizer_fn parameter:
>>> sm = SpectralMap(
... model=encoder,
... optimizer_fn="AdamW",
... optimizer_kwargs={"lr": 1e-3, "weight_decay": 1e-4},
... lr_scheduler_fn="ReduceLROnPlateau",
... lr_scheduler_kwargs={"patience": 5},
... )
Source code in spectre/parametric/base.py
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 | |
validation_step(batch: DataBatch, batch_idx: int) -> torch.Tensor
#
Validation step during training.
| PARAMETER | DESCRIPTION |
|---|---|
batch
|
Input batch data.
TYPE:
|
batch_idx
|
Batch index.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Validation loss. |
Source code in spectre/parametric/base.py
test_step(batch: DataBatch, batch_idx: int) -> torch.Tensor
#
Test step during evaluation.
| PARAMETER | DESCRIPTION |
|---|---|
batch
|
Input batch data.
TYPE:
|
batch_idx
|
Batch index.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Test loss. |
Source code in spectre/parametric/base.py
predict_step(batch: DataBatch, batch_idx: int, dataloader_idx: int | None = None) -> torch.Tensor
#
Prediction step for inference.
| PARAMETER | DESCRIPTION |
|---|---|
batch
|
Input batch data.
TYPE:
|
batch_idx
|
Batch index.
TYPE:
|
dataloader_idx
|
Dataloader index for multiple dataloaders.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Model predictions |
Source code in spectre/parametric/base.py
predict(X: torch.Tensor) -> torch.Tensor
#
Predict method for inference on raw input data. Can be used independently of Pytorch Lightning training.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data tensor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Model predictions. |
Source code in spectre/parametric/base.py
fit(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None, trainer: pl.Trainer | None = None, n_epochs: int = 100, batch_size: int = 1000, val: float = 0.2, **trainer_kwargs) -> Parametric
#
Fit the parametric model using PyTorch Lightning.
This method provides a scikit-learn-style API for training parametric models while using PyTorch Lightning internally. It creates a DataModuleWeighted, configures a Trainer, and handles the training loop.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Training data of shape (n_samples, in_features).
TYPE:
|
weights
|
Sample weights of shape (n_samples,).
TYPE:
|
target
|
Target values for supervised learning.
TYPE:
|
trainer
|
Pre-configured PyTorch Lightning Trainer instance. If provided,
TYPE:
|
n_epochs
|
Maximum number of training epochs. Only used if
TYPE:
|
batch_size
|
Batch size for training and validation. Only used if
TYPE:
|
val
|
Fraction of data to use for validation (0.0-1.0). Only used if
TYPE:
|
**trainer_kwargs
|
Additional keyword arguments for PyTorch Lightning Trainer. Only used if
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Parametric
|
Return self. |
Examples:
Basic usage with default settings:
>>> from spectre.parametric import SpectralMap
>>> sm = SpectralMap(n_states=3, model=network)
>>> sm.fit(X, n_epochs=50)
Using a pre-configured Trainer:
>>> import pytorch_lightning as pl
>>> trainer = pl.Trainer(
... max_epochs=100,
... callbacks=[pl.callbacks.EarlyStopping(monitor="val_loss")],
... logger=pl.loggers.WandbLogger(project="my-project"),
... )
>>> sm.fit(X, trainer=trainer)
With custom Trainer kwargs:
>>> sm.fit(
... X,
... n_epochs=100,
... batch_size=512,
... val=0.15,
... callbacks=[pl.callbacks.EarlyStopping(monitor="val_loss", patience=10)],
... logger=pl.loggers.TensorBoardLogger("logs/"),
... accelerator="gpu",
... devices=2,
... )
Notes
- This method calls
datamodule.setup()before training - Training status is set via Lightning hooks
on_train_end()andon_fit_end() - For full control over the training process, use PyTorch Lightning's
standard API: create a Trainer and call
trainer.fit(model, datamodule) - This method is compatible with ensemble methods that expect a fit() signature of (X, weights, target)
Source code in spectre/parametric/base.py
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 | |
parse_model(model: ModelType, device: Literal['cuda', 'cpu'] = 'cuda') -> Model
#
Parse and prepare model for training.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Neural network model or compatible structure. Can be a Model instance, Sequential module, individual torch.nn.Module, OrderedDict of layers, or list/tuple of layers.
TYPE:
|
device
|
Target device for model.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Model
|
Parsed model on the specified device. |
Source code in spectre/parametric/base.py
parse_model_dict(model_dict: dict[str, ModelType], device: Literal['cuda', 'cpu'] = 'cuda') -> dict[str, Model]
#
Parse and prepare multiple models for training.
| PARAMETER | DESCRIPTION |
|---|---|
model_dict
|
Dictionary of named models where keys are model names (e.g.,
'encoder', 'decoder') and values are model specifications
compatible with
TYPE:
|
device
|
Target device for all models.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Model]
|
Dictionary of parsed Model instances on the specified device. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If models dict is empty or contains invalid model specifications. |
TypeError
|
If models is not a dictionary. |
Examples:
>>> model_dict = {"encoder": encoder_sequential, "decoder": decoder_list}
>>> parsed = self.parse_model_dict(model_dict, device="cuda")
>>> encoder = parsed["encoder"]
>>> decoder = parsed["decoder"]
Source code in spectre/parametric/base.py
save_model(filename: str, trace: bool = False) -> None
#
Save model to file with optional TorchScript tracing.
| PARAMETER | DESCRIPTION |
|---|---|
filename
|
Output file path.
TYPE:
|
trace
|
Whether to use TorchScript tracing for deployment optimization.
TYPE:
|
Source code in spectre/parametric/base.py
load_model(filename: str, trace: bool = False) -> None
#
Load model from file.
| PARAMETER | DESCRIPTION |
|---|---|
filename
|
Input file path.
TYPE:
|
trace
|
Whether model was saved with TorchScript tracing.
TYPE:
|
Source code in spectre/parametric/base.py
from_pretrained(path: str, map_location: str | None = None, **override_kwargs) -> Parametric
classmethod
#
Load pretrained model from checkpoint.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to checkpoint file.
TYPE:
|
map_location
|
Device mapping (e.g., 'cpu', 'cuda:0').
TYPE:
|
**override_kwargs
|
Override configuration parameters.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Parametric
|
Loaded model instance. |
Examples:
>>> model = SpectralMap.from_pretrained(
... "checkpoints/best.ckpt",
... map_location="cuda:0",
... )
Source code in spectre/parametric/base.py
on_train_end() -> None
#
PyTorch Lightning hook called at the end of training.
Sets the training status to True, enabling the use of the score
method for model evaluation.
Source code in spectre/parametric/base.py
on_fit_end() -> None
#
PyTorch Lightning hook called at the end of fit (training + validation).
Sets the training status to True, enabling the use of the score
method for model evaluation.
Source code in spectre/parametric/base.py
log_training_metrics(loss: torch.Tensor, prog_bar: bool = True, auto_expand_tensors: bool = True, **extra_metrics: torch.Tensor | float | int) -> None
#
Standardized training/validation metric logging.
Logs the main loss with consistent naming and optional extra metrics. Handles train/validation mode distinction and applies standard logging parameters for PyTorch Lightning. Can expand multi-element tensors into separate metrics.
| PARAMETER | DESCRIPTION |
|---|---|
loss
|
Main loss value to log with progress bar.
TYPE:
|
prog_bar
|
Whether to show loss in progress bar.
TYPE:
|
auto_expand_tensors
|
Whether to expand multi-element tensors in extra_metrics.
TYPE:
|
**extra_metrics
|
Additional metrics to log with train/val prefix. Multi-element tensors will be expanded if auto_expand_tensors=True.
TYPE:
|
Examples:
>>> # Simple loss logging
>>> self.log_training_metrics(loss)
>>>
>>> # With additional scalar metrics
>>> self.log_training_metrics(loss, mse_loss=mse, l1_loss=l1)
>>>
>>> # With tensor metrics (auto-expanded)
>>> eigvals = torch.tensor([1.0, 0.8, 0.6])
>>> self.log_training_metrics(loss, eigval=eigvals)
>>> # Logs: train_loss, train_eigval_0, train_eigval_1, train_eigval_2
>>>
>>> # Disable auto-expansion
>>> self.log_training_metrics(loss, weights=weight, auto_expand_tensors=False)
Source code in spectre/parametric/base.py
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 | |
log_metrics_dict(metrics: dict[str, torch.Tensor | float | int], prefix: str = '', add_train_val_prefix: bool = True, auto_expand_tensors: bool = True, on_step: bool = False, on_epoch: bool = True) -> None
#
Log a dictionary of metrics with flexible naming and automatic tensor expansion.
| PARAMETER | DESCRIPTION |
|---|---|
metrics
|
Dictionary of metric names and values to log. Multi-element tensors
will be expanded if
TYPE:
|
prefix
|
Additional prefix to add before metric names.
TYPE:
|
add_train_val_prefix
|
Whether to add train/val prefix based on current mode.
TYPE:
|
auto_expand_tensors
|
Whether to expand multi-element tensors.
TYPE:
|
on_step
|
Whether to log on each step.
TYPE:
|
on_epoch
|
Whether to log on each epoch.
TYPE:
|
Examples:
>>> # Log scalar metrics
>>> loss_components = {"mse": mse_loss, "l1": l1_loss}
>>> self.log_metrics_dict(loss_components, prefix="loss_")
>>>
>>> # Log tensor metrics (auto-expanded)
>>> tensor_metrics = {
... "weights": torch.tensor([1, 2, 3]),
... "biases": torch.tensor([[1, 2], [3, 4]]),
... }
>>> self.log_metrics_dict(tensor_metrics)
>>> # Logs: train_weight_0, train_weight_1, train_weight_2, train_biases_0_0
>>>
>>> # Log without train/val prefix or tensor expansion
>>> model_stats = {"n_params": param_count, "weight_matrix": W}
>>> self.log_metrics_dict(
... model_stats,
... add_train_val_prefix=False,
... auto_expand_tensors=False,
... )
Source code in spectre/parametric/base.py
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 | |