Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Reduce LLM size and accelerate inference using pruning techniques like Wanda and SparseGPT. Use when compressing models without retraining, achieving 50% sparsity with minimal accuracy loss, or enabling faster inference on hardware accelerators. Covers unstructured pruning, structured pruning, N:M sparsity, magnitude pruning, and one-shot methods.
.claude/skills/openlair-model-pruning/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-04 | ✗→✓ | ▲ Improved | 97% | 0% |
| case-14 | ✗→✓ | ▲ Improved | 112% | 0% |
| case-06 | ✓→✗ | ▼ Worse | 176% | 0% |
| case-01 | ✓→✓ | = Same ✓ | 96% | 0% |
| case-02 | ✓→✓ | = Same ✓ | 221% | 0% |
Use Model Pruning when you need to:
Key Techniques: Wanda (weights × activations), SparseGPT (second-order), structured pruning, N:M sparsity
Papers: Wanda ICLR 2024 (arXiv 2306.11695), SparseGPT (arXiv 2301.00774)
bash# Wanda implementation git clone https://github.com/locuslab/wanda cd wanda pip install -r requirements.txt # Optional: SparseGPT git clone https://github.com/IST-DASLab/sparsegpt cd sparsegpt pip install -e . # Dependencies pip install torch transformers accelerate
Source: ICLR 2024 (arXiv 2306.11695)
pythonimport torch from transformers import AutoModelForCausalLM, AutoTokenizer # Load model model = AutoModelForCausalLM.from_pretrained( "meta-llama/Llama-2-7b-hf", torch_dtype=torch.float16, device_map="cuda" ) tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") # Calibration data (small dataset for activation statistics) calib_data = [ "The quick brown fox jumps over the lazy dog.", "Machine learning is transforming the world.", "Artificial intelligence powers modern applications.", ] # Wanda pruning function def wanda_prune(model, calib_data, sparsity=0.5): """ Wanda: Prune by weight magnitude × input activation. Args: sparsity: Fraction of weights to prune (0.5 = 50%) """ # 1. Collect activation statistics activations = {} def hook_fn(name): def hook(module, input, output): # Store input activation norms activations[name] = input[0].detach().abs().mean(dim=0) return hook # Register hooks for all linear layers hooks = [] for name, module in model.named_modules(): if isinstance(module, torch.nn.Linear): hooks.append(module.register_forward_hook(hook_fn(name))) # Run calibration data model.eval() with torch.no_grad(): for text in calib_data: inputs = tokenizer(text, return_tensors="pt").to(model.device) model(**inputs) # Remove hooks for hook in hooks: hook.remove() # 2. Prune weights based on |weight| × activation for name, module in model.named_modules(): if isinstance(module, torch.nn.Linear) and name in activations: W = module.weight.data act = activations[name] # Compute importance: |weight| × activation importance = W.abs() * act.unsqueeze(0) # Flatten and find threshold threshold = torch.quantile(importance.flatten(), sparsity) # Create mask mask = importance >= threshold # Apply mask (prune) W *= mask.float() return model # Apply Wanda pruning (50% sparsity, one-shot, no retraining) pruned_model = wanda_prune(model, calib_data, sparsity=0.5) # Save pruned_model.save_pretrained("./llama-2-7b-wanda-50")
Source: arXiv 2301.00774
pythonfrom sparsegpt import SparseGPT # Load model model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf") # Initialize SparseGPT pruner = SparseGPT(model) # Calibration data calib_data = load_calibration_data() # ~128 samples # Prune (one-shot, layer-wise reconstruction) pruned_model = pruner.prune( calib_data=calib_data, sparsity=0.5, # 50% sparsity prunen=0, # Unstructured (0) or N:M structured prunem=0, percdamp=0.01, # Damping for Hessian inverse ) # Results: Near-lossless pruning at 50% sparsity
pythondef nm_prune(weight, n=2, m=4): """ N:M pruning: Keep N weights per M consecutive weights. Example: 2:4 = keep 2 out of every 4 weights. Compatible with NVIDIA sparse tensor cores (2:4, 4:8). """ # Reshape weight into groups of M shape = weight.shape weight_flat = weight.flatten() # Pad to multiple of M pad_size = (m - weight_flat.numel() % m) % m weight_padded = F.pad(weight_flat, (0, pad_size)) # Reshape into (num_groups, m) weight_grouped = weight_padded.reshape(-1, m) # Find top-N in each group _, indices = torch.topk(weight_grouped.abs(), n, dim=-1) # Create mask mask = torch.zeros_like(weight_grouped) mask.scatter_(1, indices, 1.0) # Apply mask weight_pruned = weight_grouped * mask # Reshape back weight_pruned = weight_pruned.flatten()[:weight_flat.numel()] return weight_pruned.reshape(shape) # Apply 2:4 sparsity (NVIDIA hardware) for name, module in model.named_modules(): if isinstance(module, torch.nn.Linear): module.weight.data = nm_prune(module.weight.data, n=2, m=4) # 50% sparsity, 2× speedup on A100 with sparse tensor cores
Magnitude Pruning (baseline):
python# Prune weights with smallest absolute values importance = weight.abs() threshold = torch.quantile(importance, sparsity) mask = importance >= threshold
Wanda (weights × activations):
python# Importance = |weight| × input_activation importance = weight.abs() * activation # Better than magnitude alone (considers usage)
SparseGPT (second-order):
python# Uses Hessian (second derivative) for importance # More accurate but computationally expensive importance = weight^2 / diag(Hessian)
Unstructured (fine-grained):
Structured (coarse-grained):
Semi-structured (N:M):
python# Unstructured (random) # [1, 0, 1, 0, 1, 1, 0, 0] # Pros: Flexible, high quality # Cons: No speedup # Structured (block) # [1, 1, 0, 0, 1, 1, 0, 0] # Pros: Hardware friendly # Cons: More accuracy loss # N:M (semi-structured) # [1, 0, 1, 0] [1, 1, 0, 0] (2:4 pattern) # Pros: Hardware speedup + good quality # Cons: Requires specific hardware (NVIDIA)
pythondef gradual_prune(model, initial_sparsity=0.0, final_sparsity=0.5, num_steps=100): """Gradually increase sparsity during training.""" for step in range(num_steps): # Current sparsity current_sparsity = initial_sparsity + (final_sparsity - initial_sparsity) * (step / num_steps) # Prune at current sparsity for module in model.modules(): if isinstance(module, torch.nn.Linear): weight = module.weight.data threshold = torch.quantile(weight.abs().flatten(), current_sparsity) mask = weight.abs() >= threshold weight *= mask.float() # Train one step train_step(model) return model
pythondef layer_wise_prune(model, sparsity_per_layer): """Different sparsity for different layers.""" # Early layers: Less pruning (more important) # Late layers: More pruning (less critical) sparsity_schedule = { "layer.0": 0.3, # 30% sparsity "layer.1": 0.4, "layer.2": 0.5, "layer.3": 0.6, # 60% sparsity } for name, module in model.named_modules(): if isinstance(module, torch.nn.Linear): # Find layer index for layer_name, sparsity in sparsity_schedule.items(): if layer_name in name: # Prune at layer-specific sparsity prune_layer(module, sparsity) break return model
pythondef iterative_prune_finetune(model, target_sparsity=0.5, iterations=5): """Prune gradually with fine-tuning between iterations.""" current_sparsity = 0.0 sparsity_increment = target_sparsity / iterations for i in range(iterations): # Increase sparsity current_sparsity += sparsity_increment # Prune prune_model(model, sparsity=current_sparsity) # Fine-tune (recover accuracy) fine_tune(model, epochs=2, lr=1e-5) return model # Results: Better accuracy than one-shot at high sparsity
pythonfrom transformers import Trainer, TrainingArguments def production_pruning_pipeline( model_name="meta-llama/Llama-2-7b-hf", target_sparsity=0.5, method="wanda", # or "sparsegpt" ): # 1. Load model model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16) tokenizer = AutoTokenizer.from_pretrained(model_name) # 2. Load calibration data calib_dataset = load_dataset("wikitext", "wikitext-2-raw-v1", split="train[:1000]") # 3. Apply pruning if method == "wanda": pruned_model = wanda_prune(model, calib_dataset, sparsity=target_sparsity) elif method == "sparsegpt": pruner = SparseGPT(model) pruned_model = pruner.prune(calib_dataset, sparsity=target_sparsity) # 4. (Optional) Fine-tune to recover accuracy training_args = TrainingArguments( output_dir="./pruned-model", num_train_epochs=1, per_device_train_batch_size=4, learning_rate=1e-5, bf16=True, ) trainer = Trainer( model=pruned_model, args=training_args, train_dataset=finetune_dataset, ) trainer.train() # 5. Save pruned_model.save_pretrained("./pruned-llama-7b-50") tokenizer.save_pretrained("./pruned-llama-7b-50") return pruned_model # Usage pruned_model = production_pruning_pipeline( model_name="meta-llama/Llama-2-7b-hf", target_sparsity=0.5, method="wanda" )
pythonfrom lm_eval import evaluator # Evaluate pruned vs original model original_results = evaluator.simple_evaluate( model="hf", model_args="pretrained=meta-llama/Llama-2-7b-hf", tasks=["arc_easy", "hellaswag", "winogrande"], ) pruned_results = evaluator.simple_evaluate( model="hf", model_args="pretrained=./pruned-llama-7b-50", tasks=["arc_easy", "hellaswag", "winogrande"], ) # Compare print(f"Original: {original_results['results']['arc_easy']['acc']:.3f}") print(f"Pruned: {pruned_results['results']['arc_easy']['acc']:.3f}") print(f"Degradation: {(original_results - pruned_results):.3f}") # Typical results at 50% sparsity: # - Wanda: <1% accuracy loss # - SparseGPT: <0.5% accuracy loss # - Magnitude: 2-3% accuracy loss
python# Conservative (safe) sparsity = 0.3 # 30%, <0.5% loss # Balanced (recommended) sparsity = 0.5 # 50%, ~1% loss # Aggressive (risky) sparsity = 0.7 # 70%, 2-5% loss # Extreme (model-dependent) sparsity = 0.9 # 90%, significant degradation
python# One-shot, no retraining → Wanda or SparseGPT if no_retraining_budget: use_method = "wanda" # Faster # Best quality → SparseGPT if need_best_quality: use_method = "sparsegpt" # More accurate # Hardware speedup → N:M structured if need_speedup: use_method = "nm_prune" # 2:4 or 4:8
python# ❌ Bad: Pruning without calibration data prune_random(model) # No activation statistics # ✅ Good: Use calibration data prune_wanda(model, calib_data) # ❌ Bad: Too high sparsity in one shot prune(model, sparsity=0.9) # Massive accuracy loss # ✅ Good: Gradual or iterative iterative_prune(model, target=0.9, steps=10)
Pruning methods at 50% sparsity (LLaMA-7B):
| Method | Accuracy Loss | Speed | Memory | Retraining Needed | |--------|---------------|-------|---------|-------------------| | Magnitude | -2.5% | 1.0× | -50% | No | | Wanda | -0.8% | 1.0× | -50% | No | | SparseGPT | -0.4% | 1.0× | -50% | No | | N:M (2:4) | -1.0% | 2.0× | -50% | No | | Structured | -3.0% | 2.0× | -50% | No |
Source: Wanda paper (ICLR 2024), SparseGPT paper
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-01 | pass→pass | 16,034 | 9,530 | -41% | 1 | 1 | 0% | 3,118 | 6,098 | +96% | 0 | 0 | — |
case-02 | pass→pass | 9,286 | 7,307 | -21% | 1 | 1 | 0% | 1,722 | 5,528 | +221% | 0 | 0 | — |
case-03 | pass→pass | 11,149 | 9,575 | -14% | 1 | 1 | 0% | 2,021 | 5,774 | +186% | 0 | 0 | — |
case-04 | fail→pass | 14,778 | 8,280 | -44% | 1 | 1 | 0% | 2,907 | 5,722 | +97% | 0 | 0 | — |
case-05 | pass→pass | 15,693 | 18,626 | +19% | 1 | 1 | 0% | 2,733 | 7,518 | +175% | 0 | 0 | — |
case-06 | pass→fail | 12,731 | 14,239 | +12% | 1 | 1 | 0% | 2,365 | 6,538 | +176% | 0 | 0 | — |
case-07 | fail→fail | 11,679 | 8,125 | -30% | 1 | 1 | 0% | 2,216 | 5,632 | +154% | 0 | 0 | — |
case-08 | pass→pass | 6,362 | 6,523 | +3% | 1 | 1 | 0% | 1,165 | 5,217 | +348% | 0 | 0 | — |
case-09 | pass→pass | 11,720 | 14,531 | +24% | 1 | 1 | 0% | 2,281 | 6,436 | +182% | 0 | 0 | — |
case-10 | pass→pass | 10,535 | 9,774 | -7% | 1 | 1 | 0% | 2,086 | 5,815 | +179% | 0 | 0 | — |
case-11 | pass→pass | 12,122 | 13,201 | +9% | 1 | 1 | 0% | 2,287 | 6,953 | +204% | 0 | 0 | — |
case-12 | pass→pass | 11,115 | 12,021 | +8% | 1 | 1 | 0% | 2,559 | 6,421 | +151% | 0 | 0 | — |
case-13 | pass→pass | 14,577 | 11,763 | -19% | 1 | 1 | 0% | 2,605 | 6,512 | +150% | 0 | 0 | — |
case-14 | fail→pass | 12,829 | 4,755 | -63% | 1 | 1 | 0% | 2,351 | 4,994 | +112% | 0 | 0 | — |
case-15 | pass→pass | 14,912 | 10,360 | -31% | 1 | 1 | 0% | 3,067 | 6,141 | +100% | 0 | 0 | — |
case-16 | pass→pass | 11,720 | 14,991 | +28% | 1 | 1 | 0% | 2,408 | 7,156 | +197% | 0 | 0 | — |
case-17 | pass→pass | 6,355 | 5,989 | -6% | 1 | 1 | 0% | 1,187 | 5,250 | +342% | 0 | 0 | — |
case-18 | pass→pass | 6,904 | 8,717 | +26% | 1 | 1 | 0% | 1,179 | 5,699 | +383% | 0 | 0 | — |
case-19 | pass→pass | 12,365 | 12,943 | +5% | 1 | 1 | 0% | 2,093 | 6,357 | +204% | 0 | 0 | — |
case-20 | pass→pass | 15,309 | 18,978 | +24% | 1 | 1 | 0% | 2,809 | 7,932 | +182% | 0 | 0 | — |
case-21 | pass→pass | 15,742 | 17,992 | +14% | 1 | 1 | 0% | 2,659 | 7,195 | +171% | 0 | 0 | — |
case-22 | fail→fail | 11,825 | 12,760 | +8% | 1 | 1 | 0% | 2,197 | 6,412 | +192% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 22 cases were attempted. The headline lift of 0 percentage points is the difference between those two pass rates over the 22 comparable cases. 2 cases got worse with the skill loaded, and they are included in that figure.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.