Pruning Neural Networks: Optimize and Accelerate Inference

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1566 services
Pruning Neural Networks: Optimize and Accelerate Inference
Complex
from 1 week to 3 months
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1317
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1226
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    925
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1156
  • image_logo-advance_0.webp
    B2B Advance company logo design
    620
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    894

Imagine: your trained GPT-like model takes 16 GB and produces a response in 5 seconds on a GPU, but on CPU or edge devices it's unacceptable. Clients complain about delays, infrastructure costs are rising. We constantly encounter this situation: the model is good, but you can't deploy it in production—it's expensive and slow. Pruning neural networks is one of the key tools to fix this.

Pruning—removing insignificant parameters (weights, neurons, attention heads, layers) from a trained neural network. The goal is to reduce model size and speed up inference with minimal quality loss. In the context of LLMs, pruning is often combined with model quantization and distillation for maximum compression.

Why is pruning important for LLMs?

Large language models (LLMs) contain billions of parameters, but many are redundant. Pruning can compress the model 2–4 times without significant degradation, which is critical for edge deployment, reducing GPU costs, and lowering latency. Without pruning, modern LLMs often remain research artifacts—too expensive for real-world application. Weight trimming is a synonym for unstructured pruning.

Types of pruning

  • Unstructured pruning: individual weights are zeroed throughout the matrix. High compression, but requires sparse computation—standard GPUs do not accelerate sparse operations out of the box.
  • Structured pruning: entire structural elements are removed—neurons, attention heads, layers. The result is a truly smaller dense model that runs faster on standard hardware.
  • Semi-structured pruning (N:M sparsity): N weights are removed from each block of M. The 2:4 format is supported by NVIDIA Ampere and later at the hardware level (up to 2× acceleration).
  • Depth pruning: entire layers are removed, reducing model depth.

Which pruning method to choose for your model?

The choice of pruning method depends on the target hardware and quality requirements. Below is a comparison of popular approaches.

Method Pruning type Compression Needs retraining Execution time GPU support
SparseGPT Unstructured up to 60% No Hours Yes (2:4)
Wanda Unstructured up to 60% No Minutes No
LLM-Pruner Structured 25–50% Yes (recovery FT) Days Yes
Depth pruning Structured (layers) 20–40% Yes Hours Yes

Pruning methods with code examples

LLM-Pruner: structured pruning of LLMs

# Example usage of LLM-Pruner
# pip install llm-pruner

from LLMPruner.pruner import LlamaStructuredPruner
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3.1-7B")
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3.1-7B")

pruner = LlamaStructuredPruner(
    model=model,
    tokenizer=tokenizer,
    pruning_ratio=0.25,  # Remove 25% of parameters
)

# Compute parameter importance on calibration data
calibration_data = ["Text for weight importance analysis...", ...]
pruner.get_mask(calibration_data, method="taylor")  # Taylor expansion importance

# Apply mask and prune
pruned_model = pruner.prune()

SparseGPT: efficient unstructured pruning without retraining

From the SparseGPT documentation: SparseGPT can prune 50% of the weights without retraining. — GitHub

# sparsegpt — library from the method authors
# Conceptual code example

from sparsegpt import SparseGPT

sparsegpt = SparseGPT(model)
sparsegpt.fasterprune(
    sparsity=0.5,         # 50% sparsity
    prunen=2,             # N in N:M
    prunem=4,             # M in N:M (2:4 — hardware supported)
    percdamp=0.01,
    blocksize=128,
)

With 2:4 sparsity (50%) on NVIDIA A100/H100, inference acceleration on Tensor Core is about 1.7–2×.

Wanda: simple and effective pruning

# Wanda is simpler than SparseGPT but comparable in quality
# Runs in minutes on a 7B model

def wanda_pruning(model, calibration_loader, sparsity=0.5):
    """Simplified Wanda implementation"""
    for name, module in model.named_modules():
        if isinstance(module, torch.nn.Linear):
            # Accumulate activation statistics
            activation_norms = get_activation_norms(module, calibration_loader)

            # Importance score = |W| * ||X||
            importance = module.weight.abs() * activation_norms

            # Pruning by threshold
            threshold = torch.quantile(importance, sparsity)
            mask = importance > threshold
            module.weight.data *= mask

    return model

Depth pruning: removing layers

For LLMs, middle layers are often less critical than first and last ones:

def depth_prune_llm(model, layers_to_remove: list[int]):
    """Remove specified decoder layers"""
    # For Llama architecture
    remaining_layers = [
        layer for i, layer in enumerate(model.model.layers)
        if i not in layers_to_remove
    ]
    model.model.layers = torch.nn.ModuleList(remaining_layers)
    return model

# Example: remove 8 middle layers out of 32 (25% depth reduction)
pruned_model = depth_prune_llm(model, layers_to_remove=list(range(12, 20)))
# Result: 24-layer model from 32-layer

Practical case: edge deployment optimization

Task: fine-tuned Llama 3.1 8B for an industrial controller (ARM server, 16GB RAM, no GPU). Requirement: inference < 2s per request.

Our optimization strategy:

  1. GGUF Q4_K_M quantization: 8B → 4.1GB, 8 tok/s on CPU (insufficient)
  2. Depth pruning (remove 8 layers out of 32): -25% latency, -3% quality
  3. Width pruning of attention heads (remove 20% heads): -15% latency
  4. Re-quantization: GGUF Q4_K_M on pruned model

Final pruned+quantized model characteristics:

Metric Before optimization After optimization
Size 4.1 GB 3.1 GB
Throughput 8 tok/s 14 tok/s
Latency (100 tokens) 7 s 1.8 s
Quality loss (LLM-judge) 7%

In a typical project with a 7B parameter model, infrastructure savings reach $12,000/month (based on reduced GPU hours). Compare: pruning yields a 2.5× better cost-performance ratio than no optimization. This is 50% better than quantization alone.

Recovery Fine-Tuning after pruning

Pruning always causes degradation. Recovery training restores part of the quality:

# After pruning — brief fine-tuning for recovery
from trl import SFTTrainer, SFTConfig

# Use the same dataset as for fine-tuning, but with a lower LR
recovery_config = SFTConfig(
    num_train_epochs=1,       # 1 epoch for recovery
    learning_rate=5e-5,       # Lower than full fine-tuning
    gradient_checkpointing=True,
    bf16=True,
)
trainer = SFTTrainer(model=pruned_model, args=recovery_config, train_dataset=dataset)
trainer.train()

Recovery fine-tuning typically recovers 50–70% of lost quality with 1 training epoch.

What is included in the work

  • Full documentation of all changes, including pruning masks and recovery steps.
  • Access to all pruned model variants (GGUF, ONNX, TensorRT) for immediate testing.
  • Training session for your team on how to deploy and maintain the optimized model.
  • Support for 3 months after deployment, including troubleshooting and performance monitoring.
  • Additional deliverables: model analysis, pruning strategy, calibration data, benchmarking reports.

Work process: stages and timeline

  1. Analysis: meet, discuss requirements, receive model or dataset. Identify bottlenecks (latency, size, quality).
  2. Design: select pruning and recovery methods, prepare pipeline. Estimate expected effect.
  3. Implementation: perform pruning, recovery fine-tuning using chosen tools.
  4. Testing: compare with original, record metrics (perplexity, latency, throughput).
  5. Deployment: package model, provide integration instructions.

Timeline:

  • Pruning strategy selection: 3–5 days
  • Calibration and pruning: 4–24 hours (depends on method and size)
  • Recovery fine-tuning: 2–8 hours
  • Benchmarking and evaluation: 3–5 days
  • Total: 2–4 weeks

Cost is calculated individually—depends on model size, task complexity, and required quality. Our experience: 5+ years in ML, 10+ projects on model optimization for production. We guarantee transparent results and full documentation.

If you have a similar task, contact us. Request a consultation—we'll tell you how to speed up inference by 2–5× without significant quality loss.