Loss Base#
base
#
| CLASS | DESCRIPTION |
|---|---|
LossType |
Categories for loss functions. |
Loss |
Base class for loss functions with common parameter validation. |
Classes#
LossType
#
Bases: str, Enum
Categories for loss functions.
Used to validate loss compatibility with specific models and provide semantic grouping of loss functions.
| ATTRIBUTE | DESCRIPTION |
|---|---|
SPECTRAL |
Eigenvalue/eigenvector-based losses (e.g., eigenvalue gap, alignment).
TYPE:
|
RECONSTRUCTION |
Reconstruction error losses (e.g., MSE, MAE, Huber).
TYPE:
|
PROBABILISTIC |
Probability distribution losses (e.g., KL divergence, ELBO, entropy).
TYPE:
|
CONTRASTIVE |
Contrastive and metric learning losses (e.g., triplet, contrastive).
TYPE:
|
REGULARIZATION |
Regularization penalties (e.g., orthogonality, Laplacian smoothness).
TYPE:
|
METRIC |
Evaluation metrics adapted as losses (e.g., R2, cosine similarity).
TYPE:
|
DISTILLATION |
Distillation losses (e.g., knowledge distillation, attention distillation).
TYPE:
|
CLUSTERING |
Clustering losses (e.g., min cut).
TYPE:
|
Loss(reduce: Literal['sum', 'mean'] = 'mean', sign: float = 1.0, context_prefix: str | None = None, *args, **kwargs)
#
Bases: Module
Base class for loss functions with common parameter validation.
All loss functions inherit from this class and must implement forward()
method that accepts a context dictionary containing tensors required for loss
computation.
Child classes should override allowed_reduce and loss_types at
class level to define custom reduction operations and semantic types.
| PARAMETER | DESCRIPTION |
|---|---|
reduce
|
Reduction method.
TYPE:
|
sign
|
Loss sign multiplier. Use -1.0 for maximization, 1.0 for minimization.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
allowed_reduce |
Allowed reduction operations. Child classes can override this class attribute to support different reduction methods.
TYPE:
|
loss_types |
Loss function categories. Child classes should override this class attribute to define their semantic type(s).
TYPE:
|
Examples:
Define a custom loss with specific reduction options
>>> class MyLoss(Loss):
... allowed_reduce = ["sum", "mean"]
... loss_types = [LossType.RECONSTRUCTION]
...
... def __init__(self, reduce="mean", sign=1.0):
... super().__init__(reduce=reduce, sign=sign)
...
... def forward(self, context, **kwargs):
... X = context.get("X")
... loss = (X**2).sum()
... if self.reduce == "mean":
... loss = loss.mean()
... return self.sign * loss
| METHOD | DESCRIPTION |
|---|---|
exists |
Check if loss matches the given pattern. |
forward |
Compute loss from context dictionary. |
Source code in spectre/loss/base.py
Functions#
exists(pattern: str) -> bool
#
Check if loss matches the given pattern.
For base Loss, checks if the pattern is contained in the loss name. CompositeLoss overrides this to check all constituent losses.
| PARAMETER | DESCRIPTION |
|---|---|
pattern
|
Pattern to match against loss name (e.g., "mincut", "eigenvalue").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if pattern is contained in the loss name, False otherwise. |
Examples:
>>> loss = MinCutLoss()
>>> loss.exists("mincut")
True
>>> loss.exists("loss_mincut")
True
>>> loss.exists("mse")
False
Source code in spectre/loss/base.py
forward(context: dict[str, torch.Tensor], **kwargs) -> torch.Tensor
abstractmethod
#
Compute loss from context dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
context
|
Dictionary containing all tensors required as arguments for the inherited loss classes.
TYPE:
|
**kwargs
|
Additional keyword arguments for specific loss implementations.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Computed loss value. |
Source code in spectre/loss/base.py
LossRegistry
#
Bases: Registry
Registry for loss classes with type metadata.
| METHOD | DESCRIPTION |
|---|---|
register |
Register a loss class with the given name and types. |
get_by_type |
Return names of losses matching the given type. |
get_types |
Return types for a registered loss or loss instance. |
Functions#
register(name: str, types: list[LossType] | None = None)
classmethod
#
Register a loss class with the given name and types.
Arguments
name : str Name to register the loss under. types : list[LossType] | None Loss type categories for this loss.
| RETURNS | DESCRIPTION |
|---|---|
Callable
|
Decorator that registers the loss class. |
Source code in spectre/loss/base.py
get_by_type(loss_type: LossType) -> list[str]
classmethod
#
Return names of losses matching the given type.
Arguments
loss_type : LossType Type to filter by.
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
Names of registered losses with the given type. |
Source code in spectre/loss/base.py
get_types(loss: str | Loss) -> list[LossType]
classmethod
#
Return types for a registered loss or loss instance.
Arguments
loss : str | Loss Name of the registered loss or loss instance.
| RETURNS | DESCRIPTION |
|---|---|
list[LossType]
|
Types associated with the loss. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no loss is registered with the given name. |
Source code in spectre/loss/base.py
Functions#
initialize_loss_fn(loss_fn: Loss | str | None, loss_kwargs: dict[str, Any] | None = None) -> Loss
#
Initialize a loss from an instance or registry name.
Arguments
loss_fn : Loss | str | None Loss instance or name of registered loss. loss_kwargs : dict[str, Any] | None Keyword arguments passed to loss constructor (only for string names).
| RETURNS | DESCRIPTION |
|---|---|
Loss
|
Initialized loss instance. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
TypeError
|
If |