<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adam Grygielski on Medium]]></title>
        <description><![CDATA[Stories by Adam Grygielski on Medium]]></description>
        <link>https://medium.com/@adam.grygielski?source=rss-d36fd8acf310------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CBoCPrFQbNx70ldJtiJG5A.png</url>
            <title>Stories by Adam Grygielski on Medium</title>
            <link>https://medium.com/@adam.grygielski?source=rss-d36fd8acf310------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:16:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adam.grygielski/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Optimizing inference on CPU in MXNet 2.0]]></title>
            <link>https://medium.com/apache-mxnet/optimizing-inference-on-cpu-in-mxnet-2-0-1852ff9729b4?source=rss-d36fd8acf310------2</link>
            <guid isPermaLink="false">https://medium.com/p/1852ff9729b4</guid>
            <category><![CDATA[mxnet]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[intel]]></category>
            <dc:creator><![CDATA[Adam Grygielski]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 19:20:32 GMT</pubDate>
            <atom:updated>2021-02-22T23:55:40.205Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing inference on CPU in the Upcoming Apache MXNet 2.0</h3><p><em>Authors: </em><a href="https://github.com/grygielski"><em>Adam Grygielski</em></a><em>, </em><a href="https://github.com/bgawrych"><em>Bartłomiej Gawrych</em></a><em>, </em><a href="https://github.com/sfraczek"><em>Sylwester Fraczek</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8xA-XS2fwuTVqoK0FYN6Q.jpeg" /></figure><h3>Introduction</h3><p>Deep Learning inference is the process of deploying a trained neural network to perform prediction on unseen data. It is a commonly deployed workload in cloud servers. To provide a good user experience it has to have high performance so it is important to use optimized solutions. Optimized means also reduced hardware load and energy cost.</p><p>There are two types of performance bottlenecks to consider when optimizing a neural network. One is heavy compute-bound operations like convolution or fully-connected and the other is many small memory-bound elementwise operations such as ReLU (or transposition).</p><p>A couple of methods have been invented for optimizing Neural Networks. Operator fusion allows to chain operations together to speed up memory-bound operations by reducing memory IO operations. Quantization speeds up compute-bound operations by lowering precision and therefore simplifying computation while also reducing the amount of data being processed.</p><p>Apache MXNet (incubating) in the upcoming version 2.0 introduces some changes in the interface. Gluon API has now become the default superseding symbolic and model API. It is unifying the flexibility of imperative programming with the performance benefits of symbolic programming. Also MXNet 2.0 now fully supports NumPy semantics.</p><h3>Operator Fusion</h3><p>In previous versions of Apache MXNet operators fusion was enabled by default when MXNet was built with Intel oneDNN library. However, with version 2.0 of MXNet, Module API and GraphExecutor were replaced by CachedOp executor. Gluon’s Block is now the first choice API to define and execute a model instead of a symbolic API.</p><p>Let’s recap what operator fusion is and what benefits come along with it, but before we move on to that, it is worth mentioning that MXNet support two execution modes:</p><ul><li>imperative mode - model is executed step-by-step as defined and we can access each tensor between operator execution</li><li>symbolic mode — based on defined model MXNet engine creates graph which can be optimized by e.g. pre-allocating space — we can’t access[1] tensors between operator execution</li></ul><p>An imperative mode is great for debugging purposes and symbolic mode provides a big performance boost. More information about the imperative and symbolic mode you can find <a href="https://classic.d2l.ai/chapter_computational-performance/hybridize.html">here</a>.</p><p>Every model can be represented as a directed graph where operators and tensors are represented as nodes. Each connection between operators, where the output of a single operator can be input to another one, is represented in the graph as an edge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03DOI_29XeAIgv2f36lUCQ.png" /></figure><p>Operator fusion is nothing else but replacing two or more subsequent operators with a new single operator that combines all functions of these operators. As a result, we get a smaller graph — only one kernel is being invoked instead of a few (one per operator). These fused kernels are optimized to run as fast as possible by utilizing all available features of a modern CPU. We also get rid of MXNet engine overhead between operator calls and we’re reducing memory access (read/write) operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2txh-y_TauT50PgxJygKag.png" /></figure><p><strong>How to fuse operators in my model?</strong><br>To fuse model in MXNet 2.0 there are two requirements:</p><ul><li>the model must be defined as a subclass of HybridBlock or Symbol</li><li>the model must have specific operator patterns which can be fused</li></ul><p>At the time of publishing this article in MXNet we support three major fusing patterns:</p><ul><li>Convolution + BatchNorm + ReLU/GELU/LeakyReLU/sigmoid/SoftReLU/tanh + Elementwise Add</li><li>FullyConnected + Elementwise Op (ReLU, Square, Logistic, SoftReLu, BoundedRelu, Sqrt, Exp, Abs)</li><li>BatchNorm + ReLU</li></ul><p>As an example we define example network (sample block from ResNet architecture):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d17e0c84759af266b197f47298d06444/href">https://medium.com/media/d17e0c84759af266b197f47298d06444/href</a></iframe><p>Both HybridBlock and Symbol classes provide API to easily run fusion of operators. All we have to do is add single line of code enabling fusion passes on our model:</p><pre>net.optimize_for(data, backend=&#39;MKLDNN&#39;)</pre><p>If we would like to apply passes on a Symbol all we have to do is to call <strong>optimize_for</strong> function without passing input data on a symbol instance. Notice that Symbol’s <strong>optimize_for</strong> function is not done in-place, so we must assign it to a new variable:</p><pre>optimized_symbol = sym.optimize_for(backend=&#39;MKLDNN&#39;)</pre><p>For the above model definition in a naive benchmark with artificial data, we can gain up to 1.25x speedup without any accuracy loss on our testing machine. Detailed data on other models’ speedup is shown in the “Performance and accuracy results” part of the article.</p><h3>Quantization</h3><p>Similar to 1.x versions, MXNet 2.0 continues supporting model quantization from float32 to either signed or unsigned INT8 (s8/u8). Using a quantized model for running inference on modern CPUs can greatly increase the performance of your workloads. Quantized models utilize VNNI (Vector Neural Network Instructions) instruction set to speed-up execution of compute-heavy operations like convolution or a dot product. Moreover, using int8 data type reduces the amount of data reads in memory-bound operations like pooling or elementwise functions. MXNet uses optimized kernels delivered by <a href="https://github.com/oneapi-src/oneDNN">Intel® oneDNN</a><a href="https://github.com/oneapi-src/oneDNN)[3">[3</a>] library to speed up model execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umGfUUazPg1Dz0HgtHVLUA.png" /></figure><p>During the quantization procedure, a floating-point model is first fused using fuses mentioned in the previous chapter. After that, operators that have int8 kernels are being marked as quantized and surrounded by quantize/requantize/dequantize operators. At last, the model can be either calibrated to get rid of requantize operators or left as it is to calculate scales during runtime. There are 2 major ways of quantizing an fp32 model:</p><ul><li><strong>without calibration</strong>. This way, all we have to do is call the <strong>quantize_net </strong>function with an fp32 Gluon model and a list of input data shapes. However, this approach is not recommended in terms of performance. It will result in requantize nodes in the graph that calculate min/max values during each forward pass. Calibrating a model before deploying it results in much faster inference.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pObYh5K4SWzo58F0XIvZeg.png" /></figure><ul><li><strong>with calibration</strong>. In this approach, after quantizing the graph, a model is run with user-supplied calibration data to collect statistics of quantized layers and set min/max values as parameters. The choice of these thresholds is based on the chosen calibration method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnEgomIqdjvlvz9T5EYLmg.png" /></figure><p>Currently, there are three calibration methods supported:</p><ul><li><strong>naive </strong>— min/max values from the calibration run.</li><li><strong>entropy</strong>— uses KL divergence to determine the best symmetrical quantization thresholds for a given histogram of values.</li><li><strong>custom </strong>— uses user-defined CalibrationCollector to control a calibration process.</li></ul><p>In MXNet 2.0, the quantization procedure has been adjusted to work well with Gluon models since it’s the main API now. The goal was to allow the user to quantize fp32 HybridBlock model in just a few lines of code.</p><h4>Quantization flow in MXNet 2.0</h4><p>As an example of a quantization procedure, we will use pretrained <strong>resnet50_v1 </strong>from <strong>model_zoo.vision</strong>. To get it we simply have to run the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3d86475380175353c3a849648fbaa6d/href">https://medium.com/media/a3d86475380175353c3a849648fbaa6d/href</a></iframe><p>To compare the performance, we will use simple function calculating total inference time on the model with an artificial data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edddf3cd87726f2e6205e5d840e21136/href">https://medium.com/media/edddf3cd87726f2e6205e5d840e21136/href</a></iframe><p>Now, to get a quantized model, all we need to do is call <strong>quantize_net</strong> function from <strong>contrib.quantize</strong> and provide list of input data shapes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49087ee38f8ed55c7fc940f7c1ecf17d/href">https://medium.com/media/49087ee38f8ed55c7fc940f7c1ecf17d/href</a></iframe><p>This way, we have quantized `resnet50_v1` ready to run inference tasks. However, we didn’t use any calibration data, therefore we won’t get a satisfactory performance boost.<br>We can compare these 2 models with our <strong>benchmark_net </strong>function to calculate the total speedup. To get better results, we should first hybridize both models with <strong>static_shape </strong>and <strong>static_alloc </strong>flags set to <strong>True</strong>. We can do it to let MXNet know that we won’t be changing shapes in the model during runtime thus it can pre-allocate the memory so we won’t get runtime allocations. To properly evaluate the performance benefits of quantization, we should compare it with fp32 model with <strong>MKLDNN </strong>backend enabled. It is because the quantization procedure fuses a graph before quantizing it so if we won’t do it, we will get the summed benefit of fusing and quantization.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/425f36346e2864b6e955e0e1c9cd542c/href">https://medium.com/media/425f36346e2864b6e955e0e1c9cd542c/href</a></iframe><p>Output:</p><pre>&gt; Speedup: 0.72x</pre><p>As we can see, we didn’t get any performance benefits from using int8. It came out, that calculating min/max during runtime adds a big overhead. Now let’s try calibrating the model before actual execution. The only difference in code is that we have to provide <strong>quantize_net </strong>with calibration data stored in <strong>DataLoader</strong> class. For this example, we will use the same <strong>dummy_data </strong>but in real use-case, it would be most probably small portion of validation dataset. Notice, that we no longer have to provide <strong>data_shape </strong>attribute because it will be taken from <strong>calib_data</strong>. If we don’t specify <strong>calib_batches </strong>parameter, the whole <strong>calib_data</strong> will be used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7c7712b0b918dc7b7358a734bdeca71/href">https://medium.com/media/b7c7712b0b918dc7b7358a734bdeca71/href</a></iframe><p>Output:</p><pre>&gt; Speedup: 3.8x</pre><p>This time we’ve got significant performance boost with just few lines of code.</p><p>The other aspect of lowering the precision of a model is a difference in its accuracy. We will check that on previously tested <strong>resnet50_v1 </strong>with ImageNet dataset. To run this example you will need ImageNet dataset prepared with <a href="https://cv.gluon.ai/build/examples_datasets/imagenet.html">this tutorial</a> and stored in <strong>path_to_imagenet</strong>. Let’s compare top1 and top5 accuracy of standard fp32 model with quantized int8 model calibrated using <strong>naive </strong>and <strong>entropy </strong>calibration mode. We will use only 10 batches of the validation dataset to calibrate quantized model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11275649828c1ef5d868d8c3f89b367d/href">https://medium.com/media/11275649828c1ef5d868d8c3f89b367d/href</a></iframe><p>Output:</p><pre>&gt; FP32 Top1 Accuracy: 0.76364 Top5 Accuracy: 0.93094<br>&gt; INT8Naive Top1 Accuracy: 0.76028 Top5 Accuracy: 0.92796<br>&gt; INT8Entropy Top1 Accuracy: 0.76404 Top5 Accuracy: 0.93042</pre><p>We can see that we’ve got almost the same accuracy for quantized model but we are able to run it with much less computing power and lower latencies. The difference between calibration method is dependent on the model itself, used activation layers and the size of calibration data. It should be chosen empirically. However, if you are not experienced with custom calibration methods, you should stick to <strong>entropy </strong>by default.</p><h4>Custom layer collectors and calibrating the model</h4><p>We have prepared an interface to give the user as much flexibility as possible in almost every step of quantization and one of the results of this approach is mentioned earlier custom LayerOutputCollector parameter in quantization API.</p><p>Layer collectors are responsible for collecting statistics of each node in the graph — it means that we can observe the input/output data of every operator executed. We are able to do this by utilizing the <strong>register_op_hook </strong>method of <strong>HybridBlock </strong>class.</p><p>To write your own layer collector your class has to inherit from the <strong>CalibrationCollector</strong> class, which we have provided, to stay consistent within API. As “code is worth a thousand words” below we show an example implementation of CalibrationCollector:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92d4c12456e1ecab6ab7645e37807b30/href">https://medium.com/media/92d4c12456e1ecab6ab7645e37807b30/href</a></iframe><p>We are ‘injecting’ names of nodes which require calibration into the <strong>include_layers </strong>instance attribute of custom collector — it is organized in this way because collecting statistics for every node is very time consuming, but thanks to this you can skip nodes that do not need calibration (also you can ignore this attribute and implement your own logic of picking nodes to calibrate).</p><p>After collecting all statistic data <strong>post_collect </strong>function is called. In <strong>post_collect </strong>you can implement additional logic, which will process gathered data in the implemented way and at the end return dictionary of node name as key and tuple of min and max threshold as value, which will be used to calibrate nodes.</p><p><strong>Example of usage with quantization API:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5061127ac8d8db0c7083ff9045ab1346/href">https://medium.com/media/5061127ac8d8db0c7083ff9045ab1346/href</a></iframe><p>It is not easy to write your own logic of collector, but if you know what you are doing you can get better accuracy. In the previous version of MXNet and GluonNLP our colleagues wrote layer collector for BERT models — they clip minimum/maximum values of some layers to get better accuracy <a href="https://github.com/dmlc/gluon-nlp/blob/v0.10.x/src/gluonnlp/calibration/collector.py">BertLayerCollector</a> (note that it’s not compliant with MXNet 2.0 — you can refer to <a href="https://github.com/apache/incubator-mxnet/blob/master/python/mxnet/contrib/quantization.py#L193-L320">predefined collectors in MXNet 2.0 code</a>).</p><h3>Performance and accuracy results</h3><p>Here we present performance results of some CV models. We compare Fused and Quantized models to Base models hybridized with static memory allocation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXFtTCaoQ59BcjMUx_JrvQ.png" /><figcaption>Relative Inference Performance (img/sec) for Batch Size 128</figcaption></figure><p>As you can see, popular ResNet50 gains 62% speedup with just operator fusion and it is more than 6x faster than Base fp32 model while quantized. We may also observe that <strong>mobilenet </strong>benefits the most from presented optimizations. It’s mainly due to the efficient fusing. Moreover, in the quantized version, relu6 (which is the activation function in mobilenet) can be achieved just by adjusting scale factors of int8 computation thus we could optimize it even more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kCHeVdfCsL6vyE7umhnSw.png" /><figcaption>ImageNet(ILSVRC2012) TOP1 validation accuracy</figcaption></figure><p>These are the results of TOP1 ImageNet accuracy for computer vision models and as you can see — by calling single function you can gain a significant performance boost almost without losing accuracy. In the chart, the biggest accuracy drop is visible in mobilenet v2, but it is still only half a percentage point less than fp32 model. On the other hand, VGG19 has no accuracy lost at all and after quantization, it is over 4 times faster than the baseline model.</p><h3>Summary</h3><p>In this article, we showed how you can speed up your MXNet model on CPU with oneDNN support. If you’re fine with tiny accuracy drop, model quantization is a great method of significantly improving performance. Otherwise, you can still use model fusion supported by oneDNN primitives without any side effects. In this case, the performance boost is not so impactful as in the quantized model but accuracy doesn’t change.</p><p>Moreover, the article described how you can utilize the new <strong>CalibrationCollector </strong>class to have better control of the calibration process. Such a solution gives you flexibility and a chance to increase the accuracy of your quantized model.</p><p>Many things have changed since the introduction of MXNet 2.0. Gluon API has taken over Executor-based execution thus now users have to manually call <strong>optimize_for </strong>function to get benefits from CPU optimization passes. We have also introduced the new <strong>BatchNorm + ReLU</strong> fusion to address ResNet v2 models. Our future plans are to add support for more and more int8 models, not only in a CV domain. We are also exploring new fusion opportunities so we can speed up popular models even more.</p><h3>References</h3><p>[1] Devlin, Jacob, et al. “BERT: Pre-training of deep bidirectional transformers for language understanding.” arXiv pre-print arXiv:1810.04805 (2018).<br>[2] Banu Nagasundaram. “Vector Neural Network Instructions Enable Int8 AI Inference on Intel Architecture.” <a href="https://www.intel.ai/vnni-enables-inference/">https://www.intel.ai/vnni-enables-inference/</a>, 2019.<br>[3] Intel® oneDNN library (<a href="https://github.com/oneapi-src/oneDNN">https://github.com/oneapi-src/oneDNN</a>)</p><h3>Benchmark environment</h3><p><strong>CPU:</strong> Intel<strong>®</strong> Xeon<strong>®</strong> Platinum 8280L CPU @ 2.70GHz<br><strong>Memory:</strong> 187 GB RAM<br><strong>OS:</strong> CentOS Linux 7 (Core)<br><strong>Compiler:</strong> gcc (GCC) 7.3.1 20180303 (Red Hat 7.3.1–5)<br><strong>MXNet Commit SHA:</strong> 3746babc8fdb211584a9a661207061cb646b01a8<br><strong>oneDNN Commit SHA:</strong> 2e4732679f0211bb311780d0f383cf2dce9baca7</p><h3>Notices and Disclaimers</h3><p>© Intel Corporation. Intel, the Intel logo, and other Intel marks are trademarks of Intel Corporation or its subsidiaries. Other names and brands may be claimed as the property of others.</p><p>Performance varies by use, configuration and other factors. Learn more at <a href="http://www.intel.com/PerformanceIndex">www.Intel.com/PerformanceIndex</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1852ff9729b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-mxnet/optimizing-inference-on-cpu-in-mxnet-2-0-1852ff9729b4">Optimizing inference on CPU in MXNet 2.0</a> was originally published in <a href="https://medium.com/apache-mxnet">Apache MXNet</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>