Swin Transform model compression method fusing weight sharing, pruning and distillation
By integrating weight sharing, pruning and distillation technologies into the Swin Transformer model, the problem of model calculation complexity and performance balance in the existing technology is solved, and the model is lightweight and performance is maintained.
Patent Information
- Application Number
- CN202410870830.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-07-01
- Publication Date
- 2024-10-29
- Estimated Expiration
- 2044-07-01
AI Technical Summary
Existing SwinTransformer model compression methods have not yet found a good balance between computational complexity and performance, and it is difficult to coordinate multiple compression technologies to reduce model computational complexity.
Using a method that integrates weight sharing, pruning and distillation, by sharing weights between multiple layers of the Swin Transformer model, a parameter dependency map is constructed for structured pruning, and the KL divergence distillation method is used to restore performance.
The Swin Transformer model has been successfully lightweighted, effectively balancing the relationship between computational complexity and performance, reducing model computational complexity and maintaining high performance.
Smart Images

Figure CN118862995A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of neural network technology, and in particular to a SwinTransformer model compression method integrating weight sharing, pruning and distillation. Background Art
[0002] In recent years, in pursuit of better model performance, the structure of deep neural networks has become increasingly complex, resulting in an increase in the computational complexity of the models, which has brought great challenges to computing and storage capabilities. The SwinTransformer (Shifted Window Hierarchical Visual Transformer) model has been widely used due to its excellent performance. This model improves the problems of the traditional Transformer model in computer vision tasks and introduces the "ShiftedWindow" mechanism, becoming a model architecture that performs well in visual tasks. However, the model has a high computational complexity. For example, the Swin-Large trained on the ImageNet-1K dataset has a parameter count of up to 197 million (M), making these models unsuitable for applications with limited computing resources, such as edge computing, the Internet of Things, and real-time prediction applications. Studies have shown that large-scale pre-trained models have the problem of over-parameterization. Therefore, it is necessary and feasible to compress and optimize the pre-trained models and eliminate the redundant parameters of the models without affecting the performance of these pre-trained models as much as possible. The compressed Swin Transformer model will be more adaptable to various application scenarios while controlling the deployment cost, which is extremely important for building efficient intelligent systems and ensuring their effective application in a variety of environments.
[0003] Although the existing SwinTransformer model compression method has achieved certain success, it still faces some difficulties: First, the current model compression method has not yet found a good balance between computational complexity and performance. At the same time, existing research still has shortcomings in how to coordinate the relationship between multiple compression technologies and improve the model compression effect. Therefore, how to integrate multiple model compression technologies to reduce the model computational complexity and achieve model lightweighting without losing model performance as much as possible is an urgent problem to be solved. Summary of the invention
[0004] The technical problem to be solved by the present invention is how to provide a Swin Transformer model compression method that can effectively reduce the complexity of the model and better balance the relationship between the model calculation complexity and the model performance.
[0005] In order to solve the above technical problems, the technical solution adopted by the present invention is: a Swin Transformer model compression method integrating weight sharing, pruning and distillation, comprising the following steps:
[0006] Weight sharing: Share weights between multiple layers of the Swin Transformer model, and add transformation layers between the layers of the model to achieve weight transformation;
[0007] Structured pruning: Build and analyze the parameter dependency map of the transformation block to obtain the mutual dependency between parameters, and build a binary grouping matrix F to record the dependency between all parameters. Parameter grouping is achieved through a depth-first search algorithm, and parameters belonging to the same group will be removed at the same time.
[0008] Distillation: Use the KL divergence distillation method to restore the performance of the model after weight sharing and structured pruning.
[0009] The beneficial effect of adopting the above technical solution is that the method successfully realizes the lightweight of the Swin Transformer model by integrating multiple compression technologies, and effectively balances the relationship between computational complexity and performance. BRIEF DESCRIPTION OF THE DRAWINGS
[0010] The present invention will be further described in detail below in conjunction with the accompanying drawings and specific embodiments.
[0011] Figure 1 is a flow chart of the method described in an embodiment of the present invention;
[0012] Figure 2 is a principle block diagram of classic weight sharing in the method described in an embodiment of the present invention;
[0013] Figure 3 is a principle block diagram of weight transformation sharing in the method described in an embodiment of the present invention;
[0014] Figure 4 is a block diagram of MSA and MLP linear transformation in the method according to an embodiment of the present invention;
[0015] Figure 5 are different dependency graphs of a neural network in the method according to an embodiment of the present invention;
[0016] Figure 6 2 is a curve diagram of training accuracy change in an embodiment of the present invention. DETAILED DESCRIPTION
[0017] The following is a clear and complete description of the technical solutions in the embodiments of the present invention in conjunction with the drawings in the embodiments of the present invention. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0018] In the following description, many specific details are set forth to facilitate a full understanding of the present invention, but the present invention may also be implemented in other ways different from those described herein, and those skilled in the art may make similar generalizations without violating the connotation of the present invention. Therefore, the present invention is not limited to the specific embodiments disclosed below.
[0019] Overall, such as Figure 1 As shown, an embodiment of the present invention discloses a SwinTransformer model compression method integrating weight sharing, pruning and distillation, and the method comprises the following steps:
[0020] First, weights are shared among multiple layers of the Swin Transformer model to improve parameter utilization, and transformation layers are added to implement weight transformation to increase parameter diversity.
[0021] Secondly, the parameter dependency map of the transformation block is constructed and analyzed to obtain the mutual dependence between the parameters, and a binary grouping matrix F is constructed to record the dependency between all parameters. The parameter grouping is realized through the depth-first search (DFS) algorithm, and the parameters belonging to the same group are removed at the same time, thereby reducing the computational complexity of the model and accelerating the model reasoning.
[0022] Finally, the KL divergence distillation method is used to solve the problem of performance degradation caused by weight sharing and pruning.
[0023] Weight Sharing
[0024] Weight sharing is an effective way to improve parameter utilization efficiency. Its core idea is to share parameters across layers. Classic weight sharing is as follows: Figure 2 As shown,
[0025] Weight sharing can be expressed as a recursive update of a Transformer block:
[0026] Z i+1 =f(Z i ;θ),i=0,...,L-1 (1)
[0027] Where Z irepresents the feature embedding of the i-th layer sequence, L is the total number of layers, and θ is the weight shared across the layers of the Transformer block. Weight sharing can prevent the number of parameters from growing as the depth of the network grows. This application proposes a weight sharing method, specifically, first merging multiple layers of weights into a shared single weight, while involving transformations to increase parameter diversity.
[0028] The key idea of weight transformation is to transform the shared weights so that different layers have slightly different weights. This can not only promote parameter diversity, but also improve the expressiveness and training stability of the model.
[0029] Weight transformation sharing Figure 3 As shown, the present application combines multiple layers of weights into a single weight on the shared part, and adds a transformation layer to increase parameter diversity. T(x) represents the transformation of the weights.
[0030] like Figure 4 As shown, the present application applies linear transformations to the weights of Multi-head Self-Attention (MSA) and Multilayer Perceptron (MLP) for each weight-shared transformation layer. Each layer includes a separate transformation matrix, so the weights of the MSA module and the MLP module are different between layers. The weights of MSA and MLP are shared at each stage, and two transformation layers are added to increase the diversity of parameters.
[0031] MSA transformation: To improve parameter diversity, we insert two linear transformations before and after the softmax self-attention module. The transformed attention is defined as:
[0032]
[0033]
[0034] Where M is the number of attention heads, d is the dimension of the query, key, and value matrices. At the Kth head, the query, key, and value are generated by linear projection, respectively using Q k , K k and V k ∈R N×d Indicated by A k Indicates that softmax acts on each row of the input matrix. (1) , F (2) ∈R M×M They are the linear transformations before and after softmax. Such linear transformations can make each attention matrix A nDifferent from the previous one, the information between attention heads can be combined to increase parameter variance. Finally, a fully connected layer is applied to the connection of all head outputs.
[0035] MLP transformation: A lightweight transformation is introduced into MLP to improve parameter diversity. In particular, let the input be Y = [y1,...,y d ], where y d Represents the embedding vector of the dth position of all tokens. Then introduce d-dimensional linear transformation to transform Y into Y'=[C (1) y1,...,C (d) y d ], where C (1) ,...,C (d) ∈R N×N is the independent weight matrix of the linear layer, and then the MLP output is re-expressed as:
[0036] H=σ(Y'W (1) +b (1) )W (2) +b (2) (4)
[0037] Where σ represents the activation function, W (1) ∈R d×d' , b (1) ∈R d' , W (2) ∈R d'×d and b (2) ∈R d are the weights and biases of the first and second layers, respectively. Usually, d'>d is set. In order to reduce the number of parameters and introduce locality in the transformation, deep convolution is used to sparse and share the weights in each weight matrix, so that the number of parameters is K 2 d, not N 2 d(K<<N), where K is the convolution kernel size. After the transformation, the output of MLP is more diversified and the parameter utilization efficiency is improved.
[0038] Structured pruning:
[0039] The goal of network pruning is to remove redundant parameters from a given network to reduce its size and potentially speed up inference. In this application, by constructing a parameter dependency map of the transformation block, the interdependence between parameters is deeply analyzed, and the interdependent parameters are grouped together. The importance of each group of parameters is calculated by the L2 norm, and pruning is performed according to the importance of each group of parameters according to the set pruning ratio.
[0040] like Figure 5As shown in Figure 1, starting from a linear neural network consisting of three consecutive layers, this simple neural network can be structurally pruned by removing neurons to make it thinner. In this case, it is easy to see that some dependencies emerge between the parameters, which forces W L and W L+1 At the same time being pruned.
[0041] Specifically, in order to prune the connection W L and W L+1 The kth neuron, W L [k, :] and W L+1 [:, k] will all be deleted. When you want to achieve acceleration by pruning a neuron (indicated by black), multiple sets of parameters connected to the neuron need to be removed at the same time. These interdependent parameters constitute the smallest unit of structured pruning, usually called a group.
[0042] Then, the parameter dependency in the SwinTransformer model is modeled. In structured pruning, the parameters in the same group are dependent on each other. When you want to remove one of them, all the parameters belonging to the group need to be removed simultaneously to ensure the correctness of the structure. A binary grouping matrix F is constructed to record the dependency between all parameter pairs. If the parameters of the i-th layer and the j-th layer are dependent on each other, F is used. ij In this way, the grouping of parameters can be simply modeled as a query problem.
[0043] f(i)={j|F ij =1} (5)
[0044] However, whether parameters are interdependent is not only determined by themselves, but also affected by the intermediate layers between them. The dependency between adjacent layers can be recursively inferred. For example, there is a dependency between adjacent layers A and B, and there is also a dependency between adjacent layers B and C. Then it can be recursively inferred that there is also a dependency between A and C, although A and C are not directly connected. Then, using the local dependency between adjacent layers, the required grouping matrix F is recursively derived. This local dependency between adjacent layers is called a dependency map, which is a sparse and local relationship map because it only models the dependencies between directly connected layers.
[0045] Therefore, the grouping problem can be simplified into a path search problem. When there is a path between node i and node j in the dependency map, we can get F ij=1, that is, i and j belong to the same group, and the grouping is performed using the depth-first search (DFS) algorithm. Starting from a certain node i, find a new node j connected to it in the dependency map and merge it into the current group until there are no new connected nodes. Then, the parameters belonging to the same group will be removed at the same time to achieve model compression.
[0046] Distillation:
[0047] In order to solve the performance degradation problem caused by weight sharing and pruning, distillation is further used to transfer knowledge from large models to small compact models. The model obtained by pruning and weight sharing is retrained, and the obtained model is used as the student model in distillation.
[0048] The established distillation objective function is:
[0049] L train =L pred +D KL (6)
[0050] Where L pred To predict the loss, D KL is the KL divergence loss.
[0051] Consider predicting logit distillation. The prediction loss is as follows:
[0052]
[0053] Among them, z s and z t are the logits predicted by the student model and the teacher model, respectively, and T is the temperature value, which is used to control the smoothness of the logits. In the experiments of this application, T is set to 1. CE represents the cross entropy loss.
[0054] At the same time, the KL (Kullback-Leibler divergence) divergence method in knowledge distillation is used to improve the accuracy of the Swin Transformer student model. KL divergence not only allows the student model to replicate the direct output of the teacher model, but also imitates subtle changes in its probability distribution, thereby capturing richer inter-class relationships and probabilistic structures. By minimizing the KL divergence between the student model output and the teacher model output, the student model can more accurately approximate the decision boundary of the teacher model, which is especially critical in complex image classification tasks. In addition, compared with traditional classification losses, KL divergence provides the student model with more detailed error signals, which helps it achieve more robust learning during training.
[0055]
[0056] Among them, P and Q are the output probability distributions of the teacher and student models respectively. After softmax processing, the probability values of each category i are P(i) and Q(i).
[0057] Test results and analysis:
[0058] The performance of the method described in this application on the ImageNet-Tiny-200 dataset was evaluated for the Swin Transformer model used for image classification tasks. First, a performance benchmark for an uncompressed Swin Transformer baseline model was established. Subsequently, independent tests were conducted on the model compressed using the Torch-Pruning model compression technique and the model compressed using the method proposed in this application, and the performance of these three different models was compared and analyzed.
[0059] Experimental results show that compared with the original uncompressed Swin Transformer model, the compression method proposed in this application reduces the model computational complexity by 32%, with a minimum performance drop of only about 3%. This conclusion strongly proves that the compression method described in this application effectively reduces the model size while ensuring high performance. In contrast, the model compression method proposed in this application surpasses the existing Torch-Pruning technology and shows superior performance in maintaining a balance between model performance and compression rate.
[0060] Experimental settings and datasets:
[0061] This embodiment uses three models of different sizes, Swin-Tiny, Swin-Small and Swin-Base, as baseline models. The ImageNet-Tiny-200 dataset is used, which contains 200 categories, each of which is composed of a subset of the ImageNet large dataset, providing 100,000 pictures, with approximately 500 training pictures, 50 verification pictures and 50 test pictures for each category. During the training process, the application uses the Adam optimizer with a learning rate of 10e-4 to train the model, and the learning rate decays exponentially, and the learning rate decay factor is set to 0.95 to ensure sufficient training. The experimental code is written in Python, using the Pytorch deep learning framework, and training and testing are performed on NVIDIA 3090. This experiment is compared with the currently popular model compression method Torch-Pruning, and the comparison indicators specifically include: parameter quantity, calculation amount, model recognition accuracy, etc.
[0062] Experimental results analysis:
[0063] For Swin Transformer models of different sizes, we selected a batch_size of 64 and trained them for 50 rounds. We also compared the changes in accuracy of the original model, Torch-pruning, and the model after compression using the proposed method. The changes in the training accuracy of the three models on the ImageNet-Tiny-200 dataset are shown in the figure below. Figure 6 shown.
[0064] like Figure 6 As shown in the figure, the model pruned by the Torch-pruning method reduced the number of parameters by 30.69% on the Tiny-scale Swin Transformer model compared to the baseline model, but the Top-1 accuracy of the corresponding model decreased by 6.94%. However, the method described in this application has an average performance loss of only about 4.5% under the condition of lower model calculation complexity, which is better than the comparison method.
[0065] It can be seen that the accuracy of the model after compression by the method described in this application is maintained at a high level, indicating that this method reduces the computational complexity of the model while maintaining a balance between model performance and compression rate. It should be noted that the blue curve in the figure has a higher recognition accuracy in the first round because the model has been retrained before distillation. The blue curve in the figure is a performance change curve in the final distillation training stage.
[0066] Table 1 Model performance computational complexity
[0067]
[0068] In Table 1, the baseline Swin method is the method in "Hierarchical vision transformer using shiftedwindows[C] / / Proceedings of the IEEE / CVF international conference on computervision.2021:10012-10022.";
[0069] In Table 1, the Torch-Pruning method is the method in "Fang G, Ma X, Song M, et al. Depgraph: Towards any structural pruning[C] / / Proceedings of the IEEE / CVF Conference on Computer Vision and Pattern Recognition. 2023: 16091-16101."
[0070] Table 1 is a comparison of the model performance and computational complexity after compression of the original model, the Torch-pruning method, and the method described in this application, where the performance loss and compression rate are calculated as the percentage of the Top-1 and parameter reduction values to the original values, respectively. The results in the table show that the traditional model compression algorithm has a significant decline in model performance under high-multiple compression, resulting in a large loss in model performance. However, the method described in this application has a better balance between the number of parameters, the amount of computation, and the classification accuracy. Compared with the Torch-Pruning model compression algorithm, the method described in this application has achieved an average increase of 3.5% in image classification accuracy with lower model computational complexity. Compared with the original baseline model, the average loss in classification accuracy is about 4.5%.
[0071] The method achieves lightweight SwinTransformer model and better balances the relationship between model computational complexity and performance. Experiments on the ImageNet-Tiny-200 public dataset show that compared with the original uncompressed Swin Transformer model, after adopting the compression method described in this application, the model computational complexity is reduced by 32%, with a minimum performance drop of only about 3%, effectively reducing the model computational complexity.
Claims
1. A Swin Transformer model compression method integrating weight sharing, pruning and distillation, characterized in that The steps include: Weight sharing: Share weights between multiple layers of the Swin Transformer model and add transformation layers between the layers of the model to achieve weight transformation; Structured pruning: Build and analyze the parameter dependency map of the transformation block to obtain the mutual dependency between parameters, and build a binary grouping matrix F to record the dependency between all parameters. Parameter grouping is achieved through a depth-first search algorithm, and parameters belonging to the same group will be removed at the same time. Distillation: Use the KL divergence distillation method to restore the performance of the model after weight sharing and structured pruning.
2. The Swin Transformer model compression method integrating weight sharing, pruning and distillation according to claim 1, characterized in that: In the weight sharing: Multiple layers of weights are combined into a single weight on the shared parts, while transformation layers are added to increase parameter diversity.
3. The Swin Transformer model compression method integrating weight sharing, pruning and distillation according to claim 2, characterized in that: A linear transformation is applied to the weights of the multi-head self-attention MSA module and the multi-layer perceptron MLP module in the model, for each weight-shared transformation layer; each layer includes a separate transformation matrix, the weights of the MSA module and the MLP module are different between layers, the weights of the MSA and MLP are shared at each stage, and two transformation layers are added to increase the diversity of parameters.
4. The Swin Transformer model compression method integrating weight sharing, pruning and distillation according to claim 3, characterized in that: MSA transformation is performed in the multi-head self-attention MSA module: Two linear transformations are inserted before and after the softmax self-attention module, and the transformed attention is defined as: Where M is the number of attention heads, d is the dimension of the query, key, and value matrices. At the Kth head, linear projection is used to generate the query, key, and value, respectively. k , K k and V k ∈R N×d Indicated by A k Indicates that softmax acts on each row of the input matrix; F (1) , F (2) ∈R M×M They are the linear transformations before and after softmax, respectively. The linear transformation makes each attention matrix A n Different from the previous one, the information between attention heads is combined to increase parameter variance. Finally, a fully connected layer is applied to the concatenation of all head outputs.
5. The Swin Transformer model compression method integrating weight sharing, pruning and distillation according to claim 3, characterized in that: Perform MLP transformation in the multi-layer perceptron MLP module: Introduce a lightweight transformation in MLP, let the input be Y = [y1,...,y d ], where y d Represents the embedding vector of the d-th position of all tokens; then introduce a d-dimensional linear transformation to transform Y into Y'=[C (1) y1,...,C (d) y d ], where C (1) ,...,C (d) ∈R N×N For the linear layer independent weight matrix, then the MLP output is re-expressed as: H=σ(Y'W (1) +b (1) )W (2) +b (2) In the formula, σ represents the activation function, W (1) ∈R d×d ', b (1) ∈R d ', W (2) ∈R d ' ×d and b (2) ∈R d are the weights and biases of the first and second layers, respectively. Set d'>d; use depthwise convolution to sparse and share the weights in each weight matrix, so that the number of parameters is K 2 d, not N 2 d(K<<N), where K is the convolution kernel size.
6. The Swin Transformer model compression method integrating weight sharing, pruning and distillation according to claim 1, characterized in that: In the structured pruning: By constructing a parameter dependency map of the transformation block, we deeply analyze the interdependence between parameters and group the interdependent parameters together. We calculate the importance of each group of parameters using the L2 norm and perform pruning based on the importance of each group of parameters according to the set pruning ratio.
7. The Swin Transformer model compression method integrating weight sharing, pruning and distillation according to claim 6, characterized in that: Prune Connection W L and W L+1 The kth neuron of L [k, :] and W L+1 [:, k] deletion, when speeding up a neuron by pruning it, multiple groups of parameters connected to the neuron need to be removed at the same time. These interdependent parameters constitute the smallest unit of structured pruning, called a group; The parameter dependency in the Swin Transformer model is modeled. In structured pruning, the parameters in the same group are dependent on each other. When one of them is to be removed, all the parameters belonging to the group need to be removed simultaneously. A binary grouping matrix F is constructed to record the dependency between all parameter pairs. If the parameters of the i-th layer and the j-th layer are dependent on each other, F is used. ij To represent, the grouping of parameters is modeled as a query problem: f(i)={j|F ij =1} The required grouping matrix F is recursively derived by using the local dependency relationship between adjacent layers. This local dependency relationship between adjacent layers is called a dependency map, which is a sparse and local relationship map that only models the dependencies of directly connected layers. Therefore, the grouping problem is simplified to a path search problem. When there is a path between node i and node j in the dependency map, we get F ij =1, that is, i and j belong to the same group, and the grouping is performed using the depth-first search DFS algorithm; starting from a certain node i, find a new node j connected to it in the dependency map and merge it into the current group until there are no new connected nodes. Then, the parameters belonging to the same group will be removed at the same time to achieve model compression.
8. The Swin Transformer model compression method integrating weight sharing, pruning and distillation according to claim 1, characterized in that: Retrain the model obtained by pruning and weight sharing, and use the obtained model as the student model in distillation; The established distillation objective function is: L train =L pred +D KL Where P and Q are the output probability distributions of the teacher and student models, respectively. After softmax processing, the probability values of each category i are P(i) and Q(i); Consider predicting log-logit distillation, where the prediction loss is as follows: Among them, z s and z t are the logits predicted by the student model and the teacher model, respectively. T is the temperature value used to control the smoothness of the logits. CE represents the cross entropy loss. At the same time, the KL divergence method in knowledge distillation is used to improve the accuracy of the Swin Transformer student model; by minimizing the KL divergence between the student model output and the teacher model output, the student model is closer to the decision boundary of the teacher model. The KL divergence loss formula is: Among them, P and Q are the output probability distributions of the teacher and student models respectively. After softmax processing, the probability values of each category i are P(i) and Q(i).
Citation Information
Patent Citations
Compression method for dynamically trimming weights of deep neural network and sharing weights
CN110210618A
Pollen image classification method based on cross attention distillation Transformer
CN113887610A
SAR optical image mapping model lightweight method based on conditional generative adversarial network
CN114202017A
Image classification model compression method based on greedy strategy
CN115810128A
Network model rarefaction method fusing attention weight pruning
CN117669665A
