losses
shrinkai.distillation.losses
Knowledge Distillation loss functions.
This module provides a comprehensive suite of loss functions for Knowledge Distillation (KD), structured into three main categories based on where they operate within the neural network:
- Logit-based Distillation (Response-based): Operates on the final output logits. By applying temperature scaling, these functions transfer the "dark knowledge" of the teacher (relative probabilities assigned to non-target classes) to the student, improving its generalization capabilities.
-
Available Losses:
HintonLoss,PureKDLoss,ReverseKLLoss,BCEKDLoss,JSDLoss. -
Feature-based Distillation: Focuses on aligning intermediate representations (hidden layers, attention maps, Gram matrices). Unlike logit-based KD, this forces the student to learn the internal reasoning process and hierarchical representations of the teacher.
-
Available Losses:
FeatureLoss,AttentionMapLoss,GramMatrixLoss. -
Wrappers & Composition: Orchestration modules that do not compute mathematical distances themselves. Instead, they handle tensor dimension mapping (projection) and combine multiple distillation objectives into a single criterion.
- Available Losses:
ProjectedFeatureLoss,HybridLoss,CombinedLoss.
Note on Dimension Alignment: When using feature-based methods, feature dimensions often differ between student and teacher models. It is the user's responsibility to apply a projection layer (e.g., a 1x1 Conv or a Linear layer) to the student's features. You can use the
ProjectedFeatureLosswrapper to automate this, though a custom manual projection might sometimes be preferable depending on your architecture.
Modules:
| Name | Description |
|---|---|
base |
Base class for Knowledge Distillation loss functions. |
features |
Feature-based Knowledge Distillation loss functions. |
logits |
Logit-based Knowledge Distillation loss functions. |
wrappers |
Wrapper modules for composing and routing distillation losses. |
Classes:
| Name | Description |
|---|---|
AttentionMapLoss |
Distillation loss for Transformer attention maps. |
BCEKDLoss |
Knowledge Distillation loss for Multi-Label classification tasks. |
BaseDistillationLoss |
Abstract base class for all distillation loss functions. |
CombinedLoss |
Combines an arbitrary number of distillation losses with specific weights. |
FeatureLoss |
Computes the loss between intermediate feature maps of the Teacher and Student |
GramMatrixLoss |
Distillation loss based on Gram Matrices for style and texture transfer |
HintonLoss |
Knowledge Distillation loss (Geoffrey Hinton et al. (2015)). |
HybridLoss |
Combines a primary logit-based loss and a feature-based loss using a convex combination. |
JSDLoss |
Jensen-Shannon Divergence (JSD) loss for Knowledge Distillation. |
ProjectedFeatureLoss |
Bridge between FeatureExtractors, FeatureProjectors, and Feature Losses. |
PureKDLoss |
Pure Knowledge Distillation loss. |
ReverseKLLoss |
Reverse Kullback-Leibler divergence for Knowledge Distillation (Gu et al. (2024), |
Classes
AttentionMapLoss
Bases: BaseDistillationLoss
Distillation loss for Transformer attention maps.
This loss forces the student model to mimic the attention patterns of the teacher. It operates on attention matrices, typically of shape: [Batch, Num_Heads, Seq_Len, Seq_Len].
Equation
TinyBERT applies MSE directly on the unnormalized attention scores (before softmax); MiniLM instead matches the softmax-normalized attention distributions via KL divergence, with the teacher as the reference distribution. Note: DistilBERT (Sanh et al. (2019)) is often mentioned alongside these, but its own distillation objective operates on the output logits and last hidden state, not on attention maps.
Attributes:
| Name | Type | Description |
|---|---|---|
loss_type |
str
|
The metric to use ('mse' or 'kl'). |
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the AttentionMapLoss. |
forward |
Computes the attention map distillation loss. |
Source code in src/shrinkai/distillation/losses/features.py
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 220 221 | |
Methods:
__init__
Initializes the AttentionMapLoss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss_type
|
Literal['mse', 'kl']
|
Distance metric ('mse' or 'kl'). Defaults to 'mse'. If 'kl' is used, inputs must be unnormalized logits (before softmax), and the KL divergence will be applied across the last dimension. |
'mse'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unsupported |
Source code in src/shrinkai/distillation/losses/features.py
forward
forward(
student_outputs: Tensor | dict[str, Tensor],
teacher_outputs: Tensor | dict[str, Tensor],
labels: Tensor | None = None,
) -> torch.Tensor
Computes the attention map distillation loss.
Supports comparing single tensors or dictionaries of tensors. If dictionaries are provided, it computes the average loss across all matching keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
student_outputs
|
Tensor | dict[str, Tensor]
|
Tensor or dict of attention matrices from the student. |
required |
teacher_outputs
|
Tensor | dict[str, Tensor]
|
Tensor or dict of attention matrices from the teacher. |
required |
labels
|
Tensor | None
|
Ground-truth labels (ignored, kept for API compatibility). |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Aggregated scalar loss value. |
Source code in src/shrinkai/distillation/losses/features.py
BCEKDLoss
Bases: BaseDistillationLoss
Knowledge Distillation loss for Multi-Label classification tasks.
Unlike HintonLoss which uses Softmax (classes are mutually exclusive), this loss uses Sigmoid to treat each class independently. It computes the Binary Cross Entropy (BCE) between the student's logits and the teacher's softened targets.
Equation
Attributes:
| Name | Type | Description |
|---|---|---|
temperature |
float
|
Softening factor for logits. Must be > 0. |
alpha |
float
|
Weight balancing factor. Must be in range [0.0, 1.0]. |
Methods:
| Name | Description |
|---|---|
forward |
Computes combined hard BCE and soft BCE losses. |
Source code in src/shrinkai/distillation/losses/logits.py
Methods:
forward
forward(
student_outputs: Tensor,
teacher_outputs: Tensor,
labels: Tensor | None = None,
) -> torch.Tensor
Computes combined hard BCE and soft BCE losses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
student_outputs
|
Tensor
|
Raw unnormalized logits from the student model (Shape: [B, C] or [B, S, C]). |
required |
teacher_outputs
|
Tensor
|
Raw unnormalized logits from the teacher model (Shape: [B, C] or [B, S, C]). |
required |
labels
|
Tensor | None
|
Ground-truth labels (ignored, kept for API compatibility). |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Scalar loss value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes of |
Source code in src/shrinkai/distillation/losses/logits.py
BaseDistillationLoss
Bases: Module, ABC
Abstract base class for all distillation loss functions.
All concrete implementations must override the forward method.
Methods:
| Name | Description |
|---|---|
forward |
Computes the distillation loss. |
Source code in src/shrinkai/distillation/losses/base.py
Methods:
forward
abstractmethod
forward(
student_outputs: Tensor | dict[str, Tensor],
teacher_outputs: Tensor | dict[str, Tensor],
labels: Tensor | None = None,
) -> torch.Tensor
Computes the distillation loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
student_outputs
|
Tensor | dict[str, Tensor]
|
Output tensor (or dict of activations) from the student model. |
required |
teacher_outputs
|
Tensor | dict[str, Tensor]
|
Output tensor (or dict of activations) from the teacher model. |
required |
labels
|
Tensor | None
|
Ground-truth task labels (optional depending on the loss type). |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Scalar loss tensor for backpropagation. |
Source code in src/shrinkai/distillation/losses/base.py
CombinedLoss
Bases: BaseDistillationLoss
Combines an arbitrary number of distillation losses with specific weights.
This acts as a transparent router. It passes the raw inputs (whether they are tensors or tuples) to each underlying loss.
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the CombinedLoss. |
forward |
Computes the weighted sum of all configured losses. |
Source code in src/shrinkai/distillation/losses/wrappers.py
Methods:
__init__
Initializes the CombinedLoss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weighted_losses
|
list[tuple[BaseDistillationLoss, float]]
|
A list of tuple with instantiated loss modules and their corresponding weights. |
required |
Source code in src/shrinkai/distillation/losses/wrappers.py
forward
forward(
student_outputs: Any,
teacher_outputs: Any,
labels: Tensor | None = None,
) -> torch.Tensor
Computes the weighted sum of all configured losses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
student_outputs
|
Any
|
Tuple of (student_logits, student_features_dict). |
required |
teacher_outputs
|
Any
|
Tuple of (teacher_logits, teacher_features_dict). |
required |
labels
|
Tensor | None
|
Ground-truth labels. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Aggregated scalar loss value. |
Source code in src/shrinkai/distillation/losses/wrappers.py
FeatureLoss
Bases: BaseDistillationLoss
Computes the loss between intermediate feature maps of the Teacher and Student (Romero et al. (2015), FitNets).
This loss encourages the Student to mimic the internal representations (activations) of the Teacher. It assumes that the spatial and channel dimensions of the compared features have already been matched.
Equation
where \(\hat{f}_s, \hat{f}_t\) are the (optionally L2-normalized) flattened student and teacher feature tensors. The original FitNets "hint" loss corresponds to the MSE case; L1 and cosine are natural extensions of the same idea.
Attributes:
| Name | Type | Description |
|---|---|---|
loss_type |
str
|
Type of loss to compute ('mse', 'l1', or 'cosine'). |
normalize |
bool
|
If True, L2-normalizes the feature vectors before computing the loss. This is often useful to match the "direction" of features regardless of their magnitude. |
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the FeatureLoss. |
forward |
Computes the feature distillation loss. |
Source code in src/shrinkai/distillation/losses/features.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
Methods:
__init__
Initializes the FeatureLoss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss_type
|
Literal['mse', 'l1', 'cosine']
|
Distance metric to use ('mse', 'l1', or 'cosine'). Defaults to 'mse'. |
'mse'
|
normalize
|
bool
|
Whether to apply L2 normalization to features before comparison. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unsupported |
Source code in src/shrinkai/distillation/losses/features.py
forward
forward(
student_outputs: Tensor | dict[str, Tensor],
teacher_outputs: Tensor | dict[str, Tensor],
labels: Tensor | None = None,
) -> torch.Tensor
Computes the feature distillation loss.
Supports comparing single tensors or dictionaries of tensors. If dictionaries are provided, it computes the average loss across all matching keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
student_outputs
|
Tensor | dict[str, Tensor]
|
Tensor or dict of intermediate feature tensors from the student. |
required |
teacher_outputs
|
Tensor | dict[str, Tensor]
|
Tensor or dict of intermediate feature tensors from the teacher. |
required |
labels
|
Tensor | None
|
Ground-truth labels (ignored, kept for API compatibility). |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Aggregated scalar loss value. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If input types for student and teacher do not match. |
ValueError
|
If dict keys do not match between student and teacher. |
Source code in src/shrinkai/distillation/losses/features.py
GramMatrixLoss
Bases: BaseDistillationLoss
Distillation loss based on Gram Matrices for style and texture transfer (Gatys et al. (2016)).
Instead of forcing the student to match the exact spatial activations of the teacher (which is strict and requires identical spatial dimensions), this loss forces the student to match the channel-wise feature correlations (co-occurrence).
This is highly effective for Generative tasks, Super-Resolution, or making a student network mimic the global "texture" representation of a teacher.
Equation
where \(F \in \mathbb{R}^{C \times N}\) is a feature map flattened over its \(C\) channels and \(N\) spatial (or temporal) locations, \(G \in \mathbb{R}^{C \times C}\) is its Gram matrix of channel-wise correlations, and \(d\) is the configured distance (MSE, L1, or cosine).
Attributes:
| Name | Type | Description |
|---|---|---|
loss_type |
str
|
The distance metric to apply on the Gram matrices ('mse' or 'l1'). |
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the GramMatrixLoss. |
forward |
Computes the Gram matrix distillation loss. |
Source code in src/shrinkai/distillation/losses/features.py
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 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | |
Methods:
__init__
Initializes the GramMatrixLoss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss_type
|
Literal['mse', 'l1', 'cosine']
|
Distance metric ('mse' or 'l1'). Defaults to 'mse'. |
'mse'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unsupported |
Source code in src/shrinkai/distillation/losses/features.py
forward
forward(
student_outputs: Tensor | dict[str, Tensor],
teacher_outputs: Tensor | dict[str, Tensor],
labels: Tensor | None = None,
) -> torch.Tensor
Computes the Gram matrix distillation loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
student_outputs
|
Tensor | dict[str, Tensor]
|
Tensor or dict of intermediate features [B, C, H, W]. |
required |
teacher_outputs
|
Tensor | dict[str, Tensor]
|
Tensor or dict of intermediate features [B, C, H, W]. |
required |
labels
|
Tensor | None
|
Ground-truth labels (ignored, kept for API compatibility). |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Aggregated scalar loss value. |
Source code in src/shrinkai/distillation/losses/features.py
HintonLoss
Bases: BaseDistillationLoss
Knowledge Distillation loss (Geoffrey Hinton et al. (2015)).
Combines standard task loss (Cross-Entropy with hard ground-truth labels) and distillation loss (Kullback-Leibler divergence on softened probabilities produced by a teacher model at a given temperature).
Equation
Attributes:
| Name | Type | Description |
|---|---|---|
temperature |
float
|
Softening factor for logits. Higher values produce smoother probability distributions over classes. Must be > 0. |
alpha |
float
|
Weight balancing factor between hard label loss and distillation loss. Must be in range [0.0, 1.0]. |
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the HintonLoss module. |
forward |
Computes combined Cross-Entropy and KD divergence losses. |
Source code in src/shrinkai/distillation/losses/logits.py
Methods:
__init__
Initializes the HintonLoss module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
temperature
|
float
|
Temperature scaling factor (T > 0). Defaults to 4.0. |
4.0
|
alpha
|
float
|
Weight for distillation loss (0.0 <= alpha <= 1.0). Defaults to 0.5. |
0.5
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/shrinkai/distillation/losses/logits.py
forward
forward(
student_outputs: Tensor,
teacher_outputs: Tensor,
labels: Tensor | None = None,
) -> torch.Tensor
Computes combined Cross-Entropy and KD divergence losses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
student_outputs
|
Tensor
|
Raw unnormalized logits from the student model (Shape: [B, C]). |
required |
teacher_outputs
|
Tensor
|
Raw unnormalized logits from the teacher model (Shape: [B, C]). |
required |
labels
|
Tensor | None
|
Ground-truth class indices (Shape: [B]). Optional if alpha == 1.0. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Weighted scalar loss value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If shapes of |
Source code in src/shrinkai/distillation/losses/logits.py
HybridLoss
Bases: CombinedLoss
Combines a primary logit-based loss and a feature-based loss using a convex combination.
Equation
where \(\lambda = \text{feature_weight}\).
This loss expects the models (or the FeatureExtractor wrapper) to return
a tuple containing (logits, features_dict).
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the HybridLoss. |
Source code in src/shrinkai/distillation/losses/wrappers.py
Methods:
__init__
__init__(
logit_loss: BaseDistillationLoss,
feature_loss: BaseDistillationLoss,
feature_weight: float = 1.0,
convex_weighting: bool = False,
) -> None
Initializes the HybridLoss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logit_loss
|
BaseDistillationLoss
|
Loss applied to the final logits (e.g., a HintonLoss object). |
required |
feature_loss
|
BaseDistillationLoss
|
Loss applied to the intermediate features (e.g., a FeatureLoss object). |
required |
feature_weight
|
float
|
Balancing factor (0.0 <= weight <= 1.0). Defaults to 1. |
1.0
|
convex_weighting
|
bool
|
If True, applies (1-w) to primary loss and (w) to feature loss. If False, strictly adds (w * feature_loss) to primary loss. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/shrinkai/distillation/losses/wrappers.py
JSDLoss
Bases: BaseDistillationLoss
Jensen-Shannon Divergence (JSD) loss for Knowledge Distillation.
JSD is a symmetric and bounded alternative to the standard KL Divergence. It computes the divergence of both distributions from their average distribution M. This boundedness prevents gradient explosion, especially early in training when the student's predictions might diverge heavily from the teacher's.
Equation
Attributes:
| Name | Type | Description |
|---|---|---|
temperature |
float
|
Softening factor for logits. Must be > 0. |
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the JSDLoss module. |
forward |
Computes the JSD between softened student and teacher distributions. |
Source code in src/shrinkai/distillation/losses/logits.py
Methods:
__init__
Initializes the JSDLoss module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
temperature
|
float
|
Softening factor for logits (T > 0). Defaults to 4.0. |
4.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/shrinkai/distillation/losses/logits.py
forward
forward(
student_outputs: Tensor,
teacher_outputs: Tensor,
labels: Tensor | None = None,
) -> torch.Tensor
Computes the JSD between softened student and teacher distributions.
Args: student_outputs: Raw unnormalized logits from the student model (Shape: [B, C] or [B, S, C]). teacher_outputs: Raw unnormalized logits from the teacher model (Shape: [B, C] or [B, S, C]). labels: Ground-truth labels (ignored, kept for API compatibility).
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Scalar loss value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes of |
Source code in src/shrinkai/distillation/losses/logits.py
ProjectedFeatureLoss
Bases: BaseDistillationLoss
Bridge between FeatureExtractors, FeatureProjectors, and Feature Losses.
When using FeatureExtractor, the model outputs a tuple: (logits, features_dict).
However, feature losses (like FeatureLoss, AttentionMapLoss) expect pure
dictionaries or tensors.
This wrapper seamlessly unpacks the tuples, applies the FeatureProjector to
align the student's feature dimensions with the teacher's, and computes the
underlying feature loss.
Attributes:
| Name | Type | Description |
|---|---|---|
projector |
Module
|
The module responsible for projecting student features. |
feature_loss |
BaseDistillationLoss
|
The loss function to apply to the aligned features. |
project_teacher |
bool
|
If False (default), the projector is applied to the student's features to match the teacher's larger dimensions. If True, the projector is applied to the teacher's features to downscale them (e.g., filtering a 12-head teacher down to match a 2-head student in Transformer attention distillation). |
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the ProjectedFeatureLoss. |
forward |
Unpacks outputs, projects features (student or teacher), and computes the loss. |
Source code in src/shrinkai/distillation/losses/wrappers.py
Methods:
__init__
__init__(
projector: Module,
feature_loss: BaseDistillationLoss,
project_teacher: bool = False,
) -> None
Initializes the ProjectedFeatureLoss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
projector
|
Module
|
An instantiated FeatureProjector. |
required |
feature_loss
|
BaseDistillationLoss
|
An instantiated feature distillation loss (e.g., FeatureLoss). |
required |
project_teacher
|
bool
|
Either the projector is applied to the teacher or not. |
False
|
Source code in src/shrinkai/distillation/losses/wrappers.py
forward
forward(
student_outputs: tuple[Tensor, dict[str, Tensor]],
teacher_outputs: tuple[Tensor, dict[str, Tensor]],
labels: Tensor | None = None,
) -> torch.Tensor
Unpacks outputs, projects features (student or teacher), and computes the loss.
Source code in src/shrinkai/distillation/losses/wrappers.py
PureKDLoss
Bases: HintonLoss
Pure Knowledge Distillation loss.
Implement distillation loss (Kullback-Leibler divergence on softened probabilities
produced by a teacher model at a given temperature). In fact, a PureKDLossobject
is just a HintonLoss object with alpha set to 1.
Equation
Attributes:
| Name | Type | Description |
|---|---|---|
temperature |
float
|
Softening factor for logits. Higher values produce smoother probability distributions over classes. Must be > 0. |
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the PureKDLoss module. |
Source code in src/shrinkai/distillation/losses/logits.py
Methods:
__init__
Initializes the PureKDLoss module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
temperature
|
float
|
Temperature scaling factor (T > 0). Defaults to 4.0. |
4.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/shrinkai/distillation/losses/logits.py
ReverseKLLoss
Bases: BaseDistillationLoss
Reverse Kullback-Leibler divergence for Knowledge Distillation (Gu et al. (2024), MiniLLM).
Standard KD (Forward KL) computes KL(P_teacher || P_student), which is "mode-covering". Reverse KL computes KL(P_student || P_teacher), which is "mode-seeking".
For Large Language Models (LLMs), Reverse KL is highly effective because it strongly penalizes the student for assigning high probabilities to tokens that the teacher considers unlikely, thereby reducing hallucinations and degeneration.
Equation
Attributes:
| Name | Type | Description |
|---|---|---|
temperature |
float
|
Softening factor for logits. Must be > 0. Note: In LLM distillation, temperature is often set close to 1.0. |
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the ReverseKLLoss module. |
forward |
Computes the Reverse KL divergence loss. |
Source code in src/shrinkai/distillation/losses/logits.py
Methods:
__init__
Initializes the ReverseKLLoss module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
temperature
|
float
|
Temperature scaling factor (T > 0). Defaults to 1.0. |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/shrinkai/distillation/losses/logits.py
forward
forward(
student_outputs: Tensor,
teacher_outputs: Tensor,
labels: Tensor | None = None,
) -> torch.Tensor
Computes the Reverse KL divergence loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
student_outputs
|
Tensor
|
Raw unnormalized logits from the student model (Shape: [B, C] or [B, S, C]). |
required |
teacher_outputs
|
Tensor
|
Raw unnormalized logits from the teacher model (Shape: [B, C] or [B, S, C]). |
required |
labels
|
Tensor | None
|
Ground-truth labels (ignored, kept for API compatibility). |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Scalar loss value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes of |