A deep neural network compression method based on joint dynamic pruning
Through dynamic gradient threshold and automatic feature selection, combined with the sparsity penalty mechanism, and progressive pruning strategy layer by layer, the problems of unstable performance and high pruning times in deep neural network compression are solved, and the adaptability and generalization of the model are improved. ization capabilities, improving reasoning speed and efficiency.
Patent Information
- Application Number
- CN202410935680.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-07-12
- Publication Date
- 2024-09-17
- Estimated Expiration
- 2044-07-12
AI Technical Summary
In the existing technology, in deep neural network compression, the model performance after pruning is unstable and difficult to adjust accordingly, resulting in excessive pruning that affects the overall performance, and the number of prunings is high, which affects the adaptability and deployability of the model.
Adopt dynamic gradient threshold design, combine performance evaluation indicators for retraining, and progressively advance pruning strategies layer by layer. Through automatic feature selection and sparsity penalty mechanisms, the pruning position and amplitude are dynamically determined, reducing the number of pruning times and improving model adaptability. and generalization ability.
It improves the adaptability and generalization ability of the model, reduces unnecessary connections and calculations, improves the model's inference speed and efficiency, reduces storage requirements, and ensures the stability and deployability of the model performance.
Smart Images

Figure CN118468968B
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of neural network compression, and in particular to a deep neural network compression method based on joint dynamic pruning. Background Art
[0002] Neural network compression is an optimization technique that aims to reduce the number of parameters and computational complexity of a neural network while maintaining its predictive performance as much as possible. Since deep neural networks usually contain a large number of parameters, the computational overhead and storage requirements during training and inference are very high, especially when applied on resource-constrained devices (such as mobile devices and embedded systems). These problems are particularly prominent. Neural network compression technology uses a variety of methods to solve these problems, making the model more efficient and easier to deploy.
[0003] The technical solution pointed out in the document with the existing application publication number CN112613610A and the name of the document is a deep neural network compression method based on joint dynamic pruning, which includes the following steps: Step 1: Obtain two hyperparameters of the dynamic pruning rate β of the convolution kernel and the dynamic compression rate α of the channel; Step 2: Use the dynamic pruning method of the convolution kernel to prune Mi convolution kernels in the convolution layer; Step 3: Use the dynamic compression method of the channel to select α channels to participate in the training; Step 4: During the training process, update the model parameters so that the dynamic pruning of the convolution kernel converges to a subset of the dynamic compression of the channel; The present invention accelerates training and reasoning, maintains the capacity of the model while effectively reducing the number of floating-point operations and parameter scale of the model.
[0004] In combination with the above documents and existing technologies, after taking a network model as a benchmark, it is first necessary to use a large amount of data for model training, and then perform feature recognition and select the pruning position. During the pruning process, how to avoid excessive pruning that leads to a decline in model performance is a problem to be solved. For the pruned model, it is necessary to evaluate its performance after pruning. If the performance is unstable or abnormal, the model needs to be adjusted. The usual technical method is to make adjustments according to established strategies, for example: reducing the number of fixed pruning times, which usually requires multiple operations and cannot make effective adjustments in a targeted manner, thereby affecting the overall performance of the model. Summary of the invention
[0005] 1. Technical issues to be resolved
[0006] In view of the shortcomings of the prior art, the present invention provides a deep neural network compression method based on joint dynamic pruning, which adopts a dynamic gradient threshold design, so that targeted operations and processing can be performed when pruning is initially considered, and the gradient threshold is adjusted secondary in combination with the subsequent retraining process based on performance evaluation indicators, and the number of pruning is reduced when necessary to ensure the overall performance of the model. The pruned model can adapt to the new weight distribution and connection structure after retraining, thereby improving the adaptability and generalization ability of the model. The model can adjust the strategy according to the execution, further improving the practicality and deployability of the model, and solving the problems raised in the background technology.
[0007] (II) Technical solution
[0008] To achieve the above objectives, the present invention is implemented through the following technical solutions:
[0009] A deep neural network compression method based on joint dynamic pruning includes the following steps:
[0010] S1. Initial network training:
[0011] Select a deep neural network model with a specific task as a benchmark and use a public dataset of the same type to train the network model;
[0012] S2, feature selection and dynamic pruning:
[0013] The automatic feature selection algorithm is used to identify the features and weights in the network model, and then the gradient information of each batch is used to dynamically determine the location and magnitude of pruning. Finally, a sparsity penalty mechanism is introduced to achieve network pruning.
[0014] S3, fine-tuning pruning and retraining:
[0015] A layer-by-layer progressive pruning strategy is adopted. After each pruning, performance evaluation indicators are obtained based on the performance data. Retraining is performed based on the performance evaluation indicators. The performance evaluation indicators obtained after two retrainings are compared, and the adjustment strategy is executed according to the comparison results.
[0016] Furthermore, the process of training the network model is as follows:
[0017] S101, Data preprocessing: Data enhancement: Perform data enhancement on public datasets, including random cropping, rotation, flipping, scaling, and color jittering; Normalization: Normalize the data after data enhancement to the range of [0, 1];
[0018] S102, Model construction: Use the deep learning framework to build the initial model architecture and select the loss function for training;
[0019] S103, training process: Batch training: select the corresponding batch size; learning rate scheduling: use the learning rate scheduler to dynamically adjust the learning rate; early stopping: monitor the loss of the validation set; data segmentation: divide the data set into a training set and a validation set;
[0020] S104. Evaluation and adjustment: During the training process, the model performance is regularly evaluated on the validation set, and the model hyperparameters are adjusted based on the validation results.
[0021] Furthermore, the automatic feature selection algorithm uses an autoencoder;
[0022] The process of identifying features and weights in the network model is as follows:
[0023] S201, build an autoencoder: the size of the input layer is the same as the original network input layer, the encoder part reduces the number of neurons layer by layer; the decoder part increases the number of neurons layer by layer to reconstruct the original input;
[0024] S202, training the autoencoder: using the same data set as the initial network model, training the autoencoder;
[0025] S203, feature importance assessment: Use correlation analysis to analyze encoder weights and calculate the correlation between network layers to identify corresponding connections and features.
[0026] Furthermore, the gradient information of each batch is used to dynamically determine the location and magnitude of pruning. The specific steps are as follows:
[0027] Calculate gradients: After each training batch, calculate the weight gradients;
[0028] Pruning decision: decide whether to prune based on the gradient size, compare each gradient size with the preset gradient threshold, extract and select each gradient below the gradient threshold;
[0029] Apply pruning: Prune the selected gradient weights. Pruning involves resetting the gradient weights to zero and removing the corresponding connections. In PyTorch, logical masks are used to select the pruning method.
[0030] Furthermore, the process of presetting the gradient threshold is as follows:
[0031] The dynamic gradient threshold is preset according to the gradient distribution. After each training batch, the mean of the weight gradient is calculated synchronously, and the gradient threshold is generated based on each weight gradient, the mean and the established standard threshold. The formula is as follows:
[0032]
[0033] In the formula, represents the standard threshold, Indicates the number of weight gradients corresponding to the current training batch, represents the weight gradient corresponding to the i-th weight, i represents the number, and i=1, 2, ..., n, Represents the average value of each weight gradient under n weights, with a preset proportional coefficient: , .
[0034] Furthermore, the sparsity penalty mechanism is introduced to achieve the following network pruning process:
[0035] Introduce L1 regularization: Add L1 regularization term to the loss function;
[0036] Training network model: During the training process, L1 regularization will gradually reduce some weights to zero, and some weights represent specific weight parameters in the model.
[0037] Furthermore, the performance data includes accuracy and loss values;
[0038] The accuracy is the ratio of the number of samples correctly predicted by the model in the test set to the total number of samples, which is calculated by the following formula:
[0039]
[0040] The loss value is a measure of the difference between the model's prediction and the true label, and the loss value represents the mean squared error;
[0041] The formula used to generate the performance evaluation index is as follows:
[0042]
[0043] In the formula, represents the performance evaluation index, Represents the loss value, weight coefficient: , .
[0044] Furthermore, the process of retraining based on the performance evaluation index is as follows:
[0045] In the pre-built rule engine, the retraining batch estimate is generated based on the current performance evaluation index, and after each pruning, the corresponding number of training batches are executed according to the retraining batch estimate. The formula for generating the retraining batch estimate is as follows:
[0046]
[0047] In the formula, represents the estimated value of the retraining batch, Represents the basic number of training batches, int is the rounding function;
[0048] Here, executing a corresponding number of training batches according to the retraining batch estimate means executing one retraining.
[0049] Furthermore, the performance evaluation indicators obtained after the two retrainings are compared, and the comparison results are as follows:
[0050] If the absolute value of the difference between the performance evaluation indicators obtained after two retrainings does not exceed the preset evaluation threshold, no response action is taken; if the absolute value of the difference between the performance evaluation indicators obtained after two retrainings exceeds the preset evaluation threshold, the adjustment strategy is executed;
[0051] The adjustment strategy implemented is: increase the gradient threshold in S2, and the increase in the gradient threshold is obtained according to the following formula:
[0052]
[0053] In the formula, represents the increase in the gradient threshold, represents the error correction factor, and The value range is 0~2. represents the performance evaluation index obtained after the previous retraining, represents the performance evaluation index obtained after the last retraining, Represents the evaluation threshold.
[0054] (III) Beneficial effects
[0055] The present invention provides a deep neural network compression method based on joint dynamic pruning, which has the following beneficial effects:
[0056] 1. Data enhancement technology was used to increase the diversity of training data and improve the robustness and generalization ability of the model. After the initial model was selected, the model was built and initialized, and batch training was used, the learning rate was dynamically adjusted, and the early stopping strategy was implemented to avoid overfitting of the model on the validation set, thereby optimizing the training effect and speed;
[0057] 2. The dynamic gradient threshold design enables targeted operations and processing when initially considering pruning. Combined with the subsequent retraining process based on performance evaluation indicators, the gradient threshold is adjusted twice to reduce the number of pruning times when necessary to ensure the overall performance of the model;
[0058] 3. Through the autoencoder and correlation analysis, the features that have the greatest impact on the model performance are successfully identified and extracted, the input representation of the model is optimized, the efficiency and accuracy of feature extraction are improved, and through pruning decisions and practical applications, the model parameters are sparse, unnecessary connections and calculations are reduced, the reasoning speed and efficiency of the model are improved, and the storage requirements of the model are reduced;
[0059] 4. Subsequently, we performed layer-by-layer pruning and retraining to ensure that each adjustment of the model was within the controllable performance range and avoid large fluctuations in performance. The performance evaluation index combined accuracy and loss value to comprehensively measure the performance of the model on the test set. The pruned model was retrained to adapt to the new weight distribution and connection structure, which improved the model's adaptability and generalization ability. The model was able to adjust the strategy according to execution, further improving the model's practicality and deployability. BRIEF DESCRIPTION OF THE DRAWINGS
[0060] Figure 1 It is a flow chart of a deep neural network compression method based on joint dynamic pruning of the present invention. DETAILED DESCRIPTION
[0061] The following will be combined with the drawings in the embodiments of the present invention to clearly and completely describe the technical solutions 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.
[0062] Example 1: Please refer to Figure 1 ,This embodiment provides a deep neural network compression method based on joint dynamic pruning, which shows how to use the joint dynamic pruning method combined with innovative technical solutions to effectively compress deep neural networks and reduce the storage space and computational complexity of the model while maintaining performance;
[0063] The main steps of this compression method are as follows:
[0064] S1. Initial network training:
[0065] Select a deep neural network model with a specific task as a benchmark and use a public dataset of the same type to train the network model;
[0066] Among them, in the process of selecting the initial model:
[0067] For image classification tasks, you can choose a convolutional neural network (CNN) architecture, such as ResNet, VGG, MobileNet, or DenseNet.
[0068] Select the dataset:
[0069] Choose a large, publicly available dataset to train the model to ensure the generalization ability of the model; for example, large datasets for image classification include: ImageNet: contains more than 14 million images, covering 1,000 categories, and is the most commonly used large dataset in image classification tasks; CIFAR-10 and CIFAR-100: contain 60,000 and 60,000 32*32 color images, covering 10 and 100 categories respectively; MS-COCO: mainly used for object detection and segmentation tasks, containing about 330,000 images and 80 categories of labels;
[0070] The process of training the initial network is as follows:
[0071] S101. Data preprocessing: Data enhancement: Perform data enhancement on the training data, i.e. the public data set, including random cropping, rotation, flipping, scaling and color jittering to increase data diversity and improve the robustness of the model; Normalization: Normalize the preprocessed data to the range of [0, 1] or [-1, 1] to accelerate convergence;
[0072] S102. Model construction: Use any deep learning framework such as TensorFlow, PyTorch, and Keras to build the initial model architecture, and select a loss function (such as cross entropy loss) and optimizer (such as SGD) for training;
[0073] S103, training process: Batch training: select the corresponding batch size (batch size), usually any of 32, 64 or 128; learning rate scheduling: use the learning rate scheduler (such as learning rate gradual decay, cosine annealing, learning rate hot restart) to dynamically adjust the learning rate to improve the training effect; Early Stopping: monitor the loss of the validation set. If the validation loss no longer decreases within a few cycles, stop training in advance to prevent overfitting; Data segmentation: divide the data set into a training set and a validation set (usually in a ratio of 80%:20%) for training and evaluating model performance;
[0074] S104. Evaluation and adjustment: During the training process, regularly evaluate the model performance (such as accuracy, F1 score) on the validation set, and adjust the model hyperparameters (such as network depth, width, learning rate, etc.) and training strategies based on the validation results.
[0075] Specific training examples:
[0076] Assuming that the ResNet-50 model is selected for training on the ImageNet dataset, the following are the specific steps:
[0077] First, data preprocessing is performed: ImageNet images are preprocessed using data augmentation techniques, including random cropping, horizontal flipping, and color jittering, and the image pixel values are normalized to the range of [0, 1].
[0078] Secondly, model construction:
[0079] import torchvision.models as models
[0080] import torch.optim as optim
[0081] model = models.resnet50(pretrained=False)
[0082] criterion = torch.nn.CrossEntropyLoss()
[0083] optimizer = optim.Adam(model.parameters(), lr=0.001);
[0084] Then, the training process:
[0085] from torch.optim.lr_scheduler import StepLR
[0086] scheduler = StepLR(optimizer, step_size=7, gamma=0.1)
[0087] for epoch in range(num_epochs):
[0088] model.train()
[0089] for inputs, labels in train_loader:
[0090] optimizer.zero_grad()
[0091] outputs = model(inputs)
[0092] loss = criterion(outputs, labels)
[0093] loss.backward()
[0094] optimizer.step()
[0095] scheduler.step()
[0096] # Validation process
[0097] model.eval()
[0098] validation_loss = 0.0
[0099] correct = 0
[0100] total = 0
[0101] with torch.no_grad():
[0102] for inputs, labels in val_loader:
[0103] outputs = model(inputs)
[0104] loss = criterion(outputs, labels)
[0105] validation_loss += loss.item()
[0106] _, predicted = torch.max(outputs.data, 1)
[0107] total += labels.size(0)
[0108] correct += (predicted == labels).sum().item()
[0109] accuracy = 100 * correct / total
[0110] print(f'Epoch {epoch+1}, Validation Accuracy: {accuracy:2f}%,Validation Loss: {validation_loss / len(val_loader):4f}');
[0111] Finally, evaluate and adjust: adjust hyperparameters such as learning rate and batch size based on the accuracy and loss on the validation set; use the early stopping strategy to terminate training early if the performance of the validation set no longer improves;
[0112] Through the above steps, a ResNet-50 model with good performance on the ImageNet dataset can be trained, laying the foundation for subsequent dynamic pruning and model compression.
[0113] By adopting the above technical solutions and data enhancement technology, the diversity of training data is increased, the robustness and generalization ability of the model are improved. After the initial model is selected, the model is built and initialized, and batch training is used. The learning rate is dynamically adjusted, and an early stopping strategy is implemented to avoid overfitting of the model on the validation set, thereby optimizing the training effect and speed.
[0114] S2, feature selection and dynamic pruning:
[0115] Using the automatic feature selection algorithm, the features and weights in the network model are identified. The features and weights mentioned here are usually the most important features and weights in the corresponding network model. This step helps to determine which layers and connections are critical to model performance. Then, the gradient information of each batch is used to dynamically determine the location and magnitude of pruning, thereby dynamically adjusting the network structure. Finally, a sparsity penalty mechanism is introduced to return some weights to zero, thereby achieving network pruning.
[0116] Among them, the automatic feature selection algorithm uses an autoencoder, which is an unsupervised learning neural network used to learn low-dimensional representations of data. The autoencoder can be used to identify the most important features in the input data;
[0117] The process of identifying features and weights in the network model is as follows:
[0118] S201, build an autoencoder: the size of the input layer is the same as the original network input layer, the encoder part reduces the number of neurons layer by layer to learn compact representation; the decoder part increases the number of neurons layer by layer to reconstruct the original input;
[0119] S202, training the autoencoder: using the same dataset as the initial network, training the autoencoder to minimize the difference between the input and the reconstructed output;
[0120] S203, Feature Importance Assessment: Use correlation analysis to analyze encoder weights and calculate the correlation between network layers to identify corresponding connections and features that are critical to model performance;
[0121] Among them, when analyzing the weights of the encoder part to determine which features are most important for the reconstruction of the input data, for example:
[0122] from tensorflow.keras.layers import Input, Dense
[0123] from tensorflow.keras.models import Model
[0124] # Build the autoencoder
[0125] input_img = Input(shape=(input_dim,))
[0126] encoded = Dense(128, activation='relu')(input_img)
[0127] encoded = Dense(64, activation='relu')(encoded)
[0128] encoded = Dense(32, activation='relu')(encoded)
[0129] decoded = Dense(64, activation='relu')(encoded)
[0130] decoded = Dense(128, activation='relu')(decoded)
[0131] decoded = Dense(input_dim, activation='sigmoid')(decoded)
[0132] autoencoder = Model(input_img, decoded)
[0133] encoder = Model(input_img, encoded)
[0134] # Compile and train
[0135] autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
[0136] autoencoder.fit(x_train, x_train,
[0137] epochs=50,
[0138] batch_size=256,
[0139] shuffle=True,
[0140] validation_data=(x_test, x_test))
[0141] # Extract feature importance
[0142] encoded_imgs = encoder.predict(x_train);
[0143] The process of calculating the correlation between network layers is as follows:
[0144] Calculate the correlation between the output feature map of each layer and the final output of the model, and filter out the most important features and connections based on the correlation value. The example is as follows:
[0145] import numpy as np
[0146] from scipy.stats import pearsonr
[0147] # Calculate the correlation between features and output
[0148] def compute_correlation(feature_maps, outputs):
[0149] correlations = []
[0150] for feature_map in feature_maps:
[0151] corr, _ = pearsonr(feature_map.flatten(), outputs.flatten())
[0152] correlations.append(corr)
[0153] return correlations
[0154] # Example calculation
[0155] feature_maps = model.predict(x_train)
[0156] correlations = compute_correlation(feature_maps, y_train)
[0157] important_features = np.argsort(correlations)[-k:] # Select the most important k features;
[0158] Using the gradient information of each batch, the location and magnitude of pruning are dynamically determined. The specific steps are as follows:
[0159] Calculate gradients: After each training batch, calculate the weight gradients;
[0160] Pruning decision: Decide whether to prune based on the gradient size. Compare the size of each gradient with the preset gradient threshold, extract and select each gradient below the gradient threshold. Each gradient below the gradient threshold indicates a small gradient. The weight with a small gradient has a small impact on the model output and can be considered for pruning.
[0161] Apply pruning: prune the selected gradient weights. Pruning methods include resetting the gradient weights to zero or removing the corresponding connections. In PyTorch, logical masks are used to select pruning methods.
[0162] Specifically, calculating weight gradients, making pruning decisions, and applying pruning are the key steps in the dynamic pruning approach;
[0163] In deep learning, the weight gradient is the partial derivative of the loss function with respect to the weight, which is calculated by the back-propagation algorithm after each training batch. The weight gradient is calculated using a gradient descent optimization algorithm, such as SGD (stochastic gradient descent) or Adam. The calculation steps are as follows:
[0164] Forward propagation: forward propagation of input data through the network to calculate the predicted output of the model; calculation of loss: calculating the loss function by comparing the predicted output with the actual label; back propagation: calculating the gradient of each weight relative to the loss according to the loss function; updating weights: updating the weights in the network according to the gradient size and optimization algorithm (such as learning rate);
[0165] In PyTorch, this process typically looks like this:
[0166] optimizer.zero_grad() # Clear the previous gradient
[0167] outputs = model(inputs) # forward propagation
[0168] loss = criterion(outputs, labels) # Calculate loss
[0169] loss.backward() # Backward propagation, calculate gradient
[0170] optimizer.step() # Update weights according to gradient;
[0171] The pruning decision is based on the calculated weight gradient. The goal is to identify and prune the connections or weights that have little impact on the model. The decision method is: the magnitude of each gradient represents the absolute value of the gradient, because the positive or negative gradient determines the update direction of the weight. However, when pruning, the magnitude of the gradient is mainly concerned. The magnitude of each gradient is compared with the preset gradient threshold, and each gradient below the gradient threshold is extracted and selected.
[0172] The process of presetting the gradient threshold is as follows:
[0173] The dynamic gradient threshold is preset according to the gradient distribution. After each training batch, the mean of the weight gradient is calculated synchronously, and the gradient threshold is generated based on each weight gradient, the mean and the established standard threshold. The formula is as follows:
[0174]
[0175] In the formula, Indicates the standard threshold, which is a pre-set value. Usually a smaller value is chosen, such as 1e-4. Indicates the number of weight gradients corresponding to the current training batch, represents the weight gradient corresponding to the i-th weight, i represents the number, and i=1, 2, ..., n, Represents the average value of each weight gradient under n weights, with a preset proportional coefficient: , ; The corresponding gradient threshold will change dynamically after each training batch;
[0176] The dynamic gradient threshold design enables targeted operations and processing when pruning is initially considered. Combined with the subsequent retraining process based on performance evaluation indicators, the gradient threshold is adjusted secondary to reduce the number of pruning times when necessary to ensure the overall performance of the model.
[0177] In applied pruning, reset the weights to zero: reset the selected weights to zero, which means that these weights no longer participate in the next forward propagation and backward propagation; remove the corresponding connections: in a network with a sparse structure, the connections associated with the selected weights can be removed, thereby reducing the number of parameters of the network;
[0178] The specific implementation depends on your deep learning framework and network structure. In PyTorch, these operations can be implemented through simple logical masks. The example is as follows:
[0179] def prune_weights(model, threshold):
[0180] for name, param in model.named_parameters():
[0181] if 'weight' in name:
[0182] mask = torch.abs(param.grad)<threshold
[0183] param.data[mask] = 0;
[0184] In the above code, `param.grad` represents the gradient of the parameter, and `torch.abs(param.grad)<threshold` generates a boolean mask to select the weights with gradients less than the threshold `threshold` for pruning;
[0185] The process of introducing a sparsity penalty mechanism to achieve network pruning is as follows:
[0186] Introduce L1 regularization: Add an L1 regularization term to the loss function;
[0187] Train the network model: During the training process, L1 regularization will gradually reduce some weights to zero;
[0188] Through the above steps, feature selection and dynamic pruning can be effectively carried out, significantly reducing the number of network parameters and maintaining or improving the model performance, laying a foundation for further model compression and optimization;
[0189] It should be noted that the partial weights refer to the specific weight parameters in the model. By introducing the L1 regularization term, these weights will gradually become sparse during the training process, that is, the values of some weights will decrease or even become zero. This sparsity effect is an important feature of L1 regularization, which makes the model not only learn the features of the data during the training process, but also tend to reduce the influence of unimportant weights, thereby improving the generalization ability of the model and its adaptability to unseen data;
[0190] Specifically:
[0191] Effect of L1 regularization: After adding the L1 regularization term to the loss function, the loss function becomes the original loss plus the weight of the L1 norm. The L1 regularization term will cause some weights to gradually decrease to zero during the training process, because the optimization process tends to minimize the impact of these weights, thereby minimizing the complexity of the model;
[0192] The meaning of sparse weights: Sparse weights refer to the fact that during the training process, the values of some weights become very small or zero. These reduced weights can be considered as unimportant parts of the model, and they may contribute less to the final prediction results, so the complexity and storage requirements of the model can be reduced while maintaining the performance of the model;
[0193] In summary, by introducing L1 regularization, some weights will become sparse during the training process. These weights can be regarded as unimportant parts of the model during the learning and simplification process.
[0194] By adopting the above technical solution, through the autoencoder and correlation analysis, the features that have the greatest impact on the model performance are successfully identified and extracted, the input representation of the model is optimized, the efficiency and accuracy of feature extraction are improved, and through pruning decisions and practical applications, the model parameters are sparse, unnecessary connections and calculations are reduced, the reasoning speed and efficiency of the model are improved, and the storage requirements of the model are reduced;
[0195] These technical solutions not only improve the performance and efficiency of the model, but also lay the foundation for subsequent model optimization (such as lightweighting and deployment on resource-constrained devices). Especially in large-scale data sets and complex tasks, the application of these technologies is of great significance to improving the practicality and deployability of deep learning models.
[0196] S3, fine-tuning pruning and retraining:
[0197] Adopt a layer-by-layer progressive pruning strategy. After each pruning, obtain the performance evaluation index based on the performance data, retrain based on the performance evaluation index, compare the performance evaluation index obtained after two retrainings, and implement the adjustment strategy based on the comparison results to ensure the overall performance of the model;
[0198] Among them, the performance data represents the performance of the model on the test set, including accuracy and loss value;
[0199] The accuracy is the ratio of the number of samples correctly predicted by the model in the test set to the total number of samples, which can be calculated by the following formula:
[0200]
[0201] The loss value is a measure of the difference between the model prediction result and the true label. In this embodiment, the loss value is the mean square error. The smaller the loss value, the closer the model's prediction on the validation set or test set is to the true label.
[0202] The formula used to generate the performance evaluation index is as follows:
[0203]
[0204] In the formula, represents the performance evaluation index, Represents the loss value, weight coefficient: , , ;
[0205] The process of retraining based on performance evaluation indicators is:
[0206] In the pre-built rule engine, based on the current performance evaluation indicators, the retraining batch estimate is generated, and after each pruning, the corresponding number of training batches are executed according to the retraining batch estimate to ensure that the model can adapt to the new weight distribution and connection structure. The formula for generating the retraining batch estimate is as follows:
[0207]
[0208] In the formula, represents the estimated value of the retraining batch, Indicates the basic number of training batches. For example, the basic number is 5, and int is the rounding function;
[0209] Note: Executing the corresponding number of training batches according to the estimated number of retraining batches means performing one retraining;
[0210] Comparing the performance evaluation indicators obtained after two retrainings, the comparison results are:
[0211] If the absolute value of the difference between the performance evaluation indicators obtained after two retrainings does not exceed the preset evaluation threshold, it means that the model performance is stable and no response action is taken; if the absolute value of the difference between the performance evaluation indicators obtained after two retrainings exceeds the preset evaluation threshold, it means that the model performance is abnormal and the adjustment strategy is executed;
[0212] The adjustment strategy implemented is: increase the gradient threshold in the previous step, and the increase in the gradient threshold is obtained according to the following formula:
[0213]
[0214] In the formula, represents the increase in the gradient threshold, Represents the error correction factor, whose specific value can be adjusted by the user or generated by analytical function fitting. The value range is 0~2. represents the performance evaluation index obtained after the previous retraining, represents the performance evaluation index obtained after the last retraining, It represents the evaluation threshold, which is set according to the needs and plays a defining role. I will not elaborate on it here.
[0215] Thereby reducing the number of pruning times to ensure the overall performance of the model;
[0216] Through the above process, the model can be gradually optimized and adjusted under the guidance of the dynamic pruning strategy to ensure that the stability and accuracy of the overall performance of the model are maintained while reducing the number of parameters.
[0217] By adopting the above technical solution, layer-by-layer pruning and retraining were performed subsequently to ensure that each adjustment of the model was within the controllable performance range and avoid large fluctuations in performance. The performance evaluation index combined accuracy and loss value to comprehensively measure the performance of the model on the test set. The pruned model was retrained and was able to adapt to the new weight distribution and connection structure, which improved the model's adaptability and generalization ability. The model was able to adjust the strategy according to execution, further improving the model's practicality and deployability.
[0218] After S3, it also includes model compression: applying lightweight technologies, such as model quantization, to convert floating-point parameters into smaller integers or low-precision floating-point numbers, thereby reducing the storage space and computing overhead of the model and realizing a complete compression process; specifically: applying model quantization technology to convert floating-point parameters into 8-bit integers to reduce the storage requirements of the model; Note: Floating-point parameters represent the weights and biases in the model, which are used in the neural network to calculate the output of each neuron.
[0219] In the application, the several formulas involved are all calculated by removing the dimensions and taking their numerical values. The formula is a formula obtained by collecting a large amount of data and performing software simulation to obtain the most recent real situation. The formula is set by technical personnel in this field according to actual conditions.
[0220] The above embodiments may be implemented in whole or in part by software, hardware, firmware or any other combination thereof. When implemented using software, the above embodiments may be implemented in whole or in part in the form of a computer program product. A person of ordinary skill in the art may appreciate that the units and algorithm steps of each example described in conjunction with the embodiments disclosed herein may be implemented in electronic hardware, or in a combination of computer software and electronic hardware. Whether these functions are performed in hardware or software depends on the specific application and design constraints of the technical solution.
[0221] The units described as separate components may or may not be physically separated, and the components shown as units may or may not be physical units, and may be located in one place or distributed on multiple network units. Some or all of the units may be selected according to actual needs to achieve the purpose of the solution of this embodiment.
[0222] The above description is only a specific implementation manner of the present application, but the protection scope of the present application is not limited thereto. Any technician familiar with the technical field can easily think of changes or substitutions within the technical scope disclosed in the present application, which should be included in the protection scope of the present application.
Claims
1. A deep neural network compression method based on joint dynamic pruning, characterized in that: The steps include: S1. Initial network training: Select a deep neural network model with a specific task as a benchmark, and use a public dataset of the same type to train the network model; the public dataset of the same type includes a dataset for image classification, and the dataset for image classification includes any one of ImageNet, CIFAR-10, CIFAR-100, and MS-COCO; S2, feature selection and dynamic pruning: The automatic feature selection algorithm is used to identify the features and weights in the network model, and then the gradient information of each batch is used to dynamically determine the location and magnitude of pruning. Finally, a sparsity penalty mechanism is introduced to achieve network pruning. The specific steps are as follows: Calculate gradients: After each training batch, calculate the weight gradients; Pruning decision: decide whether to prune based on the gradient size, compare each gradient size with the preset gradient threshold, extract and select each gradient below the gradient threshold; Apply pruning: Prune the selected gradient weights. Pruning involves resetting the gradient weights to zero and removing the corresponding connections. In PyTorch, logical masks are used to select the pruning method. The process of presetting the gradient threshold is as follows: The dynamic gradient threshold is preset according to the gradient distribution. After each training batch, the mean of the weight gradient is calculated synchronously, and the gradient threshold is generated based on each weight gradient, the mean and the established standard threshold. The formula is as follows: In the formula, represents the standard threshold, Indicates the number of weight gradients corresponding to the current training batch, represents the weight gradient corresponding to the i-th weight, i represents the number, and i=1, 2, ..., n, Represents the average value of each weight gradient under n weights, with a preset proportional coefficient: , ; S3, fine-tuning pruning and retraining: Adopt a layer-by-layer progressive pruning strategy. After each pruning, obtain the performance evaluation index based on the performance data. Retrain according to the performance evaluation index. Compare the performance evaluation indexes obtained after the two retrainings. Execute the adjustment strategy according to the comparison results. Comparing the performance evaluation indicators obtained after two retrainings, the comparison results are: If the absolute value of the difference between the performance evaluation indicators obtained after two retrainings does not exceed the preset evaluation threshold, no response action is taken; if the absolute value of the difference between the performance evaluation indicators obtained after two retrainings exceeds the preset evaluation threshold, the adjustment strategy is executed; The adjustment strategy implemented is: increase the gradient threshold in S2, and the increase in the gradient threshold is obtained according to the following formula: In the formula, represents the increase in the gradient threshold, represents the error correction factor, and The value range is 0~2. represents the performance evaluation index obtained after the previous retraining, represents the performance evaluation index obtained after the last retraining, Represents the evaluation threshold.
2. The deep neural network compression method based on joint dynamic pruning according to claim 1, characterized in that: The process of training the network model is as follows: S101. Data preprocessing: Data enhancement: Perform data enhancement on public datasets, including random cropping, rotation, flipping, scaling, and color jittering; Normalization: Normalize the data after data enhancement to the range of [0, 1]; S102, Model construction: Use the deep learning framework to build the initial model architecture and select the loss function for training; S103, training process: batch training: select the corresponding batch size; Learning rate scheduling: Use the learning rate scheduler to dynamically adjust the learning rate; Early stopping: Monitor the loss of the validation set; Data segmentation: Divide the dataset into a training set and a validation set; S104. Evaluation and adjustment: During the training process, the model performance is regularly evaluated on the validation set, and the model hyperparameters are adjusted based on the validation results.
3. The deep neural network compression method based on joint dynamic pruning according to claim 2 is characterized in that: The automatic feature selection algorithm uses an autoencoder; The process of identifying features and weights in the network model is as follows: S201, build an autoencoder: the size of the input layer is the same as the original network input layer, the encoder part reduces the number of neurons layer by layer; the decoder part increases the number of neurons layer by layer to reconstruct the original input; S202, training the autoencoder: using the same data set as the initial network model, training the autoencoder; S203, feature importance assessment: Use correlation analysis to analyze encoder weights and calculate the correlation between network layers to identify corresponding connections and features.
4. The deep neural network compression method based on joint dynamic pruning according to claim 3 is characterized in that: The process of introducing a sparsity penalty mechanism to achieve network pruning is as follows: Introduce L1 regularization: Add L1 regularization term to the loss function; Training network model: During the training process, L1 regularization will gradually reduce some weights to zero, and some weights represent specific weight parameters in the model.
5. The deep neural network compression method based on joint dynamic pruning according to claim 4, characterized in that: Performance data includes accuracy and loss values; The accuracy is the ratio of the number of samples correctly predicted by the model in the test set to the total number of samples, which is calculated by the following formula: The loss value is a measure of the difference between the model's prediction and the true label, and the loss value represents the mean squared error; The formula used to generate the performance evaluation index is as follows: In the formula, represents the performance evaluation index, Represents the loss value, weight coefficient: , .
6. The deep neural network compression method based on joint dynamic pruning according to claim 5, characterized in that: The process of retraining based on performance evaluation indicators is: In the pre-built rule engine, the retraining batch estimate is generated based on the current performance evaluation index, and after each pruning, the corresponding number of training batches are executed according to the retraining batch estimate. The formula for generating the retraining batch estimate is as follows: In the formula, represents the estimated value of the retraining batch, Represents the basic number of training batches, int is the rounding function; Here, executing a corresponding number of training batches according to the retraining batch estimate means executing one retraining.
Citation Information
Cited By
Efficient collaborative reasoning method and system for privacy protection
CN119886325A
