distillation
shrinkai.distillation
Knowledge distillation: training a small student model to mimic a larger teacher.
Distiller is the high-level facade most users start from: give it a teacher,
a student, and a loss (shrinkai.distillation.losses), and it handles the
training loop (fit), evaluation, benchmarking, checkpointing, and deployment
export. DistillationEngine is the lower-level training loop it delegates to
(device management, mixed precision, gradient clipping, teacher freezing, ...),
usable directly for custom orchestration. EarlyStopping/ModelCheckpoint are
ready-to-use fit(callbacks=[...]) callbacks.
Modules:
| Name | Description |
|---|---|
callbacks |
Ready-to-use training callbacks for |
distiller |
|
engine |
|
losses |
Knowledge Distillation loss functions. |
Classes:
| Name | Description |
|---|---|
DistillationEngine |
Generic training engine for knowledge distillation across hardware targets. |
Distiller |
Unified, high-level facade for end-to-end knowledge distillation and benchmarking. |
EarlyStopping |
Stops training when a monitored metric has stopped improving. |
ModelCheckpoint |
Saves a model's weights to disk during training. |
Classes
DistillationEngine
Generic training engine for knowledge distillation across hardware targets.
Handles training/validation loops, accelerator management (MPS, CUDA, CPU), teacher state freezing, and metrics tracking.
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the DistillationEngine. |
evaluate |
Evaluates student performance on validation/test data. |
fit |
Executes the full distillation training loop. |
train_epoch |
Runs a single training epoch over the provided dataloader. |
Source code in src/shrinkai/distillation/engine.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 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 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 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 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 | |
Methods:
__init__
__init__(
student: Module,
teacher: Module,
criterion: BaseDistillationLoss,
optimizer: Optimizer,
device: device | str = "auto",
scheduler: _LRScheduler | None = None,
use_amp: bool = False,
grad_clip_norm: float | None = None,
) -> None
Initializes the DistillationEngine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
student
|
Module
|
Student neural network module to train. |
required |
teacher
|
Module
|
Pre-trained Teacher neural network module providing soft targets. |
required |
criterion
|
BaseDistillationLoss
|
Loss function adhering to |
required |
optimizer
|
Optimizer
|
PyTorch optimizer targeting student parameters. |
required |
device
|
device | str
|
Computing device ('auto', 'mps', 'cuda', 'cpu' or torch.device). |
'auto'
|
scheduler
|
_LRScheduler | None
|
Optional learning rate scheduler updated per epoch. |
None
|
use_amp
|
bool
|
If True, runs the forward passes and loss computation under
mixed precision ( |
False
|
grad_clip_norm
|
float | None
|
If set, clips the student's gradient global L2 norm to this value before each optimizer step. Defaults to None (no clipping). |
None
|
Source code in src/shrinkai/distillation/engine.py
evaluate
Evaluates student performance on validation/test data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataloader
|
DataLoader
|
Validation dataloader yielding (inputs, labels) batches. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
dict[str, float]: Validation metrics (loss, accuracy). |
Source code in src/shrinkai/distillation/engine.py
fit
fit(
train_dataloader: DataLoader,
val_dataloader: DataLoader | None = None,
epochs: int = 10,
callbacks: list[Callable[[int, dict[str, float]], None]]
| None = None,
start_epoch: int = 1,
history: dict[str, list[float]] | None = None,
) -> dict[str, list[float]]
Executes the full distillation training loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_dataloader
|
DataLoader
|
Dataloader containing training dataset. |
required |
val_dataloader
|
DataLoader | None
|
Optional dataloader for epoch-end validation. |
None
|
epochs
|
int
|
Total number of epochs to train up to (1-indexed, inclusive). Defaults to 10. |
10
|
callbacks
|
list[Callable[[int, dict[str, float]], None]] | None
|
Optional list of callback functions triggered each epoch.
A callback exposing a truthy |
None
|
start_epoch
|
int
|
1-based epoch index to resume training from. Defaults to 1
(a fresh run). Used together with |
1
|
history
|
dict[str, list[float]] | None
|
Existing training history to append to, as returned by a
previous call to |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, list[float]]
|
dict[str, list[float]]: Training history tracking loss and metrics, |
dict[str, list[float]]
|
covering both the resumed epochs (if any) and the new ones. |
Source code in src/shrinkai/distillation/engine.py
train_epoch
Runs a single training epoch over the provided dataloader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataloader
|
DataLoader
|
Training dataloader yielding (inputs, labels) batches. |
required |
epoch_idx
|
int
|
Current 1-based epoch index. |
required |
total_epochs
|
int
|
Total number of planned epochs. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
dict[str, float]: Aggregated training metrics (loss, accuracy). |
Source code in src/shrinkai/distillation/engine.py
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 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 | |
Distiller
Unified, high-level facade for end-to-end knowledge distillation and benchmarking.
Examples:
>>> from shrinkai.distillation import Distiller
>>> distiller = Distiller(teacher=teacher_vit, student=student_mobilenet)
>>> distiller.fit(train_loader, val_loader, epochs=5)
>>> distiller.save_student("distilled_student.pt")
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the Distiller. |
benchmark |
Runs complete profiling suite on both models and outputs comparison report. |
evaluate |
Evaluates student performance on a given dataloader. |
export_onnx |
Exports the trained student to ONNX. See |
export_torchscript |
Exports the trained student to TorchScript. See |
feature_analysis |
Evaluates how well the student mimics the teacher's internal hidden states. |
fit |
Trains the student model using knowledge distillation. |
load_checkpoint |
Restores a full training checkpoint saved by |
load_student |
Loads trained weights into the student model. |
save_checkpoint |
Saves a full training checkpoint (student, optimizer, scheduler, history). |
save_student |
Saves trained student model weights to disk. |
Source code in src/shrinkai/distillation/distiller.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 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 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 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 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 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | |
Methods:
__init__
__init__(
teacher: Module,
student: Module,
criterion: BaseDistillationLoss | None = None,
optimizer: Optimizer
| Literal["adam", "adamw", "sgd"] = "adamw",
lr: float = 0.001,
weight_decay: float = 0.0001,
device: device | str = "auto",
scheduler: _LRScheduler | None = None,
use_amp: bool = False,
grad_clip_norm: float | None = None,
engine_class: type[DistillationEngine] | None = None,
) -> None
Initializes the Distiller.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
teacher
|
Module
|
Pre-trained teacher neural network module. |
required |
student
|
Module
|
Target lightweight student neural network module to train. |
required |
criterion
|
BaseDistillationLoss | None
|
Distillation loss adhering to |
None
|
optimizer
|
Optimizer | Literal['adam', 'adamw', 'sgd']
|
PyTorch optimizer or name string ('adam', 'adamw', 'sgd'). Defaults to 'adamw'. |
'adamw'
|
lr
|
float
|
Learning rate applied when creating default optimizer. Defaults to 1e-3. |
0.001
|
weight_decay
|
float
|
Weight decay factor for optimizer. Defaults to 1e-4. |
0.0001
|
device
|
device | str
|
Computing target ('auto', 'mps', 'cuda', 'cpu' or torch.device). Defaults to 'auto'. |
'auto'
|
scheduler
|
_LRScheduler | None
|
Optional learning rate scheduler updated per epoch. |
None
|
use_amp
|
bool
|
If True, trains under mixed precision (fp16+scaling on CUDA, bf16 on CPU/MPS). Defaults to False. |
False
|
grad_clip_norm
|
float | None
|
If set, clips the student's gradient global L2 norm to this value before each optimizer step. Defaults to None. |
None
|
engine_class
|
type[DistillationEngine] | None
|
The engine class for distillation. If None, it uses a basic DistillationEngine. |
None
|
Source code in src/shrinkai/distillation/distiller.py
benchmark
benchmark(
sample_input: Tensor,
teacher_name: str = "Teacher",
student_name: str = "Student",
val_dataloader: DataLoader | None = None,
compute_flops: bool = False,
) -> BenchmarkReport
Runs complete profiling suite on both models and outputs comparison report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_input
|
Tensor
|
Batch tensor matching target inference dimension (e.g., [1, 3, 224, 224]). |
required |
teacher_name
|
str
|
Display label for teacher model. Defaults to "Teacher". |
'Teacher'
|
student_name
|
str
|
Display label for student model. Defaults to "Student". |
'Student'
|
val_dataloader
|
DataLoader | None
|
Optional dataloader to compute final accuracy metrics. |
None
|
compute_flops
|
bool
|
If True, also reports FLOPs per sample for both models.
Defaults to False. See |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
BenchmarkReport |
BenchmarkReport
|
Structured benchmark report ready for |
Source code in src/shrinkai/distillation/distiller.py
evaluate
Evaluates student performance on a given dataloader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataloader
|
DataLoader
|
Dataloader yielding validation/testing batches. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
dict[str, float]: Validation metrics dictionary. |
Source code in src/shrinkai/distillation/distiller.py
export_onnx
Exports the trained student to ONNX. See shrinkai.export.export_onnx.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Destination |
required |
sample_input
|
Tensor | tuple[Tensor, ...]
|
Representative input tensor (or tuple of tensors). |
required |
**kwargs
|
Any
|
Forwarded to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The path the model was exported to. |
Source code in src/shrinkai/distillation/distiller.py
export_torchscript
export_torchscript(
path: str | Path,
sample_input: Tensor | tuple[Tensor, ...] | None = None,
method: Literal["trace", "script"] = "trace",
) -> Path
Exports the trained student to TorchScript. See
shrinkai.export.export_torchscript.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Destination file path. |
required |
sample_input
|
Tensor | tuple[Tensor, ...] | None
|
Required when |
None
|
method
|
Literal['trace', 'script']
|
"trace" (default) or "script". |
'trace'
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The path the model was exported to. |
Source code in src/shrinkai/distillation/distiller.py
feature_analysis
feature_analysis(
dataloader: DataLoader, metrics: list[str] | None = None
) -> FeatureAnalyzerReport
Evaluates how well the student mimics the teacher's internal hidden states.
This requires both the teacher and student models to have been wrapped
with FeatureExtractor prior to initializing the Distiller.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataloader
|
DataLoader
|
Dataloader yielding validation/testing batches. |
required |
metrics
|
list[str] | None
|
List of metrics to compute (e.g., 'cka'). Defaults to ["cka"]. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
FeatureAnalyzerReport |
FeatureAnalyzerReport
|
Structured report ready for |
Raises:
| Type | Description |
|---|---|
ValueError
|
If models are not wrapped with |
Source code in src/shrinkai/distillation/distiller.py
fit
fit(
train_dataloader: DataLoader,
val_dataloader: DataLoader | None = None,
epochs: int = 10,
callbacks: list[Callable[[int, dict[str, float]], None]]
| None = None,
resume: bool = False,
) -> dict[str, list[float]]
Trains the student model using knowledge distillation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_dataloader
|
DataLoader
|
Dataloader yielding training batches. |
required |
val_dataloader
|
DataLoader | None
|
Optional dataloader for evaluation after each epoch. |
None
|
epochs
|
int
|
Total number of epochs to train up to (1-indexed, inclusive). Defaults to 10. |
10
|
callbacks
|
list[Callable[[int, dict[str, float]], None]] | None
|
Optional list of callback functions triggered at epoch end.
A callback exposing a truthy |
None
|
resume
|
bool
|
If True, continues training from |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, list[float]]
|
dict[str, list[float]]: Dictionary tracking history across epochs. Also |
dict[str, list[float]]
|
stored on |
Source code in src/shrinkai/distillation/distiller.py
load_checkpoint
Restores a full training checkpoint saved by save_checkpoint.
After calling this, resume training with fit(..., resume=True), it will
continue from the epoch right after the last one recorded in the restored
history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path of the saved checkpoint. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If this Distiller's scheduler configuration (present vs. absent) does not match the one the checkpoint was saved with. |
Source code in src/shrinkai/distillation/distiller.py
load_student
Loads trained weights into the student model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path of saved state dictionary. |
required |
Source code in src/shrinkai/distillation/distiller.py
save_checkpoint
Saves a full training checkpoint (student, optimizer, scheduler, history).
Unlike save_student, which only persists inference weights, this saves
everything needed to resume training later via load_checkpoint followed by
fit(..., resume=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Destination file path (e.g. 'checkpoints/epoch_10.pt'). |
required |
Source code in src/shrinkai/distillation/distiller.py
save_student
Saves trained student model weights to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Destination file path (e.g. 'models/student.pt'). |
required |
Source code in src/shrinkai/distillation/distiller.py
EarlyStopping
Stops training when a monitored metric has stopped improving.
Attributes:
| Name | Type | Description |
|---|---|---|
stop |
bool
|
Set to True once |
Methods:
| Name | Description |
|---|---|
__call__ |
Updates internal state and sets |
__init__ |
Initializes the EarlyStopping callback. |
Source code in src/shrinkai/distillation/callbacks.py
Methods:
__call__
Updates internal state and sets self.stop if patience is exhausted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epoch
|
int
|
Current 1-based epoch index. |
required |
metrics
|
dict[str, float]
|
Epoch summary dict, as passed by |
required |
Source code in src/shrinkai/distillation/callbacks.py
__init__
__init__(
monitor: str = "val_loss",
patience: int = 5,
mode: Literal["min", "max"] = "min",
min_delta: float = 0.0,
) -> None
Initializes the EarlyStopping callback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
monitor
|
str
|
Metric key to watch in the epoch summary dict (e.g. "val_loss"). |
'val_loss'
|
patience
|
int
|
Number of consecutive non-improving epochs tolerated before training is stopped. |
5
|
mode
|
Literal['min', 'max']
|
"min" if lower values of |
'min'
|
min_delta
|
float
|
Minimum absolute change to qualify as an improvement. |
0.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/shrinkai/distillation/callbacks.py
ModelCheckpoint
Saves a model's weights to disk during training.
Holds a direct reference to the module to save (typically the student), so it
plugs into fit(callbacks=[...]) without changing the existing
(epoch, metrics) -> None callback signature.
Methods:
| Name | Description |
|---|---|
__call__ |
Saves the model's weights, respecting |
__init__ |
Initializes the ModelCheckpoint callback. |
Source code in src/shrinkai/distillation/callbacks.py
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 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 | |
Methods:
__call__
Saves the model's weights, respecting save_best_only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epoch
|
int
|
Current 1-based epoch index. |
required |
metrics
|
dict[str, float]
|
Epoch summary dict, as passed by |
required |
Source code in src/shrinkai/distillation/callbacks.py
__init__
__init__(
model: Module,
filepath: str | Path,
monitor: str = "val_loss",
mode: Literal["min", "max"] = "min",
save_best_only: bool = True,
) -> None
Initializes the ModelCheckpoint callback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The module whose |
required |
filepath
|
str | Path
|
Destination path for the saved weights. |
required |
monitor
|
str
|
Metric key to watch when |
'val_loss'
|
mode
|
Literal['min', 'max']
|
"min" if lower values of |
'min'
|
save_best_only
|
bool
|
If True, only overwrite |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |