<?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 Ayan Das on Medium]]></title>
        <description><![CDATA[Stories by Ayan Das on Medium]]></description>
        <link>https://medium.com/@ayan.das?source=rss-9a49bb120cad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ST9reRi_L0B3ZFL9GlVDsA.jpeg</url>
            <title>Stories by Ayan Das on Medium</title>
            <link>https://medium.com/@ayan.das?source=rss-9a49bb120cad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:34:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayan.das/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[Distributed training of Deep Learning models with PyTorch]]></title>
            <link>https://medium.com/intel-student-ambassadors/distributed-training-of-deep-learning-models-with-pytorch-1123fa538848?source=rss-9a49bb120cad------2</link>
            <guid isPermaLink="false">https://medium.com/p/1123fa538848</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-neural-networks]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ayan Das]]></dc:creator>
            <pubDate>Wed, 10 Apr 2019 21:08:48 GMT</pubDate>
            <atom:updated>2019-04-10T21:08:48.089Z</atom:updated>
            <content:encoded><![CDATA[<p>The motive of this article is to demonstrate the idea of <strong>Distributed Computing</strong> in the context of training large scale <strong>Deep Learning (DL) </strong>models. In particular, the article first presents the basic concepts of distributed computing and how it fits into the idea of Deep learning. Then it moves on to listing the standard requirements (hardware and software) for setting up an environment capable of handling distributed applications. Finally, to provide a hands-on experience, it demonstrates a specific distributed algorithm (namely <strong>Synchronous SGD</strong>) for training DL models from a theoretical as well as implementation perspective.</p><h3>What is Distributed computing?</h3><p><strong>Distributed computing</strong> refers to the way of writing a program that makes use several distinct components connected over network. Typically, large scale computation is achieved by such an arrangement of computers capable of handling high density numeric computations in parallel. In distributed computing terminology, these computers are often referred to as <strong>nodes</strong> and a collection of such nodes form a <strong>cluster</strong> over the network. These nodes are usually connected via <a href="https://en.wikipedia.org/wiki/Ethernet"><strong>Ethernet</strong></a><strong>,</strong> but other <a href="https://en.wikipedia.org/wiki/InfiniBand"><strong>high-bandwidth networks</strong></a> are also used to take full advantage of the distributed architecture.</p><h3>How does Deep learning benefit from distributed computing?</h3><p>Although Neural Networks, the main workhorse of DL, has been in the literature from quite a while, nobody could utilise its full potential until recently. One of the primary reasons for the sudden boost in its popularity has something to with massive computational power, the very idea we are trying to address in this article. Deep learning requires training <strong>Deep neural networks (DNN)</strong> with massive number of parameters on a huge amount of data. Distributed computing is a perfect tool to take advantage of the modern hardware to its fullest. Here is the core idea:<br>A properly crafted distributed algorithm can:</p><ol><li>“<strong>Distribute</strong>” computation (forward and backward pass of a DL model) along with data across multiple nodes for coherent processing.</li><li>It can then establish an effective “<strong>Synchronization”</strong> among the nodes to achieve consistency.</li></ol><h3>MPI: A distributed computing standard</h3><p>One more terminology you have to get used to — <strong>Message Passing Interface (MPI)</strong>. MPI is the workhorse of almost all of distributed computing. MPI is an open standard that defines a set of rules on how the nodes will talk to each other over network and also a programming model/API. MPI is not a software or tool, it’s a <em>specification</em>. A group of individuals, organizations from academia and industry came forward in the summer of 1991 which eventually led to the creation of <strong>MPI Forum</strong>. The forum, with a consensus, crafted a <em>syntactic and semantic specification</em> of a library that is to be served as a guideline for different hardware vendors to come up with portable/ flexible/optimized implementations. Several hardware vendors have their own implementation of MPI — “<strong>OpenMPI</strong>”, “<strong>MPICH</strong>”, “<strong>MVAPICH</strong>”, “<strong>Intel MPI</strong>” and lot more.</p><p>In this tutorial, we are going to use <a href="https://software.intel.com/en-us/mpi-library"><strong>Intel MPI</strong></a> as it is very performant and also optimized for Intel platforms. Original Intel MPI is a <em>C library</em> and very low level in nature.</p><h3>The Setup</h3><p>Proper setup of a distributed system is very important. Without proper hardware and network arrangements, it’s pretty much useless even if one has conceptual understanding of it’s programming model. Below are the key arrangements need to be made:</p><ol><li>A set of nodes connected in a common network forming a cluster is typically required. It is recommended to have high-end servers as nodes and high-bandwidth network like InfiniBand.</li><li>Linux systems with user accounts of <strong><em>exact same name</em></strong> are required on all the nodes in the cluster.</li><li>Nodes must have <strong><em>password-less SSH</em></strong> connectivity among them. This is very crucial for seamless connectivity.</li><li>An MPI implementation must be installed. This tutorial focuses on Intel MPI only.</li><li>A <em>common filesystem</em> is required which is visible from all the nodes and the distributed applications must reside on it. <strong>Network Filesystem (NFS)</strong> is one way to achieve this.</li></ol><h3>Types of parallelization strategies</h3><p>There are two popular ways of parallelizing Deep learning models:</p><ol><li>Model parallelism</li><li>Data parallelism</li></ol><h3>Model parallelism</h3><p>Model parallelism refers to a model being logically split into several parts (i.e., some layers in one part and some in other), then placing them on different hardware/devices. Although placing the parts on different devices does have benefits in terms of execution time (asynchronous processing of data), it is usually employed to avoid memory constraints. Models with very large number of parameters, which are difficult fit into a single system due to high memory footprint, benefits from this type of strategy.</p><h3>Data parallelism</h3><p>Data parallelism, on the other hand, refers to processing multiple pieces (technically batches) of data through multiple replicas of the same network located on different hardware/devices. Unlike model parallelism, each replica may be an entire network and not just a part of it. This strategy, as you might<br>have guessed, can scale up well with increasing amount of data. But, as the entire network has to reside on a single device, it cannot help models with high memory footprints. The illustration below should make it clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSwdZsQ0QSF8VKoihiqvvw.png" /><figcaption>Model vs Data parallelism</figcaption></figure><p>Practically, Data parallelism is more popular and frequently employed in large organizations for executing production quality DL training algorithms. So, in this tutorial, we will fix our focus on data parallelism.</p><h3>The &quot;torch.distributed&quot; API</h3><p><strong>PyTorch</strong> offers a very elegant and easy-to-use API as an interface to the underlying MPI library written in C. PyTorch needs to be compiled from source and must be linked against the Intel MPI installed on the system. We will now see the basic usage of torch.distributed and how to execute it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ec327878dab3f5733be34b36c1e8bcf/href">https://medium.com/media/6ec327878dab3f5733be34b36c1e8bcf/href</a></iframe><p>Executing the above code using mpiexec, a distributed process scheduler comes with any standard MPI implementation, results in:</p><pre><strong>cluster@miriad2a:~/nfs$</strong> mpiexec -n 2 -ppn 1 -hosts miriad2a,miriad2b python ptdist.py<br>Rank-0 has sent the following tensor to Rank-1<br>tensor([ 1., -1.])<br>Rank-1 has recieved the following tensor from Rank-0<br>tensor([ 1., -1.])</pre><ol><li>The first line to be executed is dist.init_process_group(backend) which basically sets up the internal communication channel among the participating nodes. It takes an argument to specify which <em>backend</em> to use. As we are using MPI throughout, its backend=’mpi’ in our case. There are other backends as well (like “<strong>TCP</strong>”, “<strong>Gloo</strong>” and “<strong>NCCL</strong>”).</li><li>Two parameters need to be retrieved — the <strong>world size</strong> and <strong>rank</strong>.<br>“<strong>World</strong>” refers to the collection of all nodes that have been specified in a particular context of mpiexec invocation (see the -hosts flag in mpiexec).<br>“<strong>Rank</strong>” is a unique integer assigned by the MPI runtime to each of the processes. It starts from 0. The order in which they are specified in the argument of -hosts is used to assign the numbers. So, in this case, the process on node “<em>miriad2a</em>” will be assigned Rank 0 and “<em>miriad2b</em>” will be Rank 1.</li><li>x is a tensor that Rank 0 intends to send to Rank 1. It does so by dist.send(x, dst=1).</li><li>z is something that Rank 1 created before receiving the tensor. We need an already created tensor of same shape as a holder for receiving the incoming tensor. The values of z will eventually be replaced by the value of x.</li><li>Just like dist.send(..), the receiving counterpart is dist.recv(z, src=0) which receives the tensor into z.</li></ol><h3>Communication collectives</h3><p>What we saw in the last section is an example of “<strong>peer-to-peer</strong>” communication where rank(s) send data to specific rank(s) in a given context. Although this is useful as it provides user with granular control over the communication, there exist other standard and frequently used <em>patterns of communication</em> called <strong>collectives</strong>. Below is the description of one particular collective (known as <strong>all-reduce</strong>) which is of interest to us in the context of <strong>Synchronous SGD</strong> algorithm.</p><h3>The “All-reduce” collective</h3><p><strong>All-reduce</strong> is a way of synchronized communication where <em>a given reduction operation is operated on all the ranks and the reduced result is made available to all of them</em>. The below figure illustrates the idea (uses summation as the reduction operation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*EBMyS03ql4TakYS48vYaMQ.png" /><figcaption>All reduce collective</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a6402f77ca4e0a157a4353d744a72c2/href">https://medium.com/media/5a6402f77ca4e0a157a4353d744a72c2/href</a></iframe><p>When launched in a <em>world of 3</em>, results in</p><pre><strong>cluster@miriad2a:~/nfs$</strong> mpiexec -n 3 -ppn 1 -hosts miriad2a,miriad2b,miriad2c python ptdist.py<br>Rank 1 has tensor([0.])<br>Rank 0 has tensor([0.])<br>Rank 2 has tensor([0.])</pre><ol><li>The if rank == &lt;some rank&gt; … elif is a pattern we encounter again and again in distributed computing. In this case, it is used to create different tensors on different ranks.</li><li>They all execute an <strong>all-reduce</strong> together (see that dist.all_reduce(..) is outside if … elif block) with summation (dist.reduce_op.SUM) as reduction operation.</li><li>x from every rank is summed up and the summation is placed inside the same x of every rank.</li></ol><h3>Moving on to Deep learning:</h3><p>It is assumed that the reader is familiar with the standard <strong>Stochastic Gradient Descent (SGD)</strong> algorithm which is often used to train deep learning models. We will now see a variant of SGD (called <strong>Synchronous SGD</strong>) that makes use of the All-reduce collective to scale up. To lay the foundation, let’s start with the mathematical formulation of standard SGD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*ekRlm8ToTXB1Uo9oQJ8xqg.png" /></figure><p>where <strong>D</strong> is a set (mini-batch) of samples, θ is the set of all parameters, λ is the learning rate and Loss(X, y) is some loss function averaged over all samples in <strong>D</strong>.<br>The core trick that <strong>Synchronous SGD</strong> relies on is splitting the summation in the update rule over smaller subsets of (mini)batches. <strong>D</strong> is split into <strong>R</strong> number of subsets D₁, D₂, . . (preferably with same number of samples in each) such that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*qNy96Ox4i0DnD4PEnF9JmQ.png" /></figure><p>Splitting the summation of standard SGD update formula leads to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*eleRdYi41UhtAks9EJcPbQ.png" /></figure><p>Now, as the gradient operator is distributive over summation operator, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*LgsdDdIHqU32BtHnrTRxaA.png" /></figure><h3>What do we get out of this?</h3><p>Have a look at those individual gradient terms (inside square brackets) in the above equation. They can now be computed independently and summed up to get the original gradient without any loss/approximation. This is where the data parallelism comes into picture. Here is the whole story:</p><ol><li>Split the entire dataset into <strong>R</strong> equal chunks. The letter <strong>R</strong> is used to refer to <em>Replica</em>.</li><li>Launch <strong>R</strong> processes/ranks using MPI and bind each process to one chunk of the dataset.</li><li>Let each rank compute the gradient using a mini-batch (dᵣ) of size <strong>B</strong> from its own portion of data, i.e., rank <strong>r</strong> computes</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*uE_jJYWnaUXf1nPkR6yZ7w.png" /></figure><p>4. Sum up all the gradients of all the ranks and make the resulting gradient available to all of them to proceed further.</p><p>The last point is exactly the <strong>all-reduce</strong> algorithm. So, all-reduce must be executed every time all ranks have computed one gradient (on a mini-batch of size <strong>B</strong>) on their own portion of the dataset. A subtle point to note here is that summing up the gradients (on mini-batches of size <strong>B</strong>) from all <strong>R</strong> ranks leads<br>to an effective batch size of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*Tnan7En_VbYKorA0wWI7MQ.png" /></figure><p>The following are the crucial parts of the implementation (the boilerplate codes are not shown)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81de98469919032c22025dc7adcbf621/href">https://medium.com/media/81de98469919032c22025dc7adcbf621/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cd641d75e52840953bdde68f9bafa74/href">https://medium.com/media/2cd641d75e52840953bdde68f9bafa74/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7328f4eeaab19af4a47544a662703263/href">https://medium.com/media/7328f4eeaab19af4a47544a662703263/href</a></iframe><ol><li>All <strong>R</strong> ranks create their own copy/replica of the model with random weights.</li><li>Individual replicas with random weights may lead to initial de-synchronization. It is preferable to synchronize the initial weights among all the replicas. The sync_initial_weights(..) routine does exactly that. Let any one of the ranks send its weights to its siblings and the siblings must receive them to initialize themselves with it.</li><li>Fetch a mini-batch (of size <strong>B</strong>) from the respective portion of a rank and compute forward and backward pass (gradient). Important point to note here as a part of the setup, is all processes/ranks should have its own portion of data visible (usually on its own <em>hard-disk</em> OR on a <em>shared Filesystem</em>).</li><li>Execute all-reduce collective on the gradients of each replica with summation as the reduction operation. The sync_gradients(..) routine does the gradient synchronization.</li><li>After gradients have been synchronized, every replica can execute a standard SGD update on its own weights independently. The optimizer.step() does the job as usual.</li></ol><p>Now a question might arise, “<em>How do we ensure that independent updates will remain in sync?</em>”.<br>If we take a look at the update equation for the first update</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*ziM_OgpuWqyH_v5_v-2A-g.png" /></figure><p>Point 2 &amp; 4 above ensure that the <em>initial weights</em> and the <em>gradients</em> are synchronized individually. For obvious reason, a linear combination of them will also be in sync (λ is a constant). A similar logic holds for all consecutive updates.</p><h3>Performance comparison:</h3><p>The biggest bottleneck for any distributed algorithm is the synchronization. Distributed algorithms are beneficial only if the synchronization time is significantly less than computation time. Let’s have a simple comparison between the standard and synchronous SGD to see when is the later one beneficial.</p><p><strong>Definitions.</strong> Let’s assume the size of the entire dataset is <strong>N</strong>. Mini-batches of size <strong>B</strong> are processed by the network which takes time <strong>T</strong>comp. In the distributed case, time taken for all-reduce synchronization is <strong>T</strong>sync. If there are <strong>R</strong> replicas, time taken for one epoch</p><h4>For non-distributed (standard) SGD:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*gVeSYF6qBSyWZ1VAiPjfCQ.png" /></figure><h4>For Synchronous SGD:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*HDguICjRBM6SEHwwVXtXlQ.png" /></figure><p>So, for the distributed setting to be significantly beneficial over non-distributed one, we need to have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*fg119q1v5dVuQ_dO1eeTzA.png" /></figure><p>OR, equivalently</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*F82KWARAd9cMPdH8knnw0A.png" /></figure><p>The three factors contributing to the above inequality can be tweaked to extract more and more benefit out of the distributed algorithm.</p><ol><li><strong>T</strong>sync can be reduced by connecting the nodes over a high bandwidth (fast) network.</li><li><strong>T</strong>comp can be increased by increasing batch size <strong>B</strong>.</li><li><strong>R</strong> can be increased by connecting more nodes over the network and having more replicas.</li></ol><p>Hopefully, the article was clear enough to convey the central idea of <strong>Distributed Computing</strong> in the context of Deep Learning. Although, <strong>Synchronous SGD</strong> is quite popular, there are other distributed algorithms which are also used quite frequently (like <strong>Asynchronous SGD and its variants</strong>). But, what is more important is to be able to think about deep learning methods in a <em>parallel manner</em>. Please realize that not all algorithms can be parallelized out-of-the-box; some require approximations to be made which break theoretical guarantees given by the original algorithms. It is up to the algorithm designer/implementer to tackle these approximations in an efficient way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1123fa538848" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intel-student-ambassadors/distributed-training-of-deep-learning-models-with-pytorch-1123fa538848">Distributed training of Deep Learning models with PyTorch</a> was originally published in <a href="https://medium.com/intel-student-ambassadors">Intel Student Ambassadors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>