python
import torch
import torch.nn as nn
import torch.nn.utils.prune as prune
model = nn.Sequential(
nn.Conv2d(3, 16, 3, padding=1), nn.ReLU(),
nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(),
nn.AdaptiveAvgPool2d(1), nn.Flatten(),
nn.Linear(32, 10),
)
# 1. 非構造化:1 つの層の重みのうち、絶対値(L1)の小さい 30% を 0 にする
# amount は 0〜1 の小数なら割合、整数なら消す個数
prune.l1_unstructured(model[2], name="weight", amount=0.3)
print(hasattr(model[2], "weight_orig"), hasattr(model[2], "weight_mask")) # True True
# 2. 構造化:出力チャネル(dim=0)ごとに L2 ノルム(n=2)を測り、小さい 50% を 0 にする
# 0 になるだけで、行列の形(出力チャネルの数)は変わらない
prune.ln_structured(model[0], name="weight", amount=0.5, n=2, dim=0)
# 3. 大域:複数の層をまとめて比べ、全体で 20% を消す(層ごとに消える割合は変わる)
params = [(model[2], "weight"), (model[6], "weight")]
prune.global_unstructured(params, pruning_method=prune.L1Unstructured, amount=0.2)
def sparsity(t):
return float((t == 0).sum()) / t.numel()
print(f"conv2 のスパース率: {sparsity(model[2].weight):.2f}")
# 4. 枝刈りとファインチューニングを繰り返す(Han ら 2015 の考え方)
def prune_and_finetune(model, train_step, rounds=3, amount=0.2):
layers = [(m, "weight") for m in model.modules() if isinstance(m, (nn.Conv2d, nn.Linear))]
for _ in range(rounds):
# 同じ重みに何度掛けても、マスクは掛け合わされる(残った重みの 20% ずつ消える)
prune.global_unstructured(layers, pruning_method=prune.L1Unstructured, amount=amount)
model.train()
train_step(model) # 残った重みで精度を取り戻す(消した重みの勾配はマスクで 0 になる)
return model
# 5. 枝刈りを確定する:weight_orig と weight_mask を消し、0 を含む weight だけを残す
for m, name in params:
prune.remove(m, name)
print(sorted(n for n, _ in model[2].named_parameters())) # ['bias', 'weight'](weight_orig は消える)