[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ADP7XGBJN0EFQ2TYXB19C2":3,"skill-same:01M6ADP7XGBJN0EFQ2TYXB19C2":85},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":43,"linkOnly":44,"markdownContent":45,"markdownBody":46,"frontMatter":47,"refName":55,"commitSha":56,"skillDirectory":57,"forksCount":58,"repositoryHtmlUrl":59,"repositoryHomepageUrl":60,"ownerHtmlUrl":61,"ownerBlogUrl":62,"ownerDescription":63,"updatedAt":64,"install":65,"resources":78},"01M6ADP7XGBJN0EFQ2TYXB19C2","emerging-techniques-model-pruning",null,"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.","davila7\u002Fclaude-code-templates","davila7","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6216945?v=4","01M6ADEWWFPS191NFM0Y1EX1JH","Daniel Avila","01M6ADJHGM78PHQRD3XZTFDVKK",33481,"MIT","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Femerging-techniques-model-pruning\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42],"emerging techniques model pruning","techniques","model","Emerging Techniques","Model Pruning","Wanda","when","reduce","orchestra","unstructured","Unstructured Pruning","Structured Pruning","One-Shot Pruning","N:M Sparsity","Sparsity","SparseGPT","inference","Model Compression","Accelerate","Transformers","Fast Inference","fast","compression","research","2026-11-10 10:12:30",false,"---\nname: emerging-techniques-model-pruning\ndescription: 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.\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  author: Orchestra Research\n  tags: [Emerging Techniques, Model Pruning, Wanda, SparseGPT, Sparsity, Model Compression, N:M Sparsity, One-Shot Pruning, Structured Pruning, Unstructured Pruning, Fast Inference]\n  dependencies: [transformers, torch]\n---\n\n# Model Pruning: Compressing LLMs\n\n## When to Use This Skill\n\nUse Model Pruning when you need to:\n- **Reduce model size** by 40-60% with \u003C1% accuracy loss\n- **Accelerate inference** using hardware-friendly sparsity (2-4× speedup)\n- **Deploy on constrained hardware** (mobile, edge devices)\n- **Compress without retraining** using one-shot methods\n- **Enable efficient serving** with reduced memory footprint\n\n**Key Techniques**: Wanda (weights × activations), SparseGPT (second-order), structured pruning, N:M sparsity\n\n**Papers**: Wanda ICLR 2024 (arXiv 2306.11695), SparseGPT (arXiv 2301.00774)\n\n## Installation\n\n```bash\n# Wanda implementation\ngit clone https:\u002F\u002Fgithub.com\u002Flocuslab\u002Fwanda\ncd wanda\npip install -r requirements.txt\n\n# Optional: SparseGPT\ngit clone https:\u002F\u002Fgithub.com\u002FIST-DASLab\u002Fsparsegpt\ncd sparsegpt\npip install -e .\n\n# Dependencies\npip install torch transformers accelerate\n```\n\n## Quick Start\n\n### Wanda Pruning (One-Shot, No Retraining)\n\n**Source**: ICLR 2024 (arXiv 2306.11695)\n\n```python\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\n# Load model\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-7b-hf\",\n    torch_dtype=torch.float16,\n    device_map=\"cuda\"\n)\ntokenizer = AutoTokenizer.from_pretrained(\"meta-llama\u002FLlama-2-7b-hf\")\n\n# Calibration data (small dataset for activation statistics)\ncalib_data = [\n    \"The quick brown fox jumps over the lazy dog.\",\n    \"Machine learning is transforming the world.\",\n    \"Artificial intelligence powers modern applications.\",\n]\n\n# Wanda pruning function\ndef wanda_prune(model, calib_data, sparsity=0.5):\n    \"\"\"\n    Wanda: Prune by weight magnitude × input activation.\n\n    Args:\n        sparsity: Fraction of weights to prune (0.5 = 50%)\n    \"\"\"\n    # 1. Collect activation statistics\n    activations = {}\n\n    def hook_fn(name):\n        def hook(module, input, output):\n            # Store input activation norms\n            activations[name] = input[0].detach().abs().mean(dim=0)\n        return hook\n\n    # Register hooks for all linear layers\n    hooks = []\n    for name, module in model.named_modules():\n        if isinstance(module, torch.nn.Linear):\n            hooks.append(module.register_forward_hook(hook_fn(name)))\n\n    # Run calibration data\n    model.eval()\n    with torch.no_grad():\n        for text in calib_data:\n            inputs = tokenizer(text, return_tensors=\"pt\").to(model.device)\n            model(**inputs)\n\n    # Remove hooks\n    for hook in hooks:\n        hook.remove()\n\n    # 2. Prune weights based on |weight| × activation\n    for name, module in model.named_modules():\n        if isinstance(module, torch.nn.Linear) and name in activations:\n            W = module.weight.data\n            act = activations[name]\n\n            # Compute importance: |weight| × activation\n            importance = W.abs() * act.unsqueeze(0)\n\n            # Flatten and find threshold\n            threshold = torch.quantile(importance.flatten(), sparsity)\n\n            # Create mask\n            mask = importance >= threshold\n\n            # Apply mask (prune)\n            W *= mask.float()\n\n    return model\n\n# Apply Wanda pruning (50% sparsity, one-shot, no retraining)\npruned_model = wanda_prune(model, calib_data, sparsity=0.5)\n\n# Save\npruned_model.save_pretrained(\".\u002Fllama-2-7b-wanda-50\")\n```\n\n### SparseGPT (Second-Order Pruning)\n\n**Source**: arXiv 2301.00774\n\n```python\nfrom sparsegpt import SparseGPT\n\n# Load model\nmodel = AutoModelForCausalLM.from_pretrained(\"meta-llama\u002FLlama-2-7b-hf\")\n\n# Initialize SparseGPT\npruner = SparseGPT(model)\n\n# Calibration data\ncalib_data = load_calibration_data()  # ~128 samples\n\n# Prune (one-shot, layer-wise reconstruction)\npruned_model = pruner.prune(\n    calib_data=calib_data,\n    sparsity=0.5,           # 50% sparsity\n    prunen=0,               # Unstructured (0) or N:M structured\n    prunem=0,\n    percdamp=0.01,          # Damping for Hessian inverse\n)\n\n# Results: Near-lossless pruning at 50% sparsity\n```\n\n### N:M Structured Pruning (Hardware Accelerator)\n\n```python\ndef nm_prune(weight, n=2, m=4):\n    \"\"\"\n    N:M pruning: Keep N weights per M consecutive weights.\n    Example: 2:4 = keep 2 out of every 4 weights.\n\n    Compatible with NVIDIA sparse tensor cores (2:4, 4:8).\n    \"\"\"\n    # Reshape weight into groups of M\n    shape = weight.shape\n    weight_flat = weight.flatten()\n\n    # Pad to multiple of M\n    pad_size = (m - weight_flat.numel() % m) % m\n    weight_padded = F.pad(weight_flat, (0, pad_size))\n\n    # Reshape into (num_groups, m)\n    weight_grouped = weight_padded.reshape(-1, m)\n\n    # Find top-N in each group\n    _, indices = torch.topk(weight_grouped.abs(), n, dim=-1)\n\n    # Create mask\n    mask = torch.zeros_like(weight_grouped)\n    mask.scatter_(1, indices, 1.0)\n\n    # Apply mask\n    weight_pruned = weight_grouped * mask\n\n    # Reshape back\n    weight_pruned = weight_pruned.flatten()[:weight_flat.numel()]\n    return weight_pruned.reshape(shape)\n\n# Apply 2:4 sparsity (NVIDIA hardware)\nfor name, module in model.named_modules():\n    if isinstance(module, torch.nn.Linear):\n        module.weight.data = nm_prune(module.weight.data, n=2, m=4)\n\n# 50% sparsity, 2× speedup on A100 with sparse tensor cores\n```\n\n## Core Concepts\n\n### 1. Pruning Criteria\n\n**Magnitude Pruning** (baseline):\n```python\n# Prune weights with smallest absolute values\nimportance = weight.abs()\nthreshold = torch.quantile(importance, sparsity)\nmask = importance >= threshold\n```\n\n**Wanda** (weights × activations):\n```python\n# Importance = |weight| × input_activation\nimportance = weight.abs() * activation\n# Better than magnitude alone (considers usage)\n```\n\n**SparseGPT** (second-order):\n```python\n# Uses Hessian (second derivative) for importance\n# More accurate but computationally expensive\nimportance = weight^2 \u002F diag(Hessian)\n```\n\n### 2. Structured vs Unstructured\n\n**Unstructured** (fine-grained):\n- Prune individual weights\n- Higher quality (better accuracy)\n- No hardware speedup (irregular sparsity)\n\n**Structured** (coarse-grained):\n- Prune entire neurons, heads, or layers\n- Lower quality (more accuracy loss)\n- Hardware speedup (regular sparsity)\n\n**Semi-structured (N:M)**:\n- Best of both worlds\n- 50% sparsity (2:4) → 2× speedup on NVIDIA GPUs\n- Minimal accuracy loss\n\n### 3. Sparsity Patterns\n\n```python\n# Unstructured (random)\n# [1, 0, 1, 0, 1, 1, 0, 0]\n# Pros: Flexible, high quality\n# Cons: No speedup\n\n# Structured (block)\n# [1, 1, 0, 0, 1, 1, 0, 0]\n# Pros: Hardware friendly\n# Cons: More accuracy loss\n\n# N:M (semi-structured)\n# [1, 0, 1, 0] [1, 1, 0, 0]  (2:4 pattern)\n# Pros: Hardware speedup + good quality\n# Cons: Requires specific hardware (NVIDIA)\n```\n\n## Pruning Strategies\n\n### Strategy 1: Gradual Magnitude Pruning\n\n```python\ndef gradual_prune(model, initial_sparsity=0.0, final_sparsity=0.5, num_steps=100):\n    \"\"\"Gradually increase sparsity during training.\"\"\"\n    for step in range(num_steps):\n        # Current sparsity\n        current_sparsity = initial_sparsity + (final_sparsity - initial_sparsity) * (step \u002F num_steps)\n\n        # Prune at current sparsity\n        for module in model.modules():\n            if isinstance(module, torch.nn.Linear):\n                weight = module.weight.data\n                threshold = torch.quantile(weight.abs().flatten(), current_sparsity)\n                mask = weight.abs() >= threshold\n                weight *= mask.float()\n\n        # Train one step\n        train_step(model)\n\n    return model\n```\n\n### Strategy 2: Layer-wise Pruning\n\n```python\ndef layer_wise_prune(model, sparsity_per_layer):\n    \"\"\"Different sparsity for different layers.\"\"\"\n    # Early layers: Less pruning (more important)\n    # Late layers: More pruning (less critical)\n\n    sparsity_schedule = {\n        \"layer.0\": 0.3,   # 30% sparsity\n        \"layer.1\": 0.4,\n        \"layer.2\": 0.5,\n        \"layer.3\": 0.6,   # 60% sparsity\n    }\n\n    for name, module in model.named_modules():\n        if isinstance(module, torch.nn.Linear):\n            # Find layer index\n            for layer_name, sparsity in sparsity_schedule.items():\n                if layer_name in name:\n                    # Prune at layer-specific sparsity\n                    prune_layer(module, sparsity)\n                    break\n\n    return model\n```\n\n### Strategy 3: Iterative Pruning + Fine-tuning\n\n```python\ndef iterative_prune_finetune(model, target_sparsity=0.5, iterations=5):\n    \"\"\"Prune gradually with fine-tuning between iterations.\"\"\"\n    current_sparsity = 0.0\n    sparsity_increment = target_sparsity \u002F iterations\n\n    for i in range(iterations):\n        # Increase sparsity\n        current_sparsity += sparsity_increment\n\n        # Prune\n        prune_model(model, sparsity=current_sparsity)\n\n        # Fine-tune (recover accuracy)\n        fine_tune(model, epochs=2, lr=1e-5)\n\n    return model\n\n# Results: Better accuracy than one-shot at high sparsity\n```\n\n## Production Deployment\n\n### Complete Pruning Pipeline\n\n```python\nfrom transformers import Trainer, TrainingArguments\n\ndef production_pruning_pipeline(\n    model_name=\"meta-llama\u002FLlama-2-7b-hf\",\n    target_sparsity=0.5,\n    method=\"wanda\",  # or \"sparsegpt\"\n):\n    # 1. Load model\n    model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16)\n    tokenizer = AutoTokenizer.from_pretrained(model_name)\n\n    # 2. Load calibration data\n    calib_dataset = load_dataset(\"wikitext\", \"wikitext-2-raw-v1\", split=\"train[:1000]\")\n\n    # 3. Apply pruning\n    if method == \"wanda\":\n        pruned_model = wanda_prune(model, calib_dataset, sparsity=target_sparsity)\n    elif method == \"sparsegpt\":\n        pruner = SparseGPT(model)\n        pruned_model = pruner.prune(calib_dataset, sparsity=target_sparsity)\n\n    # 4. (Optional) Fine-tune to recover accuracy\n    training_args = TrainingArguments(\n        output_dir=\".\u002Fpruned-model\",\n        num_train_epochs=1,\n        per_device_train_batch_size=4,\n        learning_rate=1e-5,\n        bf16=True,\n    )\n\n    trainer = Trainer(\n        model=pruned_model,\n        args=training_args,\n        train_dataset=finetune_dataset,\n    )\n\n    trainer.train()\n\n    # 5. Save\n    pruned_model.save_pretrained(\".\u002Fpruned-llama-7b-50\")\n    tokenizer.save_pretrained(\".\u002Fpruned-llama-7b-50\")\n\n    return pruned_model\n\n# Usage\npruned_model = production_pruning_pipeline(\n    model_name=\"meta-llama\u002FLlama-2-7b-hf\",\n    target_sparsity=0.5,\n    method=\"wanda\"\n)\n```\n\n### Evaluation\n\n```python\nfrom lm_eval import evaluator\n\n# Evaluate pruned vs original model\noriginal_results = evaluator.simple_evaluate(\n    model=\"hf\",\n    model_args=\"pretrained=meta-llama\u002FLlama-2-7b-hf\",\n    tasks=[\"arc_easy\", \"hellaswag\", \"winogrande\"],\n)\n\npruned_results = evaluator.simple_evaluate(\n    model=\"hf\",\n    model_args=\"pretrained=.\u002Fpruned-llama-7b-50\",\n    tasks=[\"arc_easy\", \"hellaswag\", \"winogrande\"],\n)\n\n# Compare\nprint(f\"Original: {original_results['results']['arc_easy']['acc']:.3f}\")\nprint(f\"Pruned:   {pruned_results['results']['arc_easy']['acc']:.3f}\")\nprint(f\"Degradation: {(original_results - pruned_results):.3f}\")\n\n# Typical results at 50% sparsity:\n# - Wanda: \u003C1% accuracy loss\n# - SparseGPT: \u003C0.5% accuracy loss\n# - Magnitude: 2-3% accuracy loss\n```\n\n## Best Practices\n\n### 1. Sparsity Selection\n\n```python\n# Conservative (safe)\nsparsity = 0.3  # 30%, \u003C0.5% loss\n\n# Balanced (recommended)\nsparsity = 0.5  # 50%, ~1% loss\n\n# Aggressive (risky)\nsparsity = 0.7  # 70%, 2-5% loss\n\n# Extreme (model-dependent)\nsparsity = 0.9  # 90%, significant degradation\n```\n\n### 2. Method Selection\n\n```python\n# One-shot, no retraining → Wanda or SparseGPT\nif no_retraining_budget:\n    use_method = \"wanda\"  # Faster\n\n# Best quality → SparseGPT\nif need_best_quality:\n    use_method = \"sparsegpt\"  # More accurate\n\n# Hardware speedup → N:M structured\nif need_speedup:\n    use_method = \"nm_prune\"  # 2:4 or 4:8\n```\n\n### 3. Avoid Common Pitfalls\n\n```python\n# ❌ Bad: Pruning without calibration data\nprune_random(model)  # No activation statistics\n\n# ✅ Good: Use calibration data\nprune_wanda(model, calib_data)\n\n# ❌ Bad: Too high sparsity in one shot\nprune(model, sparsity=0.9)  # Massive accuracy loss\n\n# ✅ Good: Gradual or iterative\niterative_prune(model, target=0.9, steps=10)\n```\n\n## Performance Comparison\n\n**Pruning methods at 50% sparsity** (LLaMA-7B):\n\n| Method | Accuracy Loss | Speed | Memory | Retraining Needed |\n|--------|---------------|-------|---------|-------------------|\n| **Magnitude** | -2.5% | 1.0× | -50% | No |\n| **Wanda** | -0.8% | 1.0× | -50% | No |\n| **SparseGPT** | -0.4% | 1.0× | -50% | No |\n| **N:M (2:4)** | -1.0% | 2.0× | -50% | No |\n| **Structured** | -3.0% | 2.0× | -50% | No |\n\n**Source**: Wanda paper (ICLR 2024), SparseGPT paper\n\n## Resources\n\n- **Wanda Paper (ICLR 2024)**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2306.11695\n- **Wanda GitHub**: https:\u002F\u002Fgithub.com\u002Flocuslab\u002Fwanda\n- **SparseGPT Paper**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2301.00774\n- **SparseGPT GitHub**: https:\u002F\u002Fgithub.com\u002FIST-DASLab\u002Fsparsegpt\n- **NVIDIA Sparse Tensor Cores**: https:\u002F\u002Fdeveloper.nvidia.com\u002Fblog\u002Faccelerating-inference-with-sparsity-using-ampere-and-tensorrt\u002F\n\n\n","# Model Pruning: Compressing LLMs\n\n## When to Use This Skill\n\nUse Model Pruning when you need to:\n- **Reduce model size** by 40-60% with \u003C1% accuracy loss\n- **Accelerate inference** using hardware-friendly sparsity (2-4× speedup)\n- **Deploy on constrained hardware** (mobile, edge devices)\n- **Compress without retraining** using one-shot methods\n- **Enable efficient serving** with reduced memory footprint\n\n**Key Techniques**: Wanda (weights × activations), SparseGPT (second-order), structured pruning, N:M sparsity\n\n**Papers**: Wanda ICLR 2024 (arXiv 2306.11695), SparseGPT (arXiv 2301.00774)\n\n## Installation\n\n```bash\n# Wanda implementation\ngit clone https:\u002F\u002Fgithub.com\u002Flocuslab\u002Fwanda\ncd wanda\npip install -r requirements.txt\n\n# Optional: SparseGPT\ngit clone https:\u002F\u002Fgithub.com\u002FIST-DASLab\u002Fsparsegpt\ncd sparsegpt\npip install -e .\n\n# Dependencies\npip install torch transformers accelerate\n```\n\n## Quick Start\n\n### Wanda Pruning (One-Shot, No Retraining)\n\n**Source**: ICLR 2024 (arXiv 2306.11695)\n\n```python\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\n# Load model\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-7b-hf\",\n    torch_dtype=torch.float16,\n    device_map=\"cuda\"\n)\ntokenizer = AutoTokenizer.from_pretrained(\"meta-llama\u002FLlama-2-7b-hf\")\n\n# Calibration data (small dataset for activation statistics)\ncalib_data = [\n    \"The quick brown fox jumps over the lazy dog.\",\n    \"Machine learning is transforming the world.\",\n    \"Artificial intelligence powers modern applications.\",\n]\n\n# Wanda pruning function\ndef wanda_prune(model, calib_data, sparsity=0.5):\n    \"\"\"\n    Wanda: Prune by weight magnitude × input activation.\n\n    Args:\n        sparsity: Fraction of weights to prune (0.5 = 50%)\n    \"\"\"\n    # 1. Collect activation statistics\n    activations = {}\n\n    def hook_fn(name):\n        def hook(module, input, output):\n            # Store input activation norms\n            activations[name] = input[0].detach().abs().mean(dim=0)\n        return hook\n\n    # Register hooks for all linear layers\n    hooks = []\n    for name, module in model.named_modules():\n        if isinstance(module, torch.nn.Linear):\n            hooks.append(module.register_forward_hook(hook_fn(name)))\n\n    # Run calibration data\n    model.eval()\n    with torch.no_grad():\n        for text in calib_data:\n            inputs = tokenizer(text, return_tensors=\"pt\").to(model.device)\n            model(**inputs)\n\n    # Remove hooks\n    for hook in hooks:\n        hook.remove()\n\n    # 2. Prune weights based on |weight| × activation\n    for name, module in model.named_modules():\n        if isinstance(module, torch.nn.Linear) and name in activations:\n            W = module.weight.data\n            act = activations[name]\n\n            # Compute importance: |weight| × activation\n            importance = W.abs() * act.unsqueeze(0)\n\n            # Flatten and find threshold\n            threshold = torch.quantile(importance.flatten(), sparsity)\n\n            # Create mask\n            mask = importance >= threshold\n\n            # Apply mask (prune)\n            W *= mask.float()\n\n    return model\n\n# Apply Wanda pruning (50% sparsity, one-shot, no retraining)\npruned_model = wanda_prune(model, calib_data, sparsity=0.5)\n\n# Save\npruned_model.save_pretrained(\".\u002Fllama-2-7b-wanda-50\")\n```\n\n### SparseGPT (Second-Order Pruning)\n\n**Source**: arXiv 2301.00774\n\n```python\nfrom sparsegpt import SparseGPT\n\n# Load model\nmodel = AutoModelForCausalLM.from_pretrained(\"meta-llama\u002FLlama-2-7b-hf\")\n\n# Initialize SparseGPT\npruner = SparseGPT(model)\n\n# Calibration data\ncalib_data = load_calibration_data()  # ~128 samples\n\n# Prune (one-shot, layer-wise reconstruction)\npruned_model = pruner.prune(\n    calib_data=calib_data,\n    sparsity=0.5,           # 50% sparsity\n    prunen=0,               # Unstructured (0) or N:M structured\n    prunem=0,\n    percdamp=0.01,          # Damping for Hessian inverse\n)\n\n# Results: Near-lossless pruning at 50% sparsity\n```\n\n### N:M Structured Pruning (Hardware Accelerator)\n\n```python\ndef nm_prune(weight, n=2, m=4):\n    \"\"\"\n    N:M pruning: Keep N weights per M consecutive weights.\n    Example: 2:4 = keep 2 out of every 4 weights.\n\n    Compatible with NVIDIA sparse tensor cores (2:4, 4:8).\n    \"\"\"\n    # Reshape weight into groups of M\n    shape = weight.shape\n    weight_flat = weight.flatten()\n\n    # Pad to multiple of M\n    pad_size = (m - weight_flat.numel() % m) % m\n    weight_padded = F.pad(weight_flat, (0, pad_size))\n\n    # Reshape into (num_groups, m)\n    weight_grouped = weight_padded.reshape(-1, m)\n\n    # Find top-N in each group\n    _, indices = torch.topk(weight_grouped.abs(), n, dim=-1)\n\n    # Create mask\n    mask = torch.zeros_like(weight_grouped)\n    mask.scatter_(1, indices, 1.0)\n\n    # Apply mask\n    weight_pruned = weight_grouped * mask\n\n    # Reshape back\n    weight_pruned = weight_pruned.flatten()[:weight_flat.numel()]\n    return weight_pruned.reshape(shape)\n\n# Apply 2:4 sparsity (NVIDIA hardware)\nfor name, module in model.named_modules():\n    if isinstance(module, torch.nn.Linear):\n        module.weight.data = nm_prune(module.weight.data, n=2, m=4)\n\n# 50% sparsity, 2× speedup on A100 with sparse tensor cores\n```\n\n## Core Concepts\n\n### 1. Pruning Criteria\n\n**Magnitude Pruning** (baseline):\n```python\n# Prune weights with smallest absolute values\nimportance = weight.abs()\nthreshold = torch.quantile(importance, sparsity)\nmask = importance >= threshold\n```\n\n**Wanda** (weights × activations):\n```python\n# Importance = |weight| × input_activation\nimportance = weight.abs() * activation\n# Better than magnitude alone (considers usage)\n```\n\n**SparseGPT** (second-order):\n```python\n# Uses Hessian (second derivative) for importance\n# More accurate but computationally expensive\nimportance = weight^2 \u002F diag(Hessian)\n```\n\n### 2. Structured vs Unstructured\n\n**Unstructured** (fine-grained):\n- Prune individual weights\n- Higher quality (better accuracy)\n- No hardware speedup (irregular sparsity)\n\n**Structured** (coarse-grained):\n- Prune entire neurons, heads, or layers\n- Lower quality (more accuracy loss)\n- Hardware speedup (regular sparsity)\n\n**Semi-structured (N:M)**:\n- Best of both worlds\n- 50% sparsity (2:4) → 2× speedup on NVIDIA GPUs\n- Minimal accuracy loss\n\n### 3. Sparsity Patterns\n\n```python\n# Unstructured (random)\n# [1, 0, 1, 0, 1, 1, 0, 0]\n# Pros: Flexible, high quality\n# Cons: No speedup\n\n# Structured (block)\n# [1, 1, 0, 0, 1, 1, 0, 0]\n# Pros: Hardware friendly\n# Cons: More accuracy loss\n\n# N:M (semi-structured)\n# [1, 0, 1, 0] [1, 1, 0, 0]  (2:4 pattern)\n# Pros: Hardware speedup + good quality\n# Cons: Requires specific hardware (NVIDIA)\n```\n\n## Pruning Strategies\n\n### Strategy 1: Gradual Magnitude Pruning\n\n```python\ndef gradual_prune(model, initial_sparsity=0.0, final_sparsity=0.5, num_steps=100):\n    \"\"\"Gradually increase sparsity during training.\"\"\"\n    for step in range(num_steps):\n        # Current sparsity\n        current_sparsity = initial_sparsity + (final_sparsity - initial_sparsity) * (step \u002F num_steps)\n\n        # Prune at current sparsity\n        for module in model.modules():\n            if isinstance(module, torch.nn.Linear):\n                weight = module.weight.data\n                threshold = torch.quantile(weight.abs().flatten(), current_sparsity)\n                mask = weight.abs() >= threshold\n                weight *= mask.float()\n\n        # Train one step\n        train_step(model)\n\n    return model\n```\n\n### Strategy 2: Layer-wise Pruning\n\n```python\ndef layer_wise_prune(model, sparsity_per_layer):\n    \"\"\"Different sparsity for different layers.\"\"\"\n    # Early layers: Less pruning (more important)\n    # Late layers: More pruning (less critical)\n\n    sparsity_schedule = {\n        \"layer.0\": 0.3,   # 30% sparsity\n        \"layer.1\": 0.4,\n        \"layer.2\": 0.5,\n        \"layer.3\": 0.6,   # 60% sparsity\n    }\n\n    for name, module in model.named_modules():\n        if isinstance(module, torch.nn.Linear):\n            # Find layer index\n            for layer_name, sparsity in sparsity_schedule.items():\n                if layer_name in name:\n                    # Prune at layer-specific sparsity\n                    prune_layer(module, sparsity)\n                    break\n\n    return model\n```\n\n### Strategy 3: Iterative Pruning + Fine-tuning\n\n```python\ndef iterative_prune_finetune(model, target_sparsity=0.5, iterations=5):\n    \"\"\"Prune gradually with fine-tuning between iterations.\"\"\"\n    current_sparsity = 0.0\n    sparsity_increment = target_sparsity \u002F iterations\n\n    for i in range(iterations):\n        # Increase sparsity\n        current_sparsity += sparsity_increment\n\n        # Prune\n        prune_model(model, sparsity=current_sparsity)\n\n        # Fine-tune (recover accuracy)\n        fine_tune(model, epochs=2, lr=1e-5)\n\n    return model\n\n# Results: Better accuracy than one-shot at high sparsity\n```\n\n## Production Deployment\n\n### Complete Pruning Pipeline\n\n```python\nfrom transformers import Trainer, TrainingArguments\n\ndef production_pruning_pipeline(\n    model_name=\"meta-llama\u002FLlama-2-7b-hf\",\n    target_sparsity=0.5,\n    method=\"wanda\",  # or \"sparsegpt\"\n):\n    # 1. Load model\n    model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16)\n    tokenizer = AutoTokenizer.from_pretrained(model_name)\n\n    # 2. Load calibration data\n    calib_dataset = load_dataset(\"wikitext\", \"wikitext-2-raw-v1\", split=\"train[:1000]\")\n\n    # 3. Apply pruning\n    if method == \"wanda\":\n        pruned_model = wanda_prune(model, calib_dataset, sparsity=target_sparsity)\n    elif method == \"sparsegpt\":\n        pruner = SparseGPT(model)\n        pruned_model = pruner.prune(calib_dataset, sparsity=target_sparsity)\n\n    # 4. (Optional) Fine-tune to recover accuracy\n    training_args = TrainingArguments(\n        output_dir=\".\u002Fpruned-model\",\n        num_train_epochs=1,\n        per_device_train_batch_size=4,\n        learning_rate=1e-5,\n        bf16=True,\n    )\n\n    trainer = Trainer(\n        model=pruned_model,\n        args=training_args,\n        train_dataset=finetune_dataset,\n    )\n\n    trainer.train()\n\n    # 5. Save\n    pruned_model.save_pretrained(\".\u002Fpruned-llama-7b-50\")\n    tokenizer.save_pretrained(\".\u002Fpruned-llama-7b-50\")\n\n    return pruned_model\n\n# Usage\npruned_model = production_pruning_pipeline(\n    model_name=\"meta-llama\u002FLlama-2-7b-hf\",\n    target_sparsity=0.5,\n    method=\"wanda\"\n)\n```\n\n### Evaluation\n\n```python\nfrom lm_eval import evaluator\n\n# Evaluate pruned vs original model\noriginal_results = evaluator.simple_evaluate(\n    model=\"hf\",\n    model_args=\"pretrained=meta-llama\u002FLlama-2-7b-hf\",\n    tasks=[\"arc_easy\", \"hellaswag\", \"winogrande\"],\n)\n\npruned_results = evaluator.simple_evaluate(\n    model=\"hf\",\n    model_args=\"pretrained=.\u002Fpruned-llama-7b-50\",\n    tasks=[\"arc_easy\", \"hellaswag\", \"winogrande\"],\n)\n\n# Compare\nprint(f\"Original: {original_results['results']['arc_easy']['acc']:.3f}\")\nprint(f\"Pruned:   {pruned_results['results']['arc_easy']['acc']:.3f}\")\nprint(f\"Degradation: {(original_results - pruned_results):.3f}\")\n\n# Typical results at 50% sparsity:\n# - Wanda: \u003C1% accuracy loss\n# - SparseGPT: \u003C0.5% accuracy loss\n# - Magnitude: 2-3% accuracy loss\n```\n\n## Best Practices\n\n### 1. Sparsity Selection\n\n```python\n# Conservative (safe)\nsparsity = 0.3  # 30%, \u003C0.5% loss\n\n# Balanced (recommended)\nsparsity = 0.5  # 50%, ~1% loss\n\n# Aggressive (risky)\nsparsity = 0.7  # 70%, 2-5% loss\n\n# Extreme (model-dependent)\nsparsity = 0.9  # 90%, significant degradation\n```\n\n### 2. Method Selection\n\n```python\n# One-shot, no retraining → Wanda or SparseGPT\nif no_retraining_budget:\n    use_method = \"wanda\"  # Faster\n\n# Best quality → SparseGPT\nif need_best_quality:\n    use_method = \"sparsegpt\"  # More accurate\n\n# Hardware speedup → N:M structured\nif need_speedup:\n    use_method = \"nm_prune\"  # 2:4 or 4:8\n```\n\n### 3. Avoid Common Pitfalls\n\n```python\n# ❌ Bad: Pruning without calibration data\nprune_random(model)  # No activation statistics\n\n# ✅ Good: Use calibration data\nprune_wanda(model, calib_data)\n\n# ❌ Bad: Too high sparsity in one shot\nprune(model, sparsity=0.9)  # Massive accuracy loss\n\n# ✅ Good: Gradual or iterative\niterative_prune(model, target=0.9, steps=10)\n```\n\n## Performance Comparison\n\n**Pruning methods at 50% sparsity** (LLaMA-7B):\n\n| Method | Accuracy Loss | Speed | Memory | Retraining Needed |\n|--------|---------------|-------|---------|-------------------|\n| **Magnitude** | -2.5% | 1.0× | -50% | No |\n| **Wanda** | -0.8% | 1.0× | -50% | No |\n| **SparseGPT** | -0.4% | 1.0× | -50% | No |\n| **N:M (2:4)** | -1.0% | 2.0× | -50% | No |\n| **Structured** | -3.0% | 2.0× | -50% | No |\n\n**Source**: Wanda paper (ICLR 2024), SparseGPT paper\n\n## Resources\n\n- **Wanda Paper (ICLR 2024)**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2306.11695\n- **Wanda GitHub**: https:\u002F\u002Fgithub.com\u002Flocuslab\u002Fwanda\n- **SparseGPT Paper**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2301.00774\n- **SparseGPT GitHub**: https:\u002F\u002Fgithub.com\u002FIST-DASLab\u002Fsparsegpt\n- **NVIDIA Sparse Tensor Cores**: https:\u002F\u002Fdeveloper.nvidia.com\u002Fblog\u002Faccelerating-inference-with-sparsity-using-ampere-and-tensorrt\u002F\n\n\n",{"name":5,"license":15,"metadata":48,"description":7},{"tags":49,"author":50,"version":51,"dependencies":52},[22,23,24,34,33,36,32,31,30,29,39],"Orchestra Research","1.0.0",[53,54],"transformers","torch","main","2b749c82b5d11fac39d9a6e021ce3f5b8a541bd1","cli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Femerging-techniques-model-pruning",3931,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates","https:\u002F\u002Faitmpl.com","https:\u002F\u002Fgithub.com\u002Fdavila7","https:\u002F\u002Fdanielavila.me","Building AI dev tools with LLMs","2026-11-14 06:14:46",{"source":8,"skillName":5,"commands":66,"prompt":76,"zipAvailable":77},[67,70,73],{"tool":68,"command":69},"npx","npx skills add davila7\u002Fclaude-code-templates --skill emerging-techniques-model-pruning",{"tool":71,"command":72},"bunx","bunx skills add davila7\u002Fclaude-code-templates --skill emerging-techniques-model-pruning",{"tool":74,"command":75},"pnpm","pnpm dlx skills add davila7\u002Fclaude-code-templates --skill emerging-techniques-model-pruning","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Femerging-techniques-model-pruning\u002FSKILL.md",true,[79],{"path":80,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":83,"sourceHtmlUrl":84},"references\u002Fwanda.md","REFERENCE","参考文档",9492,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Femerging-techniques-model-pruning\u002Freferences\u002Fwanda.md",[86,116,143,176,211,235],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":97,"publishedAt":43},"01M70NHBTQ8BV0A2SCAZXEPHCX","wealthville-pool-scoring","Score DeFi liquidity pools before providing liquidity. Returns a 0-100 pool score and an Enter\u002FHold\u002FExit\u002FReduce\u002FAvoid verdict with calibrated confidence for ~68,800 Solana pools and 575 EVM pools, plus a public miss-inclusive track record. Use when asked whether a pool is worth LPing into, which pools look best right now, or how accurate the scores have actually been.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fweb-data\u002Fwealthville-pool-scoring\u002FSKILL.md",[92],{"categoryNo":93,"categoryName":94,"taxonomyType":95,"taxonomyTypeDesc":96},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[98,99,100,101,102,103,104,105,106,25,26,107,108,109,110,111,112,113,114,115],"scoring","pool","wealthville pool scoring","liquidity","which","for","exit","now","use","with","record","track","verdict","evm","solana","how","public","look",{"skillNo":117,"name":118,"nameZh":6,"description":119,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":120,"categories":121,"keywords":123,"publishedAt":43},"01M70MB6VR8ERJ4EM8D5KHBMEV","technical-debt-auditor","Scans a codebase and produces a quantified technical debt report with a prioritized remediation plan. Analyzes dead code, TODO\u002FFIXME\u002FHACK markers, dependency staleness, complexity hotspots, code duplication signals, test coverage gaps, unused exports, and outdated patterns. Use this skill when the user asks to audit their codebase for tech debt, wants a health check of their code quality, says things like \"where should I focus refactoring\", \"find code smells\", \"audit my codebase\", \"what technical debt do we have\", \"prioritize cleanup work\", or asks about code quality metrics. Also trigger when the user mentions \"code rot\", \"legacy cleanup\", \"refactoring priorities\", or wants to understand the overall health of a project before a major effort. Trigger even if the user doesn't say \"technical debt\" explicitly — any request to systematically assess code quality and identify improvement priorities belongs here.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdevelopment\u002Ftechnical-debt-auditor\u002FSKILL.md",[122],{"categoryNo":93,"categoryName":94,"taxonomyType":95,"taxonomyTypeDesc":96},[124,125,126,127,128,129,130,131,132,133,134,25,135,136,137,138,139,140,141,142],"technical debt","debt","technical","technical debt auditor","auditor","coverage","complexity","markers","project","cleanup","unused","code","todo","work","plan","focus","signals","audit","dependency",{"skillNo":144,"name":145,"nameZh":6,"description":146,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":147,"categories":148,"keywords":158,"publishedAt":43},"01M70KPYH9QNHCNME5GJQGE22K","readonly-sql-guard","Make an agent's database access provably read-only. Use when an agent runs caller-supplied SQL against a production\u002FERP\u002Fanalytics database (a \"query\" MCP tool, text-to-SQL, an admin console), or when reviewing DB-access code for write\u002FDDL\u002Fside-effect\u002Ftransaction-escape risks. Checks what a statement CALLS, not just its shape.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdatabase\u002Freadonly-sql-guard\u002FSKILL.md",[149,152,153],{"categoryNo":150,"categoryName":151,"taxonomyType":95,"taxonomyTypeDesc":96},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":93,"categoryName":94,"taxonomyType":95,"taxonomyTypeDesc":96},{"categoryNo":154,"categoryName":155,"taxonomyType":156,"taxonomyTypeDesc":157},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[159,160,161,162,163,164,165,103,166,167,168,169,170,171,172,106,173,174,25,175],"readonly","guard","sql guard","sql","readonly sql guard","erp","effect","read-only","db","just","tool","calls","only","MCP","access","database","query",{"skillNo":177,"name":178,"nameZh":6,"description":179,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":180,"licenseFileUrl":181,"sourceHtmlUrl":182,"categories":183,"keywords":187,"publishedAt":43},"01M6AFY6F7CC2BBZP1QD6VTNVC","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FSKILL.md",[184],{"categoryNo":185,"categoryName":186,"taxonomyType":95,"taxonomyTypeDesc":96},"01JBSEEDCAT000000000000009","前端开发",[188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,103,210],"artifacts builder","web","web artifacts builder","artifacts","builder","state","routing","state management","component","css","frontend","ui","Tools","file","components","shadcn","react","Tailwind","suite","jsx","html","single-file","ui components",{"skillNo":212,"name":213,"nameZh":6,"description":214,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":180,"licenseFileUrl":215,"sourceHtmlUrl":216,"categories":217,"keywords":222,"publishedAt":43},"01M6AFWF33SFV9Z3SF4PEEE4BF","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FSKILL.md",[218,221],{"categoryNo":219,"categoryName":220,"taxonomyType":95,"taxonomyTypeDesc":96},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":185,"categoryName":186,"taxonomyType":95,"taxonomyTypeDesc":96},[223,224,225,226,227,189,228,198,199,229,230,231,232,103,233,107,234],"webapp testing","testing","webapp","browser","playwright","applications","debugging","toolkit","logs","screenshots","local","behavior",{"skillNo":236,"name":237,"nameZh":6,"description":238,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":180,"licenseFileUrl":239,"sourceHtmlUrl":240,"categories":241,"keywords":249,"publishedAt":43},"01M6AF67Q67JJJ5V51JR2P52KA","discernment-nudge","After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals, or emails, estimates or projections, analysis or interpretation of data, factual claims they may rely on, or a multi-step argument — invoke this skill BEFORE finalizing your reply and then, if it applies, append 2-3 short follow-up questions, each tied to something specific in what you just produced, that help the user check key facts, probe the reasoning or assumptions, and notice missing context. Do this at most once per conversation. Skip it when the user asked a trivial how-to or simple lookup, wants a purely educational explanation, asked you only to format, convert, or assemble a file from content they provided, is writing code they will run, is doing creative writing or casual chat, or already asked you to double-check, cite, or review — the skill file explains these boundaries and the exact output format.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fdiscernment-nudge\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fdiscernment-nudge\u002FSKILL.md",[242,245,246],{"categoryNo":243,"categoryName":244,"taxonomyType":95,"taxonomyTypeDesc":96},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":93,"categoryName":94,"taxonomyType":95,"taxonomyTypeDesc":96},{"categoryNo":247,"categoryName":248,"taxonomyType":156,"taxonomyTypeDesc":157},"01JBSEEDCAT000000000000036","内容创作者",[250,251,252,253,254,255,256,257,191,258,201,135,259,260,261,262,263,171,264,25,265,266,267,268,269,113,270],"discernment nudge","nudge","interpretation","help","run","reasoning","data","writing","lookup","content","review","conversation","short","up","invoke","you","analysis","claims","argument","assemble","recommendations"]