<?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 Omri Bar on Medium]]></title>
        <description><![CDATA[Stories by Omri Bar on Medium]]></description>
        <link>https://medium.com/@baromri?source=rss-486b68bc632a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*X2lBcwzSDZYCdwXhwgAO1g.jpeg</url>
            <title>Stories by Omri Bar on Medium</title>
            <link>https://medium.com/@baromri?source=rss-486b68bc632a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:51:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baromri/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[Using OpenCode with Local Models on an Old Intel Mac]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/using-opencode-with-local-models-on-an-old-intel-mac-59dabdd1cfb1?source=rss-486b68bc632a------2"><img src="https://cdn-images-1.medium.com/max/1200/0*sbKADsdB1hjQUw_i.png" width="1200"></a></p><p class="medium-feed-snippet">A practical guide to running an isolated autonomous coding agent with native Ollama inference on an old Intel MacBook Pro.</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/using-opencode-with-local-models-on-an-old-intel-mac-59dabdd1cfb1?source=rss-486b68bc632a------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/using-opencode-with-local-models-on-an-old-intel-mac-59dabdd1cfb1?source=rss-486b68bc632a------2</link>
            <guid isPermaLink="false">https://medium.com/p/59dabdd1cfb1</guid>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[local-model]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[open-code]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Omri Bar]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 15:03:16 GMT</pubDate>
            <atom:updated>2026-09-04T15:03:16.681Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Consolidating AI Performance Measurement in Production]]></title>
            <link>https://medium.com/theator/consolidating-ai-performance-measurement-in-production-8e3605328999?source=rss-486b68bc632a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e3605328999</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[metrics-and-analytics]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[error-analysis]]></category>
            <category><![CDATA[metrics]]></category>
            <dc:creator><![CDATA[Omri Bar]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 10:09:18 GMT</pubDate>
            <atom:updated>2024-03-03T10:09:18.633Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Embracing a Single Holistic Metric</strong></h4><p>This blog post is all about metrics. Metrics are key to a successful machine learning (ML) project. Success is tricky to measure, as outperforming state-of-the-art in an interesting benchmark or publishing a paper on a new method you developed are significant success milestones. But in the scope of this post, I mean a project that reaches the production environment and impacts users in a meaningful way.</p><p>The main takeaway I will try to convey is that metrics used during development phases might not be an optimal representation of production performance. I will also suggest a more consolidated and streamlined approach to quantifying the impact of an ML system on the users in the production environment.</p><p>The transition to a single holistic metric discussed in this blog post is mainly suited to a system that provides many prediction outputs for each input sample, as this case raises a complex environment for measuring the end performance.</p><h3>So what is the problem with the metrics I know and love?</h3><p>When starting to work on a machine learning project, we usually begin with defining the project goal and determining what we want to achieve by setting the main key performance indicators (KPIs). With this goal in mind, we can start exploring two main components of a new problem: <em>what data do I need?</em> and <em>what metrics should I use?</em></p><p>Focusing on metrics, we can roughly state that each machine learning task usually requires 1–3 main measurements of success. Those metrics will be the lighthouse for the researcher to optimize on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvGHYZUgPmwLfVAF6tJTYw.jpeg" /><figcaption>Image created by <a href="https://clipdrop.co/stable-diffusion">Stable Diffusion</a></figcaption></figure><p>However, lighthouse metrics can be confusing and lead to different research directions. For example, a standard metric in classification problems is accuracy. But during training as part of the back propagation process, a loss function, such as <a href="https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html">cross-entropy loss</a>, is used to adjust the model weights based on gradient information. Now is cross-entropy always a good proxy correlated to accuracy?</p><p>The byproduct of this process yields a model that can operate — at best — on a specific dev dataset in a somewhat sterilized dev environment.</p><p>Note to avoid confusion, I’m not referring directly to a generalization or overfitting issue, as these can be measured and tackled, but more to how a model will act in production when <em>in-the-wild</em> scenarios occur.</p><p>Now let’s consider a complex ML-based system built in a chain manner, particularly in cases when one model’s output is the input of one or many other models. In this setup, the system can fail if one part of the chain fails. This is not a failure as in raising an error, but a failure mode in the quality of the end results. Such degradation impacts the end-user experience in a way that is hard to measure using commonly used metrics.</p><p>With this in mind, I would like to show how to transition to a single holistic metric, called an <em>impact metric</em>, that represents the end performance of your entire AI system as viewed by your designated users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9LE88rCn0Y5Znz34Es8cg.png" /></figure><h3>Learning by example</h3><p>In order to dive into the impact metric development, I need an example of data and related annotations. I’ll use the following example of data and annotations structure:</p><p>Given a video as input, a team of annotators review the video and tag/mark specific key moments based on designated instructions.</p><p>A single action annotation uses a structure of three elements: [action type, start time, end time]. That is, classifying the action into a specific type while marking its start and end times (in seconds).</p><p>For example, in the following two videos, taken from the <a href="https://arxiv.org/abs/1705.06950v1">Kinetics 400 Dataset</a>, the expected annotations are [throwing_discus, 6, 8] and [throwing_discus, 0, 2].</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeRJbvUAjsNA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeRJbvUAjsNA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeRJbvUAjsNA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e86158b94689a9286500fd508789d188/href">https://medium.com/media/e86158b94689a9286500fd508789d188/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5_CCNGezogo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5_CCNGezogo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5_CCNGezogo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef28e88a638ef3e3a8a5b6bddd29d9e6/href">https://medium.com/media/ef28e88a638ef3e3a8a5b6bddd29d9e6/href</a></iframe><p>Note that although this is a relatively specific example common in video understanding tasks, the same paradigm works in any setting and setup you might have in your domain, whether video-related or not, as long as the system provides multiple predictions for a given input.</p><p>Now imagine the process of manually annotating a large-scale dataset as described above using [type, start, end] and how lengthy this process would be. This would be even harder when handling videos with an extended duration, for example, in the case of self-driving cars, sports, or the <a href="https://www.nature.com/articles/s41598-020-79173-6">surgical domain</a>.</p><p>To expedite the annotation process and make it faster, more effective, cheaper, and scalable, a computer vision system can be developed to assist the annotators’ workflow. This system can predict these actions as an initial guess and the annotators can then review, fix, add, or delete. As the system improves over time, the entire annotation process can transition into an “only” validation process.</p><p>From a researcher’s point of view, during the development of the model, the focus would be on optimizing specific metrics such as <em>accuracy per second</em> or <em>mean average precision</em> (mAP) — but does this represent well enough the experience that annotators would have once this model is deployed?</p><h3>Developing a single holistic metric - <em>Impact Metric</em></h3><p>Our goal was to develop a metric that could digest two sets of inputs:<br>(1) annotations done manually by annotators and (2) the initial prediction of annotations done by the AI system.</p><p>For simplicity, consider the following two sets of input as an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*eQbQ-CT5YqNeWfgp" /></figure><p>Intuitively, we needed to measure how many changes the user made over the AI’s initial predictions and find a way to quantify each type of change. Let’s say that only adjusting an annotation’s end time (1st row above) is less ‘severe’ than deleting a complete annotation that is wrong (4th row above). Also, adding a full annotation that the system missed requires much more manual work than just deleting an incorrect annotation.</p><p>To mimic the annotator’s work and quantify each adjustment, we used a proxy task that was in proportion to the number of clicks required to make adjustments. For example, a simple value <em>fix</em> would equal 1 penalty score. A <em>delete</em> would equal 2 penalty scores, and <em>adding</em> a new annotation would equal 3 penalty scores. Obviously, the penalty mapping depends a lot on your product and application.</p><h3>You’ve got a match!</h3><p>If we look at the example above, we can see that some annotations are of the same type with different timing (1), and some have the exact timing but a different type (2). A tricky point here is how to match pairs, one from each set of annotations (algo and manual), and measure the proper penalty.</p><p>To achieve this, we used the <a href="https://en.wikipedia.org/wiki/Hungarian_algorithm">Hungarian algorithm</a>: “a combinatorial optimization algorithm that solves the <a href="https://en.wikipedia.org/wiki/Assignment_problem">assignment problem</a>”. This <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html">method</a> solves the matching problem using bipartite graphs.</p><p>We first needed to define three cost matrices:</p><ul><li>C_type - a cost matrix for the <strong>type</strong> value - a binary matrix with 1 when the type was equal between algo and manual</li><li>C_start - a cost matrix for the <strong>start</strong> value - the absolute difference between the start times of all algo vs. manual (normalized by the video duration)</li><li>C_end - a cost matrix for the <strong>end</strong> value - the absolute difference between the end times of all algo vs. manual (normalized by the video duration)</li></ul><p>For the two sets in the example above, the resultant cost matrices were:</p><pre>C_type = [[0 1 0]<br>          [0 1 0]<br>          [1 1 1]<br>          [0 1 0]]<br>C_start = [[ 0. 7. 16.]<br>           [ 7. 0. 9.]<br>           [16. 9. 0.]<br>           [20. 13. 4.]]<br>C_end = [[ 1. 9. 17.]<br>         [ 8. 0. 8.]<br>         [15. 7. 1.]<br>         [21. 13. 5.]]</pre><p>The final cost matrix was the weighted sum of these three matrices:<br>C = W_type * C_type + W_start * C_start + W_end * C_end<br>where each C[i,j] was the cost of matching <em>i</em> (algo) and <em>j</em> (manual), and all W’s are equal to 1.0.</p><p>Note that you can adjust the cost matrix definition and the weights depending on what is more important in your application.</p><p>Once we had the final cost matrix, the Hungarian algorithm’s goal was to find a complete assignment of algo to the manual. Such assignments achieved minimal cost. Given the matched pairs, we could start accumulating the penalty values:</p><ul><li>For the ones that had a pair - checking the penalty score of <strong>fixes</strong></li><li>For those without a pair in an algo set - treating it as a <strong>delete</strong> penalty</li><li>For those without a pair in a manual set - treating it as an <strong>add</strong> penalty</li></ul><p>Summing up all the penalties gave us the <em>penalty score</em>.</p><h3>Bear with me; we’re almost there</h3><p>Ok, so we had a penalty score, but what does it mean?</p><p>A perfect score is achieved if zero mistakes are made and manual annotations equal algo results. But how should we consider this value and compare different samples that have a different number of annotations?</p><p>To solve this, we also measured the ‘amount’ of work needed if the ML system didn’t provide any initial guess. Let’s call this value the <em>scratch score</em>.</p><p>Dividing the <em>penalty score</em> by the <em>scratch score </em>yielded the final impact metric value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*v71f2w7lLzrohp8jNof9GA.png" /></figure><p>Now, this final score is a very valuable measurement of our models ‘impact’ on users in production:</p><ul><li><em>impact metric</em> &gt; 1 means AI is only interfering in the work process, as more changes were needed than doing this sample from scratch.</li><li>0 &lt; <em>impact metric</em> &lt; 1 means AI provides value and help, as some changes were needed to adjust algo results but less than doing this sample from scratch.</li><li><em>impact metric</em> = 0 means a perfect match between all algo and manual annotations.</li></ul><h3>Final note: The impact metric for error analysis at a large scale</h3><p>The impact metric results are a good proxy for hunting down problems in the data or annotations. Extreme values that are out of distribution can imply something is wrong with a specific sample or its annotations. It can also help to maintain a data engine loop by surfacing hard or more important samples that can help improve the model’s main failure modes.</p><p>At scale, accumulating the impact metric values over large data can be meaningful in analyzing and understating the system’s performance. Using these results as part of the system error analysis can shed light on the main issues that interpret the annotations process or users’ experience. In addition, periodic impact metric analysis on a known fixed subset of the data can act as a gatekeeper as part of the CD process, similar to how regression tests are used to evaluate new models before deploying them to production.</p><p>Transitioning from focusing on many specific machine learning task metrics to a single holistic measurement allows a unified evaluation of AI performance in production, making it easier to track and assess overall success and overall impact on the system’s end user. Such a transition is not always trivial but contributes significantly to many aspects of the organization, from the individual researcher to end users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e3605328999" width="1" height="1" alt=""><hr><p><a href="https://medium.com/theator/consolidating-ai-performance-measurement-in-production-8e3605328999">Consolidating AI Performance Measurement in Production</a> was originally published in <a href="https://medium.com/theator">Theator Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to convert a PyTorch DataParallel project to use DistributedDataParallel]]></title>
            <link>https://medium.com/data-science/how-to-convert-a-pytorch-dataparallel-project-to-use-distributeddataparallel-b84632eed0f6?source=rss-486b68bc632a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b84632eed0f6</guid>
            <category><![CDATA[dataparallel]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[distributeddataparallel]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Omri Bar]]></dc:creator>
            <pubDate>Tue, 25 May 2021 13:01:05 GMT</pubDate>
            <atom:updated>2021-05-25T13:01:05.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9jnvL9o6VV9QiXMe" /><figcaption>Photo by <a href="https://unsplash.com/@tvick?utm_source=medium&amp;utm_medium=referral">Taylor Vick</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Many posts discuss the differences between PyTorch <a href="https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html#dataparallel">DataParallel</a> and <a href="https://arxiv.org/pdf/2006.15704.pdf">DistributedDataParallel</a> and why it is <a href="https://pytorch.org/tutorials/intermediate/ddp_tutorial.html#comparison-between-dataparallel-and-distributeddataparallel">best practice</a> to use DistributedDataParallel.</p><p>PyTorch documentation summarizes this as:</p><blockquote>“DataParallel is usually slower than DistributedDataParallel even on a single machine due to GIL contention across threads, per-iteration replicated model, and additional overhead introduced by scattering inputs and gathering outputs.”</blockquote><p>But the truth is that for development and prototyping, when working on a new project, or when building on top of an existing GitHub repository [which already uses DataParallel], it is simpler to use the DataParallel version out-of-the-box, especially when using a single server [that has one or several GPUs]. The most prominent advantage is that it is easier to debug with DataParallel.</p><p>Still, there will come the point where you would like to convert your existing DataParallel project to the big league and use DistributedDataParallel — this is apparently not trivial as it should be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*e8vFOb-aABa9Hnhqxh59hw.jpeg" /></figure><p>So in this post, I will not discuss further the advantages and disadvantages of each of the methods but rather focus on the practical aspects of converting an existing project, implemented with DataParallel, into a DistributedDataParallel project.</p><p>I’ll try to describe the different pieces as general as possible, but of course, your use case is unique 😃 and might require careful and specific adjustments based on how your implementation and code look like.</p><p>Let’s go…</p><p>The first step is the wrapper. DataParallel uses single-process with multi-thread, but DistributedDataParallel is multi-process by design, so the first thing we should do is to wrap the entire code — our main function — using a multi-process wrapper.</p><p>To do so, we are going to use a <a href="https://github.com/facebookresearch/detectron2/blob/9246ebc3af1c023cfbdae77e5d976edbcf9a2933/detectron2/engine/launch.py">wrapper</a> provided by FAIR in the <a href="https://github.com/facebookresearch/detectron2">Detectron2</a> repository. We will also need the <a href="https://github.com/facebookresearch/detectron2/blob/master/detectron2/utils/comm.py">comm</a> file, which gives some nice functionality for handling distribution resources.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c007a0fdff620f57f828976aaa827a4/href">https://medium.com/media/4c007a0fdff620f57f828976aaa827a4/href</a></iframe><p>The function that we need to run is called launch(). Let’s review the input parameters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bcf0c7880b51d85c318d6f4a2c33e16/href">https://medium.com/media/1bcf0c7880b51d85c318d6f4a2c33e16/href</a></iframe><p>We need to provide it with the number of machines we are using, for this post we will use a single machine with four GPUs, so num_machines=1 and num_gpus_per_machine=4. The machine_rank is used to specify the number [or the index] of the machine when using more than one machine, for our example machine_rank=0. dist_url is used to provide the master machine IP address when using several machines in distributed training, but since we only use one we can use dist_url=“auto”, which will use the localhost as IP and a free port. The main_func variable provides the main functionality of our code, this should be the main function used until now to run your flow in the DataParallel case. Finally, we can provide the args variable, these are all the input arguments to our main_func function.</p><p>Under the hood, the launch function will spin multiple processes using the torch multiprocessing module [torch.multiprocessing] and the spawn function, which will start the processes as new child processes — one for each GPU.</p><p>It is important to note that after running the launch function the exact same code will run in each child process simultaneously. So all pre-setup code, that needs to run only once at the beginning, should be called before running the launch function. For example, connecting to your experiments manager application, getting arguments from a config file that should be passed to all processes in advance, syncing data to the local server, etc.</p><p>Now that we have a working wrapper we can adjust our model. We need to “convert” our model, which was initialized on the CPU, to a DistributedDataParallel GPU model.</p><p>If in the DataParallel case we needed to wrap our model with:</p><p>model = torch.nn.DataParallel(model)</p><p>In the distributed case we will wrap the model with the DistributedDataParallel class, and this call will be done by each one of the processes independently. So, we first need to figure out what is the “rank” of our current process [rank is basically our GPU index], copy the model from the CPU to that specific GPU, and set it up as a DistributedDataParallel model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94ef3b0a79c47c47f2d9ba4058f7d1f7/href">https://medium.com/media/94ef3b0a79c47c47f2d9ba4058f7d1f7/href</a></iframe><p>The broadcast_buffers is an important parameter, it means whether or not to sync variables that are statistics-based between GPUs during training, such as the mean and variance of BatchNorm layers.</p><p>So we have the main wrapper and a model, next we need to adjust the data loading part.</p><p>In the DataParalle case, we have a single batch of size N, and during the forward pass it is automatically scattered evenly across our 4 GPUs, providing each GPU with its minibatch of size N/4. Now in the Distributed case, we need each GPU process to read only the samples relevant to its mini-batch out of the full samples batch. This is done with PyTorch <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.distributed.DistributedSampler">DistributedSampler</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fb93f5fe667e547d12192496b05191a/href">https://medium.com/media/7fb93f5fe667e547d12192496b05191a/href</a></iframe><p>The sampler splits the samples based on the number of processes we have and provides each process with the relevant sample indexes for his minibatch. After initializing the sampler, we need to provide the DataLoader class with this sampler instance and set its shuffle parameter to False. We will also need to call the sampler’s set_epoch(epoch) <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.distributed.DistributedSampler">function</a> as part of our epoch for-loop to get a different order of training samples in each epoch.</p><p>At this point, we basically have the three main components: a multiprocess wrapper, a model defined as a Distributed type, and a way to handle the data loading part. Next, we will review other important adjustments we can make in our code related to logging, reporting, and metrics calculation.</p><p>As all processes run the same code, using prints and a logger to report to the console [or a file] will repeatedly cause the same prints to be written. Although some might be important and relevant to report for each process, many are not, and we can use the following command to report a message only once in the main process [which is our rank 0 process]:</p><pre>if comm.is_main_process():<br>    print(“something that is printed only once”)</pre><p>This trick is also valuable when reporting metrics to an external tool or when saving the model weights. You can use it to make sure an action only happens once in the flow by the main process.</p><p>Now, what about the metrics?</p><p>Using the PyTorch DistributedDataParallel module, you don’t need to manage and “collect” [gather] the loss values from all processes to run the backward step, the loss.backward() will do it for you under the hood, and since it runs for each process, it will provide the same gradients correction to all model replications on all GPUs.</p><p>However, this is only relevant to the loss value that is used inside the backward pass. In order to report the actual loss values or their average, you will need to collect the loss per process and have the main process report their average:</p><pre>loss = criterion(outputs, labels)<br>...<br>all_loss = comm.gather(loss)<br>if comm.is_main_process():<br>    report_avg(all_loss)</pre><p>Now, all_loss has the loss values of all processes, and the main process can average them, accumulate them, and report what is needed.</p><p>Note that the gather command requires all processes to provide their values to the main process, slowing down the entire flow. A better way to handle this is to have each process collect and store its loss values and run the gather every number of iterations or at the end of an epoch.</p><p>Additional important comments:</p><ul><li>A valuable trick is the ability to sync all processes at specific points in the code and force them to wait for each other. This can be the cure for the following scenario: the flow runs and for some reason just hangs. Looking at nvidia-smi you see that all GPUs are at 100% utilization while one GPU is at 0%. This is one example of a frustrating case that occurs when working with the distribution mode and might happen because the main GPU is processing something that takes more time, like saving and uploading your model. Forcing the processes to sync at some specific points in the flow might help, for instance, when going from the evaluation step back to the next training epoch. This can be done with a barrier function by using the following command: comm.synchronize()<br>This function puts a barrier in the code, forcing all processes to wait for the rest to arrive and pass that point together 😃.</li><li>The DistributedDataParallel module transfers information between the processes, for this to happen PyTorch serializes the variables that are part of the data loader class. This requires that such variables are valid for serialization. The error is pretty informative, so you know when you are facing such an issue. I had issues with serializing part of my logger instances since it had a filter that uses a different class which was not suitable for serialization.</li></ul><p>That’s it. I hope this guide will help you transition from a PyTorch DataParallel implementation to a DistributedDataParallel mechanism and enjoy the benefits and speed it provides.</p><p>Further reading:</p><ul><li><a href="https://pytorch.org/tutorials/beginner/dist_overview.html">https://pytorch.org/tutorials/beginner/dist_overview.html</a></li><li><a href="https://pytorch.org/tutorials/intermediate/ddp_tutorial.html#comparison-between-dataparallel-and-distributeddataparallel">https://pytorch.org/tutorials/intermediate/ddp_tutorial.html#comparison-between-dataparallel-and-distributeddataparallel</a></li><li>PyTorch Distributed: Experiences on Accelerating Data Parallel Training [<a href="https://arxiv.org/pdf/2006.15704.pdf">https://arxiv.org/pdf/2006.15704.pdf</a>]</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b84632eed0f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-convert-a-pytorch-dataparallel-project-to-use-distributeddataparallel-b84632eed0f6">How to convert a PyTorch DataParallel project to use DistributedDataParallel</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[How theator Built a Continuous Training Framework To Scale up Its Surgical Intelligence Platform]]></title>
            <link>https://medium.com/pytorch/how-theator-built-a-continuous-training-framework-to-scale-up-its-surgical-intelligence-platform-b5135e3229fd?source=rss-486b68bc632a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5135e3229fd</guid>
            <category><![CDATA[devops-and-mlops]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[case-study]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Omri Bar]]></dc:creator>
            <pubDate>Thu, 17 Dec 2020 17:30:18 GMT</pubDate>
            <atom:updated>2020-12-17T17:30:18.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhEd_gATASusfJqBWtDx4Q.png" /></figure><p>Performing surgery is largely about decision making. As Dr. Frank Spencer put it in 1978, <em>“A skillfully performed operation is about 75% decision making and 25% dexterity”</em>. Five decades later, and the surgical field is finally — albeit gradually — implementing advances in data science and AI to enhance surgeons’ ability to make the best decisions in the operating room. That’s where <a href="https://theator.io/">theator</a> comes in: the company is re-imagining surgery with a Surgical Intelligence platform that leverages highly advanced AI, specifically machine learning and computer vision technology, to analyze every step, event, milestone, and critical junction of surgical procedures — significantly boosting surgeons’ overall performance.</p><p>The platform’s video-based analysis takes lengthy surgical operation videos and extracts meaningful information from them while maintaining<a href="http://proceedings.mlr.press/v121/zohar20a.html"> patient privacy</a>, providing surgeons with highlight reels of key moments in an operation, enhanced by annotations. This quantitative visualization of past surgeries not only enables surgeons to improve their craft from operation to operation, but it also informs surgical best practices for future procedures.</p><p>How did we make it possible? Automation was critical. As our R&amp;D team expanded, we began to realize that we were spending too much time manually running model training and focusing on DevOps tasks, and not enough time dedicated to core product development. That’s when we realized that running all of these processes manually was infeasible and automating training pipelines was an absolute <em>must</em>. Now, when new data comes in, it’s immediately processed and fed directly into training pipelines — speeding up workflow, minimizing human error, and freeing up our research team for more important tasks.</p><p>Here are the ins and outs of our automation process.</p><p><strong>From Software to Data Science Domain</strong></p><p>At theator, our strong engineering culture complements our core research principles and practices. In order to automate our training pipelines, we decided to borrow the “nightly build” concept from SW engineering, adapting it to the deep learning domain. The idea, in short, was to build a full continuous integration (CI)/ delivery (CD)/ training (CT) pipeline.</p><p>This automated pipeline trains and tests multiple models at <em>night </em>— as the name “nightly build” implies. It includes pipelines that generate several models chained together and manages multiple parallel pipelines that run concurrently with multiple procedure types. Experiments that pass the bar are placed in a deployment pipeline, which ultimately delivers the models to the end-users for inference.</p><p>Lastly, after annotation refinements, a feedback loop is created to collect inference data and integrate it with existing training datasets for improvement and continuous training (CT).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LY3a8QKmf7-INwYYCYX77w.jpeg" /><figcaption>High-level view of framework design</figcaption></figure><p>Building the automation was complex since there were multiple moving parts, all of which needed to be integrated together. We also faced challenges regarding ease and cost of computation, setup, maintenance, and more, and it became increasingly clear that minimizing these challenges meant choosing the optimal tools for the job. We mainly focused on selecting two core tools, i.e. the framework of choice, and the platform or toolchain on top of which our research and deployment pipeline automation was built, end to end.</p><p>We chose <a href="https://pytorch.org/">PyTorch</a> as our main ML/DL framework for both research exploration and production inference. The models we typically develop at theator are a combination of state-of-the-art methods — tailored for the surgical domain — and modules developed in-house. Since our research team stays up-to-date regarding relevant computer vision publication releases, we frequently explore new techniques related to the field. Integrating new ideas with our proprietary modules — and exploring their impact — requires a flexible framework: one that enables fast experimental iterations of sub-components of the training flow, e.g., new network architecture or a novel layer structure. We identified PyTorch as the best framework to deliver the flexibility that we needed. With PyTorch we can easily disassemble and reassemble the parts we want to focus on and it provides frictionless top to bottom debugging capabilities — from the data loading parts through their tensor representations, down to the network’s gradients during the learning process.</p><p>We chose <a href="https://allegro.ai/">Allegro</a> Trains for the underlying platform or toolchain. The key selling point for us was the fact that Allegro Trains provides most of the critical pieces needed in a highly integrated toolchain, including experiment management, data and metadata management, ML-Ops, orchestration, and automation components. It also has additional bonuses like optimizing the physical data flow for training and more.</p><p><strong>The Control Plane</strong></p><p>Because we manage multiple use cases — and new data coming in typically correlates with one or more of those use cases — training multiple models concurrently is inevitable. Doing so with separate models, however, also incurs high operational costs driven by extensive cycles and reduced researcher focus. Our researchers and engineers knew that they needed a single control plane to manage these multiple concurrent processes. To accomplish this effectively, we began using an advanced feature of Allegro Trains that enables us to set up master controller apps which — among other things — manipulate multiple, complex pipelines concurrently. The feature can orchestrate an unlimited number of concurrent pipelines, spread across various datasets and machines, on-prem or in the cloud.</p><p>We set up our master controller to automatically run experiments, change configuration files with the correct data and model configuration, and then launch the experiment on remote machines. Our researchers complete a “recipe file” and the pipeline controller takes it from there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6sDonBth2fWu4-p3RxHLyg.jpeg" /><figcaption>Master Controller</figcaption></figure><p><strong>The Workflow in a Nutshell</strong></p><p>Let’s dive a bit into our R&amp;D pipeline and explore the setup.</p><p>The first step was to create a version of the data from the various video sources: these build upon the original training video sets and other videos, coming in periodically from active medical centers in deployment, that are annotated and added to the training sets.</p><p>To accomplish this, we set up a data management solution which included:</p><ul><li>Versioning of datasets</li><li>Queryable datasets</li><li>Ability to mix and match datasets</li><li>Balance datasets</li><li>Optimized data loading</li></ul><p>We chose Allegro Trains because all of these capabilities are included out-of-the-box in their enterprise data management solution. Using their system, we’re able to organize our datasets in a queryable structure, monitor incoming data, and automatically trigger the training pipeline periodically — or when events such as when data doubles, or we receive incoming data from a new source. This is the CI aspect of our solution.</p><p>A particularly helpful feature of Allegro Trains is that it also tracks the machines’ status for utilization and models’ status for performance. Live tracking of model performance provides our researchers with quick insights that can shorten training times or lead to new research avenues. At the same time, machine observability enables them to maximize the utilization of our hardware. Correlating between an experiment’s behavior and machine utilization provides another debugging capability layer — therefore, combining these two features multiplies their impact.</p><p>On the data handling side, during training and inference, a surgical video that took hours to complete is represented as a huge 4D tensor. This makes it difficult to digest and process sequentially, out of the box. We’ve written customized data loading functionalities — based on PyTorch video handling modules — to develop our internal surgical vision models. Wrapping them with PyTorch data distribution and data parallelism has helped us achieve significant and essential acceleration in training and running experiments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vr8Ej8Kjd7CoviSXW8EaVw.jpeg" /><figcaption>Training Pipeline View</figcaption></figure><p><strong>When it’s Time to Deploy</strong></p><p>Having already covered the heavy load of automating the training of deployment-ready models, let’s now discuss the deployment aspect of our solution.</p><p>Since we run a live production platform (which has a continual feedback loop that enables retraining) we had to close the loop between creating and refining training models, and quickly deploy them — sometimes deploying multiple models at once. This problem is further complicated by the fact that pipelines may contain multiple models, and swapping models for better-performing alternatives might actually diminish the entire pipeline’s performance.</p><p>To mitigate this risk, we built a regression test pipeline that simulates production-like environments and tests the model on real field-data. This step, combined with Allegro Trains’ comparison dashboard, allows us to be confident in our pipeline and grants a “seal of approval” for models to be deployed into production. Finally, deploying models as part of the production base-code is quickly achieved with PyTorch, which enables robust and stable production-ready APIs that translates into fast surgical video analysis of new procedures curated from the operating room at inference time. This is the CD part of the solution.</p><p><strong>Wrapping it all up</strong></p><p>Having built this framework to automate and manage our entire process, from model development to deployment to continuous training for model improvement, we’ve evolved from a company that relied on traditional ML practices to a fully automated, scalable organization. Along the way, we’ve saved our researchers and engineers countless hours by allowing them to focus on where the true value-add lies. With this reduction in training time and costs, we’re now able to double down on our ultimate goal of perfecting and delivering better models for our end users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5135e3229fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pytorch/how-theator-built-a-continuous-training-framework-to-scale-up-its-surgical-intelligence-platform-b5135e3229fd">How theator Built a Continuous Training Framework To Scale up Its Surgical Intelligence Platform</a> was originally published in <a href="https://medium.com/pytorch">PyTorch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[To Publish, or Not to Publish]]></title>
            <link>https://medium.com/data-science/to-publish-or-not-to-publish-f61e06d25bc3?source=rss-486b68bc632a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f61e06d25bc3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[publishing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[stealth-research]]></category>
            <dc:creator><![CDATA[Omri Bar]]></dc:creator>
            <pubDate>Sun, 23 Feb 2020 21:20:57 GMT</pubDate>
            <atom:updated>2020-02-23T21:20:57.919Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Should [medical] companies publish and share their research in scientific publications and conferences on a regular basis</strong></h4><p>TL;DR</p><p><strong>YES. You should publish.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qQ90QMc1WLcR0xiS" /><figcaption>Photo by <a href="https://unsplash.com/@milkovi?utm_source=medium&amp;utm_medium=referral">MILKOVÍ</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, I am going to discuss whether ML groups of medical startups should routinely work on publishing papers. I will try to show the benefits and disadvantages in order to help determine if publications should be prioritized over other projects.</p><p>First, a disclaimer. Everything is written from my perspective, which is based on my personal experience, working in ML research teams in healthcare startups. I think it applies to a variety of domains, but well — who knows.</p><p>A fascinating perspective called <em>“Stealth research: Lack of peer‐reviewed evidence from healthcare unicorns” </em>was recently published in the <a href="https://onlinelibrary.wiley.com/doi/epdf/10.1111/eci.13072">European Journal of Clinical Investigation</a>. The authors discuss the issue of <strong><em>Stealth Research</em></strong><em> </em>and state that:</p><p><em>“Healthcare start‐ups are a major force in biomedical innovation, positioned to make revolutionary discoveries.”</em></p><p>but show concern that:</p><p><em>“Most of the highest‐valued start‐ups in healthcare have a limited or non‐existent participation and impact in the publicly available scientific literature.”</em></p><p>It’s a very interesting read, and I couldn’t agree more. In today’s research environment, when state-of-the-art results are frequently achieved, and code is shared in open source repositories, medical companies can’t stay behind. They must consider and find a way to share their knowledge and experience within the scientific community. I know; there is always the fear of revealing your secrets, especially in the early days of the company. Still, if you find that much of the existence of your company is hanging on one or two “secret sauce” algorithms, that are not to be shared to some extent, your company is in trouble. There are lots of smart people out there working to promote this field forward, and someone can or will figure it out. You can only profit in the long run from publishing, and you should make it a habit and routine under several considerations, which I will describe here.</p><p>Very broadly let’s divide publications possibilities into four options:</p><ol><li>Top tier journals [<a href="https://www.nature.com/">Nature</a>, <a href="https://www.sciencemag.org/">Science</a>, <a href="https://www.thelancet.com/">The Lancet</a>, …]</li><li>Clinical journals or clinical conferences [<a href="https://www.scimagojr.com/journalrank.php">Journal Rankings</a>]</li><li>Technical oriented medical conferences [<a href="http://www.miccai.org/">MICCAI</a>, <a href="https://www.midl.io/">MIDL</a>, <a href="https://www.mlforhc.org/">MLHC</a>, …]</li><li>Top technical conferences [<a href="http://cvpr2020.thecvf.com/">CVPR</a>, <a href="https://eccv2020.eu/">ECCV</a>, <a href="https://iclr.cc/">ICLR</a>, <a href="https://nips.cc/">NeurIPS</a>, …]</li></ol><p>All of these options benefit the company, team, and also the culture, but in a different degree of impact.</p><p>Let’s go through each one of these possibilities and try to understand what are the pros and cons of working toward publishing in these venues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*GME3cVgEe3i2IBXcvwWjEg.png" /></figure><h3>Top tier journals</h3><p>The holy grail publication for medical companies. The one most of the companies and researchers want to achieve. A paper you can proudly bring home to make your parents proud.</p><p>Such publication validates your research and helps your go-to-market [AI] strategy. It shows that your work has been reviewed and verified outside the inner company circles and was approved. This fact will be helpful when approaching new customers and investors.</p><p>It is also beneficial in terms of handling competing companies and improving the company moat — raising the entrance bar to the field.</p><p>Publishing in top tier journals also puts the company under the spotlight of reporters and attracts excellent public relations. The PR machine will do the work for you, describing the main key points of the paper in major magazines, social networks, interviewing the authors, etc. Eventually, this creates hype around the company and leads traction to the product by a new segment of users.</p><p>Now comes the bad parts.</p><p>Such publication requires a lot of effort and time. It often comes after an already long journey of a big project that got to an end with some breaking or innovating results, and now instead of releasing some steam, relax and move to the next project, this will hold many team members back from progressing to other tasks. Working on a paper will hold up one of the main company verticals from moving forward. This fact is not suitable for all companies and highly depends on the stage the company is at. You should think it through before starting this adventure.</p><p>It also assumes your team has the skillset and can handle the relevant tasks: writing a scientific paper, reproducing results, designing figures, reviewing the materials, etc.</p><p>Also, you should consider how this might affect the team morale, as a group and on an individual level. First, the concern of rejection, which spoils the morale and shakes the ship confidence after the significant effort already invested. Second, the reviewing process can be very long, and it can take weeks until getting the referees review back. At the same time, team members are already occupied with other tasks, and now need to contact switch back to old experiments in order to add the value of a missing statistic. Of course, this will be done in some ancient commit, which now does not work [BTW, you should use docker containers and wrap your system close to submission to be prepared for this scenario].</p><p>The last thing you should give your attention to, which might become an issue, is the authors’ order of appearance in the paper. It can turn into a pain point in case egos are involved — it is hard to make everyone happy, and often someone will be eventually unsatisfied. Think about this in advance.</p><h3>Clinical journals or clinical conferences</h3><p>In this type of publication, I mean either known journals of a specific topic in healthcare or highly valued conferences that publish a proceeding or something similar.</p><p>I think the best way is to run this with strong collaborators that lead the effort and propose the research question. The team, in this case, support and help to push the collaboration forward. This way the heavy lifting is divided between an outside group and your team. Both parties enjoy sharing and seeing another perspective of the domain they are working in. Also, a publication with known researchers and opinion leaders in your field will contribute to the company’s credibility and involvement in the industry and academia.</p><p>You should pay attention not to take too many collaborations at the same time, as they tend to overlap with the current workflow and slow down the team. Collaborators often work at a different pace and different time zone, and if not appropriately managed can lead to team frustration. It is hard to point a magic number of collaborations to work on at the same time, and also depends on the team size and who handles these projects in the long run. Additionally, it is hard to reject collaborations from an important expert, even if you already busy with others, but try to limit yourself to the best ideas, which will result in meaningful publications.</p><p>Some of these collaborations will require work from team members but put them in the non-front seat. This is inevitable for some collaborations, as researchers might want to handle the research and use your “services” when they are needed. However, having team members working on this and only sending reports can be very frustrating. I suggest that team members will be involved in the research all the way. And have them be the contact person talking to the collaborators, which will lead to more personal relationships. Besides, credit and recognition are important. If you have teammates working for others “in the dark” you will end up with low morale and frustration.</p><h3>Technical oriented medical conferences</h3><p>This type of publication is a great middle-ground. It often requires less work than other alternatives and fits many projects the team has been working on already.</p><p>Submitting papers to these conferences brings a lot of happiness to the team, and once accepted will increase team morale. It will spark other team members to push their projects to high quality in order to be relevant for this type of publication.</p><p>It can help to expose the company to the community and also recruiting new talents to the team and attract researchers with interest in publications.</p><p>On a more fuzzy viewpoint, it creates a feeling of excellence, which comes from the understanding that the work the team is doing does not only relates to the company domain but is relevant for others in adjacent domains.</p><p>I think this type of publication benefits both the company and the team. As the return of investment is high, and it requires less work than other options, I think teams should engage in such publication at least once a year.</p><h3>Top technical conferences</h3><p>If top tier journals were companies holy grail, these conferences are in the wish list of every ML researcher. We all read and work with these publications on a train-to-train basis.</p><p>Not by chance, those who submit and publish in these conferences are researchers from academia, top talent in the field or teams from big companies. It might require exploring problems that are not in direct connection to the scope of the company and often requires working with public datasets. Startups companies usually don’t have the privilege and capacity to allocate resources for such projects.</p><p>One of the advantages these conferences have, which is also right for technical oriented medical conferences, is the pre-known deadlines. Deadlines are good, especially for research teams. The deadlines are announced on the conference website, and you can adjust the team projects and set a fixed time for such publication work.</p><p>Another advantage is the short process review in these conferences compare to journals. It is basically a rejection or acceptance response [with a short period to rebuttal and update the paper].</p><p>Publications in these conferences position the team in the “big league” and brand the group as a prestigious one. However, this type of publication requires lots of computing power, which costs a lot of money, especially if you are using cloud computing. It could pile up to ten of thousands of dollars and “eat” the team computing budget. Additionally, it requires significant time and focused work on the small details that are sometimes ignored during research, like concentrating on improving 1–2% accuracy of a publicly available known dataset.</p><p>As a final note, I would like to emphasize three main points.</p><p>(1) Aim high, prepare it well and start by submitting the work to a higher level target then what you think you are worth.</p><p>(2) I think you always learn something new while working on a paper by building a more intimate understanding of your datasets and models. There is an amazing feeling when writing an article, that pushes further the quality of your work and makes it better for yourself and the company.</p><p>(3) There are many tips and different moves you can do if publications are a goal for your team. I might write another post about it, but the most important tip is getting the right experts at your side. You will need a supportive group of advisors to help push this ship to the right port. Don’t underestimate this. A word in the right direction from someone who published numerous times in the past is super important. I had the honor and privilege to work with a few super talented and smart advisors and keep learning from them today on every discussion.</p><p>So where are you planning to publish next? Share your thoughts in the responses below or send me a private message.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f61e06d25bc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/to-publish-or-not-to-publish-f61e06d25bc3">To Publish, or Not to Publish</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[Unbalanced data loading for multi-task learning in PyTorch]]></title>
            <link>https://medium.com/data-science/unbalanced-data-loading-for-multi-task-learning-in-pytorch-e030ad5033b?source=rss-486b68bc632a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e030ad5033b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[multi-task-learning]]></category>
            <category><![CDATA[unbalanced-data]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[data-handling]]></category>
            <dc:creator><![CDATA[Omri Bar]]></dc:creator>
            <pubDate>Tue, 07 Jan 2020 15:23:04 GMT</pubDate>
            <atom:updated>2020-01-21T18:41:50.757Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical PyTorch guide for training multi-task models on multiple unbalanced datasets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XrINyU1KA2jnEvqWfKNlQ.jpeg" /><figcaption><a href="http://www.freepik.com/">Designed by Kjpargeter / Freepik</a></figcaption></figure><p>Working on <a href="https://ruder.io/multi-task/">multi-task learning</a> (MTL) problems require a unique training setup, mainly in terms of data handling, model architecture, and performance evaluation metrics.</p><p>In this post, I am reviewing the data handling part. Specifically, how to train a multi-task learning model on multiple datasets and how to handle tasks with a highly unbalanced dataset.</p><p>I will describe my suggestion in three steps:</p><ol><li>Combining two (or more) datasets into a single PyTorch <em>Dataset.</em> This dataset will be the input for a PyTorch <em>DataLoader.</em></li><li>Modifying the batch preparation process to produce either one task in each batch or alternatively mix samples from both tasks in each batch.</li><li>Handling the highly unbalanced datasets at the batch level by using a <em>batch sampler </em>as part of the <em>DataLoader.</em></li></ol><p>I am only reviewing <em>Dataset </em>and<em> DataLoader</em> related code, ignoring other important modules like the model, optimizer and metrics definition.</p><p>For simplicity, I am using a generic two dataset example. However, the number of datasets and the type of data should not affect the main setup. We can even use several instances of the same dataset, in case we have more than one set of labels for the same set of samples. For example, a dataset of images with an object class and a spatial location, or a face emotions dataset with facial emotion and age labeling per image.</p><p>A <a href="https://pytorch.org/docs/stable/data.html#dataset-types">PyTorch <em>Dataset</em></a> class needs to implement the __getitem__() function. This function handles samples fetching and preparation for a given index. When using two datasets, it is then possible to have two different methods of creating samples. Hence, we can even use a single dataset, get samples with different labels, and change the samples processing scheme (the output samples should have the same shape since we stack them as a batch tensor).</p><p>First, let’s define two datasets to work with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f1fb3ee5d64ea7b44f7ebec4ee8c4dd/href">https://medium.com/media/4f1fb3ee5d64ea7b44f7ebec4ee8c4dd/href</a></iframe><p>We define two (binary) datasets, one with ten samples of ±1 (equally distributed), and the second with 55 samples, 50 samples of the digit 5, and 5 samples of the digit -5. These datasets are only for illustration. In real datasets, you should have both the samples and the labels, you will probably read the data from a database or parse it from data folders, but these simple datasets are enough to understand the main concepts.</p><p>Next, we need to define a <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader"><em>DataLoader</em></a>. We provide it with our <em>concat_dataset</em> and set the loader parameters, such as the batch size, and whether or not to shuffle the samples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/668eddcba8691047fd4a64b379cb6c32/href">https://medium.com/media/668eddcba8691047fd4a64b379cb6c32/href</a></iframe><p>The output of this part looks like:</p><pre>tensor([ 5.,  5.,  5.,  5., -5.,  5., -5.,  5.])<br>tensor([5., 5., 5., 5., 5., 5., 5., 5.])<br>tensor([-1., -5.,  5.,  1.,  5., -1.,  5., -1.])<br>tensor([5., 5., 5., 5., 5., 5., 5., 5.])<br>tensor([ 5.,  5.,  5.,  5., -5.,  1.,  5.,  5.])<br>tensor([ 5.,  5.,  5.,  1.,  5.,  5.,  5., -1.])<br>tensor([ 5.,  5.,  5.,  5., -1.,  5.,  1.,  5.])<br>tensor([ 5., -5.,  1.,  5.,  5.,  5.,  5.,  5.])<br>tensor([5.])</pre><p>Each batch is a tensor of 8 samples from our <em>concat_dataset</em>. The order is set randomly, and samples are selected from the pool of samples.</p><p>Until now, everything was relatively straight forward. The datasets are combined into a single one, and samples are randomly picked from both of the original datasets to construct the mini-batch. Now let’s try to control and manipulate the samples in each batch. We want to get samples from only one dataset in each mini-batch, switching between them every other batch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a4d357ada57d28b049680ba7e818ac8/href">https://medium.com/media/4a4d357ada57d28b049680ba7e818ac8/href</a></iframe><p>This is the definition of a <em>BatchSchedulerSampler</em> class, which creates a new samples iterator. First, by creating a <em>RandomSampler</em> for each internal dataset. And second by pulling samples (actually samples indexes) from each internal dataset iterator. Thus, building a new list of samples indexes. Using a batch size of 8 means that from each dataset we need to fetch 8 samples.</p><p>Now let’s run and print the samples using a new <em>DataLoader</em>, which gets our <em>BatchSchedulerSampler</em> as an input sampler (shuffle can’t be set to <em>True</em> when working with a sampler).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53fcc512a1b9a4d0e0fe6c6a72d3e283/href">https://medium.com/media/53fcc512a1b9a4d0e0fe6c6a72d3e283/href</a></iframe><p>The output now looks like this:</p><pre>tensor([-1., -1.,  1.,  1., -1.,  1.,  1., -1.])<br>tensor([5., 5., 5., 5., 5., 5., 5., 5.])<br>tensor([ 1., -1., -1., -1.,  1.,  1., -1.,  1.])<br>tensor([5., 5., 5., 5., 5., 5., 5., 5.])<br>tensor([-1., -1.,  1.,  1.,  1., -1.,  1., -1.])<br>tensor([ 5.,  5., -5.,  5.,  5., -5.,  5.,  5.])<br>tensor([ 1.,  1., -1., -1.,  1., -1.,  1.,  1.])<br>tensor([5., 5., 5., 5., 5., 5., 5., 5.])<br>tensor([-1., -1., -1., -1.,  1.,  1.,  1., -1.])<br>tensor([ 5., -5.,  5.,  5.,  5.,  5., -5.,  5.])<br>tensor([-1.,  1., -1.,  1., -1.,  1.,  1., -1.])<br>tensor([ 5.,  5.,  5.,  5.,  5., -5.,  5.,  5.])<br>tensor([ 1., -1., -1.,  1.,  1.,  1.,  1., -1.])<br>tensor([5., 5., 5., 5., 5., 5., 5.])</pre><p>Hurray!!! <br>For each mini-batch we now get only one dataset samples.<br>We can play with this type of scheduling in order to downsample or upsample more important tasks.</p><p>The remaining problem in our batches now comes from the second highly unbalanced dataset. This is often the case in MTL, having a main task and a few other satellite sub-tasks. Training the main task and sub-tasks together might lead to improve performance and contribute to the <a href="https://ruder.io/multi-task/">generalization</a> of the overall model. The problem is that samples of the sub-tasks are often very sparse, having only a few positive (or negative) samples. Let’s use our previous logic but also forcing a balanced batch with respect to the distribution of samples in each task.</p><p>To handle the unbalanced issue, we need to replace the random sampler in the <em>BatchSchedulerSampler</em> class with an <em>ImbalancedDatasetSampler</em> (I am using a great implementation from this <a href="https://github.com/ufoym/imbalanced-dataset-sampler">repository</a>). This class handles the balancing of the dataset. We can also mix and use <em>RandomSampler</em> for some tasks and <em>ImbalancedDatasetSampler</em> for others.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f432cdb6e5880aa384531d86e4b85dda/href">https://medium.com/media/f432cdb6e5880aa384531d86e4b85dda/href</a></iframe><p>We first create <em>ExampleImbalancedDatasetSampler</em>, which inherit from <em>ImbalancedDatasetSampler</em>, only modifying the <em>_get_label</em> function to fit our use case.</p><p>Next, we use <em>BalancedBatchSchedulerSampler</em>, which is similar to the previous <em>BatchSchedulerSampler</em> class, only replacing the usage of <em>RandomSampler</em> for the unbalanced task with the <em>ExampleImbalancedDatasetSampler</em>.</p><p>Let’s run the new <em>DataLoader</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3451e6a7aab2674c07a263d39e37fc18/href">https://medium.com/media/3451e6a7aab2674c07a263d39e37fc18/href</a></iframe><p>The output looks like:</p><pre>tensor([-1.,  1.,  1., -1., -1., -1.,  1., -1.])<br>tensor([ 5.,  5.,  5.,  5., -5., -5., -5., -5.])<br>tensor([ 1.,  1.,  1., -1.,  1., -1.,  1.,  1.])<br>tensor([ 5., -5.,  5., -5., -5., -5.,  5.,  5.])<br>tensor([-1., -1.,  1., -1., -1., -1., -1.,  1.])<br>tensor([-5.,  5.,  5.,  5.,  5., -5.,  5., -5.])<br>tensor([-1., -1.,  1.,  1.,  1.,  1., -1., -1.])<br>tensor([-5.,  5.,  5.,  5.,  5., -5.,  5.,  5.])<br>tensor([ 1., -1.,  1.,  1.,  1., -1.,  1., -1.])<br>tensor([ 5.,  5.,  5., -5.,  5., -5.,  5.,  5.])<br>tensor([-1., -1., -1., -1.,  1.,  1.,  1.,  1.])<br>tensor([-5.,  5.,  5.,  5.,  5.,  5., -5.,  5.])<br>tensor([-1.,  1., -1.,  1.,  1.,  1.,  1.,  1.])<br>tensor([-5., -5.,  5.,  5., -5., -5.,  5.])</pre><p>The mini-batches of the unbalanced task are now much more balanced.</p><p>There is a lot of room to play with this setup even further. We can combine the tasks in a balanced way, and by setting the <em>samples_to_grab</em> to 4, which is half of the batch size, we can get a mixed mini-batch with 4 samples taken from each task. To produce a ratio of 1:2 toward a more important task, we can set <em>samples_to_grab=2 </em>for the first task and <em>samples_to_grab=6</em> for the second task.</p><p>That’s it. The full code can be downloaded from my <a href="https://github.com/bomri/code-for-posts/tree/master/mtl-data-loading">repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e030ad5033b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/unbalanced-data-loading-for-multi-task-learning-in-pytorch-e030ad5033b">Unbalanced data loading for multi-task learning in 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>
        <item>
            <title><![CDATA[A lesson buying a multi GPU system]]></title>
            <link>https://medium.com/data-science/a-lesson-buying-a-multi-gpu-system-a14d3d1c710e?source=rss-486b68bc632a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a14d3d1c710e</guid>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Omri Bar]]></dc:creator>
            <pubDate>Thu, 20 Jun 2019 12:53:25 GMT</pubDate>
            <atom:updated>2019-06-20T12:53:25.234Z</atom:updated>
            <content:encoded><![CDATA[<h4>What I learned looking for an on-premise multi GPU system for deep learning experiments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*a23mQXxUg2hc3gp6hE2XFg.jpeg" /></figure><p>This story is about the H word, I mean hardware or more precisely high-end GPU system for heavy lifting deep learning tasks.</p><p>So after using GPU cloud instances for a long time and even <a href="https://medium.com/p/where-did-i-put-my-loss-values-acf6264ea347?source=email-486b68bc632a--writer.postDistributed&amp;sk=39b0e303a259edd240b0068e41351c34">writing a PyTorch checkpoint handler</a> to support saving and loading model weights and other hyperparameters as a snapshot, making it easier to work on spot instances. It was about time to get an on-premise machine. I currently focus on video-related tasks and training heavy <a href="https://arxiv.org/abs/1705.07750">I3D models</a>, so I needed a solid multi GPU machine to support such efforts. Using a large mini-batch size forces a lot of GPU memory. The latest and finest NVIDIA GPU is the <a href="https://www.nvidia.com/en-us/titan/titan-rtx/">TITAN RTX</a> packed with 24GB memory and sold at $2,499, so why not get four of these babies. I reached out to a few recommended suppliers to get a spec suggestion and price estimates of such a system. I was a bit surprised to hear one of the suppliers saying this cannot be done while the rest did send a suggestion.</p><p>His full answer was something like:</p><blockquote>They will heat up without a <strong>blower</strong>, and the best value for money is the <a href="https://www.gigabyte.com/Graphics-Card/GV-N208TTURBO-11GC#kf">GeForce RTX 2080 Ti TURBO 11G</a>, since each costs half and has 11GB of memory just get 8 of them.</blockquote><p>I actually did purchase a single GPU machine recently with a single <a href="https://www.nvidia.com/en-us/geforce/graphics-cards/rtx-2080-ti/">GEFORCE RTX 2080 Ti</a>, so I ask if I can add more GPUs to that machine, he asked for the exact GPU model and again said: “no <strong>blower,</strong> it will be too hot in the chassis”.</p><h4>So what’s the deal here and what is a blower?</h4><p>Confused I started looking for a simple answer and with Google’s help I found this image and the great <a href="https://www.pugetsystems.com/blog/2019/01/11/NVIDIA-RTX-Graphics-Card-Cooling-Issues-1326/">blog post</a> it came from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_9NWu1JoGeHK06WLzIxfkw.png" /><figcaption>A picture is worth a thousand words. The image is taken from: <a href="https://www.pugetsystems.com/blog/2019/01/11/NVIDIA-RTX-Graphics-Card-Cooling-Issues-1326/">NVIDIA RTX Graphics Card Cooling Issues</a></figcaption></figure><h3>Yep, on the right — a blower!</h3><p>A blower as written in <a href="https://www.gigabyte.com/Graphics-Card/GV-N208TTURBO-11GC#kf">GIGABYTE website</a> is:</p><blockquote>“GIGABYTE turbo fan cooling system is designed for systems that use multiple graphics cards in space restricted chassis. With the vapor chamber direct touch GPU, blower fan and specially shaped exterior, it provides more airflow and better heat dissipation.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yk-CwL9uo6vbu3XCfmWMoQ.gif" /><figcaption>The image is taken from: <a href="https://www.gigabyte.com/Graphics-Card/GV-N208TTURBO-11GC#kf">GIGABYTE product page</a></figcaption></figure><p>It turns out that gamers models, like the <a href="https://www.nvidia.com/en-us/titan/titan-rtx/">TITAN RTX</a>, are not dedicated for multi GPU systems and are designed for, well, gaming. They cool up by using an “open-air” system.</p><p>Assembling a multi GPU system on a non-server rack force you to put them close to each other and the blower’s job is to take care of the heat dissipation.</p><p>So next time you are looking for a GPU to handle deep learning tasks you better off ask your supplier if the GPU has a blower.</p><p>For more reading, I recommend this great blog post: <a href="https://www.pugetsystems.com/blog/2019/01/11/NVIDIA-RTX-Graphics-Card-Cooling-Issues-1326/">https://www.pugetsystems.com/blog/2019/01/11/NVIDIA-RTX-Graphics-Card-Cooling-Issues-1326/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a14d3d1c710e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-lesson-buying-a-multi-gpu-system-a14d3d1c710e">A lesson buying a multi GPU 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[Where did I put my loss values?]]></title>
            <link>https://medium.com/data-science/where-did-i-put-my-loss-values-acf6264ea347?source=rss-486b68bc632a------2</link>
            <guid isPermaLink="false">https://medium.com/p/acf6264ea347</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Omri Bar]]></dc:creator>
            <pubDate>Fri, 31 May 2019 13:40:28 GMT</pubDate>
            <atom:updated>2019-05-31T13:40:28.711Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to add metrics and key-values generated while training a deep learning model in PyTorch to your checkpoints.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*k0UsBCyh-kWDEroLQNYBvw.jpeg" /></figure><p>Saving and loading <a href="https://pytorch.org/">PyTorch</a> models is super easy and intuitive.</p><p>Save model weights:</p><pre>torch.save(model.state_dict(), PATH)</pre><p>Load model weights:</p><pre>model = TheModelClass()<br>model.load_state_dict(torch.load(PATH))</pre><p>This PyTorch <a href="https://pytorch.org/tutorials/beginner/saving_loading_models.html">tutorial</a> also explains how to save the optimizer state and other good tips on this topic.</p><h3>But what about all the other parameters?</h3><p>The above saving and loading examples are a good way to load your model in order to use it for inference in test time, or in case you are using a pre-trained model for finetuning.</p><p>Now let’s say you train a very deep model on a very large dataset, it’s gonna take a lot of time and in case you are using <a href="https://aws.amazon.com/ec2/">cloud instances</a>, it also costs lots of money. A good solution for saving money will be to use <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html">spot instances</a> which gives a significant discount. Chances are you’re going to lose your instance somewhere in the middle of the training process. Resume training using the model weights and optimizer state alone is not enough. You will also need all the metrics you measured, such as the loss and accuracy values for each set, the best top-k-accuracy on a validation set, the number of epochs, samples or iterations done until the stop point and any other special value you keep track on.</p><p>Those are needed in order to continue reporting the <a href="https://en.wikipedia.org/wiki/Learning_curve">learning progress curves</a> after you resume training, and for other on the fly decisions like learning rate reduction based on the validation loss which <a href="https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate">stopped improving</a>.</p><p>Fully resuming a learning experiment is also important for reproducible reasons, publishing a paper and a code base. In addition, being able to start from any “point” on the convergence curve, continue the learning process with or without changing any hyperparameters is crucial for research of a new task or field.</p><p>I am using PyTorch and working on large video datasets, such as <a href="https://deepmind.com/research/open-source/open-source-datasets/kinetics/">Kinetics</a>. In the process of looking for a full checkpoint solution for my research, I started working on such checkpoint handler for PyTorch and recently released a package to the Python Package Index (PyPI): <a href="https://pypi.org/project/pytorchcheckpoint/">https://pypi.org/project/pytorchcheckpoint/</a> <br>and also a GitHub repository:<br><a href="https://github.com/bomri/pytorch-checkpoint">https://github.com/bomri/pytorch-checkpoint</a>.</p><p>In order to install the package:</p><p>pip install pytorchcheckpoint</p><p>Then, somewhere at the beginning of your training code initiate the class:</p><pre>from pytorchcheckpoint.checkpoint import CheckpointHandler<br>checkpoint_handler = CheckpointHandler()</pre><p>Now, in addition to saving your model weights and optimizer state, you can add any other value in any step of the learning process.</p><p>For example, in order to save the number of classes you can run:</p><pre># saving<br>checkpoint_handler.store_var(var_name=&#39;n_classes&#39;, value=1000)</pre><pre># restoring<br>n_classes = checkpoint_handler.get_var(var_name=&#39;n_classes&#39;)</pre><p>In addition, you can store values and metrics:</p><ul><li>per set: training/validation/test</li><li>for each number of epochs/samples/iterations</li></ul><p>For example, the top-1-accuracy value of the train and validation sets for each epoch can be stored by using:</p><pre># train set - top1<br>checkpoint_handler.store_running_var_with_header(header=’train’, var_name=’top1&#39;, iteration=0, value=80)<br>checkpoint_handler.store_running_var_with_header(header=’train’, var_name=’top1&#39;, iteration=1, value=85)<br>checkpoint_handler.store_running_var_with_header(header=’train’, var_name=’top1&#39;, iteration=2, value=90)<br>checkpoint_handler.store_running_var_with_header(header=’train’, var_name=’top1&#39;, iteration=3, value=91)</pre><pre># valid set - top1<br>checkpoint_handler.store_running_var_with_header(header=’valid’, var_name=’top1&#39;, iteration=0, value=70)<br>checkpoint_handler.store_running_var_with_header(header=’valid’, var_name=’top1&#39;, iteration=1, value=75)<br>checkpoint_handler.store_running_var_with_header(header=’valid’, var_name=’top1&#39;, iteration=2, value=80)<br>checkpoint_handler.store_running_var_with_header(header=’valid’, var_name=’top1&#39;, iteration=3, value=85)</pre><p>Saving and loading the full checkpoint is done with a single line of code:</p><pre># save checkpoint<br>checkpoint_handler.save_checkpoint(checkpoint_path=path, iteration=25, model=model)</pre><pre># load checkpoint<br>checkpoint_handler = checkpoint_handler.load_checkpoint(path)</pre><p>You can check the pytorch-checkpoint <a href="https://github.com/bomri/pytorch-checkpoint#pytorch-checkpoint">README</a> for more useful examples.</p><p>So the next time you fire up a training process make sure you have those loss values at hand for any rainy day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acf6264ea347" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/where-did-i-put-my-loss-values-acf6264ea347">Where did I put my loss values?</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>