<?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 Kartik Sirohi  on Medium]]></title>
        <description><![CDATA[Stories by Kartik Sirohi  on Medium]]></description>
        <link>https://medium.com/@kartik.orion.dev?source=rss-aa02e105d731------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yIuU1Z_fUN0OM7sLNT_FaA.jpeg</url>
            <title>Stories by Kartik Sirohi  on Medium</title>
            <link>https://medium.com/@kartik.orion.dev?source=rss-aa02e105d731------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:03:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kartik.orion.dev/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[From 44 GFLOP/s to 376 GFLOP/s: Learning GPU Performance Through MatMul]]></title>
            <link>https://medium.com/@kartik.orion.dev/from-44-gflop-s-to-376-gflop-s-learning-gpu-performance-through-matmul-a88bcf2b7092?source=rss-aa02e105d731------2</link>
            <guid isPermaLink="false">https://medium.com/p/a88bcf2b7092</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[cuda-programming]]></category>
            <dc:creator><![CDATA[Kartik Sirohi ]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 14:14:04 GMT</pubDate>
            <atom:updated>2026-09-06T17:19:11.418Z</atom:updated>
            <content:encoded><![CDATA[<p>I am new to CUDA and GPU Programming and so one of the best problems a beginner can work on is to take an operation, implement it on the GPU, benchmark it, optimize it, repeat.</p><p>That’s what I did for a matmul kernel. If you understand basic CUDA and want to learn more about it, this is a pretty good place to be. Enjoy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WHapxSv8X22yD7jF" /></figure><h3>Running CUDA on a Mac</h3><p>The first problem I had to solve was, how do i actually run CUDA on my M1 Air. I first tried to do the usual ssh stuff by making a kaggle notebook run a server that would allow me to run my CUDA code on the P100 GPU kaggle gives out for free. This worked but then I came across <a href="https://github.com/Lulzx/cuda-metal">https://github.com/Lulzx/cuda-metal</a>.</p><p>cuda-metal allows you to compile CUDA code, then it maps it to Metal code which is the GPU programming framework for the Apple Silicon GPU. This allows you to actually run CUDA on an Apple GPU. It’s not very matured yet as a single angel from heaven <a href="https://github.com/Lulzx">Lulzx</a> maintains it.</p><h3>Vector Addition Kernel</h3><p>So now that running CUDA was sorted, it was time for my first kernel which is the one you would find a book such as Cuda by Example as the hello world of the CUDA world.</p><p>This is a vector addition kernel and it is actually pretty easy to get started with it. You really don’t have to care much about anything really cause addition of two vectors is an intuitively parallel operation and one can easily implement it.</p><p>To add two vectors you can simply have one thread handle one element. The following kernel implements parallel vector addition.</p><pre>__global__ void add(int *a, int *b, int *c, int n) {<br>    int i = threadIdx.x + blockIdx.x * blockDim.x;<br>    if (i &lt; n)<br>        c[i] = a[i] + b[i];<br>}</pre><p>It finds out the threadID from the threadIdx and the BlockIdx which basically uniquely assigns each index to a threadID. Then during execution each thread adds the corresponding elements of the two vectors.</p><h3>Matmul</h3><p>That was easy. But matmul is where it starts to get real. Let’s go deep into how I progressed through this operation.</p><h4>Sequential Algorithm</h4><p>The usual sequential O(N³) algorithm is pretty famous and intuitive once you get your hands dirty with a pen and a paper.</p><p>I derived the algorithm by working through a matrix A of size M x K and another matrix B of size K x N.</p><p>To obtain the final matrix C of size M x N, one can follow this algorithm:</p><pre><br>for(int i=0;i&lt;M;i++)<br>  <br>   for(int k=0;k&lt;N;k++)<br>      <br>      for(int j=0;j&lt;K;j++)<br><br>        C[i][k] += A[i][j] * B[j][k];</pre><p>The above algorithm runs sequentially on a CPU which basically calculates each element one by one with no parallelism whatsoever.</p><h4>Naive Parallel Kernel</h4><p>Moving to a parallel implementation, we can use CUDA threads to parallelize this operation. Think of how you multiply two matrices, you take one row from the first one and one column from the second one and you do a dot product between those two to obtain one element of the resultant matrix.</p><p>This operation has high potential for parallelism because we can take one row, column pair per thread and execute this operation.</p><p>We can take threads in two different directions to account for rows and columns of the two matrices being operated upon.</p><p>The following kernel shows the naive parallel matrix multiplication :</p><pre>__global__ void matrix_multiplication_kernel(<br>    const float* A,<br>    const float* B,<br>    float* C,<br>    int M,<br>    int K,<br>    int N<br>) {<br>    int i = threadIdx.x + blockDim.x * blockIdx.x;<br>    int k = threadIdx.y + blockDim.y * blockIdx.y;<br><br>    if (i &lt; M &amp;&amp; k &lt; N) {<br><br>        float sum = 0.0f;<br><br>        for (int j = 0; j &lt; K; j++) {<br>            sum += A[i * K + j] * B[j * N + k];<br>        }<br><br>        C[i * N + k] = sum;<br>    }<br>}</pre><p>Upon benchmarking this kernel I got the following results :</p><pre>Matrix dimensions:<br>A: 4096 x 4096<br>B: 4096 x 4096<br>C: 4096 x 4096<br><br>Iterations: 20<br>Average kernel time: 3078.51 ms<br>Performance: 44.6446 GFLOP/s</pre><p>So we are at 44.644 GFLOP/s, hmm sounds fast right? Actually if you compare this to the actual theoretical compute power of my GPU you would be surprised.</p><p>The theoretical FP32 throughput commonly quoted for the 8-core M1 GPU is around 2.6 TFLOP/s as per <a href="https://www.gpu-monkey.com/en/benchmark-apple_m1_8_core_gpu-fp32">online sources</a>. So this is not even 2 percent of the total compute available to me.</p><p>So let’s optimize this further.</p><h4>Tiled Matmul Kernel</h4><p>The first thing I wanted to understand was why the naive kernel was so slow.</p><p>The actual computation isn’t particularly complicated. For every element of C , a thread performs a dot product between a row of A and a column of B.</p><p>The problem is that the same elements of A and B are needed by many different threads.</p><p>For example, if multiple threads are computing different elements of the same row of C, they all need values from the same row of A.</p><p>Similarly, they will be pulling values from B that are repeatedly needed by other threads.</p><p>So the question becomes:</p><p>Why keep going back to global memory for data that the threads are going to reuse?</p><p>This is where tiling comes in.</p><p>Instead of having threads repeatedly access the matrices directly from global memory, we divide the matrices into smaller tiles and cooperatively load those tiles into <strong>shared memory</strong>.</p><p>Each block is scheduled to run over a Streaming Multiprocessor and hence the threads inside one block have a shared memory which is closer to the SM. Hence if we can cache the tile of the matrix in this memory then we do not need to go to the global memory to fetch data that we are using again and again.</p><p>Suppose you tile a 16 by 16 part of the matrix, then you would only need to pay the price of going to the global memory once and then for the rest of the operation you can use the tiled data to calculate the resultant element.</p><p>The following kernel does tiled matmul operation :</p><pre>#define TILE_SIZE 16<br><br>__global__ void matrix_multiplication_kernel(<br>    const float* A,<br>    const float* B,<br>    float* C,<br>    int M,<br>    int K,<br>    int N<br>) {<br><br><br>    __shared__ float tileA[TILE_SIZE][TILE_SIZE];<br>    __shared__ float tileB[TILE_SIZE][TILE_SIZE];<br><br>    <br>    float sum = 0.0f;<br><br>    int row = threadIdx.y + blockIdx.y * TILE_SIZE;<br>    int col = threadIdx.x + blockIdx.x * TILE_SIZE;<br>    <br>    int numTiles = (K + TILE_SIZE -1) / TILE_SIZE;<br><br>    <br>    for (int t = 0; t &lt; numTiles; t++) {<br><br>        // Global positions this thread loads<br>        int A_col = t * TILE_SIZE + threadIdx.x;<br>        int B_row = t * TILE_SIZE + threadIdx.y;<br><br>        // Load A tile<br>        if (row &lt; M &amp;&amp; A_col &lt; K) {<br>            tileA[threadIdx.y][threadIdx.x] =<br>                A[row * K + A_col];<br>        } else {<br>            tileA[threadIdx.y][threadIdx.x] = 0.0f;<br>        }<br><br>        // Load B tile<br>        if (B_row &lt; K &amp;&amp; col &lt; N) {<br>            tileB[threadIdx.y][threadIdx.x] =<br>                B[B_row * N + col];<br>        } else {<br>            tileB[threadIdx.y][threadIdx.x] = 0.0f;<br>        }<br><br>        // Make sure the entire tile is loaded<br>        __syncthreads();<br><br>        // Compute using shared memory<br>        #pragma unroll<br>        for (int j = 0; j &lt; TILE_SIZE; j++) {<br>            sum += tileA[threadIdx.y][j] *<br>                   tileB[j][threadIdx.x];<br>        }<br><br>        // Make sure nobody overwrites the tile<br>        // while another thread is still using it<br>        __syncthreads();<br>    }<br><br>     // Write result<br>    if (row &lt; M &amp;&amp; col &lt; N) {<br>        C[row * N + col] = sum;<br>    }<br><br><br>}</pre><p>I also used loop unrolling in this kernel to get some more speed out of it as loop unrolling can help us avoid loop overhead and potentially expose more independent instructions to the compiler.</p><p>On benchmarking this kernel I got :</p><pre>Matrix dimensions:<br>A: 4096 x 4096<br>B: 4096 x 4096<br>C: 4096 x 4096<br><br>Iterations: 20<br>Average kernel time: 755.416 ms<br>Performance: 181.938 GFLOP/s</pre><p>Boom! From 44 to 181, that’s a <strong>4.07× </strong>improvement.</p><h4>Register Tiled Matmul</h4><p>Can we go further? Yes, we can.</p><p>Now that we had optimized the memory access via tiling, how about we optimize per thread performance.</p><p>This is where <strong>register tiling</strong> comes in.</p><p>In our tiled kernel, each thread was responsible for calculating just <strong>one element of </strong>C. That means each thread maintains one accumulator:</p><pre>float sum = 0.0f;</pre><p>But we can make each thread calculate multiple elements of C instead.</p><p>For example, instead of one thread calculating:</p><pre>C[i][j]</pre><p>we can make it calculate a small 2 × 2 block:</p><pre>C[i][j]       C[i][j+1]<br>C[i+1][j]     C[i+1][j+1]</pre><p>This gives the thread four accumulators:</p><pre>float c00 = 0.0f;<br>float c01 = 0.0f;<br>float c10 = 0.0f;<br>float c11 = 0.0f;</pre><p>These values can live in <strong>registers</strong>, which are private to each thread and are among the fastest storage available to the thread.</p><p>So instead of having a 16 × 16 output tile computed by 256 threads, we can use fewer threads, with each thread doing more computation.</p><p>The following code shows the register tiled kernel :</p><pre>#define TILE_SIZE 16<br>#define THREAD_TILE 2<br><br>__global__ void matrix_multiplication_kernel(<br>    const float* A,<br>    const float* B,<br>    float* C,<br>    int M,<br>    int K,<br>    int N<br>) {<br>    __shared__ float tileA[TILE_SIZE][TILE_SIZE];<br>    __shared__ float tileB[TILE_SIZE][TILE_SIZE];<br><br>    // 8x8 threads<br>    // Each thread computes a 2x2 section of C<br><br>    int tx = threadIdx.x;<br>    int ty = threadIdx.y;<br><br>    // Top-left output computed by this thread<br>    int row = blockIdx.y * TILE_SIZE + ty * THREAD_TILE;<br>    int col = blockIdx.x * TILE_SIZE + tx * THREAD_TILE;<br><br><br>    // Four accumulators<br>    //<br>    // These should live in registers<br><br><br>    float c00 = 0.0f;<br>    float c01 = 0.0f;<br>    float c10 = 0.0f;<br>    float c11 = 0.0f;<br><br>    int numTiles = (K + TILE_SIZE - 1) / TILE_SIZE;<br><br>    for (int t = 0; t &lt; numTiles; t++) {<br><br>        // Load A tile<br><br>        //<br>        // We only have 8x8 = 64 threads,<br>        // but need to load 16x16 = 256 elements.<br>        //<br>        // Each thread therefore loads 4 elements.<br>        //<br><br>        int aRow = ty * THREAD_TILE;<br>        int aCol = tx * THREAD_TILE;<br><br>        for (int dy = 0; dy &lt; THREAD_TILE; dy++) {<br>            for (int dx = 0; dx &lt; THREAD_TILE; dx++) {<br><br>                int globalRow =<br>                    blockIdx.y * TILE_SIZE +<br>                    aRow + dy;<br><br>                int globalCol =<br>                    t * TILE_SIZE +<br>                    aCol + dx;<br><br>                if (globalRow &lt; M &amp;&amp; globalCol &lt; K) {<br>                    tileA[aRow + dy][aCol + dx] =<br>                        A[globalRow * K + globalCol];<br>                } else {<br>                    tileA[aRow + dy][aCol + dx] = 0.0f;<br>                }<br>            }<br>        }<br><br><br>        // Load B tile<br><br>        int bRow = ty * THREAD_TILE;<br>        int bCol = tx * THREAD_TILE;<br><br>        for (int dy = 0; dy &lt; THREAD_TILE; dy++) {<br>            for (int dx = 0; dx &lt; THREAD_TILE; dx++) {<br><br>                int globalRow =<br>                    t * TILE_SIZE +<br>                    bRow + dy;<br><br>                int globalCol =<br>                    blockIdx.x * TILE_SIZE +<br>                    bCol + dx;<br><br>                if (globalRow &lt; K &amp;&amp; globalCol &lt; N) {<br>                    tileB[bRow + dy][bCol + dx] =<br>                        B[globalRow * N + globalCol];<br>                } else {<br>                    tileB[bRow + dy][bCol + dx] = 0.0f;<br>                }<br>            }<br>        }<br><br><br>        // Wait until entire tile is loaded<br><br>        __syncthreads();<br><br>        // Compute 2x2 output<br><br>        #pragma unroll<br>        for (int j = 0; j &lt; TILE_SIZE; j++) {<br><br>            float a0 = tileA[ty * 2 + 0][j];<br>            float a1 = tileA[ty * 2 + 1][j];<br><br>            float b0 = tileB[j][tx * 2 + 0];<br>            float b1 = tileB[j][tx * 2 + 1];<br><br>            c00 += a0 * b0;<br>            c01 += a0 * b1;<br>            c10 += a1 * b0;<br>            c11 += a1 * b1;<br>        }<br><br><br>        // Make sure everyone is done reading before we overwrite<br>        // the shared-memory tiles<br><br>        __syncthreads();<br>    }<br><br><br>    // Store 2x2 result<br><br>    if (row &lt; M &amp;&amp; col &lt; N) {<br>        C[row * N + col] = c00;<br>    }<br><br>    if (row &lt; M &amp;&amp; col + 1 &lt; N) {<br>        C[row * N + col + 1] = c01;<br>    }<br><br>    if (row + 1 &lt; M &amp;&amp; col &lt; N) {<br>        C[(row + 1) * N + col] = c10;<br>    }<br><br>    if (row + 1 &lt; M &amp;&amp; col + 1 &lt; N) {<br>        C[(row + 1) * N + col + 1] = c11;<br>    }<br>}</pre><p>The results achieved by this kernel were :</p><pre>Matrix dimensions:<br>A: 4096 x 4096<br>B: 4096 x 4096<br>C: 4096 x 4096<br><br>Iterations: 20<br>Average kernel time: 468.021 ms<br>Performance: 293.66 GFLOP/s</pre><h4>Vectorized Register-Tiled MatMul</h4><p>Register tiling gave us another improvement, but I wanted to see if I could push the memory side of the kernel further as well.</p><p>The idea behind vectorization is simple: instead of loading individual float values from global memory, we can load multiple consecutive values at once using a float4. A float4 contains four floats, so one load brings in 16 bytes of data.</p><p>This is particularly useful when loading our tiles because the four values are consecutive in memory. Rather than having separate scalar loads for each value, we can use a single vectorized load and then unpack the four values into shared memory.</p><p>There was an important detail here, though: the starting address of the float4 load needs to be 16-byte aligned. Since our threads are loading different portions of a 16 × 16 tile, I had to carefully map the threads to the tile so that each vectorized load starts at columns 0,4,8 or 12. This meant decoupling the memory-loading layout from the 2 × 2 output layout that each thread was computing.</p><p>The kernel is given below :</p><pre>__global__ void matrix_multiplication_kernel(<br>    const float* A,<br>    const float* B,<br>    float* C,<br>    int M,<br>    int K,<br>    int N<br>) {<br>    __shared__ float tileA[TILE_SIZE][TILE_SIZE];<br>    __shared__ float tileB[TILE_SIZE][TILE_SIZE];<br><br>    int tx = threadIdx.x;<br>    int ty = threadIdx.y;<br><br><br>    // Each thread computes a 2x2 section of C<br><br>    int row =<br>        blockIdx.y * TILE_SIZE +<br>        ty * THREAD_TILE;<br><br>    int col =<br>        blockIdx.x * TILE_SIZE +<br>        tx * THREAD_TILE;<br><br><br>    // Four values held in registers<br><br>    float c00 = 0.0f;<br>    float c01 = 0.0f;<br>    float c10 = 0.0f;<br>    float c11 = 0.0f;<br><br><br>    // Flatten the 8x8 thread block<br>    //<br>    // 8 x 8 = 64 threads<br>    //<br>    // Each thread loads one float4 = 4 floats<br>    //<br>    // 64 x 4 = 256 floats<br>    //<br>    // 16 x 16 = 256 floats<br>    //<br>    // Therefore every element of the tile is loaded exactly once.<br><br><br>    int tid =<br>        ty * blockDim.x +<br>        tx;<br><br>    int loadRow =<br>        tid / 4;<br><br>    int loadCol =<br>        (tid % 4) * 4;<br><br><br>    int numTiles =<br>        (K + TILE_SIZE - 1) / TILE_SIZE;<br><br><br>    // Iterate over K dimension<br><br><br>    for (int t = 0; t &lt; numTiles; t++) {<br><br><br>        // Load A tile<br><br>        int globalARow =<br>            blockIdx.y * TILE_SIZE +<br>            loadRow;<br><br>        int globalACol =<br>            t * TILE_SIZE +<br>            loadCol;<br><br><br>        if (<br>            globalARow &lt; M &amp;&amp;<br>            globalACol + 3 &lt; K<br>        ) {<br><br>            // float4 = 4 floats = 16 bytes<br>            //<br>            // loadCol is always:<br>            //<br>            // 0, 4, 8, 12<br>            //<br>            // so the pointer is 16-byte aligned for our<br>            // 4096-wide matrices.<br><br>            const float4* ptr =<br>                reinterpret_cast&lt;const float4*&gt;(<br>                    &amp;A[<br>                        globalARow * K +<br>                        globalACol<br>                    ]<br>                );<br><br>            float4 value = ptr[0];<br><br><br>            tileA[loadRow][loadCol + 0] = value.x;<br>            tileA[loadRow][loadCol + 1] = value.y;<br>            tileA[loadRow][loadCol + 2] = value.z;<br>            tileA[loadRow][loadCol + 3] = value.w;<br><br>        } else {<br><br>            // Boundary-safe fallback<br><br>            for (int i = 0; i &lt; 4; i++) {<br><br>                int c =<br>                    globalACol + i;<br><br>                int localCol =<br>                    loadCol + i;<br><br>                if (<br>                    globalARow &lt; M &amp;&amp;<br>                    c &lt; K<br>                ) {<br>                    tileA[loadRow][localCol] =<br>                        A[<br>                            globalARow * K +<br>                            c<br>                        ];<br>                } else {<br>                    tileA[loadRow][localCol] =<br>                        0.0f;<br>                }<br>            }<br>        }<br><br><br>        // Load B tile<br><br>        int globalBRow =<br>            t * TILE_SIZE +<br>            loadRow;<br><br>        int globalBCol =<br>            blockIdx.x * TILE_SIZE +<br>            loadCol;<br><br><br>        if (<br>            globalBRow &lt; K &amp;&amp;<br>            globalBCol + 3 &lt; N<br>        ) {<br><br>            const float4* ptr =<br>                reinterpret_cast&lt;const float4*&gt;(<br>                    &amp;B[<br>                        globalBRow * N +<br>                        globalBCol<br>                    ]<br>                );<br><br>            float4 value = ptr[0];<br><br><br>            tileB[loadRow][loadCol + 0] = value.x;<br>            tileB[loadRow][loadCol + 1] = value.y;<br>            tileB[loadRow][loadCol + 2] = value.z;<br>            tileB[loadRow][loadCol + 3] = value.w;<br><br>        } else {<br><br>            // Boundary-safe fallback<br><br>            for (int i = 0; i &lt; 4; i++) {<br><br>                int c =<br>                    globalBCol + i;<br><br>                int localCol =<br>                    loadCol + i;<br><br>                if (<br>                    globalBRow &lt; K &amp;&amp;<br>                    c &lt; N<br>                ) {<br>                    tileB[loadRow][localCol] =<br>                        B[<br>                            globalBRow * N +<br>                            c<br>                        ];<br>                } else {<br>                    tileB[loadRow][localCol] =<br>                        0.0f;<br>                }<br>            }<br>        }<br><br><br>        // Wait for entire tile to be loaded<br><br>        __syncthreads();<br><br>        // Compute<br>        //<br>        // Each thread computes a 2x2 C tile.<br>        //<br>        // Everything below is reused from shared memory.<br><br>        #pragma unroll<br>        for (int j = 0; j &lt; TILE_SIZE; j++) {<br><br>            float a0 =<br>                tileA[<br>                    ty * 2 + 0<br>                ][j];<br><br>            float a1 =<br>                tileA[<br>                    ty * 2 + 1<br>                ][j];<br><br><br>            float b0 =<br>                tileB[j][<br>                    tx * 2 + 0<br>                ];<br><br>            float b1 =<br>                tileB[j][<br>                    tx * 2 + 1<br>                ];<br><br><br>            c00 += a0 * b0;<br>            c01 += a0 * b1;<br>            c10 += a1 * b0;<br>            c11 += a1 * b1;<br>        }<br><br><br>        // Make sure everyone has finished reading the tile<br>        // before it gets overwritten in the next iteration.<br><br><br>        __syncthreads();<br>    }<br><br>    // Store the 2x2 result<br><br>    if (row &lt; M &amp;&amp; col &lt; N) {<br><br>        C[<br>            row * N + col<br>        ] = c00;<br>    }<br><br><br>    if (row &lt; M &amp;&amp; col + 1 &lt; N) {<br><br>        C[<br>            row * N + col + 1<br>        ] = c01;<br>    }<br><br><br>    if (row + 1 &lt; M &amp;&amp; col &lt; N) {<br><br>        C[<br>            (row + 1) * N + col<br>        ] = c10;<br>    }<br><br><br>    if (<br>        row + 1 &lt; M &amp;&amp;<br>        col + 1 &lt; N<br>    ) {<br><br>        C[<br>            (row + 1) * N + col + 1<br>        ] = c11;<br>    }<br>}<br></pre><p>After fixing the alignment and tile-loading logic, I benchmarked the kernel again:</p><pre>Matrix dimensions:<br>A: 4096 x 4096<br>B: 4096 x 4096<br>C: 4096 x 4096<br><br>Iterations: 20<br><br>Average kernel time: 365.357 ms<br>Performance: 376.177 GFLOP/s</pre><p>So we had gone from roughly <strong>44 GFLOP/s to 376GFLOP/s</strong>.</p><p>That’s a little over a <strong>8.4×</strong> <strong>improvement</strong> over the original naive kernel.</p><p>What started as a straightforward matrix multiplication kernel had now turned into a kernel using multiple layers of optimization: shared-memory tiling to reduce global-memory traffic, register tiling to increase data reuse within each thread, and vectorized loads to improve how data is moved into the tiles.</p><h3>Validating on Real NVIDIA Hardware</h3><p>One thing I wanted to verify was whether these optimizations were actually CUDA optimizations, rather than something specific to cuda-metal’s CUDA-to-Metal translation.</p><p>So I took the exact same CUDA kernels and moved them to a Google Colab instance running a real <strong>NVIDIA Tesla T4</strong>. Instead of CuMetal, I compiled them using NVIDIA’s native CUDA compiler, nvcc, targeting the T4 with sm_75.</p><p>I kept the benchmark setup the same: 4096 × 4096 matrices and 20 iterations.</p><p>The results were:</p><pre>Naive MatMul<br><br>Average kernel time: 1143.38 ms<br>Performance: 120.204 GFLOP/s<br><br>Tiled MatMul<br><br>Average kernel time: 218.299 ms<br>Performance: 629.589 GFLOP/s<br><br>Register-Tiled MatMul<br><br>Average kernel time: 208.239 ms<br>Performance: 660.006 GFLOP/s<br><br>Vectorized Register-Tiled MatMul<br><br>Average kernel time: 181.64 ms<br>Performance: 756.53 GFLOP/s</pre><p>The progression was sort of similar:</p><p><strong>120 → 630 → 660 → 756.53 GFLOP/s</strong></p><p>The final kernel was about <strong>6.3× faster than the naive implementation</strong> on the T4.</p><p>This doesn’t mean the M1 and T4 are directly comparable, they’re completely different GPU architectures. What this experiment does give me is a useful sanity check that the optimizations weren’t dependent on cuda-metal alone.</p><h3>Me vs Apple</h3><p>I used GPT to generate an MPS version of the same throughput test so I could see how my kernel compared against Apple’s highly optimized matrix multiplication implementation.</p><p>The results were:</p><pre>Apple M1<br><br>Iterations: 20<br>Average time: 100.149 ms<br>Performance: 1372.35 GFLOP/s</pre><p>My final custom CUDA kernel reached <strong>376 GFLOP/s</strong>, while Apple’s MPS implementation reached <strong>1372 GFLOP/s</strong>.</p><p>So my kernel is running at roughly <strong>27% of the performance of Apple’s optimized implementation</strong>. That’s obviously still a big gap, but considering <strong>44 GFLOP/s </strong>was where it started, I’m pretty happy with the result.</p><p>More importantly, this gave me a useful reference point for understanding just how much optimization is still left on the table.</p><h3>CPU vs GPU</h3><p>For comparison, I also ran the same 4096 × 4096 matrix multiplication using Apple’s Accelerate framework, which provides a highly optimized CPU GEMM implementation. Across 20 runs, it achieved <strong>881.426 GFLOP/s</strong>, with an average execution time of <strong>155.928 ms</strong>.</p><p>Interestingly, this was substantially faster than my final CUDA-Metal kernel on the M1, which reached <strong>376.177 GFLOP/s</strong>. That was a pretty humbling result, despite all the optimizations I had made to the GPU kernel, a heavily optimized library implementation on the CPU was still more than <strong>2× faster</strong>.</p><p>Libraries like Accelerate have years of optimization behind them, while my kernel was essentially my first attempt at understanding GPU performance from the ground up.</p><h3>Conclusion</h3><p>Honestly, this was a pretty fun rabbit hole.</p><p>I started with a <strong>44 GFLOP/s</strong> naive kernel and ended up at 376 <strong>GFLOP/s</strong> just by gradually understanding how the GPU was moving and reusing data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a88bcf2b7092" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Intuition Behind Neural Networks — One Parameter at a Time]]></title>
            <link>https://medium.com/@kartik.orion.dev/the-intuition-behind-neural-networks-one-parameter-at-a-time-c06787914470?source=rss-aa02e105d731------2</link>
            <guid isPermaLink="false">https://medium.com/p/c06787914470</guid>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Kartik Sirohi ]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 09:34:40 GMT</pubDate>
            <atom:updated>2025-07-23T09:34:40.872Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Intuition Behind Neural Networks — One Parameter at a Time</h3><h3>Introduction</h3><p>Neural Networks have transformed the modern world with their amazing ability to learn almost anything! Neural Networks can be regarded as function approximators that approximate a curve to fit the data they have been given to learn. They have the ability to change themselves in order to fit whatever the data is, but how does that happen? How do neural networks actually learn?</p><h3>Understanding Neural Networks — One Parameter at a Time</h3><p>Parameter — You must have heard this word used in the context of neural networks so many times, but what is it actually ? and how is it related to what we’re trying to do here?</p><p>Well, in general a parameter is a part of a bigger system that you can change to see the overall effect on that system. In the similar way parameters are quantities that a neural network keeps on changing during its training in order to fit the data that it needs to learn.</p><p>But where are these parameters located in a neural net?</p><p>Parameters can be found in the weight and bias <strong>tensors</strong> in the neural network. These parameters form these matrices which are then used to compute the result and then we try to change these parameters to improve our network’s result by calculating how bad our result is by comparing it to the actual value that we needed to calculate or predict and then we slightly change the values of our parameters in order to improve the result.</p><p><em>If you do not understand what tensors mean then just consider them as an alias for matrices.</em></p><p><strong>But how does this actually work ?</strong></p><p>To deeply understand how this works, let’s track one single parameter in a very simple neural network and then observe how it’s value changes during training.</p><p>Let’s take a very simple neural network which has only a single layer and activation function.</p><p>To construct the linear layer, we need two things — A weight matrix and a bias matrix. These two actually contain the parameters that we will need to change during training.</p><p>To initialise both of these matrices in PyTorch we can use</p><pre>Weight_matrix = torch.randn(input_shape,output_shape)<br>Bias_matrix = torch.randn(output_shape)</pre><p>The code given above intialises a weight tensor and a bias tensor of size (input_shape x output_shape) and output_shape respectively where input_shape is the number of features our dataset has or it can also be thought as the number of dimensions our input data has while output_shape is the number of features or dimensions we would like for our layer to project the output to.</p><p><strong>Now what does torch.randn() do </strong>?</p><p>torch.randn() selects random numbers from a normal distribution because in the beginning we do not know what value these parameters must have in order to give a good prediction so we start with a normally distributed random collection of parameters.</p><h3>Tracking a Parameter</h3><p>Let’s try to track the values of a single parameter here to understand how this all works. For this we will take the first element of the first row of the weight matrix or in programming terms:</p><pre>interesting_parameter = Weight_matrix[0][0]</pre><p>We will store the values of this parameter in an array upon training and then plot it to see how this changes with the training steps.</p><h3>Training the Model</h3><p>Now it’s time to train the model and keep track of the values of our parameter with the training.</p><p>It must be kept in mind that the intial value of the parameter will keep on changing on running the code again and again because it is a random value. However this actually helps us understand how does the parameter contribute to the overall performance of the model.</p><p>To train the model we iterate over 400 epochs, here each epoch means one complete iteration over the entire dataset of training data. In each epoch we store the values of our interesting_parameter in an array for each batch where batch is the number of inputs that are processed together to get the mean loss over the batch.</p><p>This mean loss is then used to compute the gradients of the weights and biases which is then used to update these weights and biases or parameters by using a learning rate in the following fashion:</p><pre>model.Weight_matrix.data -= learning_rate * grad_loss_W<br>model.Bias_matrix.data -= learning_rate * grad_loss_B</pre><p>This changes our parameters so our model can make better predictions.</p><p>This is only to show you how it works under the hood, in actual applications in PyTorch we use:</p><pre>loss.backward()<br>optimizer.step()</pre><p>The model actually uses gradient descent to nudge these parameters. During training the network calculates the gradient of the loss function with respect to the parameters represented by grad_loss_W and grad_loss_B.</p><p>These values are subtracted gradually from the parameters controlled by a learning_rate which is usually a very small value to allow gradual changes in the parameters for better and accurate fitting of the data.</p><p>Here we are trying to predict the values of y from X which is a 2 column matrix meaning the input has two dimensions. The task of predicting values of a variable from input is known as a <strong>Regression Task </strong>and the loss function <strong>Mean Squared Error (MSE) </strong>is mostly used in these tasks and we will be using the same.</p><p>No problem if you do not understand these terms as our main goal is to see how parameter changes happen and building main intuition.</p><blockquote>For the sake of understanding, just remember that the network realises if it has made a mistake and to calculate how bad the mistake is, it has a special function called a loss function.</blockquote><blockquote>After finding out how bad it has performed from that function, before predicting the next output, it changes the parameters that govern how it predicts by a small value in order to give better predictions next time.</blockquote><h3>Plotting the Parameter Values across Different Iterations</h3><p>Iteration 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-a2QfqpjZkArXk65nrCfA.png" /><figcaption>Parameter Values (Y axis)</figcaption></figure><p>Iteration 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXzOYuz0NLBrtKUT2z1Vww.png" /><figcaption>Parameter Values(Y axis)</figcaption></figure><p>We train for 400 epochs with a batch size of 16 on a dataset of size 100, resulting in roughly 2800 training steps, which are plotted on the x-axis.</p><p>From here one thing that we could see is that in iteration 1, the parameter starts off with a value less than 1 and then keeps on decreasing until after the 1000th value where it starts to increase.</p><p>In Iteration 2 the parameter starts off with a similar value but this time it increases and keeps on increasing reaching values even more than 14.</p><p>One fun exercise here can be to see the values of randomly selected parameters across the weight and bias matrices in order to see how different parameters are contributing to the network.</p><h3>But What Does This Tell Us?</h3><p>This observation shows us the most important thing about how a neural network learns: <strong>it’s an optimization process.</strong></p><p>In each training run, every parameter starts at a random value. The network then calculates how wrong its predictions are (the loss) and “nudges” every single parameter in the direction that should make the loss smaller.</p><ul><li>In <strong>Iteration 1</strong>, the network found that making this specific parameter more negative, in combination with changes to all other parameters, helped reduce the loss.</li><li>In <strong>Iteration 2</strong>, due to a different random start, the network discovered a different combination of parameter values where making this specific one more positive led to a better result.</li></ul><p>This tells us that a single parameter doesn’t have an “ideal” value on its own. Its job is simply to change in whatever way is needed, working together with all the other parameters, to collectively minimize the overall error of the network. It’s this constant, collective adjustment that allows the network to approximate the complex functions needed to solve a problem.</p><p><a href="https://colab.research.google.com/drive/1D8OO241u5-wEkiTTc4XOucSCPJaMQsAC?usp=sharing">Google Colab</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c06787914470" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>