<?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 Mohsen Mahmoodzadeh on Medium]]></title>
        <description><![CDATA[Stories by Mohsen Mahmoodzadeh on Medium]]></description>
        <link>https://medium.com/@mohsen.mahmoodzadeh?source=rss-36b048b95ef1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-9niLnGD3iuH18W0VT3Q-w.jpeg</url>
            <title>Stories by Mohsen Mahmoodzadeh on Medium</title>
            <link>https://medium.com/@mohsen.mahmoodzadeh?source=rss-36b048b95ef1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:20:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohsen.mahmoodzadeh/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[A Deep Dive into ONNX & ONNX Runtime (Part 2)]]></title>
            <link>https://becominghuman.ai/a-deep-dive-into-onnx-onnx-runtime-part-2-785b523e0cca?source=rss-36b048b95ef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/785b523e0cca</guid>
            <category><![CDATA[model-optimization]]></category>
            <category><![CDATA[computational-graphs]]></category>
            <category><![CDATA[onnx-runtime]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[onnx]]></category>
            <dc:creator><![CDATA[Mohsen Mahmoodzadeh]]></dc:creator>
            <pubDate>Thu, 27 Oct 2022 15:59:17 GMT</pubDate>
            <atom:updated>2023-08-05T06:50:35.699Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@mohsen.mahmoodzadeh/a-deep-dive-into-onnx-onnx-runtime-part-1-874517c66ffc">previous part</a>, we reviewed acceleration methods and then explained the need for ONNX as a common Intermediate Representation(IR).</p><p>In this article we will look at <strong>ONNX Runtime</strong> and how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*bRunXpiVIa1-1W4dug60-g.png" /><figcaption>Source: <a href="https://www.pngfind.com/mpng/JwTibT_onnx-runtime-logo-today-triangle-hd-png-download/">https://www.pngfind.com/mpng/JwTibT_onnx-runtime-logo-today-triangle-hd-png-download/</a></figcaption></figure><h3>ONNX Runtime</h3><p>Over time, many frameworks and runtime engines have included ONNX format support in their tools.</p><figure><img alt="ONNX supporter frameworks" src="https://cdn-images-1.medium.com/max/1024/0*XiKZDTLVe00hY1Ej" /><figcaption>Frameworks, Source: <a href="https://onnx.ai/supported-tools.html">https://onnx.ai/supported-tools.html</a></figcaption></figure><figure><img alt="ONNX supporter runtime engines" src="https://cdn-images-1.medium.com/max/1024/0*78MpNtAHM37-LFzu" /><figcaption>Runtime engines, Source: <a href="https://onnx.ai/supported-tools.html">https://onnx.ai/supported-tools.html</a></figcaption></figure><p>Among runtime engines, ONNX Runtime is one of the most well-known accelerators. This accelerator can be used for both model training and inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*P4b-qNRk243c7Mmd" /><figcaption>Source: <a href="https://techcommunity.microsoft.com/t5/ai-machine-learning-blog/onnx-runtime-training-technical-deep-dive/ba-p/1398310">https://techcommunity.microsoft.com/t5/ai-machine-learning-blog/onnx-runtime-training-technical-deep-dive/ba-p/1398310</a></figcaption></figure><p>As shown above, ONNX Runtime as a runtime engine runs the ONNX model (which can be developed in different frameworks and then converted to ONNX format) on different hardware. This possibility can be done through the APIs provided by ONNX Runtime itself (under the title of Execution Providers or EP). In other words, Execution Providers are hardware acceleration interfaces for querying the capabilities of that hardware.</p><h3>Execution Providers</h3><p>Execution Providers expose their own set of capabilities to the ONNX Runtime. These capabilities can be the nodes to be executed, its memory allocator, etc. Custom accelerators (such as GPU, VPU, etc.) are examples of Execution Providers.</p><p>In general, an ONNX model does not always run on a specific Execution Provider, but the ONNX Runtime runs the model on a heterogeneous environment that contains multiple Execution Providers. There is also a default Execution Provider on which all the nodes that were not able to run on the dedicated Execution Providers will be run.</p><p>Execution Providers can be reviewed in the following two categories:</p><h4>Kernel-based Execution Providers</h4><p>They provide the implementations of the operations defined in ONNX.</p><p>Examples:</p><ul><li>CPUExecutionProvider</li><li>CUDAExecutionProvider</li><li>MKLDNNExecutionProvider</li></ul><h4>Runtime-based Execution Providers</h4><p>These Execution Providers may not have detailed implementations of ONNX operations, but they can execute the ONNX graph in whole or in part.</p><p>Examples:</p><ul><li>nGraphExecutionProvider</li><li>TensorRTExecutionProvider</li></ul><h3>Graph Optimizations</h3><p>This group of optimizations can be considered as including all the changes that are applied to the computational graph of the model. These optimizations can be divided into <strong>three</strong> levels:</p><h4>1. Basic</h4><p>This level of optimization rewrites the graph while preserving the functional meaning and applies to all Execution Providers. This rewrite includes the following:</p><p><strong>Constant folding</strong></p><p>Statically computes parts of the graph that rely only on constant initialization. This eliminates the need to calculate them at runtime.</p><p><strong>Redundant node eliminations</strong></p><ul><li>Identity elimination</li><li>Slice elimination</li><li>Unsqueeze elimination</li><li>Dropout elimination</li></ul><p><strong>Node Fusions</strong></p><ul><li>Conv Add Fusion</li><li>Conv Mul Fusion</li><li>Conv BatchNorm Fusion</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*EYqocMUYiNY-UlYo" /><figcaption>Conv BatchNorm Fusion, Source: <a href="https://medium.com/axinc-ai/using-the-onnx-official-optimizer-27d1c7da3531">https://medium.com/axinc-ai/using-the-onnx-official-optimizer-27d1c7da3531</a></figcaption></figure><p>The BatchNormalization layer is often placed after the Convolution layer (to stabilize and improve the learning efficiency), but by reducing it to the parameters of the Convolution layer, it can be removed from the network because the values of the parameters will remain constant in the Inference phase.</p><ul><li>Relu Clip Fusion</li><li>Reshape Fusion</li></ul><h4>2. Extended</h4><p>This level of optimization includes more complex node integrations that are only applied to nodes assigned to the CPU, CUDA, and ROCm Execution Providers. Some of these optimizations include:</p><ul><li>Matmul Add Fusions</li><li>Conv Activation Fusion</li><li>BERT Embedding Layer Fusion</li></ul><h4>3. Layout Optimizations</h4><p>These optimizations change the layout of the data and are only applied to nodes assigned to the CPU Execution Provider. These optimizations include:</p><ul><li>Use NCHWc layout instead of NCHW</li></ul><p>Two important things about these optimizations are:</p><ol><li>They are <strong>all enabled by default</strong>, and each one is applied to the graph after the next level of optimizations have been performed. These optimizations can also be enabled and disabled at different levels.</li></ol><blockquote>- ORT_DISABLE_ALL</blockquote><blockquote>- ORT_ENABLE_BASIC</blockquote><blockquote>- ORT_ENABLE_EXTENDED</blockquote><blockquote>- ORT_ENABLE_ALL</blockquote><p>With the <a href="https://onnxruntime.ai/docs/api/python/api_summary.html#onnxruntime.SessionOptions.graph_optimization_level"><strong><em>graph_optimization_level</em></strong></a> parameter, you can set the optimization level in the graph.</p><p>2. <strong>Offline &amp; Online mode</strong>:</p><p>All optimizations can be applied online or offline.</p><p>In online mode, when initializing an inference session, we apply all enabled optimizations prior to inference. Doing this every time a session is initialized causes time overhead.</p><p>In offline mode, after applying graph optimizations, ONNX Runtime serializes the model and saves it to disk. Because of this, we can reduce the initial setup time by reading the optimized model from disk. By setting the <a href="https://onnxruntime.ai/docs/api/python/api_summary.html#onnxruntime.SessionOptions.optimized_model_filepath"><strong><em>optmized_model_filepath</em></strong></a> parameter, it is possible to enable serialization of the optimized model on disk.</p><h4>Graph Transformations</h4><p>The optimizations can be checked from other perspectives such as the level of application on the model. In this point of view, optimizations are generally referred to as “graph transformations”. These conversions are done at three levels:</p><ol><li>Transformations that are applied under any condition, after generating the graph.</li></ol><blockquote>Example: cast insertion, mem copy insertion</blockquote><p>2. General transformations and Execution Provider-agnostic</p><blockquote>Example: dropout elimination</blockquote><p>3. Execution Provider-specific transformations</p><blockquote>Example: transpose insertion for FPGA</blockquote><p>These transformations can also be global or local.</p><p>In global mode, transformations are applied to the entire graph. The interface that applies these transformations in ONNX Runtime is called <a href="https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/optimizer/graph_transformer.h"><strong><em>GraphTransformer</em></strong></a>.</p><p>On the other hand, and in local mode, transformations can be considered rewriting rules that are applied to subgraphs and some nodes. The <a href="https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/optimizer/rewrite_rule.h"><strong><em>RewritingRule</em></strong></a> interface in the ONNX Runtime is used to implement these transformations.</p><h3>High-level architecture</h3><figure><img alt="High-level architecture" src="https://cdn-images-1.medium.com/max/1024/0*EYRc15Mozr-DLSrN" /><figcaption>Source: <a href="https://onnxruntime.ai/docs/reference/high-level-design.html#high-level-system-architecture">https://onnxruntime.ai/docs/reference/high-level-design.html#high-level-system-architecture</a></figcaption></figure><ol><li>First, ONNX Runtime converts the model graph to its in-memory graph representation.</li></ol><p>2. A series of hardware-independent optimizations are applied.</p><p>3. Based on available Execution Providers, ONNX Runtime decomposes the graph into a set of subgraphs.</p><blockquote>ONNX Runtime uses a greedy approach to assign nodes to Execution Providers. Available Execution Providers are considered in a specified order. In this order, efforts are made to assign subgraphs to special execution providers as much as possible. The default Execution Provider is considered as the last Execution Provider and is responsible for executing the remaining subgraphs that are not assigned to other Execution Providers.</blockquote><p>4. Each subgraph is assigned to an Execution Provider.</p><figure><img alt="ONNX inference workflow" src="https://cdn-images-1.medium.com/max/770/0*5O16pqcR9gtI8L9o" /><figcaption>Source: <a href="https://static.linaro.org/connect/san19/presentations/san19-211.pdf">https://static.linaro.org/connect/san19/presentations/san19-211.pdf</a></figcaption></figure><h3>ONNX Runtime Performance Tuning</h3><p>Along with the flexibility to choose the model and execution provider, there are hyper-parameters to tune to improve performance.</p><h4>Multi-threading</h4><p>ONNX Runtime supports two <a href="https://onnxruntime.ai/docs/api/python/api_summary.html#onnxruntime.SessionOptions.execution_mode"><strong><em>execution modes</em></strong></a>: sequential and parallel. The execution mode controls whether the operators of a graph are executed sequentially or in parallel. By default, the execution mode is sequential.</p><p>The parallel execution of several operators is scheduled on an inter-op thread pool. An optimized version of the <a href="https://eigen.tuxfamily.org/index.php?title=Main_Page"><strong><em>Eigen</em></strong></a> library thread pool is used for inter-operational parallelization. With the help of <a href="https://onnxruntime.ai/docs/api/python/api_summary.html#onnxruntime.SessionOptions.inter_op_num_threads"><strong><em>inter_op_num_threads</em></strong></a> parameter in ONNX Runtime, we can set the number of threads in this mode. This parameter is used when we are in parallel execution mode.</p><p>The execution of an operator is also parallelized using an intra-op thread pool. And OpenMP is used for intra-operational parallelization. With the help of the <a href="https://onnxruntime.ai/docs/api/python/api_summary.html#onnxruntime.SessionOptions.intra_op_num_threads"><strong><em>intra_op_num_threads</em></strong></a> parameter in ONNX Runtime, we can set the number of threads in this mode. This parameter is used when we are in sequential execution mode.</p><h4>Memory management</h4><p>By default, memory arenas do not return unused memory to the operating system. By setting some parameters, it will be possible for users to free the memory with a certain period of time. Currently, the only time period supported is at the end of each run.</p><blockquote>Region-based memory arena is a type of memory management in which each allocated object is assigned to a region. A region (zone, or arena, or area) or memory context is a collection of allocated objects that can be reallocated or freed. In simpler terms, an arena is a continuous and large piece of memory that is allocated once and then its different parts can be managed manually. The important thing about the arena is the complete control over how memory is allocated. The only thing out of control is the call to the initialization library.</blockquote><p>Most of the time, we have a dynamic shape model that sometimes may process a request which requires a lot of memory. Since arena doesn’t release memory by default, this memory from arena growth will remain forever as part of servicing this request, so most subsequent requests will probably not need that memory, and this means a lot of memory allocated just for some exceptions remain.</p><p>There are two types of strategies to extend or shrink memory according to incoming requests:</p><ol><li><strong>kNextPowerOfTwo</strong>: Subsequent extensions/shrinkages with larger/smaller values (multiply by/divide by 2)</li><li><strong>kSameAsRequested</strong>: Expand/Shrink as needed</li></ol><h4>Profiling and Logging</h4><p>ONNX Runtime provides information related to model profiling (multi-threading, latency of operators, etc.) as a JSON file to the developer. This file can be generated in one of the following two ways:</p><ol><li><a href="https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/test/perftest/ReadMe.txt">Onnxruntime_perf_test.exe</a></li><li>Set parameter <a href="https://onnxruntime.ai/docs/api/python/api_summary.html#onnxruntime.SessionOptions.enable_profiling"><strong><em>enable_profiling</em></strong></a> to True</li></ol><p>For logging, the <a href="https://onnxruntime.ai/docs/api/python/api_summary.html#onnxruntime.SessionOptions.log_severity_level"><strong><em>log_severity_level</em></strong></a> parameter is used to set the log level. To see all the logs, the value of this parameter should be set to 0 (verbose).</p><h3>References</h3><ol><li><a href="https://onnxruntime.ai/">https://onnxruntime.ai</a></li><li><a href="https://github.com/onnx/onnx">https://github.com/onnx/onnx</a></li><li><a href="https://github.com/microsoft/onnxruntime">https://github.com/microsoft/onnxruntime</a></li><li><a href="https://deci.ai/blog/graph-compilers/">https://deci.ai/blog/graph-compilers/</a></li><li><a href="https://deci.ai/the-deep-learning-inference-acceleration-blog-series-part-1-introduction/">https://deci.ai/the-deep-learning-inference-acceleration-blog-series-part-1-introduction/</a></li><li><a href="https://pub.towardsai.net/onnx-for-model-interoperability-faster-inference-8709375db9bf">https://pub.towardsai.net/onnx-for-model-interoperability-faster-inference-8709375db9bf</a></li><li><a href="https://towardsdatascience.com/stateful-model-serving-how-we-accelerate-inference-using-onnx-runtime-a2875a77478d">https://towardsdatascience.com/stateful-model-serving-how-we-accelerate-inference-using-onnx-runtime-a2875a77478d</a></li><li><a href="https://medium.com/axinc-ai/using-the-onnx-official-optimizer-27d1c7da3531">https://medium.com/axinc-ai/using-the-onnx-official-optimizer-27d1c7da3531</a></li><li><a href="https://stackoverflow.com/questions/12825148/what-is-the-meaning-of-the-term-arena-in-relation-to-memory">https://stackoverflow.com/questions/12825148/what-is-the-meaning-of-the-term-arena-in-relation-to-memory</a></li></ol><figure><a href="https://becominghuman.ai/"><img alt="" src="https://cdn-images-1.medium.com/max/786/1*ESljeAHVzlBQMDOYwDsLRQ.png" /></a><figcaption><a href="https://becominghuman.ai/">https://becominghuman.ai/</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=785b523e0cca" width="1" height="1" alt=""><hr><p><a href="https://becominghuman.ai/a-deep-dive-into-onnx-onnx-runtime-part-2-785b523e0cca">A Deep Dive into ONNX &amp; ONNX Runtime (Part 2)</a> was originally published in <a href="https://becominghuman.ai/">Becoming Human: Artificial Intelligence Magazine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into ONNX & ONNX Runtime (Part 1)]]></title>
            <link>https://becominghuman.ai/a-deep-dive-into-onnx-onnx-runtime-part-1-874517c66ffc?source=rss-36b048b95ef1------2</link>
            <guid isPermaLink="false">https://medium.com/p/874517c66ffc</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[onnx-runtime]]></category>
            <category><![CDATA[computational-graphs]]></category>
            <category><![CDATA[model-optimization]]></category>
            <category><![CDATA[onnx]]></category>
            <dc:creator><![CDATA[Mohsen Mahmoodzadeh]]></dc:creator>
            <pubDate>Thu, 27 Oct 2022 11:04:49 GMT</pubDate>
            <atom:updated>2022-11-02T16:42:38.480Z</atom:updated>
            <content:encoded><![CDATA[<p>Rise of deep learning started in the early 2010s thanks to the existing hardware and accelerators, and with this support, more complex and larger models were presented by researchers and engineers. However, limitations such as memory consumption and execution time remain a challenge. These challenges in the field of engineering and business become more prominent because of the limitations in computing resources.</p><p>With the spread of larger and more complex models in recent years, optimizing the models so that they can output the maximum possible quality with the minimum consumption of resources has become a critical issue. The importance of this topic in the Inference phase of deep learning models has been twofold. This importance, in addition to optimization at runtime (speed and memory consumption), is also related to the differences between the model training environment and its inference environment. In general, it is not always possible to train and infer a model on an environment. Therefore, providing the conditions to separate the development and training process from the deployment and inference process has been one of the concerns of machine learning engineers and researchers.</p><p>In this series of articles, we intend to examine the challenges of optimizing neural network models with the help of <strong>ONNX</strong> and <strong>ONNX Runtime</strong> by addressing the low-level details of them.</p><p>In part 1, we will review the introduction of optimization and acceleration methods of models and explain the reasons for the need for a common intermediate representation, ONNX.</p><p>And in <a href="https://medium.com/@mohsen.mahmoodzadeh/a-deep-dive-into-onnx-onnx-runtime-part-2-785b523e0cca">part 2</a>, we will have an in-depth look at the building blocks of ONNX Runtime.</p><p>In the following, we will have an overview of the optimization and acceleration methods available in the Inference phase:</p><h3>Inference acceleration stack</h3><figure><img alt="Inference acceleration stack" src="https://cdn-images-1.medium.com/max/1024/1*dOElJWtW7kppsMb7nNyAnw.jpeg" /><figcaption>Source: <a href="https://deci.ai/blog/graph-compilers/">https://deci.ai/blog/graph-compilers/</a></figcaption></figure><p>This stack consists of different levels, at least one of these levels should be used to have faster inference. It can be divided into <strong>three</strong> types of levels:</p><h4><strong>1. Hardware</strong>: Improve computation with parallelization</h4><p>Hardware devices are at the lowest level of accelerators. Units such as CPU, GPU, TPU, etc. perform calculations. Despite the differences, faster calculations lead to faster model derivations. However, acceleration in hardware has fundamental limitations due to reasons such as Moore’s Law.</p><figure><img alt="Moore’s law" src="https://cdn-images-1.medium.com/max/1024/1*WcnIVc8VlMAa7KnPnHzO_g.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Moore%27s_law">https://en.wikipedia.org/wiki/Moore%27s_law</a></figcaption></figure><h4>2. Software: Acceleration without changing model</h4><p>Any acceleration without changing the model is included in this category. These methods are used to optimize the computational graph in such a way that the model remains unchanged.</p><p>These methods are divided into two groups:</p><ol><li><strong>Low-level libraries</strong>: hardware-specific optimizations</li></ol><p>These libraries(e.g cuDNN, MKL-DNN, etc.) are generally used for graphics computing and provide highly-tuned implementations for common processes such as forward and backward convolutions, pooling, normalization, activation layers that mainly use GPU parallelism.</p><figure><img alt="Low-level libraries &amp; Graph compilers" src="https://cdn-images-1.medium.com/max/156/1*LuwVYp6K-kYTC6d2vTLfrw.png" /><figcaption>Sourcce: <a href="https://www.sodalite.eu/content/graph-compilers-ai-training-and-inference">https://www.sodalite.eu/content/graph-compilers-ai-training-and-inference</a></figcaption></figure><p>2. <strong>Graph compilers</strong>: Optimizing forward or backward paths in computational graph</p><p>We will talk about these groups of software accelerators later.</p><h4>3. Algorithmic: Acceleration with changing model</h4><p>These types of acceleration accelerate the inference process by changing the model or architecture. The focus of these methods is on removing possible redundancies in the model or keeping the important information of the model and discarding its less important information.</p><p>These methods can be classified into three categories:</p><ol><li><strong>Pruning</strong>: Filtering the less important weights of the network</li><li><strong>Network quantization</strong>: Replacing floating-point weights or activations with compact representations with less precision</li><li><strong>Neural Architecture Search(NAS)</strong>: Automation of network architecture engineering by choosing the right architecture from the space of allowed architectures</li></ol><h3>Graph Compiler</h3><p>Earlier in the Inference acceleration stack, graph compilers were mentioned as one of the software accelerators. In this section, we will discuss them in more depth.</p><p>Most deep learning architectures can be described using a directed acyclic graph (DAG) where each node represents a neuron. If the output of one node is the input of another node, two nodes are connected by an edge. Similar to this DAG representation, the nodes in a computational graph represent the vector operators and their edges represent the data dependencies between them.</p><figure><img alt="Forward and backward pass in computational graph" src="https://cdn-images-1.medium.com/max/1024/1*5KdDT9-50z9hHIfsEREcCA.png" /><figcaption>Source: <a href="https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/">https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/</a></figcaption></figure><p>When we define a neural network in TensorFlow or PyTorch, the network becomes a computational graph that is then executed on the desired hardware. Therefore, the computational graph can be considered an Intermediate Representation (IR), which is very useful for optimization and execution on different devices.</p><p>Computational graph complexity increases linearly with size. Graph compilers actually play a role at this point. Their goal is to optimize the generated computational graphs for inference on a given hardware.</p><p>However, the biggest challenge in using graph compilers stems from the fact that frameworks and compilers are usually developed independently of each other:</p><ol><li>A framework may implement a new operator that is not yet implemented by the compiler.</li><li>Some basic layers (such as convolution) have different implementations.</li><li>Some compilers only work with certain frameworks; For example, OpenVino only works with TensorFlow and ONNX. So if we have a PyTorch model that we want to compile on OpenVino, it must first be compiled to ONNX and then to OpenVino(we’ll talk about ONNX later).</li></ol><p>Graph compilers(e.g. TVM, TensorRT, OpenVino, etc.) map high-level computational graph from deep learning frameworks to operations that can be executed on a given hardware. When compiling a computational graph or mapping it to a hardware, compilers perform optimizations on the hardware to increase the speed of inference. These optimizations include:</p><h4>Graph Rewriting</h4><p>The structure of the graph specifies the order of execution of operations. Job scheduling considers determining the optimal order to execute a sequence of operations.</p><p>It is usually possible to achieve this optimal order by applying some basic actions; Actions such as:</p><ol><li>Remove/add a node or edge</li><li>Node fusion</li><li>Replacing a subgraph with another subgraph</li><li>Remove layers with unused output</li></ol><figure><img alt="Operation Fusion" src="https://cdn-images-1.medium.com/max/1024/1*RPBe3AMD-0z9FCDCNDQDiA.jpeg" /><figcaption>Source: <a href="https://deci.ai/blog/graph-compilers/">https://deci.ai/blog/graph-compilers/</a></figcaption></figure><h4>Operation Fusion</h4><p>Computational graphs often contain sequences of operations that are relatively frequent or have special hardware kernels for them.</p><p>This fact is exploited by many compilers, by fusing operations (when possible) and eliminating unnecessary memory accesses.</p><p>Fusion of operations is seen in many cases; For example, convolution, ReLU, and BatchNorm are usually combined into one operation.</p><h4>Assignment of Operations / Operation Scheduling</h4><p>Part of optimization is determining the best assignment of operations for the target hardware, especially in the inference phase on multiple devices.</p><p>Graph compilers provide an additional hardware abstraction layer that accelerates the inference process on various devices. Operations are scheduled based on different policies.</p><p>In case there are several different devices, each device has its own queue of ready-to-run operations. In this case, graph compilers perform optimization by determining the appropriate scheduling strategy required to assign priorities to different nodes in the graph and by considering cross-device dependencies.</p><p>Today, each framework has its own representation of the computational graph. In addition, frameworks are usually optimized for specific purposes (such as fast training, support for complex architectures, inference on mobile devices, etc.). For this reason, the developer can choose the desired framework based on one of the mentioned goals.</p><p>According to what was said, there is a requirement that the models developed with different frameworks can work optimally in any environment and according to the configurations of that environment. In other words, we need a common intermediate representation.</p><h3>ONNX, a common IR</h3><p>ONNX is a common Intermediate Representation (IR) to help build a powerful ecosystem in this field. By providing a common representation of the computation graph, ONNX helps developers choose the right framework for their purposes, allows authors to focus on creative improvements, and gives hardware vendors the ability to facilitate optimizations on their platforms.</p><figure><img alt="onnx format, a common IR" src="https://cdn-images-1.medium.com/max/892/1*lqlMGyZkoQHpbiXGYkdH_g.png" /><figcaption>Source: <a href="https://bleedai.com/training-a-custom-image-classifier-with-tensorflow-converting-to-onnx-and-using-it-in-opencv-dnn-module/">https://bleedai.com/training-a-custom-image-classifier-with-tensorflow-converting-to-onnx-and-using-it-in-opencv-dnn-module/</a></figcaption></figure><p>The three main tasks of ONNX can be listed as follows:</p><ol><li>Convert the model from any framework to ONNX format</li><li>Convert ONNX format to any desired framework</li><li>Faster inference with ONNX model on supported runtime engines</li></ol><h3>ONNX File Format</h3><p>An ONNX file is actually an extensible specification consisting of three parts:</p><ol><li>Definition of an extensible computational graph model</li><li>Standard data type definition</li><li>Definition of internal operators (built-in)</li></ol><p>The first two cases together actually form the same intermediate representation or IR. The full list of built-in operators is also available <a href="https://github.com/onnx/onnx/blob/main/docs/Operators.md">here</a> and <a href="https://github.com/onnx/onnx/blob/main/docs/Operators-ml.md">here</a>.</p><p>ONNX stores data in Protocol Buffers format. This format is a data serialization method that has its own IR and compiler. In the IR format of Protocol Buffers, the messages that will be exchanged are defined. Each field in the messages is numbered with a unique number, and only this number is transferred in the exchange of information to avoid sending a large amount of information. In this format, only the data type and data order are determined. Each data is interpreted by the software that uses it.</p><p>For example, in Protocol Buffers format, a node with specifications:</p><blockquote>Y = Conv[kernel=1, pad=1, stride=1](X, W, B)</blockquote><p>Will be defined as below:</p><figure><img alt="A Protocol Buffers example" src="https://cdn-images-1.medium.com/max/176/0*ylNwO-SaA7wCSmoF" /><figcaption>A Protocol Buffers example</figcaption></figure><p>There is a similar structure for other components of a computational graph such as <a href="https://github.com/onnx/onnx/blob/main/docs/IR.md#graphs">graph</a>, <a href="https://github.com/onnx/onnx/blob/main/docs/IR.md#nodes">node</a>, <a href="https://github.com/onnx/onnx/blob/main/docs/IR.md#attributes">feature</a>, <a href="https://github.com/onnx/onnx/blob/main/docs/IR.md#tensor-definition">tensor</a>, etc.</p><p>The highest level data structure in ONNX is a “model” defined in Protocol Buffers as ModelProto:</p><figure><img alt="ModelProto structure" src="https://cdn-images-1.medium.com/max/418/0*FiyQcQLrvSWAayfP" /><figcaption>ModelProto structure</figcaption></figure><p>For example, opset_import is a collection of “operation set” identifiers made available to the model. An implementation must support all operators in a set or reject the model. Changing, increasing or decreasing the number of operators can cause a new version of opset. For this reason, operations in ONNX are versioned.</p><p>The model developed in a given framework is converted to ONNX format by running the model on mostly random data. This transformation occurs in such a way that the performed operations are mapped to ONNX operations and finally the entire model graph is mapped to ONNX format.</p><p>Since the ONNX file is a binary file, its contents can be checked after decoding using the Protocol Buffers compiler. In the ONNX source code, this <a href="https://github.com/onnx/onnx/blob/main/docs/IR.md">structure</a> and how it is <a href="https://github.com/onnx/onnx/blob/main/onnx/onnx.proto">interpreted</a> is laid out, which can be used to encode and decode the binary model.</p><p>To decode ONNX model to Protocol Buffers format:</p><blockquote>protoc — decode=onnx.ModelProto onnx.proto &lt; yourfile.onnx &gt; yourfile.onnx.txt</blockquote><p>And also to encode to ONNX model:</p><blockquote>protoc — encode=onnx.ModelProto onnx.proto &lt; yourfile.onnx.txt &gt; yourfile.onnx</blockquote><p>can be used.</p><p>Also, tools such as <a href="https://github.com/lutzroeder/Netron">Netron</a>, <a href="https://github.com/PaddlePaddle/VisualDL">VisualDL</a> and <a href="https://github.com/zetane/viewer">Zetane</a> have been developed for the abstract visualization of ONNX model computation graph, which can be visually checked by giving the ONNX model to them.</p><p>In the <a href="https://medium.com/@mohsen.mahmoodzadeh/a-deep-dive-into-onnx-onnx-runtime-part-2-785b523e0cca">next article</a>, we’ll discuss about ONNX Runtime building blocks.</p><figure><a href="https://becominghuman.ai/"><img alt="" src="https://cdn-images-1.medium.com/max/786/1*ESljeAHVzlBQMDOYwDsLRQ.png" /></a><figcaption><a href="https://becominghuman.ai/">https://becominghuman.ai/</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=874517c66ffc" width="1" height="1" alt=""><hr><p><a href="https://becominghuman.ai/a-deep-dive-into-onnx-onnx-runtime-part-1-874517c66ffc">A Deep Dive into ONNX &amp; ONNX Runtime (Part 1)</a> was originally published in <a href="https://becominghuman.ai/">Becoming Human: Artificial Intelligence Magazine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>