channel_pruner
shrinkai.compression.pruning.channel_pruner
Physical (dependency-aware) structured channel pruning.
Unlike Pruner (which only zeroes out weights via torch.nn.utils.prune masks,
without changing tensor shapes or producing real latency/FLOPs gains), ChannelPruner
actually rebuilds smaller Conv2d/Linear (and dependent BatchNorm) layers with the
pruned channels physically removed.
Determining which layers can be safely shrunk together requires knowing the model's
real dataflow graph, removing a layer's output channels is only valid if every
downstream consumer of that output has its input channels shrunk to match. This module
uses torch.fx to trace that graph and torch.fx.passes.shape_prop.ShapeProp to know
each node's actual tensor shape.
Scope (by design, to stay correct rather than merely "not crashing"):
- Supports simple, non-branching chains: a targeted Conv2d/Linear layer whose
output feeds, without branching (exactly one consumer at every hop), through any
number of BatchNorm/activation/pooling/dropout layers, into either another
Conv2d/Linear layer or the model's final output.
- A flatten/view/reshape between a 4D conv-style tensor and a Linear layer is only
allowed once the spatial dimensions have already been reduced to 1x1 (e.g. by
AdaptiveAvgPool2d(1)). At that point each channel maps to exactly one flattened
feature, so no interleaving ambiguity exists.
- Grouped/depthwise convolutions (groups != 1) are rejected: removing channels
from a grouped conv can change which input channels feed which output channels,
which this implementation does not attempt to resolve.
- Any branching topology (residual/skip connections, concatenation, attention,
multiple consumers of the same tensor) is rejected with a clear error rather than
silently producing an incorrect model. For those architectures, use Pruner
(mask-based, safe on any topology, but without physical shrinkage) instead.
Classes:
| Name | Description |
|---|---|
ChannelPruner |
Physically removes pruned output channels from |
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 |