🤖 AI/ML

Model Pruning

Model Pruning

A model compression technique that removes unnecessary connections (weights) to reduce size and computation. Key to mobile/edge deployment and faster inference.

📖 Detailed Explanation

Model Pruning is a technique that makes a model lighter by removing weights or neurons of low importance from a neural network. Just as unnecessary branches of a tree are trimmed, removing connections that do not greatly affect performance can reduce model size by 50-90% while keeping accuracy loss within 1-2%.

Research on pruning began in the 1990s with the "Optimal Brain Damage" paper, and it has drawn renewed attention in the deep learning era as the efficient deployment of large-scale models has become important. In particular, with the emergence of LLMs and Vision Transformers causing model sizes to surge, the need for pruning has grown even greater.

Pruning methods are broadly divided into Unstructured and Structured. Unstructured pruning sets individual weights to 0 to create a sparse matrix, while Structured pruning removes whole structural units such as entire filters, channels, and attention heads. Structured pruning is more effective for actual speedup, but Unstructured pruning achieves a higher compression ratio.

In practice, pruning is essential for deployment on mobile/edge devices, reducing inference costs, and services that require real-time responses. PyTorch's torch.nn.utils.prune, the TensorFlow Model Optimization Toolkit, and NVIDIA's ASP (Automatic Sparsity) support pruning, and recently, LLM-specific pruning techniques such as SparseGPT and Wanda are also being actively researched.

Pruning MethodsCompression RatioSpeedupPros and Cons
Unstructured90-95%Limited (hardware-dependent)High compression, requires sparse matrix operations
Structured (filters/channels)50-70%2-4xActual speedup on general-purpose hardware
Semi-structured (2:4)50%2x (A100+)Optimized for NVIDIA Ampere+ GPUs
LLM Pruning (SparseGPT)50-60%1.5-2xOne-shot pruning, no retraining required

💻 Code Example

# PyTorch 모델 프루닝 예제
import torch
import torch.nn as nn
import torch.nn.utils.prune as prune

# 1. 간단한 모델 정의
class SimpleCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 64, 3, padding=1)
        self.conv2 = nn.Conv2d(64, 128, 3, padding=1)
        self.fc = nn.Linear(128 * 8 * 8, 10)

    def forward(self, x):
        x = torch.relu(self.conv1(x))
        x = torch.max_pool2d(x, 2)
        x = torch.relu(self.conv2(x))
        x = torch.max_pool2d(x, 2)
        x = x.view(x.size(0), -1)
        return self.fc(x)

model = SimpleCNN()

# 2. Unstructured Pruning (L1 크기 기준)
# Conv 레이어의 30% 가중치를 0으로
prune.l1_unstructured(model.conv1, name='weight', amount=0.3)
prune.l1_unstructured(model.conv2, name='weight', amount=0.3)

# 프루닝 상태 확인
print(f"conv1 희소성: {100 * float(torch.sum(model.conv1.weight == 0)) / model.conv1.weight.nelement():.1f}%")

# 3. Structured Pruning (전체 필터 제거)
# 중요도 낮은 필터 20% 제거
prune.ln_structured(model.conv2, name='weight', amount=0.2, n=2, dim=0)

# 4. 글로벌 프루닝 (모델 전체에서 가장 작은 가중치 제거)
parameters_to_prune = [
    (model.conv1, 'weight'),
    (model.conv2, 'weight'),
    (model.fc, 'weight'),
]
prune.global_unstructured(
    parameters_to_prune,
    pruning_method=prune.L1Unstructured,
    amount=0.4,  # 전체 가중치의 40% 제거
)

# 5. 프루닝 영구 적용 (마스크를 실제 가중치에 반영)
for module, name in parameters_to_prune:
    prune.remove(module, name)

# 6. 모델 크기 비교
def count_parameters(model):
    return sum(p.numel() for p in model.parameters())

def count_nonzero(model):
    return sum((p != 0).sum().item() for p in model.parameters())

total = count_parameters(model)
nonzero = count_nonzero(model)
print(f"총 파라미터: {total:,}")
print(f"0이 아닌 파라미터: {nonzero:,}")
print(f"희소성: {100 * (1 - nonzero/total):.1f}%")

# 7. Fine-tuning (프루닝 후 성능 복구)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
criterion = nn.CrossEntropyLoss()

# 간단한 학습 루프 (실제로는 데이터로더 사용)
# for epoch in range(5):
#     for x, y in dataloader:
#         optimizer.zero_grad()
#         loss = criterion(model(x), y)
#         loss.backward()
#         optimizer.step()

# 8. 희소 모델 저장
torch.save(model.state_dict(), "pruned_model.pt")
print("프루닝된 모델 저장 완료!")

# ===== NVIDIA 2:4 Semi-structured Sparsity =====
# A100 GPU 이상에서 2배 속도 향상
from torch.sparse import to_sparse_semi_structured, SparseSemiStructuredTensor

# 2:4 패턴: 4개 원소 중 2개가 0
# NVIDIA Ampere+ GPU에서 하드웨어 가속 지원
# sparse_weight = to_sparse_semi_structured(dense_weight)

🗣️ Say It Like This in Practice

💬 In a Model Optimization Meeting
"I tried pruning ResNet50 for mobile deployment, and removing 50% of the filters with Structured Pruning made it 2x faster, with accuracy dropping by only 1.5%. With 5 epochs of fine-tuning, it recovers up to 99% of the original performance."
💬 In an Interview
"Pruning is a model compression technique that removes weights of low importance. Unstructured pruning sets individual weights to 0 to achieve a high compression ratio but requires sparse matrix operations, while Structured pruning removes entire filters/channels, enabling actual speedup even on general-purpose hardware. After pruning, performance is recovered through fine-tuning."
💬 In a Technical Discussion
"For LLM pruning, SparseGPT or Wanda are good. Even with one-shot 50% pruning without retraining, the perplexity loss is small, and combining it with quantization can reduce model size by more than 10x. With an A100, you can also get hardware acceleration through 2:4 sparsity."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Unstructured Pruning = Misconception of Automatic Speedup

Simply setting weights to 0 does not actually improve speed. Hardware/libraries that support sparse matrix operations are required.

❌
Skipping Fine-tuning After Excessive Pruning

Pruning more than 50% significantly degrades performance. Be sure to recover performance with fine-tuning, and increase the pruning ratio gradually.

✅
Correct Approach: Combine with Quantization

Combining pruning (50%) with quantization (INT8/INT4) can reduce model size by 10-20x. Repeating gradual pruning → fine-tuning with iterative pruning makes it possible to maintain performance even at high compression ratios.

🔗 Related Terms

📚 Learn More