<?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 Saaduddin Mahmud on Medium]]></title>
        <description><![CDATA[Stories by Saaduddin Mahmud on Medium]]></description>
        <link>https://medium.com/@saadmahmud14?source=rss-88ac6bbf2c3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*I64USUDfNsF7hBNCiS43Iw.jpeg</url>
            <title>Stories by Saaduddin Mahmud on Medium</title>
            <link>https://medium.com/@saadmahmud14?source=rss-88ac6bbf2c3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:40:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saadmahmud14/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[Modifying CSRankings Part-1: Top HCI Graduate Programs in the USA]]></title>
            <link>https://saadmahmud14.medium.com/modifying-csrankings-part-1-top-hci-graduate-programs-in-the-usa-3199bf5e090a?source=rss-88ac6bbf2c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3199bf5e090a</guid>
            <category><![CDATA[phd]]></category>
            <category><![CDATA[study-abroad]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[graduate-school]]></category>
            <dc:creator><![CDATA[Saaduddin Mahmud]]></dc:creator>
            <pubDate>Sun, 29 Nov 2020 21:04:43 GMT</pubDate>
            <atom:updated>2020-11-30T05:58:56.816Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*ZdtFvZ4O7rKEuqJyz3aX_Q.jpeg" /></figure><p>If you are looking for graduate programs in Computer Science (CS), then one of the best tools you can use is <a href="http://csrankings.org/"><strong>CSRankings</strong></a>. It uses publication history from top CS conferences to rank graduate programs. However, it is missing many important conferences. For example, in the AI category, you might be disappointed not seeing conferences like ICLR, ICDM, AAMAS, AISTAT. Further, If you are interested in specific topics like Human-Robot Interaction or Social Computing, you might also be disappointed not seeing the flagship conference for those topics. I know I was. But the good news is that CSRankings’ source code is available on <a href="https://github.com/emeryberger/CSrankings"><strong>GitHub</strong></a>, and you can modify and add the conferences you need. The bad news is it is protected under the <strong>No-Derivative License</strong>. So it can not be shared in its modified form.</p><p>During my search for graduate programs, I have modified CSRankings by adding ICLR, ICDM, AAMAS, AISTAT, UAI, HRI, and CSCW. In this blog, I present one specific result after the modification. The ranking of <strong>top Human-Computer Interaction Graduate Programs in the USA</strong>. This ranking is based on publication history from 2015 to 2020 in the following conferences:</p><ol><li>CHI</li><li>UbiComp / Pervasive / IMWUT</li><li>UIST</li><li>CSCW</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*IKclOVoAPBJgWm_MnDh3fQ.png" /><figcaption><strong>Top Human-Computer Interaction Graduate Programs</strong> <strong>in the USA</strong></figcaption></figure><p>Based on this blog’s engagement, I will add the entire procedure of modifying CSRankings in the upcoming parts. (It is a messy process and will require some effort to write. I also intend to add additional features.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3199bf5e090a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallel Programming With CUDA Tutorial (Part-4: The Floyd-Warshall Algorithm)]]></title>
            <link>https://saadmahmud14.medium.com/parallel-programming-with-cuda-tutorial-part-4-the-floyd-warshall-algorithm-5e1281c46bf6?source=rss-88ac6bbf2c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e1281c46bf6</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[shortest-path]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <dc:creator><![CDATA[Saaduddin Mahmud]]></dc:creator>
            <pubDate>Wed, 29 Jul 2020 11:29:40 GMT</pubDate>
            <atom:updated>2020-07-29T13:59:48.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*sYP2y2XjHpd0Z7H2QYz8xA.png" /></figure><p>In this tutorial, we will tackle the famous <strong>Floyd–Warshall algorithm</strong> for finding shortest paths in a weighted graph with positive edge weights (or negative weights but with no negative cycles; we will not consider them here anyway). Why study this? Well, first of all, finding the shortest path between two nodes is a fundamental problem in graph theory. And second, it is not much big of a jump from my previous tutorial (Matrix Multiplication). So it will be really easy :D! In this tutorial I will assume you are already familiar with the Floyd–Warshall <strong>(FW)</strong> algorithm<strong> </strong>and mainly focus on how to implement it in CUDA. This is because it is a really popular algorithm and there are plenty of resources online that talks about it ( for example <a href="https://cp-algorithms.com/graph/all-pair-shortest-path-floyd-warshall.html">https://cp-algorithms.com/graph/all-pair-shortest-path-floyd-warshall.html</a>). As usual, lets first define the problem:</p><blockquote><strong>Problem: </strong>Given a graph G(V, E) where V is a set of vertices and E is a set of edges we have to find the length of the shortest path between each pair of vertices.</blockquote><p>In this tutorial, we will first see the standard single thread implementation of the FW<strong>. </strong>Then we will identify parts that can be parallelized without thread synchronization in the single thread version. We will also see a neat trick that can get rid of the branch statement in the standard implementation and make our code completely branchless. Using this knowledge we will finally implement the FW<strong> </strong>using CUDA (It will be a good idea to read Part-3, trust me!). Finally, we will benchmark it with single thread CPU version.</p><h4><strong>The Floyd–Warshall algorithm (Single Thread):</strong></h4><pre><strong>FloydWarshall(dis)<br>{<br>   for (int k = 0; k &lt; |V|; k++) <br>   {     <br>      for (int i = 0; i &lt; |V|; i++) <br>      {         <br>         for (int j = 0; j &lt; |V|; j++) <br>         {<br>            if(dis[i][j]&lt;dis[i][k] + dis[k][j])<br>               dis[i][j] = dis[i][k] + dis[k][j];          <br>         }     <br>      } <br>   }<br>}</strong></pre><p>Above is a classic <strong><em>O(|V|³)</em></strong> implementation of the FW. Here <strong>dis[i][j] </strong>contains the distance between vertex i and j. We can see from the pseudocode above that for a given value of k the entire <strong>dis </strong>Matrix (<strong>|V|X|V|</strong>) is updated. Reading and writing are happening in this matrix simultaneously and the actual order of these operations does not matter. This makes it a really great candidate for GPU computation. So we will run the inner two loops in the GPU. The inner two loops have <strong><em>O(|V|²) </em></strong>complexity and running them on a GPU will yield <strong><em>O(|V|²/|P|) </em></strong>complexity where <strong><em>|P|</em></strong> is the number of threads. With a typical GPU, we will get <strong><em>O(10³) </em></strong>threads. So when <strong><em>|V|~O(10³) </em></strong>we will essentially have <strong><em>O(|V|) c</em></strong>omplexity for the inner loops and<strong><em> O(|V|²) </em></strong>overall complexity<strong><em>.</em></strong></p><h4>Step 1:</h4><pre><strong>InnerLoops(dis,k) <br>{     <br>   for (int i = 0; i &lt; |V|; i++) <br>   {         <br>      for (int j = 0; j &lt; |V|; j++) <br>      {<br>         if(dis[i][j]&lt;dis[i][k] + dis[k][j])<br>            dis[i][j] = dis[i][k] + dis[k][j];<br>      }     <br>   } <br>}</strong></pre><pre><strong>FloydWarshall(dis)<br>{<br>   for (int k = 0; k &lt; |V|; k++) <br>   {     <br>      InnerLoops(dis,k);<br>   }<br>}</strong></pre><p>Now, in the first step, we will just separate the loops in two different functions. In the InnerLoops function, we have a branching condition that we need to get rid of because GPUs hate branching.</p><h4>Step 2:</h4><pre><strong>InnerLoops(dis,k)<br>{     <br>   for (int i = 0; i &lt; |V|; i++) <br>   {         <br>      for (int j = 0; j &lt; |V|; j++) <br>      {<br>         t=dis[i][k] + dis[k][j];<br>         dis[i][j]=t*(t&lt;dis[i][j])+dis[i][j]*(t&gt;=dis[i][j]);<br>      }     <br>   } <br>}</strong></pre><pre><strong>FloydWarshall(dis)<br>{<br>   for (int k = 0; k &lt; |V|; k++) <br>   {     <br>      InnerLoops(dis,k);<br>   }<br>}</strong></pre><p><strong><em>Bamm! </em></strong>We got rid of the branch condition using the simple trick shown above. This works because CPP treats logical true as 1 and logical false as 0. If you are still confused try out some values on that expression and compare it with code from step 1. It will start to make sense.</p><h4>Step 3:</h4><pre><strong>__global__<br>void GPUInnerLoops(dis,k)<br>{<br>   //calculates unique thread ID in the block<br>   int t= (blockDim.x*blockDim.y)*threadIdx.z+    (threadIdx.y*blockDim.x)+(threadIdx.x); <br>   <br>   //calculates unique block ID in the grid<br>   int b= (gridDim.x*gridDim.y)*blockIdx.z+(blockIdx.y*gridDim.x)+(blockIdx.x);<br>   <br>   //block size (this is redundant though)<br>   int T= blockDim.x*blockDim.y*blockDim.z;<br>   <br>   //grid size (this is redundant though)<br>   int B= gridDim.x*gridDim.y*gridDim.z;<br>   <br>   int t;<br>   /*<br>   * Each cell in the matrix is assigned to a different thread.<br>   * Each thread do O(number of asssigned cell) computation.<br>   * Assigned cells of different threads does not overlape with<br>   * each other. And so no need for synchronization.<br>   */</strong></pre><pre><strong>for (int i=b; i&lt;|V|; i+=B)<br>   {<br>      for(int j=t; j&lt;|V|; j+=T)<br>      {<br>         t=dis[i*V+k]+dis[k*V+j];<br>         dis[i*V+j]=t*(t&lt;dis[i*V+j])+dis[i*V+j]*(tm&gt;= dis[i*V+j]);<br>      }<br>   }<br>}</strong></pre><pre><strong>FloydWarshall(dis)<br>{</strong><br>   <strong>for (int k = 0; k &lt; |V|; k++)<br>   {<br>      GPUInnerLoops&lt;&lt;&lt;dim3(x,y,z),dim3(a,b,c)&gt;&gt;&gt;(dis,k);<br>      cudaDeviceSynchronize();<br>   }<br>}</strong></pre><p>Finally, we just convert these two functions into CUDA. This is the exact same code from Part-3 with these two lines replacing whatever there was for matrix multiplication:</p><pre><strong>t=dis[i*V+k]+dis[k*V+j];<br>dis[i*V+j]=t*(t&lt;dis[i*V+j])+dis[i*V+j]*(tm&gt;= dis[i*V+j]);</strong></pre><p>What it is doing in simple term is that in the single-thread code we were incrementing i and j with 1 in each iteration of the loops. Here we are incrementing i and j with B and T respectively in each iteration of the loops. So previously the nested loops were running for <strong><em>O(|V|²) </em></strong>as discussed earlier. Now it is running<strong> <em>O(|V|²/(B*T)) </em></strong>where<em> </em><strong><em>B*T </em></strong>is <strong><em>|P|</em> </strong>i.e the number of threads. And we are done :D!</p><h4>Benchmark</h4><p>We will now benchmark GPU FW with CPU FW by varying the number of vertices. For this, we will use Google Colab. This is a departure from the earlier tutorials. I am doing this because Google Colab is more accessible. You can find the notebook in the link below. It already contains necessary script to initialize C++ CUDA in Colab (yes, the code is still in CPP).</p><p><a href="https://github.com/Saad-Mahmud/PPCUDA">Saad-Mahmud/PPCUDA</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ractlmew5WYndWP6j7qqWA.png" /></figure><p>Without any surprise, we can see a huge boost in the performance of the FW when using GPU. I had to display the time on the logarithmic scale (base 10) because the difference is so large. To give an idea, for 32000 vertices<em> </em>in the GPU the FW takes ~20 minutes while in CPU it takes ~69.7 hours (predicted by running K&lt;|V| iterations of the outer loop). Colab gave me around ~9GB GPU memory and using this I could run the Floyd-Warshall for up to ~46000 vertices after which Colab ran out of memory (46000*46000*4 byte = 8.46 GB).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e1281c46bf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallel Programming With CUDA Tutorial (Part-3 Matrix Multiplication)]]></title>
            <link>https://saadmahmud14.medium.com/parallel-programming-with-cuda-tutorial-part-3-c29b7628a289?source=rss-88ac6bbf2c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c29b7628a289</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[cuda]]></category>
            <dc:creator><![CDATA[Saaduddin Mahmud]]></dc:creator>
            <pubDate>Thu, 31 Jan 2019 20:33:00 GMT</pubDate>
            <atom:updated>2020-09-17T18:20:20.007Z</atom:updated>
            <content:encoded><![CDATA[<h3>Parallel Programming With CUDA Tutorial (Part-3: Matrix Multiplication)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UOWg370TSfor1sF784FrGA.png" /></figure><p>In this tutorial, we will tackle a well-suited problem for Parallel Programming and quite a useful one, unlike the previous one :P. We will do Matrix Multiplication. Hurray !!! Solution to many problems in CS is formulated with Matrices. So the ability to perform fast matrix multiplication is really important. Let’s define the problem statement concretely:</p><blockquote><strong><em>Problem: </em></strong><em>Given two </em><strong><em>N*N</em></strong><em> matrix </em><strong><em>X</em></strong><em> and </em><strong><em>Y</em></strong><em> of floating point numbers, perform matrix multiplication and store the result on a </em><strong><em>N*N</em></strong><em> matrix </em><strong><em>ans</em></strong><em>.</em></blockquote><p>First, I will explain why this is a well-suited problem for Parallel Programming. After that, I will show you a sequential version of matrix multiplication and will evaluate performance for the sequential version. After that, I will move on to the parallel version and its performance evaluation. Finally, we will compare the results.</p><h3>Why This Problem?</h3><h4>Shared Resource:</h4><p>In our current context, shared resources are any entities that are accessed and used by multiple threads. So array indices that are modified or read by several threads are shared resources.</p><h4>Problem With Shared Resource:</h4><p>It is not a problem when a memory location is read by several threads. Problems arise when a memory location is updated by several threads. For example, suppose you have a variable <strong>X=0. </strong>You want to increment <strong>X</strong> with 5 different threads simultaneously. And each thread will increment <strong>X </strong>by 50. What will be the value of <strong>X </strong>after all the threads are done? Logically it should be 5*50 = 250. But if you run this program several times you will get several different answers. <strong>Why? </strong>Because when two different thread tries to update the same memory location at the same time one of the updates might get overwritten. And many similar problems might arise from shared resources.</p><p><strong>How To Solve This Problem?</strong></p><p>In our code, parts, where we access shared resources to read or modify, is called critical sections. There are two ways to solve this problem:</p><ol><li>Avoid critical section altogether. This is the ideal solution.</li><li>But sometimes it is not possible to avoid critical sections. In that case, we would require thread synchronization.</li></ol><p><strong>Finally, why this problem…?</strong></p><p>Well, for matrix multiplication it is possible to avoid critical sections. That is why I have chosen this problem. For our next tutorial, I will show how to synchronize threads with CUDA.</p><h3>Sequential Matrix Multiplication</h3><p>Below is a code for matrix multiplication using C++. It is the standard O(N³) procedure. Here <strong>x</strong>, <strong>y</strong>, and<strong> ans</strong> are three N² size matrices(N² sized 1D array. We are using 1D arrays as of it were 2D).</p><pre>void cpuMatMul(int N,double *x, double *y, double *ans)<br>{</pre><pre>for(int i=0;i&lt;N;i++)<br>    {<br>        for(int j=0;j&lt;N;j++)<br>        {<br>            for(int k=0;k&lt;N;k++)<br>            {<br>                ans[i*N+j]+=(x[i*N+k]*y[k*N+j]);<br>            }<br>        }<br>    }</pre><pre>}</pre><p>The graph below shows how the runtime scales up as N gets larger using a <strong>single core of</strong> C<strong>ore i5–7500 CPU @ 3.40GHz; 16 GB DDR4 2400mhz.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vCQGRluzcrtk201jDhN74w.png" /></figure><p>For a matrix of size 1024 X 1024, it takes about 10 seconds to complete the task. For a matrix of size 4096 X 4096, it takes about 2500 seconds(larger matrices add extra overhead. So it does not scale up exactly in O(N³) after 1024) to complete the task. Above (4096 X 4096), it just gets infeasible to run the experiment.</p><h3>Parallel Matrix Multiplication</h3><p>Following is the parallel version of the same code we have seen above.</p><pre>__global__<br>void GPUmatmul(int N, double *x, double *y, double *ans)<br>{<br>    //calculates unique thread ID in the block<br>    int t= (blockDim.x*blockDim.y)*threadIdx.z<br>           +(threadIdx.y*blockDim.x)+(threadIdx.x);</pre><pre>//calculates unique block ID in the grid<br>    int b= (gridDim.x*gridDim.y)*blockIdx.z<br>           +(blockIdx.y*gridDim.x)+(blockIdx.x);</pre><pre>//block size (this is redundant though) <br>    int T= blockDim.x*blockDim.y*blockDim.z;</pre><pre>//grid size (this is redundant though)<br>    int B= gridDim.x*gridDim.y*gridDim.z;</pre><pre>//Each cell in the matrix is assigned to a different thread. <br>    //Each thread do O(N*number of asssigned cell) computation.<br>    //Assigned cells of different threads does not overlape with<br>    //each other. And so no need for synchronization. <br>    for (int i=b;i&lt;N;i+=B)<br>    {<br>         for(int j=t;j&lt;N;j+=T)<br>         {<br>              for(int k=0;k&lt;N;k++)<br>              {<br>                   ans[i*N+j]+=(x[i*N+k]*y[k*N+j]);<br>              }<br>          }<br>     }<br>}</pre><p>Here,</p><pre><strong>t </strong>is the thread number of a thread inside a particular block. <br><strong>b </strong>is the block number of a block inside the grid. <br><strong>B</strong> is total number of block.<br><strong>T</strong> is total number of threads per block.</pre><blockquote>I have explained how thread id, block id and 3D structure of threads and blocks work in part-2.</blockquote><p>We had to calculate in this way since the thread IDs are given in CUDA as 3D tuple but we needed a single integer. With <strong>t</strong> and <strong>b </strong>we can identify each thread uniquely. After that each thread iterates over only the cells they were assigned and do <strong>O(N) </strong>computation for that cell. Let’s define the number of the assigned cell to a thread as <strong>AC. </strong>So in total, a thread does <strong>O(N*AC) </strong>computation. We can calculate:</p><p><strong>AC = (N*N)/(T*B) = (N/T)*(N/B)</strong></p><p>We assign a cell to a thread just by writing the nested for loops following way:</p><pre>for (int i=b;i&lt;N;i+=B)<br>    for(int j=t;j&lt;N;j+=T)</pre><pre>Example: Let B=2 and T=2. Size of ans is 3*3. <br>(Thread 0 of block 0): will do computation on (0,0)(0,2)(2,0)(2,2). <br>(Thread 1 of block 0): will do computation on (0,1)(2,1).<br>(Thread 0 of block 1): will do computation on (1,0)(1,2).<br>(Thread 1 of block 1): will do computation on (1,1). <br>As we can see if N is perfectly devisible by both T and B each threads will be assigned equal number of cells.</pre><p>This makes sure no two thread does computation on the same cell. It is really important. Because if two or more threads did computation on the same cell the results might become inconsistent.</p><p>Finally, we call this function using the following commands. Here, dim3(16,16,16) says how the blocks are structured in the grid. And here dim3(16,8,8) says how threads are structured in each block. We are using in total 16*16*16 blocks and 16*8*8 thread per block.</p><pre>GPUmatmul&lt;&lt;&lt;dim3(16,16,16), dim3(16,8,8)&gt;&gt;&gt;(N, x, y,ans);<br>cudaDeviceSynchronize();</pre><p>Here is the performance of the above code. Even though it is a naive code it does the wonders. Using GPU we were able to multiply two (8192*8192) matrix with the O(N³) algorithm(There are better algorithms like Karatsuba’s algorithm but too complicated to explain or implement here.) under a minute (47 sec). Which is in order of (5.5 * 10¹¹) computation. And we definitely did more computation since we had to calculate t, b, T, B. There is definitely room for improvement. Do it yourself 👊 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*eGwWD4pazQBTw57nMrGTjw.png" /></figure><h3>Comparison</h3><p>As we discussed previously, Core i5 and GTX1050ti are comparable as they are similarly priced. With a single core of core i5, it took us 2500 sec (42 min) to compute matrix multiplication for (4096 X 4096 ) sized matrices. Even if we were optimistic; it seems like it would take at least 10 (min) if we would have used all four cores. But as we can see from the graph for (4096 X4096 ) the GPU took only 5.5 sec. So the GPU was 113 times faster even with this naive approach. We also were able to (8192 X 8192 ) in 47 sec but it was infeasible for the CPU.</p><h3>Code</h3><p>The full code can be found in the following link.</p><p><a href="https://github.com/Saad-Mahmud/PPCUDA/">Saad-Mahmud/PPCUDA</a></p><p>Here is the gist for this part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cadbf7537ea04403a18218dcdb6dd8cf/href">https://medium.com/media/cadbf7537ea04403a18218dcdb6dd8cf/href</a></iframe><p><strong>Update: </strong><a href="https://medium.com/@saadmahmud14/parallel-programming-with-cuda-tutorial-part-4-the-floyd-warshall-algorithm-5e1281c46bf6"><strong>Here is the link to part 4</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c29b7628a289" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallel Programming With CUDA Tutorial (Part-2: Basics)]]></title>
            <link>https://saadmahmud14.medium.com/parallel-programming-with-cuda-tutorial-part-2-96f6eaea2832?source=rss-88ac6bbf2c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/96f6eaea2832</guid>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <dc:creator><![CDATA[Saaduddin Mahmud]]></dc:creator>
            <pubDate>Fri, 03 Aug 2018 19:26:02 GMT</pubDate>
            <atom:updated>2019-02-13T13:05:21.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8WS8H3MTFjfew1sNSilePw.png" /></figure><p>In this tutorial, we will start coding. We will do both the sequential and the parallel version of the problem we want to solve. We will also give an overview of the general architecture of how threads are organized. We will also do some performance analysis.</p><p><strong>Hardware Specification: </strong>I am using an <strong>Nvidia 1050ti 4GB. </strong>And a <strong>Core i5–7500 CPU @ 3.40GHz </strong>with<strong> 16GB DDR4 2400MHz </strong>memory. Both of them are comparable in price; Nvidia GPU being cheaper in price.</p><p>First, let’s define the problem we are going to solve. It is quite a difficult one 😉:</p><blockquote><strong>Problem: </strong>Given two array <strong>X</strong> and <strong>Y</strong> of <strong>N</strong> floating point numbers, add the number in each index of <strong>X</strong> with the number in corresponding index of <strong>Y</strong> and save the result in <strong>Y</strong>. i.e. <strong>Y[i]=X[i]+Y[i]</strong> where <strong>0≤i&lt;N</strong></blockquote><p>I have chosen this problem because it is easy to understand in both in sequential and parallel form. Now let’s write the code for sequential version and benchmark it.</p><h3>Sequential Version:</h3><p>The function <strong>add</strong> takes input <strong>N, X, Y</strong> and completes the task in the problem. It does not need to return any value as we will be sending Pointer of array X and Y. The <strong>add</strong> function is given below:</p><pre>void add(int N, float *X, float *Y)<br>{<br>   for (int i=0; i&lt;N; i++)<br>   {  <br>      Y[i] = X[i] + Y[i];<br>   }<br>}</pre><p>We will run our add function 10 times and will calculate average execution time. The full code is given below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/011ca24b145d55c3cf7894dfdff8836c/href">https://medium.com/media/011ca24b145d55c3cf7894dfdff8836c/href</a></iframe><p>We took N=2²⁷. On Average, it took the CPU about 332.82 ms. Now let’s dive into parallel programming.</p><h3>Parallel Version:</h3><h4>Algorithm:</h4><p>First, let’s talk about our strategy on making the algorithm parallel. Here is what we will do:</p><ul><li>We will take <strong>T</strong> threads.</li><li>For thread number <strong>t </strong>where<strong> 0≤t&lt;T </strong>it will work on index <strong>t+aT</strong> where <strong>a≥0 </strong>and <strong>t+aT&lt;N.</strong></li><li>An example will make it clear. Suppose we take 32 thread. So T=32.</li><li>Thread number 0 will work on index 0+0*32, 0+1* 32 , 0+2*32 i.e. 0,32,64,96,128… and so on while <strong>t+aT&lt;N.</strong></li><li>Thread number 1 will work on index 1+0*32, 1+1* 32 , 1+2*32 i.e. 1,33,65,97,129… and so on while <strong>t+aT&lt;N.</strong></li><li>This way we will divide the array among threads equally.</li></ul><p>Now we have to implement this on GPU. Let’s start doing it by creating an add function that each thread on our GPU will run. We will do it by following the pseudo code below:</p><pre>ADD(N,X,Y):<br>  t = Current thread number<br>  T = Total number of threads<br>  i = t<br>  while i&lt;N:<br>    Y[i] = X[i]+Y[i]<br>    i=i+T</pre><p>Seeing this pseudo code we can see that we will need the Current thread number as well as the total number of threads. It is quite easy to get that information with CUDA. But to understand it we first have to know the general architecture of how threads are organized.</p><h4>Organization of Threads:</h4><p>All our <strong>Threads</strong> are organized in <strong>Blocks. </strong>We can organize our threads in 1,2 or 3-dimensional blocks. Blocks are organized in <strong>Grids. </strong>We can organize our blocks in 1,2 or 3-dimensional grids. In the picture below we have 2D blocks of threads organized in a 2D grid of blocks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*Sxi3I91jSsZqPAY5AnoN1Q.png" /><figcaption><em>Grids of Thread Blocks</em></figcaption></figure><p>A function that the GPU can run, is called a <strong><em>kernel</em></strong> in CUDA. A GPU can run many concurrent Kernels each of which uses a grid. But how many grids can we have and how many blocks per grid and how many threads per block? The maximum number of resident grids depends on your GPU’s Compute capability. Numbers are given in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tim5lswQT-2RNnrjGgs5qA.png" /><figcaption>Size Specification</figcaption></figure><p>In this tutorial, we will use one-dimensional thread blocks and only one block in our grid for simplicity.</p><h4>Implementation:</h4><ol><li>How to tell the GPU that a function is a Kernel?</li></ol><p>Add <strong>__global__</strong> before it. so void add(int N, float *X, float *Y) becomes __global__ void add(int N,float *X, float *Y)</p><p>2. How to get Current thread number and the Total number of threads?</p><p>There are 4 variables each thread can access which contains information about the organization of threads and current thread. They are:</p><ul><li><strong>threadIdx : </strong>Id of the current thread.</li><li><strong>blockIdx : </strong>Id of the current block.</li><li><strong>blockDim : </strong>Size of each dimension of the current block.</li><li><strong>gridDim : </strong>Size of each dimension of the current grid.</li></ul><p>All of these are <strong>dim3 structure</strong>. we can use dot notation to access variable <strong>x,y,z </strong>which contains the information of the corresponding dimension. Example: <strong>threadIdx.x</strong></p><p>That is all we need to implement our new add function:</p><pre>__global__<br>void add(int n, float *x, float *y)<br>{<br>  int t = threadIdx.x;<br>  int T = blockDim.x;<br>  for (int i = t; i &lt; n; i += T)<br>      y[i] = x[i] + y[i];<br>}</pre><p>We will need 3 more things to finish up our code.</p><ul><li><strong>cudaMallocManaged(): </strong>Allocate Unified Memory accessible from CPU or GPU.</li><li><strong>cudaDeviceSynchronize():</strong> Wait for GPU to finish executing kernel.</li><li><strong>add&lt;&lt;&lt;dim3(1,1,1), dim3(T,1,1)&gt;&gt;&gt;(N, X, Y): </strong>To call add kernel. The first dim3(x,y,z) specifies the dimensions of the grid and the second one specifies the dimensions of the block. Since we are going to use one block in our grid and one-dimensional block with T threads we used &lt;&lt;&lt;dim3(1,1,1),dim3(T,1,1)&gt;&gt;&gt;<strong>.</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc37674dec59a14f11a71724edd1c05e/href">https://medium.com/media/fc37674dec59a14f11a71724edd1c05e/href</a></iframe><p>And we are done. With all this information we can write the full code as shown below. I have added some additional code to calculate performance and save it to a CSV file which you can skip.</p><h3>Performance Analysis:</h3><p>Using 1 GPU thread it takes about 22042.01 ms which is about 66 times slower than the CPU. But as we increase the number of threads it drops quite quickly at first and starts slowing down after it reaches about 400 threads. Using 1024 threads we can reach 46.54 ms which is about 7.1 times faster than the 1 CPU Core(I have neither exhausted the CPU nor the GPU). and about 475 times faster than using just one Thread. As we can see the relation between execution time and thread count is not linear. We can sum up our performance analysis with the graph below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSgUHFLE4utFn1gnyl9oQQ.png" /></figure><p><strong>Note:</strong> In the graph, for GPU we started showing the thread count starts from 32 because for 1 thread execution time is too high.</p><p>What if we want to use multiple blocks to speed up the process even faster. Just edit the add function as shown below:</p><pre>__global__<br>void add(int N, float *X, float *Y)<br>{<br>    int t= blockIdx.x * blockDim.x + threadIdx.x;<br>    int T = blockDim.x * gridDim.x;<br>    for (int i = t; i &lt; n; i += T)<br>        Y[i] = X[i] + Y[i];<br>}</pre><blockquote>Why are we calculating t and T this way? That is a exercise for you. Try to understand the definition of those 4 variable given above.</blockquote><ul><li>With 1 block each with 1024 threads, it is 46. 54 ms.</li><li>With 2 blocks each with 1024 threads, it becomes 27.8 ms.</li><li>With 4 blocks each with 1024 threads, it becomes 19.7 ms.</li><li>With 8 blocks each with 1024 threads, it becomes 17.7 ms.</li><li>With 16 blocks each with 1024 threads, it becomes 17.6 ms.</li><li>With 32 blocks each with 1024 threads, it becomes 17.4 ms.</li><li>With 256 blocks each with 1024 threads, it becomes 17.5 ms.</li></ul><p>After 8 blocks it does not help much. We will see in future problem how we can utilize blocks properly. Using 8*1024=8196 threads we become about 20 times faster than 1 CPU core. Graph of Performance analysis with different block size is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LA6SfI7wkbBcYaceDl2oDg.png" /></figure><p>You can find all my codes here:</p><p><a href="https://github.com/Saad-Mahmud/PPCUDA/">Saad-Mahmud/PPCUDA</a></p><p>Thanks for reading.</p><p><strong>Update: Here is the link for part-3</strong></p><p><a href="https://medium.com/@saadmahmud14/parallel-programming-with-cuda-tutorial-part-3-c29b7628a289">Parallel Programming With CUDA Tutorial (Part-3 Matrix Multiplication)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96f6eaea2832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallel Programming With CUDA Tutorial (Part-1: Setup)]]></title>
            <link>https://saadmahmud14.medium.com/parallel-programming-with-cuda-tutorial-part-1-8c72dda64d93?source=rss-88ac6bbf2c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c72dda64d93</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <dc:creator><![CDATA[Saaduddin Mahmud]]></dc:creator>
            <pubDate>Thu, 02 Aug 2018 15:40:55 GMT</pubDate>
            <atom:updated>2019-02-13T13:06:59.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8WS8H3MTFjfew1sNSilePw.png" /></figure><p>I will be posting a series of tutorial on this topic; this being the first one. In this first tutorial, I will give you an overview of this series. I will also show you how to set up the environment necessary for this tutorial series.</p><p>There are <strong>no hard prerequisites</strong> for this series of tutorials. But a little bit of knowledge in <strong>C++</strong> and <strong>Algorithm</strong> will help. We will be optimizing some well-known algorithm<strong> </strong>using parallel programming with CUDA.</p><p>I will be using <strong>Linux Ubuntu 17.10</strong> . And I will be using <strong>Geany</strong>; a very lightweight IDE (basically a text editor with an option for compiling and executing code) for this tutorial series. If you are on Windows or Mac you can still follow the upcoming tutorials. Just set up the environment on your own. Now go through following steps if you are on Ubuntu :</p><h4>STEP 1: Installing CUDA toolkit</h4><p>Run the following command on terminal. It will download about <strong>2 GB </strong>of data. So make sure you have a good internet connection.</p><pre>sudo apt-get install nvidia-cuda-toolkit</pre><h4>STEP 2: Installing g++ 4.8</h4><p>Ubuntu 17.10 comes with GCC-7 which is not compatible yet with CUDA(but look it up on the internet.). So Run the following command on terminal.</p><pre>sudo apt-get install g++-4.8</pre><h4><strong>STEP 3: Installing Geany</strong></h4><pre>sudo apt-get install geany</pre><p><strong>Note: </strong>To compile and run code without using Geany do the followings:</p><ul><li>Save your code in a text file with extension .cu . Example: filename.cu</li><li>Compile code using nvcc filename.cu -o filename command.</li><li>Run code using ./filename command.</li><li>In order to run your code with profiling use nvprof --unified-memory-profiling off ./filename This “--unified-memory-profiling off” is used because without it nvprof creates error sometimes. So you may give it a try without using it and see if you get any error. (What is profiling? It helps us measure the performance of our code.)</li></ul><p>Writing all this every time might be a pain. So I will show you how to configure Geany so that it does it for us.</p><h4>STEP 4: Configuring Geany</h4><ol><li>Open Geany</li><li>Open a new file and save it with .cu extension</li><li>Copy the following block of codes. I will explain the code in the next tutorial.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d79e794809ae6cac98c695d7f3c2c769/href">https://medium.com/media/d79e794809ae6cac98c695d7f3c2c769/href</a></iframe><p>4. After that go to <strong>Build </strong>&gt; <strong>Set Build Commands.</strong></p><p>5. Now configure it like the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDBvwvNPY1MAu2pMo2teow.png" /></figure><p>6. Use <strong>F8/F9</strong> to Compile/Build your code. Use <strong>F5</strong> to run your code. Use <strong>Build&gt; ExProfile</strong> to run it with ‘nvprof’. Note: the name ‘ExProfile’ is given by me. You may set up your own.</p><p>7. Now if you try to run your code it should run. Note that you have to do this only once. After that, each time you open up a file with .cu extension Geany will use this set of build command.</p><p>We will start coding from the next tutorial. Thank you for reading.</p><p><strong>Update: Here is the link for part-2</strong></p><p><a href="https://medium.com/@saadmahmud14/parallel-programming-with-cuda-tutorial-part-2-96f6eaea2832">Parallel Programming With CUDA Tutorial (Part-2: Basics)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c72dda64d93" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>