<?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 Fateme Bafghi on Medium]]></title>
        <description><![CDATA[Stories by Fateme Bafghi on Medium]]></description>
        <link>https://medium.com/@fatemebfg?source=rss-8094c717adfc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jfMSzARpfIgFUc6ExE9m9Q.jpeg</url>
            <title>Stories by Fateme Bafghi on Medium</title>
            <link>https://medium.com/@fatemebfg?source=rss-8094c717adfc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:44:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fatemebfg/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[TensorRT Conversion: Transforming Deep Learning Models for High-Speed Inference]]></title>
            <link>https://medium.com/@fatemebfg/tensorrt-conversion-transforming-deep-learning-models-for-high-speed-inference-36548bdca46c?source=rss-8094c717adfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/36548bdca46c</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[tensorrt]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[onnx]]></category>
            <dc:creator><![CDATA[Fateme Bafghi]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 13:01:47 GMT</pubDate>
            <atom:updated>2024-02-20T05:10:36.142Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97yEUfk6estm9oAx9AVDsw.png" /></figure><h3>What is TensorRT:</h3><p>Let’s start by quickly understanding what TensorRT is and how it can make our models better. According to<a href="https://developer.nvidia.com/tensorrt"> Nvidia’s official documentation</a>, TensorRT is a software development kit (SDK) specifically crafted for high performance deep learning inference.</p><p>TensorRT acts as a performance accelerator for deep learning models, allowing them to achieve remarkable speedups in inference time. By optimizing the model’s computations and using the power of GPUs, TensorRT can deliver up to a 4 to 5 times faster inference speed compared to non-optimized models. This level of acceleration makes TensorRT an powerful tool for deploying deep learning models in real-world services and resource-constrained embedded applications.</p><h3>How To install TensorRT</h3><p>To install TensorRT, there are various methods outlined in the official installation guide. One option is via <a href="https://docs.nvidia.com/deeplearning/tensorrt/install-guide/index.html#installing-pip">Python Package Index Installation</a>. It’s important to note that with this method, you won’t have access to TensorRT C++ APIs or the ability to compile plugins written in C++. Additionally, you’ll need to ensure you have Python 3.6 or above and are using Linux X86.</p><p>To install TensorRT through the Python wheel, you can execute the following command:</p><pre>python3 -m pip install --upgrade tensorrt</pre><p>This command will install the TensorRT package and automatically handle the installation of the required CUDA and cuDNN libraries as well. For more detailed instructions and information, it’s recommended to refer to the official <a href="https://docs.nvidia.com/deeplearning/tensorrt/install-guide/index.html">installation guide</a>.</p><h3>TensorRT Core Classes and Their Usage:</h3><p>Before diving into the conversion of an ONNX model to TensorRT, I first want to explain some of the important classes of TensorRT and a small example on them, and then we will put them together to complete our conversion process. The following classes are according to the <a href="https://docs.nvidia.com/deeplearning/tensorrt/api/python_api/index.html">TensorRT Python Documentation</a>.</p><ul><li><a href="https://docs.nvidia.com/deeplearning/tensorrt/api/python_api/infer/Core/Logger.html"><strong>Logger</strong></a><strong>: </strong>The Logger class is responsible for logging and displaying messages from various TensorRT processes. It serves as the base logger for the Builder, ICudaEngine, and RunTime classes. You can specify the severity level of the messages to be displayed, with five levels available: INTERNAL_ERROR, ERROR, WARNING, INFO, and VERBOSE.</li></ul><p>Here is an example of creating a Logger with VERBOSE level.</p><pre><br>import tensorrt as trt<br>TRT_LOGGER = trt.Logger(trt.Logger.VERBOSE)<br># Creates a TensorRT logger with the VERBOSE severity level</pre><ul><li><a href="https://docs.nvidia.com/deeplearning/tensorrt/api/python_api/infer/Core/Builder.html#id1"><strong>Builder</strong></a><strong>: </strong>The Builder class is responsible for constructing a TensorRT Engine (ICudaEngine) from an existing Network definition (INetworkDefinition). It serves as the central component for creating an optimized engine that can be deployed for high-performance inference.</li><li><a href="https://docs.nvidia.com/deeplearning/tensorrt/api/python_api/infer/Core/BuilderConfig.html"><strong>IBuilderConfig</strong></a><strong>: </strong>This is the class which contains the necessary optimization configs like the maximum workspace size or the optimization precision you want to choose.</li></ul><p>The following code creates a Builder. It also define multiple configurations which we need during optimization, like maximum workspace size, the default device type and also the optimization precision which has been set to float16.</p><pre>builder = trt.Builder(TRT_LOGGER)<br>config = builder.create_builder_config()<br><br># Set the maximum workspace size for the builder<br>config.max_workspace_size = 1 &lt;&lt; 50<br># Set the optimization precision to float16<br>config.flags |= 1 &lt;&lt; int(trt.BuilderFlag.FP16) <br># Set the default device type to GPU<br>config.default_device_type = trt.DeviceType.GPU</pre><ul><li><a href="https://docs.nvidia.com/deeplearning/tensorrt/api/python_api/infer/Graph/Network.html"><strong>INetworkDefinition</strong></a><strong>: </strong>The INetworkDefinition class is used to define the computational graph for the deep learning model. This graph can be created in two ways: either by parsing an existing model format (such as ONNX) or by manually constructing the graph using TensorRT’s ILayer objects. In this tutorial, we will focus on parsing an ONNX model to create the INetworkDefinition.</li></ul><p>One thing that we should know before creating a network, is whether our network accepts dynamic shapes or not. If so, which is considered as Explicit Batch, we should mention it in network creation. The following piece of code shows how we can create a network with Explicit Batch enabled. Please note that it is just an empty network and later we will parse our ONNX model into it.</p><pre># Enable explicit batch mode for dynamic input shapes<br>EXPLICIT_BATCH = 1 &lt;&lt; (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) #we have enabled the explicit Batch<br># Create an empty network definition with explicit batch mode<br>network = builder.create_network(EXPLICIT_BATCH) </pre><ul><li><strong>Parser: </strong>The Parser class is responsible for converting a network definition, such as ONNX, into an INetworkDefinition object that TensorRT can understand. Different model formats require different Parser implementations. For parsing ONNX models, we use the OnnxParser class, which is specifically designed to handle the ONNX format.</li></ul><pre># Create an ONNX parser for the network<br>parser = trt.OnnxParser(network, TRT_LOGGER)<br>with open(&quot;model.onnx&quot;, &quot;rb&quot;) as f:<br>  # Parse the ONNX model into the network definition<br>  if not parser.parse(f.read()):<br>  # Log any parsing errors<br>    print(&#39;ERROR: Failed to parse the ONNX file.&#39;)<br>    for error in range(parser.num_errors):<br>      logger.error(parser.get_error(error))</pre><p>In scenarios where the input shapes are dynamic, meaning they can vary in size during inference, TensorRT requires an optimization profile to be defined. This profile specifies the minimum, maximum, and optimal input sizes for each input tensor. By providing this profile, TensorRT can ensure efficient execution across a range of input shapes</p><p>The following code is an example of creating an optimization profile for a network which accepts inputs with dynamic shape in all dimension. (You should put -1 instead of the dimension size on the dynamic dimension)</p><pre># Create an optimization profile for dynamic input shapes<br>profile = builder.create_optimization_profile()<br># Add an input tensor with dynamic shape to the network<br>network.add_input(&quot;input&quot;, trt.float32, (-1, -1, -1, -1))<br># Set the minimum, optimal, and maximum input sizes for the optimization profile<br>profile.set_shape(&quot;input&quot;, configs.model.input_min_size, configs.model.input_opt_size, configs.model.input_max_size)<br># Add the optimization profile to the builder configuration<br>config.add_optimization_profile(profile)</pre><ul><li><a href="https://docs.nvidia.com/deeplearning/tensorrt/api/python_api/infer/Core/Engine.html"><strong>ICudaEngine</strong></a><strong>: </strong>The ICudaEngine class represents the optimized engine produced by TensorRT. It is the culmination of all the optimization steps and serves as the final, deployable representation of the deep learning model. The ICudaEngine can be serialized and loaded for efficient inference on GPU hardware.</li></ul><p>The following code is an example of creating an engine and writing it to a file.</p><pre># Build the serialized TensorRT engine from the network and configuration<br>engine = builder.build_serialized_network(network, config)<br>logger.info(&quot;engine was created successfully&quot;)<br>with open(&quot;model.trt&quot;, &#39;wb&#39;) as f:<br>  try:<br>    # Write the serialized engine to the file<br>    f.write(bytearray(engine))<br>  except:<br>    logger.error(&quot;file not writen&quot;)<br>        </pre><ul><li><a href="https://docs.nvidia.com/deeplearning/tensorrt/api/python_api/infer/Core/ExecutionContext.html"><strong>IExecutionContext</strong></a><strong>: </strong>This class will create a context from the tensorRT Engine to get inference from it.(I will explain more about this class in the inference article)</li></ul><p>While this tutorial focused on the core TensorRT classes essential for model conversion, it’s worth noting that TensorRT offers a comprehensive set of classes and functionalities. The classes covered here are the most crucial ones for the conversion process, but TensorRT provides additional capabilities, such as calibration and inference, which will be explored in subsequent tutorials.</p><p>The following code snippet consolidates the various TensorRT classes and steps discussed earlier to perform the complete conversion process. It demonstrates how to create a logger, builder, network definition, and optimization profile, parse an ONNX model, and build the optimized TensorRT engine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2af8801279fa64b7cc9f4fa2a329af4c/href">https://medium.com/media/2af8801279fa64b7cc9f4fa2a329af4c/href</a></iframe><p>You can Also visit my github repository on Converting a model from ONNX to TensorRT. This repository also covers the tensorRT calibration and inference.</p><p><a href="https://github.com/fatemebafghi/TensorRT-Conversion-Calibration-and-inference/tree/main">GitHub - fatemebafghi/TensorRT-Conversion-Calibration-and-inference</a></p><h3>Resources:</h3><ul><li><a href="https://developer.nvidia.com/tensorrt">NVIDIA TensorRT</a></li><li><a href="https://docs.nvidia.com/deeplearning/tensorrt/">NVIDIA TensorRT</a></li><li><a href="https://docs.nvidia.com/deeplearning/tensorrt/api/python_api/index.html">TensorRT - NVIDIA TensorRT Standard Python API Documentation 8.6.1 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36548bdca46c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Convert a PyTorch Model to ONNX]]></title>
            <link>https://medium.com/@fatemebfg/how-to-convert-a-pytorch-model-to-onnx-8ff347cf5113?source=rss-8094c717adfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ff347cf5113</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Fateme Bafghi]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 19:48:43 GMT</pubDate>
            <atom:updated>2024-02-14T15:16:47.192Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrdW81_BwT0RT7_6QBFwrw.jpeg" /></figure><h3>What is ONNX</h3><p>At first lets look at the official definition of ONNX provided by<a href="https://onnx.ai/"> onnx website</a>.</p><blockquote>ONNX is an open format built to represent machine learning models. ONNX defines a common set of operators — the building blocks of machine learning and deep learning models — and a common file format to enable AI developers to use models with a variety of frameworks, tools, runtimes, and compilers.</blockquote><p>In fact, ONNX, or Open Neural Network Exchange, is like the cool translator for machine learning models. It’s a tag team effort by Microsoft and Facebook to solve the puzzle of deploying and using models across different frameworks.</p><p>Imagine this: You’ve trained a smart model using PyTorch, but the system where it needs to work prefers TensorFlow. ONNX steps in like a superhero. It helps your model speak the language of any framework, making it super easy to switch between them.</p><p>Think of ONNX as the universal language for models. It’s like having a shared code that PyTorch, TensorFlow, and other frameworks understand. This means your models can travel freely between different frameworks, making your life as a developer much easier.</p><p>So, when you’re dealing with the challenges of putting your model into action, ONNX is there to simplify things. It’s not just a format; it’s a friendly bridge that connects different machine learning worlds, allowing models to work together seamlessly.</p><h3>Prerequisites for Converting a Model to ONNX</h3><p>In order to convert a Pytorch model to onnx, we need to install pytorch, onnx and onnxruntime libraries.</p><pre>pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118<br>pip install onnx<br>pip install onnxruntime-gpu</pre><h3>Scripting Your Model using TorchScrip</h3><p>Before jumping into converting our model to ONNX, I want to tell you about what TorchScript is. TorchScript is a way to create serializable and optimizable models from PyTorch code. Any TorchScript program can be saved from a Python process and loaded in a process where there is no Python dependency. Pytorch uses two methods in order to convert an nn.Module to a graph represented in TorchScript format: Tracing and Scripting</p><p><strong>Tracing</strong>: It runs a model with certain inputs, and “traces / records” all the operations that are executed into a graph. torch.jit.trace is an export API that uses tracing, used like torch.jit.trace(model, input)</p><p><strong>Scripting</strong>: It parses the Python source code of the model, and compiles the code into a graph. torch.jit.script is an export API that uses scripting, used like torch.jit.script(model).</p><h3>Converting my model to ONNX:</h3><p>To change our model into the ONNX format, we make use of the PyTorch ONNX library. This powerful library accepts either a nn.Module or a traced module as its input. If our model is of the nn.Module type, ONNX takes the initial step of tracing the model and then proceeds with the conversion to the ONNX format. During this process, the model is executed, creating a trace that records the operators used to calculate the outputs. Since the export function involves running the model, we have to supply a dummy input tensor. The values in this tensor can be random as long as they match the correct type and shape.</p><p>So lets create a timm model, trace it and then convert it to ONNX.</p><pre><br>import timm<br>import torch<br>  <br>original_model = timm.create_model(&#39;convnext_nano&#39;,<br>                                          pretrained=True)<br>device = torch.device(&#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;)<br>  <br>  with torch.no_grad():<br>      original_model.eval()<br><br>      original_model.to(device)<br>      scripted_model = torch.jit.trace(original_model,<br>                                        example_inputs=torch.rand(1, 3,<br>                                                                  224,<br>                                                                  224).to(device),<br>                                        check_trace=False)</pre><p>This conversion essentially turns our model into a graph, where each node signifies a distinct mathematical operation. The image below provides a snapshot of a section of the transformed model, represented visually as a graph.</p><p>For visualizing this graph, I have used <a href="https://github.com/lutzroeder/netron">NETRON</a>. You can explore the properties of each node, including its inputs and outputs, by simply clicking on it within Netron.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrOJf9vKyUqx3qeD0YMlLA.png" /><figcaption>an ONNX model graph</figcaption></figure><p>Keep in mind that, by default, the input size remains constant in the exported ONNX graph for all dimensions unless you declare a dimension as dynamic using the dynamic_axes parameter in torch.onnx.export().</p><p>For Example in the below code, the exported model can handle inputs of size [batch_size, 3, width, height], allowing variability in all axes except the number of channels.</p><pre>from torch import onnx as torch_onnx<br>import torch<br><br>input_names = [&quot;input&quot;]<br>output_names = [&quot;output&quot;]<br>dummy_input = torch.rand(1, 3, 224, 224)<br>torch.cuda.empty_cache()<br>torch.cuda.synchronize()<br><br>with torch.no_grad():<br> scripted_model.eval()<br> dynamic_axes = {&#39;input&#39;: {0: &#39;batch_size&#39;, 2: &#39;width&#39;, 3: &#39;height&#39;},<br> &#39;output&#39;: {0: &#39;batch_size&#39;, 2: &#39;width&#39;, 3: &#39;height&#39;}} # adding names for better debugging<br><br>torch_onnx.export(scripted_model,<br>                  dummy_input.to(&quot;cuda&quot;),<br>                  &quot;model.onnx&quot;,<br>                  verbose=True,<br>                  input_names=input_names, # the model&#39;s input names<br>                  output_names=output_names, # the model&#39;s output names<br>                  dynamic_axes=dynamic_axes,<br>                  opset_version=14, # the ONNX version to export the model to<br>                  do_constant_folding=True, # whether to execute constant folding for optimization<br>                  )</pre><p>In order to check whether our models has been exported correctly or not, we use check_model function. This function verifies model’s structure and confirms that the model has a valid schema. Here is a small example of checking onnx model.</p><pre>import onnx<br>def check_onnx(onnx_path):<br>  model = onnx.load(onnx_path)<br>  try:<br>    onnx.checker.check_model(model)<br>  except Exception as e:<br>    logger.error(f&quot;{e}&quot;)<br>  else:<br>    logger.info(&quot;passed successsfully&quot;)</pre><h3>Get inference from ONNX</h3><p>To predict outcomes using an ONNX model, we rely on the onnxruntime library. This handy library lets us run ONNX models smoothly across various programming languages like Python, C++, and C#. It’s flexible enough to run models on different systems, including Windows, Linux, Mac, iOS, and Android.</p><p>Getting predictions from an ONNX model begins with loading the model. This is done by creating a session using the InferenceSession function. Just provide the path to the ONNX model, session options, and the preferred provider (like CPU or GPU). The provider is like a toolset for specific hardware types. In our example, if there’s a GPU option, the library will use it; otherwise, it falls back to CPU. It supports many execution providers which are listed <a href="https://onnxruntime.ai/docs/execution-providers/">here</a>.</p><pre>providers=[‘CUDAExecutionProvider’, ‘CPUExecutionProvider’])</pre><p>The below function create an onnx session with GPU provider as the prior, and CPU as the second provider.</p><pre>def create_session():<br>   session_options = ort.SessionOptions()<br>   provider_options = None<br>   providers = [&#39;CUDAExecutionProvider&#39;, &#39;CPUExecutionProvider&#39;]<br>   session = ort.InferenceSession(&quot;model.onnx&quot;, sess_options=session_options,provider_options=provider_options, providers=providers)</pre><h3>Running ONNX session:</h3><p>In order to run an inference session, we use the run function. In order to use this function we should specify inputs, input names as a dictionary, and desired outputs. Input names and output names have been defined previously in the extraction step, but we can access their name through the get_inputs function. The below code is a simple example of running the onnx session. Please note that input data should be a numpy array.</p><pre>def run (session, input_data):<br>  input_data = np.array(input_data).astype(&#39;float32&#39;)<br>  input_name = session.get_inputs()[0].name<br>  output_name = session.get_outputs()[0].name<br>  features = session.run(output_names=[output_name], input_feed={input_name: input_data})<br>  return features</pre><p>here is the github repo of this tutorial <a href="https://github.com/fatemebafghi/Pytorch2ONNX">https://github.com/fatemebafghi/Pytorch2ONNX</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ff347cf5113" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>