Loss Eigen#
eigen
#
| CLASS | DESCRIPTION |
|---|---|
EigenvalueLoss |
Eigenvalue loss. |
AdaptiveEigenvalueLoss |
Adaptive spectral gap loss with automatic discovery of gap index. |
EigenvectorAlignmentLoss |
Eigenvector alignment loss. |
SpectralContrastiveLoss |
Contrastive loss based on kernel or transition matrix. |
| FUNCTION | DESCRIPTION |
|---|---|
eigenvalue_loss |
Compute eigenvalue-based loss for spectral methods. |
adaptive_eigenvalue_loss |
Adaptive spectral gap loss with automatic gap selection via log-sum-exp. |
eigenvector_alignment_loss |
Compute the eigenvector alignment loss. |
spectral_contrastive_loss |
Contrastive loss based on kernel or transition matrix. |
check_eigenvalues_sorted |
Check if eigenvalues are sorted in descending or ascending order. |
Classes#
EigenvalueLoss(reduce: Literal['gap', 'gap_exp', 'sum', 'sum_pow', 'cumsum', 'entropy', 'single'] = 'gap', n_eigen: int = 0, sign: float = -1.0, eps: float = torch.finfo(torch.float32).eps, context_prefix: str | None = None, **kwargs)
#
Bases: Loss
Eigenvalue loss.
Computes loss based on eigenvalues to optimize specific spectral properties.
| PARAMETER | DESCRIPTION |
|---|---|
reduce
|
Reduction operation.
TYPE:
|
n_eigen
|
Target eigenvalue index.
TYPE:
|
sign
|
Loss sign (-1 for maximization, +1 for minimization).
TYPE:
|
eps
|
Small constant for numerical stability in divisions.
TYPE:
|
**kwargs
|
Additional keyword arguments for the loss function.
TYPE:
|
Examples:
>>> loss_fn = EigenvalueLoss(reduce="gap", n_eigen=1)
>>> eigenvalues = torch.tensor([2.0, 1.5, 0.5])
>>> context = {"eigenvalues": eigenvalues}
>>> loss = loss_fn(context)
>>> print(loss)
tensor(-0.5000)
| METHOD | DESCRIPTION |
|---|---|
forward |
Compute eigenvalue loss. |
Source code in spectre/loss/eigen.py
Functions#
forward(context: dict, **kwargs) -> torch.Tensor
#
Compute eigenvalue loss.
| PARAMETER | DESCRIPTION |
|---|---|
context
|
Dictionary containing the eigenvalues (required).
TYPE:
|
**kwargs
|
Additional keyword arguments.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Eigenvalue loss. |
Source code in spectre/loss/eigen.py
AdaptiveEigenvalueLoss(n_eigen: int | None = None, min_states: int = 2, max_states: int | None = None, temperature: float = 0.1, adaptive_weight: float = 1.0, anchor_weight: float = 0.0, normalize: bool = False, gap_mode: Literal['absolute', 'relative', 'log', 'timescale'] = 'absolute', sign: float = -1.0, eps: float = torch.finfo(torch.float32).eps, context_prefix: str | None = None, **kwargs)
#
Bases: Loss
Adaptive spectral gap loss with automatic discovery of gap index.
Uses soft-argmax to differentiably maximize the largest spectral gap, allowing the model to discover optimal number of metastable states during training rather than pre-specifying the number of states.
The loss combines two components:
Adaptive component (soft-argmax over all gaps)
- Uses temperature-scaled softmax:
weights = softmax(gaps / T) - Maximizes:
sum(weights * gaps)
Anchor component (fixed gap at specified position)
- Provides stability during training
- Uses pre-training estimate as regularization
Mathematically:
where:
- \(g_i = \lambda_{i-1} - \lambda_i\) is the spectral gap for \(i\) states
- \(w_i = \text{softmax}(g_i/T)\)
- \(\alpha\) is
adaptive_weight, \(\beta\) isanchor_weight, and \(n\) isn_eigen.
| PARAMETER | DESCRIPTION |
|---|---|
n_eigen
|
Fixed position for anchor loss. Required if
TYPE:
|
min_states
|
Minimum number of states to consider. Gaps before this threshold are ignored to prevent trivial solutions.
For example, with
TYPE:
|
max_states
|
Maximum number of states to consider. If None, no upper limit. Restricts search space to prevent discovering too many artificial states.
TYPE:
|
temperature
|
Softmax temperature for soft-argmax (typical range: [0.01, 1]).
TYPE:
|
adaptive_weight
|
Weight for adaptive component (soft-max gap maximization). Sum of
TYPE:
|
anchor_weight
|
Weight for fixed anchor component (gap at Set to 0 for pure adaptive mode.
TYPE:
|
normalize
|
If True, normalizes gaps by sum of relevant eigenvalues for scale invariance. If
TYPE:
|
gap_mode
|
Mode for computing spectral gaps.
TYPE:
|
sign
|
Loss sign multiplier. -1.0 for maximization (default), 1.0 for minimization.
TYPE:
|
eps
|
Small constant for numerical stability in divisions.
TYPE:
|
**kwargs
|
Additional keyword arguments for the loss function.
DEFAULT:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
allowed_reduce |
Allowed reduction operations (only ["none"] for this loss).
TYPE:
|
loss_types |
Loss function categories (SPECTRAL).
TYPE:
|
Examples:
Pure adaptive mode:
>>> from spectre.loss import AdaptiveEigenvalueLoss
>>> from spectre.parametric import SpectralMap
>>>
>>> loss = AdaptiveEigenvalueLoss(
... min_states=2,
... max_states=10,
... temperature=0.1,
... adaptive_weight=1.0,
... anchor_weight=0.0,
... )
>>>
>>> # Use with SpectralMap
>>> sm = SpectralMap(model=model, distance_fn="euclidean", loss_fn=loss)
Anchored adaptive mode:
>>> n_est = 3
>>>
>>> loss = AdaptiveEigenvalueLoss(
... min_states=2,
... max_states=10,
... temperature=0.1,
... adaptive_weight=0.7, # 70% adaptive
... anchor_weight=0.3, # 30% fixed anchor
... n_eigen=n_est, # Anchor at estimate
... )
>>>
>>> sm = SpectralMap(model=model, kernel_fn="gaussian", loss_fn=loss)
Temperature annealing can be turned on using a PyTorch Lightning callback:
>>> from spectre.utils.callbacks import ParameterAnnealingCallback
>>>
>>> loss = AdaptiveEigenvalueLoss(
... temperature=0.1,
... adaptive_weight=0.8,
... anchor_weight=0.2,
... n_eigen=n_est,
... )
| METHOD | DESCRIPTION |
|---|---|
forward |
Compute adaptive spectral gap loss. |
Source code in spectre/loss/eigen.py
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | |
Functions#
forward(context: dict, **kwargs) -> torch.Tensor
#
Compute adaptive spectral gap loss.
| PARAMETER | DESCRIPTION |
|---|---|
context
|
Context dictionary, must contain "eigenvalues" key.
TYPE:
|
**kwargs
|
Additional keyword arguments.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Adaptive spectral gap loss. |
Source code in spectre/loss/eigen.py
EigenvectorAlignmentLoss(mode: Literal['reconstruction', 'cosine'] = 'reconstruction', reduce: Literal['mean', 'sum'] = 'mean', sign: float = 1.0, eps: float = torch.finfo(torch.float32).eps, context_prefix: str | None = None, **kwargs)
#
Bases: Loss
Eigenvector alignment loss.
Encourages embeddings to align with provided eigenvectors.
| PARAMETER | DESCRIPTION |
|---|---|
mode
|
Mode of alignment.
TYPE:
|
reduce
|
Reduction method.
TYPE:
|
sign
|
Loss sign multiplier.
TYPE:
|
eps
|
Small value for numerical stability.
TYPE:
|
**kwargs
|
Additional keyword arguments for the loss function.
TYPE:
|
Examples:
>>> loss_fn = EigenvectorAlignmentLoss(mode="reconstruction")
>>> Z = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> eigenvectors = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> context = {"Z": Z, "eigenvectors": eigenvectors}
>>> loss = loss_fn(context)
>>> print(loss)
tensor(...)
| METHOD | DESCRIPTION |
|---|---|
forward |
Compute eigenvector alignment loss. |
Source code in spectre/loss/eigen.py
Functions#
forward(context: dict, **kwargs) -> torch.Tensor
#
Compute eigenvector alignment loss.
| PARAMETER | DESCRIPTION |
|---|---|
context
|
Context dictionary containing the input data and eigenvectors.
TYPE:
|
**kwargs
|
Additional keyword arguments.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Eigenvector alignment loss. |
Source code in spectre/loss/eigen.py
SpectralContrastiveLoss(temperature: float = 0.1, threshold: float = 0.0, soft: bool = False, reduce: Literal['mean', 'sum'] = 'mean', sign: float = 1.0, context_prefix: str | None = None, **kwargs)
#
Bases: Loss
Contrastive loss based on kernel or transition matrix.
Computes a contrastive loss that encourages similar points (connected in K) to have similar embeddings in Z, while dissimilar points (not connected in K) to have dissimilar embeddings.
For binary adjacency matrices (traditional contrastive loss), connected nodes are treated as positive pairs and non-connected nodes as negative pairs.
For transition matrices (e.g., diffusion maps), a soft contrastive loss can be used where connections above a threshold are treated as positive pairs with weights proportional to the transition probabilities.
| PARAMETER | DESCRIPTION |
|---|---|
temperature
|
Temperature parameter for similarity scaling.
TYPE:
|
threshold
|
Threshold for defining positive/negative pairs when soft=True. When soft=False, this parameter is ignored and K > 0 is used.
TYPE:
|
soft
|
Whether to use soft contrastive loss with continuous weights.
TYPE:
|
reduce
|
Reduction method.
TYPE:
|
sign
|
Loss sign multiplier.
TYPE:
|
**kwargs
|
Additional keyword arguments for the loss function.
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
forward |
Compute spectral contrastive loss. |
Source code in spectre/loss/eigen.py
Functions#
forward(context: dict, **kwargs) -> torch.Tensor
#
Compute spectral contrastive loss.
Source code in spectre/loss/eigen.py
Functions#
eigenvalue_loss(eigenvalues: torch.Tensor, reduce: Literal['gap', 'gap_exp', 'sum', 'sum_pow', 'cumsum', 'entropy', 'single'] = 'gap', n_eigen: int = 0, sign: float = -1, eps: float = torch.finfo(torch.float32).eps) -> torch.Tensor
#
Compute eigenvalue-based loss for spectral methods.
Computes loss based on eigenvalues to optimize specific spectral properties.
| PARAMETER | DESCRIPTION |
|---|---|
eigenvalues
|
Eigenvalues in descending order
TYPE:
|
reduce
|
Reduction operation.
TYPE:
|
n_eigen
|
Target eigenvalue index.
TYPE:
|
sign
|
Loss sign (-1 for maximization, +1 for minimization).
TYPE:
|
eps
|
Small constant for numerical stability in divisions.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Computed reduced eigenvalue loss. |
Examples:
>>> eigenvalues = torch.tensor([2.0, 1.5, 0.5])
>>> loss = eigenvalue_loss(eigenvalues, reduce="gap", n_eigen=1)
>>> print(loss)
tensor(-0.5000)
Source code in spectre/loss/eigen.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | |
adaptive_eigenvalue_loss(eigenvalues: torch.Tensor, n_eigen: int | None = None, min_states: int = 2, max_states: int | None = None, temperature: float = 0.1, adaptive_weight: float = 1.0, anchor_weight: float = 0.0, normalize: bool = False, gap_mode: Literal['absolute', 'relative', 'log', 'timescale'] = 'absolute', sign: float = -1.0, eps: float = torch.finfo(torch.float32).eps) -> torch.Tensor
#
Adaptive spectral gap loss with automatic gap selection via log-sum-exp.
Combines adaptive gap maximization with optional fixed anchor for stability.
| PARAMETER | DESCRIPTION |
|---|---|
eigenvalues
|
Eigenvalues in descending order, shape (n_eigenvalues,)
TYPE:
|
min_states
|
Minimum states to consider. Gaps for fewer states are ignored.
TYPE:
|
max_states
|
Maximum states to consider (ignore gaps after this)
TYPE:
|
temperature
|
Temperature for log-sum-exp smooth maximum (lower = more focused).
TYPE:
|
adaptive_weight
|
Weight for adaptive component [0, 1]
TYPE:
|
anchor_weight
|
Weight for anchor component [0, 1]
TYPE:
|
n_eigen
|
Fixed position for anchor (required if anchor_weight > 0)
TYPE:
|
normalize
|
Normalize gaps by sum of relevant eigenvalues. If
TYPE:
|
gap_mode
|
Mode for computing spectral gaps.
TYPE:
|
sign
|
Loss sign (-1 for maximization)
TYPE:
|
eps
|
Numerical stability constant
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Scalar loss value |
The loss combines adaptive and anchor components:
|
|
$L = \alpha L_{\text{adaptive}} + \beta L_{\text{anchor}}$
|
|
where
|
TYPE:
|
- Spectral gaps $g_i$ for $i$ states (see `gap_mode` for formulation)
|
|
- Adaptive component via log-sum-exp (smooth max):
|
\(L_{\text{adaptive}} = T \log \sum_i \exp(g_i / T)\) |
- Anchor component: $L_{\text{anchor}} = g_n$ where $n$ is `n_eigen`
|
|
- $T$ is temperature, $\alpha$ is `adaptive_weight`, $\beta$ is `anchor_weight`
|
|
Examples:
>>> import torch
>>> eigenvalues = torch.tensor([1.0, 0.9, 0.8, 0.3, 0.2, 0.1])
>>> loss = adaptive_eigenvalue_loss(eigenvalues, temperature=0.1)
>>> print(loss)
tensor(-0.5000)
Source code in spectre/loss/eigen.py
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 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 | |
eigenvector_alignment_loss(Z: torch.Tensor, eigenvectors: torch.Tensor, mode: Literal['reconstruction', 'cosine'] = 'reconstruction', reduce: Literal['mean', 'sum'] = 'mean', sign: float = 1.0, eps: float = torch.finfo(torch.float32).eps) -> torch.Tensor
#
Compute the eigenvector alignment loss.
Encourages embeddings to align with provided eigenvectors.
| PARAMETER | DESCRIPTION |
|---|---|
Z
|
Input tensor of shape (n_samples, n_features).
TYPE:
|
eigenvectors
|
Eigenvectors of shape (n_samples, n_eigenvectors).
If
TYPE:
|
reduce
|
Reduction method.
TYPE:
|
sign
|
Loss sign multiplier.
TYPE:
|
mode
|
Mode of alignment.
TYPE:
|
eps
|
Small value for numerical stability, by default torch.finfo(torch.float32).eps.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Computed alignment loss. |
Examples:
>>> Z = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> eigenvectors = torch.tensor([[0.7071, 0.7071], [0.7071, -0.7071]])
>>> loss = eigenvector_alignment_loss(Z, eigenvectors, mode="reconstruction")
>>> print(loss)
tensor(...)
Source code in spectre/loss/eigen.py
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 | |
spectral_contrastive_loss(Z: torch.Tensor, K: torch.Tensor, temperature: float = 0.1, threshold: float = 0.0, soft: bool = False, reduce: Literal['sum', 'mean'] = 'mean', sign: float = 1.0) -> torch.Tensor
#
Contrastive loss based on kernel or transition matrix.
Computes a contrastive loss that encourages similar points (connected in K)
to have similar embeddings in input data, while dissimilar points
(not connected in K) to have dissimilar embeddings.
This implements an InfoNCE-style contrastive loss where for each anchor sample,
positive pairs (connected in K) should have higher similarity than all other
samples (including both unconnected samples and other positives).
For binary adjacency matrices (traditional contrastive loss), connected nodes are treated as positive pairs and non-connected nodes as negative pairs.
For transition matrices (e.g., diffusion maps), a soft contrastive loss can be used where connections above a threshold are treated as positive pairs with weights proportional to the transition probabilities.
| PARAMETER | DESCRIPTION |
|---|---|
Z
|
Input embeddings of shape (n_samples, in_features).
TYPE:
|
K
|
Kernel, adjacency, or transition matrix of shape (n_samples, n_samples).
TYPE:
|
temperature
|
Temperature parameter for similarity scaling.
TYPE:
|
threshold
|
Threshold for defining positive/negative pairs when soft=True. When soft=False, this parameter is ignored and K > 0 is used.
TYPE:
|
soft
|
Whether to use soft contrastive loss with continuous weights.
TYPE:
|
reduce
|
Reduction method.
TYPE:
|
sign
|
Loss sign multiplier.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Computed contrastive loss. |
Notes
The loss is computed per anchor sample \(i\) as:
\(L_i = -\log \frac{\sum_{p \in P_i} \exp(s_{ip}/T)} {\sum_{j \neq i} \exp(s_{ij}/T)}\)
where \(P_i\) is the set of positive pairs for anchor \(i\), \(s_{ij}\) is the similarity between samples \(i\) and \(j\), and \(T\) is the temperature.
In soft mode, positive pairs are weighted by their values in \(K\):
\(L_i = -\log \frac{\sum_{p \in P_i} K_{ip} \exp(s_{ip}/T)} {\sum_{j \neq i} \exp(s_{ij}/T)}\)
Examples:
For binary adjacency matrices (standard)
For diffusion maps / transition matrices (manifold-aware)
>>> loss = spectral_contrastive_loss(
... embeddings,
... transition_matrix,
... threshold=0.1,
... soft=True,
... )
Source code in spectre/loss/eigen.py
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 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 1123 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 | |
check_eigenvalues_sorted(eigenvalues: torch.Tensor, descending: bool = True, raise_error: bool = True) -> bool
#
Check if eigenvalues are sorted in descending or ascending order.
| PARAMETER | DESCRIPTION |
|---|---|
eigenvalues
|
1D tensor of eigenvalues.
TYPE:
|
descending
|
If True, check descending order; if False, check ascending order.
TYPE:
|
raise_error
|
If True, raise ValueError when not sorted; if False, return False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if sorted correctly, False otherwise (when raise_error=False). |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If eigenvalues are not sorted and raise_error=True. |
Examples:
>>> eigenvalues = torch.tensor([1.0, 3.0, 2.0])
>>> check_eigenvalues_sorted(eigenvalues, raise_error=False)
False