<?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 Aniket Maheshwari on Medium]]></title>
        <description><![CDATA[Stories by Aniket Maheshwari on Medium]]></description>
        <link>https://medium.com/@aniketm2598?source=rss-50d97f3aa5ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LbOch_Jt5_O4uyhTpvFY_w.png</url>
            <title>Stories by Aniket Maheshwari on Medium</title>
            <link>https://medium.com/@aniketm2598?source=rss-50d97f3aa5ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:18:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aniketm2598/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[FlashAttention in Triton: Up to 1.7× Faster Than PyTorch's Attention on a Laptop GPU]]></title>
            <link>https://medium.com/@aniketm2598/flashattention-in-triton-up-to-1-7-faster-than-pytorchs-attention-on-a-laptop-gpu-e2c91e9b40cc?source=rss-50d97f3aa5ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2c91e9b40cc</guid>
            <dc:creator><![CDATA[Aniket Maheshwari]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 07:50:33 GMT</pubDate>
            <atom:updated>2026-12-01T08:03:41.336Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>5 GB to 32 MB: How FlashAttention Fits Long-Context Attention on a 6 GB GPU</strong></h3><p><em>Part 1 of 2. This part is the Triton kernel. Part 2 writes the same kernel in raw CUDA with tensor-core instructions.</em></p><p>I wrote the FlashAttention forward pass in Triton and benchmarked it on my laptop’s RTX 3050 (6 GB). At 8,192 tokens and head dimension 128, it runs in 64 ms. PyTorch’s memory-efficient attention takes 97 ms. A naive implementation that stores the full score matrix needs 5 GB of extra memory at 4,096 tokens and runs out of memory at 8,192.</p><p>Across sequence lengths from 512 to 8,192, the kernel is 1.15–1.68× faster than PyTorch’s scaled_dot_product_attention at head dim 128 and 1.02–1.39× faster at head dim 64. It sustains about 17 TFLOP/s for sequences of 1,024 tokens and longer.</p><p>This post covers why attention needs a special kernel at all, how FlashAttention works, the kernel line by line, the results, and two things that went wrong while measuring.</p><h3>The problem is bytes, not FLOPs</h3><p>Attention for one head is softmax(Q·Kᵀ / √d) · V. With N tokens, Q·Kᵀ is an N × N matrix of scores. The straightforward implementation does three steps:</p><ol><li>Compute S = Q·Kᵀ and write it to GPU memory.</li><li>Read S back, compute the softmax row by row, write P.</li><li>Read P back and multiply by V.</li></ol><p>The arithmetic is 4·N²·d FLOPs, which a GPU handles well. The problem is the N × N matrix. For 32 heads at N = 4,096 in FP16, S alone is 32 × 4,096² × 2 bytes = 1 GB, and the softmax produces more copies of the same size. My naive implementation needed <strong>5.1 GB of extra memory at N = 4,096</strong>. On a 6 GB card that left Windows paging GPU memory out to system RAM, and the time jumped from 25 ms at N = 2,048 to 1,082 ms at N = 4,096: 43× slower for 4× the work. At N = 8,192 it needs 20 GB and fails.</p><p>Even when it fits, every one of those reads and writes goes to DRAM. The memory traffic grows with N², and it, not the arithmetic, sets the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3adGrunk3nLL1riPlZI6xg.png" /></figure><p>FlashAttention computes exactly the same result without ever writing S or P to memory. Its only extra memory is the output, which is why both it and PyTorch’s kernel sit at 64 MB at N = 8,192: that’s the size of O itself.</p><h3>How FlashAttention works</h3><p>The idea combines three things.</p><p><strong>Tiling.</strong> Split Q into blocks of rows and K, V into blocks of keys. Load one Q block, then stream K and V blocks past it. Each score tile is small enough to live in registers and shared memory.</p><p><strong>Fusion.</strong> For each tile, compute the scores, the softmax contribution and the multiply by V inside one kernel. The tile never goes to DRAM.</p><p><strong>Online softmax.</strong> This is the part that makes tiling possible. Softmax needs the maximum and the sum of a whole row before it can normalize anything, but with tiling you only see one block of the row at a time. The fix is to keep three running values per query row and correct them as new tiles arrive:</p><ul><li>m: the largest score seen so far</li><li>l: the sum of exp(score − m) so far</li><li>o: the unnormalized output, Σ exp(score − m) · v so far</li></ul><p>When a new tile raises the maximum from m_old to m_new, everything accumulated so far was computed relative to the wrong maximum. Multiplying it by α = exp(m_old − m_new) fixes that:</p><pre>m_new = max(m_old, rowmax(S_tile))<br>α     = exp(m_old − m_new)<br>P     = exp(S_tile − m_new)<br>l     = α·l + rowsum(P)<br>o     = α·o + P·V_tile</pre><p>After the last tile, the output is o / l. The exp(−m) factors cancel between numerator and denominator, so the result is exactly softmax(S)·V, not an approximation. I wrote about the online softmax trick on its own in an earlier article; FlashAttention is that trick plus one extra line for o.</p><p>A tiny example. One query row sees scores 2 and 4 in two tiles of one key each, with values v₁ = [1, 0] and v₂ = [0, 1]:</p><ul><li>Tile 1: m = 2, l = 1, o = [1, 0].</li><li>Tile 2: m rises to 4, so α = e^(2−4) = 0.135. Then l = 0.135 + 1 = 1.135 and o = [0.135, 0] + [0, 1] = [0.135, 1].</li><li>Output: o / l = [0.119, 0.881].</li></ul><p>That matches softmax([2, 4]) = [0.119, 0.881] applied to the values directly.</p><h3>The kernel</h3><p>One Triton program handles BLOCK_M query rows of one (batch, head) pair and loops over all key/value blocks. This is the FlashAttention-2 loop order: the outer loop is over queries, so m, l and o stay in registers for the whole loop and O is written exactly once.</p><pre>@triton.jit<br>def _attn_fwd(Q, K, V, O, L, sm_scale, N, stride_h, stride_n,<br>              D: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, CAUSAL: tl.constexpr):<br>    pid_m = tl.program_id(0)                     # which block of queries<br>    bh = tl.program_id(1)                        # which (batch, head)<br>    offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)<br>    offs_n = tl.arange(0, BLOCK_N)<br>    offs_d = tl.arange(0, D)<br>    base = bh.to(tl.int64) * stride_h            # int64: B*H*N*D can exceed 2^31<br>    q = tl.load(Q + base + offs_m[:, None] * stride_n + offs_d[None, :],<br>                mask=offs_m[:, None] &lt; N, other=0.0)<br>    m_i = tl.full([BLOCK_M], float(&quot;-inf&quot;), tl.float32)<br>    l_i = tl.zeros([BLOCK_M], tl.float32)<br>    acc = tl.zeros([BLOCK_M, D], tl.float32)<br>    qk_scale = sm_scale * 1.4426950408889634     # exp(x) = exp2(x * log2 e)<br>    hi = N<br>    if CAUSAL:<br>        hi = tl.minimum((pid_m + 1) * BLOCK_M, N)  # skip key blocks above the diagonal<br>    for start_n in range(0, hi, BLOCK_N):<br>        cols = start_n + offs_n<br>        k = tl.load(K + base + cols[None, :] * stride_n + offs_d[:, None],<br>                    mask=cols[None, :] &lt; N, other=0.0)   # loaded as K^T<br>        s = tl.dot(q, k) * qk_scale<br>        valid = cols[None, :] &lt; N<br>        if CAUSAL:<br>            valid = valid &amp; (offs_m[:, None] &gt;= cols[None, :])<br>        s = tl.where(valid, s, float(&quot;-inf&quot;))<br>        m_new = tl.maximum(m_i, tl.max(s, 1))<br>        alpha = tl.exp2(m_i - m_new)<br>        p = tl.exp2(s - m_new[:, None])<br>        l_i = l_i * alpha + tl.sum(p, 1)<br>        v = tl.load(V + base + cols[:, None] * stride_n + offs_d[None, :],<br>                    mask=cols[:, None] &lt; N, other=0.0)<br>        acc = acc * alpha[:, None] + tl.dot(p.to(v.dtype), v)<br>        m_i = m_new<br>    acc = acc / l_i[:, None]<br>    tl.store(O + base + offs_m[:, None] * stride_n + offs_d[None, :],<br>             acc.to(O.dtype.element_ty), mask=offs_m[:, None] &lt; N)<br>    tl.store(L + bh.to(tl.int64) * N + offs_m, m_i + tl.log2(l_i), mask=offs_m &lt; N)</pre><p>The details that matter:</p><p><strong>exp2 instead of </strong><strong>exp.</strong> The GPU&#39;s special-function unit computes 2^x natively, and e^x = 2^(x·log₂e). I fold log₂e into the score scale once, so every exponential in the loop is a single exp2 with no extra multiply. The running max is then kept in the log2 domain, which is fine because only differences of it are ever exponentiated.</p><p><strong>K is loaded already transposed.</strong> cols[None, :] and offs_d[:, None] make the loaded tile [D, BLOCK_N], so tl.dot(q, k) computes Q·Kᵀ with no transpose op.</p><p><strong>Accumulate in FP32, multiply in FP16.</strong> Scores, m, l and the output accumulator are FP32. p is cast to FP16 just before tl.dot(p, v), so the second matmul still runs on the tensor cores.</p><p><strong>Causal attention skips work, it doesn’t just mask it.</strong> For the query block pid_m, keys beyond (pid_m + 1) · BLOCK_M are all in the future, so the loop stops there. That skips about half the tiles. Only the tiles that cross the diagonal need the element-wise mask.</p><p><strong>Why there is no NaN case.</strong> If a whole tile were masked for a row before that row had seen any valid key, m_i and m_new would both be −∞ and exp2(−∞ − (−∞)) would be NaN. That can&#39;t happen here: the first tile always starts at key 0, and every row is allowed to see key 0, so m_i is finite after the first iteration.</p><p><strong>int64 offsets.</strong> bh · stride_h is computed in 64-bit. At 32 heads × 8,192 tokens × 128 dims the offsets reach about 33.5 million, which fits in 32 bits, but a batch of 64 such sequences reaches 2³¹ (about 2.1 billion) and would silently wrap in 32-bit arithmetic.</p><p><strong>The log-sum-exp is saved.</strong> m + log2(l) per row is the only extra state the backward pass needs to recompute the softmax without storing it.</p><p>Block sizes, warps and pipeline stages are chosen by triton.autotune from seven configurations, separately for each (N, head dim, causal) combination.</p><h3>Correctness</h3><p>23 tests compare the output against an FP32 reference implementation, with an absolute tolerance of 0.02 for FP16 outputs:</p><ul><li>head dims 64 and 128, causal and non-causal</li><li>sequence lengths 64, 128, 1,000 and 1,031, so that the last tile is partly out of range and the masks get exercised</li><li>four different block shapes on a length of 517</li><li>scores around 400, far past where exp overflows in FP32 (about 88), to check that the running max does its job</li><li>the saved log-sum-exp against torch.logsumexp</li><li>a direct comparison with PyTorch’s own scaled_dot_product_attention</li></ul><p>All 23 pass.</p><h3>Results</h3><p>Setup: RTX 3050 6 GB Laptop GPU (20 SMs, Ampere), Windows, PyTorch 2.11, Triton 3.9. 32 heads, FP16. Times are medians from triton.testing.do_bench. The comparison is PyTorch SDPA&#39;s memory-efficient backend; PyTorch&#39;s FlashAttention backend isn&#39;t built for Windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XECKrsW_OQtti__qkHiYbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L3XkIqDZ09JjxBzVR1_6zQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykHYMETUuDXVk9x2bF-6lA.png" /></figure><p>At head dim 128 and N ≥ 1,024 the kernel is 1.5–1.7× faster than PyTorch without a causal mask and 1.3–1.5× faster with one. At head dim 64 the gap is smaller, 1.0–1.4×, and PyTorch’s kernel is essentially tied at N = 1,024.</p><h3>How close is that to the hardware?</h3><p>This is the question I spent the most time on, and the honest answer is: close, but I can’t give an exact percentage on a laptop.</p><p>My first attempt to measure the GPU’s peak said cuBLAS gets 5.1 TFLOP/s on a 2,048 × 2,048 FP16 matmul and 13.1 TFLOP/s at 6,144. That would have made my attention kernel, at 17 TFLOP/s, faster than the hardware. The measurement was the problem: the benchmark ran short bursts with pauses between them, and the laptop GPU never left its low-power state. nvidia-smi showed the clock at 210–735 MHz, out of a possible 2,100.</p><p>Under continuous load the clock comes up. 300 back-to-back 8,192 × 8,192 FP16 matmuls, about 25 seconds of work, ran at 17.9 TFLOP/s. But a laptop’s clock depends on power and temperature from one minute to the next, so two benchmarks run separately aren’t guaranteed to see the same clock. A precise “% of cuBLAS” needs both measured interleaved in the same run, which I’ll do before Part 2.</p><p>What I can say for certain is the upper bound. With FP16 inputs and FP32 accumulation, this chip’s tensor cores do 512 FLOPs per SM per cycle. At its maximum boost clock of 2.1 GHz that’s 20 × 512 × 2.1 × 10⁹ = 21.5 TFLOP/s, the most it could ever do. The kernel’s 17 TFLOP/s is about 80% of that ceiling, and the real fraction is higher, because the laptop doesn’t hold 2.1 GHz under sustained load.</p><p>Why can attention get that close to the tensor-core limit at all, when softmax adds work that isn’t a matmul? My reading, which I haven’t profiled yet: on a GeForce Ampere chip like this one, the tensor cores with FP32 accumulation are only about 2× faster than the regular FP32 units (512 vs 256 FLOPs per SM per cycle). On an A100 that ratio is 16×. At head dim 128, each attention score costs 512 tensor-core FLOPs (Q·Kᵀ plus P·V), roughly one tensor-core cycle per SM, while its softmax work is about ten FP32 operations and one exp2, a small fraction of a cycle on 128 FP32 lanes. So on this chip softmax is cheap relative to the matmuls, and the kernel spends most of its time where a plain matmul would. On data-center GPUs the balance is very different, which is a large part of why FlashAttention-3 and -4 exist.</p><h3>Two smaller findings</h3><p><strong>The autotuner picks small key tiles for head dim 128.</strong> At head dim 128 it chose BLOCK_M = 128, BLOCK_N = 32 with 4 warps for almost every length. My explanation is register pressure. The FP32 output accumulator for 128 rows × 128 dims is 64 KB, which is already 128 registers per thread across 128 threads. A 128 × 64 score tile would add another 64. Halving the key tile to 32 keeps the kernel inside the register file without spilling. At head dim 64 the accumulator is half the size, and it picks 64-wide key tiles.</p><p><strong>Short sequences are slower.</strong> At N = 512 the kernel gets 11.7 TFLOP/s instead of 17. Each program loops over only 16 key tiles, so the fixed costs of loading Q and writing O are a bigger share of its time. I first saw N = 512 at twice this time. That turned out to be the clock problem above, not the kernel.</p><h3>What’s next</h3><ul><li><strong>The same kernel in raw CUDA</strong> (Part 2): mma.sync tensor-core instructions, ldmatrix, cp.async pipelining and a swizzled shared-memory layout, written by hand instead of generated by Triton.</li><li><strong>Causal masking only on the diagonal tiles.</strong> Right now every tile in a causal row applies the mask, even tiles entirely below the diagonal that don’t need it. Splitting the loop into unmasked and masked stages, the way the official Triton tutorial does, should give a few percent on causal runs.</li><li><strong>A decode-attention kernel</strong> that reads keys and values from a paged KV cache, which is the next milestone of the inference engine this kernel is part of.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2c91e9b40cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Online softmax: how to compute softmax in pieces]]></title>
            <link>https://medium.com/@aniketm2598/online-softmax-how-to-compute-softmax-in-pieces-4b41dd095b3e?source=rss-50d97f3aa5ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b41dd095b3e</guid>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Aniket Maheshwari]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 02:11:17 GMT</pubDate>
            <atom:updated>2026-11-15T02:15:11.767Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@aniketm2598/naive-attention-from-scratch-the-memory-wall-flashattention-removes-e313df769543?sharedUserId=aniketm2598">In my last article</a>, naive attention ran into a wall: the N×N score matrix has to go to memory and back, and at long context that traffic is what makes attention slow. The fix sounds simple: compute attention in tiles that stay on chip. It runs into one problem. Softmax refuses to be computed in pieces. Online softmax is how you make it.</p><h3>Where we left off</h3><p>For one attention head, attention is three steps (ignoring the 1/√d scale): S = QKᵀ, P = softmax(S), O = PV. Q, K and V are each N × d, where N is the number of tokens and d is the head size, usually 64 or 128. The problem is the matrix in the middle. S has one score for every pair of tokens, so it’s N × N.</p><p>At N = 8,192 that’s 67 million scores. In FP16, 134 MB for a single head.</p><p>Naive attention moves that matrix through GPU memory four times:</p><ol><li>write S after the QKᵀ matmul</li><li>read S back to compute the softmax</li><li>write P, the softmax output</li><li>read P back for the multiply by V</li></ol><p>That’s about 537 MB of traffic per head, just for intermediate results nobody keeps. Q, K, V and O together are only 8 MB. The scores cost 64× more memory traffic than the actual inputs and outputs (the ratio is N / d = 8,192 / 128).</p><p>On my RTX 3050 (168 GB/s), moving those 537 MB takes about 3.2 ms per head. The two matmuls themselves are 34 GFLOP, about 2.3 ms at the card’s ~15 TFLOP/s FP16 tensor-core peak. The GPU spends more time shuttling scores in and out of memory than doing the actual math. Across 32 heads, that’s ~100 ms per layer spent moving data, for a single 8K-token prompt.</p><p>So that’s the plan from the top of this article: never write S to memory. Compute it in tiles small enough to live in on-chip SRAM, use each tile, throw it away. The two matmuls are fine with this, since matrix multiplication splits into blocks cleanly.</p><p>The softmax isn’t.</p><h3>Why softmax won’t split</h3><p>Softmax turns a row of raw scores into weights that are positive and sum to 1:</p><p>p_i = e^(s_i) / Σ_j e^(s_j)</p><p>Look at the denominator. Every single weight depends on the sum over the entire row. A tile that holds 64 of a row’s 8,192 scores can compute 64 exponentials, but it can’t turn them into weights, because it doesn’t know the other 8,128 terms of the sum.</p><p>It gets worse. Nobody computes softmax with that formula as written, because e^x overflows fast. The largest FP16 number is 65,504, so e^x overflows for any x above 11.1. Even FP32 overflows above 88.7. Attention scores go past 11 all the time. Feed the scores [2, 5, 100] into the formula and e¹⁰⁰ becomes infinity, the sum becomes infinity, and infinity / infinity is NaN.</p><p>On my GPU, in FP32: e^s = [7.39, 148.4, inf], and the softmax comes out as [0, 0, NaN]. Every weight is wrong, not just the last one.</p><p>The standard fix is to subtract the row’s maximum first. Softmax doesn’t change when you shift every score by the same amount, so you compute e^(s_i − m) instead, where m is the row max. Now the largest exponent is e⁰ = 1 and nothing overflows. For [2, 5, 100]: e^(−98), e^(−95), e⁰. All safe.</p><p>That’s safe softmax, and it takes three passes over the row:</p><ol><li>find the max m</li><li>sum the exponentials: l = Σ e^(s_i − m)</li><li>normalize: p_i = e^(s_i − m) / l</li></ol><p>So softmax needs two numbers from the whole row, the max and the sum, before it can finish even one weight. A tile sees 1/128th of the row. It can’t finish step 1, so it can’t start step 2.</p><p>Tiling attention looks impossible. It isn’t.</p><h3>The trick: you don’t need the true max up front</h3><p>The idea comes from a 2018 NVIDIA paper by Maxim Milakov and Natalia Gimelshein, <a href="http://arxiv.org/abs/1805.02867"><em>Online normalizer calculation for softmax</em></a>. Instead of finding the max first and the sum second, keep both as running values and update them as each score arrives:</p><ul><li><strong>m</strong>: the largest score seen so far</li><li><strong>l</strong>: the sum of exponentials so far, all computed relative to m</li></ul><p>When a new score comes in, two things can happen.</p><p><strong>The max doesn’t change.</strong> Add the new exponential to l. Done.</p><p><strong>The new score is bigger than the max.</strong> Now there’s a problem. Every term already inside l was computed as e^(s − m_old). It should have been e^(s − m_new). Each of those terms is wrong.</p><p>But they’re all wrong by the same amount. Every one of them used the same old max, so every one is too big by the same factor, e^(m_new − m_old). That means you don’t need to recompute anything. One multiplication fixes the whole sum:</p><p>l × e^(m_old − m_new)</p><p>Why that’s exact, using e^a × e^b = e^(a+b):</p><p>e^(s − m_old) × e^(m_old − m_new) = e^(s − m_new)</p><p>Every old term lands exactly where it would have been if you had known the new max from the start.</p><p>The whole algorithm, written the way one CUDA thread would process a row:</p><pre>float m = -INFINITY;   // running max<br>float l = 0.0f;        // running sum of exponentials, relative to m<br><br>for (int j = 0; j &lt; n; j++) {<br>    float m_new = fmaxf(m, s[j]);<br>    l = l * expf(m - m_new) + expf(s[j] - m_new);   // rescale old sum, add new term<br>    m = m_new;<br>}<br>// m is now the true row max, l the true sum</pre><p>On the first iteration m is −∞, so expf(m − m_new) is 0 and l starts cleanly at zero, with no special case. (This version updates one score at a time, which is the clearest way to see the idea. Real kernels process a chunk per update; the math is identical.)</p><p>Three properties make this work:</p><ul><li><strong>It’s exact.</strong> After the last element, m is the true row max and l is the true sum. No approximation anywhere.</li><li><strong>It never overflows.</strong> Every exponent is a score minus a max at least as big as it, so it’s ≤ 0. The correction factor e^(m_old − m_new) is ≤ 1, so it can only shrink l.</li><li><strong>One read gives both.</strong> Safe softmax reads the row once for the max and again for the sum. This gets both in a single pass.</li></ul><p>There’s a bonus that matters a lot on a GPU: two partial results can be merged. If one thread has processed the first half of a row, giving (m_a, l_a), and another thread the second half, giving (m_b, l_b), then:</p><pre>float m = fmaxf(m_a, m_b);<br>float l = l_a * expf(m_a - m) + l_b * expf(m_b - m);</pre><p>Same rescale trick, applied to two sums instead of one. That merge rule is what lets 32 threads in a warp split one row, each run the loop on its own slice, and combine their results with warp shuffles. It’s also the rule FlashAttention and Flash-Decoding use to split attention across tiles and across thread blocks.</p><p>For a standalone softmax, you still need one more pass to turn each score into a weight: p_i = e^(s_i − m) / l. So it’s 2 passes instead of 3. Inside attention, even that last pass disappears. More on that in a moment.</p><h3>Worked example</h3><p>Here’s the trick on real numbers. Take one row of 8 attention scores and process it in two blocks of 4, the way a tiled kernel would. For a block, the update is the same as before, just with the block’s max and the block’s sum:</p><p>m_new = max(m, max of block)<br> l = l × e^(m − m_new) + Σ over block of e^(s − m_new)</p><p>Row: [1, 3, 2, 0 | 5, 1, 4, 2]</p><p><strong>Block 1: [1, 3, 2, 0]</strong></p><ul><li>Running max: m = 3</li><li>Exponentials relative to 3: e^(−2) = 0.1353, e⁰ = 1, e^(−1) = 0.3679, e^(−3) = 0.0498</li><li>Running sum: l = 1.5530</li></ul><p><strong>Block 2: [5, 1, 4, 2]</strong></p><ul><li>The block’s max is 5, bigger than 3. New running max: m = 5</li><li>Everything in l was computed relative to 3, so all of it is too big by e^(5−3). Fix it with one multiply: 1.5530 × e^(3−5) = 1.5530 × 0.1353 = 0.2102</li><li>Block 2’s exponentials relative to 5: e⁰ = 1, e^(−4) = 0.0183, e^(−1) = 0.3679, e^(−3) = 0.0498, which sum to 1.4360</li><li>Running sum: l = 0.2102 + 1.4360 = 1.6462</li></ul><p>Check against regular two-pass softmax. Max of the whole row = 5. Sum of e^(s − 5) over all 8 scores = 0.0183 + 0.1353 + 0.0498 + 0.0067 + 1 + 0.0183 + 0.3679 + 0.0498 = 1.6462. Identical, and not approximately identical: it’s the same sum, regrouped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*era8INiSYeHl1zNwPUZBBA.png" /></figure><p>What happens if you skip the rescale? You’d add 1.5530 + 1.4360 = 2.9890, mixing terms computed against two different maxes. The weight for the score of 5 would come out as 1 / 2.989 = 0.335. The correct weight is 1 / 1.6462 = 0.607. Without the rescale, the softmax is off by almost half for the most important token in the row.</p><p>Final weights, e^(s − 5) / 1.6462:</p><p>[0.011, 0.082, 0.030, 0.004, 0.607, 0.011, 0.223, 0.030]</p><h3>The code</h3><p>Two kernels, one block of 256 threads per row, same reductions in both, so the only difference is the algorithm.</p><p>Safe softmax reads every score three times: once for the max, once for the sum, once to normalize and write:</p><pre>float m = -INFINITY;                                          // read 1: max<br>for (int j = threadIdx.x; j &lt; n; j += blockDim.x) m = fmaxf(m, r[j]);<br>m = blockMax(m);<br><br>float l = 0.0f;                                               // read 2: sum<br>for (int j = threadIdx.x; j &lt; n; j += blockDim.x) l += expf(r[j] - m);<br>l = blockSum(l);<br><br>float inv = 1.0f / l;                                         // read 3 + write<br>for (int j = threadIdx.x; j &lt; n; j += blockDim.x) o[j] = expf(r[j] - m) * inv;</pre><p>Online softmax reads every score twice. In the first read, each thread keeps a running max and sum over its slice of the row:</p><pre>float m = -INFINITY, l = 0.0f;<br>for (int j = threadIdx.x; j &lt; n; j += blockDim.x) {<br>    float s = r[j];<br>    if (s &gt; m) { l = l * expf(m - s) + 1.0f; m = s; }   // new max: rescale, add e^0<br>    else       { l += expf(s - m); }                     // same max: just add<br>}</pre><p>This is the loop from earlier with one optimization: when the max doesn’t change, the rescale factor is e⁰ = 1, so skip it. That’s one expf per score instead of two.</p><p>Then the 256 partial results get merged, first within each warp using shuffles, then across the 8 warps through shared memory, using the merge rule:</p><pre>__device__ void mergeMS(float&amp; m, float&amp; l, float m2, float l2) {<br>    float mn = fmaxf(m, m2);<br>    if (mn == -INFINITY) return;            // both empty: avoid (-inf) - (-inf) = NaN<br>    l = l * expf(m - mn) + l2 * expf(m2 - mn);<br>    m = mn;<br>}<br><br>// within each warp<br>for (int off = 16; off &gt; 0; off &gt;&gt;= 1) {<br>    float m2 = __shfl_xor_sync(0xffffffff, m, off);<br>    float l2 = __shfl_xor_sync(0xffffffff, l, off);<br>    mergeMS(m, l, m2, l2);<br>}<br>// lane 0 of each warp writes (m, l) to shared memory,<br>// then warp 0 merges the 8 warp results the same way</pre><p>The −∞ check matters. A thread whose slice was empty still has m = −∞, and merging two of those would compute (−∞) − (−∞), which is NaN.</p><p>After the merge, every thread knows the row’s true max and true sum. The last pass reads each score once more and writes the weight:</p><pre>float rowmax = wm[0], inv = 1.0f / wl[0];<br>for (int j = threadIdx.x; j &lt; n; j += blockDim.x)<br>    o[j] = expf(r[j] - rowmax) * inv;</pre><p>Safe softmax: 3 reads + 1 write per element. Online softmax: 2 reads + 1 write. If both kernels are purely memory-bound, that’s 4 units of traffic against 3, so online softmax should be about 1.33× faster.</p><h3>Results</h3><p>4,096 rows, FP32, RTX 3050 6GB Laptop GPU (20 SMs, 1.5 MB L2, 168 GB/s):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QmnXA0H2qqJldRaYFnccYQ.png" /></figure><p>Both kernels match a double-precision CPU reference to within 1e-9. Online softmax is exact, so there’s no accuracy cost.</p><p>The 1.32× is almost exactly the ratio of bytes moved: 4 units of traffic down to 3. Nsight Compute shows why:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pb5Lt2IjMlUJq6hbJz6jhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHtjEGGS5U2AsXxIRUVz4Q.jpeg" /><figcaption><em>Nsight Compute, all four kernels. Memory throughput sits at 93–94% for every one of them, and online softmax finishes in about 75% of the time at both sizes.</em></figcaption></figure><p>The input at 8K columns is 134 MB. Safe softmax read 402 MB from DRAM, exactly 3 copies. Online softmax read 268 MB, exactly 2. Every pass went back to memory, even though each row is only 32 KB.</p><p>The cache can’t save the extra pass because of how many rows are in flight. With 256 threads per block, each of the 20 SMs runs up to 6 blocks at once, so about 120 rows are being processed simultaneously. That’s 3.8 MB of rows against a 1.5 MB L2, and 192 KB per SM against a 128 KB L1. By the time a block comes back for its second read, its row has been evicted.</p><p>Both kernels run at about 94% of the card’s peak DRAM bandwidth. They are as fast as the memory allows. Nsight Compute agrees: its estimate of the remaining speedup for either kernel is about 6%, and the main stall reason is warps waiting on memory loads. The only way to make a memory-bound kernel faster is to move fewer bytes, and that’s all online softmax does: one less trip through memory per element, one third less read traffic, 1.32× faster.</p><p>Compute throughput goes up from 14.5% to 23.2%: the same exponentials, squeezed into less time because one memory pass is gone.</p><p>That’s the same lesson that drives FlashAttention, at a bigger scale. Count the bytes that reach DRAM, not the operations.</p><h3>From softmax to attention</h3><p>Standalone softmax still needs that last pass to write the weights. Attention doesn’t, because nobody needs the weights. Attention needs O = PV, a weighted sum of the rows of V. So instead of storing weights, keep a running output.</p><p>For one query row, keep three things as you walk over K and V one tile at a time:</p><ul><li><strong>m</strong>: the running max of the scores</li><li><strong>l</strong>: the running sum of exponentials, relative to m</li><li><strong>o</strong>: a running output vector of d numbers, also relative to m</li></ul><p>For each tile of keys and values:</p><pre>s     = q · K_tileᵀ                 // scores for this tile, on chip<br>m_new = max(m, max(s))<br>p     = exp(s - m_new)              // unnormalized weights, on chip<br>l     = l * exp(m - m_new) + sum(p)<br>o     = o * exp(m - m_new) + p · V_tile<br>m     = m_new</pre><p>At the end, divide once: O = o / l.</p><p>The output gets the same rescale as the sum, for the same reason. Every term inside o is some e^(s − m_old) times a row of V, so when the max changes they’re all too big by the same factor, and one multiply fixes them all.</p><p>The scores s and weights p exist only for one tile, inside on-chip memory, and are thrown away as soon as the tile is done. The N × N matrix from the top of this article is never written, so the 537 MB of score traffic per head is gone. That’s the core of FlashAttention.</p><h3>What’s next</h3><p>Online softmax handles one row. FlashAttention runs it for a whole tile of queries at once, loads K and V tiles into shared memory, and does the two matmuls on tensor cores. Next article: a FlashAttention forward kernel in CUDA, built on exactly this loop, benchmarked against the naive version from the last article on the same 3050. After that, the same kernel in Triton, to see how much of the work the compiler takes off your hands.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b41dd095b3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Naive attention from scratch — the memory wall FlashAttention removes]]></title>
            <link>https://medium.com/@aniketm2598/naive-attention-from-scratch-the-memory-wall-flashattention-removes-e313df769543?source=rss-50d97f3aa5ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/e313df769543</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[flash-attention]]></category>
            <category><![CDATA[gpu-programming]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[hpc]]></category>
            <dc:creator><![CDATA[Aniket Maheshwari]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 04:57:12 GMT</pubDate>
            <atom:updated>2026-10-21T04:57:12.886Z</atom:updated>
            <content:encoded><![CDATA[<p>Standard attention has a memory problem, and the cleanest way to understand FlashAttention is to first build the version that has it.</p><p>I wrote attention the naive way on an RTX 3050: compute the full N×N score matrix, write it to global memory, read it back to softmax it, read it again to multiply by V. Three stages, one big matrix shuttled to and from DRAM. Measured across sequence lengths, the matrix grows exactly quadratically : 4.2 MB at 1024 tokens, 67.1 MB at 4096 — and runtime tracks it at ~3.5× per doubling.</p><p>For one head, one layer. A real model has dozens of each. This is the wall, measured.</p><h4><strong>What attention computes</strong></h4><p>Given queries Q, keys K, and values V — each (N, d), one row per token — attention produces, for each token, a weighted average over all value vectors, weighted by query-key similarity:</p><pre>S = QKᵀ / √d        # (N, N) score matrix<br>P = softmax(S)      # row-wise, (N, N)<br>O = P · V           # (N, d) output</pre><p>The whole cost is the (N, N) matrix. It scales with the square of the sequence length while Q, K, V scale linearly at N=4096, d=64, the inputs are 1 MB each but S is 67 MB. In this formulation, softmax needs a full row of scores before it can normalize, so the naive kernel builds the whole matrix before step 2 begins.</p><h4><strong>The naive kernel: three stages, one big matrix</strong></h4><p>The implementation follows the three lines of math literally, one kernel per line.</p><p><strong>Stage 1: scores.</strong> One thread per entry of S. Thread (i, j) dots row i of Q with row j of K, scales the result, and writes it to global memory:</p><pre>__global__ void qkT(const float* Q, const float* K, float* S, int n, int d, float scale) {<br>    int i = blockIdx.y * blockDim.y + threadIdx.y;   // query row<br>    int j = blockIdx.x * blockDim.x + threadIdx.x;   // key row<br>    if (i &lt; n &amp;&amp; j &lt; n) {<br>        float acc = 0.0f;<br>        for (int k = 0; k &lt; d; k++) acc += Q[i*d + k] * K[j*d + k];<br>        S[i*n + j] = acc * scale;<br>    }<br>}</pre><p>That write to S is the line this article is about. Every entry of the N×N matrix lands in DRAM.</p><p><strong>Stage 2: row softmax.</strong> One block per row. It reads the row three times — once for the max, once to sum the exponentials, and once more to normalize — writing the result back in place. This is the stable three-pass softmax from the previous post, applied to every row of S.</p><p><strong>Stage 3: output.</strong> One thread per output element. Thread (i, k) walks across row i of S and column k of V:</p><pre>__global__ void sv(const float* S, const float* V, float* O, int n, int d) {<br>    int i = blockIdx.y * blockDim.y + threadIdx.y;   // query row<br>    int k = blockIdx.x * blockDim.x + threadIdx.x;   // output dim<br>    if (i &lt; n &amp;&amp; k &lt; d) {<br>        float acc = 0.0f;<br>        for (int j = 0; j &lt; n; j++) acc += S[i*n + j] * V[j*d + k];<br>        O[i*d + k] = acc;<br>    }<br>}</pre><p>Add up the trips through S. Stage 1 writes it. Stage 2 reads it three times — max, sum, normalize — and writes it back. Stage 3 reads it once more. That’s six full passes over an N×N matrix to produce an N×d output. Q, K, and V are small — 1 MB each at 4096 tokens. S is the traffic.</p><p><strong>The measurement</strong></p><p>I ran the same kernel at three sequence lengths with head dimension 64, keeping everything else fixed:</p><pre>seq     score matrix S     runtime      vs previous<br>1024        4.2 MB         1.786 ms          —<br>2048       16.8 MB         6.235 ms        3.49×<br>4096       67.1 MB        21.790 ms        3.50×</pre><p>Every time the sequence length doubles, memory goes up exactly 4×. That’s O(n²) with no rounding. Runtime goes up about 3.5× per doubling. It falls a little short of 4× because the fixed costs, three kernel launches plus per-row softmax setup, are a bigger share of the total at small sizes. The direction is still the same, and every stage is quadratic in sequence length.</p><p>Pushing the arithmetic past what I measured makes the problem obvious. At 8,192 tokens, S is 268 MB. At 32,768 tokens, which is an ordinary context length for current models, it’s 4.3 GB. That’s for one head in one layer, and it’s most of my 6 GB card before Q, K, V, or the model weights have been stored anywhere.</p><p><strong>What the profiler said</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ak3BGsnsyKvhpxKjsWyCmw.png" /><figcaption><em>Nsight Compute on naive attention at seq=4096. The QKᵀ kernel takes 75% of the runtime because of uncoalesced reads of K, with 4 of 32 bytes per sector used. The softmax is already near its memory ceiling.</em></figcaption></figure><p>Of the 27.05 ms the profiler measured — higher than the benchmark’s 21.79 ms, because Nsight locks clocks and replays each kernel — the split was:</p><pre>qkT          20.40 ms   75%   uncoalesced K reads, 4/32 bytes per sector used<br>softmaxRows   1.97 ms    7%   ~4% headroom left, near its ceiling<br>sv            4.68 ms   17%</pre><p>The surprise is in the first row. The stage I expected to be cheap, a dot product per entry, takes three-quarters of the time, because adjacent threads read rows of K that are 64 floats apart and waste 7 of every 8 bytes the memory system delivers. The softmax, which I expected to be the problem, is already close to its bandwidth limit.</p><p>This splits the cost of naive attention into two kinds. Some of it is fixable: shared-memory tiling turns the strided qkT reads into coalesced ones, just as it did for matmul. Some of it is not fixable this way: no matter how well each kernel is written, the N×N matrix still has to be written once and read back several times. FlashAttention targets both.</p><p><strong>What FlashAttention changes</strong></p><p>Look at what the three stages actually need. Stage 3 needs one row of the softmaxed scores at a time. The softmax needs one row of raw scores at a time. Nothing in the computation ever needs the whole N×N matrix at once. It only exists because the naive kernel finishes each stage completely before starting the next.</p><p>FlashAttention removes that boundary between stages. It loads a block of queries and a block of keys and values into on-chip SRAM, computes that block’s scores, and folds them into the output right away. The online softmax from the previous post is what makes this correct. It keeps a running max and sum and rescales them as each new block of keys arrives, so partial results from different blocks combine exactly. The full score matrix never gets written to DRAM, because only one tile of it ever exists, in SRAM, and it’s discarded once it has been used.</p><p>That fixes both problems from this post together. Tiling through SRAM makes the reads coalesced, and never materializing S takes the O(n²) intermediate out of the memory traffic. The math stays the same. Only the order of operations changes. That’s the next post.</p><p><strong>Key Takeaways</strong></p><ul><li>Naive attention materializes an N×N score matrix whose memory grows exactly 4× each time the sequence length doubles: 4.2 MB at 1,024 tokens, 67.1 MB at 4,096, and 4.3 GB at 32K, per head, per layer.</li><li>The profiler split the cost into two kinds. One was fixable: the QKᵀ kernel spent 75% of the runtime on uncoalesced reads of K. The other was structural: the matrix makes six trips through DRAM no matter how good the kernels are.</li><li>Nothing in the math requires the full matrix at once. It exists only because each stage finishes before the next begins, and that’s the opening FlashAttention uses.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e313df769543" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Online softmax from scratch — the primitive behind FlashAttention]]></title>
            <link>https://medium.com/@aniketm2598/online-softmax-from-scratch-the-primitive-behind-flashattention-020f15323f0f?source=rss-50d97f3aa5ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/020f15323f0f</guid>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hpc]]></category>
            <dc:creator><![CDATA[Aniket Maheshwari]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 04:08:15 GMT</pubDate>
            <atom:updated>2026-09-23T04:08:15.330Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first post in a series building toward FlashAttention. It starts with softmax, because the core trick in FlashAttention is really a trick about computing softmax without seeing all the data at once. Softmax is memory-bound. The arithmetic is trivial it’s a max, an exponential and a division per element but the cost is moving the data. So, the way to make it faster isn’t faster math, it’s fewer passes over memory.</p><p>The naive implementation reads each row three times. Once to find the max, once to sum the exponentials, once to normalize. I fused the first two passes into one using online SoftMax, dropping from three reads to two. On my RTX 3050, throughput went from 83 to 104 GB/s.</p><p>The technique that makes this possible is maintaining a running max and sum and rescaling the sum whenever the max changes.</p><h4><strong>The numerical stability problem</strong></h4><p>Written directly from the definition, softmax is exp(x_i) divided by the sum of exp(x_j). That’s correct on paper but broken in floating point: exp grows so fast that exp(89) overflows FP32, and a single inf turns the whole output into NaN.</p><p>The fix is to subtract the row maximum before exponentiating:</p><pre>softmax(x_i) = exp(x_i - max) / Σ exp(x_j - max)</pre><p>This is mathematically identical . The exp(-max) factor cancels between numerator and denominator but now every exponent is ≤ 0, so every exp call returns a value in (0, 1]. No overflow, ever! This is why every real softmax implementation finds the max first, and it’s the reason the naive kernel needs that first pass at all.</p><h4><strong>The naive kernel: three passes</strong></h4><p>The structure follows directly from the formula. One block handles one row and the threads in the block cooperate on the three passes.</p><pre>// Pass 1: max<br>float local_max = -INFINITY;<br>for (int i = tid; i &lt; cols; i += blockDim.x)<br>    local_max = fmaxf(local_max, row_ptr[i]);<br>// warp + block reduce → row_max<br><br>// Pass 2: denominator<br>float local_sum = 0.0f;<br>for (int i = tid; i &lt; cols; i += blockDim.x)<br>    local_sum += expf(row_ptr[i] - row_max);<br>// warp + block reduce → row_sum<br><br>// Pass 3: normalize and write<br>for (int i = tid; i &lt; cols; i += blockDim.x)<br>    out_ptr[i] = expf(row_ptr[i] - row_max) / row_sum;</pre><p>Each pass strides across the row with 256 threads on a 4096-wide row, each thread handles 16 elements. Passes 1 and 2 each end in a reduction: warp-level with __shfl_down_sync, then across warps through shared memory, the same two-level pattern from my reduction kernel. Pass 1 reduces with fmaxf, pass 2 with +.</p><p>The cost is in the reads. The input row is read three times from global memory once per pass. For a memory-bound kernel, that’s the number to attack.</p><p>Result: 83.2 GB/s, about 37% of the RTX 3050’s ~224 GB/s peak.</p><h4><strong>Online softmax: one pass for max and sum</strong></h4><p>The reason max and sum are separate passes in the naive version is a data dependency: you can’t compute exp(x — max) until you know the max. Online softmax breaks that dependency by tracking a running max and running sum simultaneously, rescaling the sum whenever the running max increases.</p><p>The per-element update:</p><pre>float new_max = fmaxf(running_max, x);<br>running_sum = running_sum * expf(running_max - new_max) + expf(x - new_max);<br>running_max = new_max;</pre><p>When x is larger than everything seen so far, new_max jumps, and expf(running_max — new_max) is a factor less than 1 that shrinks the previously accumulated sum to match the new reference point. When x is smaller, the max is unchanged, the rescale factor is 1, and the new term is just added. Either way, after one pass running_max and running_sum are both correct.</p><p>The same rule merges partial results from different threads or warps:</p><pre>float new_max = fmaxf(maxA, maxB);<br>float sum = sumA * expf(maxA - new_max) + sumB * expf(maxB - new_max);</pre><p>That merge , two independent (max, sum) states combined into one , is the primitive at the heart of FlashAttention. FlashAttention processes attention in tiles, each tile producing a partial softmax, and folds them together with exactly this formula. The SoftMax kernel here is that mechanism in isolation.</p><h4><strong>The result</strong></h4><p>Naive (3 passes): 83.2 GB/s</p><p>Online (2 passes): 104.5 GB/s (1.26×)</p><p>Eliminating one pass took the kernel from 37% to 47% of peak bandwidth. Going from three reads-plus-a-write to two-reads-plus-a-write predicts a 4/3 ≈ 1.33× speedup; the measured 1.26× sits just below it, the difference being the extra rescaling arithmetic and L2 catching part of naive’s redundant third read.</p><p>The profiler shows the kernel is at its practical ceiling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRFyqE6o0J8LpXfQ3e04FQ.png" /></figure><p>Memory throughput is 93.96% and compute is 32.13% , firmly memory-bound, as any softmax kernel should be. The estimated speedup is only 6.04%. That number is the interesting one: the matmul kernels in earlier posts left 49–70% on the table, but this kernel has no large bottleneck remaining. At 94% memory throughput reading 64MB per pass, the kernel is close to the wall. The only way to go meaningfully faster is to read the data fewer times , which is precisely the idea FlashAttention takes to its limit by never writing the attention matrix to memory at all.</p><h4>Key Takeaways:</h4><p>- Softmax barely computes anything per byte, so it’s memory-bound. The only meaningful lever is reducing passes over the data.</p><p>- Online softmax fuses the max and sum into one pass by keeping a running max and rescaling the running sum whenever the max grows. Three reads become two — 83 → 104 GB/s on the RTX 3050.</p><p>- The merge formula, combining two (max, sum) states by rescaling both to their shared max, is the exact primitive FlashAttention uses to fold attention tiles together. This kernel is that mechanism in isolation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=020f15323f0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FP32 to FP16 tensor cores: why naive wmma beats FP32 optimization]]></title>
            <link>https://medium.com/@aniketm2598/fp32-to-fp16-tensor-cores-why-naive-wmma-beats-fp32-optimization-477803418082?source=rss-50d97f3aa5ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/477803418082</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[hpc]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[Aniket Maheshwari]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 04:49:17 GMT</pubDate>
            <atom:updated>2026-08-27T04:50:11.821Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous articles, I’ve tried optimizing a matrix multiplication kernel using different optimization techniques to get from 467 to 3200 GFLOP/s. I’m continuing this journey to maximize GFLOP/s for my RTX 3050 and implemented a tensor core version with no optimization — just raw wmma API, loading straight from global memory. It hit 3471 GFLOP/s on the first correct run.</p><p>Then I tried to optimize it. I added shared memory tiling, the same technique that gave my FP32 kernel a 6× speedup. On the tensor core kernel, it made things slower. 3471 GFLOP/s dropped to 1953 GFLOP/s. Tiling worked exactly as intended on global memory, but created a new bottleneck somewhere else entirely.</p><h3><strong>Tensor Cores: A Different Kind of Hardware</strong></h3><p>All the previous kernels in my previous posts ran on CUDA cores, which are the standard units on the GPU. They are scalar units which means it multiplies two numbers and adds them, one pair per cycle. My RTX 3050 has 2560 of them, which is where the ~9 TFLOP/s FP32 peak comes from.</p><p>Tensor cores are different hardware. It is a matrix unit so in one instruction it computes D = A*B + C where A, B, and C are 16*16 matrices. So rather than operating on individual numbers like CUDA cores, a tensor core multiplies 2 small matrices and sums the result in a single instruction. On GPU that is a 16*16*16 operation i.e. 4096 multiply-add, 8192 FLOPs per instruction. My RTX 3050’s tensor cores hit roughly 80 TFLOP/s for FP16 — about 10× the FP32 ceiling.</p><p>This ratio explains the benchmark. A naïve tensor core kernel and a heavily optimized FP32 kernel aren’t really competing on equal terms because tensor core hardware is built specifically for matrix multiplication.</p><p>The tradeoff here is that tensor cores are harder to program, because the data lives in fragments — a format where each 16*16 matrix is distributed across all 32 threads in a warp, with each thread holding a piece of it in registers. No single thread owns the whole matrix.</p><h3><strong>The Naive wmma Kernel</strong></h3><p>The wmma API (Warp Matrix Multiply-Accumulate) is CUDA’s highest-level interface for tensor cores. Programming tensor cores directly would require knowing the exact register layout of each fragment — which thread holds which element of the 16×16 matrix. The wmma API abstracts that away. It handles the fragment layout internally — you don’t need to know which thread holds which elements. You just declare a fragment, load data into it, run the operation, and store the result. You work with opaque fragment types, call load/store/mma functions, and the hardware handles the distribution.</p><p>The naive version is simple. Each warp handles one 16*16 output tile. It loops over the K dimension in chunks of 16, loading a fragment of A and a fragment of B from global memory each iteration, and accumulating into a float accumulator fragment.</p><pre>fragment&lt;matrix_a, 16, 16, 16, half, row_major&gt; a_frag;<br>fragment&lt;matrix_b, 16, 16, 16, half, row_major&gt; b_frag;<br>fragment&lt;accumulator, 16, 16, 16, float&gt; c_frag;<br><br>fill_fragment(c_frag, 0.0f);<br><br>for (int k = 0; k &lt; n; k += 16) {<br>    load_matrix_sync(a_frag, A + row * n + k, n);<br>    load_matrix_sync(b_frag, B + k * n + col, n);<br>    mma_sync(c_frag, a_frag, b_frag, c_frag);<br>}<br><br>store_matrix_sync(C + row * n + col, c_frag, n, mem_row_major);</pre><p>Here Inputs A and B are stored in FP16, accumulator is FP32 because accumulating in FP16 over 64 iterations would compound rounding errors and produce results too far from the reference. Each mma_sync call does one 16×16×16 multiply-accumulate — 8192 FLOPs. For N=1024 there are 64 iterations (1024/16), so each warp executes 64 tensor core instructions to compute its output tile.</p><p>One thing to note: B must be declared row_major to match how it’s stored in memory. Getting the layout wrong produces incorrect results without any error — the kernel compiles and runs, just gives wrong numbers. That was the first bug I hit.</p><p>Result at N=1024: 3471 GFLOP/s, correct output.</p><h3><strong>The Profiler: Memory-Bound Despite Tensor Cores</strong></h3><p>The naive result of 3471 GFLOP/s looks good compared to the FP32 kernels but my RTX 3050’s tensor core peak is ~80 TFLOP/s so that’s roughly 4% utilization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lt_1WA-ILkdZe4EEnJ99ug.png" /></figure><ul><li>Compute throughput: 34.52%</li><li>Memory throughput: 97.75%</li></ul><p>The kernel is almost completely memory-bound. The tensor cores are finishing their work fast and then sitting idle, waiting for the next chunk of data to arrive from global memory. Each warp loads its A and B fragments directly from DRAM — no sharing, no reuse. Thread (0,0)’s warp and thread (0,1)’s warp both need overlapping rows of A, but they each make their own separate trip to global memory.</p><p>The fix is obvious: shared memory tiling. Load data cooperatively into shared memory first, then have each warp load its fragment from there. Same technique that fixed the FP32 kernel’s memory bottleneck.</p><h3><strong>The Tiling Attempt</strong></h3><p>Adding shared memory tiling to the tensor core kernel follows the same pattern as the FP32 version. Each block cooperatively loads a chunk of A and B into shared memory, syncs, then each warp loads its fragment from there instead of global memory. Less DRAM traffic, more reuse.</p><p>Benchmark: 1953 GFLOP/s. Slower than naive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDxAFNVolwWv3cnf7ToE3w.png" /></figure><p>Memory throughput: 46.40% — down from 97.75%. The tiling genuinely worked on the global memory side. The kernel was moving significantly less data from DRAM. But compute throughput also fell from 34.52% to 21.85%, and the top bottleneck had completely changed. Where the naive kernel flagged uncoalesced global loads, the tiled kernel flagged uncoalesced shared memory accesses — 73% of shared memory wavefronts were excessive, with a 70.51% estimated speedup from fixing them.</p><p>The kernel traded a global memory bottleneck for a shared memory bank conflict. The tiling accomplished exactly what it was supposed to — it just created a new problem in the process.</p><h3><strong>Key Takeaways</strong></h3><ul><li>Tensor cores are a different class of hardware — a 16×16×16 matrix multiply in one instruction, ~80 TFLOP/s peak on the RTX 3050 versus ~9 TFLOP/s for FP32 CUDA cores. A naive tensor core kernel starts ahead of a heavily optimized FP32 one.</li><li>Even with tensor cores, you can be memory-bound. 97.75% memory throughput and 34.52% compute means the tensor cores are idle most of the time, waiting on DRAM.</li><li>Fixing one bottleneck exposes the next one. Tiling cut global memory pressure in half but immediately surfaced shared memory bank conflicts.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=477803418082" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using float4 to fix uncoalesced writes in a CUDA matmul]]></title>
            <link>https://medium.com/@aniketm2598/using-float4-to-fix-uncoalesced-writes-in-a-cuda-matmul-01ed5ba8fa45?source=rss-50d97f3aa5ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/01ed5ba8fa45</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[gpu-programming]]></category>
            <category><![CDATA[hpc]]></category>
            <dc:creator><![CDATA[Aniket Maheshwari]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 06:19:18 GMT</pubDate>
            <atom:updated>2026-08-19T06:19:18.992Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last matmul article, I ended with a bottleneck the profiler had flagged: the write-back to global memory was uncoalesced, wasting 75% of every memory transaction. The register-tiled kernel was writing results to global memory one float at a time, scattering the stores across memory.</p><p>The fix was small — pack four float results into one float4 and write them in a single 16-byte instruction instead of four 4-byte ones. One change, localized to the last few lines of the kernel.</p><p>It worked. The kernel got faster — 3076 GFLOP/s. But that’s a 1.2x improvement, not the 1.6x the profiler suggested. Here’s what I learned about why.</p><h3><strong>The Problem : Scattered Stores</strong></h3><p>Each thread in the register-tiled kernel owns a 4×4 chunk of output. When it’s time to write those 16 values back to global memory, the original code did it one float at a time:</p><pre>for (int i = 0; i &lt; TM; i++)<br>    for (int j = 0; j &lt; TN; j++)<br>        C[(rowStart + i) * N + (colStart + j)] = sum[i][j];</pre><p>Here’s why that’s wasteful. The GPU always moves memory in 32-byte chunks called sectors — even if you only asked for 4 bytes. So each 4-byte write triggers a 32-byte sector transaction, and only 4 of those 32 bytes are actually used. Every store was running at 1/8th efficiency. Do that for millions of writes and you’re wasting most of your store bandwidth.</p><p>Nsight Compute confirmed this: “only 8.0 of 32 bytes transmitted per sector are utilized.” The estimated 61% speedup assumed fixing this was the only bottleneck.</p><h3><strong>The Fix: float4</strong></h3><p>The fix is simple in concept — stop writing one float at a time. Pack all four column values into a single 16-byte write. CUDA has a built-in type for exactly this: float4 — four floats grouped together, written in one instruction.</p><pre>for (int i = 0; i &lt; TM; i++) {<br>    float4 out;<br>    out.x = sum[i][0];<br>    out.y = sum[i][1];<br>    out.z = sum[i][2];<br>    out.w = sum[i][3];<br>    reinterpret_cast&lt;float4*&gt;(C)[(rowStart + i) * (n / 4) + (colStart / 4)] = out;<br>}</pre><p>The reinterpret_cast&lt;float4*&gt; tells the compiler to treat C as an array of float4s instead of floats — same memory, different access size. Instead of four 4-byte writes, each row now produces one 16-byte write. Sector utilization goes from 4/32 (12.5%) to 16/32 (50%) — four times better. The hardware emits a single 128-bit store instruction instead of four 32-bit ones.</p><p>After this change, the store warning vanished from the profiler entirely. Throughput went from 2574 to 3076 GFLOP/s. Real, but nowhere near 61%.</p><h3><strong>Why 20% and Not 61%</strong></h3><p>Here’s the thing about “estimated speedup” in Nsight — it assumes everything else stays perfect. It measures how much faster the kernel would run if that one specific issue were the only thing holding it back. In reality, kernels have multiple overlapping bottlenecks.</p><p>When I reprofiled after the float4 change, two things stood out. First, the store warning was gone — fix confirmed. Second, a new warning had surfaced: shared memory bank conflicts, 2.4-way, flagged at 28% estimated speedup.</p><p>The bottlenecks were layered. Fixing the stores didn’t hand me 61% because underneath the store problem sat a bank conflict problem, and underneath that likely more. Each fix reveals the next constraint rather than delivering the full estimated payoff. Performance is gated by the current worst bottleneck — not the sum of every issue you could theoretically fix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqghNSrbWq403qPd1dEzEw.png" /></figure><h3><strong>Key Takeaways</strong></h3><p>- Nsight’s estimated speedup assumes the flagged issue is your only bottleneck. Treat it as a direction to look, not a number to expect.</p><p>- Vectorizing memory access with float4 is one of the easiest optimizations available — a few lines, no algorithmic change, immediate improvement in bandwidth utilization.</p><p>- Performance is gated by the current worst bottleneck. Fix it and the next one appears. Optimization is a sequence, not a single move.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01ed5ba8fa45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From naive atomics to warp shuffles: building a CUDA reduction kernel on an RTX 3050]]></title>
            <link>https://medium.com/@aniketm2598/from-naive-atomics-to-warp-shuffles-building-a-cuda-reduction-kernel-on-an-rtx-3050-22bc38a03f3e?source=rss-50d97f3aa5ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/22bc38a03f3e</guid>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[hpc]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Aniket Maheshwari]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 02:40:49 GMT</pubDate>
            <atom:updated>2026-08-04T02:40:49.622Z</atom:updated>
            <content:encoded><![CDATA[<p>Reduction sounds simple. Summing 16 million numbers is a one-liner in Python. On a GPU it’s a whole different process. There are three ways to approach reduction on a GPU. Each one has different performance characteristics and different failure modes. I tried all three.</p><p>My RTX 3050 can move 224 GB/s of data. My reduction kernel hit 128.7 GB/s — 57% of peak — in 0.521 ms across 16M elements.</p><p>Here’s how I got there — and what the profiler said about the other 43%.</p><h3><strong>Naive Atomics:</strong></h3><p>This is the simplest approach. Here every thread grabs one element from the input array and directly adds it to the output using atomicAdd.</p><pre>__global__ void reduceNaive(float* input, float* output, int n) {<br>    int idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    if (idx &lt; n)<br>        atomicAdd(output, input[idx]);<br>}</pre><p>But the problem here is, 16 million threads all trying to atomically update the same single memory address. Now, Using Atomics here guarantee correctness by serializing concurrent updates but this means 16 million operations are running in sequence while they could have been running in parallel.</p><p>Result: 27.716 ms. 2.4 GB/s. That’s 53x slower than the warp shuffle version and 1% of what the GPU’s memory system can actually do.</p><p>The GPU has 2560 cores sitting idle waiting their turn to increment one counter.</p><h3><strong>Shared Memory Reduction:</strong></h3><p>The naive version failed because every thread was fighting over one global memory address. The fix is simple in concept — don’t do the final addition globally. Do most of the work locally first, then combine.</p><p>Here’s the idea: instead of 16 million threads all adding to one output, split the work. Each block of 256 threads is responsible for summing its own 256 elements. Once a block has its local sum, only one thread from that block touches the global output. So instead of 16 million global atomic operations, you have 65536 — one per block.</p><p>The local summing happens in shared memory — fast, on-chip memory that all threads in a block can access. The pattern is a tree reduction:</p><ul><li>Start: 256 threads, each holding one value</li><li>Step 1: first 128 threads each add the value from 128 threads ahead. Now 128 threads hold partial sums.</li><li>Step 2: first 64 threads each add the value from 64 threads ahead. Now 64 threads hold partial sums.</li><li>Step 3, 4, 5… keep halving until thread 0 holds the sum of all 256 elements.</li><li>Thread 0 does one atomicAdd to global memory.</li></ul><pre>__global__ void reduceShared(float* input, float* output, int n) {<br>    __shared__ float sdata[256];<br><br>    int idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    int tid = threadIdx.x;<br><br>    sdata[tid] = (idx &lt; n) ? input[idx] : 0.0f;<br>    __syncthreads();<br><br>    for (int stride = blockDim.x / 2; stride &gt; 0; stride &gt;&gt;= 1) {<br>        if (tid &lt; stride)<br>            sdata[tid] += sdata[tid + stride];<br>        __syncthreads();<br>    }<br><br>    if (tid == 0)<br>        atomicAdd(output, sdata[0]);<br>}</pre><p>The tree pattern also eliminates the divergence problem. At each step, the active threads are always the first half of the block and inactive threads are the second half — whole warps drop out cleanly instead of alternating active and idle threads within the same warp.</p><p>Result: 0.841 ms. 79.8 GB/s. 33x faster than naive atomics just by doing the reduction locally before touching global memory.</p><h3><strong>Warp Shuffle Reduction:</strong></h3><p>Shared memory reduction got us to 79.8 GB/s. Good, but not good enough. The problem is every step of the tree reduction is doing three things: writing to shared memory, reading from shared memory, and waiting at a __syncthreads() barrier for every thread in the block to catch up. For a 256-thread block that’s 8 steps of this write-read-sync cycle. It adds up.</p><p>Here’s the question: do threads actually need shared memory to communicate? Or is there a faster way?</p><p>Turns out there is. Within a warp — a group of 32 threads that execute together in lockstep — threads can read each other’s registers directly. Not shared memory. Not global memory. Registers. The hardware supports this through a set of instructions called warp shuffle intrinsics, and they work in a single instruction with no memory access and no barrier needed.</p><p>Think about what that means. Instead of:</p><ol><li>Write value to shared memory</li><li>Sync</li><li>Read value from shared memory</li></ol><p>You just do:</p><ol><li>Read directly from another thread’s register</li></ol><p>One step instead of three. No sync needed because all 32 threads in a warp are already executing the same instruction at the same time — there’s nothing to wait for.</p><p>The specific intrinsic we use is __shfl_down_sync. Here’s how it reduces 32 values down to 1 in just 5 instructions:</p><pre>__device__ float warpReduceSum(float val) {<br>    val += __shfl_down_sync(0xFFFFFFFF, val, 16); // each thread adds value from 16 lanes ahead<br>    val += __shfl_down_sync(0xFFFFFFFF, val, 8);  // each thread adds value from 8 lanes ahead<br>    val += __shfl_down_sync(0xFFFFFFFF, val, 4);<br>    val += __shfl_down_sync(0xFFFFFFFF, val, 2);<br>    val += __shfl_down_sync(0xFFFFFFFF, val, 1);<br>    return val;  // lane 0 now holds the sum of all 32 threads<br>}</pre><p>After the first instruction (delta=16): lane 0 holds its own value plus lane 16’s value. Lane 1 holds its value plus lane 17’s. And so on. After all 5 instructions, lane 0 holds the sum of all 32 values. Zero shared memory touched. Zero barriers waited on.</p><p>Now the full kernel uses this in two stages:</p><p><strong>Stage 1:</strong> Every warp independently runs warpReduceSum on its 32 threads. A 256-thread block has 8 warps, so after this step we have 8 partial sums — one per warp — sitting in lane 0’s register of each warp.</p><p><strong>Stage 2:</strong> Those 8 values need to be combined. This is the only place shared memory appears — lane 0 of each warp writes its partial sum into a shared memory array of 8 slots. Then warp 0 loads those 8 values and runs warpReduceSum one more time. Thread 0 ends up with the block’s total sum and does one final atomicAdd to global memory.</p><pre>__global__ void reduceWarpShuffle(float* input, float* output, int n) {<br>    __shared__ float sdata[32];  // only 8 slots actually used, one per warp<br><br>    int idx = blockIdx.x * blockDim.x + threadIdx.x;<br>    int lane = threadIdx.x % 32;<br>    int warpId = threadIdx.x / 32;<br><br>    // each thread loads its value<br>    float val = (idx &lt; n) ? input[idx] : 0.0f;<br><br>    // stage 1: warp-level reduction using shuffles — no shared memory<br>    val = warpReduceSum(val);<br><br>    // write warp results to shared memory<br>    if (lane == 0)<br>        sdata[warpId] = val;<br>    __syncthreads();<br><br>    // stage 2: warp 0 reduces the 8 warp sums<br>    if (warpId == 0) {<br>        val = (lane &lt; blockDim.x / 32) ? sdata[lane] : 0.0f;<br>        val = warpReduceSum(val);<br>    }<br><br>    // thread 0 writes final result<br>    if (threadIdx.x == 0)<br>        atomicAdd(output, val);<br>}</pre><p>Shared memory is used exactly once — to pass 8 values between warps. Everything else stays in registers. One __syncthreads() instead of 8.</p><p>Result: 0.523 ms. 128.4 GB/s. 1.6x faster than shared memory reduction, 53x faster than naive atomics, 57% of peak memory bandwidth on an RTX 3050.</p><p>The remaining 43% is what Nsight Compute flagged — we’ll get to that next.</p><h3><strong>What Nsight Compute said about the other 43%:</strong></h3><p>128.4 GB/s sounds good. But the RTX 3050 can move 224 GB/s. That’s 43% left on the table. So I ran Nsight Compute to see where it’s going.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdL8mNl9LSu0ND5Yhi0bVQ.png" /></figure><p>Three things flagged:</p><p><strong>1. Achieved Occupancy (21.75% estimated speedup)</strong><br> Theoretical occupancy is 100% but measured is 73.9%. In a reduction kernel this makes sense — in the later stages of the shuffle tree, most threads are idle while only a few are still doing work. The SM has warps resident but they’re not all active every cycle.</p><p><strong>2. Long Scoreboard Stalls (21.75% estimated speedup)</strong><br> Warps are spending 12.9 cycles on average waiting on memory loads — specifically the initial input[idx] read from global memory. 46.5% of all cycles are stalled here. This is the fundamental cost of reading 16M floats from DRAM — you can’t eliminate it, only hide it better with more occupancy.</p><p><strong>3. FP32 Non-Fused Instructions</strong><br> The compiler isn’t fusing additions into FMA instructions. For a pure sum reduction this barely matters since we’re doing additions not multiply-adds, but it’s worth noting.</p><p>The two real bottlenecks — occupancy and memory stalls — are connected. More occupancy means more warps to hide latency with. The profiler is telling: if you could keep more warps busy during the memory load phase, you’d cover more of those stall cycles and push closer to peak bandwidth.</p><p>That’s the next optimization — but that’s a different article.</p><h3><strong>Key Takeaways:</strong></h3><ul><li>If every thread is hitting the same global address, you don’t have a parallel program anymore. You have a queue. Naive atomics on 16M elements proves this — 27ms for something that should take 0.5ms.</li><li>Shared memory is the right level to reduce at. Do the work locally per block, then combine. 33x speedup just from that one change.</li><li>Warp shuffles exist because shared memory has overhead too. Register-to-register communication within a warp is faster than anything involving memory. Five shuffle instructions, no barriers, lane 0 has the sum.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22bc38a03f3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From 467 to 3600 GFLOP/s: optimizing CUDA matrix multiplication on an RTX 3050]]></title>
            <link>https://medium.com/@aniketm2598/from-467-to-3600-gflop-s-optimizing-cuda-matrix-multiplication-on-an-rtx-3050-543022d260cd?source=rss-50d97f3aa5ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/543022d260cd</guid>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gpu-programming]]></category>
            <dc:creator><![CDATA[Aniket Maheshwari]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 03:08:23 GMT</pubDate>
            <atom:updated>2026-07-28T03:10:41.962Z</atom:updated>
            <content:encoded><![CDATA[<p>Three versions of the same problem — matrix multiplication. Same GPU, same matrix size, same math. Here’s what each one measured:</p><p>Naive: 467 GFLOP/s</p><p>Tiled: 620 GFLOP/s (1.3x faster)</p><p>Register-tiled: 3600 GFLOP/s (7.8x faster overall)</p><p>Theory says tiling should reduce DRAM traffic by 16x — I got 1.3x. Then register tiling, which I expected to be a modest improvement on top of tiling, gave me 6x more on top of that.</p><p>Here’s what actually happened.</p><h3>Naive Kernel:</h3><p>The 1st version I tried was the simplest approach i.e. naïve kernel. So here, each of the thread in the kernel is responsible for one output in the matrix. So, one thread takes one row of A, one column of B and multiplies those elements and then sums everything up. That’s it.</p><pre>__global__ void matmulNaive(float* A, float* B, float* C, int n) {<br>    int row = blockIdx.y * blockDim.y + threadIdx.y;<br>    int col = blockIdx.x * blockDim.x + threadIdx.x;<br><br>    if (row &lt; n &amp;&amp; col &lt; n) {<br>        float sum = 0.0f;<br>        for (int k = 0; k &lt; n; k++) {<br>            sum += A[row * n + k] * B[k * n + col];<br>        }<br>       C[row * n + col] = sum;<br>    }<br>}</pre><p>For matrix multiplication, Thread (0,0) and Thread (0,1) both will need same row of A and different column of B. Here’s the problem with naïve version, as each iteration of the inner loop goes straight to fetch the values of the same row A from DRAM which is the slowest memory on the GPU. Now both thread (0,0) and thread (0,1) need the same row of A but they are not sharing these values with each other and making separate trips to DRAM.</p><p>I ran this through Nsight Compute to see what was actually happening — only 18 of 32 bytes per memory sector were actually being used. Half the memory bandwidth wasted on every load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7hrhHV1hS6Oro-ao5E_eA.png" /><figcaption>Nsight Compute flagging the naive kernel’s memory access pattern — only 18 of 32 bytes per memory sector are being used. Fixing coalescing alone could give 43% more performance.</figcaption></figure><p>Result: 467 GFLOP/s. My RTX 3050 can do ~9000 GFLOP/s. That’s 5% of peak. The compute units were mostly just sitting there waiting on memory.</p><h3>Tiled Kernel:</h3><p>Tiled kernel approach solves the issue with naïve kernel was each thread going to DRAM independently. The idea is simple, Threads in a block cooperate with each other rather than working in isolation. We load a small chunk of matrix A and matrix B into shared memory first since that it is on-chip and much faster to access than DRAM so it takes fewer cycles per access. Once load into shared memory, every thread reads values from there.</p><pre><br>#define TILE_SIZE 16<br><br>__global__ void matmulTiled(float* A, float* B, float* C, int n) {<br>    __shared__ float tileA[TILE_SIZE][TILE_SIZE];<br>    __shared__ float tileB[TILE_SIZE][TILE_SIZE];<br><br>    int row = blockIdx.y * TILE_SIZE + threadIdx.y;<br>    int col = blockIdx.x * TILE_SIZE + threadIdx.x;<br><br>    float sum = 0.0f;<br><br>    for (int t = 0; t &lt; n / TILE_SIZE; t++) {<br><br>        // cooperative load: each thread loads one element of each tile<br>        tileA[threadIdx.y][threadIdx.x] = A[row * n + (t * TILE_SIZE + threadIdx.x)];<br>        tileB[threadIdx.y][threadIdx.x] = B[(t * TILE_SIZE + threadIdx.y) * n + col];<br><br>        __syncthreads();<br><br>        // compute partial dot product from this tile<br>        for (int k = 0; k &lt; TILE_SIZE; k++) {<br>            sum += tileA[threadIdx.y][k] * tileB[k][threadIdx.x];<br>        }<br><br>        __syncthreads();<br>    }<br><br>    if (row &lt; n &amp;&amp; col &lt; n)<br>        C[row * n + col] = sum;<br>}</pre><p>Now here, our TILE_SIZE is 16 so in theory our new kernel should run 16x speedup on memory bound than naïve kernel as tiling reduces DRAM traffic by a factor of TILE_SIZE, which is 16 in our case. However, what I actually got is: 620 GFLOP per second. That’s 1.3x faster than naïve. Not 16x.</p><p>I went to the profiler to figure out why. Here’s what it showed:</p><p>Naive DRAM reads: ~280 MB</p><p>Tiled DRAM reads: ~278 MB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pHJLioeCvjc8Ddeh6xpMQ.png" /><figcaption>Nsight Compute on the tiled kernel — coalescing warning is gone, only one warning left (MIO Throttle Stall from shared memory pressure). Estimated speedup dropped to 7.87% meaning most obvious problems are fixed.</figcaption></figure><p>The reason behind this is L2 cache. Since our working set (1024 * 1024) is small enough that the GPU’s L2 cache was already absorbing most of the naïve kernel redundant reads automatically. So, when thread (0,0) reads row A, that row lands in L2 automatically by the hardware. Now when thread (0,1) wants to read the same row, instead of going to DRAM, it hits L2 cache.</p><p>So in our case tiling didn’t drastically improve the performance but in real life scenarios at larger matrix sizes where the working set overflows L2, tiling would show much closer to that theoretical 16x improvement.</p><h3>Register Tiled Kernel:</h3><p>Tiling kernel did help speed up a little but the shared memory was still being hit redundantly though. In both the previous kernels, each thread is responsible for computing one output element. What if we changed that so each thread computes more than one, in this case 4*4 block of 16 output elements. So, the same values are loaded from shared memory into registers get reused across all 16 multiply-adds instead of just 1.</p><pre>#define BM 64<br>#define BN 64<br>#define BK 16<br>#define TM 4<br>#define TN 4<br><br>__global__ void matmulRegisterTiled(float* A, float* B, float* C, int n) {<br>    // where does this thread&#39;s 4x4 output chunk start in C?<br>    int rowStart = blockIdx.y * BM + threadIdx.y * TM;<br>    int colStart = blockIdx.x * BN + threadIdx.x * TN;<br><br>    // accumulator: 4x4 output values, all in registers<br>    float sum[TM][TN] = {0.0f};<br><br>    // shared memory tiles<br>    __shared__ float tileA[BM][BK];<br>    __shared__ float tileB[BK][BN];<br><br>    // each thread loads 4 elements of tileA and 4 of tileB<br>    // thread grid is 16x16 = 256 threads<br>    // tileA is 64x16 = 1024 elements → each thread loads 4<br>    int threadRow = threadIdx.y;  // 0-15<br>    int threadCol = threadIdx.x;  // 0-15<br><br>    for (int t = 0; t &lt; N / BK; t++) {<br><br>        // cooperative load of tileA (64x16)<br>        // each thread loads a 4x1 column strip<br>        for (int i = 0; i &lt; TM; i++) {<br>            tileA[threadRow * TM + i][threadCol] =<br>                A[(blockIdx.y * BM + threadRow * TM + i) * N<br>                  + (t * BK + threadCol)];<br>        }<br><br>        // cooperative load of tileB (16x64)<br>        // each thread loads a 1x4 row strip<br>        for (int i = 0; i &lt; TN; i++) {<br>            tileB[threadRow][threadCol * TN + i] =<br>                B[(t * BK + threadRow) * N<br>                  + (blockIdx.x * BN + threadCol * TN + i)];<br>        }<br><br>        __syncthreads();<br><br>        // compute: each thread does TM x TN = 4x4 = 16 multiply-adds<br>        for (int k = 0; k &lt; BK; k++) {<br>            // load this thread&#39;s slice of tileA and tileB into registers<br>            float regA[TM], regB[TN];<br>            for (int i = 0; i &lt; TM; i++)<br>                regA[i] = tileA[threadRow * TM + i][k];<br>            for (int j = 0; j &lt; TN; j++)<br>                regB[j] = tileB[k][threadCol * TN + j];<br><br>            // outer product: reuse regA and regB across all 16 outputs<br>            for (int i = 0; i &lt; TM; i++)<br>                for (int j = 0; j &lt; TN; j++)<br>                    sum[i][j] += regA[i] * regB[j];<br>        }<br><br>        __syncthreads();<br>    }<br><br>    // write results to C<br>    for (int i = 0; i &lt; TM; i++)<br>        for (int j = 0; j &lt; TN; j++)<br>            if (rowStart + i &lt; N &amp;&amp; colStart + j &lt; N)<br>                C[(rowStart + i) * N + (colStart + j)] = sum[i][j];<br>}</pre><p>Result: 3600 GFLOP/s. That’s 7.8x faster than naive and 6x faster than tiled.</p><p>This time the profiler told a very different story:</p><p>Naive DRAM reads: ~280 MB</p><p>Tiled DRAM reads: ~278 MB</p><p>Register-tiled DRAM reads: ~53 MB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6M9CzYFL2i-rI8fVKNW-jw.png" /><figcaption>Nsight Compute on the register-tiled kernel — new bottleneck appeared. The write-back step where each thread writes its 4×4 results to global memory is now scattered. That’s the next thing to fix.</figcaption></figure><p>Here we have 5x less DRAM traffic than both naïve and tiled. The optimization actually showed up this time around and there are 2 reasons for that. First, Since each thread is doing 16 outputs rather than 1 means same data is reused 16 times before being discarded — this is genuine register-level reuse. Second, the bigger output tile (64×64 instead of 16×16) meant the working set finally exceeded what L2 could absorb, so the reuse actually eliminated real DRAM trips instead of just duplicating what the cache was already doing.</p><p>The compute units went from sitting idle waiting on memory to actually doing work. 40% of theoretical peak on an RTX 3050 — not cuBLAS level, but a real number from a kernel written from scratch.</p><p><strong>What’s Next:</strong></p><p>I achieved 40% of theoretical peak which is decent result for a kernel written from scratch but there’s still a lot left to be squeezed out perform wise. The profiler flagged uncoalesced store access patterns in the register-tiled kernel — the write-back step where each thread writes its 4×4 results back to global memory is scattered. Vectorized stores can be used to fix this.</p><p>Everything I’ve done so far uses regular CUDA cores doing one multiply-add at a time but tensor cores can do 4*4*4 matrix multiply in a single instruction and that’s where the real throughput live for GEMM on modern NVIDIA GPUs. Getting to cuBLAS — level performance means using them.</p><p><strong>Key Takeaways:</strong></p><ul><li>Tiling reduces DRAM traffic in theory but with a small matrix size L2 cache already handles the redundancy reads so the real-world speedup can be much smaller than expected.</li><li>Always profile — the profiler will tell you things you simply can’t see from timing alone. Like in my case, Naïve and tiled had nearly identical DRAM reads — without ncu, I’d never know why tiling didn’t help.</li><li>Register tiling is where the actual performance lives — reusing data across multiple outputs per thread is what finally moved the needle from 5% to 40% of peak.</li></ul><p>Full code: <a href="https://github.com/rorschach02/cuda-kernels">github.com/rorschach02/cuda-kernels</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=543022d260cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>