Pruning Techniques for Transformer Models
1. Definition and Motivation for Pruning
Definition and Motivation for Pruning
Conceptual Definition of Pruning
Pruning in the context of transformer models refers to the systematic removal of parameters, neurons, or entire attention heads to reduce model size and computational overhead while preserving performance. Mathematically, pruning can be viewed as imposing sparsity constraints on the weight matrices. For a weight matrix W ∈ ℝm×n, pruning enforces:
where k is the desired number of non-zero weights and ||·||0 denotes the L0 pseudo-norm. The goal is to retain only the most salient weights, discarding those with minimal contribution to model output.
Motivations for Pruning
Pruning is driven by several key factors:
- Computational Efficiency: Large transformer models (e.g., GPT-3, BERT) often contain redundant parameters. Pruning reduces FLOPs and memory usage, enabling deployment on edge devices.
- Inference Speed: Sparse models exhibit faster inference due to reduced memory bandwidth requirements and optimized matrix operations.
- Energy Consumption: Fewer active parameters lead to lower energy usage, critical for sustainable AI deployments.
- Generalization: Pruning can act as an implicit regularizer, improving model robustness by eliminating noisy or overfitted weights.
Historical Context and Evolution
Pruning traces its roots to classical neural network compression techniques like Optimal Brain Damage (LeCun et al., 1990) and has evolved with transformer-specific methods such as:
- Magnitude-based pruning: Removes weights with smallest absolute values.
- Movement pruning: Dynamically prunes during fine-tuning based on weight updates (Sanh et al., 2020).
- Structured pruning: Eliminates entire attention heads or layers rather than individual weights.
Practical Trade-offs
The effectiveness of pruning depends on:
where W' is the pruned weight matrix and ℒ is the loss function. Key challenges include:
- Maintaining gradient flow through pruned architectures
- Balancing sparsity levels across layers (e.g., attention vs. FFN layers)
- Avoiding catastrophic drops in downstream task performance
Emerging Research Directions
Recent work explores:
- Dynamic sparsity: Allowing pruned connections to reactivate during inference
- Neural architecture search (NAS): Automating optimal pruning configurations
- Quantization-aware pruning: Joint optimization with low-bit precision
Key Metrics for Evaluating Pruning Effectiveness
Evaluating the success of pruning techniques in transformer models requires a combination of quantitative and qualitative metrics. These metrics assess not only the reduction in model size but also the preservation of performance and computational efficiency.
Sparsity and Compression Ratio
The most straightforward metrics measure the reduction in model parameters. Sparsity quantifies the percentage of zeroed-out weights:
where \( N_{\text{zero}} \) is the count of pruned weights and \( N_{\text{total}} \) is the total number of weights. Compression ratio complements sparsity by measuring the reduction in model size:
For example, a model pruned to 90% sparsity achieves a compression ratio of 10x. However, these metrics alone are insufficient—they must be evaluated alongside performance retention.
Performance Retention Metrics
Pruning should minimally impact model accuracy. Key evaluation metrics include:
- Task-specific accuracy drop: The difference in accuracy (e.g., F1-score, BLEU, perplexity) between the original and pruned model on validation/test data.
- Relative performance: \( \frac{A_{\text{pruned}}}{A_{\text{original}}} \), where \( A \) is the evaluation metric.
- Performance-sparsity tradeoff curves: Plotting accuracy versus sparsity reveals the Pareto frontier of optimal pruning configurations.
For language models, perplexity increase after pruning is a critical indicator of degradation in language modeling capability.
Computational Efficiency Metrics
The practical benefits of pruning manifest in improved inference efficiency:
- FLOPs reduction: The decrease in floating-point operations during inference, calculated as \( \frac{\text{FLOPs}_{\text{original}} - \text{FLOPs}_{\text{pruned}}}{\text{FLOPs}_{\text{original}}} \).
- Latency improvement: Measured on target hardware under realistic batch sizes.
- Memory footprint reduction: Especially crucial for edge deployment, measured via model size in MB or GPU memory usage.
Note that FLOPs reduction doesn't always translate linearly to speedup due to hardware-specific sparse computation overhead.
Structural Metrics for Pruned Networks
Advanced evaluation considers the structural integrity of the pruned network:
- Layer-wise sensitivity: Measures how pruning different layers affects overall performance, revealing architectural bottlenecks.
- Connectivity preservation: The fraction of original attention heads or feed-forward paths remaining intact.
- Gradient flow analysis: Tracking how pruning affects gradient magnitudes during backpropagation indicates training stability.
Values significantly below 1 suggest the pruned model may struggle to learn effectively.
Robustness and Generalization
Pruned models should maintain robustness properties:
- Out-of-distribution (OOD) performance drop: Evaluate on domain-shifted or adversarial datasets.
- Calibration metrics: Pruning can affect model confidence calibration; measure via Expected Calibration Error (ECE).
Recent studies show that over-pruning can disproportionately harm OOD performance compared to in-distribution accuracy.
Hardware-Aware Metrics
For deployment-focused evaluation:
- Actual speedup: Benchmarked wall-clock time on target CPUs/GPUs/TPUs, accounting for sparse operation overhead.
- Energy efficiency: Measured in joules per inference, particularly for edge devices.
- Hardware utilization: Profile memory bandwidth usage and compute unit occupancy.
Modern accelerators like NVIDIA's Ampere architecture achieve better speedups at high sparsity levels (e.g., 2-4x at 90% sparsity) compared to older hardware.

Trade-offs: Performance vs. Model Size
Pruning transformer models introduces a fundamental trade-off between computational efficiency and model performance. The relationship between sparsity and accuracy is nonlinear, often following a power-law distribution where initial pruning yields minimal accuracy loss, but aggressive sparsity leads to rapid degradation. This behavior can be modeled empirically using a modified Pareto frontier:
where s represents sparsity ratio, ℒ0 is the baseline loss, and α, β are dataset-dependent coefficients. For transformer architectures, β typically falls between 2.1-3.3, explaining the steep performance cliff observed beyond 70-80% sparsity.
Architectural Sensitivity to Pruning
Attention mechanisms exhibit non-uniform sensitivity to pruning across layers. The key observations:
- Early layers tolerate higher sparsity (50-70%) due to redundant feature extraction
- Middle attention layers require careful pruning (30-50%) to maintain relational reasoning
- Final layers demand the lowest sparsity (10-30%) for precise output generation
This sensitivity profile emerges from the gradient flow dynamics during fine-tuning, where Hessian-based analysis reveals attention heads in later layers have significantly higher Fisher information values.
Quantitative Trade-off Analysis
The performance-size trade-off can be quantified through the compression-accuracy product (CAP):
Modern sparse transformers achieve CAP improvements of 3-5× over dense baselines. For example, a 70% pruned BERT model typically shows:
| Metric | Dense | Pruned |
|---|---|---|
| Parameters | 110M | 33M |
| GLUE Score | 80.5 | 78.2 |
| Inference Latency | 142ms | 63ms |
Practical Optimization Strategies
Optimal pruning requires balancing multiple constraints:
- Task-aware pruning: GLUE tasks tolerate 2-3× more sparsity than generative tasks
- Hardware-aware sparsity: Structured pruning patterns that match accelerator architectures (e.g., 4:2 sparsity for NVIDIA Ampere)
- Dynamic recovery: Alternating pruning phases with recovery training epochs
The most effective approaches combine magnitude-based pruning for initial compression with movement pruning during fine-tuning, achieving 60-70% sparsity with <1% accuracy drop on most NLP benchmarks.
Emergent Research Directions
Recent work in learned sparsity demonstrates potential to break traditional trade-off curves:
- Differentiable pruning masks with Gumbel-softmax sampling
- Attention head importance prediction using auxiliary networks
- Block-sparse patterns optimized for specific hardware
These methods show promise in pushing the Pareto frontier, with some achieving 80% sparsity while maintaining 95% of original model accuracy through dynamic, input-dependent pruning.

2. Structured vs. Unstructured Pruning
Structured vs. Unstructured Pruning
Definition and Core Differences
Pruning in transformer models involves removing redundant or less important parameters to reduce computational overhead while preserving model performance. The two primary approaches—structured and unstructured pruning—differ fundamentally in their granularity and hardware implications.
- Unstructured pruning removes individual weights or neurons without regard to their position in the network. This results in a sparse weight matrix where zeroed-out values are distributed irregularly.
- Structured pruning removes entire blocks of parameters (e.g., attention heads, layers, or channels), maintaining dense matrix operations that align with hardware acceleration.
Mathematical Formulation
For a weight matrix W ∈ ℝm×n, unstructured pruning applies an element-wise mask M:
where M is a binary mask with Mi,j ∈ {0,1}. In contrast, structured pruning removes entire rows, columns, or blocks. For example, pruning k attention heads in a transformer layer modifies the multi-head attention output:
Hardware and Efficiency Trade-offs
Unstructured pruning achieves higher theoretical sparsity (e.g., 90%+ zeroes) but requires specialized sparse computation libraries (e.g., CuSPARSE) to realize speedups. Structured pruning, while less aggressive in sparsity, leverages existing dense linear algebra kernels (e.g., BLAS) and achieves predictable latency reductions. Recent work shows that:
- NVIDIA A100 GPUs achieve 2-4× speedup with 50% structured sparsity but only 1.2× with 90% unstructured sparsity.
- Structured pruning reduces memory bandwidth requirements proportionally to the pruning ratio, whereas unstructured pruning often requires metadata storage for sparse formats (CSR, COO).
Practical Implementation
Popular libraries implement these techniques differently:
- Unstructured: Magnitude pruning via torch.nn.utils.prune removes weights below a threshold.
- Structured: TorchPruner uses L1-norm of filters or attention heads to rank and remove entire structures.
For transformers, structured pruning often targets:
- Heads in multi-head attention (e.g., reducing 12 → 8 heads)
- Feed-forward network intermediate dimensions (e.g., 2048 → 1024)
- Entire encoder/decoder layers (layer dropping)
Case Study: BERT Pruning
On the GLUE benchmark, structured pruning of 40% attention heads preserves 98% of the original BERT-base accuracy while reducing FLOPs by 35%. Unstructured pruning achieves 50% sparsity but requires retraining with distillation to recover performance.

2.2 Magnitude-Based Pruning
Magnitude-based pruning is one of the simplest and most widely used techniques for reducing the size of transformer models. The core idea is to remove weights with the smallest magnitudes, under the assumption that these contribute least to the model's performance. This approach is computationally efficient and requires no additional training data, making it attractive for practical deployment scenarios.
Mathematical Formulation
Given a weight matrix W ∈ ℝm×n, magnitude-based pruning involves selecting a sparsity level s (e.g., 50%) and zeroing out the smallest s% of weights by absolute value. Formally, the pruned weight matrix W' is computed as:
where τ is the threshold determined by the target sparsity s. The threshold can be found by sorting all weights by magnitude and selecting the value at the s-th percentile.
Iterative Magnitude Pruning
One-shot pruning to high sparsity levels often leads to significant accuracy drops. Instead, iterative magnitude pruning (IMP) gradually increases sparsity over multiple training epochs:
- Train the model to convergence
- Prune a small fraction of weights (e.g., 20%)
- Fine-tune the remaining weights
- Repeat until target sparsity is reached
This approach allows the network to adapt to the pruning process, preserving more of its original performance. The Lottery Ticket Hypothesis suggests that IMP works because it discovers sparse subnetworks that were already present in the original dense network.
Practical Considerations
When applying magnitude pruning to transformers, several architectural factors must be considered:
- Attention Heads: Pruning entire attention heads (structured pruning) often works better than pruning individual weights in attention layers
- Layer Sensitivity: Later layers typically tolerate higher sparsity than early layers
- Embedding Layers: These are usually left unpruned or pruned lightly due to their critical role in input representation
Recent work has shown that magnitude pruning can achieve 60-80% sparsity in transformer models with minimal accuracy loss when combined with proper fine-tuning. The technique is particularly effective when applied to larger models, which tend to have more redundant parameters.
Extensions and Variants
Several improvements to basic magnitude pruning have been proposed:
- Layer-adaptive thresholds: Using different τ values per layer based on their sensitivity
- Block pruning: Pruning entire blocks of weights together to improve hardware efficiency
- Movement pruning: Considering both weight magnitudes and their changes during training
This hybrid approach often outperforms pure magnitude-based methods by capturing both the static and dynamic importance of weights.

Gradient-Based Pruning
Gradient-based pruning leverages the gradients of the loss function with respect to the model parameters to determine the importance of weights, attention heads, or entire layers. Unlike magnitude-based pruning, which only considers absolute weight values, gradient-based methods capture the dynamic contribution of each parameter to the learning process. This approach is particularly effective in transformer models, where gradients provide a more nuanced signal of parameter importance.
Mathematical Foundation
The importance score Iij for a weight wij in a transformer model can be computed using the gradient gij of the loss function L with respect to the weight:
This score combines both the weight magnitude and its gradient, ensuring that parameters contributing significantly to the loss landscape are preserved. For structured pruning (e.g., attention heads or layers), the importance is aggregated across all weights in the structure:
Implementation Steps
- Compute Gradients: During a forward-backward pass, store the gradients of the loss with respect to all trainable parameters.
- Calculate Importance Scores: For each weight, compute the product of its value and the corresponding gradient magnitude.
- Rank Parameters: Sort all parameters (or structures) by their importance scores in descending order.
- Prune Least Important: Remove the bottom-k parameters or structures based on a predefined sparsity target.
- Fine-Tune: Retrain the pruned model to recover any lost performance.
Variants and Enhancements
Taylor Expansion-Based Pruning
An extension of gradient-based pruning uses a first-order Taylor expansion to approximate the change in loss if a parameter were pruned:
This justifies the use of Iij as a proxy for the actual impact on the loss. Higher-order terms are typically neglected due to computational constraints.
Iterative Gradient Pruning
Instead of one-shot pruning, gradients can be evaluated over multiple training iterations to account for dynamic parameter importance. The importance score is then accumulated as an exponential moving average:
where β controls the smoothing factor. This mitigates noise in gradient estimates and leads to more stable pruning decisions.
Practical Considerations
- Gradient Noise: Stochastic gradients in mini-batch training can introduce variance in importance scores. Larger batch sizes or gradient averaging improves reliability.
- Memory Overhead: Storing gradients for all parameters doubles the memory footprint during pruning. This can be prohibitive for very large models.
- Dynamic Sparsity: Gradient signals evolve during training, so iterative pruning often outperforms one-shot approaches.
Case Study: Pruning BERT
In Movement Pruning (Sanh et al., 2020), gradients are used to learn a soft mask over weights during fine-tuning. The mask values are optimized via gradient descent, and weights are gradually zeroed out based on their importance. This approach achieves 95% sparsity in BERT while retaining 98% of the original accuracy on downstream tasks.

Lottery Ticket Hypothesis in Transformers
The Lottery Ticket Hypothesis (LTH), introduced by Frankle & Carbin (2019), posits that dense neural networks contain sparse subnetworks ("winning tickets") that, when trained in isolation, can match or exceed the performance of the original network. This principle has been extended to Transformer models, offering a framework for efficient pruning while preserving model accuracy.
Mathematical Formulation
Given a Transformer model with parameters θ and a binary mask m ∈ {0,1}|θ|, the LTH seeks a subnetwork θ ⊙ m (where ⊙ denotes element-wise multiplication) that satisfies:
where L is the loss function. The optimal mask m is found through iterative magnitude pruning:
- Train the model to convergence, obtaining parameters θ0
- Prune the smallest magnitude weights, generating mask mk at step k
- Reset remaining weights to their initial values θ0 ⊙ mk
- Retrain the pruned network
Adaptations for Transformer Architectures
Transformers present unique challenges for LTH due to their attention mechanisms and layer normalization. Key adaptations include:
- Structured Pruning: Pruning entire attention heads or feed-forward neurons rather than individual weights maintains architectural integrity
- Layer-wise Sparsity: Applying different sparsity levels to query/key/value projections and feed-forward layers based on their sensitivity
- Dynamic Masking: Allowing pruned connections to regrow during training, as proposed in RigL (Evci et al., 2020)
where Wl represents weights at layer l, and ||·||F is the Frobenius norm. Layers with higher sensitivity are pruned less aggressively.
Empirical Results in Transformers
Recent studies demonstrate that:
- BERT models retain 90% of original performance at 70-80% sparsity when using iterative magnitude pruning
- Attention heads exhibit varying importance across layers, with middle layers often containing the most critical heads
- Winning tickets found in pre-trained models transfer better across tasks than those found through task-specific pruning
Practical Implementation Considerations
When applying LTH to Transformers:
- Use gradual pruning schedules (e.g., 20% pruning every 10k steps) rather than one-shot pruning
- Maintain sparsity in embedding layers below 50% to preserve semantic information
- Combine LTH with quantization for additional compression benefits
- Monitor task-specific metrics (not just loss) when evaluating subnetworks
The figure below illustrates the iterative pruning process for a Transformer model:

3. Iterative Pruning and Fine-Tuning
3.1 Iterative Pruning and Fine-Tuning
Iterative pruning and fine-tuning is a structured approach to model compression where pruning and retraining are performed in cycles, allowing the model to recover lost accuracy incrementally. Unlike one-shot pruning, which removes weights in a single step, iterative pruning gradually eliminates redundant parameters while maintaining performance through intermediate fine-tuning phases.
Mathematical Formulation
The process can be formalized as an optimization problem where the goal is to minimize the loss function L under a sparsity constraint. Let θ denote the model parameters, and let S be the target sparsity level. At each iteration t, the following steps are executed:
Here, η is the learning rate, and St is the sparsity level at iteration t, typically increased gradually (e.g., from 10% to 90%). The Prune function removes weights based on a criterion such as magnitude, gradient importance, or Hessian-based sensitivity.
Pruning Criteria
Common criteria for selecting weights to prune include:
- Magnitude-based pruning: Removes weights with the smallest absolute values.
- Gradient-based pruning: Prioritizes weights with the least impact on the loss gradient.
- Second-order pruning: Uses the Hessian matrix to identify weights that minimally affect the loss curvature.
Implementation Workflow
A typical iterative pruning pipeline consists of the following steps:
- Train the model to convergence on the target dataset.
- Prune a small fraction of weights (e.g., 10-20%) based on the selected criterion.
- Fine-tune the pruned model to recover lost accuracy.
- Repeat steps 2-3 until the desired sparsity level is achieved.
Practical Considerations
Key hyperparameters influencing performance include:
- Pruning schedule: Linear, exponential, or step-wise increase in sparsity.
- Fine-tuning duration: Number of epochs per iteration.
- Learning rate adaptation: Often reduced during later fine-tuning phases.
Empirical studies show that iterative pruning outperforms one-shot pruning, particularly for high sparsity levels (>80%), as it allows the network to adapt its remaining connections more effectively. For example, in BERT models, iterative magnitude pruning with gradual sparsity increase retains >90% of the original accuracy at 90% sparsity.
Case Study: Pruning Vision Transformers
When applied to Vision Transformers (ViTs), iterative pruning often focuses on attention heads and MLP layers. Research indicates that:
- Attention heads exhibit varying importance, with many being redundant.
- MLP layers can be pruned aggressively while maintaining performance.
For a ViT-Base model (86M parameters), iterative pruning achieves 60% sparsity with <1% accuracy drop on ImageNet by removing less important attention heads and MLP neurons.
where Ai(j) is the attention matrix for head i in sample j, and N is the number of samples.

Dynamic Pruning During Training
Dynamic pruning adjusts model sparsity during training rather than as a post-training step. Unlike static pruning, which removes weights once and permanently, dynamic pruning allows weights to regrow based on gradient signals, enabling adaptive sparsity patterns that evolve with the optimization process. This approach mitigates the risk of irreversible pruning decisions that may harm model convergence.
Gradient-Based Importance Scoring
The core mechanism of dynamic pruning relies on scoring weight importance using gradient information. A common formulation computes the importance score Sij for weight wij as:
where ∇wijℒ is the gradient of the loss ℒ with respect to wij. Weights with scores below a threshold τ are pruned, while others are retained. The threshold can be adjusted dynamically to maintain a target sparsity level s:
where top-k selects the k-th largest score to enforce s% sparsity. This ensures the model remains within computational constraints while allowing important weights to regrow.
Iterative Pruning Schedules
Dynamic pruning typically follows an iterative schedule, alternating between pruning and training phases. The pruning rate often increases gradually to avoid abrupt performance degradation. A common schedule uses a cubic interpolation from initial sparsity si to final sparsity sf over N steps:
where t is the current training step. This allows the model to adapt progressively to higher sparsity levels.
Regrowth Mechanisms
To compensate for overly aggressive pruning, dynamic methods often include regrowth of previously pruned weights. One approach reinitializes pruned weights with small random values if their gradients exceed a reactivation threshold. Another strategy redistributes the budget by regrowing weights with the highest gradient magnitudes, ensuring exploration of new connectivity patterns.
Practical Considerations
- Memory Overhead: Dynamic pruning requires storing masks and gradient histories, increasing memory usage by ~15–20% compared to static pruning.
- Convergence Stability: The alternating prune-train cycle can introduce oscillations. Momentum correction (e.g., scaling optimizer momentum for pruned weights) is often necessary.
- Hardware Support: Sparse matrix operations must leverage specialized kernels (e.g., NVIDIA’s Sparse Tensor Cores) to realize speedups.
Empirical studies show dynamic pruning can achieve 80–90% sparsity in transformer models like BERT with <1% accuracy drop, outperforming static pruning by 2–4% on downstream tasks.
Layer-Specific Pruning Strategies
Layer-specific pruning acknowledges that not all layers in a transformer model contribute equally to its performance. Sensitivity analysis reveals that attention heads and feed-forward layers exhibit varying importance depending on their depth and position in the architecture. This observation motivates targeted pruning strategies that adapt to layer-specific characteristics.
Attention Head Pruning
Multi-head attention layers often contain redundant heads that can be removed with minimal impact on model performance. The importance score Ih for head h in layer l can be computed using gradient-based metrics:
where Ah(l) represents the attention weights for head h, ℒ is the loss function, and N is the number of samples. Heads with scores below a learned threshold τh are pruned, with the threshold adapted per layer using:
where μ(l) and σ(l) are the mean and standard deviation of importance scores in layer l, and α controls the pruning aggressiveness.
Feed-Forward Network Pruning
Feed-forward layers exhibit different pruning characteristics, with intermediate dimensions often overparameterized. Structured pruning works particularly well here by removing entire neurons based on their L2 norm:
where W(l) is the weight matrix of layer l and sj represents the importance of neuron j. Layer-wise adaptive thresholds ensure balanced pruning across depths:
where β is the target compression ratio and d(l) is the original layer width.
Embedding Layer Compression
Token embedding layers require special consideration due to their discrete input space. Dimensionality reduction through:
where Wc is a learned compression matrix, proves more effective than direct pruning. The compression ratio can vary across layers, with lower layers typically tolerating more aggressive reduction.
Layer-Wise Sparsity Allocation
Optimal sparsity distribution follows a predictable pattern across transformer depths. Empirical studies show that middle layers can sustain higher sparsity than input/output-proximate layers. The layer-wise sparsity s(l) can be parameterized as:
where L is the total number of layers and γ controls the curvature of the sparsity distribution. This quadratic allocation matches the observed sensitivity profile of transformer models.
Practical implementations often combine these strategies, with attention head pruning applied to early layers, feed-forward pruning dominating middle layers, and embedding compression reserved for input/output layers. The resulting models maintain >90% of original performance while achieving 3-5× compression rates in production environments.

4. Pruning in Popular Frameworks (PyTorch, TensorFlow)
Pruning in Popular Frameworks (PyTorch, TensorFlow)
PyTorch Pruning Implementation
PyTorch provides built-in support for pruning through the torch.nn.utils.prune module. The framework supports both unstructured and structured pruning, with methods like l1_unstructured, random_unstructured, and ln_structured. Pruning in PyTorch follows a three-step process:
- Parameter Selection: Identify the weights or neurons to prune (e.g.,
nn.Linearlayers). - Pruning Application: Apply a pruning mask using one of the available methods.
- Permanent Removal: Make pruning permanent by removing zeroed-out weights.
import torch.nn.utils.prune as prune
model = ... # Pretrained transformer model
parameters_to_prune = [(module, 'weight') for module in model.modules()
if isinstance(module, torch.nn.Linear)]
prune.global_unstructured(
parameters_to_prune,
pruning_method=prune.L1Unstructured,
amount=0.4 # Prune 40% of weights
)
PyTorch also supports custom pruning functions by subclassing BasePruningMethod. For transformer models, iterative magnitude pruning is often applied to attention heads and feed-forward layers.
TensorFlow Pruning API
TensorFlow's pruning implementation is available through the tensorflow_model_optimization toolkit. The PruneLowMagnitude wrapper enables gradual pruning during training via the following steps:
where t is current training step and T is total steps. This polynomial decay schedule prevents aggressive early pruning.
import tensorflow_model_optimization as tfmot
pruning_params = {
'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(
initial_sparsity=0.30,
final_sparsity=0.70,
begin_step=2000,
end_step=8000
)
}
model_for_pruning = tfmot.sparsity.keras.prune_low_magnitude(
original_model, **pruning_params
)
Framework-Specific Considerations
When pruning transformer models, key differences emerge between frameworks:
| Feature | PyTorch | TensorFlow |
|---|---|---|
| Attention Head Pruning | Manual mask implementation | Built-in structured pruning |
| Gradient Flow | Pruned weights remain in computation graph | Optionally removes pruned weights entirely |
| Quantization Compatibility | Separate optimization step | Joint pruning-quantization API |
For BERT-like architectures, TensorFlow's PruneLowMagnitude typically achieves higher compression rates while PyTorch offers more flexibility for custom pruning strategies. Both frameworks support exporting pruned models to ONNX format for deployment.
Advanced Pruning Techniques
Recent research has introduced hybrid approaches combining framework capabilities with custom implementations:
- Movement Pruning: Uses gradient signals rather than magnitude, implemented via PyTorch hooks
- Block Sparse Patterns: Enables structured pruning for hardware acceleration
- Learned Thresholding: Trainable parameters determine pruning thresholds
where λ controls the sparsity penalty strength. Modern implementations often use layer-wise adaptive λ values based on sensitivity analysis.
Case Study: Pruning BERT for Efficiency
BERT Architecture and Pruning Targets
The BERT (Bidirectional Encoder Representations from Transformers) architecture consists of multiple transformer encoder layers, each containing self-attention mechanisms and feed-forward networks. Pruning BERT involves identifying and removing redundant parameters while preserving model performance. Key pruning targets include:
- Attention heads: Some heads contribute minimally to the model's performance.
- Feed-forward neurons: Certain neurons in intermediate layers can be pruned without significant accuracy loss.
- Embedding dimensions: Reducing the dimensionality of token embeddings can decrease memory usage.
Magnitude-Based Weight Pruning
Magnitude-based pruning removes weights with the smallest absolute values, assuming they contribute least to the model's output. For a given weight matrix W ∈ ℝm×n, the pruning process follows:
where τ is a threshold determined by the desired sparsity level. For BERT, this is often applied iteratively during fine-tuning to allow the model to adapt to the sparsity pattern.
Structured Pruning of Attention Heads
Structured pruning removes entire attention heads, reducing computational overhead in self-attention layers. The importance of head i in layer l can be quantified using the head importance score:
where Hli represents the output of head i, L is the loss function, and D is the validation dataset. Heads with the lowest scores are pruned first.
Layer Dropout for Dynamic Sparsity
LayerDrop introduces structured sparsity by randomly dropping entire layers during training. For a model with L layers, each layer is retained with probability p:
This encourages the model to be robust to missing layers, enabling aggressive pruning during inference.
Knowledge Distillation with Pruned BERT
Pruned BERT models often suffer from accuracy degradation. Knowledge distillation mitigates this by training the pruned model (student) to mimic the predictions of the original model (teacher). The distillation loss combines task-specific loss Ltask and KL divergence:
where T is the temperature scaling factor and α balances the two objectives.
Empirical Results on GLUE Benchmark
Recent studies show that BERT-base can be pruned to 40% sparsity with <1% accuracy drop on GLUE tasks. Key findings include:
- Attention heads in middle layers are more redundant than those in early or late layers.
- Magnitude pruning outperforms random pruning by 2-3% in accuracy at high sparsity levels.
- Combining pruning with quantization achieves 8× compression with negligible performance loss.
Practical Implementation Considerations
When implementing BERT pruning:
- Use gradual pruning schedules to allow model adaptation (e.g., cubic sparsity increase from 0% to target over training).
- Employ rewinding to reset weights to early training snapshots before fine-tuning the pruned model.
- Leverage hardware-aware pruning to optimize for specific inference accelerators.

4.3 Debugging and Validating Pruned Models
After pruning a transformer model, rigorous validation is necessary to ensure performance degradation remains within acceptable bounds. Unlike traditional neural networks, transformers exhibit unique failure modes due to their reliance on self-attention mechanisms and residual connections. Debugging involves both quantitative metrics and qualitative inspection of attention patterns.
Quantitative Validation Metrics
The primary metrics for evaluating pruned models include:
- Task-specific performance drop: Measure accuracy, BLEU score, or other relevant metrics on a held-out validation set. A drop of more than 2-5% typically indicates problematic pruning.
- Perplexity increase: For language models, perplexity should not rise significantly post-pruning. A 10-15% increase is often the upper limit.
- Latency and memory footprint: Verify that the theoretical FLOPs reduction translates to actual speedups, accounting for hardware-specific bottlenecks.
where ΔP is the relative performance drop and P represents the evaluation metric.
Attention Head Analysis
Pruning often disrupts critical attention heads. To diagnose issues:
- Visualize attention maps before and after pruning for key examples. Sudden loss of diagonal patterns or long-range dependencies indicates over-pruning.
- Compute head importance scores using gradient-based methods like:
where Ah is the attention matrix for head h and ℒ is the loss function.
Gradient Flow Inspection
Pruned transformers frequently suffer from gradient starvation in remaining layers. Use these diagnostic techniques:
- Gradient norm ratios between layers should remain within one order of magnitude. Compute:
for all layer pairs (i,j). Ratios rij > 10 indicate potential blockages.
- Hessian spectrum analysis reveals loss landscape changes. A significant increase in condition number suggests optimization difficulties.
Recovery Techniques
When validation uncovers issues, consider these corrective measures:
- Targeted rewinding: Reinitialize problematic layers to their pre-trained weights while keeping others pruned.
- Progressive unfreezing during fine-tuning helps recover lost capacity gradually.
- Architecture-aware distillation from the original model can compensate for pruned attention heads.
For vision transformers, spatial attention patterns require special validation. The mean intersection-over-union (mIoU) between original and pruned attention maps should exceed 0.7 for critical layers.

5. Key Research Papers on Transformer Pruning
5.1 Key Research Papers on Transformer Pruning
- TPrune: Efficient Transformer Pruning for Mobile Devices — Current model compression techniques for Transformer models mainly fall into three categories: Model Pruning, Transfer Learning, and Efficient Transformer Variants. Model Pruning method fine-tunes the original pre-trained model to force the weights [13, 14, 15] or activations [16, 17, 18] to be zeros as much as possible. A transformer model may ...
- Efficient label-free pruning and retraining for Text-VQA Transformers — The majority of Transformer pruning techniques [8], [12], [13], [25] are integrated into the training process. Regularization on weights or mask variables induces sparsity during learning [8], [12], [14]. Additionally, researchers have proposed post-training pruning techniques [10], [11] that are applied to trained models. Several existing post ...
- A Fast Post-Training Pruning Framework for Transformers - ar5iv — To address the above limitations, we propose a fast post-training pruning framework for Transformers that does not require any retraining of the models. As illustrated in Figure 1, our framework takes as input a Transformer model, a sample dataset, and a FLOPs/latency constraint.It then outputs a pruned Transformer model that can be deployed immediately.
- PDF Global Vision Transformer Pruning with Hessian-Aware Saliency — To improve model efficiency, very recent works perform structural pruning on vision transformer models, with train-able gate variables [53] or Taylor importance score [5]. Both methods show the potential of compressing ViT models, yet only consider part of the prunable architecture, use uniform
- Adaptive Pruning of Pretrained Transformer via Differential Inclusions — The process of pruning a Transformer model is twofold: first targeting the MLP and then the Attention mechanism. Approaches such as WDpruning (Yu et al., 2022 ) employ a mask-based technique. Specifically, a mask M 𝑀 M italic_M is defined to correspond to each column of the MLP's weight matrix, and pruning is conducted by considering the ...
- PDF Latency-aware structured pruning of pretrained transformer-based models — able latency-aware pruning for Transformer-based models on a target device. LAP-NAS prunes the model, then performs an efficient architecture search using pruning metrics and layer-wise latency measurements to reduce latency while maintaining accuracy. This technique combines the simplicity and speed of iterative pruning with the design space
- Magnitude Pruning of Large Pretrained Transformer Models with a Mixture ... — evaluated on large transformer models across different tasks and datasets. Moreover, as we will discuss in Section 2.3, several key challenges prevent us from directly adopting their methods for pruning larger models. In this work, we introduce MGPP, a magnitude-based iterative pruning algorithm that is both simple and effective.
- PDF A Fast Post-Training Pruning Framework for Transformers - NeurIPS — training pruning framework for Transformers that does not require any retraining. Given a resource constraint and a sample dataset, our framework automatically prunes the Transformer model using structured sparsity methods. To retain high accuracy without retraining, we introduce three novel techniques: (i) a lightweight
- PDF The Role of Token Pruning in E cient Transformer Architectures — Token pruning methods can be categorized based on several key dimensions, in- cluding whether pruning decisions are static or dynamic, whether the pruning mechanism is heuristic-based or learnable, and whether pruning is applied at a
- Efficient Transformer Inference Through Hybrid Dynamic Pruning — In the world of deep learning, transformer models have become very significant, leading to improvements in many areas from understanding language to recognizing images, covering a wide range of applications. Despite their success, the deployment of these models in real-time applications, particularly on edge devices, poses significant challenges due to their computational intensity and memory ...
5.2 Open-Source Libraries and Repositories
- TPrune: Efficient Transformer Pruning for Mobile Devices — Current model compression techniques for Transformer models mainly fall into three categories: Model Pruning, Transfer Learning, and Efficient Transformer Variants. Model Pruning method fine-tunes the original pre-trained model to force the weights [13, 14, 15] or activations [16, 17, 18] to be zeros as much as possible. A transformer model may ...
- PDF PLATON: Pruning Large Transformer Models with Upper Confidence Bound of ... — iterative pruning (Han et al.,2015b;Zhu & Gupta,2018; Paganini & Forde,2020;Louizos et al.,2018;Sanh et al., 2020). One-shot pruning specifies the sparsity pattern of a fully-trained dense model based on the weights' importance scores, and then trains a sparse model via "rewinding" (i.e., prune the fully-trained model and then re-train ...
- Efficient label-free pruning and retraining for Text-VQA Transformers — These post-training structured pruning techniques for Transformers have been evaluated on BERT, a Transformer encoder architecture used in NLP benchmarks [17]. This paper focuses on post-training structured pruning of autoregressive Transformers 1 for Text-VQA, particularly emphasizing a setting that does not rely on a labeled dataset.
- A Fast Post-Training Pruning Framework for Transformers - ar5iv — To address the above limitations, we propose a fast post-training pruning framework for Transformers that does not require any retraining of the models. As illustrated in Figure 1, our framework takes as input a Transformer model, a sample dataset, and a FLOPs/latency constraint.It then outputs a pruned Transformer model that can be deployed immediately.
- PDF Latency-aware structured pruning of pretrained transformer-based models — able latency-aware pruning for Transformer-based models on a target device. LAP-NAS prunes the model, then performs an efficient architecture search using pruning metrics and layer-wise latency measurements to reduce latency while maintaining accuracy. This technique combines the simplicity and speed of iterative pruning with the design space
- A Fast Post-Training Pruning Framework for Transformers - arXiv.org — Pruning is an effective way to reduce the huge inference cost of Transformer models. However, prior work on pruning Transformers requires retraining the models. This can add high training cost and high complexity to model deployment, making it difficult to use in many practical situations. To address this, we propose a fast post-
- PDF A Fast Post-Training Pruning Framework for Transformers - NeurIPS — training pruning framework for Transformers that does not require any retraining. Given a resource constraint and a sample dataset, our framework automatically prunes the Transformer model using structured sparsity methods. To retain high accuracy without retraining, we introduce three novel techniques: (i) a lightweight
- torch-pruning 1.5.2 on PyPI - Libraries.io - security & maintenance ... — Torch-Pruning (TP) is a framework for structural pruning with the following features: General-purpose Pruning Toolkit: TP enables structural pruning for a wide range of deep neural networks. Different from torch.nn.utils.prune that zeroizes parameters via masking, Torch-Pruning deploys an algorithm called ⚡ DepGraph to group and remove coupled parameters.
- Differentiable Subset Pruning of Transformer Heads Open Access - MIT Press — Abstract. Multi-head attention, a collection of several attention mechanisms that independently attend to different parts of the input, is the key ingredient in the Transformer. Recent work has shown, however, that a large proportion of the heads in a Transformer's multi-head attention mechanism can be safely pruned away without significantly harming the performance of the model; such ...
- VainF/Torch-Pruning - GitHub — The above example shows the core algorithm, DepGraph, that captures the dependencies in structural pruning. The target layer model.conv1 is coupled with multiple layers, necessitating their simultaneous removal in structural pruning. We can print the group to take a look at the internal dependencies.
5.3 Recommended Books and Tutorials
- TPrune: Efficient Transformer Pruning for Mobile Devices — Current model compression techniques for Transformer models mainly fall into three categories: Model Pruning, Transfer Learning, and Efficient Transformer Variants. Model Pruning method fine-tunes the original pre-trained model to force the weights [13, 14, 15] or activations [16, 17, 18] to be zeros as much as possible. A transformer model may ...
- TPrune: Efficient Transformer Pruning for Mobile Devices — Nonetheless, previous Transformer pruning works did not perform a thorough model analysis and evaluation on each Transformer component on off-the-shelf mobile devices. In this work, we analyze and prune transformer models at the line-wise granularity and also implement our pruning method on real mobile platforms.
- Efficient label-free pruning and retraining for Text-VQA Transformers — The majority of Transformer pruning techniques [8], [12], [13], [25] are integrated into the training process. Regularization on weights or mask variables induces sparsity during learning [8], [12], [14]. Additionally, researchers have proposed post-training pruning techniques [10], [11] that are applied to trained models. Several existing post ...
- A Fast Post-Training Pruning Framework for Transformers - arXiv.org — Pruning is an effective way to reduce the huge inference cost of Transformer models. However, prior work on pruning Transformers requires retraining the models. This can add high training cost and high complexity to model deployment, making it difficult to use in many practical situations. To address this, we propose a fast post-
- PDF A Fast Post-Training Pruning Framework for Transformers - NeurIPS — training pruning framework for Transformers that does not require any retraining. Given a resource constraint and a sample dataset, our framework automatically prunes the Transformer model using structured sparsity methods. To retain high accuracy without retraining, we introduce three novel techniques: (i) a lightweight
- PDF Differentiable Subset Pruning of Transformer Heads - ACL Anthology — model size shrinkage.2 Our experiments also suggest several broader conclusions about pruning Transformers. In this paper, we taxonomize existing pruning methods into two pruning paradigms: pipelined pruning and joint pruning. Pipelined pruning consists of two stages: (i) training or fine-tuning an over-parameterized model on the target task ...
- (PDF) transformer Design guide - Academia.edu — This guide serves as a comprehensive resource for understanding transformer technology within electric power engineering. ... Electrical and Electronic Engineering, 2012 ... The bibliographic research presented in this paper is important because it includes and analyzes the best research papers on transformers coming from many countries all ...
- PDF Transformer Engineering: Design, Technology, and Diagnostics — engineers in the transformer industry and the student community. A few improvements have been incorporated in the other chapters as well. Understanding the basics of electromagnetic fields is an essential prerequisite for doing advanced computations. Chapter 12 explains the field theory relevant to transformer engineering in a simple manner.
- Differentiable Subset Pruning of Transformer Heads Open Access - MIT Press — Abstract. Multi-head attention, a collection of several attention mechanisms that independently attend to different parts of the input, is the key ingredient in the Transformer. Recent work has shown, however, that a large proportion of the heads in a Transformer's multi-head attention mechanism can be safely pruned away without significantly harming the performance of the model; such ...
- Deep Learning — 20 Deep Generative Models; Bibliography; Index; FAQ. Can I get a PDF of this book? No, our contract with MIT Press forbids distribution of too easily copied electronic formats of the book. Why are you using HTML format for the web version of the book? This format is a sort of weak DRM required by our contract with MIT Press.








