Token Merging and Pruning in Transformers
1. Core Concepts: Tokens, Attention, and Redundancy
Core Concepts: Tokens, Attention, and Redundancy
Transformers process input sequences by breaking them into discrete units called tokens, which are typically subword or word-level representations. Each token is embedded into a high-dimensional vector space, where its semantic and syntactic relationships with other tokens are modeled through self-attention mechanisms. The self-attention operation computes pairwise interactions between tokens, generating a weighted sum of values based on their relevance, as defined by:
Here, Q (queries), K (keys), and V (values) are linear transformations of the input embeddings, and dk is the dimension of the key vectors. The softmax normalization ensures that attention weights sum to one, allowing the model to focus on the most relevant tokens dynamically.
Token Redundancy in Transformer Models
Despite their effectiveness, transformers exhibit significant computational inefficiencies due to token redundancy. Empirical studies show that many attention heads assign near-uniform weights to large subsets of tokens, particularly in deeper layers. This phenomenon arises because:
- Localized attention patterns: Many tokens attend primarily to their immediate neighbors, making distant tokens computationally irrelevant.
- Low-rank attention matrices: The rank of the attention matrix is often much smaller than the sequence length, implying that a subset of tokens can sufficiently represent the full interaction space.
Quantifying Redundancy
Redundancy can be measured using the token importance score, which quantifies how much a token contributes to the final output. For a given token ti, its importance Ii can be approximated via gradient-based methods or attention weight aggregation:
where αij is the attention weight from token i to j, and ∇xi ℒ(xj) is the gradient of the loss with respect to the token embedding. Tokens with low Ii are candidates for merging or pruning.
Practical Implications
Redundancy-aware methods like Token Merging (ToMe) and Dynamic Token Pruning exploit these insights to reduce computational overhead without significant accuracy loss. For instance, ToMe merges similar tokens in intermediate layers using clustering, while pruning methods eliminate tokens below an adaptive threshold. These techniques achieve speedups of 1.5–2× in vision transformers and autoregressive language models.
Case Study: BERT Inference Optimization
In BERT, up to 40% of tokens in classification tasks can be pruned after the first few layers with minimal impact on accuracy. This is validated by the observation that later layers rely heavily on [CLS] token representations, making many input tokens redundant. Pruning these tokens reduces FLOPs by 30% while maintaining 98% of the original F1 score on GLUE benchmarks.

Why Merge or Prune Tokens? Efficiency vs. Performance Trade-offs
Transformer models, particularly in large-scale applications like vision or language tasks, process sequences of tokens where computational complexity scales quadratically with sequence length due to self-attention mechanisms. Token merging and pruning techniques address this inefficiency by reducing the number of tokens processed in intermediate layers, trading off minimal accuracy degradation for significant computational savings.
Computational Complexity of Self-Attention
The self-attention mechanism in Transformers has a time and memory complexity of O(n²d), where n is the sequence length and d is the embedding dimension. For high-resolution images or long documents, n can reach thousands of tokens, making attention layers prohibitively expensive. Token reduction methods mitigate this by lowering the effective n in later layers.
Token Merging: Preserving Information via Aggregation
Token merging combines semantically similar tokens, typically using cosine similarity or learned attention weights. For example, ToMe (Token Merging) merges the k most similar tokens in a layer by averaging their embeddings:
where Si is the set of tokens merged into the i-th output token. This preserves global context while reducing redundancy, often achieving 30–50% FLOPs reduction with <1% accuracy drop in vision Transformers.
Token Pruning: Dynamic Sparsification
Pruning discards low-salience tokens entirely, often based on attention scores or learned importance metrics. For instance, a token xi may be pruned if its L2-norm falls below a threshold τ:
DynamicViT and similar methods prune up to 40% of tokens in later layers, disproportionately benefiting inference speed since pruned tokens bypass all subsequent computations.
Trade-offs: Accuracy, Latency, and Memory
- Accuracy: Merging is more stable than pruning, as no information is fully discarded. Pruning risks losing rare but critical tokens (e.g., small objects in images).
- Latency: Pruning reduces compute more aggressively, especially for long sequences, but merging’s regularity enables better hardware utilization.
- Memory: Both methods lower peak memory usage by reducing the active token count, crucial for edge deployment.
Practical Considerations
In vision Transformers, merging is often applied after early layers where spatial redundancy is high. For NLP, pruning may be preferred in decoder-only models (e.g., GPT) to maintain autoregressive consistency. The choice hinges on the task’s tolerance for information loss versus the need for real-time throughput.

Key Metrics: FLOPs Reduction, Memory Savings, and Accuracy Impact
When evaluating token merging and pruning techniques in transformer models, three primary metrics dominate the analysis: FLOPs reduction, memory savings, and accuracy impact. These metrics provide a quantitative framework for assessing the trade-offs between computational efficiency and model performance.
FLOPs Reduction
Floating-point operations (FLOPs) serve as a proxy for computational cost. Token merging reduces FLOPs by decreasing the number of tokens processed in self-attention layers. For a transformer with N tokens, the FLOPs for self-attention scale as O(N²d), where d is the feature dimension. Merging k tokens into m merged tokens (where m < k) reduces FLOPs proportionally.
Here, r represents the merging ratio (k/m). For example, merging every 2 tokens (r=2) reduces attention FLOPs by approximately 4×. However, this assumes uniform merging; dynamic merging strategies may yield variable savings.
Memory Savings
Memory consumption in transformers primarily stems from storing attention matrices and intermediate activations. Token pruning directly reduces memory by eliminating tokens entirely, while merging compresses them. The memory footprint for attention scales as:
Pruning 30% of tokens reduces this to 4(0.7N)² = 1.96N² bytes, a 51% reduction. Merging achieves similar savings by reducing N while preserving information through weighted combinations. Memory savings extend beyond attention to layer norms and feed-forward networks, as fewer tokens pass through subsequent layers.
Accuracy Impact
The critical trade-off lies in accuracy degradation. Pruning and merging inevitably discard information, potentially harming task performance. The accuracy drop depends on:
- Token selection criteria: Importance scores based on attention weights or gradient norms preserve critical tokens better than random pruning.
- Merging strategy: Weighted averaging (e.g., ToMe) often outperforms naive concatenation.
- Task sensitivity: Image classification tolerates higher compression than fine-grained sequence tasks like named entity recognition.
Empirical studies show that careful merging can limit accuracy drops to 1-2% on ImageNet at 2× FLOPs reduction, while aggressive pruning (50% tokens) may incur 5-10% degradation. The Pareto frontier between FLOPs reduction and accuracy guides optimal strategy selection.
Practical Considerations
In real-world deployments, the choice between merging and pruning depends on hardware constraints and latency requirements. Merging introduces slight overhead from computing token similarities but maintains parallelizability. Pruning enables dynamic computation but may require sparse operations support. Profiling tools like NVIDIA Nsight help quantify actual speedups, as theoretical FLOPs reductions don't always translate linearly to wall-clock time due to memory bandwidth bottlenecks.

2. Similarity-Based Merging: Cosine and Euclidean Distance Approaches
2.1 Similarity-Based Merging: Cosine and Euclidean Distance Approaches
Similarity-based merging in transformers relies on quantifying the resemblance between token representations to identify redundant or semantically equivalent tokens. Two dominant metrics for this purpose are cosine similarity and Euclidean distance, each offering distinct advantages depending on the nature of the token embeddings.
Cosine Similarity for Token Merging
Cosine similarity measures the angular alignment between two vectors, making it invariant to their magnitudes. Given token embeddings x and y in a d-dimensional space, their cosine similarity is computed as:
Values range from −1 (perfect anti-correlation) to 1 (identical direction). For transformer tokens, values closer to 1 indicate semantic equivalence, enabling merging of tokens with similarity exceeding a threshold τ. This approach is particularly effective in high-dimensional spaces where magnitude variations are noise-dominated.
Euclidean Distance as an Alternative Metric
Euclidean distance quantifies the straight-line separation between vectors:
Unlike cosine similarity, Euclidean distance is sensitive to both direction and magnitude. This makes it suitable for tasks where the norm of embeddings carries meaningful information, such as in energy-based models. Tokens are merged if their distance falls below a threshold ϵ, often normalized by embedding dimensionality.
Comparative Analysis
- Normalization Sensitivity: Cosine similarity inherently normalizes embeddings, while Euclidean distance requires explicit normalization (e.g., L2) for stable comparisons.
- Contextual Performance: Cosine similarity outperforms in NLP tasks where semantic alignment matters more than magnitude. Euclidean distance excels in low-dimensional or physics-inspired embeddings.
- Computational Overhead: Both metrics scale quadratically with token count, but cosine similarity avoids square root operations.
Practical Implementation
In transformer architectures, similarity-based merging is typically applied during inference or fine-tuning. For example, tokens in ViTs (Vision Transformers) with cosine similarity >0.9 are merged by averaging their embeddings, reducing sequence length without significant accuracy loss. Euclidean-based merging is preferred in graph transformers where node features have interpretable magnitudes.

Dynamic Token Merging with Learned Thresholds
Dynamic token merging extends static token reduction techniques by introducing adaptive thresholds learned during training. Unlike fixed merging rules, this approach optimizes the trade-off between computational efficiency and model performance by allowing the network to determine which tokens to merge based on their contextual importance.
Learned Threshold Mechanism
The core innovation lies in parameterizing the merging decision through a gating function G that outputs a merge probability for each token pair. For tokens xi and xj, the merge score is computed as:
where Wg and bg are learnable parameters, ⊙ denotes element-wise multiplication, and τ is a temperature parameter controlling decision sharpness. The sigmoid function σ maps scores to [0,1], interpreted as merge probabilities.
Differentiable Merging via Gumbel-Softmax
To enable gradient flow through discrete merge decisions, we employ the Gumbel-Softmax reparameterization:
where g1, g2 are i.i.d. Gumbel noise samples. This continuous relaxation approaches an exact merge/non-merge decision as τ→0 while remaining differentiable.
Training Objective
The model jointly optimizes the primary task loss Ltask and a merging regularization term:
where λ controls the computational cost trade-off, and FLOPs(l) estimates layer-wise operations reduced through merging. The expectation is taken over stochastic merge decisions during training.
Architectural Integration
Dynamic merging layers are typically inserted between transformer blocks, processing the sequence as:
- Compute pairwise similarity scores for all tokens in local windows
- Sample merge decisions using the gating mechanism
- Fuse tokens via weighted averaging based on merge probabilities
- Propagate reduced sequence to next layer
The windowed approach maintains O(n) complexity relative to sequence length n, contrasting with the O(n2) cost of global attention.
Practical Considerations
Key implementation details include:
- Gradient estimation: Straight-through estimator for merge/non-merge indicators
- Temperature annealing: Start with high τ for exploration, gradually reduce to sharpen decisions
- Memory efficiency: Sparse implementation for merge masks avoids materializing full attention matrices
Empirical results show dynamic merging achieves 2-4× speedups in vision transformers with <1% accuracy drop, outperforming static methods like ToMe by adapting to input complexity.

2.3 Hierarchical Merging Strategies for Long Sequences
Hierarchical merging addresses the quadratic complexity of self-attention in transformers by progressively reducing sequence length through multi-level token aggregation. Unlike uniform merging, which applies a fixed compression ratio globally, hierarchical approaches preserve fine-grained local information while enabling coarse-grained global reasoning.
Multi-Resolution Token Grouping
The core mechanism partitions the input sequence into nested segments using a binary tree structure. At each level l, tokens are grouped into non-overlapping clusters of size kl, where kl increases exponentially with depth:
where k0 is the base cluster size (typically 2-8 tokens). Cluster representations are computed via weighted averaging using attention scores as weights:
where 𝒩i denotes the neighborhood of tokens in cluster i at level l.
Adaptive Depth Selection
The merging depth L is dynamically determined based on sequence entropy. For an input sequence S, the stopping criterion evaluates the KL-divergence between adjacent levels:
where P(l) represents the attention weight distribution at level l, and ε is a threshold (typically 0.1-0.3). This ensures merging stops when further aggregation would cause significant information loss.
Gradient-Aware Merging
Recent advancements incorporate gradient signals during merging to preserve salient features. The cluster weights αij are modified to include gradient magnitudes:
where γ is a learnable parameter and ℒ is the task loss. This approach shows particular effectiveness in vision transformers, where gradient hotspots often correspond to semantically important regions.
Computational Complexity Analysis
Hierarchical merging reduces the asymptotic complexity of self-attention from O(n2) to O(n log n) for a sequence of length n. The breakdown per level shows:
- Level 0: Full attention on n/k0 clusters (O((n/k0)2))
- Level l: Attention on n/(2lk0) clusters (O((n/(2lk0))2))
The total complexity becomes dominated by the finest level when k0 ≪ n.

3. Importance Scoring: Attention Weights and Gradient-Based Criteria
Importance Scoring: Attention Weights and Gradient-Based Criteria
Attention-Based Importance Scoring
The self-attention mechanism in transformers provides a natural way to assess token importance through attention weights. For a given layer l with H attention heads, the raw attention weight matrix Al,h for head h is computed as:
where Ql,h and Kl,h are the query and key matrices respectively, and dk is the dimension of the key vectors. The importance score si for token i can be derived by aggregating attention weights across all heads and layers:
This formulation captures both the influence of token i on other tokens (via outgoing attention weights) and its receptiveness to contextual information (via incoming attention weights). In practice, some implementations use only the outgoing attention weights for computational efficiency.
Gradient-Based Importance Measures
While attention weights provide a direct measure of token interaction, gradient-based methods offer a complementary perspective by quantifying how much each token contributes to the final loss. The gradient magnitude with respect to token embeddings serves as an importance indicator:
where ei is the embedding of token i and ℒ is the loss function. More sophisticated approaches compute the product of gradients and embeddings (similar to saliency maps in computer vision):
This method tends to be more stable than pure gradient magnitudes as it accounts for both the token representation and its influence on the loss.
Combined Scoring Approaches
State-of-the-art token pruning methods often combine multiple importance signals. A common hybrid approach linearly combines attention and gradient scores:
where α is a mixing hyperparameter typically tuned on validation data. Some recent work has proposed more sophisticated combinations using learned gating mechanisms or small neural networks to dynamically weight different importance signals.
Practical Considerations
When implementing importance scoring in practice, several factors must be considered:
- Computational overhead: Gradient-based methods require backward passes, making them more expensive than attention-only approaches
- Layer selection: Attention weights from different layers capture different types of information - early layers often focus more on local syntax while later layers capture higher-level semantics
- Normalization: Scores should be properly normalized across the sequence to avoid length-dependent biases
- Dynamic vs static pruning: Some methods compute importance scores once per input (static) while others recompute them during processing (dynamic)
Recent work has shown that the optimal importance metric varies across tasks - for example, gradient-based methods tend to work better for tasks requiring fine-grained understanding, while attention-based methods suffice for more general language modeling tasks.

Adaptive Pruning: Layer-Specific Token Elimination
Unlike static pruning methods that apply uniform compression across all layers, adaptive pruning dynamically eliminates tokens based on layer-specific importance metrics. This approach recognizes that different transformer layers exhibit varying sensitivity to token removal, with early layers often processing redundant spatial information while later layers refine semantically critical features.
Importance Scoring for Adaptive Pruning
The core mechanism relies on computing token importance scores Il(t) at each layer l through gradient-weighted class activation:
where zlt represents the token embedding at position t in layer l, and ℒ is the task loss. The Hadamard product with gradients captures both activation magnitude and downstream influence.
Layer-Wise Threshold Adaptation
Pruning thresholds τl are computed dynamically per layer using exponential moving averages of importance scores:
with smoothing factor α typically set to 0.1-0.3. This adaptive thresholding prevents over-pruning in critical layers while aggressively compressing redundant early layers.
Practical Implementation Considerations
- Memory-efficient scoring: Importance scores can be approximated using last-attention weights in decoder layers or spatial pooling in vision transformers
- Batch-wise stability: Layer thresholds should be updated across multiple batches to avoid oscillation
- Warmup period: Most implementations disable pruning for the first 10-20% of training steps
Architectural Modifications
Effective adaptive pruning requires three key architectural changes:
- Token regrouping: Surviving tokens are reordered contiguously to maintain efficient matrix operations
- Cross-layer propagation: Pruning masks must propagate through skip connections
- Gradient masking: Eliminated tokens receive zero gradients during backpropagation
Recent work in DynamicViT demonstrates that layer-specific pruning can reduce FLOPs by 40-60% in vision transformers with less than 1% accuracy drop, significantly outperforming uniform pruning baselines. The technique shows particular promise in long-sequence domains like video processing and document understanding.
3.3 Combining Pruning with Quantization for Hardware Efficiency
Pruning and quantization are complementary techniques for optimizing transformer models for hardware deployment. While pruning reduces the number of parameters by eliminating redundant connections, quantization compresses the remaining weights into lower-bit representations. When combined, these methods yield multiplicative efficiency gains in memory footprint, compute latency, and energy consumption.
Mathematical Foundations of Joint Optimization
The joint effect of pruning and quantization can be formalized through the parameter density reduction ratio D:
where sp is the sparsity ratio from pruning, bq is the quantized bit-width, and borig is the original bit-width (typically 32-bit floating point). For example, applying 70% sparsity with 8-bit quantization yields:
indicating a 13.3× reduction in parameter storage requirements. The actual hardware benefits are even greater due to:
- Reduced memory bandwidth pressure from smaller activations
- Elimination of zero-value multiplications in pruned weights
- Simplified arithmetic circuits for lower-precision operations
Hardware-Aware Co-Design Strategies
Effective joint optimization requires consideration of hardware constraints during training:
- Block-structured pruning aligns sparsity patterns with hardware vector units (e.g., 4×4 blocks for SIMD architectures)
- Mixed-precision quantization allocates higher bits to sensitive attention layers while aggressively quantizing feed-forward networks
- Sparsity-aware numerics uses bitmask encoding to skip zero computations without branch penalties
Modern accelerators like NVIDIA's Tensor Cores and Google's TPUs implement dedicated units for sparse low-precision matrix multiplication, achieving 2-4× speedups over dense FP32 operations. The optimal pruning-quantization tradeoff depends on the target hardware's:
- Memory hierarchy (cache sizes, bandwidth)
- Compute throughput for different numeric formats
- On-chip sparsity processing capabilities
Practical Implementation Considerations
Joint optimization introduces several training challenges:
where Q(θl) enforces quantization-aware training through straight-through estimators. Best practices include:
- Progressive application - prune first, then quantize the sparse model
- Alternating optimization cycles between sparsity and precision
- Hardware-in-the-loop validation using tools like TVM or TensorRT
Recent work shows that transformer models can maintain 98% of original accuracy at 8-bit precision with 70% sparsity when using proper initialization and gradual compression schedules. The BERT-Large model, for instance, reduces from 1.3GB to just 98MB under these settings while maintaining <1% accuracy drop on GLUE benchmarks.

4. Integration with Popular Transformer Architectures (BERT, GPT, ViT)
Integration with Popular Transformer Architectures (BERT, GPT, ViT)
BERT: Bidirectional Encoder Representations from Transformers
Token merging and pruning in BERT must account for its bidirectional attention mechanism, which processes tokens in both directions simultaneously. Unlike unidirectional models, pruning tokens in BERT affects the contextual understanding of surrounding tokens. To mitigate this, dynamic token importance scoring is used, where the relevance of a token is computed based on its contribution to the attention weights across all layers. For a given token ti in layer l, its importance score I(ti, l) can be derived as:
Here, αijl represents the attention weight between tokens i and j in layer l, while WQl and WKl are the query and key weight matrices. Tokens with scores below a dynamically computed threshold are pruned or merged with neighboring tokens.
GPT: Generative Pre-trained Transformer
In autoregressive models like GPT, token pruning must preserve the sequential dependency of generated text. Since GPT uses masked self-attention, pruning tokens at position i affects all subsequent positions. A common approach is to employ gradient-based token importance estimation, where the gradient of the loss with respect to each token embedding is computed. The importance score S(ti) is given by:
Here, ei is the embedding of token ti, and ℒ is the model's loss function. Tokens with low scores are candidates for merging or pruning. To maintain coherence, GPT-based pruning often employs a sliding window approach, where only tokens outside a fixed context window are pruned.
Vision Transformers (ViT)
In ViT, tokens correspond to image patches, and pruning decisions must consider spatial locality. Unlike NLP transformers, ViT tokens exhibit strong local correlations. Patch merging is a common technique, where adjacent patches are combined based on similarity metrics. For two patches pi and pj, their similarity σ(pi, pj) can be computed as:
Here, f(·) denotes the patch embedding function. Patches with high similarity are merged, reducing the token count while preserving visual information. Additionally, ViT pruning often employs attention-based saliency maps to identify less informative patches.
Practical Implementation Considerations
Integrating token merging and pruning into existing transformer architectures requires careful tuning of hyperparameters such as pruning thresholds, merging criteria, and layer-specific policies. For BERT and GPT, dynamic pruning during inference can reduce computational overhead, while ViT often benefits from static pruning during training. Below is a comparison of token reduction techniques across architectures:
| Architecture | Pruning Strategy | Merging Strategy | Typical Token Reduction |
|---|---|---|---|
| BERT | Dynamic importance scoring | Attention-weighted averaging | 20-40% |
| GPT | Gradient-based saliency | Sliding window merging | 15-30% |
| ViT | Spatial similarity | Patch concatenation | 30-50% |
Recent advancements like ToMe (Token Merging) and DiffPruning have shown promise in achieving higher compression rates without significant accuracy drops. These methods leverage differentiable pruning gates and learned merging policies, making them adaptable to various transformer architectures.
Training Strategies: End-to-End vs. Post-Training Optimization
End-to-End Training with Token Merging/Pruning
End-to-end training integrates token merging or pruning directly into the transformer's optimization loop. The key advantage lies in joint optimization of both the base model parameters θ and the merging/pruning policy ϕ. The objective function becomes:
where Mϕ represents the merging/pruning operation parameterized by ϕ, and R(ϕ) is a regularization term controlling sparsity. The gradient updates must account for the non-differentiable nature of token selection:
Practical implementations often use Gumbel-Softmax or REINFORCE estimators to approximate gradients through discrete operations. Recent work like ToMe (Token Merging) demonstrates that end-to-end training can achieve 2-4× speedups with <1% accuracy drop on ImageNet when merging is learned jointly with ViT parameters.
Post-Training Optimization Approaches
Post-training methods apply token reduction after standard transformer training, requiring no modifications to the original training pipeline. These approaches typically fall into two categories:
- Static pruning: Computes token importance scores si using metrics like attention magnitude or gradient norms, then preserves top-k tokens:
$$ \mathcal{T}_{pruned} = \{t_i | s_i \in \text{top-k}(s)\} $$
- Dynamic merging: Clusters tokens based on similarity metrics in real-time during inference, commonly using:
$$ \text{merge}(t_i, t_j) = \frac{a_{ii}t_i + a_{ij}t_j}{a_{ii} + a_{ij}} $$where aij are attention weights between tokens.
Methods like DiffPrune show that post-training token pruning can remove 40-60% of tokens in BERT with minimal accuracy degradation when using second-order sensitivity analysis for token selection.
Tradeoffs and Empirical Comparisons
The choice between strategies involves fundamental compromises:
| Metric | End-to-End | Post-Training |
|---|---|---|
| Compute Overhead | Higher (20-30% longer training) | Negligible |
| Accuracy Retention | Better (ΔAcc ≈ 0.5-1.5%) | Worse (ΔAcc ≈ 2-5%) |
| Hardware Compatibility | Requires custom kernels | Works on vanilla transformers |
Recent hybrid approaches like DyToMe combine both paradigms - first training with soft merging targets, then fine-tuning the merging policy post-training. This achieves 3.1× FLOPs reduction on GPT-2 with only 1.8% perplexity increase compared to 4.2% for pure post-training methods.
Implementation Considerations
Effective deployment requires addressing several practical challenges:
- Gradient estimation: For end-to-end training, the straight-through estimator often outperforms REINFORCE in stability:
$$ abla_\phi \mathbb{E}_{z\sim p_\phi} [f(z)] \approx \mathbb{E}[f(z) abla_\phi \log p_\phi(z)] $$
- Memory constraints: Token merging creates irregular memory access patterns that may require specialized attention implementations to maintain efficiency.
- Curriculum learning: Gradually increasing merging/pruning rates during training improves final model performance (e.g., linear schedule from 0% to target sparsity).
4.3 Debugging and Profiling Merging/Pruning Pipelines
Performance Bottleneck Identification
When optimizing transformer architectures through token merging and pruning, the first critical step involves identifying computational bottlenecks. Profiling tools like PyTorch Profiler or NVIDIA Nsight Systems reveal layer-wise execution times and memory allocation patterns. Key metrics to examine include:
- Attention computation time per head
- Token merging overhead versus theoretical speedup
- Memory bandwidth saturation during pruning operations
Numerical Stability Verification
Aggressive pruning can introduce numerical instability in attention weights. Implement gradient checking by comparing analytical and numerical gradients:
Values exceeding 1e-6 typically indicate problematic operations. Common failure points include:
- Division by near-zero magnitudes in softmax denominators
- Overflow in attention score computations
- Underflow in pruned token contributions
Visualization Techniques
Attention head visualization before and after merging reveals information flow patterns. Create heatmaps showing:
- Token-to-token attention weights
- Pruning mask evolution across layers
- Merging decision boundaries
Automated Testing Framework
Implement differential testing against the baseline model:
def test_pruning_equivalence(model, pruned_model, inputs):
with torch.no_grad():
baseline = model(inputs)
pruned = pruned_model(inputs)
return torch.allclose(baseline, pruned, rtol=1e-3, atol=1e-5)
Memory Access Pattern Analysis
Modern GPUs suffer performance penalties from non-coalesced memory accesses. Profile memory transactions using:
- DRAM bandwidth utilization
- L2 cache hit rates
- Shared memory bank conflicts
Optimal merging strategies minimize memory transactions through:
5. Foundational Papers on Token Efficiency in Transformers
5.1 Foundational Papers on Token Efficiency in Transformers
- Joint merging and pruning: adaptive selection of better token ... — The Journal of Electronic Imaging publishes papers that are normally considered in the design, engineering, and applications of electronic imaging technologies. ... which are mainly divided into token pruning and token merging. Yet, we believe that neither pruning only to reduce non-critical tokens nor merging to reduce similar tokens are ...
- PDF Beyond Attentive Tokens: Incorporating Token Importance and Diversity ... — an efficient token decoupling and merging method that can jointly consider the token importance and diversity for to-ken pruning. According to the class token attention, we de-couple the attentive and inattentive tokens. In addition to preserving the most discriminative local tokens, we merge similar inattentive tokens and match homogeneous atten-
- Efficient Transformer Adaptation with Soft Token Merging - OpenReview — methods to derive the soft token merging schemes. 193. that encourage partial token usage with minimum. 194. loss in accuracy. Towards this end, we introduce. 195. the soft token merging system (Sec.3.1) and token. 196. inflation module (Sec.3.1), learning to dynami-197. cally reconfigure the token processing paths in a. 198
- 1 Efficient Visual Transformer by Learnable Token Merging - arXiv.org — transformers by pruning or token merging are discussed in Section 2. The formulation of LTM-Transformer is de-tailed in Section 3. The effectiveness of LTM-Transformer ... In this paper, we focus on learning to merge tokens guided by the information bottleneck theory of deep learning and primarily review existing works on Token Pruning and ...
- PDF Which Tokens to Use? Investigating Token Reduction in Vision Transformers — tokens based on their distance to the image center, setting the threshold such that the absolute difference between the kept tokens and Prs is minimized, where P is the initial amount of spatial tokens. 3.1.2 Static Keep Rate Pruning Top-K is a commonly used pruning baseline, where the at-tention between the P spatial tokens and the CLS token ...
- Automatic pruning rate adjustment for dynamic token ... - Springer — Visualization of the Token Reduction for ImageNet-1k dataset: (a)-(c) are token pruning and (d)-(f) are token merging visualization. Each pruning method is applied to an off-the-shelf ViT-L with a pruning rate of 5% for each layer, without fine-tuning; since ViT-L has 24 layers of Transformer Encoders, token reduction in layers 8, 16, and ...
- Efficient Time Series Processing for Trans Formers and State-space ... — - Token merging in time series We present first studies on token merging in time series analysis, exploring its application beyond transformer architectures to include state-space models. For this purpose, we propose a domain-specific token merging algorithm that combines tokens within a local neighborhood around each token, preserving causality.
- PDF The Role of Token Pruning in E cient Transformer Architectures — In the following sections, we explore various token pruning techniques, cate-gorize existing methods, and discuss their empirical performance and real-world applications[22]. 3 TaxonomyofTokenPruningMethods Token pruning methods can be categorized based on several key dimensions, in-
- Efficient Time Series Processing for Transformers and State-Space ... — evaluations, we analyze the impact of token merging on various time series transformer models and state-space models. Our key contributions are as follows: - Token merging in time series We present first studies on token merging in time series analysis, exploring its application beyond transformer architectures to include state-space models ...
- PDF ALGM: Adaptive Local-then-Global Token Merging for Efficient Semantic ... — quality. (b) Token merging approaches like ToMe [2] show that gradually merging redundant tokens across the entire image (i.e., globally) can greatly boost the efficiency, but at the cost of segmentation quality. Thus, our second objec-tive is to also apply global token merging to further improve efficiency, but without harming the segmentation ...
5.2 Open-Source Implementations and Toolkits
- PDF Which Tokens to Use? Investigating Token Reduction in Vision Transformers — cation of the input token sequence can be divided into two primary paradigms: token pruning [12, 14, 23, 27, 29, 35, 39, 41, 49, 60, 61] and token merging [3, 16, 36, 42, 46, 58, 59, 64, 66]. Pruning-based methods aim to reduce the to-ken sequence by removing tokens, whereas merging-based methods reduce the token sequence by combining tokens.
- Automatic pruning rate adjustment for dynamic token ... - Springer — Visualization of the Token Reduction for ImageNet-1k dataset: (a)-(c) are token pruning and (d)-(f) are token merging visualization. Each pruning method is applied to an off-the-shelf ViT-L with a pruning rate of 5% for each layer, without fine-tuning; since ViT-L has 24 layers of Transformer Encoders, token reduction in layers 8, 16, and ...
- Joint merging and pruning: adaptive selection of better token ... — Yet, we believe that neither pruning only to reduce non-critical tokens nor merging to reduce similar tokens are optimal strategies for token compression. To overcome this challenge, this work proposes a token compression framework: joint merging and pruning (JMP), which adaptively selects a better token compression strategy based on the ...
- PDF Pruning One More Token is Enough: Leveraging Latency-Workload Non ... — Second, we determine token pruning schedule by leverag-ing non-linear latency-workload relationships. Third, we demonstrate a training-free, token pruning method utilizing this schedule. We show other methods may increase latency by 2-30%, while we reduce latency by 9-26%. For simi-lar latency (within 5.2% or 7ms) across devices we achieve
- WACV 2025 Open Access Repository — These WACV 2025 papers are the Open Access versions, provided by the Computer Vision Foundation. ... Second we determine token pruning schedule by leveraging non-linear latency-workload relationships. ... across devices we achieve 78.6%-84.5% ImageNet1K classification accuracy while the state-of-the-art Token Merging achieves 45.8%-85.4% ...
- PDF The Role of Token Pruning in E cient Transformer Architectures — The Role of Token Pruning in E cient Transformer Architectures Cheng Tai 1, Rong Qiu , Zihan He 1, ... models. Finally, we outline open research directions and discuss potential integrations with other efficiency-driven techniques, such as quantization ... Token pruning has been applied to various NLP tasks, each with different sensi ...
- [2407.05941] Pruning One More Token is Enough: Leveraging Latency ... — This paper investigates how to efficiently deploy vision transformers on edge devices for small workloads. Recent methods reduce the latency of transformer neural networks by removing or merging tokens, with small accuracy degradation. However, these methods are not designed with edge device deployment in mind: they do not leverage information about the latency-workload trends to improve ...
- (PDF) Accelerating Transformers with Spectrum-Preserving Token Merging — A new token merging procedure for accelerating V iT architectures is designed to protect crucial yet small-region tokens while identifying redundant ones for merging based on contextual token ...
- Token merging - Hugging Face — The apply_patch function exposes a number of arguments to help strike a balance between pipeline inference speed and the quality of the generated tokens. The most important argument is ratio which controls the number of tokens that are merged during the forward pass.. As reported in the paper, ToMe can greatly preserve the quality of the generated images while boosting inference speed.
- (PDF) Reducing Vision Transformer Latency on Edge ... - ResearchGate — Fig. 5: Illustration of our token pruning method for a single transformer encoder layer at inference time. We compute an attention score and V score for each tok en to estimate importance, then
5.3 Emerging Research Directions and Unresolved Challenges
- PRIMATE: Processing in Memory Acceleration for Dynamic Token-pruning ... — A. Transformer and Dynamic Token Pruning The token pruning strategy is to prune tokens based on an impor-tance score of each token. To arrive at this score, we take the dot 9798350393545/24/$$31.00 ©2024 IEEE 6A4 557 2024 29th Asia and South Pacific Design Automation Conference (ASP DAC) | 979 8 3503 9354 5/24/$$31.00 ...
- PDF Which Tokens to Use? Investigating Token Reduction in Vision Transformers — ATS can sample fewer than Prs tokens at stage s. 3.1.4 Hard-Merging ToMe [3] is a recent token merging method, where the set of tokens are split into a bipartite graph with equal sized partitions Aand B, where edges are constructed by draw-ing a single edge for each node in Ato the node in Bwith the highest cosine similarity. The Ps(1−rs ...
- DRViT: A dynamic redundancy-aware vision transformer accelerator via ... — The Token Merging and Pruning Module is located between the Attention module and MLP module, as shown in Fig. 2. In our stream pattern, a token matrix is a transmission unit between different modules, so it is very convenient to merge and prune tokens on hardware. Fig. 3 illustrates the hardware architecture of the Token Merging and Pruning Module.
- Token Pruning for Efficient NLP, Vision, and Speech Models — The rapid growth of Transformer-based architectures has led to significant advancements in natural language processing (NLP), computer vision, and speech processing. However, their increasing computational demands pose challenges for real-time inference, edge deployment, and energy efficiency. Token pruning has emerged as a promising solution to mitigate these issues by dynamically reducing ...
- PDF The Role of Token Pruning in E cient Transformer Architectures — In the following sections, we explore various token pruning techniques, cate-gorize existing methods, and discuss their empirical performance and real-world applications[22]. 3 TaxonomyofTokenPruningMethods Token pruning methods can be categorized based on several key dimensions, in-
- PDF ALGM: Adaptive Local-then-Global Token Merging for Efficient Semantic ... — most methods merge tokens if they have a high similarity score [2,3,5,8,17,28,43]. Other methods combine differ-ent merging, pruning or fusing approaches [3,5,8,28,44]. Token reduction for semantic segmentation. Some token merging methods for image classification can also be applied to semantic segmentation [2,6,17,24,28] by reconstructing ...
- (PDF) Constraint-aware and Ranking-distilled Token Pruning for ... — Constraint-aware and Ranking-distilled Token Pruning for E icient Transformer Inference KDD '23, August 6-10, 2023, Long Beach, CA, USA Figure 2: Our approach learns layer gate masks and token
- Joint merging and pruning: adaptive selection of better token ... — Vision transformer (ViT) is widely used to handle artificial intelligence tasks, making significant advances in a variety of computer vision tasks. However, due to the secondary interaction between tokens, the ViT model is inefficient, which greatly limits the application of the ViT model in real scenarios. In recent years, people have noticed that not all tokens contribute equally to the ...
- Dynamic Layer-Wise Token Pruning for Sequence-to-Sequence Transformer ... — We introduce Seek2Skim, a novel token pruning approach that improves the computational efficiency of transformer inference by dynamically adjusting computations in both the encoder and decoder. We propose dynamic cross-attention filtering that ensures each decoder token attends to the most relevant subset of encoder states, preventing adverse ...
- (PDF) ATMformer: An Adaptive Token Merging Vision Transformer for ... — adaptive token merging strategy, important small-scale tokens are retained in the last layer feature maps. Consequently, the A TM-former only utilizes the last layer feature map for








