features
shrinkai.distillation.losses.features
Feature-based Knowledge Distillation loss functions.
This module provides loss functions designed to operate on the intermediate representations (hidden layers, attention maps, feature maps) of neural networks.
Unlike logit-based distillation which only penalizes the final output, feature distillation forces the student to learn the internal reasoning process and hierarchical representations of the teacher. This is particularly crucial when the teacher is much deeper than the student (e.g., FitNets, TinyBERT).
Available Losses
- FeatureLoss: Aligns standard activations (Conv/Linear) using MSE, L1, or Cosine.
- AttentionMapLoss: Aligns Transformer attention matrices (TinyBERT style).
- GramMatrixLoss: Aligns feature co-occurrences for style/texture transfer.
Note
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 before passing them to these losses.
To deal with, you can use a ProjectedFeatureLoss, it is a solution, but not
necessarily the best one for your problem.
Examples:
>>> from shrinkai.distillation.losses import FeatureLoss
>>> criterion = FeatureLoss(loss_type="mse", normalize=True)
>>> loss = criterion(student_hidden_states, teacher_hidden_states)
Classes:
| Name | Description |
|---|---|
AttentionMapLoss |
Distillation loss for Transformer attention maps. |
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 |
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
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. |