<?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 Pieterluitjens on Medium]]></title>
        <description><![CDATA[Stories by Pieterluitjens on Medium]]></description>
        <link>https://medium.com/@pieterluitjens?source=rss-c9ecbc5d6813------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*eSj0cX2f9sPdqoEyLuDpDw.jpeg</url>
            <title>Stories by Pieterluitjens on Medium</title>
            <link>https://medium.com/@pieterluitjens?source=rss-c9ecbc5d6813------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:31:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pieterluitjens/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[What It Really Takes to Build An AI System]]></title>
            <link>https://medium.com/data-science/what-it-really-takes-to-build-an-ai-system-bd89b935315f?source=rss-c9ecbc5d6813------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd89b935315f</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[management]]></category>
            <dc:creator><![CDATA[Pieterluitjens]]></dc:creator>
            <pubDate>Wed, 17 Feb 2021 19:42:13 GMT</pubDate>
            <atom:updated>2021-02-17T19:42:13.797Z</atom:updated>
            <content:encoded><![CDATA[<h4>It’s more complicated than many think</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ft5tbLX19qojh8UIRBwy8Q.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@charlotte-may">Charlotte May</a> on <a href="https://www.pexels.com/photo/crop-students-doing-research-together-5965676/">Pexels</a></figcaption></figure><p>Today we live in a world of unprecedented open-source code. Companies such as Google and Facebook have put their internal AI solutions in the public domain, a previously unheard of step. There are also plenty of resources today on how to quickly and easily build AI solutions. Despite this, it remains a massive amount of work to develop a real-world AI application to the level of quality and reliability usually required for production deployments, and the amount of work required is frequently underestimated, even by experienced developers and managers. There’s a saying ‘the last 20% of the work takes 80% of the time’ and nowhere is that more true than AI systems.</p><p>In this post I’ll go over some of the key reasons why AI systems take so much effort to build and why it’s frequently a better choice to buy an existing system. This is best highlighted with an example, for which I will refer to a Traffic Sign Recognition (TSR) system I once worked on for an automaker. TSR sounds simple, right? It is also frequently used in ‘Build Your Own Classifier in 5 Minutes’ posts. Well, let’s dive in!</p><h3>Data</h3><h4>Edge Cases. Edge cases everywhere.</h4><p>You probably guessed it, but data usually the number one time and money consumer. This stems from our consistent underestimation of the complexity of the real world, and how many edge cases there are for even the most simple tasks.</p><p>On my TSR project, we encountered all sorts of things. For example, many highways use LED signs, which in addition to looking completely different from normal signs, are difficult to capture with a camera (try filming a computer screen). To solve this, we ended up building a module that would overlay multiple frames to capture a complete image of a sign. The system also had to work in a variety of conditions. At night, the highly reflective signs are much brighter than the surrounding environment, whilst signs are barely visible when driving through fog, rain, or into the sun.</p><p>European signs frequently have a red border, but on old signs this can be almost completely faded away. Additionally, in many European cities, it’s also become trendy to put stickers on signs. Signs were also frequently obscured by plants or other roadside obstacles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmAeBDe1gujG36LGhXrcsw.png" /><figcaption>Traffic signs with various lighting conditions, stickers and age. Images by author</figcaption></figure><p>Even when signs are perfectly visible in good conditions, they can be tricky to identify amongst all the noise. For example, trucks in Europe have speed limit stickers on the back that are identical to roadside signs but that indicate how fast they are allowed to drive. Things also get tricky at highway intersections, as exit speed limit signs can be perfectly visible from the highway itself. And what if the sign is covered in snow, which just so happens to be the same colour as most traffic signs?</p><p>The complexity of the real world isn’t limited to Computer Vision, I recently wrote a complementary article on <a href="https://dev.to/yaysummeriscoming/natural-language-v-regex-the-context-wars-5cb0">regexes in the real world</a>.</p><h4>A good dataset is hard to find</h4><p>Lots of models are published and open-sourced, but the datasets they are trained on for production applications are usually kept under lock &amp; key. Some data (like credit card numbers) are especially hard to obtain. In fact, a ‘data moat’ is the main competitive advantage of many AI companies.</p><p>But what about all of those juicy datasets researchers use, you might wonder? Unfortunately, production applications don’t match up neatly with research tasks. And even if they did, research datasets usually don’t allow for commercial use (e.g. ImageNet). It’s also common to have a lot of labelling errors in research datasets, preventing the development of high quality models. A good example is Google’s OpenImages object detection dataset. Consisting of 1.7 million images with 600 different classes labelled, it could be useful for training object detection models. Unfortunately, the training split has less than half the labels per image that the validation split does, which would imply that a significant number of examples aren’t labelled.</p><p>Datasets for TSR also fall prey to these issues. Freely available TSR datasets don’t allow for commercial use, contain too few examples to be of any real use, and are marred by significant labelling errors. Additionally, they only use examples captured in good lighting conditions in one country. And cars have a pesky habit of travelling into new jurisdictions with different traffic laws and different traffic sign designs.</p><h4>Creating a custom dataset is expensive and time-consuming</h4><p>Why not create your own dataset, you say? Well, let’s have a look at that. First step is to decide on labels/outputs and collect data, making sure every single edge case is captured. Then it’s important to make sure you have good validation and test sets that provide a reliable, balanced snapshot of your performance.</p><p>Next comes the data hygiene and formatting, which can take a lot of time. It’s very important to get this step right. Transformer models, for example suffer a surprisingly large drop in performance when this step isn’t done correctly.</p><p>For most tasks, the data then needs to be labelled. For the projects I’ve worked on, we’ve always built our own labelling tool or modified open source tools, as existing out-of-the-box tools never quite suit the task at hand. You’ll also need data infrastructure to manage, version and serve your new dataset.</p><p>Next, you’ll need to involve some humans to annotate your dataset. If you’re lucky and can share the data outside your organization and your task doesn’t require too much domain knowledge, you might outsource annotation tasks. If not, it takes a ton of work to hire and manage your new team of annotators. In either case, annotator training can also be some work, as most tasks require some domain knowledge and are typically more complicated than clicking on objects in an image. And since turnover in this type of role is high, you can expect to find yourself on that hamster wheel more than you’d expect. One of the best ways to support your annotators is by having an annotation guide they can start with reading before you jump into the annotation and feedback training cycle. Creating the annotation guide itself is a lot of work, as many labels are ambiguous if not defined correctly, often an exhaustive list of examples must be included, along with a living FAQ section that has to be added to as you discover that more and more clarifications are needed to account for the variety of understandings that humans can about a single concept.</p><p>Finally, it’s important to verify your process to ensure it maintains a high quality of output. Annotators also need to label edge cases consistently for the model to work well. For example, at Private AI we’re frequently confronted with thousands of tiny questions on what constitutes sensitive information. For example, “I like Game of Thrones” probably isn’t going to identify someone, but “I like David Lynch’s 1984 rendition of Dune” narrows things down a bit.</p><p>In summary, whilst data annotators can be found quite cheaply, a large amount of valuable dev/management time is required to construct a dataset. As an alternative, you can go to services like Amazon’s Mechanical Turk to outsource part of the process. In my experience however, these services are quite expensive and don’t deliver high quality labels. On top of this, in real projects, the requirements/specifications usually change. This means going over the data multiple times as internal and external requirements (like data protection regulations) change.</p><p>The process of building a dataset has also gotten harder over the last 5 years. The TSR project I worked on was pre-GDPR, and nowadays privacy is a must when collecting data.</p><h3>Model Stuff</h3><h4>You’ve got your data. Now what?</h4><p>Now we’ve arrived at the most visible part of the process: building the model. We can use the plethora of open-source solutions out there, but there’s typically a lot of work to be done fixing small bugs that impact accuracy, accounting for the large variety of possible real-world input types, ensuring the code works as well as it can given the new data and labels you’ve added, etc. A while back I wrote my own MobileNet V3 implementation, as none of the implementations I could find matched the paper — not even the <a href="https://github.com/keras-team/keras-applications/blob/master/keras_applications/mobilenet_v3.py">keras-applications implementation</a>. Similarly at Private AI, getting state-of-the-art models to run at 100% of their capacity has been a lot of work. You also need to make sure that the code allows for commercial use — this typically knocks out a lot of research paper implementations.</p><p>A production system frequently relies on a combination of domain-specific techniques to improve performance, which requires integrating a bunch of different codebases together. Finally everything should be tested, something that open-source code is usually light on. After all, who likes writing tests?</p><h3>Deployment</h3><p>So you’ve gotten the data and you’ve built your model — now it’s time to put it into production. This is another area open-source code is usually light on, even though things have gotten significantly better in the past few years. If your application is to run in the cloud, this can be quite simple (just put your Pytorch model into a Docker container), but that comes with a caveat: running ML in the cloud can get <em>really </em>expensive. Just a few GPU-equipped instances easily cost tens of thousands per year to run. And you’ll typically run in a few different zones to reduce latency.</p><p>Things get significantly more complicated when integrating into mobile apps or embedded systems. In these situations you’re usually forced to run on CPU due to hardware fragmentation (I’m looking at you, Android) or compatibility issues. That TSR project I worked on required all code to be written according to a 30-year-old C standard and had to fit in just a few megabytes! The use of external libraries was also precluded due to issues surrounding safety certification.</p><p>In any case, model optimization is usually necessary. The trouble is that Deep Learning inference packages are at a much lower state of readiness and much harder to use than training tools such as Tensorflow or Pytorch. Recently I converted a transformer model to Intel’s OpenVINO package. Except Intel’s demo example no longer worked with the latest version of Pytorch, so I had to go into OpenVINO’s source code and make some fixes myself.</p><p>Real-world applications also involve more than just running an AI model. There’s normally a lot of pre- and post-processing required, all of which also needs to be productionized. In particular, integration in an application may require porting to the application language (like C++ or Java). On that TSR project, a large amount of code was required to match the detected signs together with the navigation map.</p><p>Finally it’s worth noting that people with expertise in this area are REALLY hard to find.</p><h3>Ongoing Tasks</h3><p>So, we’re at the finish line! Your application is now in production, doing its thing sorting/identifying/talking with widgets. Now comes the ongoing maintenance.</p><p>Like any piece of software, there will be bugs and model prediction failures. In particular (and despite your best efforts), there will be plenty of work to do in collecting the data needed to fill in the edge cases that were missed during the initial data collection phase. The world we live in isn’t static, so data needs to be continually collected and put through the system. A good example is Covid-19. Try asking any pre-2019 chatbot what that is.</p><p>Finally, whilst not strictly necessary, it’s good practice to periodically evaluate and integrate the latest research advancements.</p><h3>Summary</h3><p>So that’s what it <em>really</em> takes to build a production ML application. As you can see, it typically takes a team with diverse specialities such as data science, model deployment to build a complete system, and application domain expertise There remains enormous demand for these skills in 2021, meaning that building up a team can be a very costly exercise. Complicating the matter further is staff turnover, which could mean that the system your company just spent a large amount of time &amp; money building is suddenly unmaintainable, presenting a very real business risk.</p><p>So hopefully this helps you approach your ‘buy vs build’ decision armed with more info. It’s considerably more complicated than ‘oh lets get model X and switch it on’. I’ve seen firsthand and heard many accounts of companies not batting an eyelid at giving hundreds of thousands per year to Amazon/Microsoft/Google for cloud computing, despite 3rd party solutions offering a fraction of the total cost of ownership. If you decide to build yourself, make sure you have a lot of contingency! And consider all the costs like cloud compute, hiring &amp; management.</p><p>And that TSR application? I can say I was quite proud of how well our system worked, but it required many, many <em>decades</em> of developer time to achieve.</p><h4>Further Reading</h4><p><a href="https://towardsdatascience.com/beyond-the-ai-hype-5f72914524af">Beyond the AI hype: What you really need to consider for your startup idea</a></p><p><a href="https://integrate.ai/resources/the-ai-dilemma-build-vs-buy/">https://integrate.ai/resources/the-ai-dilemma-build-vs-buy/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd89b935315f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-it-really-takes-to-build-an-ai-system-bd89b935315f">What It Really Takes to Build An AI System</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Liability & AI]]></title>
            <link>https://medium.com/ai-the-law/liability-ai-c30514e095ec?source=rss-c9ecbc5d6813------2</link>
            <guid isPermaLink="false">https://medium.com/p/c30514e095ec</guid>
            <category><![CDATA[liability]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[law]]></category>
            <dc:creator><![CDATA[Pieterluitjens]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 16:17:27 GMT</pubDate>
            <atom:updated>2020-09-01T16:17:27.405Z</atom:updated>
            <content:encoded><![CDATA[<h4>An AI System Developer’s Perspective</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*IIvQbCbN27FVhHW-" /></figure><p>AI is rapidly being deployed around the world in many different use cases, with few guidelines for manufacturers, developers, and operators to follow. Along with the complexity of creating the technology, there remain many unanswered legal questions. As the CTO of a startup making privacy technologies accessible and easy to integrate, I have spent a significant amount of time thinking at the intersection of privacy, AI, and liability. More recently, I’ve taken a wider lens and have been deliberating over AI and liability overall. While many developers and engineers would rather stay as far away from thinking about the law as possible (I was one of them), that attitude might very well come back to bite us. As AI becomes more ubiquitous, we will be affected by the way failures in AI systems will be arbitrated, and by who and what is deemed to be at fault for a given failure. I was recently given “<strong>Rechtshandbuch Artificial Intelligence und Machine Learning</strong>” (in English: Legal Handbook of Artificial Intelligence and Machine Learning”) an excellent book on the legal implications of AI that covers the matter of liability.</p><p>The book, edited and published by Markus Kaulartz and Tom Braegelmann, provides an overview of one of the most significant legal conundrums our societies are facing; namely, that laws must keep up with technology, but must do so in such a way that does not hinder innovation. We look specifically at Chapter 4.2, written by Maren Wöbbeking, which explores the careful balance that must exist between legal liability and the technologies behind Artificial Intelligence (AI). Key to achieving this balance are accurate risk measurements associated with autonomous systems and carefully attributing responsibility to system manufacturers, system operators, and bystanders.</p><h3>Risks of Autonomous Systems</h3><p>When considering legal liability around autonomous vehicles, for example, one must take into account both (1) the processes for autonomous decision-making and (2) the traceability and explainability of the decisions. It becomes particularly obvious why proper decision-making traceability is essential in order to determine liability when we specifically consider the disastrous effects that human-falsified input data might have on an outcome.</p><p>Wöbbeking quite rightly points out the implications of human interactions with autonomous systems when it comes to determining liability: the majority of autonomous systems still rely heavily on supervised or semi-supervised learning (meaning that one or many humans have to inform the system on which inputs correspond to which outputs at the training phase), and there is a growing literature in adversarial machine learning that’s dedicated to thwarting the many ways in which inputs to an AI system during both inference and training can lead to completely unexpected outputs/outcomes.</p><p>Broadly speaking, end-to-end approaches using a singular, large network yield the best results, but how can one pinpoint failure in such a system? Think of a complex system such as an autonomous car, with multiple sensory inputs such as LIDAR &amp; cameras, what would happen if the camera calibration where to drift? It might be a better idea to build seperate networks with clearly defined inputs &amp; outputs for this reason — but then, this might impact accuracy, increasing the risk of failure.</p><p>In addition to considering potential attacks to AI models through the use of deceptive inputs or even to slight equipment malfunctions that detrimentally modify input signals, as Wöbbeking mentions, it is a human’s responsibility to determine that an autonomous system is being used in the same environment it was trained to run in (i.e., was created for).</p><p>Another aspect of liability law should consider whether appropriate measures were taken in order to mitigate the risks of using AI. Under the constrained environments that AI are currently deployed in, they seem to actually reduce the risk of performing certain tasks when compared to a human performing the same task. Risk mitigation will become increasingly relevant and crucial if autonomous systems are to be deployed in more varied and less constrained environments.</p><h3>Strict Liability</h3><p>Wöbbeking proceeds to discuss which questions might be covered by existing or new liability laws. One particularly difficult question to answer is whether the risks inherent in the state-of-the-art autonomous systems which otherwise reduce risk should be borne by the injured party, the operator, or the manufacturer.</p><p>One possible framework that could apply to autonomous systems is that of strict liability.</p><blockquote><em>“Strict liability differs from ordinary negligence because strict liability establishes liability without fault. In other words, when a defendant is held strictly liable for harm caused to the plaintiff, he is held liable simply because the injury happened.” — </em><a href="https://lawshelf.com/coursewarecontentview/introduction-to-strict-liability/"><em>https://lawshelf.com/coursewarecontentview/introduction-to-strict-liability/</em></a></blockquote><p>The manufacturer of the autonomous system is the party who has the most knowledge and control over the risks and also the most incentive to cut costs. Allocation of responsibility to the manufacturer therefore becomes an extra incentive for them to thoroughly evaluate and mitigate risk. However, holding the manufacturers strictly liable has the very real risk of inhibiting innovation. While manufacturers have a lot more control than operators, they cannot always control whether the operators have deployed a system according to the instructions. Operators themselves often have a choice between either using or not using an autonomous system they are provided with. Their obligations, while limited, are crucial: reducing risk by using the system as instructed.</p><h3>Proportional Liability</h3><p>An alternative framework that could be applied to autonomous systems is that of proportional liability.</p><blockquote><em>“Proportional Liability — refers to an arrangement for the assignment of liability in which each member of a group is held responsible for the financial results of the group in proportion to its participation.” — </em><a href="https://www.irmi.com/term/insurance-definitions/proportional-liability"><em>https://www.irmi.com/term/insurance-definitions/proportional-liability</em></a></blockquote><p>Programmers, data providers, manufacturers, all further developers, third parties manipulating the system, operators, and users all influence the system and contribute to a possible wrong decision. Taking multi-causality into account, while more complex than blaming a single party, might be the right way to assess liability. Propositional liability might bypass any innovation inhibition by the manufacturers, while still holding irresponsible manufacturers more accountable for their lack of risk mitigation. It would help increase the likelihood that operators will take the necessary precautions around autonomous system use.</p><h3>Risk recovery</h3><p>Finally, Wöbbeking postulates that a possible regulation for the allocation of any recourse and liability risks would be to pool the risks through a community insurance solution. Possibly a solution similar to social security law. This would probably avoid the complexities associated with liability law and (among other benefits) would also mitigate the disadvantages of a specific risk allocation.</p><h3>Further commentary</h3><p>Whatever the legal future of AI looks like, there are some clear takeaways for AI system developers on what we can do now to prepare ourselves; namely:</p><ol><li>Clearly document the design &amp; testing process;</li><li>Follow software engineering best practices — e.g. no dynamic allocation of memory and no use of recursion;</li><li>Take great care in designing validation and test sets. And make sure a new test set is used after each major system update;</li><li>Account for bias.</li></ol><h3>Selected Relevant Resources (cited in Kaulartz/Braegelmann)</h3><p><a href="https://ec.europa.eu/digital-single-market/en/news/policy-and-investment-recommendations-trustworthy-artificial-intelligence">https://ec.europa.eu/digital-single-market/en/news/policy-and-investment-recommendations-trustworthy-artificial-intelligence</a></p><p><a href="https://standards.ieee.org/industry-connections/ec/autonomous-systems.html">https://standards.ieee.org/industry-connections/ec/autonomous-systems.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c30514e095ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-the-law/liability-ai-c30514e095ec">Liability &amp; AI</a> was originally published in <a href="https://medium.com/ai-the-law">AI &amp; the Law</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accelerating Tensorflow Lite with XNNPACK]]></title>
            <link>https://medium.com/data-science/accelerating-tensorflow-lite-with-xnnpack-ece7dc8726d0?source=rss-c9ecbc5d6813------2</link>
            <guid isPermaLink="false">https://medium.com/p/ece7dc8726d0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tensorflow-lite]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-engineering]]></category>
            <category><![CDATA[inference]]></category>
            <dc:creator><![CDATA[Pieterluitjens]]></dc:creator>
            <pubDate>Fri, 12 Jun 2020 16:40:22 GMT</pubDate>
            <atom:updated>2020-06-13T16:25:38.713Z</atom:updated>
            <content:encoded><![CDATA[<h4>The new Tensorflow Lite XNNPACK delegate enables best in-class performance on x86 and ARM CPUs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*urM2hWRDX8tRFGr0.jpg" /><figcaption>Photo by SpaceX on <a href="https://www.flickr.com/photos/spacex/49421604803https://www.flickr.com/photos/spacex/49421604803">Flickr</a></figcaption></figure><p>TL;DR: The new Tensorflow Lite XNNPACK delegate enables best in-class performance on x86 and ARM CPUs — over 10x faster than the default Tensorflow Lite backend in some cases.</p><p>Tensorflow Lite is one of my favourite software packages. It enables easy and fast deployment on a range of hardware and now comes with a wide range of delegates to accelerate inference — GPU, Core ML and Hexagon, to name a few. One drawback of Tensorflow Lite however is that it’s been designed with mobile applications in mind, and therefore isn’t optimised for Intel &amp; AMD x86 processors. Better x86 support is on the Tensorflow Lite development <a href="https://www.tensorflow.org/lite/guide/roadmap">roadmap</a>, but for now Tensorflow Lite mostly relies on converting ARM Neon instructions to SSE via the Neon_2_SSE bridge.</p><p>There is however a new Tensorflow Lite delegate for CPU-based floating-point computations, XNNPACK, that does feature x86 AVX and AVX-512 optimizations. In this post I’ll walk you through using XNNPACK and show some benchmarks.</p><h3>Installing &amp; Using XNNPACK</h3><p>Instructions for using XNNPACK can be found <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/delegates/xnnpack">here</a>. Most notably, there’s now a build flag that will enable the XNNPACK delegate by default. This is handy, as until now it wasn’t possible to load Tensorflow Lite delegates in Python. The command to build Tensorflow from source would look like:</p><pre>bazel build --define tflite_with_xnnpack=true \ <br>  //tensorflow/tools/pip_package:build_pip_package</pre><p>The Tensorflow Lite <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/tools/benchmark#on-android">benchmark tool</a> also now has a flag to enable the XNNPACK delegate. For example, to profile on your x86 machine, first build the profiler tool:</p><pre>bazel build -c opt --verbose_failures \    <br>  tensorflow/lite/tools/benchmark:benchmark_model</pre><p>Then run the profiler with the following command:</p><pre>bazel-bin/tensorflow/lite/tools/benchmark/benchmark_model \<br>  --graph=&lt;model path&gt; --warmup_runs=50 --num_runs=1000 \<br>  --enable_op_profiling=true --use_xnnpack=true</pre><h3>Optimizing for XNNPACK</h3><p>It is important to ensure that models are suitable for XNNPACK, as it only supports a subset of all Tensorflow Lite operators. For example, the standard Keras implementations often use explicit padding layers and implement the top global pooling layer via the mean operator. When using the normal TFLite backend this only increases runtime by a few percentage points, but these operations aren’t supported by XNNPACK, resulting in considerable overhead — 30% in the case of MobileNet V2 with 8 threads(see below)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d49SeJX0byxthP4FLltg9Q.png" /></figure><p>Padding is easily fixed by replacing the explicit padding layers with padding built into the convolution operations:</p><pre># Before<br>x = layers.ZeroPadding2D(padding=((3, 3), (3, 3)), name=&#39;conv1_pad&#39;)(img_input)<br>x = layers.Conv2D(64, 7, strides=2, use_bias=use_bias, name=&#39;conv1_conv&#39;, padding=&#39;valid&#39;)(x)</pre><pre># After<br>x = layers.Conv2D(64, 7, strides=2, use_bias=use_bias, name=&#39;conv1_conv&#39;, padding=&#39;same&#39;)(img_input)</pre><p>The global average pooling layer can be replaced by a average pooling layer with a large kernel:</p><pre># Before<br>x = layers.GlobalAveragePooling2D()(x)<br>x = layers.Dense(classes, activation=&#39;softmax&#39;)(x)</pre><pre># After<br># Use XNNPACK compatible average pooling<br>x = layers.AveragePooling2D(pool_size=(7, 7))(x)<br>    <br># Implement the top dense layer as a convolution, so we don&#39;t need to remove spatial dims<br>x = layers.Conv2D(classes, kernel_size=1)(x)<br>x = layers.Softmax()(x)</pre><p>Note that you will have to retrain the model. You can find fixed versions of these models in the repo accompanying this article <a href="https://github.com/yaysummeriscoming/xnnpack_benchmarks">here</a>.</p><h3>Benchmarks</h3><h4>ARM</h4><p>Ok, so benchmarks! First I decided to test MobileNet V3 on my Galaxy S8:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABvU6g5jZR-PePxi4sQItA.png" /></figure><p>I tested using 1 thread over 1000 iterations, with 50 warm up iterations.</p><p>As you can see, XNNPACK offers excellent performance, on top of the standard Tensorflow Lite CPU backend. It’s worth noting that XNNPACK supports ARM Float 16 instructions included in newer ARMv8.2-A CPUs (e.g., A55), but unfortunately I don’t have one on hand. The GPU backend is still faster, especially for larger models. However, it requires OpenGL ES 3.1 or higher, which is only available on ~2/3 of all Android devices (see market share <a href="https://developer.android.com/about/dashboards">here</a>.</p><h4>x86</h4><p>Now on to x86. I decided to compare against Intel’s OpenVino package using MobileNet V2 and ResNet50. For testing I used a Google Cloud N2 Cascade Lake instance, with 8 vCPUs. With 1 thread:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLBa_ZPnrmH0t_ZSjCX-fQ.png" /></figure><p>And 8 threads:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*St-EGIFwQ38w6Pk1H8BMJQ.png" /></figure><p>As you can see, Tensorflow Lite using the XNNPACK delegate performs admirably, in some cases over 10x faster than the default Tensorflow Lite backend. Performance approaches that of OpenVino for MobileNet V2, but falls short for ResNet 50. I don’t see this as a huge issue however, as depthwise convolution based architectures such as MobileNet V2 are far better suited for CPU deployment. XNNPACK also features better scaling over multiple CPU cores than the standard backend. Note that the TFLite benchmark tool corresponds to OpenVINO’s latency mode, so it would be interesting to see what XNNPACK could deliver if configured for throughput.</p><h3>Summary</h3><p>Tensorflow Lite can now offer great x86 performance via the new XNNPACK delegate, outperforming Intel’s OpenVino package in some cases. The main drawback of XNNPACK is that it is designed for floating point computation only. 8-bit model quantization can easily result in a &gt;2x performance increase, with an even higher increase when deployed on the new Intel Cascade Lake CPUs which support AVX-512 VNNI instructions. Support for 8-bit quantization on x86 is on the Tensorflow Lite roadmap, perhaps even in the <a href="https://github.com/tensorflow/tensorflow/issues/34536">next release</a>.</p><p>Similarly, for mobile deployments, XNNPACK outperforms the Tensorflow Lite default backend. Whilst the GPU delegate is still faster than XNNPACK, XNNPACK is useful on devices that don’t support GPU computation.</p><p>I’m especially excited about XNNPACK because it simplifies the deployment process by allowing one to stay within the Tensorflow ecosystem. It is now possible to convert a model once with Tensorflow Lite and deploy to multiple platforms, reducing the number of different software packages required. It’s also worth noting that AMD processors are becoming less of a rarity, and OpenVino is an Intel product. I tried to test on a Google Cloud N2D EYPC instance, but unfortunately, I couldn’t get my quota increased.</p><p>I hope you found this article helpful. The code to reproduce these benchmarks is located <a href="https://github.com/yaysummeriscoming/mobilenet_v3_tflite">here</a> and <a href="https://github.com/yaysummeriscoming/xnnpack_benchmarks">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ece7dc8726d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/accelerating-tensorflow-lite-with-xnnpack-ece7dc8726d0">Accelerating Tensorflow Lite with XNNPACK</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NVIDIA DALI: Speeding up PyTorch]]></title>
            <link>https://medium.com/data-science/nvidia-dali-speeding-up-pytorch-876c80182440?source=rss-c9ecbc5d6813------2</link>
            <guid isPermaLink="false">https://medium.com/p/876c80182440</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pre-processing]]></category>
            <dc:creator><![CDATA[Pieterluitjens]]></dc:creator>
            <pubDate>Wed, 22 Jan 2020 00:34:23 GMT</pubDate>
            <atom:updated>2020-03-20T08:44:32.087Z</atom:updated>
            <content:encoded><![CDATA[<h4>Some techniques to improve DALI resource usage &amp; create a completely CPU-based pipeline. Up to 4x faster PyTorch training</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nv8KUH2eNlhVK-jheFkmfQ.jpeg" /></figure><p>TL;DR: I showcase some techniques to improve DALI resource usage &amp; create a completely CPU-based pipeline. These techniques stabilize long-term memory usage and allow for ~50% larger batch size compared to the example CPU &amp; GPU pipelines provided with the DALI package. Testing with a Tesla V100 accelerator shows that PyTorch+DALI can reach processing speeds of nearly 4000 images/s, ~4X faster than native PyTorch.</p><p>Update 20/3/2019: DALI 0.19 features improved memory management, eliminating the gradual rise in memory usage (<a href="https://github.com/NVIDIA/DALI/issues/278">278</a>). I’d still recommend to re-import DALI when using the GPU pipeline however in order to reduce GPU memory usage.</p><h3>Introduction</h3><p>The last couple of years have seen tremendous progress on the Deep Learning hardware front. Nvidia’s latest offerings, the Tesla V100 &amp; Geforce RTX series, contain dedicated tensor cores to accelerate the operations commonly used in neural networks. The V100, in particular, has enough power to train neural networks at thousands of images per second, bringing single-GPU training on the ImageNet dataset down to just a few hours for small models. That’s a far cry from the 5 days it took to train the AlexNet model on ImageNet in 2012!</p><p>Such powerful GPUs strain the data preprocessing pipeline. To account for this, Tensorflow released a new data loader: tf.data.Dataset. The pipeline is written in C++ and uses a graph-based approach whereby multiple preprocessing operations are chained together to form a pipeline. PyTorch on the other hand uses a data loader written in Python on top of the PIL library — great for ease of use and flexibility, not so great for speed. Although the PIL-SIMD library does improve the situation a bit.</p><p>Enter the NVIDIA Data Loading Library (DALI): designed to remove the data preprocessing bottleneck, allowing for training and inference to run at full speed. DALI is primarily designed to do preprocessing on a GPU, but most operations also have a fast CPU implementation. This articles focuses on PyTorch, however DALI also supports Tensorflow, MXNet &amp; TensorRT. TensorRT support, in particular, is great. It allows for both the training and inference steps to use the exact same preprocessing code. Different frameworks like Tensorflow &amp; PyTorch typically feature small differences between the data loaders, which might end up affecting accuracy.</p><p>Below are some great resources to get started with DALI:</p><p><a href="https://developer.nvidia.com/DALI">DALI Home</a></p><p><a href="https://devblogs.nvidia.com/fast-ai-data-preprocessing-with-nvidia-dali/">Fast AI Data Preprocessing with NVIDIA DALI</a></p><p><a href="https://docs.nvidia.com/deeplearning/sdk/dali-developer-guide/docs/index.html">DALI Developer Guide</a></p><p><a href="https://docs.nvidia.com/deeplearning/sdk/dali-developer-guide/docs/examples/getting%20started.html">Getting Started</a></p><p>For the remainder of this article I’m going to assume a basic familiarity with ImageNet preprocessing and the <a href="https://github.com/NVIDIA/DALI/blob/master/docs/examples/pytorch/resnet50/main.py">DALI ImageNet example</a>. I’ll discuss some issues that I ran up against whilst using DALI, along with how I got around them. We’ll look at both CPU and GPU pipelines.</p><h3>DALI Long-Term Memory Usage</h3><p>Update 20/3/2019: This issue has been fixed in DALI 0.19</p><p>The first issue I encountered with DALI is that RAM usage increases with every training epoch, causing OOM errors (even on a VM with 78GB RAM). This has been flagged (<a href="https://github.com/NVIDIA/DALI/issues/278">278</a>, <a href="https://github.com/NVIDIA/DALI/issues/344">344</a>, <a href="https://github.com/NVIDIA/DALI/issues/486">486</a>), but has yet to be fixed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3atcaNFm3mTcvhCugwI1Lw.png" /></figure><p>The only solution I could find wasn’t pretty — reimport DALI &amp; recreate the train &amp; validation pipelines at every epoch:</p><pre>del self.train_loader, self.val_loader, self.train_pipe, self.val_pipe<br>torch.cuda.synchronize()<br>torch.cuda.empty_cache()<br>gc.collect()</pre><pre>importlib.reload(dali)<br>from dali import HybridTrainPipe, HybridValPipe, DaliIteratorCPU, DaliIteratorGPU</pre><pre>&lt;rebuild DALI pipeline&gt;</pre><p>Note that, with this workaround, DALI still requires a lot of RAM to get the best results. Given how cheap RAM is nowadays (relative to Nvidia GPUs at least) this isn’t much of a concern; rather, GPU memory is more of a problem. As can be seen from the table below, the maximum batch size possible whilst using DALI is as much as 50% lower than TorchVision:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JEx7IapPCETQzaDQP6-kQA.png" /></figure><p>In the following sections, I’ll cover some approaches to reduce GPU memory usage.</p><h3>Building a Completely CPU-based Pipeline</h3><p>Let’s look at the example <a href="https://github.com/NVIDIA/DALI/blob/master/docs/examples/pytorch/resnet50/main.py">CPU pipeline</a> first. The CPU-based pipeline is useful for when peak throughput isn’t required (e.g., when working with medium &amp; large sized models like ResNet50). The CPU training pipeline only does the decoding &amp; resizing operations on CPU however, with the CropMirrorNormalize operation running on GPU. This is significant. I found that even just transferring the output to GPU with DALI used a lot of GPU memory. To circumvent this, I modified the <a href="https://github.com/NVIDIA/DALI/blob/master/docs/examples/pytorch/resnet50/main.py">example CPU pipeline</a> to run entirely on CPU:</p><pre>class HybridTrainPipe(Pipeline):<br>    def __init__(self, batch_size, num_threads, device_id, data_dir, crop,<br>                 mean, std, local_rank=0, world_size=1, dali_cpu=False, shuffle=True, fp16=False,<br>                 min_crop_size=0.08):<br><br>        # As we&#39;re recreating the Pipeline at every epoch, the seed must be -1 (random seed)<br>        super(HybridTrainPipe, self).__init__(batch_size, num_threads, device_id, seed=-1)<br><br>        # Enabling read_ahead slowed down processing ~40%<br>        self.input = ops.FileReader(file_root=data_dir, shard_id=local_rank, num_shards=world_size,<br>                                    random_shuffle=shuffle)<br><br>        # Let user decide which pipeline works best with the chosen model<br>        if dali_cpu:<br>            decode_device = &quot;cpu&quot;<br>            self.dali_device = &quot;cpu&quot;<br>            self.flip = ops.Flip(device=self.dali_device)<br>        else:<br>            decode_device = &quot;mixed&quot;<br>            self.dali_device = &quot;gpu&quot;<br><br>            output_dtype = types.FLOAT<br>            if self.dali_device == &quot;gpu&quot; and fp16:<br>                output_dtype = types.FLOAT16<br><br>            self.cmn = ops.CropMirrorNormalize(device=&quot;gpu&quot;,<br>                                               output_dtype=output_dtype,<br>                                               output_layout=types.NCHW,<br>                                               crop=(crop, crop),<br>                                               image_type=types.RGB,<br>                                               mean=mean,<br>                                               std=std,)<br><br>        # To be able to handle all images from full-sized ImageNet, this padding sets the size of the internal nvJPEG buffers without additional reallocations<br>        device_memory_padding = 211025920 if decode_device == &#39;mixed&#39; else 0<br>        host_memory_padding = 140544512 if decode_device == &#39;mixed&#39; else 0<br>        self.decode = ops.ImageDecoderRandomCrop(device=decode_device, output_type=types.RGB,<br>                                                 device_memory_padding=device_memory_padding,<br>                                                 host_memory_padding=host_memory_padding,<br>                                                 random_aspect_ratio=[0.8, 1.25],<br>                                                 random_area=[min_crop_size, 1.0],<br>                                                 num_attempts=100)<br><br>        # Resize as desired.  To match torchvision data loader, use triangular interpolation.<br>        self.res = ops.Resize(device=self.dali_device, resize_x=crop, resize_y=crop,<br>                              interp_type=types.INTERP_TRIANGULAR)<br><br>        self.coin = ops.CoinFlip(probability=0.5)<br>        print(&#39;DALI &quot;{0}&quot; variant&#39;.format(self.dali_device))<br><br>    def define_graph(self):<br>        rng = self.coin()<br>        self.jpegs, self.labels = self.input(name=&quot;Reader&quot;)<br><br>        # Combined decode &amp; random crop<br>        images = self.decode(self.jpegs)<br><br>        # Resize as desired<br>        images = self.res(images)<br><br>        if self.dali_device == &quot;gpu&quot;:<br>            output = self.cmn(images, mirror=rng)<br>        else:<br>            # CPU backend uses torch to apply mean &amp; std<br>            output = self.flip(images, horizontal=rng)<br><br>        self.labels = self.labels.gpu()<br>        return [output, self.labels]</pre><p>The DALI pipeline now outputs an 8-bit tensor on the CPU. We need to use PyTorch to do the CPU-&gt; GPU transfer, the conversion to floating point numbers, and the normalization. These last two ops are done on GPU, given that, in practice, they’re very fast and they reduce the CPU -&gt; GPU memory bandwidth requirement. I tried pinning the tensor before transferring to GPU, but didn’t manage to get any performance uplift from doing so. Putting it together with a prefetcher:</p><pre>def _preproc_worker(dali_iterator, cuda_stream, fp16, mean, std, output_queue, proc_next_input, done_event, pin_memory):<br>    &quot;&quot;&quot;<br>    Worker function to parse DALI output &amp; apply final preprocessing steps<br>    &quot;&quot;&quot;<br><br>    while not done_event.is_set():<br>        # Wait until main thread signals to proc_next_input -- normally once it has taken the last processed input<br>        proc_next_input.wait()<br>        proc_next_input.clear()<br><br>        if done_event.is_set():<br>            print(&#39;Shutting down preproc thread&#39;)<br>            break<br><br>        try:<br>            data = next(dali_iterator)<br><br>            # Decode the data output<br>            input_orig = data[0][&#39;data&#39;]<br>            target = data[0][&#39;label&#39;].squeeze().long()  # DALI should already output target on device<br><br>            # Copy to GPU and apply final processing in separate CUDA stream<br>            with torch.cuda.stream(cuda_stream):<br>                input = input_orig<br>                if pin_memory:<br>                    input = input.pin_memory()<br>                    del input_orig  # Save memory<br>                input = input.cuda(non_blocking=True)<br><br>                input = input.permute(0, 3, 1, 2)<br><br>                # Input tensor is kept as 8-bit integer for transfer to GPU, to save bandwidth<br>                if fp16:<br>                    input = input.half()<br>                else:<br>                    input = input.float()<br><br>                input = input.sub_(mean).div_(std)<br><br>            # Put the result on the queue<br>            output_queue.put((input, target))<br><br>        except StopIteration:<br>            print(&#39;Resetting DALI loader&#39;)<br>            dali_iterator.reset()<br>            output_queue.put(None)<br><br><br>class DaliIteratorCPU(DaliIterator):<br>    &quot;&quot;&quot;<br>    Wrapper class to decode the DALI iterator output &amp; provide iterator that functions in the same way as TorchVision.<br>    Note that permutation to channels first, converting from 8-bit integer to float &amp; normalization are all performed on GPU<br><br>    pipelines (Pipeline): DALI pipelines<br>    size (int): Number of examples in set<br>    fp16 (bool): Use fp16 as output format, f32 otherwise<br>    mean (tuple): Image mean value for each channel<br>    std (tuple): Image standard deviation value for each channel<br>    pin_memory (bool): Transfer input tensor to pinned memory, before moving to GPU<br>    &quot;&quot;&quot;<br>    def __init__(self, fp16=False, mean=(0., 0., 0.), std=(1., 1., 1.), pin_memory=True, **kwargs):<br>        super().__init__(**kwargs)<br>        print(&#39;Using DALI CPU iterator&#39;)<br>        self.stream = torch.cuda.Stream()<br><br>        self.fp16 = fp16<br>        self.mean = torch.tensor(mean).cuda().view(1, 3, 1, 1)<br>        self.std = torch.tensor(std).cuda().view(1, 3, 1, 1)<br>        self.pin_memory = pin_memory<br><br>        if self.fp16:<br>            self.mean = self.mean.half()<br>            self.std = self.std.half()<br><br>        self.proc_next_input = Event()<br>        self.done_event = Event()<br>        self.output_queue = queue.Queue(maxsize=5)<br>        self.preproc_thread = threading.Thread(<br>            target=_preproc_worker,<br>            kwargs={&#39;dali_iterator&#39;: self._dali_iterator, &#39;cuda_stream&#39;: self.stream, &#39;fp16&#39;: self.fp16, &#39;mean&#39;: self.mean, &#39;std&#39;: self.std, &#39;proc_next_input&#39;: self.proc_next_input, &#39;done_event&#39;: self.done_event, &#39;output_queue&#39;: self.output_queue, &#39;pin_memory&#39;: self.pin_memory})<br>        self.preproc_thread.daemon = True<br>        self.preproc_thread.start()<br><br>        self.proc_next_input.set()<br><br>    def __next__(self):<br>        torch.cuda.current_stream().wait_stream(self.stream)<br>        data = self.output_queue.get()<br>        self.proc_next_input.set()<br>        if data is None:<br>            raise StopIteration<br>        return data<br><br>    def __del__(self):<br>        self.done_event.set()<br>        self.proc_next_input.set()<br>        torch.cuda.current_stream().wait_stream(self.stream)<br>        self.preproc_thread.join()</pre><h3>GPU-Based Pipeline</h3><p>In my testing, the new full CPU pipeline detailed above is about twice as fast as TorchVision’s data loader, whilst achieving nearly the same maximum batch size. The CPU pipeline works great with large models like ResNet50; however, when using small models like AlexNet or ResNet18, the CPU pipeline still isn’t able to keep up with the GPU. For these cases, the <a href="https://github.com/NVIDIA/DALI/blob/master/docs/examples/pytorch/resnet50/main.py">example GPU pipeline</a> works best. The trouble is that the GPU pipeline reduces the maximum possible batch size by almost 50%, limiting throughput.</p><p>One way to significantly reduce GPU memory usage is by keeping the validation pipeline off the GPU until it’s actually needed at the end of an epoch. This is easy to do as we’re already reimporting the DALI library and recreating data loaders at every epoch.</p><h3>More Tips</h3><p>More tips for using DALI:</p><p>* For validation, a batch size that evenly divides the dataset size works best e.g. 500 instead of 512 for a validation set size of 50000 — this avoids a partial batch at the end of the validation dataset.</p><p>* Similar to the Tensorflow &amp; PyTorch data loaders, the TorchVision and DALI pipelines don’t produce bit-identical outputs — you’ll see the validation accuracies differ slightly. I found that this is due to different JPEG image decoders. There was previously an issue with resizing but this is now fixed. The flipside is that DALI supports TensorRT, allowing for the exact same preprocessing to be used for training &amp; inference.</p><p>* For peak throughput, try setting the number of data loader workers to number_of_virtual_CPU cores. 2 gave the best performance (2 virtual cores = 1 physical core)</p><p>* If you want absolute best performance and don’t care about having outputs similar to TorchVision, try turning off triangular interpolation on the DALI image resize</p><p>* Don’t forget about disk IO. Make sure you have enough RAM to cache the dataset and/or a really fast SSD. DALI can pull up to 400Mb/s from disk!</p><h3>Putting it Together</h3><p>To help integrate these modifications easily, I created a <a href="https://github.com/yaysummeriscoming/DALI_pytorch_demo/blob/master/dataloader.py">data loader class</a> with all the modifications described here, including both DALI and TorchVision backends. Usage is simple. Instantiate the data loader:</p><pre>dataset = Dataset(data_dir, <br>                  batch_size,<br>                  val_batch_size<br>                  workers,<br>                  use_dali,<br>                  dali_cpu,<br>                  fp16)</pre><p>Then get the train &amp; validation data loaders:</p><pre>train_loader = dataset.get_train_loader()<br>val_loader = dataset.get_val_loader()</pre><p>Reset the data loader at the end of every training epoch:</p><pre>dataset.reset()</pre><p>Optionally, the validation pipeline can be recreated on GPU prior to model validation:</p><pre>dataset.prep_for_val()</pre><h3>Benchmarks</h3><p>Here are the max batch sizes I was able to use with ResNet18:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5DbQfYjwI0LBUm8w4YSWw.png" /></figure><p>So, by applying these modifications, the max batch size DALI can use in both CPU &amp; GPU modes is increased by ~50%!</p><p>Here are some throughput figures with Shufflenet V2 0.5 &amp; batch size 512:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHlv_-Uwy4a4f_J-yagOMQ.png" /></figure><p>And here are some results of using the DALI GPU pipeline to train various networks included in TorchVision:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4kLD3jk0wSElVbXnhsURg.png" /></figure><p>All tests were run on a Google Cloud V100 instance with 12 vCPUs (6 physical cores), 78GB RAM &amp; using Apex FP16 training. To reproduce these results, use the following arguments:<br> — fp16 — batch-size 512 — workers 10 — arch “shufflenet_v2_x0_5 or resnet18” — prof — use-dali</p><p>So, with DALI, a single Tesla V100 can reach speeds of nearly 4000 image/s! That’s just over half of what Nvidia’s super expensive DGX-1 with 8 V100 GPUs can do (albeit using small models). For me, being able to do an ImageNet training run on a single GPU in a few hours was a productivity game changer. Hopefully it will be for you as well. Feedback appreciated!</p><p>The code presented in this article is <a href="https://github.com/yaysummeriscoming/DALI_pytorch_demo">here</a></p><h3>Acknowledgements</h3><p>Many thanks to Patricia Thaine for her feedback on an earlier draft of this post.</p><p>Cover image by <a href="https://pixabay.com/users/JacekAbramowicz-1981807/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1201077">Jacek Abramowicz</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=876c80182440" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/nvidia-dali-speeding-up-pytorch-876c80182440">NVIDIA DALI: Speeding up PyTorch</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>