Loss Distillation#
distillation
#
| CLASS | DESCRIPTION |
|---|---|
DistillationLoss |
Distillation loss that adapts to teacher-student pair. |
FeatureMatchingLoss |
Loss for matching intermediate feature representations. |
SpectralPreservationLoss |
Loss for preserving spectral properties in distillation. |
| FUNCTION | DESCRIPTION |
|---|---|
distillation_loss |
Compute combined distillation loss and task loss (MSE by default). |
feature_matching_loss |
Compute feature matching loss between teacher and student features. |
spectral_preservation_loss |
Loss for preserving spectral properties in distillation. |
Classes#
DistillationLoss(alpha: float = 0.7, temperature: float = 4.0, shape_matching: Literal['projection', 'padding', 'truncation'] = 'projection', reduce: Literal['sum', 'mean'] = 'mean', sign: float = 1.0, context_prefix: str | None = None)
#
Bases: Loss
Distillation loss that adapts to teacher-student pair.
Combines distillation loss (student vs teacher) with task loss (student vs ground truth) with using a weighted combination.
Loss is given as \(\alpha L_D + (1 - \alpha) L_T\), where \(\alpha\) balances the two components.
Distillation loss is given as \(L_D = t^2 \mathrm{KL}(\text{softmax}(S / t)~\|~\text{softmax}(T / t))\), where \(t\) is the temperature parameter.
Task loss is given as mean squared error \(L_T = \text{MSE}(S, Y)\), where \(S\) is the student output and \(Y\) is the ground truth.
| PARAMETER | DESCRIPTION |
|---|---|
alpha
|
Weight for distillation loss vs task loss.
TYPE:
|
temperature
|
Temperature for soft target scaling.
TYPE:
|
shape_matching
|
Method to adapt student outputs to teacher shape.
TYPE:
|
reduce
|
Reduction method.
TYPE:
|
sign
|
Sign multiplier for loss.
TYPE:
|
Examples:
>>> loss_fn = DistillationLoss(alpha=0.7, temperature=4.0)
>>> T = torch.randn(100, 10)
>>> S = torch.randn(100, 10)
>>> target = torch.randn(100, 10)
>>> context = {"T": T, "S": S, "target": target}
>>> loss = loss_fn(context)
| METHOD | DESCRIPTION |
|---|---|
forward |
Compute combined distillation loss and task loss (MSE by default). |
Source code in spectre/loss/distillation.py
Functions#
forward(context: dict, **kwargs) -> torch.Tensor
#
Compute combined distillation loss and task loss (MSE by default).
| PARAMETER | DESCRIPTION |
|---|---|
context
|
Context dictionary containing teacher outputs (
TYPE:
|
**kwargs
|
Additional keyword arguments.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Combined loss. |
Source code in spectre/loss/distillation.py
FeatureMatchingLoss(feature_weight: float = 1.0, shape_matching: Literal['projection', 'padding', 'truncation'] = 'projection', reduce: Literal['sum', 'mean'] = 'mean', sign: float = 1.0, context_prefix: str | None = None)
#
Bases: Loss
Loss for matching intermediate feature representations.
Computes MSE loss between teacher and student feature maps, automatically handling dimension mismatches through projection.
Loss is defined as \(\frac{1}{L} \sum_{i=1}^L \| F_S^{(i)} - F_T^{(i)} \|^2_2\), where \(L\) is the number of feature layers, and \(F_S^{(i)}\) and \(F_T^{(i)}\) are the student and teacher feature maps at layer \(i\).
| PARAMETER | DESCRIPTION |
|---|---|
feature_weight
|
Weight for feature matching loss.
TYPE:
|
shape_matching
|
Method to adapt student outputs to teacher shape.
TYPE:
|
reduce
|
Reduction method.
TYPE:
|
sign
|
Sign multiplier for loss.
TYPE:
|
Examples:
>>> loss_fn = FeatureMatchingLoss(feature_weight=1.0)
>>> T = {"layer1": torch.randn(100, 64), "layer2": torch.randn(100, 128, 8, 8)}
>>> S = {"layer1": torch.randn(100, 32), "layer2": torch.randn(100, 64, 8, 8)}
>>> context = {"T": T, "S": S}
>>> loss = loss_fn(context)
| METHOD | DESCRIPTION |
|---|---|
forward |
Compute feature matching loss between teacher and student features. |
Source code in spectre/loss/distillation.py
Functions#
forward(context: dict, **kwargs) -> torch.Tensor
#
Compute feature matching loss between teacher and student features.
| PARAMETER | DESCRIPTION |
|---|---|
context
|
Dictionary containing:
TYPE:
|
**kwargs
|
Additional keyword arguments.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Feature matching loss. |
Source code in spectre/loss/distillation.py
SpectralPreservationLoss(kernel_fn: Kernel | str = 'gaussian', kernel_kwargs: dict | None = None, distance_fn: PairwiseDistance | str = 'euclidean', distance_kwargs: dict | None = None, eigenvalue_weight: float = 0.5, eigengap_weight: float = 0.5, reduce: Literal['mean', 'sum'] = 'mean', sign: float = 1.0, symmetric_eigendecomposition: bool = True, context_prefix: str | None = None)
#
Bases: Loss
Loss for preserving spectral properties in distillation.
Preserves eigenvalue structures, spectral gaps, and kernel properties when distilling from spectral models.
Spectral preservation loss is given as \(w_{\lambda} L_{\lambda} + w_{\Delta\lambda} L_{\Delta\lambda}\), where \(w_{\lambda}\) and \(w_{\Delta\lambda}\) are weights for eigenvalue matching and spectral gap preservation, respectively.
Eigenvalue loss is computed as MSE between teacher and student eigenvalues.
Spectral gap loss is computed as MSE between differences of consecutive eigenvalues (gaps) of teacher and student.
| PARAMETER | DESCRIPTION |
|---|---|
kernel_fn
|
Kernel function specification.
Available string options:
TYPE:
|
kernel_kwargs
|
Keyword arguments for kernel instantiation when See kernels for available options.
TYPE:
|
distance_fn
|
Distance metric specification.
Available string options:
TYPE:
|
distance_kwargs
|
Keyword arguments for distance instantiation when
TYPE:
|
eigenvalue_weight
|
Weight for eigenvalue matching loss. If 0, eigenvalue loss is not computed.
TYPE:
|
eigengap_weight
|
Weight for spectral gap preservation. If 0, gap loss is not computed.
TYPE:
|
reduce
|
Reduction method. Specifies how the loss is aggregated across samples.
TYPE:
|
sign
|
Sign multiplier for loss. Positive for minimization, negative for maximization.
TYPE:
|
symmetric_eigendecomposition
|
Whether to use symmetric eigendecomposition for eigenvalue matching.
TYPE:
|
Examples:
>>> # With pre-computed eigenvalues
>>> loss_fn = SpectralPreservationLoss(eigenvalue_weight=1.0, eigengap_weight=0.5)
>>> context = {"T_eigenvalues": t_eigvals, "S_eigenvalues": s_eigvals}
>>> loss = loss_fn(context)
>>>
>>> # With custom distance/kernel functions
>>> from spectre.pairwise_distance import pairwise_distance_mahalanobis
>>> from spectre.kernel import t_kernel
>>> loss_fn = SpectralPreservationLoss(
... distance_fn=pairwise_distance_mahalanobis,
... kernel_fn=t_kernel,
... kernel_kwargs={"alpha": 1.0, "beta": 3.0},
... )
>>> context = {"S": student_output, "T": teacher_output}
>>> loss = loss_fn(context)
| METHOD | DESCRIPTION |
|---|---|
forward |
Compute spectral preservation loss. |
Source code in spectre/loss/distillation.py
Functions#
forward(context: dict, **kwargs) -> torch.Tensor
#
Compute spectral preservation loss.
| PARAMETER | DESCRIPTION |
|---|---|
context
|
Dictionary containing either eigenvalues or embeddings:
TYPE:
|
**kwargs
|
Additional keyword arguments.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Spectral preservation loss. |
Source code in spectre/loss/distillation.py
Functions#
distillation_loss(S: torch.Tensor, T: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None, alpha: float = 0.7, temperature: float = 4.0, shape_matching: Literal['projection', 'padding', 'truncation'] = 'projection', reduce: Literal['sum', 'mean'] = 'mean', sign: float = 1.0)
#
Compute combined distillation loss and task loss (MSE by default).
Combines distillation loss (student vs teacher) with task loss (student vs ground truth) with using a weighted combination.
Loss is given as \(\alpha L_D + (1 - \alpha) L_T\), where \(\alpha\) balances the two components.
Distillation loss is given as \(L_D = t^2 \mathrm{KL}(\text{softmax}(S / t)~\|~\text{softmax}(T / t))\), where \(t\) is the temperature parameter.
Task loss is given as mean squared error \(L_T = \text{MSE}(S, Y)\), where \(S\) is the student output and \(Y\) is the ground truth.
| PARAMETER | DESCRIPTION |
|---|---|
S
|
Student model outputs of shape (n_samples, k_features).
TYPE:
|
T
|
Teacher model outputs of shape (n_samples, l_features).
TYPE:
|
weights
|
Sample weights of shape (n_samples,).
TYPE:
|
target
|
Ground truth targets of shape (n_samples,).
TYPE:
|
alpha
|
Weight for distillation loss vs task loss.
TYPE:
|
temperature
|
Temperature for soft target scaling.
TYPE:
|
shape_matching
|
Method to adapt student outputs to teacher shape.
TYPE:
|
reduce
|
Reduction method.
TYPE:
|
sign
|
Sign multiplier for loss.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Distillation loss. |
Examples:
Source code in spectre/loss/distillation.py
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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
feature_matching_loss(S: torch.Tensor, T: torch.Tensor, weights: torch.Tensor | None = None, feature_weight: float = 1.0, shape_matching: Literal['projection', 'padding', 'truncation'] = 'projection', reduce: Literal['sum', 'mean'] = 'mean', sign: float = 1.0)
#
Compute feature matching loss between teacher and student features.
Computes MSE loss between teacher and student feature maps, automatically handling dimension mismatches through projection.
Loss is defined as \(\frac{1}{L} \sum_{i=1}^L \| F_S^{(i)} - F_T^{(i)} \|^2_2\), where \(L\) is the number of feature layers, and \(F_S^{(i)}\) and \(F_T^{(i)}\) are the student and teacher feature maps at layer \(i\).
| PARAMETER | DESCRIPTION |
|---|---|
S
|
Student feature dict with layer names as keys and tensors as values.
TYPE:
|
T
|
Teacher feature dict with layer names as keys and tensors as values.
TYPE:
|
weights
|
Sample weights of shape (n_samples,).
TYPE:
|
feature_weight
|
Weight for feature matching loss.
TYPE:
|
shape_matching
|
Method to adapt student outputs to teacher shape.
TYPE:
|
reduce
|
Reduction method.
TYPE:
|
sign
|
Sign multiplier for loss.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Feature matching loss. |
Examples:
Source code in spectre/loss/distillation.py
372 373 374 375 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 | |
spectral_preservation_loss(*, S: torch.Tensor | None = None, T: torch.Tensor | None = None, S_eigenvalues: torch.Tensor | None = None, T_eigenvalues: torch.Tensor | None = None, distance_fn: PairwiseDistance, kernel_fn: Kernel, weights: torch.Tensor | None = None, eigenvalue_weight: float = 1.0, eigengap_weight: float = 0.5, reduce: Literal['mean', 'sum'] = 'mean', sign: float = 1.0, symmetric_eigendecomposition: bool = True)
#
Loss for preserving spectral properties in distillation.
Preserves eigenvalue structures, spectral gaps, and kernel properties when distilling from spectral models.
Spectral preservation loss is given as \(w_{\lambda} L_{\lambda} + w_{\Delta\lambda} L_{\Delta\lambda}\), where \(w_{\lambda}\) and \(w_{\Delta\lambda}\) are weights for eigenvalue matching and spectral gap preservation, respectively.
Eigenvalue loss is computed as MSE between teacher and student eigenvalues.
Spectral gap loss is computed as MSE between differences of consecutive eigenvalues (gaps) of teacher and student.
| PARAMETER | DESCRIPTION |
|---|---|
S
|
Student output of shape (n_samples, k_features). Required if eigenvalues not provided.
TYPE:
|
T
|
Teacher output of shape (n_samples, l_features). Required if eigenvalues not provided.
TYPE:
|
S_eigenvalues
|
Pre-computed student eigenvalues. If provided, eigenvalues are ignored.
TYPE:
|
T_eigenvalues
|
Pre-computed teacher eigenvalues. If provided, eigenvalues are ignored.
TYPE:
|
distance_fn
|
Pairwise distance function.
TYPE:
|
kernel_fn
|
Kernel function.
TYPE:
|
weights
|
Sample weights of shape (n_samples,).
TYPE:
|
eigenvalue_weight
|
Weight for eigenvalue matching loss. If 0, eigenvalue loss is not computed.
TYPE:
|
eigengap_weight
|
Weight for spectral gap preservation. If 0, gap loss is not computed.
TYPE:
|
reduce
|
Reduction method. Specifies how the loss is aggregated across eigenvalues.
TYPE:
|
sign
|
Sign multiplier for loss. Positive for minimization, negative for maximization.
TYPE:
|
symmetric_eigendecomposition
|
Whether to use symmetric eigendecomposition for eigenvalue matching.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Spectral preservation loss. |
Examples:
>>> # With pre-computed eigenvalues
>>> loss = spectral_preservation_loss(
... T_eigenvalues=t_eigvals,
... S_eigenvalues=s_eigvals,
... eigenvalue_weight=1.0,
... eigengap_weight=0.5,
... )
>>>
>>> # With embeddings and default distance/kernel
>>> loss = spectral_preservation_loss(
... S=student_output,
... T=teacher_output,
... eigenvalue_weight=1.0,
... eigengap_weight=0.5,
... )
>>>
>>> # With custom distance/kernel functions
>>> from spectre.pairwise_distance import pairwise_distance_mahalanobis
>>> from spectre.kernel import t_kernel
>>> loss = spectral_preservation_loss(
... S=student_output,
... T=teacher_output,
... distance_fn=pairwise_distance_mahalanobis,
... kernel_fn=t_kernel,
... kernel_kwargs={"alpha": 1.0, "beta": 3.0},
... )
Source code in spectre/loss/distillation.py
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 680 681 682 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 806 807 | |
match_shape(S: torch.Tensor, T: torch.Tensor, method: str = 'projection') -> torch.Tensor
#
Match dimensions between student and teacher tensors (2D only).
- Learnable adaptation: Creates a linear layer that can be trained
- Preserves information: Projects high-dimensional features to lower dimensions
- Bidirectional: Works whether student is smaller or larger than teacher
- Compatible with backprop: Gradients flow through the projection layer
| PARAMETER | DESCRIPTION |
|---|---|
S
|
Student model output (n_samples, n_features).
TYPE:
|
T
|
Teacher model output (n_samples, n_features).
TYPE:
|
method
|
Method for dimension matching ('projection', 'padding', 'truncation').
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Student tensor adapted to teacher dimensions. |
Examples:
>>> S = torch.randn(100, 32) # Student output
>>> T = torch.randn(100, 64) # Teacher output
>>> S_matched = match_shape(S, T, method="projection") # S adapted to T's shape
>>> S_matched.shape
torch.Size([100, 64])