<?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 Roman on Medium]]></title>
        <description><![CDATA[Stories by Roman on Medium]]></description>
        <link>https://medium.com/@r7vme?source=rss-761cb01aca37------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*12-1ccMupT6Q8cXhinH9MQ.png</url>
            <title>Stories by Roman on Medium</title>
            <link>https://medium.com/@r7vme?source=rss-761cb01aca37------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:00:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@r7vme/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[Testing a C-code with system calls]]></title>
            <link>https://r7vme.medium.com/testing-a-c-code-with-system-calls-f49c53d3157d?source=rss-761cb01aca37------2</link>
            <guid isPermaLink="false">https://medium.com/p/f49c53d3157d</guid>
            <category><![CDATA[cmake]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Roman]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 11:53:56 GMT</pubDate>
            <atom:updated>2021-01-26T11:53:56.774Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><p>A project template for testing C-code with system calls see on <a href="https://github.com/r7vme/testing-c-code-with-system-calls">github</a>. It uses FFF for mocking and Catch2 as a testing framework. The solution is based on linker --wrap feature.</p><h3>Intro</h3><p>If you ever wrote a low-level library that uses system calls you know that it’s not easy to test such code. In this short post I want to share a “turn key” template with <a href="https://github.com/meekrosoft/fff"><strong>FFF</strong></a> and <a href="https://github.com/catchorg/Catch2"><strong>Catch2</strong></a> testing frameworks that allows easy test such code.</p><h3>The Problem</h3><p>Let’s say we have a function that checks if we run on a multi or single-core system.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8686dd705215e332c4a2134ecfe1fd4b/href">https://medium.com/media/8686dd705215e332c4a2134ecfe1fd4b/href</a></iframe><p>The problem of unit testing such function that it calls an external function <a href="https://man7.org/linux/man-pages/man3/get_nprocs.3.html">get_nprocs_conf()</a> behavior of which we do not control. Moreover result from this function will change from machine to machine, so <strong>unit testing such code is not really easy.</strong></p><h3>The Solution</h3><p>We will use a wrap trick provided by a GCC linker (also available in LLVM’s gold linker). By specifying the linker option --wrap=get_nprocs_conf, we will get a chance<strong> to redefine </strong><strong>get_nprocs_conf() as we want.</strong></p><p>From <a href="https://linux.die.net/man/1/ld">ld manual</a></p><blockquote>— wrap=symbol</blockquote><blockquote>Use a wrapper function for symbol. Any undefined reference to symbol will be resolved to “__wrap_symbol”. Any undefined reference to “__real_symbol” will be resolved to symbol.</blockquote><p>The only thing we need now is to define __wrap_get_nprocs_conf() .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35c767b8d154c76aa4c5ac8687bc8e2b/href">https://medium.com/media/35c767b8d154c76aa4c5ac8687bc8e2b/href</a></iframe><p>Now compile and run</p><pre>gcc main.c &amp;&amp; ./a.out</pre><p>Will return multicore system . If we let linker to wrap get_nprocs_conf() result will be different.</p><pre>gcc -Wl,--wrap=get_nprocs_conf main.c &amp;&amp; ./a.out</pre><p>Will return singlecore system . Magic!</p><h3>Mocking And Testing With FFF and Catch2</h3><p>Now let’s try to do the same, but using proper frameworks.</p><ul><li><a href="https://github.com/meekrosoft/fff"><strong>FFF</strong></a> is a mocking framework that defines wrapper functions for us (creates mocks).</li><li><a href="https://github.com/catchorg/Catch2"><strong>Catch2</strong></a> is a C++ testing framework. Modern replacement for google test. I use it for more than two years and really enjoying writing BDD-style tests (<a href="http://www.electronvector.com/blog/using-catch-to-write-bdd-style-unit-tests-for-c">see why you want to write BDD-style tests with Catch2</a> too).</li></ul><p><a href="https://github.com/r7vme/testing-c-code-with-system-calls"><strong>Template</strong></a> that I provide below is actually the main the goal of this post, i.e. I want to show how a real project can be tested with FFF and Catch2.</p><p>The final test_lib.cpp looks like that. Let’s quickly jump thru it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/914a4a9bc9ac8aafa4c7a8e33e12d50c/href">https://medium.com/media/914a4a9bc9ac8aafa4c7a8e33e12d50c/href</a></iframe><p>Include catch2 and fff. DEFINE_FFF_GLOBALS is a mandatory directive from FFF, should only be added once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19bb44b687dc7607a8a4199904d0467f/href">https://medium.com/media/19bb44b687dc7607a8a4199904d0467f/href</a></iframe><p>Then let FFF define __wrap_get_nprocs_conf() . FFF creates a special struct to store all mock information. Struct name has a suffix_fake (i.e. __wrap_get_nprocs_conf_fake).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25c0aa5fdaf086b9eb604c3a84f0c922/href">https://medium.com/media/25c0aa5fdaf086b9eb604c3a84f0c922/href</a></iframe><p>If you have a big project you may want to move all includes and wrapper definitions to a separate header and include it in your test files.</p><p>Finally, define a test. The most important to mention that we should call a RESET_FAKE in every test. This is related to the fact that pure-C FFF uses global variables.</p><p>In the test itself, we set get_nproc_conf() to return 2 and check that is_multicore_system() will return true. Finally we also check that get_nprocs_conf was called only once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8793efd710d30ae51d18b0cf723eb60/href">https://medium.com/media/a8793efd710d30ae51d18b0cf723eb60/href</a></iframe><p>FFF supports different kinds of functions and allows e.g. to check arguments and many more. Please check the <a href="https://github.com/meekrosoft/fff">readme</a>.</p><h3>What’s next?</h3><p>You can clone and compile my template. It includes both FFF and Catch2 as third_party dependencies (they both header-only).</p><pre>git clone <a href="https://github.com/r7vme/testing-c-code-with-system-calls">https://github.com/r7vme/testing-c-code-with-system-calls</a><br> ./build_and_test.sh</pre><p>Then you can reuse my template for your project of just copy-paste some “best practices” from it.</p><p>Happy Testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f49c53d3157d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On importance of unified tooling]]></title>
            <link>https://r7vme.medium.com/on-importance-of-unified-tooling-2a8a71205acf?source=rss-761cb01aca37------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a8a71205acf</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cicd-tools]]></category>
            <dc:creator><![CDATA[Roman]]></dc:creator>
            <pubDate>Mon, 28 Dec 2020 09:13:32 GMT</pubDate>
            <atom:updated>2020-12-28T09:13:32.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQ2R9dPBsw5axnseRukkEQ.jpeg" /></figure><p>What does your typical work day as a (software) developer look like?</p><p>You probably spend some time writing actual code, a lot of time integrating it with existing systems and finally spend weeks delivering it to production.</p><p>In this short post I want to emphasize the importance of unified tooling.</p><p><strong>By “tooling” I mean</strong> everything — from debuggers to monitoring systems.</p><p><strong>By “unified” I mean</strong> that the tooling stack is explicitly defined i.e. set as a “standard” across the company.</p><p>The working process without “unified tooling” is deplorable. At best you’ll have <strong>a long feedback loop</strong> and will not be able to scale development of your product, at worst your product quality will suffer. From my professional experience, if you are trying to build a scalable product, you definitely need a unified tooling.</p><p>Here are 5 main tips that I have.</p><h3>1. Consciously spend time on tooling</h3><p><a href="https://youtu.be/BnIz7H5ruy0?t=919">Here</a> Edmond Lau (The Effective Engineer book) quotes Bobby Jonhsohn (ex Eng.Director of Facebook), who says that the <strong>most successful engineers spend third of the time on tools</strong>. I just want to add my motto here:</p><blockquote>If you did something manually twice — automate it!</blockquote><h3>2. Continuous integration of the code is a must</h3><p>Your project is already built automatically on pushing code to the repository? That is great! But do you also run unit tests automatically? What about code linting? Do you also deploy automatically to production? You should do it all. It scales productivity and quality exponentially. Here is a rough list of tools to do CI/CD:</p><ul><li>Gitlab CI/CD</li><li>Github Actions</li><li>CircleCI</li><li>TravisCI</li><li>Jenkins</li><li>Terraform</li><li>Ansible</li><li>many others</li></ul><h3>3. Create a unified development environment</h3><p>Consider this — a new developer joins a company and has to setup her/his working environment. How does she/he do that? With a long “how-to” document or senior developer should sit together and do “pair debugging”? Newcomers ideally should be able to compile and test the whole codebase in one day without help. How is this achievable? — tooling! Even with a huge codebase it is possible to do a <strong>one-command build/test/run environments</strong>. I usually do docker-based isolated environments. Another suggestion here, store all your configuration files (compiler, linter, IDE config, etc.) in git.</p><h3>4. Create and maintain an example module</h3><p>To continuously incorporate “best coding” practices, I suggest to have a “golden” example module. This module should be always with up-to-date code and can be copy-pasted when a new feature is started. To advance the example module further, you can write a simple code generation that will generate a real module from this template.</p><h3>5. Unify your technological stack</h3><p>Do not start writing tools right away, you may need to first define and unify your stack (OS, middleware, infrastructure, compiler, external dependencies, etc.), you also can write down all those decisions into “coding” or “implementation guidelines”. Good tooling comes easy with a defined stack.</p><p>That’s all for today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a8a71205acf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-time kernel for NVIDIA AGX Xavier]]></title>
            <link>https://r7vme.medium.com/real-time-kernel-for-nvidia-agx-xavier-b660e107a211?source=rss-761cb01aca37------2</link>
            <guid isPermaLink="false">https://medium.com/p/b660e107a211</guid>
            <category><![CDATA[jetson-agx-xavier]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[realtime]]></category>
            <dc:creator><![CDATA[Roman]]></dc:creator>
            <pubDate>Fri, 15 Nov 2019 14:25:14 GMT</pubDate>
            <atom:updated>2019-11-15T14:25:14.119Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post i want to share a quick way (one command) of recompiling Linux kernel with PREEMPT_RT patch for NVIDIA Jetson AGX Xavier.</p><p>Supported version: <strong>Jetpack 4.2.1</strong> (L4T 32.2.1), kernel <strong>4.9.140</strong></p><p>Supported hw: <strong>Jetson AGX Xavier</strong></p><p>New platforms (Nano, TX2, etc.), new versions are welcomed <a href="https://github.com/r7vme/xavier-base-docker-images/tree/master/realtime-kernel">here</a>.</p><ul><li>Cross-compilation will happen inside docker on your laptop.</li><li>Kernel update do not require full re-flashing, so Jetson filesystem will be preserved (kittens are safe). Done with Nvidia OTA update service.</li></ul><h3>Short version</h3><p>To build RT kernel for Xavier execute following commands on your x86_64 laptop</p><pre>git clone <a href="https://github.com/r7vme/xavier-base-docker-images">https://github.com/r7vme/xavier-base-docker-images</a><br>cd xavier-base-docker-images/realtime-kernel<br>docker build -t xavier-rt-kernel:32.2.1 -f Dockerfile.l4t_32_2_1 .</pre><p>It will download NVIDIA provided sources, apply PREEMPT_RT patches and compile the kernel. Finally it will generate OTA update image that can be used to quickly update kernel.</p><h3>Description</h3><p>Make sure you have successfully flashed your Xavier with Jetpack 4.2.1 (later one should also work) and already have <strong>ssh access</strong> to the board. No need for any USB cables, only one reboot will be required, because NVIDIA <a href="https://docs.nvidia.com/jetson/l4t/index.html#page/Tegra%2520Linux%2520Driver%2520Package%2520Development%2520Guide%2Fbootloader_update.html%23wwconnect_header">OTA (over-the-air-update) service</a> will be used.</p><p>For simplicity and reproducibility i provide a <a href="https://github.com/r7vme/xavier-base-docker-images/tree/master/realtime-kernel">Dockerfile</a>. One can also use this Dockerfile as a reference, but execute commands manually on your Linux system.</p><p>Dockerfile is just compiled list of commands provided in:</p><ul><li><a href="https://docs.nvidia.com/jetson/l4t/index.html#page/Tegra%2520Linux%2520Driver%2520Package%2520Development%2520Guide%2Fkernel_custom.html%23">Official L4T (Linux for Tegra) documentation</a></li><li><a href="https://developer.ridgerun.com/wiki/index.php?title=Xavier/JetPack_4.1/Compiling_Code/Kernel">Ridgerun documentation</a></li><li>and some bits that I discovered by myself or from nvidia devtalk forum</li></ul><h3>Compile kernel</h3><p>Make sure you have at least 20GB of free space and <a href="https://docs.docker.com/install/">docker</a> installed.</p><pre>git clone <a href="https://github.com/r7vme/xavier-base-docker-images">https://github.com/r7vme/xavier-base-docker-images</a><br>cd xavier-base-docker-images/realtime-kernel</pre><pre>docker build -t xavier-rt-kernel:32.2.1 -f Dockerfile.l4t_32_2_1 .</pre><p>Extract images and kernel modules</p><pre>docker run --rm -v $(pwd):/host xavier-rt-kernel:32.2.1 \<br>  cp /Linux_for_Tegra/kernel/kernel_supplements.tbz2  /Linux_for_Tegra/bootloader/payloads_t19x/bl_update_payload /Linux_for_Tegra/bootloader/payloads_t19x/bl_update_payload_default       /host</pre><p>bl_update_payload - image for OTA update containing real-time kernel bl_update_payload_default - image for OTA update containing default kernel kernel_supplements.tbz2 - archive containing kernel modules. Should be extracted to /lib/modules</p><h3>Update Xavier</h3><p><em>WARN: Make sure to have backups in case something will go wrong! Did not go for me, but anyway.</em></p><p>Extract and copy files to Xavier.</p><pre>scp kernel_supplements.tbz2 &lt;host&gt;:/tmp<br>scp bl_update_payload bl_update_payload_default &lt;host&gt;:/tmp</pre><p>Extract kernel modules. This step is necessary, because we are not re-flashing eMMC card (rootfs), but only updating a bootloader (kernel).</p><pre>sudo -i<br>tar -C / -xf /tmp/kernel_supplements.tbz2</pre><p>Flash new bootloader (commands described <a href="https://docs.nvidia.com/jetson/l4t/index.html#page/Tegra%2520Linux%2520Driver%2520Package%2520Development%2520Guide%2Fbootloader_update.html%23wwconnect_header">here</a>)</p><pre>cp /tmp/bl_update_payload* /opt<br>mkdir /opt/ota_package<br>nv_update_engine --enable-ab</pre><pre>cp /opt/bl_update_payload /opt/ota_package/<br>nv_update_engine --install</pre><p>If everything went well Jetson will be booted with new kernel</p><pre>uname -r<br>4.9.140-rt93+</pre><p>Now tools like <a href="https://wiki.linuxfoundation.org/realtime/documentation/howto/tools/cyclictest/start">cyclitest</a> should work</p><pre>sudo cyclictest --mlockall --smp --priority=80 --interval=200 --distance=0</pre><h3>To switch back to default kernel</h3><pre>cp /opt/bl_update_payload_default /opt/ota_package/bl_update_payload<br>nv_update_engine --install</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b660e107a211" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting Neural Network To TensorRT . Part 2 Creating a Custom Layer.]]></title>
            <link>https://r7vme.medium.com/converting-neural-network-to-tensorrt-part-2-creating-a-custom-layer-5297ee694d8?source=rss-761cb01aca37------2</link>
            <guid isPermaLink="false">https://medium.com/p/5297ee694d8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[tensorrt]]></category>
            <category><![CDATA[cuda]]></category>
            <dc:creator><![CDATA[Roman]]></dc:creator>
            <pubDate>Tue, 09 Jul 2019 19:31:10 GMT</pubDate>
            <atom:updated>2019-07-09T19:31:10.809Z</atom:updated>
            <content:encoded><![CDATA[<h3>Converting Neural Network To TensorRT . Part 2 Creating a Custom Layer.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*4-PvNFH9_i9XxazYmn4cGA.png" /></figure><p><strong>Part 1:</strong> <a href="https://medium.com/@r7vme/converting-neural-network-to-tensorrt-part-1-using-existing-plugins-edd9c2b9e42a">https://medium.com/@r7vme/converting-neural-network-to-tensorrt-part-1-using-existing-plugins-edd9c2b9e42a</a></p><p>In <a href="https://medium.com/@r7vme/converting-neural-network-to-tensorrt-part-1-using-existing-plugins-edd9c2b9e42a">part 1</a> i’ve described how to convert neural network with supported layers to TensorRT plan. In this part i’ll try to describe how to create a custom layer for TensorRT. Example will be a <a href="https://github.com/r7vme/tensorrt_l2norm_helper">“l2norm_helper”</a> plugin that i created to support <a href="https://www.tensorflow.org/api_docs/python/tf/math/l2_normalize">TensorFlow l2_normalize operation</a>.</p><p><strong>Source code: </strong><a href="https://github.com/r7vme/tensorrt_l2norm_helper"><strong>https://github.com/r7vme/tensorrt_l2norm_helper</strong></a></p><p>TensorRT plugin requires two major parts to be implemented:</p><ol><li>CUDA kernels (aka device code)</li><li>TensorRT classes: <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/c_api/classnvinfer1_1_1_i_plugin_v2.html">IPluginV2</a> and <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/c_api/classnvinfer1_1_1_i_plugin_creator.html">IPluginCreator</a></li></ol><h3><strong>Why l2_normalize is not supported by TensorRT?</strong></h3><p>This is a reasonable question. First let’s check what <a href="https://github.com/tensorflow/tensorflow/blob/v1.13.1/tensorflow/python/ops/nn_impl.py#L382-L386">l2_normalize is in TensorFlow</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef3b2d04f1b6f02fa319459c81a9fe6a/href">https://medium.com/media/ef3b2d04f1b6f02fa319459c81a9fe6a/href</a></iframe><p>It consists bunch of operations actually (not only one). And two throwing errors in TensorRT (checked with 5.0.6). Seems these two do not pass some internal TensorRT restrictions (<a href="https://devtalk.nvidia.com/default/topic/1030077/tensorrt/seeing-quot-unsupported-binary-op-max-with-constant-right-quot-when-converting-tensorflow-graph-to-tensorrt-engine-">related thread</a>).</p><blockquote>l2_normalize/Maximum: Unsupported binary op max with constant right</blockquote><blockquote>l2_normalize/Rsqrt: Unary not supported for other non-constant node</blockquote><h3>CUDA kernels</h3><p>Let’s start with workhorse (CUDA kernels). If you’re new to CUDA,<a href="https://www.nvidia.com/docs/IO/116711/sc11-cuda-c-basics.pdf"> <strong>highly recommend this presentation</strong></a> from NVIDIA. Rsqrt kernel does “1/sqrt(x)” for every member of input vector and assigns value to output vector. Easy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/887572b9bde2dd8e4f0c82b764ac7c58/href">https://medium.com/media/887572b9bde2dd8e4f0c82b764ac7c58/href</a></iframe><p>Actually initially i though that i’ll be implementing whole l2_normalize, but after realizing what it costs to just implement “simple” reduce_sum, i fell back to solution with rsqrt and max. <a href="http://developer.download.nvidia.com/compute/cuda/1.1-Beta/x86_website/projects/reduction/doc/reduction.pdf">Just check out <strong>awesome presentation from Mark Harris about parallel reduction</strong></a>.</p><p>Ok, continue, second kernel for max. Compare vector member and compare with “eps” (really small number that prevents division by zero) and take bigger one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/723150772fb252b9af31aea321118111/href">https://medium.com/media/723150772fb252b9af31aea321118111/href</a></iframe><p>Actually implementing this kernel can be avoided by replacing “math_ops.maximum” with “math_ops.add”, but this require reimplementing l2_normalize in your network definition. That’s it, just two CUDA kernels.</p><h3>Implementing IPluginV2 and IPluginCreator</h3><p>In general, you have to just implement two classes IPluginV2 and IPluginCreator, easy! This even can be single .cpp file like in <a href="https://github.com/NVIDIA/TensorRT/tree/9656ef6a1f32211e6d2b3cb172c5d155d2eb0be0/samples/opensource/samplePlugin">“samplePLugin”</a>.</p><p><strong>NOTE:</strong> for 5.1 you have to go with IPluginV2Ext, but in 5.0 it’s not supported yet.</p><p><strong>NOTE:</strong> In older plugin versions, you have to implement <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/c_api/classnvinfer1_1_1_i_plugin_factory.html">IPluginFactory</a>, in newer (from 5.0?) it’s not necessary, but IPluginCreator have to be implemented instead.</p><p>Before implementing your own plugin, i recommend to start with <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-developer-guide/index.html#extending">official docs</a> (which contain many important details). Good starting points are <a href="https://github.com/NVIDIA/TensorRT/tree/9656ef6a1f32211e6d2b3cb172c5d155d2eb0be0/plugin/normalizePlugin">official normalizePlugin</a> from TensorRT repo (thanks for making it opensource, NVIDIA). Or under <a href="https://github.com/NVIDIA/TensorRT/tree/9656ef6a1f32211e6d2b3cb172c5d155d2eb0be0/samples">“samples”</a> there are bunch trivial ones (e.g. samplePlugin is just one file). Below i’ll highlight most important details that took me a time to realize on my own.</p><p><strong>Plugin input</strong> can consist:</p><ul><li>custom parameters (in my case “op_type” and “eps”)</li><li>input vector dimensions C, H, W</li><li>weights (no weights in my case)</li></ul><pre><a href="https://github.com/r7vme/tensorrt_l2norm_helper/blob/master/trt_l2norm_helper/l2norm_helper.h#L35">L2NormHelper(int op_type, float eps, int C, int H, int W);</a></pre><p>At runtime, input values read from serialized buffer (separate constructor required)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64220c60d882f367b7b83b69aa94c8fa/href">https://medium.com/media/64220c60d882f367b7b83b69aa94c8fa/href</a></iframe><p>here are <a href="https://github.com/r7vme/tensorrt_l2norm_helper/blob/9462f7b3dd139193ae12a14314eecfd409145c5e/trt_l2norm_helper/l2norm_helper.h#L118-L133">useful read/write snippets </a>for Serialization/Deserialization from nvidia samples.</p><p><strong>Execution of CUDA kernels</strong> should be called from enqueue</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af4bef42c3264fdfd2add37b510ff472/href">https://medium.com/media/af4bef42c3264fdfd2add37b510ff472/href</a></iframe><p><strong>Input is always a 4D matrix </strong>(in NCHW dimension order) (as far as i can tell). Even if in TF you had 3D matrix (e.g. shape (?,6,2)) in TRT it will be 3D matrix (?,6,2,1). In my case, batch members <a href="https://github.com/r7vme/tensorrt_l2norm_helper/blob/9462f7b3dd139193ae12a14314eecfd409145c5e/trt_l2norm_helper/l2norm_helper.cu#L55">processed sequentially</a> (TODO: this is actually can easily be done in parallel).</p><p><strong>IPluginCreator</strong> stays mostly intact. Main function is createPlugin. It gets values from “PluginFieldCollection” and then creates new instance of a plugin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cf612338ed56a2bcfb1567724bb11b6/href">https://medium.com/media/8cf612338ed56a2bcfb1567724bb11b6/href</a></iframe><p><strong>Plugin registration happens automatically</strong> by adding special line in header.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a493f84e072656884239b361b9e82177/href">https://medium.com/media/a493f84e072656884239b361b9e82177/href</a></iframe><p>After this done, application can use plugin by simply including header file.</p><pre>#include &quot;l2norm_helper.h&quot;</pre><p><strong>Cmake from 3.8 has built-in support for CUDA. </strong>The only problem i was not able to solve is autodetection of gpu compute capabilities (cmake 3.10.2). <a href="# TODO: I did not found a proper way to autoselect cuda compute capability # with cmake 3.10. Set 7.2 for xavier. Otherwise breaks fp16 functions. target_compile_options(trt_l2norm_helper   PRIVATE   # TODO: I did not found a proper way to autoselect cuda compute capability # with cmake 3.10. Set 7.2 for xavier. Otherwise breaks fp16 functions. target_compile_options(trt_l2norm_helper   PRIVATE   $&lt;$&lt;COMPILE_LANGUAGE:CUDA&gt;:-gencode arch=compute_72,code=sm_72&gt; )lt;# TODO: I did not found a proper way to autoselect cuda compute capability # with cmake 3.10. Set 7.2 for xavier. Otherwise breaks fp16 functions. target_compile_options(trt_l2norm_helper   PRIVATE   $&lt;$&lt;COMPILE_LANGUAGE:CUDA&gt;:-gencode arch=compute_72,code=sm_72&gt; )lt;COMPILE_LANGUAGE:CUDA&gt;:-gencode arch=compute_72,code=sm_72&gt; )">Hard-coded value for Xavier</a> (in fp16 branch) (Help appreciated).</p><p>Last, but not least<strong> FP16 (half-precision) support</strong>. I implemented all pieces that are necessary imo (<a href="https://github.com/r7vme/tensorrt_l2norm_helper/tree/fp16support">branch f16support</a>), but still i see that before and after it adds reformat layers. <strong>Is it even possible to use FP16 in custom layer?</strong></p><blockquote>Adding reformat layer: leaky_re_lu_3/LeakyRelu output to be reformatted 0 (leaky_re_lu_3/LeakyRelu) from Half(1,1,1,12) to Float(1,1,1,12) <br>Adding reformat layer: orientation/l2_normalize output to be reformatted 0 (orientation/l2_normalize) from Float(1,1,2,12) to Half(1,1,2,12)</blockquote><p>This was my first own TensorRT plugin, any feedback appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5297ee694d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting Neural Network To TensorRT . Part 1 Using Existing Plugins.]]></title>
            <link>https://r7vme.medium.com/converting-neural-network-to-tensorrt-part-1-using-existing-plugins-edd9c2b9e42a?source=rss-761cb01aca37------2</link>
            <guid isPermaLink="false">https://medium.com/p/edd9c2b9e42a</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorrt]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nvidia]]></category>
            <dc:creator><![CDATA[Roman]]></dc:creator>
            <pubDate>Tue, 09 Jul 2019 19:15:38 GMT</pubDate>
            <atom:updated>2019-07-09T19:32:21.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>Converting Neural Network To TensorRT . Part 1 Using Existing Plugins.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*m2ThnyOrBA_8RJ2UTWAWZg.png" /><figcaption>Every 3D bounding box estimation on image above took only 6 milliseconds.</figcaption></figure><h4><strong>What is TensorRT?</strong></h4><p>TensorRT is a framework from NVIDIA that allows significantly speed-up inference performance of neural network. TensorRT does this by fusing multiple layers together and selecting optimized (cuda) kernels. In addition, lower-precision data type can be used (e.g. float16 or int8). In the end, up to 4x-5x performance boost can be achieved, which is critical for real-time applications.</p><p>TensorRT usually comes together with JetPack (NVIDIA’s software for Jetson series embedded devices). For non-Jetpack installations checkout TensorRT <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-install-guide/index.html">installation guide</a>.</p><p>DISCLAIMER: This post describes specific pitfalls and advanced example with custom layer. For “out-of-the-box” TensorRT examples please check out <a href="https://github.com/NVIDIA-AI-IOT/tf_to_trt_image_classification">tf_to_trt_image_classification</a> repo. NVIDIA has really good tutorials there!</p><p>Example that described in this post has following inference times.</p><ul><li>30 milliseconds TensorFlow</li><li>18 milliseconds TensorRT with FP32 (Floating point 32bit)</li><li><strong>6 milliseconds TensorRT with FP16 (Floating point 16bit)</strong></li></ul><p>As you can see final result is <strong>5x times!!! </strong>faster than pure TensorFlow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yj8aZGd2RFJpQmuApGKiaQ.png" /><figcaption>Inference time in ms</figcaption></figure><p>Blog post divided into two parts: <strong>Part 1 (this):</strong> describes overall workflow and shows how to use existing TensorRT plugins. <strong>Part 2 (</strong><a href="https://medium.com/@r7vme/converting-neural-network-to-tensorrt-part-2-creating-a-custom-layer-5297ee694d8"><strong>link</strong></a><strong>): </strong>shows how to create custom TensorRT layer/plugin.</p><h4>Selecting a neural network</h4><p>As an example i’ll take TensorFlow/Keras based network for 3D bounding boxes estimation (<a href="https://github.com/cersar/3D_detection">code</a>, <a href="https://arxiv.org/abs/1612.00496">paper</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdpLwWZ9lb9h42QyO8MvbA.png" /></figure><p><strong>Why this network?</strong></p><ul><li><strong>l2_normalize operation</strong>, which is not supported by TensorRT (we will build a custom plugin for it)</li><li><strong>LeakyRelu operation</strong> can be replaced with official LRelu_TRT plugin, but unsupported by default. More about official plugins below.</li><li><strong>Flatten layer</strong>, which is able to silently confuse TensorRT and completely ruin network quality. This layer will be replaced with Reshape.</li></ul><h4><strong>General workflow</strong></h4><p>First thing to do is to freeze and optimize your graph . Resulted prorobuf (.pb) file will be used by next steps. <a href="https://github.com/r7vme/3D_detection/blob/97a32622804e56c95ecac33c1c327272f257154c/freeze_and_optimize.py">This script</a> can be used to freeze graph.</p><p>After graph has been frozen:</p><ol><li>Convert TensorFlow protobuf to UFF format (seems UFF used only in TensorRT)</li><li>Convert UFF to TensorRT plan (.engine)</li></ol><p>INFO: TensorRT plan is a serialized binary data compiled exclusively for specific hardware type (i.e. plan for Jetson TX2 only works on Jetson TX2).</p><p>For PyTorch, Caffe or other frameworks workflow is a bit different and not covered here.</p><p>In general, both steps can be done with one python script. But because some TensorRT API functions are not available via Python API (e.g. Deel Learning Accelerator related), most of the <a href="https://github.com/NVIDIA-AI-IOT/tf_to_trt_image_classification/blob/10822955cd9d8747f35faf26338de8742dc914dc/src/uff_to_plan.cpp">NVIDIA official scripts use C++ for the second step</a>. For my plugin (<a href="https://medium.com/@r7vme/converting-neural-network-to-tensorrt-part-2-creating-a-custom-layer-5297ee694d8"><strong>Part 2</strong></a>) I also will use C++ script (feel free to <a href="https://github.com/r7vme/tensorrt_l2norm_helper/pulls">make a PR</a> with pybind to make it work with Python ).</p><p><strong>As baseline example (save it for later ;))</strong>, take a look at the following python script that converts our network (VGG16 backbone) to TensorRT plan. To avoid custom layers l2_normalize operations are removed with “dynamic_graph.remove(node)” (covered in <a href="https://medium.com/@r7vme/converting-neural-network-to-tensorrt-part-2-creating-a-custom-layer-5297ee694d8">Part 2</a>). But before this script can actually work, few modifications in the original network are required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8b32b5c4f1415e8d44e5c3b1be7c3f6/href">https://medium.com/media/b8b32b5c4f1415e8d44e5c3b1be7c3f6/href</a></iframe><h4><strong>Replacing ambiguous operations</strong></h4><p>Even if TensorFlow/Keras operation is supported by TensorRT sometimes it can work in unexpected manner.</p><p><strong>Flatten operation</strong> do not specify exact parameters — (?, ?) — (i.e. depends on input) and for some reason this confuses TensorRT. By default this messes up NN output exactly after this operation. This can be related to the fact that TensorFlow uses NHWC and TensorRT uses NCHW dimentions order. N-number of batches, H — height, W-width, C-channels. So we have to specify exactly what we want and do not rely on TensorRT assumptions about flatten behavior.</p><pre>- x = Flatten()(vgg16_model.output)<br>+ x = Reshape((25088,))(vgg16_model.output)</pre><p><strong>Reshape with “-1”.</strong> TensorRT complains if “-1” is used in reshape operation. In TensorFlow “-1&quot; is a specific case, when exact value will be computed based on input shape.</p><blockquote>UFFParser: Parser error: reshape_2/Reshape: Reshape: -1 dimension specified more than 1 time</blockquote><p>This can be solved by using exact shapes</p><pre>- orientation = Reshape((bin_num, -1))(orientation)<br>+ orientation = Reshape((bin_num, 2))(orientation)</pre><p>NOTE: After above changes we don’t need to retrain network as operations are equal.</p><h4><strong>Replacing LeakyRelu with TensorRT plugin</strong></h4><p>Here is a bit the tricky part. Despite the fact that there is <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/c_api/_nv_infer_plugin_8h.html#a95bea26f16c1e5c739222630599e6ff9">existing plugin for LeakyRelu</a>, it’s not obvious (from docs) how to use it.</p><p>We need a surgeon.</p><p>Turns out this is a pretty simple operation called “<strong>collapse_namespaces</strong>” by <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/python_api/graphsurgeon/graphsurgeon.html">graph surgeon</a>. Graph surgeon as name states is special utility intended to cure graphs via surgery. With graph surgeon you can remove/append/replace nodes. “collapse_namespaces” is intended to replace nodes, that’s it, we specify original node name and prepare new replacement node and collapse_namespaces will do the surgery.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86efdf32f3271cbb64bcc4643019cbe3/href">https://medium.com/media/86efdf32f3271cbb64bcc4643019cbe3/href</a></iframe><p>“negSlope” is alpha coefficient in LeakyRelu. Different plugins can have different attributes.</p><p>Under the hood, if we look on original box3d.pbtxt and box3d-uff.pbtxt (not generated here), original LeakyRelu node (.pbtxt) will be replaced with new plugin node.</p><p>Original TensorFlow node.</p><pre>node {<br>  name: &quot;leaky_re_lu_2/LeakyRelu&quot;<br>  op: &quot;LeakyRelu&quot;<br>  input: &quot;dense_3/BiasAdd&quot;<br>  attr {<br>    key: &quot;T&quot;<br>    value {<br>      type: DT_FLOAT<br>    }<br>  }<br>  attr {<br>    key: &quot;alpha&quot;<br>    value {<br>      f: 0.10000000149011612<br>    }<br>  }<br>}</pre><p>New TRT plugin node.</p><pre>nodes {<br>    id: &quot;leaky_re_lu_2/LeakyRelu&quot;<br>    inputs: &quot;dense_3/BiasAdd&quot;<br>    operation: &quot;_LReLU_TRT&quot;<br>    fields {<br>      key: &quot;negSlope_u_float&quot;<br>      value {<br>        d: 0.1<br>      }<br>    }<br>  }</pre><p><strong>IMPORTANT: </strong>Do not forget to initialize TRT plugins, otherwise TRT will not be able to recognize _LRelu_TRT.</p><p>Python</p><pre>trt.init_libnvinfer_plugins(G_LOGGER, “”)</pre><p>C++</p><pre>nvinfer1::initLibNvInferPlugins(&amp;gLogger, “”)</pre><p>All other TRT plugins listed <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/c_api/_nv_infer_plugin_8h.html">here</a>. All supported operations/layers <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-support-matrix/index.html">here</a>.</p><p>In <a href="https://medium.com/@r7vme/converting-neural-network-to-tensorrt-part-2-creating-a-custom-layer-5297ee694d8">Part 2</a>, I will describe how to create a custom plugin.</p><h4>Environment</h4><ul><li>Nvidia Jetson AGX Xavier</li><li>Jetpack 4.2 (CUDA 10.0.166, TensorRT 5.0.6)</li><li>TensorFlow 1.13.1</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edd9c2b9e42a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DEEP DIVE INTO TENSORFLOW EXAMPLE PARTIAL DIFFERENTIAL EQUATIONS]]></title>
            <link>https://r7vme.medium.com/deep-dive-into-tensorflow-example-partial-differential-equations-909a474717e5?source=rss-761cb01aca37------2</link>
            <guid isPermaLink="false">https://medium.com/p/909a474717e5</guid>
            <category><![CDATA[calculus]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <dc:creator><![CDATA[Roman]]></dc:creator>
            <pubDate>Sat, 05 Jan 2019 00:24:26 GMT</pubDate>
            <atom:updated>2019-01-05T00:24:26.660Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*7hqlXD7hFdBPNSv3DASW_g.jpeg" /></figure><p>This post describes mathematics behind TensorFlow’s tutorial example “Partial differential equations”.</p><p>Please find a Jupyter notebook with blog post under the link below.</p><p><a href="https://colab.research.google.com/github/r7vme/tensorflow-example-pdes/blob/master/pdes.ipynb">https://colab.research.google.com/github/r7vme/tensorflow-example-pdes/blob/master/pdes.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=909a474717e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>