[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6EB3S7DQX795TMBBRCDN4Z9":3,"skill-same:01M6EB3S7DQX795TMBBRCDN4Z9":94},{"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":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":50,"commitSha":51,"skillDirectory":52,"forksCount":53,"repositoryHtmlUrl":54,"repositoryHomepageUrl":6,"ownerHtmlUrl":55,"ownerBlogUrl":6,"ownerDescription":56,"updatedAt":57,"install":58,"resources":71},"01M6EB3S7DQX795TMBBRCDN4Z9","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.","luokai0\u002Fai-agent-skills-by-luo-kai","luokai0","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F266954973?v=4","01M6E16VNT42JB8B3X3254QWJ7","luo kai","01M6E16VTFVP6S5XJF1V1MPV90",14,"MIT","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F18-ai-agents-and-automation (by Luo Kai)\u002F16-other-agents\u002Fmodel-pruning\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"model","Model Pruning","Model Compression","Unstructured Pruning","Structured Pruning","One-Shot Pruning","N:M Sparsity","Sparsity","SparseGPT","Wanda","Emerging Techniques","compression","Accelerate","methods","models","minimal","use","Transformers","Fast Inference","fast","2026-11-10 10:12:30",false,"---\nname: 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.\nversion: 1.0.0\nauthor: luo-kai\nlicense: MIT\ntags: [Emerging Techniques, Model Pruning, Wanda, SparseGPT, Sparsity, Model Compression, N:M Sparsity, One-Shot Pruning, Structured Pruning, Unstructured Pruning, Fast Inference]\ndependencies: [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,"tags":44,"author":45,"license":15,"version":46,"description":7,"dependencies":47},[29,20,28,27,26,21,25,24,23,22,37],"luo-kai","1.0.0",[48,49],"transformers","torch","main","4d2fb89cdfb75f3f6fd3c6c5ec9ad90ea129eb3c","ai-agent-skills\u002F18-ai-agents-and-automation (by Luo Kai)\u002F16-other-agents\u002Fmodel-pruning",1,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai","https:\u002F\u002Fgithub.com\u002Fluokai0","a solo builder.","2026-05-06 04:29:04",{"source":8,"skillName":5,"commands":59,"prompt":69,"zipAvailable":70},[60,63,66],{"tool":61,"command":62},"npx","npx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill model-pruning",{"tool":64,"command":65},"bunx","bunx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill model-pruning",{"tool":67,"command":68},"pnpm","pnpm dlx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill model-pruning","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F18-ai-agents-and-automation (by Luo Kai)\u002F16-other-agents\u002Fmodel-pruning\u002FSKILL.md",true,[72,78,82,86,90],{"path":73,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":76,"sourceHtmlUrl":77},"evals\u002Fevals.json","REFERENCE","参考文档",19413,"https:\u002F\u002Fgithub.com\u002Fpattanation\u002FNorvik\u002Fblob\u002Fclaude\u002Finstall-gsd-build-foQdV\u002F.agents\u002Fskills\u002Fgolang-samber-lo\u002Fevals\u002Fevals.json",{"path":79,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002Fadvanced-patterns.md",4491,"https:\u002F\u002Fgithub.com\u002Fpattanation\u002FNorvik\u002Fblob\u002Fclaude\u002Finstall-gsd-build-foQdV\u002F.agents\u002Fskills\u002Fgolang-samber-lo\u002Freferences\u002Fadvanced-patterns.md",{"path":83,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":84,"sourceHtmlUrl":85},"references\u002Fapi-reference.md",18274,"https:\u002F\u002Fgithub.com\u002Fpattanation\u002FNorvik\u002Fblob\u002Fclaude\u002Finstall-gsd-build-foQdV\u002F.agents\u002Fskills\u002Fgolang-samber-lo\u002Freferences\u002Fapi-reference.md",{"path":87,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":88,"sourceHtmlUrl":89},"references\u002Fpackage-guide.md",6293,"https:\u002F\u002Fgithub.com\u002Fpattanation\u002FNorvik\u002Fblob\u002Fclaude\u002Finstall-gsd-build-foQdV\u002F.agents\u002Fskills\u002Fgolang-samber-lo\u002Freferences\u002Fpackage-guide.md",{"path":91,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":92,"sourceHtmlUrl":93},"references\u002Fwanda.md",9492,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F18-ai-agents-and-automation (by Luo Kai)\u002F16-other-agents\u002Fmodel-pruning\u002Freferences\u002Fwanda.md",[95,121,138,168,200,237],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":39},"01M6F2SKTE208174C7S7JJCZC7","write-contracts","Generates secure Aptos Move V2 smart contracts with Object model, Digital Asset integration, security patterns, and storage type guidance. Includes comprehensive storage decision framework for optimal data structure selection. Triggers on: 'write contract', 'create NFT collection', 'build marketplace', 'implement minting', 'generate Move module', 'create token contract', 'build DAO', 'implement staking'. Ask storage questions when: 'store', 'track', 'registry', 'mapping', 'list', 'collection'.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fwrite-contracts\u002FSKILL.md",[],[102,103,104,105,106,107,108,109,19,110,111,112,113,114,115,116,117,118,119,120],"write","contracts","write contracts","storage","secure","create","generate","collection","decision","ask","smart-contracts","selection","objects","structure","nft","token","aptos","critical","move",{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":39},"01M6F2RFXJ6T9MKW0A7N7GM45B","web-search","通用网络搜索技能，支持多引擎搜索（百度、必应、DuckDuckGo），无需API密钥即可获取实时信息","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fweb-search-ex-skill\u002FSKILL.md",[],[128,129,130,131,132,133,134,135,136,137],"web","search","web search","搜索","baidu","bing","duckduckgo","百度","多引擎","internet",{"skillNo":139,"name":140,"nameZh":6,"description":141,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":142,"categories":143,"keywords":149,"publishedAt":39},"01M6F2K968G1FZEZFPW2E6B222","solo-build","Execute implementation plan tasks with TDD workflow, auto-commit, and phase gates. Use when user says \"build it\", \"start building\", \"execute plan\", \"implement tasks\", \"ship it\", or references a track ID. Do NOT use for planning (use \u002Fplan) or scaffolding (use \u002Fscaffold).","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fsolo-build\u002FSKILL.md",[144],{"categoryNo":145,"categoryName":146,"taxonomyType":147,"taxonomyTypeDesc":148},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[150,151,152,153,154,155,156,157,129,158,159,160,102,161,162,163,164,165,166,167],"build","solo","solo build","MCP","workflow","commit","tasks","code","Bash","plan","read","auto","references","context7","query","scaffolding","ship it","project",{"skillNo":169,"name":170,"nameZh":6,"description":171,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":172,"categories":173,"keywords":180,"publishedAt":39},"01M6F2GKN39SGHSPWYB3662YC8","react-email","Use when building HTML email templates with React components, adding a visual email editor to an application using the React Email visual editor, rendering emails to HTML, or sending emails with Resend. Covers welcome emails, password resets, notifications, order confirmations, newsletters, transactional emails, and the embeddable email editor component.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Freact-email-skills\u002FSKILL.md",[174,177],{"categoryNo":175,"categoryName":176,"taxonomyType":147,"taxonomyTypeDesc":148},"01JBSEEDCAT000000000000005","邮件与沟通",{"categoryNo":178,"categoryName":179,"taxonomyType":147,"taxonomyTypeDesc":148},"01JBSEEDCAT000000000000009","前端开发",[181,182,183,184,185,186,187,188,189,190,191,192,193,35,194,195,196,197,198,199],"react","email","react email","github","editor","components","react components","component","welcome","https","notifications","password","node","html","resend","visual","emails","rendering","with",{"skillNo":201,"name":202,"nameZh":6,"description":203,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":204,"categories":205,"keywords":218,"publishedAt":39},"01M6F2FBVGVDFSG8SSFJGXA40C","APITester Agent-Driven API Testing","Test API endpoints and document responses. Define tests in plain English, run them, get formatted results. Agent-driven Postman alternative.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fopenclaw-api-tester\u002FSKILL.md",[206,209,212,213],{"categoryNo":207,"categoryName":208,"taxonomyType":147,"taxonomyTypeDesc":148},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":210,"categoryName":211,"taxonomyType":147,"taxonomyTypeDesc":148},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":145,"categoryName":146,"taxonomyType":147,"taxonomyTypeDesc":148},{"categoryNo":214,"categoryName":215,"taxonomyType":216,"taxonomyTypeDesc":217},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236],"testing","api","api testing","driven","APITester Agent Driven API Testing","test","run","postman","results","plain english","tester","endpoints","document","get","define","tests","english","api-tester",{"skillNo":238,"name":239,"nameZh":6,"description":240,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":241,"categories":242,"keywords":243,"publishedAt":39},"01M6F273Y3NGAPVJZ608BC0G9G","hubspot-implementation-plan","Generate a phased implementation plan from a HubSpot audit report. Creates prioritized, sequenced cleanup processes with effort estimates, dependencies, and automation feasibility. Use after running \u002Fhubspot-audit.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fhubspot-implementation-plan\u002FSKILL.md",[],[159,244,245,246,247,248,249,108,250,251,252,253,254,35,255,256,199,257],"implementation","hubspot","hubspot implementation plan","automation","feasibility","cleanup","planning","report","audit","audit report","phased implementation","dependencies","processes","hubspot audit"]