Chasing Sparsity in Vision Transformers: An End-to-End Exploration
Tianlong Chen, Yu Cheng, Zhe Gan, Lu Yuan, Lei Zhang, Zhangyang Wang
Introduction
Recent years have seen substantial efforts devoted to scaling deep networks to enormous sizes. Parameter counts are frequently measured in billions rather than millions, with the time and financial outlay necessary to train these models growing in concert. The trend undoubtedly continues with the recent forefront of transformers for computer vision tasks. By leveraging self-attention, reducing weight sharing such as convolutions, and feeding massive training data, vision transformers have established many new state-of-the-art (SOTA) records in image classification , object detection , image enhancement , and image generation . Existing vision transformers and variants, despite the impressive empirical performance, have in general suffered from gigantic parameter-counts, heavy run-time memory usages, and tedious training. That naturally calls for the next step research of slimming their inference and training, without compromising the performance.
Model compression and efficient learning are no strangers to deep learning researchers, although their exploration in the emerging vision transformer field remains scarce . Among the large variety of compression means , sparsity has been one of the central themes since the beginning . Conventional approaches first train dense networks, and then prune a large portion of parameters in the trained networks to zero. Those methods significantly reduce the inference complexity. However, the price is to cost even more significant computational resources and memory footprints at training, since they commonly require (multiple rounds of) re-training to restore the accuracy loss . That price becomes particularly prohibitive for vision transformers, whose vanilla one-pass training is already much more tedious, slow, and unstable compared to training standard convolutional networks.
An emerging subfield has explored the prospect of directly training smaller, sparse subnetworks in place of the full networks without sacrificing performance. The key idea is to reuse the sparsity pattern found through pruning and train a sparse network from scratch. The seminal work of lottery ticket hypothesis (LTH) demonstrated that standard dense networks contain sparse matching subnetworks (sometimes called “winning tickets”) capable of training in isolation to full accuracy. In other words, we could have trained smaller networks from the start if only we had known which subnetworks to choose. Unfortunately, LTH requires to empirically find these intriguing subnetworks by an iterative pruning procedure , which still cannot get rid of the expensiveness of post-training pruning. In view of that, follow-up works reveal that sparsity patterns might emerge at the initialization , the early stage of training , or in dynamic forms throughout training by updating model parameters and architecture typologies simultaneously. These efforts shed light on the appealing prospect of “end to end” efficiency from training to inference, by involving sparsity throughout the full learning lifecycle.
This paper presents the first-of-its-kind comprehensive exploration of integrating sparsity in vision transformers (ViTs) “from end to end”. With (dynamic) sparsity as the unified tool, we can improve the inference efficiency from both model and data perspectives, while also saving training memory costs. Our innovative efforts are unfolded along with the following three thrusts:
From Dense to (Dynamic) Sparse: Our primary quest is to find sparse ViTs without sacrificing the achievable accuracy, and meanwhile trimming down the training memory overhead. To meet this challenging demand, we draw inspirations from the latest sparse training works that dynamically extract and train sparse subnetworks instead of training the full models. Sticking to a fixed small parameter budget, our technique jointly optimizes model parameters and explores connectivity throughout the entire training process. We term our first basic approach as Sparse Vision Transformer Exploration (SViTE).
From Unstructured to Structured: Most sparse training works restricted discussion to unstructured sparsity. To attain structured sparsity which is more hardware-friendly, unlike classical channel pruning available for convolutional networks, we customize a first-order importance approximation to guide the prune-and-grow of self-attention heads inside ViTs. This seamlessly extends SViTE to its second variant of Structured Sparse Vision Transformer Exploration (S2ViTE).
From Model to Data: We further conduct a unified co-exploration towards joint data and architecture sparsity. That is by plugging in a novel learnable token selector to determine the most vital patch embeddings in the current input sample. The resultant framework of Sparse Vision Transformer Co-Exploration (SViTE+) remains to be end-to-end trainable and can gain additional efficiency.
Extensive experiments are conducted on ImageNet with DeiT-Tiny/Small/Base. Results of substantial computation savings and nearly undamaged accuracies consistently endorse our proposals’ effectiveness. Perhaps most impressively, we find that the sparse (co-)training can even improve the ViT accuracy rather than compromising it, making sparsity a tantalizing “free lunch”. For example, applying SViTE+ on DeiT-Small produces superior compressed ViTs at model sparsity plus data sparsity, saving FLOPs and running time, while attaining a surprising improvement of accuracy; even when the data sparsity increases to (the model sparsity unchanged), there is still no accuracy degradation, meanwhile saving FLOPs and running time.
Related Work
Transformer stems from natural language processing (NLP) applications. The Vision Transformer (ViT) pioneered to leverage a pure transformer, to encode an image by splitting it into a sequence of patches, projecting them into token embeddings, and feeding them to transformer encoders. With sufficient training data, ViT is able to outperform convolution neural networks on various image classification benchmarks . Many ViT variants have been proposed since then. For example, DeiT and T2T-ViT are proposed to enhance ViT’s training data efficiency, by leveraging teacher-student and better crafted architectures respectively. In addition to image classification, ViT has attracted wide attention in diverse computer vision tasks, including object detection , segmentation , enhancement , image generation , video understanding , vision-language and 3D point cloud .
Despite the impressive empirical performance, ViTs are generally heavy to train, and the trained models remain massive. That naturally motivates the study to reduce ViT inference and training costs, by considering model compression means. Model compression has been well studied in both computer vision and NLP applications . Two concurrent works made initial attempts towards ViT post-training compression by pruning the intermediate features and tokens respectively, but did not jointly consider weight pruning nor efficient training. Another loosely related field is the study of efficient attention mechanisms . They mainly reduce the calculation complexity for self-attention modules via various approximations such as low-rank decomposition. Our proposed techniques represent an orthogonal direction and can be potentially combined with them, which we leave as future work. Another latest concurrent work introduced an interpretable module to dynamically and gracefully drop the redundant patches, gaining not only inference efficiency but also interpretability. Being a unique and orthogonal effort from ours, their method did not consider the training efficiency yet.
Pruning and Sparse Training.
Pruning is well-known to effectively reduce deep network inference costs . It can be roughly categorized into two groups: unstructured pruning by removing insignificant weight elements per certain criterion, such as weight magnitude , gradient and hessian ; structured pruning by remove model sub-structures, e.g., channels and attention heads , which are often more aligned with hardware efficiency. All above require training the full dense model first, usually for several train-prune-retrain rounds.
The recent surge of sparse training seeks to adaptively identify high-quality sparse subnetworks and train only them. Starting from scratch, those methods learn to optimize the model weights together with sparse connectivity simultaneously. first introduced the Sparse Evolutionary Training (SET) technique , reaching superior performance compared to training with fixed sparse connectivity . leverages “weight reallocation" to improve performance of obtained sparse subnetworks. Furthermore, gradient information from the backward pass is utilized to guide the update of the dynamic sparse connectivity , which produces substantial performance gains. The latest investigations demonstrate that more exhaustive exploration in the connectivity space plays a crucial role in the quality of found sparse subnetworks. Current sparse training methods mostly focus on convolutional networks. Most of them discuss unstructured sparsity, except a handful considering training convolutional networks with structured sparsity.
Methodology
Our SViTE method (and its variants S2ViTE and SViTE+) is inspired from state-of-the-art sparse training approaches in CNNs. This section presents the sparse exploration of ViT architectures, then shows the detailed procedure of input token selection for extra efficiency gains.
Sparse training starts from a randomly sparsified model; after optimizing several iterations, it shrinks a portion of parameters based on pre-defined pruning criterion, and activates new connections w.r.t. grow indicators. After upgrading the sparse topology, it trains the new subnetwork until the next update of the connectivity. An illustration of the overall procedure is shown in Figure 1. The key factors of sparse training are ❶ sparsity distribution, ❷ update schedule, ❸ pruning and ❹ grow criterion.
Notations.
Sparse Vision Transformer Exploration (SViTE).
Structured Sparse Vision Transformer Exploration (S2ViTE).
Although models with unstructured sparsity achieve superior performance, structured sparsity is much more hardware friendly and brings practical efficiency on realistic platforms, which motivates us to propose Structured Sparse ViT Exploration (S2ViTE). We inherit the design of ❶ sparsity distribution and ❷ update schedule from the unstructured SViTE, and a round-up function is used to eliminate decimals in the parameter counting. The key differences lie in the new ❸ pruning and ❹ grow strategies.
Pruning criterion: Let denote features computed from the self-attention head {, , } and input embeddings , as shown in Figure 1. We perform the Taylor expansion to the loss function , and derive a proxy score for head importance blow:
2 Data and Architecture Sparsity Co-Exploration for Higher Efficiency
Besides exploring sparse transformer architectures, we further slim the dimension of input token embeddings for extra efficiency bonus by leveraging a learnable token selector, as presented in Figure 1. Meanwhile, the introduced data sparsity also serves as an implicit regularization for ViT training, which potentially leads to improved generalization ability, as evidenced in Table 6. Note that, due to skip connections, the number of input tokens actually determines the dimension of intermediate features, which substantially contributes to the overall computation cost. In other words, the slimmed input token embeddings directly result in compressed intermediate features, and bring substantial efficiency gains.
Experiments
We extend several effective pruning methods from CNN compression as our strong baselines. Unstructured pruning: One-shot weight Magnitude Pruning (OMP) , which removes insignificant parameters with the globally smallest weight values; Gradually Magnitude Pruning (GMP) , which seamlessly incorporates gradual pruning techniques within the training process by eliminating a few small magnitude weights per iteration; and Taylor Pruning (TP) , which utilizes the first-order approximation of the training loss to estimate units’ importance for model sparsification. Structured pruning: Salience-based Structured Pruning (SSP). We draw inspiration from , and remove sub-modules in ViT (e.g., self-attention heads) by leveraging their weight, activation, and gradient information. Moreover, due to the repetitive architecture of ViT, we can easily reduce the number of transformer layers to create a smaller dense ViT (Small-Dense) baseline that has similar parameter counts to the pruned ViT model.
Implementation details.
Our experiments are conducted on ImageNet with DeiT-Tiny/Small/Base backbones. The detailed training configurations are listed in Table 1, which mainly follows the default setups in . All involved customized hyperparameters are tuned via grid search (later shown in Figure 3). For a better exploration of sparsity connectivities, we increase training epochs to 600 for all experiments. GMP has an additional hyperparameter, i.e., the pruning schedule, which starts from and ends at of the training epochs with times pruning in total. More details are referred to Appendix A1.
Training time measuring protocol.
We strictly measure the running time saving of (sparse) vision transformers on the ImageNet-1K task using CUDA benchmark mode. To be specific, we separately calculate the time elapsed during each iteration, to eliminate the impact of the hardware environment as much as possible. Note that the time for the data I/O is excluded.
Highlight of our findings.
The overall performance of SViTE, S2ViTE, and SViTE+ on DeiT backbones are summarized in Figure 2. We highlight some takeaways below.
Takeaways: ❶ SViTE produces sparse DeiTs with enhanced generalization and substantial reduced FLOPs, compared to its dense counterpart (). SViTE+ further improves the performance of SViTE by selecting the most vital patches. ❷ S2ViTE achieves matched accuracy on DeiT-Small, and significantly enhances performance on DeiT-Base. Meanwhile, its structural sparsity brings considerable running time savings. ❸ Appropriate data and architecture sparsities can effectively regularize ViT training, leading to a new SOTA win-win between ViT accuracy and efficiency.
1 SViTE with Unstructured Sparsity
We perform SViTE to mine vital unstructured sparsity in DeiTs . Solid lines in Figure 2 record the top-1 test-set accuracy over FLOPs on ImageNet-1K of SViTE-Small and SViTE-Base with a range of sparsity from to . In general, we observe that SViTE generates superior sparse ViTs with both accuracy and efficiency gains. Table 2, 3, and 5 present the comparison between SViTE and various pruning baselines. From these extensive results, we draw several consistent observations. First, compared to the dense baselines, SViTE-Tiny, -Small, and -Base obtain , , and FLOPs reduction, respectively, at sparsity levels with only a negligible accuracy drop within . It verifies the effectiveness of our proposal, and indicates severe parameter redundancy in ViT. Second, our SViTE models from dynamic explorations consistently surpass other competitive baseline methods, including OMP, GMP, TP, and Small-Dense by a substantial performance margin. Among all the baseline approaches, GMP that advocates a gradual pruning schedule achieves the best accuracy with all three DeiT backbones. Third, in Figure 2, both SViTE-Small (blue solid line) and SViTE-Base (green solid line) show an improved trade-off between accuracy and efficiency, compared to their dense DeiT counterparts. Interestingly, we also observe that with similar parameter counts, a large sparse ViT consistently outperforms the corresponding smaller dense ViT. A possible explanation is those appropriate sparse typologies regularize network training and lead to enhanced generalization, which coincides with recent findings of critical subnetworks (i.e., winning tickets) in dense CNNs and NLP transformer models.
2 S2ViTE with Structured Sparsity
For more practical benefits, we investigate sparse DeiTs with structured sparsity. Results are summarized in Table 4. Besides the obtained FLOPs savings, S2ViTE-Tiny, S2ViTE-Small, and S2ViTE-Base enjoy an extra , , and running time reduction, respectively, from structured sparsity with competitive top-1 accuracies. Furthermore, S2ViTE consistently outperforms the baseline structured pruning method (SSP), which again demonstrates the superior sparse connectivity learned from dynamic sparse training.
The most impressive results come from S2ViTE-Base at structured sparsity. It even surpasses the dense DeiT base model by accuracy with parameter counts, FLOPs, and running time reductions. We conclude that () an adequate sparsity from S2ViTE boosts ViT’s generalization ability, which can be regarded as an implicit regularization; () larger ViTs (e.g., DeiT-Base) tend to have more superfluous self-attention heads, and are more amenable to structural sparsification from S2ViTE, based on Figure 2 where dash lines denote the overall performance of S2ViTE-Small and S2ViTE-Base with a range of sparsity from to .
3 SViTE+ with Data and Architecture Sparsity Co-Exploration
In this section, we study data and architecture sparsity co-exploration for ViTs, i.e., SViTE+. Blessed by the reduced input token embeddings, even ViTs with unstructured sparsity can have running time savings. The benefits are mainly from the shrunk input and intermediate feature dimensions. Without loss of generality, we consider SViTE+-Small with unstructured sparsity and S2ViTE+-Small with structured sparsity as examples. As shown in Table 6 and Figure 2, SViTE+-Small at unstructured sparsity is capable of abandoning tokens while achieving running time and FLOPs savings, with even improved top-1 testing accuracy. It again demonstrates that data sparsity as an implicit regularizer plays a beneficial role in ViT training. However, slimming input and intermediate embedding is less effective when incorporated with S2ViTE, suggesting that aggressively removing structural sub-modules hurts ViT’s generalization.
4 Ablation and Generalization Study of SViTEs
Batch size in SViTE.
Generalization study of SViTE and its variants.
It is worth mentioning that our proposed frameworks (SViTE, S2ViTE, SViTE+) are independent of the backbone architectures, and can be easily plugged in other vision transformer models . We implemented both SViTE and S2ViTE on TNT-S . SViTE-TNT-S gains accuracy improvements (Ours: v.s. TNT-S: ) and FLOPs savings at unstructured sparsity; S2ViTE-TNT-S obtains FLOPs and running time reductions at structured sparsity with almost unimpaired accuracy (Ours: v.s. TNT-S:).
5 Visualization
We provide unit-wise and element-wise heatmap visualizations for SViTE-Base with structured sparsity in Figure A7 (in Appendix). Similarly, element-wise heatmap visualizations of SViTE-Base with unstructured sparsity are displayed in Figure A6. We find that even unstructured sparsity exploration can develop obvious structural patterns (i.e., “vertical lines” in mask heatmaps), which implies a stronger potential for hardware speedup .
Self-attention heatmaps.
As shown in Figure 4, we utilize tools in to visualize attention maps of (sparse) ViTs. Multiple attention heads show similar behaviors, which implies the structural redundancy. Fortunately, S2ViTE eliminates unnecessary heads to some extent. With regard to SViTE-Base’s visual results, it seems to activate fewer attention heads for predictions (darker colors mean larger values), compared to the ones of dense DeiT-Base. We also observe that in the bottom layers, the attention probabilities are more centered at several heads; while in the top layers, the attention probabilities are more uniformly distributed. This kind of tendency is well preserved by our sparse ViT (SViTE) from Dense ViTs.
Learned patch selection patterns.
Figure 5 presents the learned behaviors of our token selector in SViTE+. We observe that the useless removed patches are typically distributed around the main object or in the background. Meanwhile, the patches within the objects of interest are largely persevered, which evidences the effectiveness of our learned patch token selector.
Conclusion and Discussion of Broader Impact
In this work, we introduce sparse ViT exploration algorithms, SViTE, and its variants S2ViTE and SViTE+, to explore high-quality sparse patterns in both ViT’s architecture and input token embeddings, alleviating training memory bottleneck and pursuing inference ultra-efficiency (e.g., running time and FLOPs). Comprehensive experiments on ImageNet validate the effectiveness of our proposal. Our informative visualizations further demonstrate that SViTE+ is capable of mining crucial connections and input tokens by eliminating redundant units and dropping useless token embeddings. Future work includes examining the performance of our sparse ViTs on incoming hardware accelerators , which will provide better supports for sparsity.
This work is scientific in nature, and we do not believe it has immediate negative societal impacts. Our findings of sparse vision transformers are highly likely to reduce both memory and energy costs substantially, leading to economic deployment in real-world applications (e.g., on smartphones).
Acknowledgment
Z.W. is in part supported by an NSF RTML project (#2053279).
References
Checklist
Do the main claims made in the abstract and introduction accurately reflect the paper’s contributions and scope? [Yes]
Did you describe the limitations of your work? [Yes] Please see section 4.3.
Did you discuss any potential negative societal impacts of your work? [Yes] Please see section 5.
Have you read the ethics review guidelines and ensured that your paper conforms to them? [Yes]
If you are including theoretical results…
Did you state the full set of assumptions of all theoretical results? [N/A] Our work does not contain theoretical results.
Did you include complete proofs of all theoretical results? [N/A] Our work does not contain theoretical results.
Did you include the code, data, and instructions needed to reproduce the main experimental results (either in the supplemental material or as a URL)? [Yes] We used publicly available data in all of our experiments. Meanwhile we either provide the detailed implementations or cite the papers of them following the authors instructions (See Section 4). All of our codes are provided in https://github.com/VITA-Group/SViTE.
Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)? [Yes] We provides all the training details in Section 4.
Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)? [No] We did not report the error bars since running vision transformer on ImageNet are extremely resource-consuming. For example, each reported number takes around V100 GPU hours. We will continue running the experiments and report the confidence intervals in future versions.
Did you include the total amount of compute and the type of resources used (e.g., type of GPUs, internal cluster, or cloud provider)? [Yes] We describe the details of computation resources in Section A1 of the supplement.
If you are using existing assets (e.g., code, data, models) or curating/releasing new assets…
If your work uses existing assets, did you cite the creators? [Yes] We used publicly available data, i.e., ImageNet, in our experiments. We cited the corresponding papers published by the creators in Section 4.
Did you mention the license of the assets? [No] The license of ImageNet is included in the paper that we have cited.
Did you include any new assets either in the supplemental material or as a URL? [Yes] The ImageNet we used are publicly available. And all our codes are included in https://github.com/VITA-Group/SViTE.
Did you discuss whether and how consent was obtained from people whose data you’re using/curating? [N/A] We did not collect/curate new data.
Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content? [N/A] All ImageNet datasets are already publicly available and broadly adopted. I do not think there are any issues of personally identifiable information or offensive content.
If you used crowdsourcing or conducted research with human subjects…
Did you include the full text of instructions given to participants and screenshots, if applicable? [N/A]
Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable? [N/A]
Did you include the estimated hourly wage paid to participants and the total amount spent on participant compensation? [N/A]
Appendix A1 More Implementation Details
All experiments use Tesla V100-SXM2-32GB GPUs as computing resources. Specifically, each experiment is ran with V100s for days.
Why do we choose 600600600 training epochs for SViTE experiments?
Choosing training epochs for sparse training is to maintain similar training FLOPs compared to dense ViT training. Specifically, if training a dense DeiT model for epochs needs x FLOPs, training SViTE-DeiT at sparsity for epochs needs x FLOPs. In summary, we compare our SViTE ( epochs) and DeiT baselines ( epochs) based on a similar training budget. Such comparison fashion is widely adopted in sparse training literature like (see Table ’s caption in and Figure in for details). Meanwhile, note that the reported running time is per epoch saving (i.e., total running time / total epoch), which would not be affected by the number of training epochs.
Baseline models with longer epochs.
Actually, the performance of DeiT training without distillation saturates after epochs, as stated in . We also conduct longer epoch ( epochs) training for DeiT-Small and -Base models. Our results collected in the table A7 align with the original DeiT paper . It suggests that our proposed SViTE is still able to achieve better accuracy with fewer parameters and fewer training&inference computations. Specifically, at structured sparsity, our sparsified DeiT-Base can achieve accuracy gain, at training FLOPs, inference FLOPs, and running time savings, compared to its dense counterpart with epochs.
Appendix A2 More Experimental Results
As shown in Figure A6, we observe that from the initial random mask to explored mask in SViTE, plenty of structural patterns emerge (i.e., the darker “vertical" lines mean completely pruned neurons in the MLPs). It is supervising that unstructured sparse exploration can lead to structured patterns, which implies the great potential to be accelerated in real-world hardware devices.
Sparse topology of S2ViTE-Base with structured sparsity.
Figure A7 shows mask visualizations of pruned multi-attention heads and MLPs in vision transformers. It shows that S2ViTE indeed explores totally different connectivity patterns, compared to the initial topology.
Ablation of only applying our learnable token selector.
We compare these three setup: (a) DeiT-Small ( test accuracy); (b) DeiT-Small + Token selector with data sparsity ( test accuracy); (c) DeiT-Small + Token selector with data sparsity + SViTE with unstructured sparsity ( test accuracy). It demonstrates that simultaneously enforcing data and architecture sparsity brings more performance gains.
Ablation of the layerwise sparsity of attention maps.
As shown in Table A8, we investigate the layerwise sparsity of attention maps. Dense DeiT-Small and SViTE+-Small with data sparsity and model sparsity are adopted for experiments. We calculate the percentage of elements in attention maps whose magnitude is smaller than . We observe that the bottom layers’ attention maps of SViTE+ are denser than the ones in dense ViT, while it is opposite for the top layers.