compression
shrinkai.compression
Model compression: pruning and quantization.
Two independent, composable families of techniques for shrinking a model after (or during) training:
- Pruning (
shrinkai.compression.pruning): induces sparsity (Pruner) or physically removes channels (ChannelPruner). - Quantization (
shrinkai.compression.quantization): reduces numerical precision of weights/activations (Quantizer), via PTQ or QAT.
Both can be combined with shrinkai.distillation (e.g. quantization-aware
training driven by a Distiller) or used standalone on any nn.Module.
Modules:
| Name | Description |
|---|---|
pruning |
Pruning: inducing sparsity or physically shrinking a model. |
quantization |
Quantization: reducing the numerical precision of a model's weights/activations. |
Classes:
| Name | Description |
|---|---|
ChannelPruner |
Physically removes pruned output channels from |
Pruner |
Orchestrates the pruning of PyTorch models to induce sparsity. |
PruningConfig |
Configuration parameters for model pruning. |
QuantConfig |
Configuration parameters for model quantization. |
Quantizer |
Orchestrates the quantization of PyTorch models. |
Classes
ChannelPruner
Physically removes pruned output channels from Conv2d/Linear layers.
See the module docstring for the exact topologies this supports and rejects.
Equation
Output units (rows of the weight tensor) are ranked by their \(L_2\) norm,
following the filter-pruning criterion of Li et al. (2017) (who originally
used the \(L_1\) norm; this implementation uses \(L_2\), matching Pruner's
structured method):
The amount fraction of channels with the smallest norm are removed,
physically, unlike Pruner, whose masking-based criterion is identical
but only zeroes the weights without changing tensor shapes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
float
|
Fraction of output channels/neurons to remove from each targeted layer, ranked by L2-norm (lowest-norm channels removed first). Must be in (0.0, 1.0). Defaults to 0.3. |
0.3
|
Methods:
| Name | Description |
|---|---|
apply |
Physically prunes the given layers, propagating the shrink downstream. |
benchmark |
Compares the original model against the physically pruned one. |
Source code in src/shrinkai/compression/pruning/channel_pruner.py
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 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 455 456 457 458 459 460 461 462 463 464 465 466 | |
Methods:
apply
Physically prunes the given layers, propagating the shrink downstream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The model to prune. Mutated in place (its pruned submodules are replaced) and also returned for convenience. |
required |
target_layers
|
list[str]
|
Names (as in |
required |
sample_input
|
Tensor
|
A representative input tensor, used to trace the model's dataflow graph and determine each node's actual tensor shape. Not used for any weight-affecting computation. |
required |
Returns:
| Type | Description |
|---|---|
Module
|
nn.Module: The same |
Module
|
dependent BatchNorm / downstream layer) physically shrunk. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a target layer does not exist, is not a |
Source code in src/shrinkai/compression/pruning/channel_pruner.py
benchmark
benchmark(
original_model: Module,
pruned_model: Module,
sample_input: Tensor,
original_name: str = "Original (Dense)",
pruned_name: str = "Pruned (Physically Shrunk)",
val_dataloader: DataLoader | None = None,
device: str | device = "cpu",
compute_flops: bool = False,
) -> BenchmarkReport
Compares the original model against the physically pruned one.
Unlike Pruner.benchmark, no .finalize()-style step is needed first:
pruned_model (as returned by .apply()) already has fewer parameters,
so real gains in size, latency, and FLOPs are expected here, not just
theoretical sparsity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_model
|
Module
|
The original, unpruned model. |
required |
pruned_model
|
Module
|
The model returned by |
required |
sample_input
|
Tensor
|
A dummy tensor for latency measurement. |
required |
original_name
|
str
|
Display label for the original model. |
'Original (Dense)'
|
pruned_name
|
str
|
Display label for the pruned model. |
'Pruned (Physically Shrunk)'
|
val_dataloader
|
DataLoader | None
|
Optional dataloader for accuracy comparison. |
None
|
device
|
str | device
|
Device for the benchmark. |
'cpu'
|
compute_flops
|
bool
|
If True, also reports FLOPs per sample for both
models. Safe to enable here (unlike for |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
BenchmarkReport |
BenchmarkReport
|
Structured benchmark report ready for |
Source code in src/shrinkai/compression/pruning/channel_pruner.py
Pruner
Orchestrates the pruning of PyTorch models to induce sparsity.
The Pruner traverses the model and applies masking to the weights according to the PruningConfig. It seamlessly supports "Pruning-Aware Training" since PyTorch pruning attaches forward pre-hooks to dynamically mask weights during the forward pass, allowing gradient updates on the remaining unpruned weights.
Equation
Both criteria rank elements/channels by an importance score \(s\) and mask
(zero out) the fraction amount with the lowest score:
The structured criterion follows the filter-pruning idea of Li et al.
(2017), who originally ranked filters by their \(L_1\) norm; this
implementation uses PyTorch's torch.nn.utils.prune.ln_structured with
\(n=2\) instead. Neither criterion changes tensor shapes (the pruned
elements/channels stay in memory as zeros). Refer to ChannelPruner for
physical channel removal using the same \(L_2\) criterion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PruningConfig
|
The configuration object defining the pruning rules. |
required |
Methods:
| Name | Description |
|---|---|
apply |
Applies the selected pruning strategy to the model's target layers. |
benchmark |
Evaluates and compares the performance footprint of the dense vs. pruned model. |
finalize |
Makes the pruning permanent by removing the PyTorch forward hooks and |
Source code in src/shrinkai/compression/pruning/pruning.py
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 | |
Methods:
apply
Applies the selected pruning strategy to the model's target layers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The standard PyTorch model. |
required |
Returns:
| Type | Description |
|---|---|
Module
|
nn.Module: The pruned model (with pruning hooks attached). |
Source code in src/shrinkai/compression/pruning/pruning.py
benchmark
benchmark(
original_model: Module,
pruned_model: Module,
sample_input: Tensor,
original_name: str = "Original (Dense)",
pruned_name: str = "Pruned (Sparse)",
val_dataloader: DataLoader | None = None,
device: str | device = "cpu",
) -> BenchmarkReport
Evaluates and compares the performance footprint of the dense vs. pruned model. Note: True latency gains for unstructured pruning require sparse-tensor supported hardware engines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_model
|
Module
|
The dense baseline model. |
required |
pruned_model
|
Module
|
The pruned model. |
required |
sample_input
|
Tensor
|
A dummy tensor for latency measurement. |
required |
original_name
|
str
|
Display label for baseline. |
'Original (Dense)'
|
pruned_name
|
str
|
Display label for pruned model. |
'Pruned (Sparse)'
|
val_dataloader
|
DataLoader | None
|
Dataloader for accuracy. |
None
|
device
|
str | device
|
Device for the benchmark. |
'cpu'
|
Returns:
| Name | Type | Description |
|---|---|---|
BenchmarkReport |
BenchmarkReport
|
Structured benchmark report ready for |
Source code in src/shrinkai/compression/pruning/pruning.py
finalize
staticmethod
Makes the pruning permanent by removing the PyTorch forward hooks and baking the sparsity mask directly into the weight tensors.
This MUST be called after training/distillation before saving the model for deployment, otherwise the masking overhead slows down inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pruned_model
|
Module
|
The model with pruning hooks attached. |
required |
Returns:
| Type | Description |
|---|---|
Module
|
nn.Module: The permanent, clean sparse model. |
Source code in src/shrinkai/compression/pruning/pruning.py
PruningConfig
dataclass
Configuration parameters for model pruning.
Attributes:
| Name | Type | Description |
|---|---|---|
method |
str
|
The pruning strategy to apply.
- "unstructured": Removes individual weights based on L1-norm (closest to zero).
Creates sparse tensors but doesn't change tensor shapes.
- "structured": Zeroes entire channels/neurons based on their Ln-norm,
via |
amount |
float
|
The fraction of weights/channels to prune. Must be a float between 0.0 and 1.0 (e.g., 0.3 means 30% pruned). Defaults to 0.3. |
target_types |
tuple
|
The PyTorch module types to apply pruning to. Defaults to (nn.Linear, nn.Conv2d). |
Source code in src/shrinkai/compression/pruning/pruning.py
QuantConfig
dataclass
Configuration parameters for model quantization.
This dataclass standardizes how quantization is applied across different backends and strategies. It defines the target bit-width and the mathematical approach used to compress the network.
Attributes:
| Name | Type | Description |
|---|---|---|
target_dtype |
str
|
The target data type for the model's weights. Currently supported options include: - "int8": 8-bit integer (Standard for CPU/Edge deployment). - "fp16": 16-bit float (Standard for GPU memory reduction). Defaults to "int8". |
strategy |
str
|
The quantization strategy to apply.
- "ptq" (Post-Training Quantization): Applies immediate mathematical
conversion to the weights. No gradient computation or training is required.
- "qat" (Quantization-Aware Training): Prepares the model with FakeQuantize
nodes. Requires subsequent training (e.g., via |
backend |
str
|
The underlying engine executing the quantization. - "torch": Native PyTorch quantization (fbgemm/qnnpack). Ideal for CNNs and small LMs. - "bitsandbytes": (Reserved for future LLM integration) Block-wise quantization. Defaults to "torch". |
calibrate_data |
Any | None
|
A dataloader (or any iterable of batches, each
either a plain input tensor or a |
Source code in src/shrinkai/compression/quantization/quantization.py
Quantizer
Orchestrates the quantization of PyTorch models.
The Quantizer reads a QuantConfig and safely modifies the computational graph
of a given PyTorch nn.Module. It handles the complexities of PyTorch's native
quantization APIs.
Equation
PTQ and QAT both rely on the affine (uniform) quantization scheme of Jacob et al. (2018):
where \(s > 0\) (scale) and \(z\) (zero-point) are derived from the observed
range of \(x\), via calibration on calibrate_data for static PTQ
activations, on the fly per-batch for dynamic PTQ, or from weight
statistics directly, and \([q_{min}, q_{max}]\) bounds the target integer
range (e.g. \([-128, 127]\) for int8). PyTorch's default backends use
\(z = 0\) (symmetric) for weights and the full affine form for activations.
For QAT, this same round-trip is simulated in the forward pass ("Fake
Quantization") while gradients flow through it via the straight-through
estimator (\(\partial q / \partial x \approx 1\) inside \([x_{min}, x_{max}]\),
\(0\) outside), letting the model adapt its weights to the quantization
noise before finalize_qat() converts it to real integer weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
QuantConfig
|
The configuration object defining the quantization rules. |
required |
Methods:
| Name | Description |
|---|---|
apply |
Applies the selected quantization strategy to the model. |
benchmark |
Runs complete profiling suite on original and quantized models. |
finalize_qat |
To be called AFTER the distillation training loop (distiller.fit). |
Source code in src/shrinkai/compression/quantization/quantization.py
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 | |
Methods:
apply
Applies the selected quantization strategy to the model.
Depending on config.strategy, this method will either immediately convert
the weights (PTQ) or insert FakeQuantize nodes for future training (QAT).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The standard, full-precision PyTorch model. |
required |
Returns:
| Type | Description |
|---|---|
Module
|
nn.Module: The modified model. If PTQ, it is ready for deployment. |
Module
|
If QAT, it must be trained and then passed to |
Source code in src/shrinkai/compression/quantization/quantization.py
benchmark
benchmark(
original_model: Module,
quantized_model: Module,
sample_input: Tensor,
original_name: str = "Original (FP32)",
quantized_name: str = "Quantized",
val_dataloader: DataLoader | None = None,
device: str | device = "cpu",
) -> BenchmarkReport
Runs complete profiling suite on original and quantized models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_model
|
Module
|
The base FP32 PyTorch model. |
required |
quantized_model
|
Module
|
The model returned by |
required |
sample_input
|
Tensor
|
Batch tensor matching target inference dimension. |
required |
original_name
|
str
|
Display label for the original model. |
'Original (FP32)'
|
quantized_name
|
str
|
Display label for the quantized model. |
'Quantized'
|
val_dataloader
|
DataLoader | None
|
Optional dataloader to compute final accuracy metrics. |
None
|
device
|
str | device
|
Device to run the benchmark on (default "cpu", as INT8 is often CPU-optimized). |
'cpu'
|
Returns:
| Name | Type | Description |
|---|---|---|
BenchmarkReport |
BenchmarkReport
|
Structured benchmark report ready for |
Source code in src/shrinkai/compression/quantization/quantization.py
finalize_qat
staticmethod
To be called AFTER the distillation training loop (distiller.fit). Converts the simulated FakeQuantize nodes into actual quantized weights (e.g., int8).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
qat_model
|
Module
|
The model trained with FakeQuantize nodes. |
required |
Returns:
| Type | Description |
|---|---|
Module
|
nn.Module: The fully quantized model. |