<?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 AI Practitioner and Writer on Medium]]></title>
        <description><![CDATA[Stories by AI Practitioner and Writer on Medium]]></description>
        <link>https://medium.com/@aiwriterbros?source=rss-2e218d3ebd79------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8QugX9IceGOBYd4zQC3lEQ.png</url>
            <title>Stories by AI Practitioner and Writer on Medium</title>
            <link>https://medium.com/@aiwriterbros?source=rss-2e218d3ebd79------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:34:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aiwriterbros/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[Computer Vision applications for the industry]]></title>
            <link>https://medium.com/@aiwriterbros/computer-vision-applications-for-the-industry-218ae48e9d6a?source=rss-2e218d3ebd79------2</link>
            <guid isPermaLink="false">https://medium.com/p/218ae48e9d6a</guid>
            <category><![CDATA[industry]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[AI Practitioner and Writer]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 12:35:00 GMT</pubDate>
            <atom:updated>2023-01-17T12:35:00.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhLvv-GTNzjTMCgCH0FutQ.jpeg" /><figcaption>Industrial photo found on Pexels (CC0 licensed)</figcaption></figure><h4>Industrial applications and market overview of Deep Learning and Computer vision</h4><h3>Overview</h3><p>This article gives an overview of the growth factors and drivers of computer vision, the market segments and leaders, and finally concludes with use cases that include the latest advancements in the construction industry, manufacturing industry, and healthcare.</p><p>Computer Vision (CV) is a sub-field of artificial intelligence​ ​(AI) which consists in bringing human vision capability into computing systems. It deals with interpreting real-world scenarios which are captured by camera-enabled mobile devices in the form of images and videos. Some of the most commonly used computer vision-based applications are facial recognition, human-computer interface, gesture recognition, visual quality inspection of goods in manufacturing processes, in navigation for autonomous vehicles, medical image analysis, and image restoration.</p><h3>Growth factors and drivers</h3><p>The main drivers which pushing CV-based applications into the market are the following:</p><ol><li>There is a persistent demand in the market for industrial-based (e.g., quality inspection, predictive maintenance, automation, security, human-machine interaction, etc) or consumer-based (e.g., augmented reality (AR), virtual reality (VR)) applications.</li><li>In the last decade, there has been substantial advancement in technology from both aspects of hardware and software. Machine learning-based approaches, especially deep learning, have seen tremendous growth in the last decade. Deep learning-based models (e.g Convolutional Neural Networks and Transformers) have achieved even accuracies in certain specific tasks(e.g., image classification) higher than humans. Similarly, AI-enabled processors are having a much bigger presence in nearly all mobile devices such as smartphones, drones, raspberry pi, and similar small board computers and consumer electronic devices. It is now possible much more easily process and analyze images on these devices.</li><li>Lastly, all the major software and tech giants like Google, NVIDIA, Intel, Microsoft, Amazon, etc. are increasingly investing in research and development projects associated with CV and AI. There is a huge rush of investments into start-ups that are providing cutting-edge solutions. This money either comes in the form of investment by venture capital firms or in the form of grants by government agencies.</li></ol><p>Despite big hype and the success of CV/AI, there remain, however, some challenges for the technology adoption in the industry. Some of them are</p><blockquote>Lack of industrial digitization.</blockquote><blockquote>Not enough technical experts available in the market.</blockquote><blockquote>Concerns regarding data privacy and</blockquote><blockquote>Unreliability of the AI algorithms due to their black-box behavior, in other words the lack of model explainability.</blockquote><h3>Market segments and leaders</h3><p>The Global AI in Computer Vision market is majorly segmented in terms of components, verticals, and geographical regions. On the basis of components, it is further divided into hardware and software. On the basis of verticals, it can be divided into manufacturing, automobile, healthcare, logistics, security and surveillance, robotics, consumer electronics, entertainment, and many others. On the basis of geographical regions, it can be divided majorly into North America, Europe, and Asia. This market is mainly dominated by North America, especially the U.S., followed by Europe (U.K., Germany, France) and witnessing a fast and rapidly growing rate in the Asia Pacific (China, Japan, India). Some of the major important market players are Google, Amazon, Nvidia, Facebook, Microsoft, Uber, Cognex Corporation, Qualcomm, Apple, Basler AG, etc.</p><h3>Use-cases</h3><p>Below are some industrial-specific use cases which demonstrate potential uses of computer vision-based technologies. Some of them are research-type while others are already being used in a production setting.</p><h4>​Construction industry​</h4><p>Computer vision can potentially bring a lot of added value to the construction industry by providing real-time monitoring of construction sites. Another major concern in this industry is the worker’s accidents and mishap happening which can be prevented by monitoring the workers. Here are some of the use cases in this industry:</p><ul><li><strong><em>Automated progress monitoring of a construction site</em></strong></li></ul><p>Traditionally, an expert needs to visit the construction site and needs to estimate the amount of work done. This process is manual, time-consuming, subjective and prone to error. It is important to compare the actual state of the project to the as-planned state so that potential delays can be identified early within the project life-cycle. This manual process can be automated by using imaging technologies, such as camera, LiDAR and 3D range imaging to capture the current state of the site. Using the imaging data, an estimate 3D model/geometry of the site can be generated which can be compared (or registration) with a 3D CAD model of the planned building. Thus, the current state of construction site progression can be calculated.</p><ul><li><strong><em>Infrastructure Quality Assessment</em></strong></li></ul><p>It is important on a timely basis to check the quality of the roads, bridges and buildings to ensure the quality to prevent any kind of hazardous accidents. Preventive measures can be taken if some significant cracks/holes can be detected early enough. Due to bigger and long sizes of roads, bridges and buildings, it is not feasible to send a person to manually inspect them and their evaluations can be highly subjective. Therefore, AI can play an important role to detect cracks and holes in the images acquired by a camera system mounted on a drone.</p><ul><li><strong><em>Workers safety monitoring</em></strong></li></ul><p>The construction company is one of the most dangerous sectors in the world since workers accidents are the highest number compared with other industries. Generally, construction workers accidents are caused by an unsafe act and unsafe condition that can occur separately or together, thus safety monitoring is needed to achieve zero accident. One of the possibilities to reduce the risk of resulting injuries is to ensure that all workers wear the correct Personal Protection Compliance (PPE), e.g., helmet, goggles, gloves and vest. Most of the injuries are as a direct result of PPE failure or non-compliance and these could be eliminated through proper monitoring and alerts. Surprisingly, most businesses still manually monitor employees’ PPE compliance and therefore, there is a strong need to automate this monitoring process with the help of AI. A camera system powered with AI software can be installed at the entrance of the construction site which automatically checks PPE compliance of the workers passing through it.</p><h4>Manufacturing industry</h4><p>Quality control, in general, is one of the main challenges that are well-tackled by the usage of AI and computer vision-powered technologies. Traditionally, quality control monitoring is being performed under the guidance of experts, however, it is getting more and more common to rely on computer vision-based systems rather than human visions. These monitoring systems usually consist of cameras with some lightning conditions and computer hardware and software systems.</p><p>Key advantages of the computer vision applications in this context are:</p><blockquote>improved high-quality control.</blockquote><blockquote>decrease in labor cost.</blockquote><blockquote>high-speed processing capability and</blockquote><blockquote>continuous operations.</blockquote><p>Followings are some of computer vision-based applications:</p><ul><li><strong><em>Packaging (or good) inspection</em></strong></li></ul><p>It is crucial for a manufacturing companies to check whether products that are manufactured are of desired quality and forms. For example, for a pharmaceutical companies, it is important to count tablets or capsules and check their forms (if they are either broken or partially formed) before placing them into containers. Computer vision-based systems can determine whether tablets are broken or partially formed. As tablets make their way through the production line, images of them are taken and are processed to check if the tables are the right color, length, width and not broken. In a similar way, other kinds of goods can be inspected.</p><ul><li><strong><em>Predictive maintenance​</em></strong></li></ul><p>Predictive maintenance is the process of using machine learning and IoT devices to monitor data on machinery and components, often using sensors, to collect data points and identify signals or take corrective actions before components break down. Cameras can be attached to the machines or robots to take pictures of them on a regular basis. These images along with meta-data can be subsequently processed which can eventually identify problems before they happen.</p><ul><li><strong><em>Defect detection</em></strong></li></ul><p>Manufacturers unarguably want components that roll off the production line to be free of defects and issues, but being able to do this at scale can pose problems for more manual efforts. Machine vision is the ideal technology that can help businesses automate a problem like this. A machine vision-based system can identify defects, store images and associated metadata related to it. As items are processed along the production line, any defects that are identified get classified according to their type, they are then assigned a grade to help further identify the severity of the defect.</p><h4>Healthcare</h4><p>With the availability of large medical imaging data, increasing computing power, and decreasing the cost of hardware, Deep Learning has made possible a paradigm shift in the field of medical imaging analysis. Two major concerns in medical diagnostics are</p><blockquote>early detection of the disease and</blockquote><blockquote>a need for a second reader (or assistant) to complement the main doctor which can potentially lead to the right decision-making.</blockquote><p>Some of the specific use cases within the medical imaging (i.e., Radiology) domain are mentioned below:</p><ul><li><strong><em>Detect Signs of Diabetic Retinopathy​</em></strong></li></ul><p>Diabetic Retinopathy (DR) is a diabetic complication that affects the eyes. High blood sugar due to diabetes (both type 1 or type 2) damages the tiny blood vessels in the retina, leading to a distorted vision. Eventually, it can cause blindness. DR is a leading cause of blindness, resulting in up to 24,000 cases each year in adults in the US. To avoid any complication, early detection of DR is important, therefore, patients are advised to have regular screening of their eyes. It is during this stage when the treatments to avoid vision loss are really effective. With early detection, DR can be treated with techniques that have been shown to reduce the risk of severe vision loss by &gt;90%. The AI-based solution can, therefore, be used for an initial screening which can refer detected milder cases to the ophthalmologist. Thus, it can reduce the burden on the ophthalmologists who would have to examine much fewer patients.</p><ul><li><strong><em>Lung cancer detection using CT scan​</em></strong></li></ul><p>Lung cancer is the leading cause of cancer deaths worldwide. A low dose CT (computed tomography) is the standard diagnostic test for lung cancer for those at high risk. Studies have found that screening can either reduce the risk of dying or improve life quality since treatments (e.g., removing the tumor) are effective enough during the early stage. In addition to finding definite cancers, the scans can also identify spots that might later become cancer, so that radiologists can sort patients into risk groups and decide whether they need biopsies or more frequent follow-up scans to keep track of the suspect regions. But, the test has pitfalls: it can miss tumors, or mistake benign spots for malignancies and push patients into invasive, risky procedures like lung biopsies or surgery. And, different radiologists might have different subjective opinions about the same scan. AI may help doctors make more accurate readings of CT scans by looking into complex patterns which might be missed out by them.</p><ul><li><strong><em>Early Detection of Skin Cancer Detection​</em></strong></li></ul><p>Early detection of skin cancer can potentially reduce the risk of advanced melanoma by a high proportion. Characteristics of suspicious moles are described by the ‘ABCDE’ rule: Asymmetry, Border irregularity, Color variation,Diameter and Evolving. Recently, AI-based systems have shown promising results in detecting skin cancer. They were trained on a large collection of dermoscopic images that have been labeled as benign or malignant. However, there are still some concerns related to the reliability of such systems. All the training data were nearly always captured in optimal conditions. Therefore, they cannot take real-world unpredictabilities into accounts, e.g. in a real-world scenario, everyone has a different phone, there are different lighting conditions and background are different and all the racial skin types need to be included in the training data.</p><h3>Conclusion</h3><p>We have seen some of the real-world applications of Computer Vision in this article. This list, of course, goes further than that. There is no doubt that Computer Vision and Artificial Intelligence are having more presence in our daily life and will continue to in the future. They can help industries to boost their productivity while ensuring a high quality of the goods. And, soon we will see AI helping doctors to diagnose patients better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=218ae48e9d6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intel OpenVINO with OpenCV]]></title>
            <link>https://medium.com/sclable/intel-openvino-with-opencv-f5ad03363a38?source=rss-2e218d3ebd79------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5ad03363a38</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[openvino]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[edge-computing]]></category>
            <dc:creator><![CDATA[AI Practitioner and Writer]]></dc:creator>
            <pubDate>Fri, 16 Oct 2020 09:05:41 GMT</pubDate>
            <atom:updated>2020-10-16T09:05:41.169Z</atom:updated>
            <content:encoded><![CDATA[<p>A guide to speed up inferences of trained Deep Learning models across Intel hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5sMHh7qQxwjHRJW5LXnCw.png" /><figcaption><a href="https://opencv.org/openvino-toolkit-2019-r1-1-is-now-available/">Open Vino</a>, background photo by Kelly Lacy on Pexels</figcaption></figure><h3>Introduction</h3><p>Training deep learning models is compute-intensive and it is performed either in the cloud or on a workstation machine, both of which are equipped with high-end GPUs and CPUs. On the other hand, the execution of these trained models does not necessarily require such expensive solutions and quite often are required to run in mobile or edge devices which might be equipped with low-end CPUs/GPUs/FPGAs or even with external USB neural network accelerators like the <a href="https://www.intel.com/content/dam/support/us/en/documents/boardsandkits/neural-compute-sticks/NCS2_Product-Brief-English.pdf">Intel Movidius Neural Stick 2 (NCS 2)</a>.</p><p>In this article, we will go through a toolkit provided by Intel called <a href="https://opencv.org/openvino-toolkit-2019-r1-1-is-now-available/">OpenVINO</a> and see how it can be used to perform model inference efficiently across various intel platforms ranging from clouds/servers to edge devices. We shall also see how it can be used along with OpenCV, especially with its Deep Neural Network (DNN) module. Several examples of image classification, object detection and image segmentation are provided in this <a href="https://github.com/sclable/openvino_opencv">Github repository</a>.</p><h3>What is OpenVINO?</h3><p>OpenVINO (Open Visual Inference and Neural Network Optimization) is a toolkit which allows to run DL models across various Intel specific hardware devices like Intel CPUs (Xeon, Core and Atom), Intel Integrated GPUs (HD Graphics and Iris), VPUs (Movidius Neural Compute Stick 2), Intel FPGAs (Vision Accelerator and Programmable Acceleration Card) etc., with just a few lines of codes.</p><p>It efficiently uses these Intel hardware devices for model inference and it does so by using optimized implementation (provided by Intel) of the libraries that directly communicate and execute models on hardware while hiding all the details from the user.</p><h3>Principles</h3><p>OpenVINO focuses primarily on three things:</p><ol><li><strong>Portability</strong> — it supports running of trained models across different Intel platforms such as CPUs, Integrated Graphics GPU, FPGA, NCS 2 etc.</li><li><strong>Interoperability</strong> — various models trained on different DL frameworks (such as Tensorflow, Caffe, PyTorch etc) can be converted into their intermediate representations and they can then be used by an inference engine later on. It converts different formats into a single unified representation.</li><li><strong>Model Optimization</strong> — models can be further optimized to run faster.</li></ol><p>Specifically, OpenVINO is designed to optimize the execution of Convolutional Neural Networks (CNNs), thus, it supports the deployment of Computer Vision (CV) oriented solutions anywhere from clouds/servers to edge devices, as long as they are running on Intel devices.</p><h3>Why using OpenVINO?</h3><p>In simple terms, you might want to use OpenVINO if:</p><ul><li>You want to get the <strong>best performance</strong> of your model execution on any of the Intel hardware.</li><li>You wish to run <strong>several models</strong> on various devices at the same time (e.g., one model running on CPU while another running on GPU etc).</li><li>You seek to run your model in a <strong>heterogeneous</strong> manner (e.g. a model is divided into some parts and those parts are being run across different devices).</li><li>You would like to run a model inference in an <strong>asynchronous</strong> mode (e.g. video or camera stream processing).</li></ul><p>Other advantages:</p><ul><li>It enables you to <strong>run the model on Intel Movidius Neural Compute Stick 2 (NCS 2)</strong> which is basically a USB neural-network accelerator (See figure 2). Its primary use is in Edge Computing when you do not have enough computational power in your main device and you want to use an external device for this purpose.</li><li>Your computer, laptop or standalone server is most likely equipped with Intel GPU which you might not be using. OpenVINO enables it for model inference, therefore <strong>saving (or freeing up) your CPU for some other tasks</strong>. Thus, you can use your hardware more efficiently.</li></ul><p>Figure 1 provides an overall workflow of model deployment with OpenVINO. Two most important components of OpenVINO are (i) <strong>Model Optimizer</strong> (MO) and (ii) <strong>Inference engine</strong> (IE). Both of them are described in the following subsections in detail. The primary functionality of MO is to convert and optimize existing models while IE is responsible for running the models in user-provided target devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*zQsfgL-72ZrDFj70" /><figcaption><em>Fig.1: Deployment of a DL trained model with OpenVINO. Source: </em><a href="https://docs.openvinotoolkit.org/2018_R5/_docs_MO_DG_Deep_Learning_Model_Optimizer_DevGuide.html"><em>Model Optimizer Developer Guide</em></a><em>.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vNIg1WneVfdKisNU" /><figcaption><em>Fig. 2: Intel Movidius Neural Compute Stick 2. Source:</em><a href="https://software.intel.com/content/www/us/en/develop/articles/intel-neural-compute-stick-2-and-open-source-openvino-toolkit.html"><em> Intel NCS 2</em></a><em>.</em></figcaption></figure><h3>OpenVINO Workflow</h3><p>The overall workflow of OpenVINO can be summarized in the following steps:</p><ol><li><strong>Configure</strong> the working environment for the model optimizer [<a href="https://docs.openvinotoolkit.org/latest/openvino_docs_MO_DG_prepare_model_Config_Model_Optimizer.html">link</a>]: install prerequisites of the DL frameworks (Tensorflow or PyTorch or Caffe etc) that your model was trained on.</li><li><strong>Run the model optimizer</strong> to convert and optimize the trained model into Intermediate Representation (IR) format [<a href="https://docs.openvinotoolkit.org/latest/openvino_docs_MO_DG_prepare_model_convert_model_Converting_Model.html">link</a>]: This step is hardware agnostic and until this point, we do not need to execute/run the model (offline phase). IR format consists of two files:</li></ol><p><strong><em>.bin</em></strong><em> — weights and biases (i.e. parameters) of a trained model in binary format.</em></p><p><strong><em>.xml</em></strong><em> — network architecture (i.e. topology) in XML format.</em></p><blockquote><strong>Note:</strong> OpenVINO does not work directly with Keras model (.h5), however, you can always convert Keras model into Tensorflow frozen graph first (if TF &lt; 2.0). Check out this <a href="https://stackoverflow.com/questions/45466020/how-to-export-keras-h5-to-tensorflow-pb">stackoverflow post</a> for the conversion. While for TF&gt;=2.0 versions, load the .h5 model and save it back again using <strong>saved_model API</strong>.</blockquote><p>3. Once we get the model in IR format, the <strong>Inference Engine (IE) will load and run the model</strong> inference on the target platform (online phase).</p><h3>Model Optimizer (MO)</h3><p>The necessity for <a href="https://docs.openvinotoolkit.org/latest/openvino_docs_MO_DG_Deep_Learning_Model_Optimizer_DevGuide.html">MO</a> and IE comes from the fact that there are various DL frameworks (e.g, Tensorflow, PyTorch, Caffe, MXNet etc) out there and there is a wide range of Intel provided hardware. So, directly mapping a model trained on these DL frameworks to any of these devices/hardware is not straightforward.</p><p>In fact, it is a quite complex task because of the following reasons:</p><ul><li>Representations (or, network topologies) of the models are totally different from one framework to another.</li><li>Each of these devices has different instruction sets and use different programming environments to work on. For example, implementation of the same operations of some layers is different in CPU (it uses Intel MKL or OpenBLAS) and in GPU (it uses cuDNN/CUDA).</li></ul><p>So, Intel has built a <strong>common API</strong> (which is OpenVINO) through which we are able to run a model across these devices without knowing the hardware details and the underlying libraries/plugins being used to access them.</p><p>As mentioned before, MO is used in the first offline phase and it is hardware agnostic. MO primarily performs the following three tasks:</p><ol><li><strong>Conversion</strong> of a DL model (either .pb, .onnx or .caffemodel etc) to Intermediate Representation (IR) format, which includes .xml file (which contains the model’s network topology) and .bin file (which contains the weights and biases, i.e., parameters of the model).</li><li><strong>Optimization</strong> of the model (e.g., <a href="https://docs.openvinotoolkit.org/latest/openvino_docs_MO_DG_prepare_model_Model_Optimization_Techniques.html">fusion of the layers</a>, it helps to save computation and memory usage). <a href="https://nenadmarkus.com/p/fusing-batchnorm-and-conv/">For example</a>, a batch-normalization layer can be easily fused with the previous convolutional/fully-connected layer to become a single layer. It will then execute both of these operations in a single pass, hence, saving computational cost and storage of intermediate results. This optimization is turned on by default.</li><li><strong>Quantization</strong> of model parameters to various precision formats (FP32, FP16 and INT8). For example, CPU works better with FP32 while GPU works fast in FP16 whereas NCS 2 does not operate in FP32. It always depends on the kind of device which you would like to perform inference on. Therefore, it is important to check the requirements of the device before the conversion of the weights. Keep in mind that not all the layers are supported by every device. Please refer to <a href="https://docs.openvinotoolkit.org/latest/openvino_docs_IE_DG_supported_plugins_Supported_Devices.html">this link</a> for more details, e.g. Activations Selu or Softplus are not supported by NCS 2. Table 1 provides details for the supported precisions, e.g. NCS 2 (VPU plugins) works only on FP 16 precision.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vv9a2rxBRT_-zRcC6E2Vvw.png" /><figcaption><em>Table 1: Model formats across various devices. Source: </em><a href="https://docs.openvinotoolkit.org/latest/openvino_docs_IE_DG_supported_plugins_Supported_Devices.html"><em>Supported devices</em></a><em>.</em></figcaption></figure><h3>Inference Engine (IE)</h3><p>The <a href="https://docs.openvinotoolkit.org/latest/openvino_docs_IE_DG_Deep_Learning_Inference_Engine_DevGuide.html">Inference Engine (IE)</a> is a set of C++ libraries providing a common and unified API which lets the user perform inference on the device of their desired choice, e.g., CPU, GPU, FPGA, VPU etc. It provides an API to read the IR files (.bin and .xml) generated by the MO, to set the inputs and outputs and to execute the model on devices. In addition to its primary C++ implementation, there are also Python bindings available.</p><p>Intel provides a wide range of computing devices and in order to work and operate with these devices, ideally, we need to learn/study the required libraries beforehand. This can be quite a complex and overwhelming task since there exist many of those libraries and all of them are quite different in nature. For example, in order to work and operate on a GPU, one should know OpenCL or CUDA and likewise for other devices. Thanks to OpenVINO, this complexity is taken away from us. IE abstracts out all of these hardware and software details for us since it is built on the top of all of these libraries and for end-users, it provides a common API which is quite easy to work with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*fKnr62OboVFoTvhb" /><figcaption><em>Fig. 3: Inference Engine Architecture. Source: </em><a href="https://www.mouser.in/datasheet/2/598/OpenVINO_Development_Guide_2019R1-1663633.pdf"><em>OpenVINO development guide</em></a><em>.</em></figcaption></figure><p>As can be seen from figure 3 that IE is based on a plugin architecture. So, IE chooses the right plugins for the supported devices. Each plugin then uses the required corresponding optimized libraries under the hood in order to communicate and perform computations on those devices. For example CPU plugin uses Intel MKL-DNN library (Intel Math Kernel Library), GPU plugin uses clDNN library (Intel Compute Library OpenCL), VPU plugin uses MYRIAD APIs (specifically for NCS 2) etc.</p><p>In the end, all the user needs to do is to simply select the targeted device as a backend where the model inference should be performed and the rest will be taken care by IE. IE will choose the correct plugin and will execute the model on it.</p><blockquote><strong>Note</strong> that there are two more topics worth mentioning related to the inference: heterogeneous plugin and asynchronous execution.</blockquote><h4>Heterogeneous plugin</h4><p><a href="https://docs.openvinotoolkit.org/latest/openvino_docs_IE_DG_supported_plugins_HETERO.html">Heterogeneous plugin</a> is a part of the IE (See figure 4) and sits on the top of all the plugins and enables us to utilize all the available hardware at the same time for a single inference. It allows us to break down a network into different parts and assign them specific hardware to execute them. For example, a specific computationally expensive layer (let’s say CONV layer) can be assigned to be executed in GPU (or, NCS 2 or any kind of accelerator) and other layers (let’s say non-linear ones or those which are not supported by GPU/NCS2) can be executed in CPU as a fallback option. Another example can be simply to use all the available devices for a single inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*AQgqyooRMpDm9i3s" /><figcaption><em>Fig.4: Inference using a heterogeneous plugin. Source: </em><a href="https://mc.ai/introduction-to-openvino-toolkit-for-deploying-ai-models-on-the-edge-part-1/"><em>Introduction to OpenVINO</em></a><em>.</em></figcaption></figure><p>There are two independent ways of executing inference in heterogeneous mode:</p><ul><li>Setting affinities to layers, i.e., assigning which layer should be executed in which device, e.g., <em>network.getLayerByName(“CONV”)-&gt;affinity=“GPU”</em></li><li>Setting the whole network on various devices according to a priority, e.g., <em>dispatcher.getPluginByDevice(“HETERO: FPGA, GPU, CPU”)</em>. It means a layer is going to be executed first in FPGA and if its implementation for that layer (let’s say RELU6) is not supported in that device, then, it automatically goes to look for GPU and so on.</li></ul><h4>Asynchronous execution</h4><p>With the Async API (i.e., asynchronous mode of execution), you can easily perform two tasks at the same time instead of waiting for another job/task to be finished in a sequential manner (i.e, synchronous execution). It is especially useful in video processing, e.g., instead of waiting for inference on the current frame to be completed, let’s say on GPU or NCS 2, one can continue to do other things, e.g., preparing the next frame (either preprocessing or decoding) on CPU. Thus, it provides parallel processing capabilities in the application. Here is a <a href="https://docs.openvinotoolkit.org/latest/openvino_inference_engine_ie_bridges_python_sample_classification_sample_async_README.html">link</a> to a Python example.</p><p>It is important to note that Async mode should not be run on the same device because the device is already busy with a current job and assigning another job to it is not good for the parallel performance.</p><h3>OpenVINO with OpenCV</h3><p>OpenCV does not need any introduction as it is the most important library for computer vision. Recently, it marked its 20th anniversary (it was created in June 2000). OpenCV provides several <a href="https://docs.opencv.org/master/">very useful modules</a> for working in the computer vision domain and one of them is called the Deep Neural Network (DNN) module.</p><p>DNN module implements forward pass (i.e., model inference) of deep networks and thus, it can enable us to run prediction with just OpenCV. It supports various popular deep learning frameworks including Tensorflow, PyTorch and Caffe. Thus, it can load and run models in their native formats (.pb, .onnx or .caffemodel) and also, in intermediate representations (IR) formats (produced by the model optimizer).</p><p>There are lots of advantages of performing inference in OpenCV only:</p><ul><li>No need to install any heavy DL training framework in the system for production use.</li><li>DNN module code is quite <strong>simple, clean and compact</strong>.</li><li>Functionalities provided are <strong>highly optimized</strong> (AVX and NEON instruction sets accelerated).</li><li>It is widely supported across various devices including resource-constrained mobile (e.g., Android) and edge devices (e.g., Raspberry Pi).</li><li>Empirically, it has been found by <a href="https://www.learnopencv.com/cpu-performance-comparison-of-opencv-and-other-deep-learning-frameworks/">Satya Mallick’s study</a> that <strong>inference using OpenCV’s DNN module is faster than any of the other DL frameworks</strong>. He compared the CPU’s performance on all of them.</li></ul><p>In addition, OpenCV provides a possibility of executing trained models in devices like CPU (default), NVIDIA GPU or Intel GPU. However, for using NVIDIA GPU or Intel GPU as a target backend, one needs to compile and build OpenCV from scratch with CUDA and OpenCL options enabled, respectively.</p><p>So, instead of building OpenCV with OpenCL, OpenVINO eases this process because, by default, its installation comes along with OpenCL. It also further enhances OpenCV’s capabilities by making it run on Intel Movidius NCS 2.</p><blockquote><strong>Note</strong>: for using OpenCV’s DNN module exclusively on NVIDIA GPUs, follow <a href="https://www.pyimagesearch.com/2020/02/03/how-to-use-opencvs-dnn-module-with-nvidia-gpus-cuda-and-cudnn/">this installation guide</a> for compiling and building OpenCV with CUDA.</blockquote><p>Some of the useful OpenCV’s DNN functions/methods which we are going to use in this article are given below. For full more details, <a href="https://docs.opencv.org/master/df/d57/namespacecv_1_1dnn.html">please refer to this link</a>.</p><ul><li><em>blobFromImage()</em> — prepare/preprocessing an input image (e.g., image resizing, mean subtraction, scaling, crop image from center and swapping R &amp; B channels).</li><li><em>blobFromImages()</em> — same as blobFromImage() but on a batch of images.</li><li><em>forward()</em> — runs forward/inference pass to compute output on the input blob. The output format/array will depend on the kind of task.</li><li><em>setInput()</em> — set the input blob to the network for inference.</li><li><em>setPreferableBackend()</em> — set a specific computation backend to use. If using OpenVINO or OpenCV compiled with the inference engine, then, the default backend is <em>DNN_BACKEND_INFERENCE_ENGINE</em> otherwise it is <em>DNN_BACKEND_OPENCV</em>.</li><li><em>setPreferableTarget() </em>— performs computations on specific target devices, e.g., <em>DNN_TARGET_CPU</em>, <em>DNN_TARGET_OPENCL</em> (for Intel GPU FP32), <em>DNN_TARGET_OPENCL_FP16</em> (for Intel GPU FP16, preferred), <em>DNN_TARGET_MYRIAD</em> (for NCS 2), <em>DNN_TARGET_FPGA</em>, <em>DNN_TARGET_CUDA</em> (for NVIDIA GPU FP 32) and <em>DNN_TARGET_CUDA_FP16</em> (for NVIDIA GPU FP16, preferred).</li><li><em>readNet()</em> — read a model in any of the supported formats.</li><li><em>readNetFromModelOptimizer()</em> — reads a model stored in IR format (.bin and .xml).</li><li><em>readNetFromTensorflow()</em> — reads a model stored in TF format (.pb and .pbtxt). Similarly, <em>readNetFromCaffe()</em>, <em>readNetFromDarkNet()</em>, <em>readNetFromTorch()</em> and <em>readNetFromONNX()</em>.</li></ul><h3>Installation</h3><p>For this article, sample codes have been developed and tested in macOS Mojave (10.14.6), Raspberry Pi 4, NCS 2 and with Python (3.6) bindings of OpenVINO. OpenVINO 2020.1.023 (which has OpenCV 4.2.0) version is used, although a newer version (2021.1) exists now.</p><p>Please set up a Python virtual environment where all the required packages will be installed. For OpenVINO installations, refer to the following documentation for the guidelines. Here are the links:</p><ul><li>Installation on macOS: <a href="https://docs.openvinotoolkit.org/latest/openvino_docs_install_guides_installing_openvino_macos.html">https://docs.openvinotoolkit.org/latest/openvino_docs_install_guides_installing_openvino_macos.html</a></li><li>Installation on Raspberry Pi: <a href="https://docs.openvinotoolkit.org/latest/openvino_docs_install_guides_installing_openvino_raspbian.html">https://docs.openvinotoolkit.org/latest/openvino_docs_install_guides_installing_openvino_raspbian.html</a></li></ul><p>Regarding the NCS 2 installation, also refer to the links given above. There are separate sub-sections describing its installation on both macOS and Raspberry Pi. Installation of OpenVINO will include following packages: (i) Model Optimizer; (ii) Inference Engine; (iii) Optimized OpenCV; (iv) OpenCL; (v) Demo / sample codes; (vi) Intel Media SDK (optional, alternatively one can use FFmpeg library) and (vii) Documentations.</p><blockquote><strong>Notes</strong>: Unfortunately, OpenVINO for macOS <a href="https://docs.openvinotoolkit.org/latest/openvino_docs_install_guides_installing_openvino_macos.html">does not support inference on Intel GPU!</a> It only supports inference on Intel CPUs and Intel NCS 2. And,</blockquote><blockquote>Please make sure to <strong>run a sample application</strong> provided in the installation guide in order to verify if the installation is done correctly.</blockquote><h3>Example</h3><ul><li>OpenVINO provides two kinds of model repositories: (i) <a href="https://docs.openvinotoolkit.org/latest/omz_models_intel_index.html">Intel pre-trained models</a> and (ii) <a href="https://docs.openvinotoolkit.org/latest/omz_models_public_index.html">publicly pre-trained models</a>. Models which are included in an Intel-based repository are already converted into IR formats and they have also been quantized (mostly) into FP32, FP16 and INT8 while the publicly pre-trained repository contains models in their native formats (Tensorflow, Caffe etc).</li><li>It is important to first look into the documentation of a model before downloading, especially for the publicly trained models. For example, all the preprocessing details will be required (i.e., input image size, RGB/BGR order, mean value to subtract, scale to divide etc) for the preparation of an input image. For the Intel-based models which are already in their IR formats, these preprocessing operations are appended at the beginning of the network layer which you can check by opening their XML file.</li><li>Activate your virtual environment and initialize all the environmental variables required by running this command:</li></ul><blockquote>source /opt /intel/openvino/bin/setupvars.sh</blockquote><blockquote><em>It should output this message</em>: [setupvars.sh] OpenVINO environment initialized</blockquote><ul><li>Optionally, you can put the source command in the <em>bash_profile</em> so that you do not need to run it every time.</li><li>To see all the models (Intel and publicly available ones) which can be downloaded, run the downloader script as:</li></ul><blockquote>$ cd /opt/intel/openvino/deployment_tools/tools/model_downloader</blockquote><blockquote>$ python3 downloader.py — print_all</blockquote><ul><li>Now, let’s download a face detection pre-trained model (“<a href="https://docs.openvinotoolkit.org/latest/omz_models_intel_face_detection_retail_0004_description_face_detection_retail_0004.html"><em>face-detection-retail-0004</em></a>”) which is already converted into IR format and with a precision of FP16 so that we can run this model either in Intel GPU or NCS 2. If you want to infer it on the CPU, then, it’s better to download it in FP32. Although FP16 also works in CPU, the inference engine will most likely need to typecast the values of the weights from FP16 to FP32 all the time.</li></ul><blockquote>$ python3 downloader.py — name face-detection-retail-0004 — precisions FP16 — output_dir PROVIDE_DIR_WHERE_TO_DOWNLOAD</blockquote><ul><li>Below is the relevant code snippet to run face detection model on NCS 2 with a webcam. It has been also tested in Raspberry pi 4:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7825d8b1e5d8c50fce4dfe11c9c09ab/href">https://medium.com/media/a7825d8b1e5d8c50fce4dfe11c9c09ab/href</a></iframe><p>There are also other examples (classification, detection and segmentation) included in the Github repository. Following is the list of codes with a short description:</p><ol><li><a href="https://github.com/sclable/openvino_opencv/blob/main/01_model_downloader.ipynb">Model downloader</a> — to download models from OpenVINO model zoo.</li><li><a href="https://github.com/sclable/openvino_opencv/blob/main/02_model_conversion.ipynb">Model conversion</a> — to convert the model from their native format to IR format.</li><li><a href="https://github.com/sclable/openvino_opencv/blob/main/03_image_classification_mobilenetv2.ipynb">Image classification</a> using MobileNetV2 model.</li><li><a href="https://github.com/sclable/openvino_opencv/blob/main/04_image_classification_inception_resnet_v2.ipynb">Image classification</a> using Inception ResNet V2 model.</li><li><a href="https://github.com/sclable/openvino_opencv/blob/main/05_face_detection_webcam_NCS2.ipynb">Face detection</a> using a webcam and model inference performed on NCS 2.</li><li><a href="https://github.com/sclable/openvino_opencv/blob/main/06_object_detection_mobilenetv2_ssd.ipynb">General object detection</a> using MobileNetV2 and SSD based model.</li><li><a href="https://github.com/sclable/openvino_opencv/blob/main/07_road_segmentation.ipynb">Road segmentation</a> using semantic segmentation model.</li><li><a href="https://github.com/sclable/openvino_opencv/blob/main/08_pavement_crack_segmentation.ipynb">Custom pavement cracks segmentation</a> model based on the UNet model.</li></ol><h3>Conclusion</h3><p>Deep learning-based models can be easily trained on NVIDIA GPUs since there is a vast availability of popular frameworks which supports them. However, executing them in the most performant way and moreover, in resource-constrained devices is not that straightforward. Since Intel owns and provides vast majorities of various computing devices, there was an obvious need to provide something which covers all of their devices for the inference purpose. Thus, they created OpenVINO which provides a common and unified API to be able to access all of them at a very high level.</p><p>In this article, we have gone through OpenVINO and also, we have covered the model optimizer and inference engine which are the two most important components of it. One of the most convenient parts of OpenVINO is that it comes with OpenCV which is already compiled and built to support Intel GPU and Intel NCS 2. We have seen that in OpenCV it takes only one line of code to select a preferred target device to run the model inference on.</p><p><a href="https://github.com/sclable/openvino_opencv">Github link</a> for various use-cases is provided above, feel free to play around with it.</p><p>This article was written for <a href="https://medium.com/sclable">Sclable’s blog on Medium</a>.<br>If you liked it, give it a clap and share if you ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5ad03363a38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sclable/intel-openvino-with-opencv-f5ad03363a38">Intel OpenVINO with OpenCV</a> was originally published in <a href="https://medium.com/sclable">sclable</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Quantization Using Tensorflow Lite]]></title>
            <link>https://medium.com/sclable/model-quantization-using-tensorflow-lite-2fe6a171a90d?source=rss-2e218d3ebd79------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fe6a171a90d</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[tensorflow-lite]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[edge-computing]]></category>
            <dc:creator><![CDATA[AI Practitioner and Writer]]></dc:creator>
            <pubDate>Mon, 11 May 2020 15:40:41 GMT</pubDate>
            <atom:updated>2020-10-12T16:07:30.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjsEPItNww_khr8o2me-xg.png" /><figcaption>Image courtesy: <a href="https://www.tensorflow.org/lite">https://www.tensorflow.org/lite</a></figcaption></figure><h3>Model Quantization Using TensorFlow Lite</h3><h4>Deployment of deep learning models on mobile devices.</h4><p>Battery and memory are the two most important resources for mobile, edge or IoT devices. They are available in a limited amount compared to the clouds or in-house servers. Directly deploying any deep learning (DL) based trained model will not work as they are resource hungry. Therefore, any DL model-based inference on those devices needs to take into account the following characteristics of the model:(i) they need to be smaller in size to save memory; (ii) they need to consume as little energy to save battery life and (iii) they need to have low latency or, in other words, high inference time so that a user feels that the model is reacting instantaneously. In short, it is crucial to make the model efficient for memory, energy and processor usage for their deployment in mobile and edge devices. In this article, we will go through <a href="https://www.tensorflow.org/lite">TensorFlow Lite</a> (open source DL framework for on-device inference) and discuss one of the main methods of optimization called quantization. Quantization helps to reduce the model size and also makes models compatible to run on devices. We will see in detail one of the ways of doing quantization when the model is trained, called post-training quantization.</p><h4><strong>What is TensorFlow lite (TFLite)?</strong></h4><p>To meet all the criteria of the models mentioned above, Google provides an on-device inference engine called <a href="https://www.tensorflow.org/lite/guide">TensorFlow-lite (TFLite)</a>. TFLite is targeted especially to mobile, edge or IoT devices, optimizing for speed, model size and power consumption. It also has support for GPU-based model inference via GPU delegates. These delegates can communicate with the native libraries for GPU acceleration via their APIs. For example, for Android devices, the GPU delegate uses Android Neural Network API and for iOS devices, it uses Metal API for hardware-accelerated inference operations. Fig1. shows the internal architecture of the TFLite. TFLite consists of two main components:</p><ul><li><strong>Interpreter</strong>: TFLite comes with a very light interpreter (with a size of less than 300 KB) which runs the optimized models on various devices. To run the model on various devices such as Android or iOS, TFLite interpreter comes with multi-language APIs: on Android, TFLite inference can be performed using either JAVA or C++ APIs; on iOS, there are APIs written in Swift and Objective-C and on Linux platforms (including Raspberry Pi), TFLite APIs are available in C++ and Python.</li><li><strong>Converter</strong>: converts the TensorFlow or Keras model (.pb or .h5) into TFLite model (.tflite) which can be directly deployed in those devices. This file can then be used by the interpreter for inference purposes. The converted model is stored in an efficient file format which uses <a href="https://google.github.io/flatbuffers/"><strong>FlatBuffers</strong></a>. In addition to creating FlatBuffer, TFLite converter can also apply optimizations to the model which reduce the size of the model, inference time or both. However, this optimization can come with the cost of a reduction in accuracy. The kind of optimization used is called quantization, which is the topic of discussion of this article and we will explain it in detail.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XYp_M6VzgMLPINiW" /><figcaption>Fig1. TensorFlow Lite internal architecture. Image courtesy: <a href="https://www.tensorflow.org/lite/convert">https://www.tensorflow.org/lite/convert</a></figcaption></figure><h4><strong>What is model quantization and why do we need it?</strong></h4><p>One of the most useful optimizations that TFLite uses is called quantization. Quantization is using lower-bit representations than higher bits for a given real-valued number. For example, you can represent a continuous real number such as a 32-bit (or, 4 bytes) floating-point number with a discrete number such as an 8-bit (or, 1 byte) integer number. In deep learning, weights and biases (or, simply parameters of your neural network) are stored as 32-bit floating-point numbers so that high precision calculation can happen during model training. And, when the model is trained, they can be reduced to 8-bit integers which eventually means a reduction of the model size. They can either be reduced to 16-bit floating points (2x reduction in size) or 8-bit integers (4x reduction in size). Of course, this might come with the tradeoff in the accuracy of the model’s predictions. However, it has been <a href="https://www.tensorflow.org/lite/performance/best_practices">empirically shown</a> in many situations that a quantized model does not suffer from a significant decay, or no decay at all, especially when using <a href="https://blog.tensorflow.org/2019/08/tensorflow-model-optimization-toolkit_5.html">16-bits floating points</a>, which reduces the model’s size by half (See Fig 4). Similarly, we can also quantize the activation values, however, it requires a calibration step to determine some scaling parameters from a representative dataset. This is explained in detail in the “Full quantization” sub-section. Figures 2, 3 and 4 show some examples regarding the effect of full quantization (weights and activations values to 8-bit INT) on model size, latency time and accuracy, respectively. <a href="https://blog.tensorflow.org/2018/09/introducing-model-optimization-toolkit.html">They have used Google Android Pixel 2 for the experiments</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*QwfridZH0D4-Scov" /><figcaption>Fig2. Model size comparison. Image courtesy: <a href="https://blog.tensorflow.org/2018/09/introducing-model-optimization-toolkit.html">https://blog.tensorflow.org/2018/09/introducing-model-optimization-toolkit.html</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/0*-ZRYbIXGaacPiEs2" /><figcaption>Fig3. Latency time comparison. Image courtesy: <a href="https://blog.tensorflow.org/2018/09/introducing-model-optimization-toolkit.html">https://blog.tensorflow.org/2018/09/introducing-model-optimization-toolkit.html</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/0*x-aiJ_jFNmcMFmW-" /><figcaption>Fig4. Accuracy comparison. Image courtesy: <a href="https://blog.tensorflow.org/2018/09/introducing-model-optimization-toolkit.html">https://blog.tensorflow.org/2018/09/introducing-model-optimization-toolkit.html</a></figcaption></figure><h4><strong>What are the quantization possibilities?</strong></h4><p>There are two options that TFLite provides for a model quantization:</p><p>(i) <strong>post-training quantization</strong>: simply entails the quantization of the parameters after the model is trained. This is the main focus of this article and we will present it in more detail. And,</p><p>(ii) <strong>quantization-aware training</strong>: entails quantizing the model during the training time. It requires modification to the network before initial training (uses fake quantization nodes) and it learns the 8-bit weights through training rather than conversion later. It is only available at the moment for a subset of CNN architectures. This is not the focus of this article.</p><h4><strong>Post-training quantization</strong></h4><p>Post-training quantization does not require any modifications to the network, so you can convert a previously-trained network into a quantized model, for example, 32-bit FP to 16-bit FP or 8-bits INT. This post-training quantization can be further divided into three parts depending on (i) if no quantization is performed, which simply means a conversion of TensorFlow model to a “.tflite” file format; (ii) if only weights of the model are quantized. It is also called hybrid quantization and (iii) if, along with weights, activations are also quantized. It is called full quantization. It is quite important for all the methods mentioned below in order to check the accuracy of the quantized model and ensure that the degradation is acceptable.</p><p>Depending upon different hardware that has been chosen for inference purposes on mobile or edge devices, there are different kinds of quantization that you might want to apply, such as:</p><ul><li>for running a model in a CPU (e.g., ARM processors), 8-bit INT or no quantization (32-bit FP) can work. Models which are converted to 16-bit FP can still be run on the CPU, however, float 16 weights are upsampled to float 32 before the inference.</li><li>for a GPU (e.g., ARM Mali, Qualcomm Adreno etc), a reduced 16-bit is a good choice because GPUs can compute with both 16-bit or 32-bit FP which means quantization is not at all a requirement. TFLite GPU delegates need to be configured to execute float 16 data.</li><li>for inference on an edge TPU (e.g., Google Coral), full integer (8-bit INT) of both weights and activations is a requirement. Note that it is not same as <a href="https://coral.ai/docs/edgetpu/faq/">Cloud TPUs</a> which are used for model training.</li></ul><p>The following figure shows a list of possibilities to consider when dealing with post-training quantization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qvBEc50iknpv3z9G" /><figcaption>Fig5. Deciding which post-training quantization strategy to choose. Image courtesy: <a href="https://www.tensorflow.org/lite/performance/post_training_quantization">https://www.tensorflow.org/lite/performance/post_training_quantization</a></figcaption></figure><p>(i) <strong>No quantization</strong>: Here the trained model is not at all quantized, the TensorFlow model (.pb or .h5) is simply converted into TFLite (.tflite) file. Conversion to TFLite is important because only after that it enables you to deploy your model into a device so that the interpreter can run it. For example, quantization might not be necessary if you are using a very light-weight version of a custom network or using pre-trained MobileNet which is relatively small. Remember quantization may come with the cost of reducing the accuracy of your model. Then, in case of no degradation, it is fine to simply convert your model to TFLite model which can be then imported and interpreted by the TFLite interpreter running on the device itself. Note that your TFLite model’s size will be a little bit smaller than your original TensorFlow model. This is due to the usage of FlatBuffers for creating TFLite models. Check the difference between <a href="https://codeburst.io/json-vs-protocol-buffers-vs-flatbuffers-a4247f8bda6f">protocol buffer and FlatBuffers here.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QZz7W3yLJaKec-S3" /><figcaption>Fig6. Conversion of TF.Keras model to TFLite model without quantization</figcaption></figure><p>(ii) <strong>Weights/hybrid quantization</strong>: Here only the weights of the trained model are quantized, either to 16-bit FP or 8-bit INT. This will reduce your model size 2x or 4x, respectively. In case of 16-bit FP quantized weights, they will be converted back (or, dequantized) into 32-bit FP when running in a CPU since <a href="https://ieeexplore.ieee.org/document/8645923">current generation CPUs do not support native 16-bit FP arithmetics</a>. However, 16-bit FP can be a good choice when using a GPU since it can operate on float 16 data. In the case of 8-bit INT quantized weights, some operators (called hybrid operators) which are also able to work with integer data will dynamically quantize activation values to 8-bit INT and perform computations with 8-bit weights and activations. This provides latencies close to fully fixed point inference (e.g., full integer quantization). However, the outputs are de-quantized (or, converted back) to float precision. This can provide a speedup over pure floating-point computation, but the memory footprint will remain the same. <a href="https://www.tensorflow.org/lite/performance/post_training_quantization">Hybrid operators</a> are available for the most compute-intensive part in a network, e.g, fully_connected, conv2d etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J9aSkkDy11jRWvEQ" /><figcaption>Fig7: Conversions of weights to 8-bit INT.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SF3T56P96OqUEtWX" /><figcaption>Fig8: conversions of weights to 16-bit FP.</figcaption></figure><p>(iii) <strong>Full quantization</strong>: Here we fully quantize the trained model, i.e., quantization of both weight and activation values is performed. Quantization of weights is quite straightforward, as mentioned above, however, quantization of activation values is not so straightforward. What does quantizing activation values mean? The output of an activation function is mapped to, for example [+127, -128] signed INT values. This will be the quantization of the activation values using (signed) 8-bit INT. Now, this conversion or mapping of activations from a floating-point (32-bits FP) to integer requires a calibration step to determine the scaling parameters. These parameters are computed by running several examples of your representative dataset (e.g., testing or validation dataset) through the model. TFLite computes and stores the MIN and MAX values of the activations from the representative dataset. With MIN and MAX values, TFLite maps any floating-point number to [+127, -128]. The activations are then quantized on the fly at inference time.</p><p>It is important to note that many mobiles or embedded devices <a href="https://stackoverflow.com/questions/5103957/why-does-using-float-instead-of-double-not-improve-android-performance">do not support floating-point operations</a>, since most of the time either they lack <a href="https://en.wikipedia.org/wiki/Floating-point_unit">Floating-Point Units (FPUs)</a> or they are disabled to save power. Therefore, a full-integer quantization (i.e., both weights and activations are converted into 8-bit INT) is usually a requirement. These integers not only require less memory but also arithmetic with integers can run very quickly, hence, they provide low latency time. For example, <a href="https://coral.ai/docs/edgetpu/models-intro/">Google’s Coral Edge TPU</a> supports only TFLite models that are fully 8-bit quantized, therefore, any floating-point operations are not supported and those models will not be compatible. Note that not all operators are supported by Edge TPU from <a href="https://www.tensorflow.org/lite/guide/ops_compatibility">TFLite’s list of compatible operators</a> — a list of supported operators can be found <a href="https://coral.ai/docs/edgetpu/models-intro/#supported-operations">here</a>.</p><p>On the other hand, for those cases where integer-based arithmetic is not supported, the 8-bit quantized model will fall back into 32-bit floating-point, if possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bwcwnpHUE04niuDh" /><figcaption>Fig9: Representative data generator</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-oYiSIb0Z3uMG_RQ" /><figcaption>Fig10: Conversion of both weights and activations to 8-bit INT.</figcaption></figure><h4><strong>What mobile-friendly deep learning models are available?</strong></h4><p>The following are some (out of the box) pre-trained-models which are fully supported (i.e., full-integer quantization) by TFLite. For image classification: MobileNet, MobileNetv2, ResNet-50 and Inception-V3; for object detection: MobileNet V1 or V2 with SSD and for semantic segmentation: DeepLAB V1.</p><h4><strong>Conclusion</strong></h4><p>We have gone through TensorFlow Lite (TFLite) and one of the most important techniques of model optimization called model quantization. We have seen the “post-training quantization” technique in detail.</p><p>It is always important to keep the following things in mind before performing any kind of quantization: (i) the target device specification (which kind of mobile device and where do you want to run inference), (ii) which kind of arithmetic is being supported (FP32 or FP16 or INT8) by the hardware (CPU or GPU or TPU) and (iii) lastly, which kind of operations are supported by TensorFlow Lite.</p><p>Github link for the code is provided below, feel free to play around with it.</p><p>This article was written for <a href="https://medium.com/sclable">Sclable’s blog on Medium</a>.<br>If you liked it, give it a clap and share if you ❤️</p><p><strong>Github link with an example</strong>: <a href="https://github.com/sanchit88/tf_model_quant">https://github.com/sanchit88/tf_model_quant</a></p><h4><strong>References</strong></h4><ul><li>Google Coral Edge TPU: <a href="https://coral.ai/docs/edgetpu/models-intro/">https://coral.ai/docs/edgetpu/models-intro/</a></li><li>TensorFlow Lite homepage: <a href="https://www.tensorflow.org/lite/guide">https://www.tensorflow.org/lite/guide</a></li><li>TFLite post-training quantization: <a href="https://www.tensorflow.org/lite/performance/post_training_quantization">https://www.tensorflow.org/lite/performance/post_training_quantization</a></li><li>TFLite post-training weights quantization: <a href="https://www.tensorflow.org/lite/performance/post_training_quant">https://www.tensorflow.org/lite/performance/post_training_quant</a></li><li>TFLite post-training float16 quantization: <a href="https://www.tensorflow.org/lite/performance/post_training_float16_quant">https://www.tensorflow.org/lite/performance/post_training_float16_quant</a></li><li>TFLite GPU delegates: <a href="https://www.tensorflow.org/lite/performance/gpu">https://www.tensorflow.org/lite/performance/gpu</a></li><li>TFLite official blog post: <a href="https://blog.tensorflow.org/2018/09/introducing-model-optimization-toolkit.html">https://blog.tensorflow.org/2018/09/introducing-model-optimization-toolkit.html</a></li><li>AI mobile benchmarking: <a href="http://ai-benchmark.com/ranking">http://ai-benchmark.com/ranking</a></li><li>TFLite blog on 16-bit FP quantization: <a href="https://blog.tensorflow.org/2019/08/tensorflow-model-optimization-toolkit_5.html">https://blog.tensorflow.org/2019/08/tensorflow-model-optimization-toolkit_5.html</a></li><li>How is the Edge TPU different from Cloud TPUs? <a href="https://coral.ai/docs/edgetpu/faq/">https://coral.ai/docs/edgetpu/faq/</a></li><li>On-Device Neural Net Inference with Mobile GPUs: <a href="https://arxiv.org/pdf/1907.01989.pdf">https://arxiv.org/pdf/1907.01989.pdf</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fe6a171a90d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sclable/model-quantization-using-tensorflow-lite-2fe6a171a90d">Model Quantization Using Tensorflow Lite</a> was originally published in <a href="https://medium.com/sclable">sclable</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>