Neural Network Compression Framework for fast model inference

2020·arXiv

Abstract

1. Introduction

Deep Neural Networks are perhaps the most important breakthrough in machine learning in the last ten years [9, 24, 26, 16]. It brought new opportunities to improve the accuracy of algorithms for almost all ML problems by introducing models with millions of parameters. However, such models dramatically affected the performance of algorithms because the majority of them requires billions of operations to make the accurate predictions. The analysis of the models [27, 21, 23] has shown that many of them have a high level of redundancy, basically caused by the fact that most of the networks were created to achieve the highest accuracy in academia environment while deployment has performance/accuracy trade-off as a guiding principle. This observation induced the development of new methods which create more computation-efficient Deep Learning (DL) models, so that these models can be used in real-world applications with constrained resources, such as edge inferencing.

Most of these methods can be roughly divided into two categories. The first category contains the so-called Neural Architecture Search (NAS) algorithms [32, 25, 11], which allow constructing efficient neural networks for a particular dataset and specific hardware that will be used for model inference. The second category of methods aims to improve the performance of the existing and usually hand-crafted DL models without an impact on their architecture design. Moreover, as we show in our research these methods can be successfully applied to the models obtained by NAS algorithms. One example of such methods is quantization [8, 3], which is used to transform the model from floating-point to fixed-point representation and more effectively use the hardware supporting fixed-point arithmetic. The extreme case of quantized networks are binary networks [7, 19, 28] where the weights and/or activations are represented by one of two available values so that the original convolution can be equivalently replaced by XNOR and POPCOUNT operations, leading to a dramatic decrease in inference time on proper hardware. Another method belonging to this group is introducing sparsity into the model weights [10, 17, 13] which can be further exploited to reduce the data transfer rate at inference time, or even bring performance speed-up by the usage of sparse arithmetic given that it is supported by HW.

In general, any method from the second group can be applied either during or after the training, which adds a further distinction of these methods into post-training methods and methods which are applied with fine-tuning. Our framework contains methods which use fine-tuning when compressing model.

Shortly, our contribution is a new NNCF framework

which has the following important features:

• Support of quantization, binarization, and sparsity algorithms with fine-tuning.

• Automatic model graph transformation - the model is wrapped and additional layers are inserted in the model graph.

• Ability to mix compression methods and apply them at the same time.

• Training samples for Image Classification, Object Detection and Semantic Segmentation as well as configu-ration files for various models compression.

• HW-accelerated layers for fast model fine-tuning and multi-GPU training support.

• Compatibility with OpenVINO Toolkit [1].

It worth noting that we make an accent on production in our work in order to provide a simple but powerful solution for the inference acceleration of neural network solving problems in various domains. Moreover, we should also note that we are not the authors of all the compression methods implemented in the framework. For example, binarization and RB sparsity algorithms were taken from 3rd party projects by agreement with their authors and integrated into the framework.

2. Related Work

Currently, there are multiple efforts to bring compression algorithms not only into the research community but towards a wider range of users who are interested in real-world DL applications. Almost all DL frameworks, in one way or another, provide support of compression features. For example, quantizing a model into INT8 precision is now becoming a mainstream approach to accelerate inference with minimum effort.

One of the influential works here is [8], which introduced the so-called Quantization-aware Training (QAT) for TensorFlow. This work highlights problems of algorithmic aspects of uniform quantization for CNNs with fine-tuning, and also proposes an efficient inference pipeline based on the instructions available in specific hardware. The QAT is based on the Fake Quantization operation which, in turn, can be represented a pair of Quantize/Dequantize operations. The important feature of the proposed software solution is the automatic insertion of the Fake Quantization operations, which makes the model optimization more straightforward for the user. However, this approach has significant drawbacks - namely, increased training time and memory consumption. Another concern is that the quantization method of [8] is based on the naive min/max approach and potentially may achieve worse results than more sophisticated quantization range selection strategies. The latter problem is solved by methods proposed in [3], where quantization parameters are learned using gradient descent. In our framework we use a similar quantization method, along with other quantization schemes, while also providing the ability to automatically insert Fake Quantization operations in the model graph.

Another TensorFlow-based Graffitist framework, which also leverages the training of quantization thresholds [22], aims to improve upon the QAT techniques by providing range-precision balancing of the resultant per-tensor quantization parameters via training these jointly with network weights. This scheme is similar to ours but is limited to symmetric quantization, factor-of-2 quantization scales, and only allows for 4/8 bit quantization widths, while our framework imposes no such restrictions to be more flexible to the end users. Furthermore, NNCF does not perform additional network graph transformations during the quantization process, such as batch normalization folding which requires double computation of convolutional operation, and therefore is less demanding to memory and computational resources.

From the PyTorch-based tools available for model compression, the Neural Network Distiller [31] is the famous one. It contains an implementation of algorithms of various compression methods, such as quantization, binarization, filter pruning, and others. However, this solution mostly focuses on research tasks rather than the application of the methods to real use cases. The most critical drawback of Distiller is the lack of a ready pipeline from the model compression to the inference.

The main feature of existing compression frameworks is usually the ability to quantize the weights and/or activations of the model from 32 bit floating point into lower bit-width representations without sacrificing much of the model accuracy. However, as it is now commonly known [6], deep neural networks can also typically tolerate high levels of sparsity, that is, a large proportion of weights or neurons in the network can be zeroed out without much harm to model performance. NNCF allows to produce compressed models that are both quantized and sparsified. The algorithms implemented in NNCF constitute non-structured network sparsification approaches, i.e. methods that result in sparse weight matrices of convolutional and fully-connected layers with zeros randomly distributed inside the weight tensors. This is in contrast to the so-called structured sparsity methods, which aim to prune away whole neurons or convolutional filters [12]. The non-structured sparsity algorithms generally range from relatively straightforward magnitude-based weight pruning schemes [6, 30] to more complex approaches such as variational and targeted dropout [15, 5] and regularization [14].

3. Framework Architecture

NNCF is built on top of the popular PyTorch framework. Conceptually, NNCF consists of an integral core part with set of compression methods which form an NNCF Python package, and of a set of training samples which demonstrate capabilities of the compression methods implemented in the package. Each compression method has three basic components with a defined interface:

• Compression Method itself, responsible for correct model transformation, initialization and exporting the model to use it outside PyTorch.

• Compression Loss, representing an additional loss function introduced in the compression algorithm to facilitate compression.

• Compression Scheduler, controlling the parameters of the compression method during the training process.

We assume that potentially any compression method can be implemented using these three abstractions. For example, Regularization-Based (RB) sparsity method implemented in NNCF introduces a weights mask for Convolution and Fully-Connected layers which is an additional training parameter. This mask is added when the model is being wrapped and multiplied by weights during the export. This sparsity method exploits -regularization loss and implements its own scheduler which gradually increases the sparsity rate.

As mentioned before, one of the important features of the framework is automatic model transformation, i.e. the insertion of the auxiliary layers and operations required for a particular compression algorithm. This requires access to the PyTorch model graph, which is actually not made available by the PyTorch framework. To overcome this problem we patch PyTorch module in order to get access to all its operations at any time.

Another important novelty of NNCF is the support of algorithms mixing where the user can build own compression pipeline using several compression methods. An example of it is the models which are trained to be sparse and quantized at the same time to efficiently utilize sparse fixed-point arithmetic of the target hardware. The mixing feature implemented inside the framework does not require any adaptations from the user side. To enable it one only needs to specify set of supported compression methods in the con-figuration file.

Fig. 1 shows the common training pipeline for model compression. At the initial step a particular compression algorithm is instantiated and the model is wrapped with additional compression layers. After that the wrapped model is fine-tuned on the target dataset using modified training pipeline. This modification contains a call of Compression Loss computation which is added to the main loss (e.g. it can be cross-entropy loss in case of classification task) and then Compression Scheduler step is called. As we show in Appendix A any existing training pipeline written on PyTorch can be easily adopted to support model compression using NNCF. After the compressed model is trained we can export it to ONNX format for the further usage in OpenVINO[1] inference toolkit.

4. Compression Methods Overview

In this section we give an overview of the compression methods implemented in NNCF framework.

4.1. Quantization

The first and most common compression method is quantization. Our quantization approach combines ideas of QAT [8] and PACT [3] and very close to TQT [22]: we train quantization parameters jointly with network weights using so-called ”fake” quantization operations inside the model graph. But in contrast to TQT, NNCF supports symmetric and asymmetric schemes for activations and weights as well as the support of per-channel quantization of weights which helps to quantize even lightweight models produced by NAS, such as EfficientNet-B0.

For all supported schemes quantization is represented by the affine mapping of integers q to real numbers r:

where s and z are quantization parameters. The constant s (”scale factor”) is a positive real number, z (zero-point) has the same type as quantized value q and maps to the real value r = 0. Zero-point is used for asymmetric quantization and provides proper handling of zero paddings. For symmetric quantization it is equal to 0.

Symmetric quantization. During the training we optimize the scale parameter that represents range of the original signal:

where defines quantization range. Zeropoint always equal to zero in this case. Quantization ranges for activation and weights are tailored toward the hardware options available at OpenVINO Toolkit (see Table 1). Three point-wise operations are sequentially applied to quantize r to q: scaling, clamping and rounding.

Figure 1: A common model compression pipeline with NNCF. At the first step, an original full-precision model is automatically wrapped by the compression algorithm and then fine-tuned for a pre-defined number of epochs. After the training is done the model is exported to ONNX format and can be inferred with OpenVINO.

Table 1: Quantization ranges for symmetric mode for dif- ferent bit-width of integer number.

where denotes “bankers” rounding operation.

Asymmetric quantization. Unlike symmetric quantization, for asymmetric we optimize boundaries of floating point range () and use zero-point (z) from (1).

In addition we add a constraint to the quantization scheme: floating-point zero should be exactly mapped into integer within quantization range. This constraint allows ef-ficient implementation of layers with padding. Therefore we ”tune” ranges before quantization with the following scheme:

Comparing quantization modes. The main advantage of symmetric quantization is simplicity. It does not have zero-point, which introduces additional logic in hardware. But asymmetric mode allows fully utilize quantization ranges, which may potentially lead to better accuracy, especially for lower than to 8-bits quantization, as we show in the table 2.

Training and inference. As it was mentioned, quantization is simulated on forward pass of training by means of FakeQuantization operations which perform quantization according to (2) or (3) and dequantization (4) at the same time:

Table 2: Quantization scheme comparison for different bit- width for weights and activations using MobileNet v2 and CIFAR-100 dataset. Top-1 accuracy is used as a metric. 32-bit floating point model has 65.53%.

FakeQuantization layers are automatically inserted in the model graph. Weights get ”fake” quantized before the corresponding operations. Activations are quantized when the preceding layer changes the data type of the tensor, except for basic fusion patterns which correspond to one operation at inference time, such as Conv + ReLU or Conv + BatchNorm + ReLU.

Unlike QAT [8] and TQT [22], we do not do BatchNorm folding in order to avoid double computation of convolution and additional memory consumption which significantly slow down the training. However, to avoid misalignment between BatchNorm statistics during the training and inference we need to use a large batch size (256 or more).

4.2. Binarization

Currently NNCF supports binarizing weights and activations of 2D convolutional PyTorch layers (Conv2D).

Weight binarization can be done either via XNOR binarization [20] or via DoReFa binarization [29] schemes. For DoReFa binarization the scale of binarized weights for each convolution operation is calculated as the mean of absolute values of non-binarized convolutional filter weights, while for XNOR binarization each convolutional operation will have scales that are calculated in the same manner, but per-input channel for the convolutional filter.

Activation binarization is implemented via binarizing inputs of the convolutional layers in the following way:

where in are the non-binarized activation values, out - binarized activation values, H(x) is the Heaviside step function and s and t are trainable parameters corresponding to binarization scale and threshold respectively. The thresholds t are trained separately for each output activation channel dimension.

It is usually not recommended to binarize certain layers of CNNs - for instance, the input convolutional layer, the fully connected layer and the convolutional layer directly preceding it or the ResNet “downsample” layers. NNCF allows picking an exact subset of layers to be binarized via the layer blacklist/whitelist mechanism as in other NNCF compression methods.

Finally, training binarized networks requires a special scheduling of the training process, tailored specifically for each model architecture. NNCF samples demonstrate binarization of a ResNet-18 architecture pre-trained on ImageNet using a four-stage process, where each stage taking a certain number of fine-tuning epochs:

• Stage 1: the network is trained without any binarization,

• Stage 2: the training continues with binarization enabled for activations only,

• Stage 3: binarization is enabled both for activations and weights,

• Stage 4: the optimizer learning rate, which had been kept constant at previous stages, is decreased according to a polynomial law, while weight decay parameter of the optimizer is set to 0.

The configuration files for the NNCF binarization algorithm allow controlling the stage durations of this training schedule. Table 4 presents the results of binarizing ResNet-18 with either XNOR or DoReFa weight binarization and scale-threshold activation binarization (5).

4.3. Sparsity

NNCF supports two non-structured sparsity algorithms: i.) a simple magnitude-based sparsity training scheme, and ii.) regularization-based training, which is a modifica-tion of the method proposed in [14]. It has been argued [4] that complex approaches to sparsification like regularization produce inconsistent results when applied to large benchmark dataset (e.g. ImageNet for classification, as opposed to e.g. CIFAR-100) and that magnitude-based sparsity algorithms provide comparable or better results in these cases. However, we found out in our experiments that the regularization-based (RB) approach to sparsity outperforms the simple magnitude-based method for several classifica-tion models trained on ImageNet, achieving higher accuracy for the same sparsity level value for several models (e.g. MobilenetV2). Hence, both methods could be used in different contexts, with RB sparsity requiring tuning of the training schedule and a longer training procedure, but ultimately producing better results for certain tasks. We briefly describe the details of both network sparsification algorithms implemented in NNCF below.

Magnitude-based sparsity. In the magnitude-based weight pruning algorithm, the magnitude of each weight is used as a measure of its importance. In the NNCF implementation of magnitude-based sparsity, a certain schedule for the desired sparsity rate (equal to , where SL is the sparsity level) over the training process is de-fined, and a threshold value is calculated each time SL is

Table 3: Accuracy results of INT8 quantization measured in the training framework in FP32 precision.

* Whole word masking.

Table 4: Binarization results measured in the training framework

Table 5: Sparsification+quantization results measured in the training framework

Table 6: Accuracy top-1 results for INT8 quantization of EfficientNet-B0 model on ImageNet measured in the training framework

changed by the compression scheduler. Weights that are lower than the calculated threshold value are then zeroed out. The compression scheduler can be set to increase

the sparsity rate from an initial to a final level over a certain number of training epochs. The dynamics of sparsity level increase during training are adjustable and support polynomial, exponential, adaptive and multistep modes.

Regularization-based sparsity. In the RB sparsity algorithm, a complexity loss term is added to the total loss function during training, defined as

where is the number of network parameters and SL is the desired sparsity level (percentage of non-zero weights) of the network is set out to achieve. Note that the above reg- ularization loss term penalizes networks with sparsity levels both lower and higher than the defined SL level. Following the derivations in [14], in order to make the loss term differentiable, the model weights are reparametrized as follows:

where is the stochastic binary gate, . It can be shown that the above formulation is equivalent to being sampled from the Bernoulli distribution with probability parameter sigmoid. Hence, are the trainable parameters which control whether the weight is going to be zeroed out at test time (which is done for ).

On each training iteration, the set of binary gate values is sampled once from the above distribution and multiplied with network weights. In the Monte Carlo approximation of the loss function in [14], the mask of binary gates is generally sampled and applied several times per training iteration, but single mask sampling is sufficient in practice (as shown in [14]). The expected loss term was shown to be proportional to the sum of probabilities of gates being non-zero [14], which in our case results in the following expression

To make the error loss term (e.g. cross-entropy for classi-fication) differentiable w.r.t , we treat the threshold function t(x) = [x > c] as a straight-through estimator (i.e. dt/dx = 1).

5. Results

Some of the results for different compression methods were disclosed in the corresponding sections. Table 6 reports compression results for EfficientNet-B0, which gives best combination of accuracy and performance on ImageNet. We compare accuracy achieved on floating point model (76.84% of top-1) and with accuracy of compressed one.

Here we show performance results for compressed models with OpenVINO toolkit in the Table 7.

To extend the scope of trainable models and to validate that NNCF could be easily combined with existing PyTorch-based training pipelines, we integrated NNCF with the popular mmdetection object detection toolbox [2]. As a result, we were able to train INT8-quantized and INT8-quantized+sparse object detection models available in mmdetection on the challenging COCO dataset and

Table 7: Relative performance/accuracy results with Open- VINO on Intel RXeon RGold 6230 Processor

achieve a less than 1 mAP point drop for the COCO-based mAP evaluation metric. Specific results for compressed RetinaNet-FPN-based detection models are shown in table 8.

Table 8: Validation set metrics for original and compressed mmdetection models. Shown are mAP values for models trained and tested on the COCO dataset.

6. Conclusions

In this work we presented new NNCF framework for model compression with fine-tuning. It supports various compression methods and allows combining them to get more lightweight neural networks. We paid special attention to usability aspects and simplified the compression process setup as well as approbate the framework on a wide range of models. Models obtained with NNCF show state-of-the-art results in terms of accuracy-performance trade-off. The framework is compatible with OpenVINO inference toolkit which makes it attractive to apply the compression to real-world applications. We are constantly working on developing new features and improvement of the current ones as well as adding support of new models.

References

[1] Intel Rhttps://software.intel.com/en-us/openvino-toolkit. 2, 3

[2] K. Chen, J. Wang, J. Pang, Y. Cao, Y. Xiong, X. Li, S. Sun, W. Feng, Z. Liu, J. Xu, et al. Mmdetection: Open mmlab detection toolbox and benchmark. arXiv preprint arXiv:1906.07155, 2019. 7

[3] J. Choi, Z. Wang, S. Venkataramani, P. I.-J. Chuang, V. Srini- vasan, and K. Gopalakrishnan. Pact: Parameterized clip-

ping activation for quantized neural networks. arXiv preprint arXiv:1805.06085, 2018. 1, 2, 3

[4] T. Gale, E. Elsen, and S. Hooker. The state of sparsity in deep neural networks. arXiv preprint arXiv:1902.09574, 2019. 5

[5] A. N. Gomez, I. Zhang, K. Swersky, Y. Gal, and G. E. Hinton. Learning sparse networks using targeted dropout. arXiv preprint arXiv:1905.13678, 2019. 2

[6] S. Han, J. Pool, J. Tran, and W. Dally. Learning both weights and connections for efficient neural network. In Advances in neural information processing systems, pages 1135–1143, 2015. 2

[7] I. Hubara, M. Courbariaux, D. Soudry, R. El-Yaniv, and Y. Bengio. Binarized neural networks. In Advances in neural information processing systems, pages 4107–4115, 2016. 1

[8] R. Krishnamoorthi. Quantizing deep convolutional networks for efficient inference: A whitepaper. arXiv preprint arXiv:1806.08342, 2018. 1, 2, 3, 5

[9] A. Krizhevsky, I. Sutskever, and G. E. Hinton. Imagenet classification with deep convolutional neural networks. In F. Pereira, C. J. C. Burges, L. Bottou, and K. Q. Weinberger, editors, Advances in Neural Information Processing Systems 25, pages 1097–1105. Curran Associates, Inc., 2012. 1

[10] B. Liu, M. Wang, H. Foroosh, M. Tappen, and M. Pensky. Sparse convolutional neural networks. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 806–814, 2015. 1

[11] C. Liu, B. Zoph, M. Neumann, J. Shlens, W. Hua, L.-J. Li, L. Fei-Fei, A. Yuille, J. Huang, and K. Murphy. Progressive neural architecture search. In Proceedings of the European Conference on Computer Vision (ECCV), pages 19–34, 2018. 1

[12] Z. Liu, J. Li, Z. Shen, G. Huang, S. Yan, and C. Zhang. Learning efficient convolutional networks through network slimming. In Proceedings of the IEEE International Conference on Computer Vision, pages 2736–2744, 2017. 2

[13] C. Louizos, M. Welling, and D. P. Kingma. Learning sparse neural networks through l0 regularization. arXiv preprint arXiv:1712.01312, 2017. 1

[14] C. Louizos, M. Welling, and D. P. Kingma. Learning sparse neural networks through l0 regularization. arXiv preprint arXiv:1712.01312, 2017. 2, 5, 7

[15] D. Molchanov, A. Ashukha, and D. Vetrov. Variational dropout sparsifies deep neural networks. In Proceedings of the 34th International Conference on Machine LearningVolume 70, pages 2498–2507. JMLR. org, 2017. 2

[16] A. v. d. Oord, S. Dieleman, H. Zen, K. Simonyan, O. Vinyals, A. Graves, N. Kalchbrenner, A. Senior, and K. Kavukcuoglu. Wavenet: A generative model for raw audio. arXiv preprint arXiv:1609.03499, 2016. 1

[17] J. Park, S. Li, W. Wen, P. T. P. Tang, H. Li, Y. Chen, and P. Dubey. Faster cnns with direct sparse convolutions and guided pruning. arXiv preprint arXiv:1608.01409, 2016. 1

[18] A. Paszke, S. Gross, S. Chintala, G. Chanan, E. Yang, Z. De- Vito, Z. Lin, A. Desmaison, L. Antiga, and A. Lerer. Automatic differentiation in pytorch. In NIPS-W, 2017. 1

[19] M. Rastegari, V. Ordonez, J. Redmon, and A. Farhadi. Xnor- net: Imagenet classification using binary convolutional neu-

ral networks. In European Conference on Computer Vision, pages 525–542. Springer, 2016. 1

[20] M. Rastegari, V. Ordonez, J. Redmon, and A. Farhadi. Xnor- net: Imagenet classification using binary convolutional neural networks. In European Conference on Computer Vision, pages 525–542. Springer, 2016. 5

[21] P. Rodr´ıguez, J. Gonzalez, G. Cucurull, J. M. Gonfaus, and X. Roca. Regularizing cnns with locally constrained decorrelations. arXiv preprint arXiv:1611.01967, 2016. 1

[22] M. W. C. H. D. Sambhav R. Jain, Albert Gural. Trained quantization thresholds for accurate and efficient fixed-point inference of deep neural networks, 2019. 2, 3, 5

[23] W. Shang, K. Sohn, D. Almeida, and H. Lee. Understanding and improving convolutional neural networks via concatenated rectified linear units. In international conference on machine learning, pages 2217–2225, 2016. 1

[24] K. Simonyan and A. Zisserman. Very deep convolutional networks for large-scale image recognition, 2014. 1

[25] M. Tan, B. Chen, R. Pang, V. Vasudevan, M. Sandler, A. Howard, and Q. V. Le. Mnasnet: Platform-aware neural architecture search for mobile. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 2820–2828, 2019. 1

[26] Y. Wu, M. Schuster, Z. Chen, Q. V. Le, M. Norouzi, W. Macherey, M. Krikun, Y. Cao, Q. Gao, K. Macherey, et al. Google’s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv:1609.08144, 2016. 1

[27] M. D. Zeiler and R. Fergus. Visualizing and understanding convolutional networks. In European conference on computer vision, pages 818–833. Springer, 2014. 1

[28] S. Zhou, Y. Wu, Z. Ni, X. Zhou, H. Wen, and Y. Zou. Dorefa-net: Training low bitwidth convolutional neural networks with low bitwidth gradients. arXiv preprint arXiv:1606.06160, 2016. 1

[29] S. Zhou, Y. Wu, Z. Ni, X. Zhou, H. Wen, and Y. Zou. Dorefa-net: Training low bitwidth convolutional neural networks with low bitwidth gradients. arXiv preprint arXiv:1606.06160, 2016. 5

[30] M. Zhu and S. Gupta. To prune, or not to prune: explor- ing the efficacy of pruning for model compression. arXiv preprint arXiv:1710.01878, 2017. 2

[31] N. Zmora, G. Jacob, L. Zlotnik, B. Elharar, and G. Novik. Neural network distiller, June 2018. 2

[32] B. Zoph, V. Vasudevan, J. Shlens, and Q. V. Le. Learning transferable architectures for scalable image recognition. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 8697–8710, 2018. 1

A. Appendix

Described below are the steps required to modify an existing PyTorch training pipeline in order for it to be integrated with NNCF. The described use case implies there exists a PyTorch pipeline that reproduces model training in floating point precision and a pre-trained model snapshot. The objective of NNCF is to compress this model in order to accelerate the inference time. Once the NNCF package is installed, the user needs to revise the training code and introduce minor changes to enable model compression. Below are the steps needed to modify the training pipeline code in PyTorch:

• Add the following imports in the beginning of the training sample right after importing PyTorch:

from nncf.algo_selector \ import create_compression_algorithm \ as create_cm_algo

• Once a model instance is created and the pre-trained weights are loaded, a compression algorithm should be created and the model should be wrapped:

cm_algo = create_cm_algo(model, config) model = cm_algo.model

where config is a dictionary where all the options and hyperparametersof compression methods are specified.

• Then the model can be wrapped with DataParallel or DistributedDataParallel classes for multi-GPU training. In the case of distributed training you also need to call compressionalgo.distributed() method at this stage.

• You should call the compressionalgo.initialize() method before the start of your training loop to initialize model parameters related to its compression (e.g. parameters of FakeQuantize layers). Some compression algorithms (e.g. quantization) require arguments (e.g. the trainloader for your training dataset) to be supplied to the initialize() method.

• The following changes have to be applied to the training loop code: after model inference is done on the current training iteration, the compression loss should be added (using the + operator) to the common loss. e.g. cross-entropy loss:

compress_loss = cm_algo.loss() loss = cross_entropy_loss + compress_loss

Call the scheduler step() after each training iteration:

Call the scheduler epochstep() after each training epoch:

Designed for Accessibility and to further Open Science