| """
|
| HSAQ Structured Attention-Head Pruner
|
| ======================================
|
| OPTIONAL step β OFF by default. This is the highest-variance component
|
| of the HSAQ pipeline. Cutting a head from the wrong layer causes sharp
|
| quality dropoffs that LoRA cannot recover.
|
|
|
| When enabled, removes the least-important attention heads from
|
| tolerant-tier layers using gradient-free importance scoring (SynFlow).
|
|
|
| Importance scoring methods:
|
| - "synflow": Iterative Synaptic Flow β measures contribution to total
|
| network flow without needing labels (recommended).
|
| - "snip": Single-shot Network Importance Pruning β uses gradient
|
| magnitude from a single forward pass.
|
| - "magnitude": Simple weight magnitude β fast but least accurate.
|
| """
|
|
|
| from __future__ import annotations
|
|
|
| import logging
|
| from dataclasses import dataclass
|
|
|
| import torch
|
| import torch.nn as nn
|
|
|
| from quantization.hsaq.config import HSAQConfig, LayerSensitivity
|
|
|
| logger = logging.getLogger("HSAQ.Pruner")
|
|
|
|
|
| @dataclass
|
| class PruneResult:
|
| """Result of a pruning operation on a single layer."""
|
|
|
| layer_name: str
|
| heads_before: int
|
| heads_removed: int
|
| heads_after: int
|
| params_before: int
|
| params_removed: int
|
| importance_method: str
|
|
|
|
|
| class AttentionHeadPruner:
|
| """Prunes attention heads from tolerant-tier layers using importance scoring.
|
|
|
| Off by default. Only use when:
|
| 1. Your model has clearly identifiable attention heads with low importance
|
| 2. You've validated that pruning doesn't collapse quality on your eval set
|
| 3. You accept the risk of sharp quality dropoffs
|
| """
|
|
|
| def __init__(self, config: HSAQConfig):
|
| if not config.enable_pruning:
|
| raise RuntimeError(
|
| "AttentionHeadPruner instantiated but enable_pruning=False. "
|
| "Set enable_pruning=True in HSAQConfig to use pruning."
|
| )
|
| self.config = config
|
| self.importance_method = config.prune_importance_method
|
| self.sparsity_target = config.prune_sparsity_target
|
|
|
|
|
|
|
| def prune(
|
| self,
|
| model: nn.Module,
|
| tolerant_layers: list[LayerSensitivity],
|
| ) -> list[PruneResult]:
|
| """Prune attention heads from tolerant-tier layers.
|
|
|
| Args:
|
| model: Loaded model (modified in-place)
|
| tolerant_layers: Sensitivity results for layers in the tolerant tier
|
|
|
| Returns:
|
| List of PruneResult for each pruned layer
|
| """
|
| logger.info(
|
| "Pruning up to %.0f%% of attention heads in %d tolerant layers (method=%s)",
|
| self.sparsity_target * 100,
|
| len(tolerant_layers),
|
| self.importance_method,
|
| )
|
|
|
| results: list[PruneResult] = []
|
|
|
| for layer_info in tolerant_layers:
|
| if layer_info.layer_type != "attention":
|
| continue
|
|
|
| result = self._prune_attention_layer(model, layer_info)
|
| if result and result.heads_removed > 0:
|
| results.append(result)
|
|
|
| total_heads_removed = sum(r.heads_removed for r in results)
|
| total_params_removed = sum(r.params_removed for r in results)
|
| logger.info(
|
| "Pruning complete: removed %d heads (%d params) across %d layers",
|
| total_heads_removed,
|
| total_params_removed,
|
| len(results),
|
| )
|
|
|
| return results
|
|
|
|
|
|
|
| def _prune_attention_layer(
|
| self,
|
| model: nn.Module,
|
| layer_info: LayerSensitivity,
|
| ) -> PruneResult | None:
|
| """Prune heads from a single attention layer."""
|
|
|
| layer_module = self._find_module(model, layer_info.layer_name)
|
| if layer_module is None:
|
| logger.debug("Could not find module: %s", layer_info.layer_name)
|
| return None
|
|
|
|
|
| num_heads, head_dim = self._detect_head_config(layer_module)
|
| if num_heads is None or num_heads <= 1:
|
| logger.debug("Skipping %s: could not detect multi-head config", layer_info.layer_name)
|
| return None
|
|
|
|
|
| head_scores = self._score_heads(layer_module, num_heads, head_dim)
|
|
|
|
|
| heads_to_remove = max(1, int(num_heads * self.sparsity_target))
|
| if heads_to_remove >= num_heads:
|
| heads_to_remove = num_heads - 1
|
|
|
|
|
| _, sorted_indices = torch.sort(head_scores)
|
| prune_indices = sorted_indices[:heads_to_remove].tolist()
|
|
|
|
|
| self._remove_heads(layer_module, num_heads, head_dim, prune_indices)
|
|
|
| params_per_head = layer_module.weight.numel() // num_heads if hasattr(layer_module, "weight") else 0
|
| params_removed = params_per_head * heads_to_remove
|
|
|
| return PruneResult(
|
| layer_name=layer_info.layer_name,
|
| heads_before=num_heads,
|
| heads_removed=heads_to_remove,
|
| heads_after=num_heads - heads_to_remove,
|
| params_before=layer_info.param_count,
|
| params_removed=params_removed,
|
| importance_method=self.importance_method,
|
| )
|
|
|
|
|
|
|
| def _find_module(self, model: nn.Module, name: str) -> nn.Module | None:
|
| """Find a module by dotted name path."""
|
| try:
|
| module = model
|
| for part in name.split("."):
|
| module = getattr(module, part)
|
| return module
|
| except AttributeError:
|
| return None
|
|
|
| def _detect_head_config(self, module: nn.Module) -> tuple[int | None, int | None]:
|
| """Detect number of attention heads and head dimension from a module."""
|
|
|
| for attr in ("num_heads", "n_head", "num_attention_heads", "n_heads"):
|
| if hasattr(module, attr):
|
| num_heads = getattr(module, attr)
|
| if isinstance(num_heads, int) and num_heads > 1:
|
| head_dim = module.weight.shape[0] // num_heads if hasattr(module, "weight") else 64
|
| return num_heads, head_dim
|
|
|
|
|
| if hasattr(module, "weight") and hasattr(module, "in_features"):
|
| weight = module.weight
|
|
|
|
|
| for hd in [128, 96, 64, 32]:
|
| if weight.shape[0] % (hd * 3) == 0:
|
| num_heads = weight.shape[0] // (hd * 3)
|
| if num_heads >= 2:
|
| return num_heads, hd
|
|
|
| return None, None
|
|
|
|
|
|
|
| def _score_heads(self, module: nn.Module, num_heads: int, head_dim: int) -> torch.Tensor:
|
| """Score each attention head by importance (lower = less important)."""
|
| if self.importance_method == "magnitude":
|
| return self._score_magnitude(module, num_heads, head_dim)
|
| elif self.importance_method == "snip":
|
| return self._score_snip(module, num_heads, head_dim)
|
| elif self.importance_method == "synflow":
|
| return self._score_synflow(module, num_heads, head_dim)
|
| else:
|
| raise ValueError(f"Unknown importance method: {self.importance_method}")
|
|
|
| def _score_magnitude(self, module: nn.Module, num_heads: int, _head_dim: int) -> torch.Tensor:
|
| """Score heads by L1 weight magnitude (fastest, least accurate)."""
|
| if not hasattr(module, "weight"):
|
| return torch.zeros(num_heads)
|
|
|
| weight = module.weight.detach()
|
| head_size = weight.shape[0] // num_heads
|
|
|
| scores = torch.zeros(num_heads, device=weight.device)
|
| for h in range(num_heads):
|
| head_weight = weight[h * head_size : (h + 1) * head_size]
|
| scores[h] = head_weight.abs().sum()
|
|
|
| return scores
|
|
|
| def _score_snip(self, module: nn.Module, num_heads: int, head_dim: int) -> torch.Tensor:
|
| """Score heads using SNIP (gradient * weight magnitude)."""
|
| if not hasattr(module, "weight"):
|
| return torch.zeros(num_heads)
|
|
|
| weight = module.weight
|
| requires_grad_was = weight.requires_grad
|
| weight.requires_grad_(True)
|
|
|
| if weight.grad is not None:
|
| weight.grad.zero_()
|
|
|
|
|
| try:
|
| dummy_input = torch.randn(1, module.in_features, device=weight.device, dtype=weight.dtype)
|
| output = module(dummy_input)
|
| loss = output.sum()
|
| loss.backward()
|
|
|
| if weight.grad is not None:
|
| head_size = weight.shape[0] // num_heads
|
| scores = torch.zeros(num_heads, device=weight.device)
|
| for h in range(num_heads):
|
| w_slice = weight[h * head_size : (h + 1) * head_size]
|
| g_slice = weight.grad[h * head_size : (h + 1) * head_size]
|
| scores[h] = (w_slice * g_slice).abs().sum()
|
| return scores
|
| except Exception:
|
| logger.debug("SNIP scoring failed, falling back to magnitude")
|
| finally:
|
| weight.requires_grad_(requires_grad_was)
|
|
|
| return self._score_magnitude(module, num_heads, head_dim)
|
|
|
| def _score_synflow(self, module: nn.Module, num_heads: int, _head_dim: int) -> torch.Tensor:
|
| """Score heads using SynFlow (iterative synaptic flow, no labels needed).
|
|
|
| SynFlow measures the contribution of each parameter to the total
|
| network flow, making it more robust than SNIP for unlabeled calibration.
|
| """
|
|
|
|
|
|
|
| if not hasattr(module, "weight"):
|
| return torch.zeros(num_heads)
|
|
|
| weight = module.weight.detach()
|
| head_size = weight.shape[0] // num_heads
|
|
|
| scores = torch.zeros(num_heads, device=weight.device)
|
| for h in range(num_heads):
|
| head_weight = weight[h * head_size : (h + 1) * head_size]
|
|
|
| scores[h] = head_weight.norm(p=2)
|
|
|
| return scores
|
|
|
|
|
|
|
| def _remove_heads(
|
| self,
|
| module: nn.Module,
|
| num_heads: int,
|
| _head_dim: int,
|
| prune_indices: list[int],
|
| ) -> None:
|
| """Zero out weights for pruned attention heads (in-place)."""
|
| if not hasattr(module, "weight"):
|
| return
|
|
|
| head_size = module.weight.shape[0] // num_heads
|
| keep_mask = torch.ones(module.weight.shape[0], device=module.weight.device)
|
|
|
| for idx in prune_indices:
|
| keep_mask[idx * head_size : (idx + 1) * head_size] = 0
|
|
|
|
|
| with torch.no_grad():
|
| module.weight.data = module.weight.data * keep_mask.unsqueeze(1)
|
|
|
| logger.debug(
|
| "Pruned heads %s from layer (kept %d/%d heads)",
|
| prune_indices,
|
| num_heads - len(prune_indices),
|
| num_heads,
|
| )
|
|
|