Network structure construction method and device based on knowledge distillation
Through a token selection network based on knowledge distillation, combined with channel and spatial information fusion, it solves the problems of compatibility and generalization properties of existing token cropping methods, and achieves efficient calculation reduction and accuracy improvement in image classification tasks.
Patent Information
- Application Number
- CN202410679289.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-05-29
- Publication Date
- 2024-10-11
- Estimated Expiration
- 2044-05-29
AI Technical Summary
While reducing the amount of calculation, the existing token pruning method results in an incomplete spatial structure that is incompatible with deep and narrow Transformers, and requires a time-consuming pre-training process. Moreover, the heavily designed token pruning network structure lacks generalization properties and is difficult to implement. Apply directly on other models.
Using a token selection network based on knowledge distillation, by designing a visual Transformer model for token selection, using a preset fully connected layer to score image patches, and distilling the necessity score from the teacher network, combined with the fusion of channel and spatial information, the design is lightweight A large amount of tokens can be used to select the network, and it can be plug-and-play after training to reduce the amount of calculation.
It is possible to reduce the amount of calculation in image classification tasks while maintaining or improving accuracy. The network model can better retain useful information, use image spatial correlation, limit the range of accuracy decline to a smaller range, and does not rely on specific Network structure.
Smart Images

Figure CN118761439A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of network structure construction, and specifically to a network structure construction method and device based on knowledge distillation. Background Art
[0002] In recent years, ViT has become popular in image classification and visual analysis tasks.
[0003] However, its huge computational cost still limits its use in some applications. Since the computational complexity of ViT is quadratic with respect to the input sequence length, the mainstream paradigm to reduce the amount of computation is to reduce the number of tokens.
[0004] Researchers have proposed several methods, including structured spatial compression, using progressively shrinking pyramids to reduce computation of large feature maps, and unstructured token pruning. However, existing token pruning methods still have some limitations.
[0005] However, one of the limitations is that the incomplete spatial structure they create is incompatible with the structured spatial compression commonly used in modern deep and narrow Transformers. In addition, they usually require a time-consuming pre-training process. Finally, these highly designed token pruning network structures do not have the characteristics of generalization, and their transferability is not strong. This method cannot be simply applied to other models. If you want to use a certain token pruning strategy, you must carefully redesign each model.
[0006] Therefore, a new solution to the above problems needs to be proposed. Summary of the invention
[0007] The purpose of the present invention is to provide a method and device for constructing a network structure based on knowledge distillation, so as to solve the characteristic limitation that the token clipping strategy does not have generalization and expand the applicable scenarios, and then select a token network based on knowledge distillation. The network is very lightweight and does not depend on any network model structure. It is plug-and-play after training, and the amount of calculation is greatly reduced with a small loss of accuracy.
[0008] To achieve the above object, the present invention provides the following technical solution: a method for constructing a network structure based on knowledge distillation, comprising at least the following steps:
[0009] Step 1: Design a visual transformer model based on token selection, score the patch blocks of the input image through the preset fully connected layer, and score the token score with a size of (1×N), where N is the number of non-overlapping image patches divided by the original input image resolution (H, W) and the number of channels c, and the resolution of each patch block is (P, P);
[0010] Step 2: Design and train a Token selection network to distill the necessity score ranking information from the trained teacher network, obtain the hidden state of each patch by learning a specific projection matrix W and bias vector b, and perform necessity scoring;
[0011] Step 3: Design a visual transformer model for token selection named TS-ViT, distill the learned pruning header information from the trained structured token pruning network model, and train the token selection network;
[0012] Step 4: Design the loss function of TS-ViT;
[0013] Step 5: Perform image classification training and testing on a specific dataset using an optimized model used in conjunction with a token selection network to reduce computational effort and maintain or improve image classification accuracy.
[0014] Furthermore, the Token selection network in step 2 transforms the Token sequence through learning, and processes the spatial coordinate information of the Token by adding a 2D absolute position encoding based on sine and cosine functions to effectively integrate the position information.
[0015] Furthermore, the spatial coordinate information of the Token is processed by mixing the Token using channel-mixing and spatial-mixing blocks, thereby realizing the fusion of channel and spatial information. The relevant fully connected layers and activation functions are used to transform the optimized TS-token into the Token necessity score, thereby optimizing the Token selection process on the image classification dataset and improving the classification accuracy and efficiency of the model.
[0016] Furthermore, the step three at least includes the following steps:
[0017] Suppose there is an image I of size H×W, where H represents height and W represents width;
[0018] This image can be divided into image blocks of size P×P, where P is a predefined block size;
[0019] Each chunk is linearly projected into a token x of size C i , where i∈[1,N];
[0020] Add the position vector in step 2 to obtain a token sequence X of size N×C containing position information. At the same time, Tokenscore∈R can be obtained in the Token selection network.1×N ;
[0021] Next, the tokens are sorted according to the Token score, and the first N*ratio tokens are retained. Ratio is a hyperparameter that can be set according to the actual situation.
[0022] Finally, a tensor of size (N*ratio)×C is obtained and sent to the Transformer Encoder.
[0023] Furthermore, the loss function of the TS-ViT includes the task loss and the regression loss Lts of the difference between the necessity score of the patch given by the Token selection network and the score given by the teacher model.
[0024] A network structure construction device based on knowledge distillation, comprising at least an input unit, a scoring unit, a token selection unit, a loss function unit, and a training and testing unit;
[0025] The input unit is used to receive an input image and divide it into Patch blocks;
[0026] The scoring unit includes a preset fully connected layer, and the scoring unit is used to score the Patch block and generate a Token score;
[0027] The Token selection unit includes a projection matrix W and a bias vector b, and the Token selection unit is used to distill the necessity score from the teacher network and perform necessity scoring on the hidden state of each Patch block;
[0028] The loss function unit includes a task loss part and a regression loss part of the difference between the score of the Token selection network and the teacher model;
[0029] The training and testing unit is used to train and test the model on a specific data set to optimize the accuracy and efficiency of image classification.
[0030] Compared with the prior art, the present invention has the following beneficial effects:
[0031] The present invention is based on a Token selection network based on knowledge distillation. The network is very lightweight and does not rely on any network model structure. It is plug-and-play after training and can greatly reduce the amount of calculation with a small loss of accuracy. The network model can better retain useful information when performing image cutting and can better utilize the spatial correlation in the image. It can achieve higher efficiency by cutting the amount of calculation and limit the range of accuracy drop to a relatively small range. BRIEF DESCRIPTION OF THE DRAWINGS
[0032] In order to more clearly illustrate the technical solutions of the embodiments of the present invention, the accompanying drawings required for describing the embodiments will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of the present invention. For ordinary technicians in this field, other accompanying drawings can be obtained based on these accompanying drawings without paying creative work.
[0033] Figure 1 Select a network for the Token of the present invention to insert a usage diagram;
[0034] Figure 2 Select a network structure diagram for the Token of the present invention;
[0035] Figure 3 It is a schematic diagram of the TS-ViT structure of the present invention. DETAILED DESCRIPTION
[0036] The technical solutions in the embodiments of the present invention will be described clearly and completely below 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, rather than all the embodiments.
[0037] Embodiment 1:
[0038] See also Figure 1 - Figure 3 , a network structure construction method based on knowledge distillation, comprising at least the following steps:
[0039] Step 1: Design a visual transformer model based on token selection, score the patch blocks of the input image through the preset fully connected layer, and score the token score with a size of (1×N), where N is the number of non-overlapping image patches divided by the original input image resolution (H, W) and the number of channels c, and the resolution of each patch block is (P, P);
[0040] The visual transformer model based on Token selection designed in step 1 is as follows Figure 1 As shown in Figure 2. The visual transformer model needs to be able to obtain the importance information of the patch block after training. The specific design of the Token selection network structure is as follows: Figure 2 (a) shown.
[0041] The Token selection network scores each patch of the input image based on the input image. If the image is divided into N blocks, it will output a Token-score of size (1×N), representing the score of each of the N patches. The resolution of the original input image is (H, W), and the number of channels is c. The Token selection network will divide this image into N (N=H*W / P*P) non-overlapping image patch sequences as input, and obtain a four-dimensional tensor X' of size N×P×P×c. Then all patches will become hidden dimensions C after passing through the same fully connected layer (Per-patchFully-connected). Specifically, it can be expressed using the following formula:
[0042] Z=X′W+b
[0043] Flatten each patch in Z into a one-dimensional vector to obtain a two-dimensional Table of size N×(P×P×c), which can be represented as a two-dimensional tensor X of size N×C:
[0044] X = reshape(Z,[N,C])
[0045] Get a token sequence X∈R N×C . Add positional encoding to it, for each token x i , embedding its position information into vector pos i Add to the sequence to form position embedding token x pos,i , that is, x pos,i =x i +pos i , where pos i It can be expressed as:
[0046]
[0047] Add TS-token before the Token sequence, which is at the first position in the Token sequence. It is learnable and is used to integrate the necessity score ranking information between tokens. At this time, the token sequence X∈R (N+1)×C .
[0048] X=Concat(Ts-token,X)
[0049] Next, Token selects two main parts of the network: Channel Mixing Block and Spatial Mixing Block. Figure 2As shown in (b), the channel mixing module has the same structure as the spatial mixing module, which consists of an LN layer and an MLP layer. The MLP layer consists of two fully-connected layers and an activation function. The token selection network uses the channel-mixing MLP and token-mixing MLP to map the rows and columns of the Table respectively. Similar to the Per-patch Fully-connected, the channel-mixing MLP and token-mixing MLP share weights in the mapping process in different columns and rows:
[0050] U i,* =W2×σ(W1×LN(X) i,* ) for i=1..N+1
[0051] Y *,j =W4×σ(W3×LN(U) *,j ) for j=1..C
[0052] Where W1, W2 are the first and second layers of the channel-mixing MLP, W3, W4 are the first and second layers of the token-mixing MLP. σ represents GULE. U is the output of the Channel Mixing module, the input of the Spatial Mixing module, and Y is the output of the Spatial Mixing module. In the actual operation process, after U is obtained, it is transposed into the Spatial Mixing module to achieve the above-mentioned transformation operation on rows and columns.
[0053] After the channel-mixing block and token-mixing block extract the channel and space features, the previously embedded token-score is separated;
[0054] TokenScore=σ(W×Y 0,* )
[0055] Where σ represents Relu, Tokenscore∈R 1×N .
[0056] Step 2: Design and train a Token selection network to distill the necessity score ranking information from the trained teacher network, obtain the hidden state of each patch by learning a specific projection matrix W and bias vector b, and perform necessity scoring;
[0057] The token selection network transforms the token sequence by learning, and processes the spatial coordinate information of the token by adding 2D absolute position encoding based on sine and cosine functions to effectively integrate the position information. This method is specifically targeted at image classification datasets to enhance the model's ability to understand spatial information when processing image classification tasks;
[0058] The channel-mixing and spatial-mixing blocks are used to mix the tokens, thus achieving the fusion of channel and spatial information. In addition, the relevant fully connected layers and activation functions are used to transform the optimized TS-token into the token necessity score, thereby optimizing the token selection process on the image classification dataset and improving the classification accuracy and efficiency of the model;
[0059] Step 3: Design a visual transformer model for token selection named TS-ViT, such as Figure 3 As shown in (a), we distill the learned pruning header information from the trained structured token pruning network model and train the token selection network.
[0060] Suppose there is an image I of size H×W, where H represents height and W represents width. This image can be divided into image blocks of size P×P, where P is a predefined block size. Each block is linearly projected into a token x of size C. i , where i∈[1,N]. Add the position vector in step 2. Get a token sequence X of size N×C containing position information. At the same time, you can get Tokenscore∈R in the Token selection network. 1×N Next, the tokens are sorted according to Tokenscore, and the first N*ratio tokens are retained. Ratio is a hyperparameter that can be set according to the actual situation. Finally, a tensor of size (N*ratio)×C is obtained and sent to the Transformer Encoder. Specifically: the token sequence containing position information is represented as a matrix X of size N×C: X=[x_1,x_2,...,x_N]^T, where x iis the i-th token, T represents transposition, sort the token sequence according to the Token score, retain the first N×ratio blocks, and convert the Token score into a vector of size 1×N, where the i-th element represents the score corresponding to the i-th token. Next, use the element values in Token Score to sort the rows of X to obtain a new matrix Y, where the i-th row corresponds to the original row corresponding to the value of the i-th element in Token score after sorting. Specifically, it can be expressed using the following formula:
[0061] sorted_indices=arg sort(TokenScore)
[0062] Y = X[sorted_indices,:]
[0063] Among them, argsort(Token Score) is an index vector sorted by the element value in Token Score. Finally, the first N×ratio blocks are intercepted from Y to obtain a matrix Z of size (N×ratio)×C, which can be expressed as follows:
[0064] Z=Y[:N×ratio,:]
[0065] Here, Z is a two-dimensional tensor of size (N×ratio)×C.
[0066] Transformer Encoder Figure 3 As shown in (b), it consists of L Transformer blocks, where L is the number of layers in the model. Each block includes an MSA module and FFN. Z is sent to the Transformer Encoder for processing. To obtain the final encoded output, a tensor of size (N×ratio)×C, where each row represents the feature representation of an image block. This Transformer block is almost the same as the Transformer block in VIT, but does not contain class-token, so the pooling layer will be used at the end, as follows:
[0067] Z l ′=MSA(LN(Z l-1 ))+Z l-1 l=1..L
[0068] Z l ′=MSA(LN(Z l-1 ))+Z l-1 l=1..L
[0069] Y=LN(Z L )
[0070] Here, the size of Y is (N*ratio)×C. Finally, all feature vectors are integrated through an average pooling layer to obtain a tensor of size 1×C (C is the size of the model's embedding vector). This tensor contains the feature representation of the entire image. Finally, the tensor is input into a fully connected layer for tasks such as classification or regression. [i] The details are as follows:
[0071]
[0072] Perform an average pooling operation on Y to obtain a tensor Y' of size 1×C, and finally send Y' to the classification head to obtain the final probability output y.
[0073] During training, the image input will enter three modules in parallel. One is the backbone, which can be any backbone that uses tokens for patch input. It is used to output the final classification result and generate LCE classification loss. The Token selection suggestion network obtained in step 2 is used to generate token-scores for image patches. It is used to crop the tokens before the backbone tokens are input into the Transformer Encoder to remove unimportant tokens. Finally, there is the teacher model. Since the Token selection suggestion needs to learn the knowledge of the teacher model to select tokens, the teacher model also outputs a token-score. The Manhattan distance between the two, i.e. the L1 distance, is used as the Token score loss and recorded as TSLoss. It is added to the classification loss LCE as the final loss to assist in the Token selection network training.
[0074] Step 4: Design the loss function of TS-ViT. The loss function of TS-ViT consists of two parts: one is the task loss, and the other is the regression loss Lts of the difference between the necessity score of the patch given by the Token selection network and the score given by the teacher model. When using the TS-ViT model for classification tasks, the cross entropy loss function is used as the classification loss function during training. Suppose there is a training set containing M samples, there are a total of C categories, and the true label corresponding to the i-th sample is y i , the output probability of the TS-ViT model for this sample is p i . Then the classification loss Lce can be expressed as:
[0075]
[0076] Where log represents the natural logarithm function. When using the Token selection network model for token-score regression tasks, L1 loss is used as the regression loss function during training. Suppose there is a dataset containing M images, each of which is divided into N patches. The score of the jth token of the i-th image output by the Token selection network model corresponding to the jth patch of the i-th image is p i,j , the score of the jth token of the i-th image output by the corresponding evo-vit model is y i,j , then the L1 regression loss can be expressed as:
[0077]
[0078] The final loss is defined as:
[0079] L=Lce+λLts
[0080] Where λ is a hyperparameter used to balance the token score loss Lts and the classification loss LCE.
[0081] Step 5: Perform image classification training and testing on a specific dataset using an optimized model used in conjunction with a token selection network to reduce computational effort and maintain or improve image classification accuracy.
[0082] Embodiment 2:
[0083] This embodiment further discloses a method for a token selection model based on knowledge distillation based on the above embodiment 1;
[0084] Step 1: Perform image classification training and testing on the ImageNet-1K dataset for different model benchmarks. No other external data is used for training. The dataset contains 1,000 categories. Unless otherwise specified, the default image resolution used is 224×224 pixels.
[0085] Step 2: The Transformer Encoder in TS-ViT is roughly the same as that in ViT, except that the tokens input to the Transformer Encoder are selected and there is no class token.
[0086] Step 3: During the training of the Token Selection Network, the teacher model selected is the Evo-vit small model, and the hyperparameter λ is set to 10. The knowledge distillation of the Token Selection Network converges at 10 epochs, and after 10 epochs, the teacher model is no longer needed, and the token score loss Lts is no longer needed.
[0087] Step 4: On ImageNet-1k, the classification of TS-vit converges at about 300 epochs, and the training strategy is consistent with the deit training strategy.
[0088] The TS-vit-tiny baseline in the final TS-ViT model successfully reduces the computation by 40%, and the Top-1 accuracy on ImageNet drops by only within 0.8%.
[0089] Embodiment three:
[0090] This embodiment is used to further disclose a device for constructing a network structure based on knowledge distillation on the premise of the first embodiment, including: an input unit, a scoring unit, a Token selection unit, a loss function unit, and a training and testing unit;
[0091] The input unit is used to receive the input image and divide it into Patch blocks;
[0092] The scoring unit includes a preset fully connected layer, and the scoring unit is used to score the Patch block and generate a Token score;
[0093] The Token selection unit includes a projection matrix W and a bias vector b, and the Token selection unit is used to distill the necessity score from the teacher network and perform necessity scoring on the hidden state of each Patch block;
[0094] The loss function unit includes the task loss part and the regression loss part of the difference between the token selection network and the teacher model score;
[0095] The training and testing units are used to train and test the model on a specific dataset to optimize the accuracy and efficiency of image classification.
[0096] Embodiment 4:
[0097] This embodiment is used to disclose a computer-readable storage medium, which stores a computer program. When the program is executed by a processor, the method in the first embodiment is implemented, including:
[0098] Receive and process input images into Patch blocks;
[0099] Use the preset fully connected layer to score the Patch block to generate a Token score;
[0100] Distill the necessity scores from the teacher network through the Token selection network and score each patch block;
[0101] Apply loss function to train the model;
[0102] Train and test image classification on a specific dataset.
[0103] Embodiment five:
[0104] This embodiment is used to disclose a computer program product, including computer executable code, stored on a non-transitory computer readable medium, and used to execute the method in Embodiment 1. When the code is executed by a processor of a computer, the following operations are performed:
[0105] Receive and process input images to generate Patch blocks and corresponding Token scores;
[0106] Use Token to select a network for necessity scoring;
[0107] Apply loss functions including task loss and regression loss;
[0108] Train and test image classification models on specific datasets to optimize performance and reduce computation.
[0109] It will be apparent to those skilled in the art that the invention is not limited to the details of the exemplary embodiments described above and that the invention can be implemented in other specific forms without departing from the spirit or essential features of the invention. Therefore, the embodiments should be considered exemplary and non-limiting in all respects, and the scope of the invention is defined by the appended claims rather than the foregoing description, and it is intended that all variations falling within the meaning and scope of the equivalent elements of the claims be included in the invention. Any reference numeral in a claim should not be considered as limiting the claim to which it relates.
Claims
1. A network structure construction method based on knowledge distillation, characterized in that: At least the following steps are included: Step 1: Design a visual transformer model based on token selection, score the patch blocks of the input image through the preset fully connected layer, and score the token score with a size of (1×N), where N is the number of non-overlapping image patches divided by the original input image resolution (H, W) and the number of channels c, and the resolution of each patch block is (P, P); Step 2: Design and train a Token selection network to distill the necessity score ranking information from the trained teacher network, obtain the hidden state of each patch by learning a specific projection matrix W and bias vector b, and perform necessity scoring; Step 3: Design a visual transformer model for token selection named TS-ViT, distill the learned pruning header information from the trained structured token pruning network model, and train the token selection network; Step 4: Design the loss function of TS-ViT; Step 5: Perform image classification training and testing on a specific dataset using an optimized model used in conjunction with a token selection network to reduce computational effort and maintain or improve image classification accuracy.
2. The method for constructing a network structure based on knowledge distillation according to claim 1, characterized in that: The Token selection network in step 2 transforms the Token sequence through learning, and processes the spatial coordinate information of the Token by adding a 2D absolute position encoding based on sine and cosine functions to effectively integrate the position information.
3. The method for constructing a network structure based on knowledge distillation according to claim 2, characterized in that: The spatial coordinate information of the Token is processed by mixing the Token using channel-mixing and spatial-mixing blocks, thereby realizing the fusion of channel and spatial information. The relevant fully connected layers and activation functions are used to transform the optimized TS-token into the Token necessity score, thereby optimizing the Token selection process on the image classification dataset and improving the classification accuracy and efficiency of the model.
4. The method for constructing a network structure based on knowledge distillation according to claim 1, characterized in that: The step three at least includes the following steps: Suppose there is an image I of size H×W, where H represents height and W represents width; This image can be divided into image blocks of size P×P, where P is a predefined block size; Each block is linearly projected into a token x of size C i , where i∈[1,N]; Add the position vector in step 2 to obtain a token sequence X of size N×C containing position information. At the same time, Tokenscore∈R can be obtained in the Token selection network. 1×N ; Next, the tokens are sorted according to the Token score, and the first N*ratio tokens are retained. Ratio is a hyperparameter that can be set according to the actual situation. Finally, a tensor of size (N*ratio)×C is obtained and sent to the Transformer Encoder.
5. The method for constructing a network structure based on knowledge distillation according to claim 1, characterized in that: The loss function of TS-ViT includes the task loss and the regression loss Lts of the difference between the necessity score of the patch given by the Token selection network and the score given by the teacher model.
6. A network structure construction device based on knowledge distillation, used in the network structure construction method based on knowledge distillation according to any one of claims 1 to 5, characterized in that: At least includes input unit, scoring unit, token selection unit, loss function unit and training and testing unit; The input unit is used to receive an input image and divide it into Patch blocks; The scoring unit includes a preset fully connected layer, and the scoring unit is used to score the Patch block and generate a Token score; The Token selection unit includes a projection matrix W and a bias vector b, and the Token selection unit is used to distill the necessity score from the teacher network and perform necessity scoring on the hidden state of each Patch block; The loss function unit includes a task loss part and a regression loss part of the difference between the score of the Token selection network and the teacher model; The training and testing unit is used to train and test the model on a specific data set to optimize the accuracy and efficiency of image classification.
Citation Information
Patent Citations
Pollen image classification method based on cross attention distillation Transformer
CN113887610A
Efficient human body posture estimation method based on Transform token mask
CN117292429A
Efficiency of vision transformers with adaptive token pruning
US20230368494A1
Cited By
ViT semantic segmentation progressive Token pruning method and system based on multi-scale Tsallis entropy and low-level visual feature guidance
CN120851110A
Visual large model Token adaptive optimization method, system and device based on differential evolution and medium
CN120912953A
