File size: 12,531 Bytes
8b187bb |
1 2 3 4 5 6 7 8 9 10 11 12 13 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 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 |
"""
MiniMind Pruning Toolkit
Structured and unstructured pruning for model compression.
"""
from typing import Optional, Dict, List, Tuple
from pathlib import Path
from dataclasses import dataclass
from enum import Enum
import torch
import torch.nn as nn
import torch.nn.utils.prune as prune
class PruningMethod(Enum):
"""Supported pruning methods."""
MAGNITUDE = "magnitude" # L1 magnitude pruning
STRUCTURED = "structured" # Channel/head pruning
MOVEMENT = "movement" # Movement pruning (requires training)
WANDA = "wanda" # Weights AND Activations
@dataclass
class PruningConfig:
"""Configuration for pruning."""
method: PruningMethod = PruningMethod.MAGNITUDE
sparsity: float = 0.5 # Target sparsity ratio
structured: bool = False # Whether to use structured pruning
prune_heads: bool = True # Prune attention heads
prune_experts: bool = True # Prune MoE experts
prune_ffn: bool = True # Prune FFN neurons
min_heads: int = 2 # Minimum attention heads to keep
min_experts: int = 2 # Minimum experts to keep
class Mind2Pruner:
"""Pruner for MiniMind models."""
def __init__(self, config: Optional[PruningConfig] = None):
self.config = config or PruningConfig()
def prune(
self,
model: nn.Module,
calibration_data: Optional[torch.Tensor] = None,
) -> nn.Module:
"""
Prune the model.
Args:
model: Model to prune
calibration_data: Data for importance estimation
Returns:
Pruned model
"""
if self.config.method == PruningMethod.MAGNITUDE:
return self._magnitude_pruning(model)
elif self.config.method == PruningMethod.STRUCTURED:
return self._structured_pruning(model, calibration_data)
elif self.config.method == PruningMethod.WANDA:
return self._wanda_pruning(model, calibration_data)
else:
raise ValueError(f"Unsupported pruning method: {self.config.method}")
def _magnitude_pruning(self, model: nn.Module) -> nn.Module:
"""Apply unstructured magnitude pruning."""
modules_to_prune = []
for name, module in model.named_modules():
if isinstance(module, nn.Linear):
modules_to_prune.append((module, "weight"))
# Apply global unstructured pruning
prune.global_unstructured(
modules_to_prune,
pruning_method=prune.L1Unstructured,
amount=self.config.sparsity,
)
# Make pruning permanent
for module, _ in modules_to_prune:
prune.remove(module, "weight")
return model
def _structured_pruning(
self,
model: nn.Module,
calibration_data: Optional[torch.Tensor] = None,
) -> nn.Module:
"""Apply structured pruning (channels/heads)."""
# Compute importance scores
importance_scores = self._compute_importance(model, calibration_data)
# Prune attention heads
if self.config.prune_heads:
model = self._prune_attention_heads(model, importance_scores)
# Prune FFN neurons
if self.config.prune_ffn:
model = self._prune_ffn_neurons(model, importance_scores)
# Prune experts
if self.config.prune_experts:
model = self._prune_experts(model, importance_scores)
return model
def _compute_importance(
self,
model: nn.Module,
calibration_data: Optional[torch.Tensor] = None,
) -> Dict[str, torch.Tensor]:
"""Compute importance scores for different components."""
importance = {}
# Head importance (based on output norm)
for name, module in model.named_modules():
if hasattr(module, "num_heads"):
# Use weight magnitude as proxy for importance
q_weight = getattr(module, "q_proj", None)
if q_weight is not None:
weight = q_weight.weight.data
num_heads = module.num_heads
head_dim = weight.shape[0] // num_heads
head_importance = torch.zeros(num_heads)
for h in range(num_heads):
start = h * head_dim
end = (h + 1) * head_dim
head_importance[h] = weight[start:end].norm()
importance[f"{name}.heads"] = head_importance
# FFN neuron importance
for name, module in model.named_modules():
if isinstance(module, nn.Linear) and "gate_proj" in name:
weight = module.weight.data
neuron_importance = weight.norm(dim=1)
importance[f"{name}.neurons"] = neuron_importance
# Expert importance (for MoE)
for name, module in model.named_modules():
if hasattr(module, "experts"):
expert_importance = torch.zeros(len(module.experts))
for i, expert in enumerate(module.experts):
expert_params = sum(p.numel() for p in expert.parameters())
expert_norm = sum(p.data.norm() for p in expert.parameters())
expert_importance[i] = expert_norm / max(1, expert_params)
importance[f"{name}.experts"] = expert_importance
return importance
def _prune_attention_heads(
self,
model: nn.Module,
importance: Dict[str, torch.Tensor],
) -> nn.Module:
"""Prune least important attention heads."""
for name, module in model.named_modules():
if hasattr(module, "num_heads"):
head_key = f"{name}.heads"
if head_key in importance:
scores = importance[head_key]
num_heads = len(scores)
num_prune = int(num_heads * self.config.sparsity)
num_keep = max(self.config.min_heads, num_heads - num_prune)
# Get indices of heads to keep
_, keep_indices = torch.topk(scores, num_keep)
keep_indices = keep_indices.sort()[0]
# Create mask for pruning
head_dim = module.head_dim
mask = torch.zeros(num_heads * head_dim)
for idx in keep_indices:
start = idx * head_dim
end = (idx + 1) * head_dim
mask[start:end] = 1
# Apply mask to Q, K, V, O projections
for proj_name in ["q_proj", "o_proj"]:
proj = getattr(module, proj_name, None)
if proj is not None:
if proj_name == "q_proj":
proj.weight.data *= mask.unsqueeze(1).to(proj.weight.device)
else:
proj.weight.data *= mask.unsqueeze(0).to(proj.weight.device)
return model
def _prune_ffn_neurons(
self,
model: nn.Module,
importance: Dict[str, torch.Tensor],
) -> nn.Module:
"""Prune least important FFN neurons."""
for name, module in model.named_modules():
if isinstance(module, nn.Linear) and "gate_proj" in name:
neuron_key = f"{name}.neurons"
if neuron_key in importance:
scores = importance[neuron_key]
num_neurons = len(scores)
num_prune = int(num_neurons * self.config.sparsity)
num_keep = num_neurons - num_prune
_, keep_indices = torch.topk(scores, num_keep)
# Create neuron mask
mask = torch.zeros(num_neurons)
mask[keep_indices] = 1
# Apply to gate and up projections
module.weight.data *= mask.unsqueeze(1).to(module.weight.device)
return model
def _prune_experts(
self,
model: nn.Module,
importance: Dict[str, torch.Tensor],
) -> nn.Module:
"""Prune least important MoE experts."""
for name, module in model.named_modules():
if hasattr(module, "experts"):
expert_key = f"{name}.experts"
if expert_key in importance:
scores = importance[expert_key]
num_experts = len(scores)
num_prune = int(num_experts * self.config.sparsity)
num_keep = max(self.config.min_experts, num_experts - num_prune)
_, keep_indices = torch.topk(scores, num_keep)
keep_indices = keep_indices.sort()[0].tolist()
# Zero out pruned experts (actual removal requires model restructuring)
for i, expert in enumerate(module.experts):
if i not in keep_indices:
for param in expert.parameters():
param.data.zero_()
print(f"Pruned experts in {name}: keeping {keep_indices}")
return model
def _wanda_pruning(
self,
model: nn.Module,
calibration_data: Optional[torch.Tensor] = None,
) -> nn.Module:
"""
Apply WANDA (Weights AND Activations) pruning.
Combines weight magnitude with activation magnitude.
"""
if calibration_data is None:
print("Warning: WANDA requires calibration data, falling back to magnitude pruning")
return self._magnitude_pruning(model)
model.eval()
activation_norms = {}
# Hook to capture activations
def hook_fn(name):
def hook(module, input, output):
if isinstance(input, tuple):
input = input[0]
activation_norms[name] = input.abs().mean(dim=(0, 1))
return hook
# Register hooks
handles = []
for name, module in model.named_modules():
if isinstance(module, nn.Linear):
handles.append(module.register_forward_hook(hook_fn(name)))
# Run calibration
with torch.no_grad():
model(calibration_data)
# Remove hooks
for handle in handles:
handle.remove()
# Compute WANDA scores and prune
for name, module in model.named_modules():
if isinstance(module, nn.Linear) and name in activation_norms:
weight = module.weight.data
act_norm = activation_norms[name].to(weight.device)
# WANDA score: |W| * |X|
wanda_score = weight.abs() * act_norm.unsqueeze(0)
# Prune based on scores
threshold = torch.quantile(wanda_score.flatten(), self.config.sparsity)
mask = (wanda_score >= threshold).float()
module.weight.data *= mask
return model
def compute_sparsity(self, model: nn.Module) -> Dict[str, float]:
"""Compute actual sparsity of the model."""
total_params = 0
zero_params = 0
layer_sparsity = {}
for name, module in model.named_modules():
if isinstance(module, nn.Linear):
params = module.weight.numel()
zeros = (module.weight == 0).sum().item()
total_params += params
zero_params += zeros
layer_sparsity[name] = zeros / params
return {
"total_sparsity": zero_params / max(1, total_params),
"layer_sparsity": layer_sparsity,
}
def prune_model(
model: nn.Module,
sparsity: float = 0.5,
method: str = "magnitude",
calibration_data: Optional[torch.Tensor] = None,
) -> nn.Module:
"""
Convenience function to prune a model.
Args:
model: Model to prune
sparsity: Target sparsity ratio
method: Pruning method (magnitude, structured, wanda)
calibration_data: Calibration data for importance estimation
Returns:
Pruned model
"""
config = PruningConfig(
method=PruningMethod(method),
sparsity=sparsity,
)
pruner = Mind2Pruner(config)
return pruner.prune(model, calibration_data)
|