<?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 Shreyas Dixit on Medium]]></title>
        <description><![CDATA[Stories by Shreyas Dixit on Medium]]></description>
        <link>https://medium.com/@srddev?source=rss-5a5bc853a7b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*arN_67VsjzrXdyhabvd4BQ.jpeg</url>
            <title>Stories by Shreyas Dixit on Medium</title>
            <link>https://medium.com/@srddev?source=rss-5a5bc853a7b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:03:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srddev/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[Prefill vs. Decode: What an LLM Is Really Doing on the GPU]]></title>
            <link>https://medium.com/@srddev/prefill-vs-decode-what-an-llm-is-really-doing-on-the-gpu-8015533d8717?source=rss-5a5bc853a7b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8015533d8717</guid>
            <dc:creator><![CDATA[Shreyas Dixit]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 16:06:12 GMT</pubDate>
            <atom:updated>2026-11-15T07:14:36.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-MmvylzM8hNWUQGFFwBLw.png" /></figure><p>You enter a prompt, wait briefly, and then watch an answer arrive token by token. At the API level this looks like one operation: generate().</p><p>Inside the GPU, it is better understood as two different workloads connected by a cache. The model first processes the prompt in bulk. Then it enters a loop in which it generates one new token at a time.</p><p>Those phases use the same weights, but they stress the hardware differently. The first phase tends to expose compute throughput. The second often exposes memory bandwidth, cache layout, and kernel-launch overhead.</p><p>This distinction is the starting point for understanding LLM serving performance.</p><h3>A compact mental model</h3><p>An autoregressive language model predicts the next token from the tokens it has seen:</p><pre>prompt -&gt; next token -&gt; prompt + next token -&gt; next token -&gt; ...</pre><p>The loop is simple. The work required to implement it efficiently is not.</p><p>For each transformer layer, the model transforms token representations using attention and a feed-forward network. At the end, the final representation is projected to vocabulary logits, a token is selected, and that token becomes the input to the next iteration.</p><p>The important observation is that the first iteration has an entire prompt to work on, while later iterations have only one newly arrived token.</p><h3>From text to tensors</h3><p>Before the GPU runs a transformer layer, the input string is converted into token IDs. A tokenizer maps pieces of text to integers:</p><pre>prompt = &quot;How does GPU inference work?&quot;<br>token_ids = tokenizer.encode(prompt)</pre><p>The IDs index an embedding table. If the vocabulary has V entries and the model hidden size is H, the table has shape [V, H]:</p><pre>hidden = embedding_table[token_ids]  # [sequence_length, hidden_size]</pre><p>At kernel level, embedding lookup is not a matrix multiplication. Each GPU thread or thread group copies one row of the embedding table into the output. The access pattern is mostly a gather, so locality depends on the token IDs and on whether multiple requests happen to use nearby rows.</p><p>Position information is added at this stage or inside attention. Rotary position embeddings, commonly called RoPE, apply position-dependent rotations to query and key vectors. This lets attention distinguish token order without storing a separate learned vector for every absolute position.</p><h3>What one transformer layer computes</h3><p>Ignoring normalization and residual connections for a moment, self-attention can be summarized as:</p><pre>Q = hidden @ Wq<br>K = hidden @ Wk<br>V = hidden @ Wv</pre><pre>scores = Q @ transpose(K)<br>scores = scores / sqrt(head_dim)<br>weights = softmax(scores)<br>attention_output = weights @ V</pre><p>The feed-forward network then transforms each token independently. A simplified version looks like:</p><pre>expanded = hidden @ W_up<br>activated = activation(expanded)<br>output = activated @ W_down</pre><p>Attention moves information between token positions. The feed-forward network processes information within each position. Both contain large matrix operations, but their shapes change dramatically between prefill and decode.</p><h3>The kernel view: what does the GPU actually execute?</h3><p>The Python-like equations above hide the work performed by CUDA kernels. A typical layer may launch kernels for:</p><ol><li>embedding lookup and positional rotation;</li><li>the fused or unfused QKV projection;</li><li>attention score computation;</li><li>masking and softmax;</li><li>the value-weighted attention output;</li><li>output projection;</li><li>normalization and activation;</li><li>the two feed-forward projections.</li></ol><p>Some production runtimes fuse several of these operations. For example, a fused attention kernel can load tiles of Q, K, and V, compute partial softmax statistics, and write the output without materializing the full attention matrix in global memory.</p><p>That matters because a kernel is constrained by more than its floating-point operation count. It also has to move bytes through the memory hierarchy, schedule threads, use registers and shared memory effectively, and avoid unnecessary kernel launches.</p><h3>Phase one: prefill</h3><p>Prefill processes all prompt tokens before generation begins. If the batch size is B, prompt length is S, and hidden size is H, a projection has a shape similar to:</p><pre>activations: [B * S, H]<br>weights:     [H, H]<br>output:     [B * S, H]</pre><p>The sequence dimension is available as parallel work. A CUDA GEMM kernel can divide the output matrix into tiles. Thread blocks cooperatively load tiles of the input and weights into shared memory, perform multiply-accumulate operations in registers, and write an output tile back to global memory.</p><p>Conceptually:</p><pre>for each output tile:<br>    load activation tile into shared memory<br>    load weight tile into shared memory<br>    synchronize threads<br>    accumulate products in registers<br>    repeat over the reduction dimension<br>    store output tile</pre><p>Modern GPUs are designed for this kind of matrix-matrix multiplication. Tensor Cores can execute many low-precision multiply-accumulate operations per cycle, while the large number of prompt rows gives the scheduler enough independent work to occupy the machine.</p><p>Prefill is therefore often limited by math throughput, although memory traffic, attention strategy, and prompt length still matter. The user-visible metric is usually time to first token (TTFT): the delay between submitting the request and receiving the first generated token.</p><p>A simplified prefill loop is:</p><pre>hidden = embed(prompt_ids)</pre><pre>for layer in layers:<br>    q, k, v = layer.project_qkv(hidden)       # many tokens at once<br>    hidden = layer.attend_prefill(q, k, v)<br>    hidden = layer.feed_forward(hidden)<br>    kv_cache[layer].write(k, v)</pre><pre>first_token = sample(lm_head(hidden[:, -1, :]))</pre><p>The cache is populated as a side effect of this work.</p><h3>Phase two: decode</h3><p>After the first token, the model normally receives one new token per iteration. The new query must attend to the keys and values for the complete context, but the old keys and values do not need to be recomputed.</p><p>The projection now resembles:</p><pre>activations: [B, 1, H]<br>weights:     [H, H]<br>output:      [B, 1, H]</pre><p>This is closer to a matrix-vector operation than a large matrix-matrix operation. The arithmetic per request is narrow, but the model still needs to read its weight matrices and the relevant KV-cache entries.</p><pre>while not finished:<br>    hidden = embed(next_token)</pre><pre>    for layer in layers:<br>        q, k_new, v_new = layer.project_qkv(hidden)<br>        kv_cache[layer].append(k_new, v_new)<br>        hidden = layer.attend_decode(q, kv_cache[layer])<br>        hidden = layer.feed_forward(hidden)</pre><pre>    next_token = sample(lm_head(hidden))<br>    yield next_token</pre><p>The user-visible metric is usually inter-token latency (ITL): the time between successive generated tokens. Decode quality is not determined by ITL alone, but ITL strongly affects whether streaming feels responsive.</p><h3>Why the bottleneck changes</h3><p>A useful first approximation is arithmetic intensity:</p><pre>arithmetic intensity = operations performed / bytes moved</pre><p>Large prefill GEMMs reuse weight tiles across many prompt tokens. That reuse can produce high arithmetic intensity, making the GPU’s compute units the limiting resource.</p><p>A decode step has much less work per request. The system may repeatedly fetch large weight matrices to perform a small amount of useful work for each token. It also reads an expanding KV cache. In this regime, the GPU may have unused arithmetic capacity while the execution waits on memory movement or synchronization.</p><p>This is why the same model can look compute-bound during prefill and memory-bound during decode. The labels are not absolute: batching multiple decode requests can restore larger GEMMs, and a poorly optimized prefill kernel can still be bandwidth- limited. They are a way to form a testable hypothesis about the dominant cost.</p><h3>Attention kernels and the cost of materializing scores</h3><p>Naive attention computes a score matrix with shape [query_tokens, key_tokens]. For a long prompt, materializing this matrix can consume substantial memory traffic:</p><pre>scores = Q @ K.transpose(-2, -1)<br>probabilities = softmax(scores)<br>output = probabilities @ V</pre><p>An optimized attention kernel avoids writing every intermediate value to global memory. It processes blocks of Q, K, and V in shared memory or registers, maintains the running maximum and normalization terms needed by softmax, and directly accumulates the output.</p><p>This family of techniques is often described as tiled or memory-efficient attention; FlashAttention is a well-known example. The central insight is not that the math changes. The same attention result is computed with a better IO schedule.</p><p>For decode, the query tile may contain only one token per sequence. The kernel then scans the cached keys and values, which makes cache layout and coalesced memory access especially important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1__VPU5vFdwJlXjR1oVOng.png" /></figure><h3>The KV cache is an algorithmic optimization and a memory problem</h3><p>Without a KV cache, every generated token would recompute keys and values for all previous tokens. The cache stores those tensors once per layer:</p><pre>K cache: [batch, kv_heads, context_length, head_dim]<br>V cache: [batch, kv_heads, context_length, head_dim]</pre><p>The exact layout varies by runtime. That choice affects whether a warp can read adjacent addresses, whether cache updates are contiguous, and how efficiently different requests can share a batch.</p><p>Appending with repeated tensor concatenation is conceptually simple but can cause reallocations and copies:</p><pre># Educational pseudocode; avoid reallocating this way in a production loop.<br>K = concatenate([K, k_new], axis=context_axis)</pre><p>Real serving systems preallocate capacity, use blocks or pages, and track which physical cache blocks belong to each sequence. Paged KV-cache designs reduce fragmentation and make it easier to batch requests with different sequence lengths.</p><p>Grouped-query attention and multi-query attention reduce the number of distinct K/V heads. KV-cache quantization reduces bytes per element. Sliding-window or sink-token strategies limit how much history later queries must read. Each technique changes a different part of the memory and accuracy trade-off.</p><h3>Kernel mapping: a practical CUDA checklist</h3><p>When investigating a slow kernel, I want to answer these questions before changing the algorithm:</p><h3>1. What is the work tile?</h3><p>For a GEMM, identify the output tile assigned to each thread block and the reduction dimension. For attention, identify Q/K/V tile sizes and how the sequence dimension is partitioned across warps.</p><h3>2. Where do the operands live?</h3><p>Global memory provides capacity but has high latency. Shared memory can stage a tile for reuse. Registers are fast but limited per thread. A kernel that spills registers to local memory can lose the benefit of an apparently good tiling strategy.</p><h3>3. Are accesses coalesced?</h3><p>Neighboring threads should usually access neighboring addresses. A poor KV-cache layout can turn a logically simple decode attention operation into many inefficient memory transactions.</p><h3>4. How much synchronization is necessary?</h3><p>Block-level barriers are useful when sharing tiles, but excessive synchronization reduces available instruction-level parallelism. Fusing operations can also remove intermediate reads and writes, at the cost of a more complex kernel.</p><h3>5. Is the launch overhead visible?</h3><p>Decode may launch many small kernels per token and per layer. CUDA Graphs, operator fusion, persistent kernels, and carefully chosen batching can reduce this overhead. The best choice depends on whether request shapes are stable enough to capture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDuM-25RclpTipj_fd8LiA.png" /></figure><h3>Quantization changes the memory equation</h3><p>Inference often uses lower precision than training. A rough weight-storage estimate for a model with P parameters is:</p><pre>FP32: P * 4 bytes<br>FP16/BF16: P * 2 bytes<br>INT8: P * 1 byte<br>INT4: P * 0.5 bytes</pre><p>The real footprint includes scales, zero points, metadata, activations, temporary buffers, and the KV cache, so these numbers are only a first estimate.</p><p>Lower precision can help in two ways: it reduces memory capacity requirements and reduces the number of bytes moved by bandwidth-sensitive kernels. It may also enable specialized Tensor Core instructions. The cost is accuracy risk and possible dequantization overhead.</p><p>For decode, reducing weight and cache traffic can be especially valuable. But a quantized kernel is only a win if its packing, scaling, and dequantization path are efficient enough to offset their overhead.</p><h3>Measuring the two phases correctly</h3><p>GPU execution is asynchronous with respect to the CPU. This timing pattern is not reliable:</p><pre>start = time.perf_counter()<br>output = model(input_ids)<br>elapsed = time.perf_counter() - start</pre><p>The CPU may stop the timer before the GPU has finished. Use CUDA events or explicit synchronization around the region being measured:</p><pre>start = torch.cuda.Event(enable_timing=True)<br>end = torch.cuda.Event(enable_timing=True)</pre><pre>for _ in range(warmup):<br>    run_step()</pre><pre>torch.cuda.synchronize()<br>start.record()<br>run_step()<br>end.record()<br>end.synchronize()</pre><pre>milliseconds = start.elapsed_time(end)</pre><p>For a useful report, record:</p><ul><li>GPU model and driver;</li><li>PyTorch and CUDA versions;</li><li>batch size and sequence lengths;</li><li>number of layers, heads, KV heads, and hidden size;</li><li>dtype and quantization format;</li><li>warm-up and repetition counts;</li><li>whether the measurement includes sampling, synchronization, and data transfers.</li></ul><p>The first result I want is not a single “tokens per second” number. It is a table that separates TTFT, per-token decode latency, total generation time, and memory usage across prompt and generation lengths.</p><h3>The experiment in this repository</h3><p>The project begins with a small workload-shape benchmark:</p><pre>cd 01-prefill-vs-decode<br>python -m venv .venv<br>.venv\Scripts\Activate.ps1<br>python -m pip install -e &quot;.[dev]&quot;<br>python -m pip install -r requirements-cuda.txt</pre><pre>python -m prefill_vs_decode.benchmark \<br>  --prompt-tokens 512 \<br>  --decode-tokens 32</pre><p>The first version isolates projection shapes. The next version will replace that baseline with explicit attention, a real KV cache, CUDA-event timing, and a sweep over prompt length, context length, batch size, and precision.</p><p>The goal is not to reproduce a production serving engine immediately. It is to make each performance effect visible enough to reason about and measure.</p><h3>Putting the request together</h3><p>An LLM request can now be viewed as this pipeline:</p><pre>text<br>  -&gt; tokenize<br>  -&gt; embedding and position handling<br>  -&gt; prefill: large parallel kernels, populate KV cache<br>  -&gt; sample first token<br>  -&gt; decode loop:<br>       read one token<br>       project Q/K/V<br>       append K/V<br>       attend over cached history<br>       run feed-forward network<br>       sample next token<br>  -&gt; detokenize and stream</pre><p>Serving systems add continuous batching, request scheduling, speculative decoding, quantization, paged memory management, and specialized attention kernels. These features are easier to understand once prefill and decode are treated as separate performance problems.</p><h3>What to ask when inference feels slow</h3><p>The first diagnostic question should be: slow to start, or slow to stream?</p><ul><li>Slow first token points toward prompt processing, queueing, input transfers, or prefill kernels.</li><li>Slow tokens after generation begins points toward decode arithmetic intensity, KV-cache bandwidth, kernel launches, batching, or sampling overhead.</li><li>High GPU utilization does not automatically mean efficient inference; utilization can hide poor memory behavior or unnecessary work.</li><li>A longer context affects both computation and cache capacity, which can reduce the number of concurrent requests the GPU can hold.</li></ul><p>The transformer equations are only the beginning. Inference performance is decided by how those equations are tiled, fused, quantized, scheduled, and connected to memory.</p><h3>Conclusion</h3><p>Prefill and decode are two phases of one request, but they are not the same workload. Prefill offers broad parallelism and often rewards high-throughput matrix kernels. Decode repeats a narrow computation and often rewards efficient memory movement, cache management, batching, and low launch overhead.</p><p>The KV cache makes autoregressive generation practical, while also becoming one of the main memory costs to control. At the kernel level, the important questions are how data is tiled, where it is stored, how often it is moved, and how much work each GPU launch exposes.</p><p>Thanks for reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8015533d8717" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inference Optimization : GEMM]]></title>
            <link>https://medium.com/@srddev/inference-optimization-gemm-623c1fcc001e?source=rss-5a5bc853a7b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/623c1fcc001e</guid>
            <category><![CDATA[gemm]]></category>
            <category><![CDATA[opencl]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[matmul]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Shreyas Dixit]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 02:31:01 GMT</pubDate>
            <atom:updated>2026-04-14T02:31:01.495Z</atom:updated>
            <content:encoded><![CDATA[<h3>Inference Optimization : GEMM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FCZxiScCrX6Ub_bxfDffow.png" /></figure><p>If you look under the hood of any modern LLM, past the attention mechanisms and layer norms, it basically boils down to one thing: Matrix Multiplication (MatMul). It is the undisputed bottleneck for both training and inference.</p><p>In my last post, we looked at the physical constraints of the hardware. We talked about the “Memory Wall” the reality that your GPU’s math cores spend most of their time sitting idle, starved of data, just waiting for massive weight tensors to be dragged out of VRAM. You can’t fix this by just having a faster GPU; you have to write code that explicitly respects the hardware’s memory hierarchy.</p><p>Today, we are going hands-on. <strong>If you search the web for how to do this, you will find a mountain of incredible tutorials dedicated entirely to NVIDIA’s CUDA. But there is a glaring gap in the ecosystem: there are almost zero comprehensive guides covering these exact same low-level optimizations in OpenCL. So, I am giving it a try.</strong></p><p>I am going to write a MatMul kernel from scratch using OpenCL. We will start with the most naive, unoptimized code possible, and then step-by-step, we will fix it. We’ll cover memory coalescing, SRAM tiling, and warp-level register caching until we push the silicon to its absolute limit.</p><p>To make things interesting, I am going to benchmark every single optimization stage across two totally different architectures: an integrated AMD Radeon iGPU and a dedicated NVIDIA RTX 3060 for matrices of shape 1024x1024. As you will see, hardware dictates everything, and what is highly optimized for one chip might actually break the other. The aim of this blog is to simply learn, implement, and document the optimization of matmuls.</p><h3>The GPU Execution Hierarchy</h3><p>Basic understanding of how the GPU organizes its workforce is crucial before we write our first line of code. When we dispatch a compute job to the GPU, we don’t just throw a million threads at it randomly; we organize them into a strict 3D hierarchy:</p><ol><li><strong>The Work Grid (<em>NDRange</em> in OpenCL):</strong> This represents the entire problem space. If we are multiplying two 1024x1024 matrices, our global grid will have 1,048,576 individual workers.</li><li><strong>The Block (<em>Work-group</em> in OpenCL):</strong> The GPU chops the massive Work Grid into smaller, manageable chunks called Blocks. Threads inside the same block are special — they can communicate with each other, synchronize their execution, and share ultra-fast SRAM memory.</li><li><strong>The Single Thread (<em>Work-item</em> in OpenCL):</strong> The individual worker at the bottom of the pyramid. It executes the actual math in our C++ kernel.</li></ol><p>The entire dark art of GPU optimization lies in how we manipulate these blocks and threads to share data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39ov-3Vzqai-2GGtLgtYSg.png" /><figcaption>GPU Execution Hierarchy</figcaption></figure><h4>Kernel 1 : The Naive Baseline</h4><p>The most natural way to perform matrix multiplication is computing each output element as a dot product. In OpenCL, instead of writing nested for loops for the rows and columns, we assign one thread to compute exactly one element of the output matrix C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*m0WHxY6q7iY_uv06HP1ThA.png" /></figure><pre>__kernel void NaiveMatMul(__global const float* A, __global const float* B, __global float* C, int M, int N, int K) {<br>    // Get the row and column this specific thread is responsible for<br>    const int row = get_global_id(1);<br>    const int col = get_global_id(0);<br><br>    float sum = 0.0f;<br>    if (row &lt; M &amp;&amp; col &lt; N) {<br>        for (int i = 0; i &lt; K; i++) {<br>            float a = A[row * K + i];<br>            float b = B[i * N + col];<br>            sum += a * b;<br>            <br>            // Writing the result directly to Global Memory<br>            C[row * N + col] = sum; <br>        }<br>    }<br>}</pre><p>This kernel takes about <strong>168.7 ms</strong> on my integrated AMD Radeon GPU and <strong>31.6 ms</strong> on my dedicated NVIDIA RTX 3060.</p><p><strong>Lower Bounding the Fastest Possible Runtime</strong></p><p>For a matrix multiplication of two 1024 x 1024 matrices:</p><ul><li><strong>Total FLOPs:</strong> For each of the 1024² entries of C, we have to perform a dot product of two vectors of size 1024. This involves a multiply and an add at each step (2 FLOPs).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/0*i2mAeKVssBJYhybH.png" /></figure><ul><li><strong>Total data to read (minimum!):</strong> Both Matrix A and Matrix B need to be read at least once.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/0*N6oTY7KfMsw4kBcC.png" /></figure><ul><li><strong>Total data to store:</strong> The resulting Matrix C must be written to memory.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*RLhN4jesxaEklCrj.png" /></figure><p>So <strong>12.57 MB</strong> is the absolute minimum amount of memory that <em>any</em> implementation would have to transfer from/to global GPU memory, assuming it has a magically infinite cache that never drops a value.</p><p>To recap, when I run this kernel on an RTX 3060, it achieves ~68 GFLOPs. Pretty bad, considering that an RTX 3060 is advertised as being able to achieve nearly 7,000 GFLOPs (7 TFLOPs). Where as the AMD GPU gets around 12.73 GFLOPs.</p><p>But notice how the NVIDIA GPU is over 5 times faster than the AMD GPU on the exact same code. Why? Because dedicated high-end GPUs have massive L2 caches and incredibly wide GDDR6 memory buses. The NVIDIA silicon is essentially brute-forcing its way through our 12.8 GB of bad memory requests, buffering the redundant global writes in its cache to hide our coding mistakes.</p><h4>Kernel 2 : <strong>Register Accumulation</strong></h4><p>If you take a look at the above code again , you can see that we are writing the output to the C matrix which is in the global memory in the for loop itself. One might say this is a very small thing, but when we move that repeated writing to the global memory outside the for loop it will create a impact for the kernel.</p><pre>__kernel void NaiveMatMul(__global const float* A, __global const float* B, __global float* C, int M, int N, int K) {<br>    const int row = get_global_id(0);<br>    const int col = get_global_id(1);<br><br>    if (row &lt; M &amp;&amp; col &lt; N) {<br>        float sum = 0.0f;<br>        for (int i = 0; i &lt; K; i++) {<br>            // Memory access: Row of A, Column of B<br>            sum += A[row * K + i] * B[i * N + col];<br>        }<br>        // WRITE ONLY ONCE AFTER THE LOOP<br>        C[row * N + col] = sum;<br>    }<br>}</pre><ul><li><strong>AMD iGPU:</strong> 29.83 GFLOPS (2.3× faster)</li><li><strong>NVIDIA 3060:</strong> 157.14 GFLOPS (2.3× faster)</li></ul><p>Just by moving one line of code out of a loop, we instantly eliminated millions of unnecessary VRAM writes and more than doubled our performance on both architectures. Notice how the RTX 3060 is churning out 157 GFLOPS on essentially naive code. High-end GPUs have massive L2 caches that act as a crutch, automatically buffering terrible memory access patterns. But 157 GFLOPS is barely a fraction of what this silicon is capable of. To push higher, we have to stop focusing on <em>how often</em> we write to memory, and look at <em>how</em> we are reading from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*nCsCRABeM-bxwdqsYDbxow.png" /><figcaption>Continuous and Non Continuous Memory access</figcaption></figure><h4>Kernel 3 : Global Memory Coalescing</h4><p>We fixed <em>how often</em> we write to memory, but we haven’t fixed <em>how</em> we read from it. To understand the next massive flaw, we need to look at how GPUs actually execute threads.</p><p>A GPU does not run threads completely independently. It groups them into physical batches officially called <strong>Sub-groups</strong> in OpenCL, though you will almost always hear them referred to by their hardware-specific names: <strong>Warps</strong> (32 threads) on NVIDIA, or <strong>Wavefronts</strong> (32 to 64 threads) on AMD. All the threads inside this sub-group execute the exact same instruction at the exact same time.</p><p>In our previous kernels, we mapped our thread IDs like this:</p><pre>const int row = get_global_id(0);<br>const int col = get_global_id(1);</pre><p>In OpenCL, get_global_id(0) is the fastest-moving dimension. This means threads inside the same sub-group have contiguous id(0) values. So, Thread 0 handles row 0, Thread 1 handles row 1, Thread 2 handles row 2, and so on. They all share the same col.</p><p>Now look at how we fetch from Matrix A: A[row * K + i]</p><p>Because Matrix A is flattened into a 1D array in row-major order, Thread 0 requests index 0. Thread 1 requests index K (which is 1024). Thread 2 requests index 2048. The memory controller panics. Instead of scooping up a single contiguous chunk of memory, it has to issue 32 separate, scattered memory transactions across the VRAM to serve a single sub-group. This is known as a <strong>strided memory access</strong>, and it completely destroys memory bandwidth.</p><p>The fix is literally swapping two numbers. We map get_global_id(0) to the col instead of the row.</p><pre>__kernel void GlobalCoalescing_MatMul(__global const float* A, __global const float* B, __global float* C, int M, int N, int K) {<br>    // Mapping ID(0) to Column for coalesced memory access<br>    const int col = get_global_id(0); <br>    const int row = get_global_id(1);<br><br>    if (row &lt; M &amp;&amp; col &lt; N) {<br>        float sum = 0.0f;<br>        for (int i = 0; i &lt; K; i++) {<br>            // A[row * K + i]: Row-based access (stays same for all &#39;col&#39; in a subgroup)<br>            // B[i * N + col]: Column-based access (contiguous for adjacent &#39;col&#39;)<br>            sum += A[row * K + i] * B[i * N + col];<br>        }<br>        // Write once to global memory<br>        C[row * N + col] = sum;<br>    }<br>}</pre><p>Now, Thread 0 wants B[0], Thread 1 wants B[1], and Thread 2 wants B[2]. They are sitting right next to each other in physical RAM. The GPU can grab all the floats for the entire sub-group in a single, massive memory fetch. This is called <strong>Memory Coalescing</strong>.</p><ul><li><strong>AMD iGPU:</strong> 125.74 GFLOPS (9.8× faster than base)</li><li><strong>NVIDIA 3060:</strong> 664.71 GFLOPS (9.7× faster than base)</li></ul><p>By simply aligning our threads with the physical layout of the memory, we achieved an identical ~10x total speedup on both architectures. On the NVIDIA side, we are finally pushing past 600 GFLOPS. But we are still reading from Global Memory inside the K loop. To go faster, we have to stop relying on the L2 cache and explicitly take control of the silicon&#39;s ultra-fast internal memory.</p><h4>Kernel 4: Local / Shared Memory</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*8svij0HPnWnRSWTlSkgIyg.png" /><figcaption>Local Memory Access</figcaption></figure><p>Even with perfect memory coalescing, we are still hitting a physical ceiling. Look at our innermost loop: we are still fetching from A and B (which live in Global Memory) for every single step of K. If multiple threads need the same data, they are all independently crossing the PCIe bus or VRAM controller to get it. This is a massive waste of bandwidth.</p><p>To break through the Memory Wall, we must use <strong>Local Memory</strong> (often called Shared Memory in CUDA or SRAM on the spec sheet). This is a tiny, ultra-fast scratchpad physically baked into the Compute Unit. Instead of each thread fetching data individually, we will have a work-group of threads <em>cooperatively</em> load a block (or “tile”) of Matrix A and Matrix B into SRAM. Once the data is safely in SRAM, the threads can perform all their math at near-zero latency before moving on to load the next tile.</p><pre>#define MAX_TILE 16<br>__kernel void SharedMem_MatMul(__global const float* A, __global const float* B, __global float* C, int M, int N, int K) {<br>    const int col = get_global_id(0);<br>    const int row = get_global_id(1);<br>    // Local ID: The thread&#39;s position inside its specific work-group<br>    int col_local = get_local_id(0);<br>    int row_local = get_local_id(1);<br>    // Allocate ultra-fast SRAM for the tiles<br>    __local float TileA[MAX_TILE][MAX_TILE];<br>    __local float TileB[MAX_TILE][MAX_TILE];<br>    float sum = 0.0f;<br>    const int numTiles = (K + MAX_TILE - 1) / MAX_TILE;<br>    <br>    // Slide the tiles across the K dimension<br>    for (int t = 0; t &lt; numTiles; t++) {<br>        <br>        // 1. Cooperative Load: Each thread loads exactly ONE element into SRAM<br>        if (row &lt; M &amp;&amp; (t * MAX_TILE + col_local) &lt; K) {<br>            TileA[row_local][col_local] = A[row * K + (t * MAX_TILE + col_local)];<br>        } else {<br>            TileA[row_local][col_local] = 0.0f;<br>        }<br>        if (col &lt; N &amp;&amp; (t * MAX_TILE + row_local) &lt; K) {<br>            TileB[row_local][col_local] = B[(t * MAX_TILE + row_local) * N + col];<br>        } else {<br>            TileB[row_local][col_local] = 0.0f;<br>        }<br>        // 2. Synchronize: STOP! Wait for all threads to finish loading the tile<br>        barrier(CLK_LOCAL_MEM_FENCE);<br>        // 3. Compute: Multiply the tiles currently in local memory (Lightning Fast)<br>        for (int i = 0; i &lt; MAX_TILE; i++) {<br>            sum += TileA[row_local][i] * TileB[i][col_local];<br>        }<br>        // 4. Synchronize: STOP! Wait for all threads to finish math before overwriting the tile<br>        barrier(CLK_LOCAL_MEM_FENCE);<br>    }<br>    // 5. Write final accumulated result to Global Memory<br>    if (row &lt; M &amp;&amp; col &lt; N) {<br>        C[row * N + col] = sum;<br>    }<br>}</pre><p>The magic here is the barrier(CLK_LOCAL_MEM_FENCE). A work-group is a team. Thread 0 cannot start doing math until Thread 255 has finished loading its piece of the tile into SRAM. The barrier forces the hardware to pause the fast threads until the slow memory fetches complete. Once the barrier drops, the entire work-group rips through the math loop using the hyper-fast SRAM, completely ignoring Global Memory.</p><ul><li><strong>AMD iGPU:</strong> 227.61 GFLOPS (17.8× faster than base)</li><li><strong>NVIDIA 3060:</strong> 840.21 GFLOPS (12.3× faster than base)</li></ul><p>The results are explosive. We have nearly doubled our performance again. On the NVIDIA RTX 3060, we are now pushing <strong>840 GFLOPS</strong>.</p><p>However, look closely at how we are loading the tiles. We are loading both Tile A and Tile B into SRAM. Do we actually need to do that? In the next stage, we will question if we are wasting precious synchronization time by caching things that don’t need to be cached.</p><h4>Kernel 5: Shared Memory (Tile B Only)</h4><p>In the previous step, we forced the work-group to cooperatively load both Tile A and Tile B into SRAM. We hit a massive speedup, but we also introduced two barrier() synchronization points. Synchronization is expensive it forces the fastest threads to wait for the slowest threads.</p><p>Do we actually need to cache <em>both</em> tiles? Let’s look at the math and how the threads are executing it. Because we mapped get_global_id(0) to the columns and get_global_id(1) to the rows, all 32 threads inside a single subgroup are calculating adjacent elements on the <em>same row</em> of the output matrix. This means during the inner K loop, <strong>all 32 threads are requesting the exact same value from Matrix A at the exact same time.</strong> Modern GPUs are smart enough to handle this. When 32 threads ask for the exact same memory address, the L1 cache executes a <strong>hardware broadcast</strong>. It fetches the value from VRAM once and instantly hands it to all 32 threads. We don&#39;t need to manually cache Matrix A in SRAM; the hardware is already doing it for us for free. Matrix B, however, is being accessed column-by-column across the threads, which still requires the SRAM tile to avoid VRAM thrashing. This asymmetric memory access pattern is actually the fundamental reality of running Large Language Models.</p><p>At Inference, Matrix B represents the <strong>model weights</strong>. They are massive, completely static, and must be reused for every single token you generate. Matrix A represents the <strong>user prompt/activations</strong> (the batch size). It is small, dynamic, and changes every step. You <em>must</em> tile and cache the static weights (Matrix B) to survive the memory wall, but the activations (Matrix A) can simply stream directly through the registers via broadcast.</p><pre>#define TS 16 // Tile Size (16x16 = 256 threads)<br>__kernel void SharedMem_MatMul(__global const float* A, __global const float* B, __global float* C, int M, int N, int K) {<br>    // Global position in C<br>    const int col = get_global_id(0);<br>    const int row = get_global_id(1);<br><br>    // Local position within the work-group<br>    const int local_col = get_local_id(0);<br>    const int local_row = get_local_id(1);<br><br>    // Only Tile B is stored in SRAM<br>    __local float TileB[TS][TS];<br><br>    float sum = 0.0f;<br><br>    // Loop over tiles of K<br>    const int numTiles = K / TS;<br>    for (int t = 0; t &lt; numTiles; t++) {<br><br>        // 1. Cooperative Load: Only load Matrix B into Local Memory<br>        // Every thread loads one element of B<br>        int b_row = t * TS + local_row;<br>        int b_col = col; // Same as global col<br>        <br>        if (b_row &lt; K &amp;&amp; b_col &lt; N) {<br>            TileB[local_row][local_col] = B[b_row * N + b_col];<br>        } else {<br>            TileB[local_row][local_col] = 0.0f;<br>        }<br><br>        // 2. Sync: Wait for Tile B to be fully loaded<br>        barrier(CLK_LOCAL_MEM_FENCE);<br><br>        // 3. Compute: Fetch A from Global Mem, B from Local Mem<br>        // All threads in a work-group row will access the same A element (Broadcast)<br>        for (int k = 0; k &lt; TS; k++) {<br>            float valA = A[row * K + (t * TS + k)];<br>            float valB = TileB[k][local_col];<br>            sum += valA * valB;<br>        }<br><br>        // 4. Sync: Ensure calculation is done before loading the next tile of B<br>        barrier(CLK_LOCAL_MEM_FENCE);<br>    }<br><br>    // Write final result<br>    if (row &lt; M &amp;&amp; col &lt; N) {<br>        C[row * N + col] = sum;<br>    }<br>}</pre><ul><li><strong>AMD iGPU:</strong> 293.82 GFLOPS (23.1× faster than base) (1.29× faster than Kernel 4)</li><li><strong>NVIDIA 3060:</strong> 576.62 GFLOPS (8.5× faster than base) (0.69× speed of Kernel 4)</li></ul><p>Look at those results. We just hit our first massive hardware divergence. By deleting code and reducing SRAM usage, the <strong>AMD iGPU</strong> got nearly 30% faster. It loved the reduced barrier synchronization and the freed-up Local Memory. The <strong>NVIDIA RTX 3060</strong>, however, completely collapsed, losing over 260 GFLOPS of performance. Why? Because NVIDIA’s architecture is highly tuned for heavy Shared Memory utilization. By forcing the RTX 3060 to rely on the L1 cache broadcast for Matrix A instead of explicit SRAM, we introduced a latency bottleneck that choked the Tensor/CUDA cores.</p><blockquote>What is “optimized” for one chip is a foot-gun for the other.</blockquote><h4>Kernel 6: 1D Block-Tiling (Work Per Thread)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Huv48dlY_iVTdNbhShFXTQ.png" /></figure><p>Up until now, our rule has been <strong>1 Thread = 1 Output Element</strong>. We’ve optimized <em>where</em> that thread gets its data by using SRAM, but we haven’t fundamentally changed the amount of work the thread is actually doing.</p><p>To break the 1 Teraflop barrier, we need to increase our <strong>Arithmetic Intensity</strong> the ratio of math operations to memory fetches. Right now, a thread fetches a value from A, fetches a value from B, and does one multiply-add. That is a 1:1 ratio.</p><p>What if we make one thread compute <strong>4 output elements</strong> instead of 1?</p><p>This technique is called <strong>Thread Coarsening</strong> or increasing the Work-Per-Thread (WPT). As the diagram illustrates, a single thread is now responsible for a 1x4 horizontal row in Matrix C. To compute this, it fetches a <em>single</em> scalar value from Matrix A, keeps it hot in a hardware register, and multiplies it against a 1x4 horizontal row from Matrix B. By reusing that single value from A four times, we just quadrupled our arithmetic intensity.</p><pre>#define TS 16  // Tile Size<br>#define WPT 4  // Work Per Thread <br>__kernel void BlockTile1D_MatMul(__global const float* A, __global const float* B, __global float* C, int M, int N, int K) {<br>    <br>    // row is standard, but col identifies the START of our 4-column block<br>    const int row = get_global_id(1);<br>    const int local_row = get_local_id(1);<br>    const int local_col = get_local_id(0);<br>    <br>    // Which block of 4 columns is this work-group handling?<br>    const int group_col_start = get_group_id(0) * TS * WPT;<br>    <br>    // SRAM for Matrix B (Needs to be wider to hold 4 tiles worth of columns)<br>    __local float TileB[TS][TS * WPT];<br>    <br>    // Hardware Registers (Private Memory) to hold our 4 independent results<br>    float sum[WPT];<br>    for (int w = 0; w &lt; WPT; w++) {<br>        sum[w] = 0.0f;<br>    }<br>    for (int t = 0; t &lt; (K / TS); t++) {<br>        // 1. COOPERATIVE LOAD: Pull 4 elements of B into SRAM<br>        for (int w = 0; w &lt; WPT; w++) {<br>            int tiled_col = local_col + (w * TS);<br>            int global_col = group_col_start + tiled_col;<br>            TileB[local_row][tiled_col] = B[(t * TS + local_row) * N + global_col];<br>        }<br>        barrier(CLK_LOCAL_MEM_FENCE);<br>        // 2. COMPUTE: Maximize Register Reuse<br>        for (int k = 0; k &lt; TS; k++) {<br>            // Fetch A exactly ONCE from Global Memory (Broadcast to row)<br>            float valA = A[row * K + (t * TS + k)];<br>            // Use that ONE value of A to do FOUR math operations<br>            for (int w = 0; w &lt; WPT; w++) {<br>                sum[w] += valA * TileB[k][local_col + (w * TS)];<br>            }<br>        }<br>        barrier(CLK_LOCAL_MEM_FENCE);<br>    }<br>    // 3. STORE: Write the 4 results back to Global Memory<br>    for (int w = 0; w &lt; WPT; w++) {<br>        int global_col = group_col_start + local_col + (w * TS);<br>        if (row &lt; M &amp;&amp; global_col &lt; N) {<br>            C[row * N + global_col] = sum[w];<br>        }<br>    }<br>}</pre><ul><li><strong>AMD iGPU:</strong> 340.87 GFLOPS (26.7× faster than base)</li><li><strong>NVIDIA 3060:</strong> 927.94 GFLOPS (13.6× faster than base)</li></ul><p>By giving each thread 4 registers to accumulate math, we have massively reduced the memory bottleneck. The AMD iGPU saw a solid 15% boost, easily crossing the 300 GFLOPS mark. But look at the NVIDIA RTX 3060. In the previous step, stripping out SRAM caching for Matrix A crashed the NVIDIA chip down to 586 GFLOPS. By implementing 1D Block Tiling, the RTX 3060 came roaring back, rocketing to <strong>927 GFLOPS</strong> a massive 58% jump. By maximizing register reuse, we finally fed the NVIDIA math cores the data they were starving for. But a 1x4 horizontal row is just the beginning. If 1D tiling works this well, what happens if we tile in 2D?</p><h4>Kernel 7: 2D Block-Tiling (Work Per Thread)</h4><p>In the previous step, we had each thread compute a 1x4 horizontal row. By fetching a single value from Matrix A and reusing it 4 times against Matrix B, we increased our arithmetic intensity. But why stop at a 1D row? What if we make each thread compute a <strong>2D grid</strong> of outputs?</p><p>Let’s look at the math of <strong>Register Reuse</strong> (Arithmetic Intensity):</p><p><strong>Naive:</strong> Load 1 from A, Load 1 from B -&gt; 1 Math Operation. (Ratio: 0.5 ops per load)</p><p><strong>1D Block (1x4):</strong> Load 1 from A, Load 4 from B -&gt; 4 Math Operations. (Ratio: 0.8 ops per load)</p><p><strong>2D Block (4x4):</strong> Load 4 from A, Load 4 from B -&gt; 16 Math Operations. (Ratio: 2.0 ops per load)</p><p>By moving to a 4x4 grid per thread, we only double our memory fetches (from 4 to 8), but we <strong>quadruple</strong> our math operations (from 4 to 16). We are finally doing significantly more math than memory movement. Because each thread in our 16x16 work-group is now computing a 4x4 block, the work-group as a whole is conquering a massive 64x64 block of Matrix C. To feed this beast, we have to expand our SRAM allocation. We now cooperatively load a 64x16 tile of A and a 16x64 tile of B.</p><pre>#define TS 16   // The dimension we split K by (Tile Size)<br>#define WPT 4    // Work Per Thread (Each thread handles a 4x4 output grid)<br>__kernel void BlockTile2D_MatMul(__global const float* A, __global const float* B, __global float* C, int M, int N, int K) {<br>    <br>    const int local_col = get_local_id(0); // 0 to 15<br>    const int local_row = get_local_id(1); // 0 to 15<br>    <br>    // Each work-group handles a massive 64x64 block of C<br>    const int group_row = get_group_id(1) * TS * WPT;<br>    const int group_col = get_group_id(0) * TS * WPT;<br>    <br>    // Registers for the 4x4 tray (16 private floats total)<br>    float sum[WPT][WPT];<br>    for(int r=0; r&lt;WPT; r++) <br>        for(int c=0; c&lt;WPT; c++) <br>            sum[r][c] = 0.0f;<br>    <br>    // Expanded SRAM Tiles to feed the 64x64 work-group requirement<br>    __local float TileA[TS * WPT][TS]; // 64 x 16<br>    __local float TileB[TS][TS * WPT]; // 16 x 64<br>    for (int t = 0; t &lt; (K / TS); t++) {<br>        <br>        // 1. Cooperative Load: Fill the larger SRAM Tiles<br>        for (int w = 0; w &lt; WPT; w++) {<br>            // Load A: Row is spread across WPT, Column is the K-tile<br>            int a_row = group_row + local_row + (w * TS);<br>            int a_col = t * TS + local_col;<br>            TileA[local_row + (w * TS)][local_col] = A[a_row * K + a_col];<br>            // Load B: Row is the K-tile, Column is spread across WPT<br>            int b_row = t * TS + local_row;<br>            int b_col = group_col + local_col + (w * TS);<br>            TileB[local_row][local_col + (w * TS)] = B[b_row * N + b_col];<br>        }<br>        <br>        barrier(CLK_LOCAL_MEM_FENCE);<br>        // 2. Compute 4x4 Block (Maximum Register Reuse)<br>        for (int k = 0; k &lt; TS; k++) {<br>            <br>            // Pre-load a row of B values into registers for this specific k-step<br>            float b_vals[WPT];<br>            for (int c = 0; c &lt; WPT; c++) {<br>                b_vals[c] = TileB[k][local_col + (c * TS)];<br>            }<br>            // Multiply against the column of A values<br>            for (int r = 0; r &lt; WPT; r++) {<br>                float a_val = TileA[local_row + (r * TS)][k];<br>                for (int c = 0; c &lt; WPT; c++) {<br>                    sum[r][c] += a_val * b_vals[c];<br>                }<br>            }<br>        }<br>        barrier(CLK_LOCAL_MEM_FENCE);<br>    }<br>    // 3. Write all 16 results back to Global Memory C<br>    for (int r = 0; r &lt; WPT; r++) {<br>        for (int c = 0; c &lt; WPT; c++) {<br>            int cur_r = group_row + local_row + (r * TS);<br>            int cur_c = group_col + local_col + (c * TS);<br>            if (cur_r &lt; M &amp;&amp; cur_c &lt; N) {<br>                C[cur_r * N + cur_c] = sum[r][c];<br>            }<br>        }<br>    }<br>}</pre><ul><li><strong>AMD iGPU:</strong> 680.64 GFLOPS (53.4× faster than base)</li><li><strong>NVIDIA 3060:</strong> 2182.26 GFLOPS (32.1× faster than base)</li></ul><p>By upgrading from a 1D row to a 2D grid of registers, performance literally exploded on both architectures. We strictly doubled the performance of the AMD iGPU, pushing it to an incredible <strong>680 GFLOPS</strong> on integrated silicon.</p><p>But the NVIDIA RTX 3060 is where the sheer violence of memory optimization shows itself. It didn’t just break the 1 Teraflop barrier; it completely bypassed it, rocketing to <strong>2.18 Teraflops</strong>. We are now running <strong>32 times faster</strong> than our original code.</p><p>By holding 16 values in ultra-fast hardware registers and reusing them ruthlessly, we have almost entirely eliminated the memory bottleneck. The ALUs (math cores) are finally spending the majority of their clock cycles doing actual math instead of waiting for data. But we aren’t done. The math is incredibly fast now, but how we load data <em>into</em> the registers is slightly sloppy. Next, we will use explicit <strong>Vector Instructions</strong> to force the hardware to load data in larger, chunkier blocks.</p><h4>Kernel 8: Vectorization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*KpeIo8lscc317uc8xotAhg.png" /></figure><p>We have optimized our memory access patterns and maximized our register reuse. But there is still one subtle inefficiency in how we are talking to the hardware. Currently, when we ask the memory controller for data, we are asking for a standard float (32 bits). But modern GPU memory buses are incredibly wide often 128-bit, 256-bit, or even 384-bit. Asking a 128-bit memory controller to fetch a 32-bit float is like sending a massive dump truck to pick up a single brick.</p><p>We can force the hardware to utilize its full bus width by using explicit <strong>Vector Data Types</strong>. Instead of loading four separate 32-bit floats, we use vload4 to grab a single 128-bit float4 chunk in one massive memory transaction.</p><p>Not only does this optimize the memory bus, but it also allows the ALU (math cores) to use SIMD (Single Instruction, Multiple Data) instructions. The math operation sum += a * b_vec calculates 4 multiply-adds simultaneously at the hardware level.</p><pre>#define TS 16   // Tile Size for K<br>#define WPT 4    // Each thread handles 4x4 block<br>__kernel void BlockTile2D_Vload_MatMul(__global const float* A, __global const float* B, __global float* C,  int M, int N, int K) {<br>    <br>    const int tx = get_local_id(0); // 0-15<br>    const int ty = get_local_id(1); // 0-15<br>    <br>    // Each group handles a 64x64 block of C<br>    const int group_row = get_group_id(1) * 64;<br>    const int group_col = get_group_id(0) * 64;<br>    <br>    // Registers: Array of float4 (16 floats total, packed into 4 vector registers)<br>    float4 sum[WPT];<br>    <br>    for(int i=0; i&lt;WPT; i++) sum[i] = (float4)(0.0f);<br>    __local float TileA[64][16];<br>    __local float TileB[16][64];<br>    <br>    for (int t = 0; t &lt; K; t += TS) {<br>        // 1. Cooperative Load<br>        for (int i = 0; i &lt; WPT; i++) {<br>            // Load A: Standard scalar load<br>            int a_row = group_row + ty + i * TS;<br>            int a_col = t + tx;<br>            TileA[ty + i * TS][tx] = A[a_row * K + a_col];<br>            // Load B: Use vload4 to fetch 128 bits (4 floats) at once!<br>            int b_row = t + ty;<br>            int b_col_vec = (group_col + tx * 4) / 4;<br>            vstore4(vload4(b_col_vec, &amp;B[b_row * N]), tx, &amp;TileB[ty][0]);<br>        }<br>        <br>        barrier(CLK_LOCAL_MEM_FENCE);<br>        // 2. Compute 4x4 block<br>        for (int k = 0; k &lt; TS; k++) {<br>            // Read 4 columns from SRAM instantly as a float4<br>            float4 b_vec = vload4(tx, &amp;TileB[k][0]);<br>            for (int r = 0; r &lt; WPT; r++) {<br>                float a_val = TileA[ty * WPT + r][k];<br>                // SIMD Math: Multiply a scalar by a float4 vector in one instruction<br>                sum[r] += (float4)(a_val) * b_vec;<br>            }<br>        }<br>        barrier(CLK_LOCAL_MEM_FENCE);<br>    }<br>    // 3. Vectorized Write back to Global Memory<br>    for (int r = 0; r &lt; WPT; r++) {<br>        int cur_r = group_row + ty * WPT + r;<br>        int cur_c_vec = (group_col + tx * 4) / 4;<br>        if (cur_r &lt; M &amp;&amp; (group_col + tx * 4) &lt; N) {<br>            vstore4(sum[r], cur_c_vec, &amp;C[cur_r * N]);<br>        }<br>    }<br>}</pre><ul><li><strong>AMD iGPU:</strong> 746.32 GFLOPS (58.6× faster than base)</li><li><strong>NVIDIA 3060:</strong> 2291.97 GFLOPS (33.7× faster than base)</li></ul><p>Vectorization gave us a final 5–9% performance polish. Why wasn’t it a massive 4x multiplier? Because at this stage, we have already eliminated the major memory bottlenecks. We are heavily compute-bound.</p><p>However, forcing 128-bit memory transactions safely squeezed out the last remaining drops of bandwidth efficiency, pushing the NVIDIA RTX 3060 to <strong>2.29 Teraflops</strong> and the AMD chip to nearly <strong>750 GFLOPS</strong>.</p><h4>Kernel 9: Sub-group Tiling (Warp Tiling)</h4><p>Up until now, we had two levels:</p><ol><li><strong>Work-group (Block):</strong> Loads a big chunk of data from Global Memory into SRAM</li><li><strong>Thread:</strong> Grabs a few values from SRAM and computes a small piece of the result.</li></ol><p>This works, but it ignores how the hardware actually groups threads. The GPU executes threads in batches of 32 (Sub-group). If we don’t explicitly organize how this <em>batch</em> shares data, we waste time re-reading the same values from SRAM into registers. We need a middle layer.</p><ol><li><strong>Work-group (Block):</strong> Loads a massive 64x128 chunk from Global Memory into SRAM.</li><li><strong>Sub-group :</strong> Claims a specific sub-section of that SRAM data to hold in the registers for its 32 threads.</li><li><strong>Thread:</strong> Computes an 8x8 grid within its Subgroup’s territory.</li></ol><p>To do this efficiently, we have to <strong>decouple loading from computing</strong>. During the load phase, we don’t care about the 2D grid. We treat all 128 threads in the work-group as a flat, 1D assembly line (const int tid = ty * RTS + tx). They scoop up data from VRAM in perfectly straight lines. Once the SRAM is full, they snap back into their 2D grid formation to do the math.</p><pre>#define TS 16       // Tile size for K-dimension<br>#define WPT 8       // Work Per Thread (Each thread handles an 8x8 block)<br>#define RTS 16      // Row Tile Size (Threads in X)<br>#define CTS 8       // Column Tile Size (Threads in Y)<br><br>__kernel void SubgroupTile_MatMul(__global const float* A, __global const float* B, __global float* C, int M, int N, int K) {<br>    const int tx = get_local_id(0); // 0..15<br>    const int ty = get_local_id(1); // 0..7<br>    <br>    // The Work-group handles a massive 64x128 block of Matrix C<br>    const int group_row = get_group_id(1) * 64;<br>    const int group_col = get_group_id(0) * 128;<br><br>    // REGISTER CACHING: 64 private floats per thread!<br>    float sum[WPT][WPT];<br>    for(int r=0; r&lt;WPT; r++) {<br>        for(int c=0; c&lt;WPT; c++) sum[r][c] = 0.0f;<br>    }<br><br>    // LOCAL MEMORY (SRAM)<br>    __local float TileA[64][TS];  <br>    __local float TileB[TS][128]; <br><br>    // THE DECOUPLING: A flat thread ID (0 to 127) for cooperative memory loading<br>    const int tid = ty * RTS + tx; <br><br>    for (int t = 0; t &lt; K; t += TS) {<br><br>        // 1. COOPERATIVE LOAD (Using the flat 1D assembly line)<br>        for(int i = 0; i &lt; 8; i++) {<br>            int idx = i * 128 + tid; // Perfectly sequential access<br>            int rowA = idx / TS;<br>            int colA = idx % TS;<br>            TileA[rowA][colA] = A[(group_row + rowA) * K + (t + colA)];<br>        }<br><br>        for(int i = 0; i &lt; 16; i++) {<br>            int idx = i * 128 + tid; // Perfectly sequential access<br>            int rowB = idx / 128;<br>            int colB = idx % 128;<br>            TileB[rowB][colB] = B[(t + rowB) * N + (group_col + colB)];<br>        }<br><br>        barrier(CLK_LOCAL_MEM_FENCE);<br><br>        // 2. COMPUTE: Snap back to the 2D grid and utilize Subgroup-level locality<br>        for (int k = 0; k &lt; TS; k++) {<br>            <br>            // Load a chunk from SRAM into Registers<br>            float regB[WPT];<br>            for (int c = 0; c &lt; WPT; c++) {<br>                regB[c] = TileB[k][tx + (c * RTS)];<br>            }<br><br>            // Compute using purely register-to-register math<br>            for (int r = 0; r &lt; WPT; r++) {<br>                float regA = TileA[ty + (r * CTS)][k];<br>                for (int c = 0; c &lt; WPT; c++) {<br>                    sum[r][c] += regA * regB[c];<br>                }<br>            }<br>        }<br>        barrier(CLK_LOCAL_MEM_FENCE);<br>    }<br><br>    // 3. STORE (Write the 8x8 grid back to Global Memory)<br>    for (int r = 0; r &lt; WPT; r++) {<br>        for (int c = 0; c &lt; WPT; c++) {<br>            int cur_r = group_row + ty + (r * CTS);<br>            int cur_c = group_col + tx + (c * RTS);<br>            if (cur_r &lt; M &amp;&amp; cur_c &lt; N) {<br>                C[cur_r * N + cur_c] = sum[r][c];<br>            }<br>        }<br>    }<br>}</pre><ul><li><strong>AMD iGPU:</strong> 326.36 GFLOPS (25.6× faster than base)</li><li><strong>NVIDIA 3060:</strong> 3382.50 GFLOPS (49.8× faster than base)</li></ul><p>For the <strong>NVIDIA RTX 3060</strong>, this was the holy grail. By introducing a subgroup-level hierarchy and moving to an 8x8 compute block, we hit an astonishing <strong>3.38 Teraflops</strong>. We are finally feeding the 3060’s math pipelines fast enough to unlock serious hardware utilization, capturing a massive chunk of its raw compute power. <strong>The code takes a mere 0.63 milliseconds to complete over 2 billion operations.</strong></p><p>For the <strong>AMD iGPU</strong>, this kernel was an absolute disaster. Performance degraded by more than 50% compared to our previous version, dropping back down to 326 GFLOPS.</p><p>Why did the AMD chip fail so spectacularly? <strong>Register Pressure.</strong> Look at the top of the kernel: float sum[WPT][WPT]. Because WPT is 8, we are demanding <strong>64 hardware registers per thread</strong> just to hold the accumulator matrix, plus additional registers for regA, regB, loop counters, and indices. The NVIDIA architecture has massive register files designed specifically to handle this kind of heavy subgroup-level caching. The AMD integrated graphics architecture simply does not have enough physical registers per compute unit to support this. When a GPU runs out of physical registers, it silently starts dumping those variables into Global Memory (VRAM) to make room. This is called <strong>Register Spilling</strong>. It completely undermines our optimization, pushing our ultra-fast register math back out into the slow VRAM we fought so hard to escape.</p><h4>Kernel 10 : Vectorized Subgroup Tiling</h4><pre>#define TS 16       // Tile size for K-dimension<br>#define WPT_M 8     // 8 rows per thread<br>#define WPT_N 2     // 2 float4s (8 columns) per thread<br><br>__kernel void Vectorized_SubgroupTiling(__global const float* A, <br>                                      __global const float* B, <br>                                      __global float* C, <br>                                      int M, int N, int K) {<br>    <br>    // 16x16 threads = 256 threads per group<br>    const int tx = get_local_id(0); // 0..15<br>    const int ty = get_local_id(1); // 0..15<br>    <br>    // Group handles a 128x128 block of the output matrix C<br>    const int group_row = get_group_id(1) * 128;<br>    const int group_col = get_group_id(0) * 128; <br><br>    // REGISTER CACHING using vectors (8x2 float4s = 8x8 floats)<br>    float4 sum[WPT_M][WPT_N];<br>    for(int i = 0; i &lt; WPT_M; i++) {<br>        for(int j = 0; j &lt; WPT_N; j++) {<br>            sum[i][j] = (float4)(0.0f);<br>        }<br>    }<br><br>    // LOCAL MEMORY<br>    __local float TileA[128][16];<br>    __local float TileB[16][128];<br><br>    for (int t = 0; t &lt; K; t += TS) {<br><br>        // 1. COOPERATIVE LOAD WITHOUT MODULO<br>        // Tile A: 128x16. 256 threads load 8 elements each.<br>        // tx (0-15) cleanly maps to the 16 columns. ty handles the rows.<br>        for (int i = 0; i &lt; 8; i++) {<br>            int a_row = group_row + ty + (i * 16);<br>            int a_col = t + tx;<br>            TileA[ty + (i * 16)][tx] = A[a_row * K + a_col];<br>        }<br><br>        // Tile B: 16x128. 256 threads load 8 elements (2 float4s) each.<br>        // ty (0-15) cleanly maps to the 16 rows. tx handles the columns.<br>        for (int i = 0; i &lt; 2; i++) {<br>            int b_row = t + ty;<br>            // Vectorized global offset<br>            int b_col_vec = (group_col / 4) + tx + (i * 16);<br>            // Vectorized local offset<br>            int local_col_vec = tx + (i * 16);<br>            <br>            vstore4(vload4(b_col_vec, &amp;B[b_row * N]), local_col_vec, &amp;TileB[ty][0]);<br>        }<br><br>        barrier(CLK_LOCAL_MEM_FENCE);<br><br>        // 2. COMPUTE<br>        for (int k = 0; k &lt; TS; k++) {<br>            <br>            // Pre-load a row of TileB into registers (vectorized)<br>            float4 b_vec[WPT_N];<br>            for (int j = 0; j &lt; WPT_N; j++) {<br>                b_vec[j] = vload4(tx + (j * 16), &amp;TileB[k][0]);<br>            }<br><br>            // Multiply against TileA (Broadcast from Shared Memory)<br>            for (int i = 0; i &lt; WPT_M; i++) {<br>                float a_val = TileA[ty + (i * 16)][k];<br>                float4 a_vec = (float4)(a_val); // Broadcast scalar to vector<br>                <br>                for (int j = 0; j &lt; WPT_N; j++) {<br>                    sum[i][j] += a_vec * b_vec[j];<br>                }<br>            }<br>        }<br>        barrier(CLK_LOCAL_MEM_FENCE);<br>    }<br><br>    // 3. STORE (Vectorized)<br>    for (int i = 0; i &lt; WPT_M; i++) {<br>        for (int j = 0; j &lt; WPT_N; j++) {<br>            int cur_r = group_row + ty + (i * 16);<br>            int cur_c_vec = (group_col / 4) + tx + (j * 16);<br>            <br>            if (cur_r &lt; M) {<br>                vstore4(sum[i][j], cur_c_vec, &amp;C[cur_r * N]);<br>            }<br>        }<br>    }<br>}</pre><p>In Kernel 9, we achieved our best on the NVIDIA RTX 3060 (3.38 TFLOPS) by using an 8x8 warp-tiled compute block. But doing so completely destroyed the AMD iGPU, dropping it to 326 GFLOPS due to massive <strong>Register Spilling</strong>. The AMD compiler could not efficiently map our 64 independent scalar sum variables to its physical register files, so it panicked and dumped them into VRAM.</p><p>To save the AMD chip, we need to combine the Sub-group hierarchy from Kernel 9 with the 128-bit Vectorization from Kernel 8.</p><p>Instead of asking the compiler to manage 64 independent float registers, we explicitly pack them into a 2D array of 128-bit vectors: float4 sum[8][2]. This still holds 64 floats (8 rows x 2 vectors x 4 floats), but it explicitly maps them to hardware vector registers.</p><p>Furthermore, we optimize the <strong>Cooperative Load</strong> phase. In Kernel 9, we used a flat 1D thread ID and modulo arithmetic (%) to figure out which thread loads which cell. Modulo math is surprisingly expensive on ALUs. By cleverly sizing our work-group and tiles, we can map tx and ty directly to the columns and rows of our SRAM tiles, eliminating the math overhead and fetching memory purely via vload4.</p><ul><li><strong>AMD iGPU:</strong> 917.95 GFLOPS (72.1× faster than base)</li><li><strong>NVIDIA 3060:</strong> 3236.35 GFLOPS (47.6× faster than base)</li></ul><p>By explicitly packaging our variables into 128-bit float4 vectors, the AMD compiler finally understood our intent. It stopped spilling to VRAM, locked everything into hardware registers, and rocketed from 326 GFLOPS to an incredible <strong>917.95 GFLOPS</strong>. We squeezed nearly a Teraflop out of a laptop&#39;s integrated graphics chip.</p><p>But what about the NVIDIA RTX 3060? Performance actually <em>dropped</em> by about 4%, falling from 3.38 TFLOPS down to 3.23 TFLOPS. Why? Because the NVIDIA driver compiler is notoriously aggressive. In Kernel 9, when we gave it raw scalar float arrays, the NVIDIA compiler used its own proprietary heuristics to unroll the loops, schedule the warps, and maximize Tensor Core or ALU utilization perfectly. By forcing strict OpenCL float4 vector boundaries and rigid 256-thread grids upon it, we essentially got in its way, adding a tiny bit of instruction overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAAlIDPbNMobCzvEaFQojg.png" /></figure><h3>Conclusion</h3><p>I originally undertook this study to learn GEMM (General Matrix Multiplication) optimization from the ground up, specifically to understand the foundational mechanics that drive Large Language Model (LLM) Inference Optimization.</p><p>The ultimate takeaway from this journey is understanding how we can ruthlessly optimize matmuls for pure speed at inference. It proves that the latest, most magical LLMs in the world actually rely on a deep foundation of bare-metal hardware engineering that is much more than what meets the eye. As you can see in the scaling timeline above, pushing these limits also reveals a brutal truth: the exact same code can yield wildly different performance characteristics depending entirely on the physical architecture executing it.</p><p>If you want to run these benchmarks yourself, test them on your own hardware, or dive into the raw C++ host code and OpenCL kernels, everything is open-source and available on my GitHub repository:</p><p>🔗 <a href="https://github.com/SRDdev/OpenCL-LLM"><strong>GitHub — SRDdev/OpenCL-LLM</strong></a></p><p>There are undoubtedly many more optimizations out there that I am still learning. For example, moving away from OpenCL and using hardware-specific APIs like CUDA on NVIDIA can unlock up to 3+ TFLOPS of additional performance using the exact same logic, simply by accessing Tensor Cores and PTX assembly. If you know of other techniques or have spotted ways to push these OpenCL kernels even further, I would love to hear about them in the comments!</p><p><strong>Acknowledgements &amp; Further Reading</strong> Finally, I want to give a massive thank you to the incredible engineers and writers whose blogs, tutorials, and deep dives served as the foundation for my learning. If you want to fall further down the matrix multiplication rabbit hole, I highly recommend checking out these phenomenal resources:</p><ul><li><a href="https://siboehm.com/articles/22/CUDA-MMM"><strong>How to Optimize a CUDA Matmul Kernel for cuBLAS-like Performance: a Worklog</strong></a> by Simon Boehm</li><li><a href="https://www.aleksagordic.com/"><strong>Inside NVIDIA GPUs: Anatomy of high performance matmul kernels</strong></a> by Aleksa Gordić <em>(From GPU architecture and PTX/SASS to warp-tiling and deep asynchronous tensor core pipelines)</em></li><li><a href="https://cudaforfun.substack.com/"><strong>Outperforming cuBLAS on H100: a Worklog</strong></a> by CUDA for Fun</li><li><a href="https://salykova.github.io/"><strong>Advanced Matrix Multiplication Optimization on NVIDIA GPUs</strong></a> by Salykova</li><li><a href="https://leimao.github.io/article/CUDA-Matrix-Multiplication-Optimization"><strong>CUDA Matrix Multiplication Optimization</strong></a> by Lei Mao</li></ul><blockquote>Congratulations on finishing the blog!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=623c1fcc001e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inference Acceleration: The OpenCL Foundation]]></title>
            <link>https://medium.com/@srddev/inference-acceleration-the-opencl-foundation-3b0a3af68243?source=rss-5a5bc853a7b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b0a3af68243</guid>
            <category><![CDATA[opencl]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[inference-optimization]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mls]]></category>
            <dc:creator><![CDATA[Shreyas Dixit]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 06:31:00 GMT</pubDate>
            <atom:updated>2026-02-25T06:31:00.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JzXJtytf36cpy6PASl06_g.png" /></figure><blockquote>“I have been fascinated by the challenge of model optimization moving beyond standard libraries to understand how hardware actually executes math.”</blockquote><p>Most people today will hear kernels and think about “CUDA” and for good reason. If you are training a massive model in a data center, you are almost certainly using Nvidia silicon. CUDA is the undisputed king there, it has an incredible ecosystem, highly polished libraries, and it abstracts away a massive amount of hardware friction. But what happens when we do not want to call APIs to H100s and run the models locally on mobiles, SOCs, or laptops (without Nvidia) ?</p><p>When we move inference to these edge devices, we crash into a fundamental physical limit. <strong>It turns out that for modern Transformers, the main bottleneck isn’t actually the math</strong>. Our chips generally have plenty of raw compute (ALUs) to multiply matrices. The true enemy is the “Memory Wall” the agonizingly slow process of dragging massive tensors, like weights and the KV cache, from the main system RAM (HRAM) into the tiny, high-speed on-chip SRAM where the calculations actually happen. Every round-trip to global memory starves the compute cores and drains power. To make LLMs run efficiently on local hardware, you don’t just need fast arithmetic; you need absolute, granular control over how data is tiled and moved.</p><h3>OpenCL</h3><p>OpenCL is an open standard for writing portable parallel programs that run on many kinds of hardware: CPUs, GPUs, and other accelerators. While CUDA locks you into a single vendor’s ecosystem, OpenCL allows you to run the same program on different vendors’ hardware. It scales from clusters down to the mobile chips in our pockets. Throughout this Inference Acceleration series, I’ll be diving into OpenCL to see exactly how much compute performance I can squeeze out of the device sitting on my desk.</p><h4>Hardware Hierarchy</h4><p>Before we write any code, we need to talk about the physical reality of the chip. When we say we are “optimizing a kernel,” what we are really doing is playing a game of logistics. Hardware is not a single, monolithic bucket of compute; it is a strict hierarchy of memory spaces. Every block of memory has its own size, its own speed, and its own physical location. The further away the data is from the compute cores, the longer it takes to fetch, and the more power it burns.</p><p>OpenCL exposes multiple memory regions with these varying sizes and speeds. Understanding this layout is the entire secret to bypassing the Memory Wall</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mN6kNAif-nweKJ_19lq21g.png" /></figure><ul><li><strong>Host Memory (CPU RAM):</strong> The <strong>4 to 32 GB</strong> starting point for your application that sits across the motherboard. It connects to the GPU via the PCIe bus, making data transfers to the device notoriously slow and expensive.</li><li><strong>Global Memory (HRAM/VRAM):</strong> The primary <strong>0.25 to 12 GB</strong> on-device storage pool that holds your massive model weights and KV cache. It is large but suffers from high latency; frequent thread fetches from here create the computational bottleneck known as the “Memory Wall”.</li><li><strong>Local Memory (SRAM):</strong> A tiny (<strong>16–48 kB</strong>), ultra-fast scratchpad physically located on the Compute Unit and shared among a specific group of threads (work-group). Optimized kernels like Flash Attention load small “tiles” of data here to do the math, effectively bypassing the global memory wall.</li><li><strong>Private Memory (Registers):</strong> The absolute fastest memory on the chip, dedicated exclusively to a single thread or work-item. This is the raw hardware register level where the actual matrix multiplication arithmetic physically executes.</li></ul><p>The simple idea is keep the data which may be required for different computations on the SRAM for as much time as you can and hence reduce the number of read and writes to the Host Memory or even Global Memory.</p><h4>OpenCL Hierarchy</h4><p>Now that we have understood the physical memory layout, we need to talk about another hierarchy: the software architecture. To write OpenCL code, you can’t just throw C++ at the GPU. You have to navigate a specific API structure that bridges your host application and the raw silicon. Just like the hardware has a strict hierarchy, OpenCL organizes its software into a logical chain of command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9O-e0OcNeYC31wpleaPatA.png" /></figure><h4>Platform</h4><p>A platform represents a vendor’s OpenCL implementation installed on the system (for example, Intel, AMD, or NVIDIA).<br>The host queries platforms first to discover which OpenCL runtimes are available and what types of devices they expose.</p><h4>Device</h4><p>A device is a physical compute target associated with a platform.<br>This can be a CPU, GPU, or a dedicated accelerator.<br>Devices are where kernels actually execute.</p><h4>Context</h4><p>A context is a logical container created by the host.<br>It groups one or more devices together with their associated memory objects and compiled programs.<br>All memory allocations and kernel executions must belong to a context.</p><h4>Command Queue</h4><p>A command queue is the submission interface between the host and a specific device. All operations memory transfers, kernel launches, and synchronization are issued into a command queue and executed in order (or out of order, if explicitly configured).</p><p>This hierarchy defines the control path from the host application down to kernel execution. Once these objects are in place, the runtime has everything it needs to schedule work on the device.</p><h3>OpenCL Code</h3><p>The very first code we will write is to understand the hardware we have and simply log all the details which we just understood. This code is written in C++ and is very straightforward to understand.</p><p>First we start by importing all the required things like the Opencl library and iostream and vectors , I have also written a very basic formatted print function to avoid writing it again and again.</p><pre>#define CL_HPP_TARGET_OPENCL_VERSION 200 <br>#include &lt;CL/opencl.hpp&gt;<br>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;string&gt;<br>#include &lt;iomanip&gt;<br>using namespace std;<br><br>void printRow(string label, string value) {<br>    cout &lt;&lt; left &lt;&lt; setw(32) &lt;&lt; label &lt;&lt; &quot;: &quot; &lt;&lt; value &lt;&lt; endl;<br>}<br><br>int main(){<br>// Continued in the next block.</pre><h4>Platform Setup</h4><p>First, let’s clarify a quick detail: the Platform is <em>not</em> the physical device itself. As we mapped out in the hierarchy above, the Platform is the vendor-specific OpenCL implementation (like NVIDIA, AMD, or Intel) installed on your system. It is the software gateway that allows the host to talk to the hardware.</p><pre>    // 1. Setup Platform<br>    vector&lt;cl::Platform&gt; platforms;<br>    cl::Platform::get(&amp;platforms);<br>    if (platforms.empty()) {<br>        cout &lt;&lt; &quot;Error: No OpenCL Platform Found!&quot; &lt;&lt; endl;<br>        return 1;<br>    }</pre><p>In this snippet, we are doing the very first part of the “hardware handshake.” We use the OpenCL C++ API (cl::Platform::get) to ask the host operating system what vendor drivers are currently available. We store these in a standard vector. If that vector comes back empty, it means the host cannot see any OpenCL drivers, and we hard stop the program. Once we have a valid Platform, the next logical step is to dive into it and find the actual physical <strong>Device</strong> (the GPU) we want to run our math on.</p><h4>Device Selection</h4><p>Once we have a valid Platform, we need to locate the physical hardware that will actually execute our math.</p><pre>    // 2. Setup Device (Selecting the first available GPU)<br>    vector&lt;cl::Device&gt; devices;<br>    platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &amp;devices);<br>    if (devices.empty()) {<br>        cout &lt;&lt; &quot;Error: No GPU Device Found on this platform!&quot; &lt;&lt; endl;<br>        return 1;<br>    }<br>    cl::Device device = devices[0];</pre><p>Here, we query the platform specifically for GPUs by passing the CL_DEVICE_TYPE_GPU flag. A single OpenCL platform can manage multiple types of compute hardware (like your CPU and your GPU), so this filter ensures we are exclusively targeting the high-throughput accelerator. We store the discovered devices in a vector and grab the first one (devices[0]). This cl::Device object becomes our direct software handle to the physical silicon.</p><h4>Querying Device Limits</h4><p>Now we reach the core of the hardware handshake. We interrogate our chosen device using the getInfo function to extract the exact physical constraints of our silicon.</p><pre>    // --- Header ---<br>    cout &lt;&lt; &quot;==========================================================&quot; &lt;&lt; endl;<br>    cout &lt;&lt; &quot;      PHASE I: HARDWARE HANDSHAKE &amp; MEMORY MAPPING       &quot; &lt;&lt; endl;<br>    cout &lt;&lt; &quot;      Device: &quot; &lt;&lt; device.getInfo&lt;CL_DEVICE_NAME&gt;() &lt;&lt; endl;<br>    cout &lt;&lt; &quot;==========================================================&quot; &lt;&lt; endl;<br><br>    // --- [1] EXECUTION RESOURCES (The &quot;Workers&quot;) ---<br>    size_t maxWGSize = device.getInfo&lt;CL_DEVICE_MAX_WORK_GROUP_SIZE&gt;();<br>    cl_uint computeUnits = device.getInfo&lt;CL_DEVICE_MAX_COMPUTE_UNITS&gt;();<br>    cl_uint maxDims = device.getInfo&lt;CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS&gt;();<br>    vector&lt;size_t&gt; maxItems = device.getInfo&lt;CL_DEVICE_MAX_WORK_ITEM_SIZES&gt;();<br><br>    cout &lt;&lt; &quot;\n[1] EXECUTION RESOURCES&quot; &lt;&lt; endl;<br>    printRow(&quot;Compute Units (Cores/SMs)&quot;, to_string(computeUnits));<br>    printRow(&quot;Max Work-Group Size&quot;, to_string(maxWGSize) + &quot; threads&quot;);<br>    string dims = to_string(maxItems[0]) + &quot; x &quot; + to_string(maxItems[1]) + &quot; x &quot; + to_string(maxItems[2]);<br>    printRow(&quot;Max Work-Item Sizes (X/Y/Z)&quot;, dims);<br><br>    // --- [2] MEMORY HIERARCHY (HRAM -&gt; SRAM -&gt; Registers) ---<br>    cl_ulong globalMem = device.getInfo&lt;CL_DEVICE_GLOBAL_MEM_SIZE&gt;();<br>    cl_ulong cacheSize = device.getInfo&lt;CL_DEVICE_GLOBAL_MEM_CACHE_SIZE&gt;();<br>    cl_ulong localMem  = device.getInfo&lt;CL_DEVICE_LOCAL_MEM_SIZE&gt;();<br>    cl_ulong maxAlloc  = device.getInfo&lt;CL_DEVICE_MAX_MEM_ALLOC_SIZE&gt;();<br>    <br>    // Resilient check for Unified Memory (UMA)<br>    cl_bool unifiedMem = 0;<br>    try {<br>        device.getInfo(CL_DEVICE_HOST_UNIFIED_MEMORY, &amp;unifiedMem);<br>    } catch (...) {<br>        // If the driver throws an error, we assume it&#39;s a modern UMA device <br>        // where this specific flag is deprecated or handled via SVM.<br>    }<br><br>    cout &lt;&lt; &quot;\n[2] MEMORY HIERARCHY&quot; &lt;&lt; endl;<br>    printRow(&quot;HRAM (Global Memory)&quot;, to_string(globalMem / (1024 * 1024)) + &quot; MB&quot;);<br>    printRow(&quot;Global Mem Cache (L2)&quot;, to_string(cacheSize / 1024) + &quot; KB&quot;);<br>    printRow(&quot;SRAM (Local Memory/Tile)&quot;, to_string(localMem / 1024) + &quot; KB&quot;);<br>    printRow(&quot;Max Single Buffer Size&quot;, to_string(maxAlloc / (1024 * 1024)) + &quot; MB&quot;);<br>    printRow(&quot;Unified Memory (UMA)&quot;, (unifiedMem ? &quot;YES (Shared Host RAM)&quot; : &quot;NO (Discrete VRAM)&quot;));<br><br>    // --- [3] VECTORIZATION &amp; DATA TYPES ---<br>    cl_uint prefVecFloat = device.getInfo&lt;CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT&gt;();<br>    cl_uint prefVecHalf  = device.getInfo&lt;CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF&gt;();<br>    string extensions    = device.getInfo&lt;CL_DEVICE_EXTENSIONS&gt;();<br>    bool hasFP16 = (extensions.find(&quot;cl_khr_fp16&quot;) != string::npos);<br><br>    cout &lt;&lt; &quot;\n[3] VECTORIZATION &amp; PRECISION&quot; &lt;&lt; endl;<br>    printRow(&quot;Preferred Float Vector Width&quot;, to_string(prefVecFloat) + &quot; (float&quot; + to_string(prefVecFloat) + &quot;)&quot;);<br>    printRow(&quot;Preferred Half Vector Width&quot;, to_string(prefVecHalf) + &quot; (half&quot; + to_string(prefVecHalf) + &quot;)&quot;);<br>    printRow(&quot;Native FP16 Support&quot;, (hasFP16 ? &quot;YES&quot; : &quot;NO&quot;));<br><br>    cout &lt;&lt; &quot;\n==========================================================&quot; &lt;&lt; endl;<br>    cout &lt;&lt; &quot;OPTIMIZATION HINT:&quot; &lt;&lt; endl;<br>    if (localMem &lt; 32768) {<br>        cout &lt;&lt; &quot;&gt;&gt; Small SRAM detected. Use aggressive tiling and small block sizes.&quot; &lt;&lt; endl;<br>    } else {<br>        cout &lt;&lt; &quot;&gt;&gt; Large SRAM available. Ideal for high-performance fused kernels.&quot; &lt;&lt; endl;<br>    }<br>    cout &lt;&lt; &quot;==========================================================&quot; &lt;&lt; endl;<br><br>    return 0;<br>}</pre><p>This block breaks down into three critical optimization pillars:</p><ul><li><strong>Execution Resources:</strong> We query the maximum compute units and work-group sizes. This tells us exactly how to shape our parallel execution grid, known as the NDRange.</li><li><strong>Memory Hierarchy:</strong> We extract the exact boundaries of our Global (HRAM) and Local (SRAM) memory. The CL_DEVICE_LOCAL_MEM_SIZE is the most important number here—it dictates our maximum matrix tile size to avoid hitting the memory wall.</li><li><strong>Vectorization &amp; Precision:</strong> We check for native FP16 support and preferred vector widths. This tells us if we should process data as single scalars or pack them into vector types (like float4) for maximum arithmetic throughput.</li></ul><h3>Build and Run</h3><p>To build and run this, simply compile the source file while linking the OpenCL library (e.g., g++ cl_info.cpp -o cl_info.exe -lOpenCL) and execute the resulting binary in your terminal.</p><pre>C:\Users\OpenCL-LLM&gt;.\Hardware\build\cl_info.exe                                                                                                                              <br>==========================================================<br>      PHASE I: HARDWARE HANDSHAKE &amp; MEMORY MAPPING       <br>      Device: NVIDIA GeForce RTX 3060 Laptop GPU<br>==========================================================<br>[1] EXECUTION RESOURCES<br>Compute Units (Cores/SMs)       : 30<br>Max Work-Group Size             : 1024 threads<br>Max Work-Item Sizes (X/Y/Z)     : 1024 x 1024 x 64<br>[2] MEMORY HIERARCHY<br>HRAM (Global Memory)            : 6143 MB<br>Global Mem Cache (L2)           : 840 KB<br>SRAM (Local Memory/Tile)        : 48 KB<br>Max Single Buffer Size          : 1535 MB<br>Unified Memory (UMA)            : NO (Discrete VRAM)<br>[3] VECTORIZATION &amp; PRECISION<br>Preferred Float Vector Width    : 1 (float1)<br>Preferred Half Vector Width     : 0 (half0)<br>Native FP16 Support             : NO<br>==========================================================<br>OPTIMIZATION HINT:<br>&gt;&gt; Large SRAM available. Ideal for high-performance fused kernels.<br>==========================================================</pre><h3>Engineering Deep Dive: Translating Specs to Code</h3><p>It is one thing to print out a list of hardware specifications; it is another entirely to let them dictate your kernel design. When you are forced to manually bypass the memory wall, you cannot guess your parameters. Here is exactly how those raw numbers shaped my approach.</p><p><strong>The Math for Tiling (The SRAM Limit)</strong> My device reported 48 KB of Local Memory (SRAM). This is the most critical number for writing a matrix multiplication kernel. 48 KB gives us exactly 12,288 standard 32-bit floats. Because our math requires holding a tile of Matrix A and a tile of Matrix B in SRAM simultaneously, each tile is strictly limited to 6,144 floats.</p><p>The math is unforgiving: Square Root of 6,144 = 78.3</p><p>This means the absolute maximum, power-of-two tile size I can safely use is 64x64. If I greedily hardcode a 128x128 tile size, the kernel will immediately crash with a CL_OUT_OF_RESOURCES error.</p><p><strong>The Grid Shape (Execution Resources)</strong> The GPU has 30 Compute Units and allows up to 1024 threads per work-group. The naive approach to hiding memory latency is to max out that thread count. However, maximizing threads exhausts the Private Memory (registers), causing the hardware to “spill” registers back out to slower memory.</p><p>Instead, the execution grid must tightly map to the tile size. For an optimal 64x64 tile, dispatching work-groups of 256 threads (a 16x16 2D grid) — where each thread loops to compute multiple output elements — hits the perfect sweet spot for hardware occupancy.</p><p><strong>Data Transfer Strategy (The PCIe Bottleneck)</strong></p><p>Unified Memory (UMA) returned NO. This confirmed my CPU RAM and GPU VRAM do not physically share memory. Attempting to use &quot;zero-copy&quot; pointers here would just trigger hidden, painfully slow PCIe transfers under the hood. Furthermore, even though the GPU has 6 GB of total VRAM, OpenCL capped my single buffer allocation at 1.5 GB.</p><p>The takeaway? If I want to load a 3 GB LLM weight matrix, I cannot pass it as a single array. It must be explicitly chunked and moved via manual read/write buffer commands to respect the PCIe bus limits.</p><p><strong>The “NVIDIA Quirk” (Vectorization)</strong></p><p>This finding was fascinating. The RTX 3060 physically possesses Tensor Cores and hardware FP16 support. Yet, the OpenCL driver reported a preferred vector width of 1 (a purely scalar architecture) and absolutely no native FP16 support.</p><p>Why? NVIDIA intentionally limits its OpenCL driver implementation to push developers toward their proprietary CUDA ecosystem. OpenCL is forced to see a downgraded, scalar architecture. This immediately altered my coding strategy: wasting time trying to vectorize data types (like float4 or half) on this specific machine is pointless, as the compiler will just de-vectorize it sequentially. Instead, I had to rely entirely on the massive raw thread count to handle the parallelism.</p><h3>Memory Wall: Space vs. Speed</h3><p>In theory, the “Memory Wall” is the bottleneck between the processor and the memory chips. But to truly understand how it impacts Large Language Models on standard consumer hardware, we need to measure it on the bare metal and more importantly, we need to see how it <em>scales</em>.</p><p>I set up a programmatic experiment. We push varying sizes of data arrays (from 256,000 up to over 20 million elements) to the hardware. For every element, the processor is forced to perform a simple addition operation 10,000 times. The math is identical across the board. The only difference is <em>where</em> those numbers physically reside on the silicon: <strong>Global Memory (System RAM/VRAM)</strong>, <strong>Local Memory (SRAM/Cache)</strong>, or <strong>Private Registers</strong>.</p><p>To ensure we are testing physical hardware limits and not software tricks, I used volatile pointers in the OpenCL kernel to bypass aggressive compiler optimizations that usually try to delete predictable loops. I ran this benchmark across both a CPU and a discrete GPU to see how standard consumer hardware handles the physical distance of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hKy4Fy6-JJQT3ucGrqZzSg.png" /><figcaption>Code for the same is available at `memory_benchmarking_scale.cpp`</figcaption></figure><p>The resulting graphs reveal a brutal reality about hardware architecture that applies equally to both CPUs and GPUs:</p><ul><li><strong>Global Memory (The Red Line):</strong> Whether it is CPU System RAM or GPU VRAM, this is your off-chip storage. It has massive capacity, but the execution time skyrockets as the array size grows. Fetching data requires crossing a slow system bus, and that latency compounds aggressively.</li><li><strong>Local Memory (The Blue Line):</strong> This is the shared memory physically baked into the compute units (SRAM on GPUs, L1/L2/L3 Cache on CPUs). It scales much more gracefully, effectively halving the execution time. It is significantly faster, but the space is severely constrained a GPU compute unit might only have <strong>48 KB</strong> to share.</li><li><strong>Registers (The Green Line):</strong> This is the absolute speed limit of the ALUs (the math cores). The line is virtually flat, staying near 0 ms. The data never leaves the thread. It is nearly instantaneous, but you can only hold a few <strong>Bytes</strong> per thread.</li></ul><p>Looking at the <strong>Total Time Saved</strong> graphs on the right, the massive shaded gap represents the exact amount of time your processor’s math cores spend doing absolutely nothing. They are just idling, waiting for data to arrive from the motherboard.</p><p>What does a scaling addition benchmark have to do with Large Language Models? Everything.</p><p>LLM inference is almost entirely memory-bound, not compute-bound. When you prompt a model, the CPU or GPU has to pull massive weight matrices to perform matrix multiplication. This creates a severe physical dilemma for normal consumer laptops: The model weights are massive (gigabytes in size), meaning they <em>must</em> be stored in the slow, off-chip <strong>Global Memory</strong>. As our graph proves, constantly reading large arrays from Global Memory causes execution time to explode. If we write a naive Matrix Multiplication script for our LLM, the hardware will fetch every single row and column from main memory over and over again for every calculation. Our highly capable math cores will sit idle, starved of data, and our token generation speed will be trapped on the red line.</p><p>To make an LLM run fast on a normal laptop, we cannot just “compute harder.” We have to orchestrate the traffic. We need to stay off the red line and jump to the blue line. We must take the massive weight matrices sitting in System RAM or VRAM and chop them into precise, mathematical blocks that fit perfectly into that tiny <strong>48 KB SRAM</strong> limit. We load a block exactly once, do all the rapid-fire register math locally without ever touching the slow main memory again, write the result, and then swap the next block in.</p><p>This technique is called <strong>Tiling</strong>, and it is the foundational secret behind every highly optimized inference engine.</p><h3>Conclusion : Hardware</h3><p>By mapping these physical constraints, we’ve replaced guesswork with a precise mathematical blueprint for our next step: building a fully cache-optimized, Tiled Matrix Multiplication kernel in the next blogs.</p><p><em>GitHub : </em><a href="https://github.com/SRDdev/OpenCL-LLM/tree/master"><em>https://github.com/SRDdev/OpenCL-LLM/tree/master</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b0a3af68243" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradients and Parameters]]></title>
            <link>https://medium.com/@srddev/gradients-and-parameters-7f9f20d56b83?source=rss-5a5bc853a7b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f9f20d56b83</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gradient]]></category>
            <category><![CDATA[parameter]]></category>
            <category><![CDATA[model-training]]></category>
            <dc:creator><![CDATA[Shreyas Dixit]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 02:31:39 GMT</pubDate>
            <atom:updated>2025-08-04T02:31:39.974Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63bBsRUPV-OC_naaEPBXTg.png" /></figure><p>Training modern neural networks can sometimes feel like flying blind. You monitor loss curves and accuracy metrics, but the inner workings of how the millions of parameters actually learn remain mostly invisible. Things can go smoothly for a while, but when the training process fails, gradients explode, or the model refuses to converge, the lack of transparency can be frustrating. In this blog, we will explore the often-overlooked aspects of neural network training parameters and gradients. We’ll look at how these dynamics play a critical role in the learning process and how tracking them closely can help us better understand model behavior during training.</p><p>To understand what’s happening during training, it’s important to first break down two key components: parameters and gradients. Parameters are the weights and biases that a neural network uses to make predictions. They are essentially the model’s memory, storing everything the model has learned during training. Initially, these parameters are random, but as training progresses, they adjust to capture patterns in the data. Gradients, on the other hand, are the directions that guide the model on how to update its parameters. After each forward pass, the model computes the error and uses backpropagation to calculate gradients, which tell it how much each parameter should change to minimize that error. In simpler terms, gradients act as the learning signal, helping the model gradually improve its predictions. While we may be familiar with how gradients flow through a simple perceptron with a small number of samples, understanding how gradients behave in models with many layers and large datasets is a more complex challenge. How do gradients flow across multiple layers, and how can we infer what’s going on when the dynamics become less transparent? This is what we will explore in the following sections, aiming to shed light on these hidden processes and make the internal workings of modern neural networks more understandable.</p><h3>Experimental Setup</h3><p><strong>What is BitNet</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*erF3LNKEpbPCsba4.jpeg" /></figure><p>BitNet is a 1-bit Transformer architecture introduced by researchers at Microsoft Research and Peking University. Unlike traditional Transformers that use full-precision weights, BitNet employs a novel component called the BitLinear layer. This layer replaces standard linear layers and utilizes ternary weights (−1, 0, +1) and 8-bit activations, allowing the model to be trained with 1-bit weights from scratch. This approach significantly reduces memory usage and computational requirements while maintaining competitive performance on language modeling tasks.</p><p>The BitLinear layer operates by first computing the average of the absolute values of the weight matrix to determine a scaling factor. The weights are then divided by this scale, rounded to the nearest ternary value, and rescaled to continue in full precision. Activations are quantized to 8-bit precision using symmetric per-channel quantization. BitNet’s architecture retains the standard Transformer backbone, including multi-head self-attention and feed-forward networks, but replaces each linear layer with a BitLinear layer. This modification enables the model to scale efficiently in terms of both memory and computation, making it suitable for large language models.</p><p>For more detailed information, you can refer to the original paper: <a href="https://arxiv.org/abs/2310.11453">https://arxiv.org/abs/2310.11453</a></p><h4>Dataset</h4><p>For training, we utilized the <a href="https://huggingface.co/datasets/Open-Orca/OpenOrca">OpenOrca</a> dataset, an open-source collection derived from the FLAN dataset. OpenOrca comprises approximately 1 million GPT-4 completions and 3.2 million GPT-3.5 completions, augmented to enhance reasoning capabilities. The dataset is organized into tabular entries, each containing a system prompt, a question, and a corresponding response generated by GPT-3.5 or GPT-4. This structure aligns with the distributions presented in the ORCA paper and serves as a valuable resource for instruction-following tasks.</p><h4>Training Setup</h4><p>We trained the BitNet model from scratch using a subset of approximately 10,000 samples from the OpenOrca dataset. The training was conducted on a personal laptop equipped with an NVIDIA GeForce RTX 4070 GPU, featuring 8GB of VRAM. Despite the limited hardware, we achieved efficient training by employing gradient accumulation, mixed precision, and optimizing batch sizes. The model was trained using a sequence length of 512 tokens and an effective batch size of 32. To monitor training dynamics, we integrated Weights &amp; Biases (W&amp;B) for real-time tracking of parameters and gradients.</p><h4>Monitoring</h4><p>When monitoring training dynamics, histograms of gradients provide valuable insights into how the model is adjusting its parameters over time. Each histogram visually represents the distribution of gradient values for a specific layer in the model, and understanding these distributions is key to diagnosing potential issues in the training process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmFPMnve8xsgJi2YTL-GaA.png" /></figure><p>The histogram for <strong>model.embedding.weight</strong> shows how the gradient values are spread across a range of values. Ideally, we expect a <strong>gradual and even distribution</strong>, indicating that the gradients are neither too large nor too small. If the histogram shows <strong>spikes or an extremely narrow range</strong>, it could suggest potential issues like gradient explosion (spikes in gradient magnitude) or vanishing gradients (gradients being too small to make meaningful updates). In this case, the histogram displays a <strong>steady spread</strong> of values, suggesting stable gradient updates and normal learning progress in the embedding layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5_82q4hjQbQHH1xFCavfQ.png" /></figure><p>Next, we look at the gradients for <strong>model.fc_out.bias</strong>, which are also visualized in a histogram. Here, a <strong>uniform distribution</strong> across the range is what we expect, with the values not diverging too far from the center. A <strong>narrow spread</strong> indicates that the model’s adjustments to the bias term are small, and if the distribution were to shift drastically or become skewed, it could signal that the learning process is becoming unbalanced. In this case, the histogram of model.fc_out.bias shows that the gradients are <strong>well-behaved</strong>, with no unexpected spikes or irregularities. This indicates stable learning and proper bias adjustments during training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Biffmb8Lac_jzUfk5EeMyQ.png" /></figure><p>The histogram for <strong>model.fc_out.weight</strong> gives us insight into how the weights of the output layer are being updated. Similar to the bias gradients, we expect to see a <strong>wide and even distribution</strong> of gradient values across a range, signaling consistent updates without extreme shifts. A <strong>regular spread</strong> without sharp peaks suggests that the weight adjustments are progressing normally, without gradient instability. In this case, the histogram reveals a <strong>uniform spread of values</strong>, indicating that the gradient updates are stable and that the output layer is learning effectively.</p><h3>What to Look For: Identifying Potential Issues in the Gradient Histograms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JA1Los7S74Fk2dr-b8IlJQ.png" /></figure><p>In addition to understanding the patterns in gradient histograms, it’s crucial to consider <strong>initialization strategies</strong> for various layers of the model and how their gradients should behave over time. The behavior of gradients and their trends during training can provide valuable insights into whether the model is learning effectively or facing issues.</p><h4>1. Initial Starting Points for Each Layer</h4><p>The <strong>initialization of parameters</strong> in each layer plays a significant role in determining the behavior of gradients throughout the training process. Here are some typical initial values and guidelines for various layers:</p><p><strong>Embedding Layer (</strong><strong>model.embedding.weight)</strong>:<br> The embedding layer typically uses random initialization methods, such as <strong>Xavier/Glorot</strong> or <strong>He initialization</strong>, depending on the activation function used. The weights should start with small, random values, and the gradients in the early stages of training should ideally be evenly distributed around zero. The bias values are often initialized to zero.</p><ul><li><strong>What to expect</strong>: A uniform distribution in the gradient histogram with no extreme spikes or narrow distributions. Gradients should gradually grow as the model learns.</li></ul><p><strong>Fully Connected (FC) Layers (</strong><strong>model.fc_out.bias, </strong><strong>model.fc_out.weight)</strong>:<br> The weights for FC layers are generally initialized with small random values, and biases are initialized to zero. For deeper networks, <strong>Xavier initialization</strong> is often used for ReLU activations, while <strong>He initialization</strong> can be better suited for layers using ReLU.</p><ul><li><strong>What to expect</strong>: At the start, the gradients for the weights and biases should be small but gradually increase. Bias gradients should stay relatively small, with a uniform spread in the histogram, and weight gradients should show a smooth progression. If the initial weights are poorly chosen, there might be larger initial fluctuations.</li></ul><p><strong>Feed-Forward Networks (</strong><strong>model.transformer_layers.x.ffn.0.weight, </strong><strong>model.transformer_layers.x.ffn.0.bias)</strong>:<br> Similar to FC layers, the feed-forward weights should start with small random values (e.g., Xavier or He initialization), and biases should be initialized to zero. These layers often handle the internal transformations within the model, so stable gradients here are crucial for learning.</p><ul><li><strong>What to expect</strong>: The gradient distribution should gradually expand as the training progresses. Large deviations or extreme values early on can signal poor initialization or issues with gradient flow.</li></ul><p><strong>Attention Layers (</strong><strong>model.transformer_layers.x.attn.in_proj_weight)</strong>:<br> Attention layer weights are generally initialized in the same way as feed-forward layers. They are typically initialized with small random values. Since attention weights are used for scaling the input representations, stable gradients are essential for ensuring efficient learning.</p><ul><li><strong>What to expect</strong>: A smooth, even distribution of gradient values during training. If gradients remain consistently small or large, it may signal issues with the attention mechanism or the layer’s capacity to learn from the data.</li></ul><p><strong>Normalization Layers (</strong><strong>model.norm1, </strong><strong>model.norm2)</strong>:<br> For normalization layers like <strong>LayerNorm</strong> or <strong>BatchNorm</strong>, the weights are typically initialized to ones, while biases are initialized to zeros. These layers should help stabilize the gradient flow by normalizing activations and gradients across the layers.</p><ul><li><strong>What to expect</strong>: The gradient histograms should show consistent values over time, with no extreme spikes or irregular behavior. If the normalization layers aren’t behaving as expected, the gradients might either grow uncontrollably or shrink too much, leading to issues in training.</li></ul><h4>2. Ideal Trends Over Time</h4><p>Now that we’ve discussed the initial starting points for each layer, let’s move on to the <strong>ideal trends</strong> you should expect to see in the gradient histograms over time during training:</p><ul><li><strong>Stable Growth in Gradients</strong>:<br> Initially, the gradient values should be relatively small but should gradually grow as the model learns from the data. Gradients should show smooth increases over time, with no drastic jumps or collapses.</li><li><strong>Uniformity in Distribution</strong>:<br> For most layers, you should see <strong>uniform gradient distributions</strong>, where the values spread out evenly. This is particularly true for layers like embeddings, feed-forward layers, and normalization layers, where smooth and consistent updates are critical to effective learning.</li><li><strong>Gradual Shifts in Mean and Variance</strong>:<br> Over time, the mean and variance of gradient distributions should gradually adjust as the model learns. You want to see slight shifts in the distribution, but the histogram should generally remain well-behaved with no large fluctuations.</li><li><strong>No Extreme Fluctuations</strong>:<br> The key indicator of healthy training is the absence of extreme fluctuations in gradient magnitudes. Gradients should grow steadily, and any large fluctuations could indicate underlying issues like poor learning rates, problematic initialization, or architectural flaws.</li></ul><h4>3. What to Look For When Things Go Wrong</h4><p>While monitoring the trends in the histograms, there are certain <strong>warning signs</strong> to look for, indicating that something might be wrong with the training process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeaQtExxF_7AbwiV6fJqqA.png" /></figure><p><strong>Unstable Gradients</strong>:</p><ul><li><strong>What to look for</strong>: Large spikes or extreme outliers in the histogram, especially for early layers. Gradients that shoot up dramatically or drop to zero suddenly.</li><li><strong>What it means</strong>: This is a sign of <strong>gradient explosion</strong> or <strong>vanishing gradients</strong>. If the gradients explode, you might need to clip them. If they vanish, you may need to adjust activation functions or initialization schemes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gA6Av6nJ6cve7Y9myn2pZA.png" /></figure><p><strong>Gradients Too Small</strong>:</p><ul><li><strong>What to look for</strong>: A histogram where most of the gradient values are clustered very close to zero. The spread is tight and narrow.</li><li><strong>What it means</strong>: This could indicate <strong>vanishing gradients</strong>, especially in deep networks or layers with certain activation functions like sigmoid or tanh. If left unchecked, this will prevent the model from learning.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*maFmZxozw783WP138OrNFw.png" /></figure><p><strong>Irregular or Skewed Distribution</strong>:</p><ul><li><strong>What to look for</strong>: A histogram that is heavily skewed or has a non-uniform spread. One side might have many more values than the other, or the histogram may be bimodal (two peaks).</li><li><strong>What it means</strong>: Skewed or irregular distributions may signal <strong>unbalanced learning</strong> or a <strong>bad initialisation</strong>, where some parts of the network are learning much faster than others. This could lead to the model converging to sub optimal solutions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osfFxxErzX6wBP764vS2yw.png" /></figure><p><strong>Flat Distribution</strong>:</p><ul><li><strong>What to look for</strong>: A histogram that is flat across the gradient range, with nearly all values spread evenly across the entire range.</li><li><strong>What it means</strong>: A flat distribution often points to <strong>overly aggressive learning rates</strong> or issues with <strong>optimiser settings</strong>, which could lead to <strong>unstable training</strong> and poor model convergence.</li></ul><p>By knowing what to expect in gradient histograms and understanding the initial conditions and ideal trends for each layer, you can make informed decisions during training. These insights allow you to detect problems early and apply corrective measures, such as adjusting initialisation strategies, learning rates, or using techniques like gradient clipping. Monitoring these trends ensures a smoother training process, preventing issues that could hinder model performance.</p><h4>Optimizing Gradient Flow: Techniques and Best Practices</h4><p>Now that we’ve seen how to use gradient histograms to diagnose problems like vanishing and exploding gradients, the next logical step is to explore the tools and techniques we can use to fix them. Maintaining a stable and predictable flow of gradients is not just a diagnostic exercise; it’s a critical part of designing and training robust neural networks. Here, we’ll dive into some of the most effective strategies for optimizing gradient flow, ensuring your model learns efficiently and avoids common pitfalls.</p><h4>Gradient Clipping: The First Line of Defense Against Exploding Gradients</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P5d8vYIU8BzlU1Ae.jpg" /></figure><p>Exploding gradients, where the magnitude of gradients grows uncontrollably, can cause destructive parameter updates and lead to model divergence (often resulting in NaN loss values).</p><p><strong>Solution:</strong> Gradient clipping is a straightforward and effective technique to prevent this. It ensures that the magnitude of the gradients does not exceed a predefined threshold. Before a parameter update is applied, the L2 norm of the gradients is calculated. If it’s larger than the threshold, the entire gradient vector is scaled down to fit within that limit.</p><p>This single line acts as a safety net, ensuring your model makes steady, controlled updates even in the presence of extreme gradient values. On a W&amp;B gradient histogram, this would appear as a sharp cutoff, with no values exceeding the clipping threshold.</p><p><strong>How to implement (in PyTorch)</strong></p><pre># Your normal training code in Pytorch<br># After loss.backward() and before optimizer.step():<br>torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)  # Clip gradients to a max norm of 1.0<br>optimizer.step()</pre><h3>Normalization Layers: Stabilizing Activations and Gradients</h3><p>Unstable gradient flow can arise from “internal covariate shift,” where the distribution of activations within a network keeps changing during training. This makes it challenging for the model to learn, often resulting in vanishing or exploding gradients.</p><p><strong>Solution:</strong> Normalization layers like <strong>Batch Normalization (BatchNorm)</strong> and <strong>Layer Normalization (LayerNorm)</strong> are designed to stabilize activations across layers, preventing drastic shifts in their distribution and helping maintain stable gradients.</p><ul><li><strong>Batch Normalization (BatchNorm):</strong> Normalizes activations across the mini-batch by adjusting them to have a mean of zero and a standard deviation of one. This stabilizes the activations and ensures they stay within a reasonable range.</li><li><strong>Layer Normalization (LayerNorm):</strong> Normalizes the activations across the feature dimension for each sample individually. It is particularly effective for sequence models, like Transformers, where batch sizes can vary.</li></ul><p>Both techniques smooth the loss landscape, enabling the use of higher learning rates and making the model training more robust. They ensure that gradients behave more stably during training, and can be visualized as more uniform histograms on tools like W&amp;B.</p><p>Code Example (Batch Normalization in PyTorch):</p><pre>import torch<br>import torch.nn as nn<br># Simple model with BatchNorm<br>class SimpleNN(nn.Module):<br>    def __init__(self):<br>        super(SimpleNN, self).__init__()<br>        self.fc1 = nn.Linear(10, 50)<br>        self.bn1 = nn.BatchNorm1d(50)  # BatchNorm layer<br>        self.fc2 = nn.Linear(50, 1)<br>    def forward(self, x):<br>        x = torch.relu(self.fc1(x))<br>        x = self.bn1(x)  # Apply BatchNorm<br>        x = self.fc2(x)<br>        return x<br># Model instantiation and forward pass<br>model = SimpleNN()<br>x = torch.randn(32, 10)  # 32 samples, 10 features each<br>output = model(x)</pre><p>Code Example (Layer Normalization in PyTorch):</p><pre>class TransformerLayerNorm(nn.Module):<br>    def __init__(self, feature_size):<br>        super(TransformerLayerNorm, self).__init__()<br>        self.ln = nn.LayerNorm(feature_size)  # LayerNorm<br><br>    def forward(self, x):<br>        return self.ln(x)  # Apply LayerNorm<br><br># Example usage<br>model_ln = TransformerLayerNorm(50)<br>x = torch.randn(32, 50)  # 32 samples, 50 features<br>output_ln = model_ln(x)</pre><p>These normalization techniques help keep the activation&#39;s within a stable range, resulting in smoother gradient flow and more effective training.</p><h4>Strategic Initialization: Setting the Stage for Success</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rkwFdSTCRP8e_UBZX6FxUA.png" /></figure><p>Poor weight initialization can doom a training run before it even starts. If initial weights are too large, gradients will explode. If they’re too small, gradients will vanish almost instantly.</p><p><strong>Solution:</strong> Use intelligent initialization methods that account for the network’s architecture and activation functions.</p><ul><li><strong>Xavier/Glorot Initialization:</strong> Designed for activation functions like tanh or sigmoid, this method initializes weights from a distribution with a specific variance, ensuring the variance of activations and gradients remains roughly constant across layers.</li><li><strong>He (Kaiming) Initialization:</strong> The go-to for networks using the <strong>ReLU</strong> activation function. He initialization compensates for ReLU’s tendency to set negative values to zero by scaling the initial weights appropriately.</li><li><strong>How to implement (in PyTorch):</strong> You can initialize layers individually, as shown in the example from our inspiration article:</li></ul><pre>class Net(nn.Module):<br>    def __init__(self):<br>        super(Net, self).__init__()<br>        self.conv1 = nn.Conv2d(3, 32, 3, 1)<br>        torch.nn.init.kaiming_uniform_(self.conv1.weight, mode=&#39;fan_in&#39;, nonlinearity=&#39;relu&#39;)</pre><p>A good initialization strategy prevents initial gradient distributions from being heavily skewed or clustered around zero, as you would see in your W&amp;B histograms.</p><h4>The Right Activation Function: A Cornerstone of Gradient Health</h4><p>Activation functions like sigmoid and tanh suffer from a “saturation” problem. As inputs become very large or very small, the derivative (and therefore the gradient) of these functions approaches zero. This is the primary cause of the classic vanishing gradient problem.</p><p><strong>Solution:</strong> Use activation functions that do not saturate as easily, such as <strong>ReLU</strong> and its variants.</p><ul><li><strong>ReLU (Rectified Linear Unit):</strong> For positive inputs, ReLU has a constant derivative of 1. This simple property allows gradients to flow backwards through the network without diminishing, mitigating the vanishing gradient problem.</li><li><strong>Leaky ReLU, ELU, and GELU:</strong> These functions address the “dying ReLU” problem (where a neuron can get stuck with a negative input and never activate again) by allowing a small, non-zero gradient for negative inputs.</li></ul><p>By avoiding the saturation regions of sigmoid and tanh, ReLU-based functions ensure a healthy gradient signal is propagated deep into the network, as evidenced by more stable and spread-out gradient histograms.</p><h4>Adaptive Optimizers and Learning Rate Schedules</h4><p>A static learning rate can be problematic. A rate that is too high can cause oscillations or exploding gradients, while one that is too low can lead to vanishing gradients and extremely slow convergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3TKOvTqAWTlVotNb5VjyA.png" /><figcaption>Cosine Learnring Rate over 200 steps and variations of it.</figcaption></figure><p><strong>Solution:</strong> Use adaptive optimizers like <strong>Adam</strong> or <strong>RMSprop</strong>, and learning rate schedulers. Adaptive optimizers maintain a per-parameter learning rate, adjusting it based on the history of gradients for that specific parameter. They essentially use smaller updates for parameters with frequently large gradients and larger updates for those with small, infrequent gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*APVpIiixA6P3WzVX.png" /></figure><p><strong>What to look for:</strong> A learning rate finder, as demonstrated in our inspiration article, can plot the loss against the learning rate, helping you identify an optimal range. Using W&amp;B to log and visualize this curve is an excellent practice. Furthermore, techniques like a <strong>warm-up learning rate schedule</strong> can also prevent instability in the early stages of training.</p><p>By combining these practices from choosing the right initialization to using gradient clipping and normalization you can actively shape and control the learning process. These tools move you beyond simple monitoring, providing the means to prevent and correct gradient-related issues, ultimately ensuring a smoother, more effective training process and a better performing model.</p><h3>Conclusion</h3><p>Training neural networks doesn’t have to be mysterious. By focusing on gradients and parameters, we can better understand how models learn. We explored the relationship between parameters (the model’s memory) and gradients (the learning signal). Tools like Weights &amp; Biases help visualize gradient histograms, revealing issues such as spikes or narrow ranges. Recognizing these patterns allows for early troubleshooting.</p><p>We also discussed strategies to optimize gradient flow, including gradient clipping, and careful choices in normalization, initialization, and activation functions. These techniques help maintain stable and efficient training.</p><p>Ultimately, understanding and optimizing gradients is key to building well-trained models. With these strategies, you can try to move past trial and error and confidently diagnose training issues.</p><blockquote><strong>Happy Gradient Watching !</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f9f20d56b83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PaliGemma: The Future of Vision-Language AI]]></title>
            <link>https://medium.com/@srddev/paligemma-the-future-of-vision-language-ai-d44cfbdb10f5?source=rss-5a5bc853a7b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d44cfbdb10f5</guid>
            <category><![CDATA[paligemma]]></category>
            <category><![CDATA[deepmind]]></category>
            <category><![CDATA[vision-language]]></category>
            <category><![CDATA[siglip]]></category>
            <category><![CDATA[multimodal]]></category>
            <dc:creator><![CDATA[Shreyas Dixit]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 21:58:03 GMT</pubDate>
            <atom:updated>2024-12-22T21:58:03.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2lvQzf0V1Ej6tNwiROVQw.jpeg" /></figure><p>PaliGemma was released by Google DeepMind in October of 2024, I know this is a bit late considering the pace at which AI is developing but today We will dive in PaliGemma and its architecture and how it works !</p><p>In this blog we will dive into PaliGemma model and try to understand how the new generation of Language models (Vision Language Models) work !</p><h3>What is a Vision Language Model ?</h3><p>A Vision-Language Model (VLM) is a type of AI model designed to understand and generate responses that combine visual and textual information. These models use a vision models to process images and a language models to handle text, enabling them to perform tasks like <strong>image captioning, visual question answering, and object detection</strong>. By integrating visual and language inputs, VLMs bridge the gap between how machines interpret images and how they process natural language, allowing for more sophisticated, multimodal AI applications.</p><blockquote>“Let’s explore each component of this model individually before delving into the full architecture.”</blockquote><h3>SigLIP : Vision Encoder</h3><p>One of my favorite aspects and a key factor in the success of PaliGemma is the use of <strong>“</strong><a href="https://arxiv.org/abs/2303.15343"><strong>Sigmoid Loss for Language Image Pre-Training</strong></a><strong>” (SigLIP)</strong>. Designed as an enhanced version of CLIP (Contrastive Language-Image Pre-Training), SigLIP delivers significantly improved results and has become the go-to model for encoding images into a vector space.</p><p>SigLIP learns by taking image and text pairs, such as <em>“</em><strong><em>A golden retriever holding a tulip sitting on the ground in front of a fence</em></strong><em>”</em>, and encoding them into the same vector space. The model learns that the image vector is closer to its paired text vector than to unrelated descriptions like <em>“A man riding a bike”</em> or <em>“A red car in a New York street”</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*KmvpNEUZH2XxI9XjK9rJYg.jpeg" /></figure><p>The model is trained using <strong>contrastive learning</strong> (a method that allows models to extract meaningful representations from data by leveraging similarity and dissimilarity. It maps similar instances close together in a latent space while pushing apart those that are dissimilar). This approach allows SigLIP to learn through billions of text-image pairs, enabling its image encoder to generate highly accurate representations that align seamlessly with their corresponding textual descriptions. The Encoder from this training is used in PaliGemma as the Vision Encoder , now given an image the encoder generates highly accurate image vectors.</p><p>code for the SigLIP : <a href="https://github.com/SRDdev/PaliGemma/blob/master/modules/vision_encoder.py">Vision Encoder</a></p><h3>Gemma : Language Model</h3><p>Gemma is a series of Open language models built by Google. It is an auto-regressive decoder only model which has 2 variations a 2B and 7B version. It is built using the same foundational logics as the Gemini family of models and incorporates the following things.</p><ol><li>Grouped Query Attention (GQA): This mechanism improves parameter efficiency by allowing shared projections for queries and values, reducing the computational load while maintaining performance</li><li>RMSNorm: The inclusion of RMSNorm enhances training stability compared to traditional normalization techniques</li><li>Rotary Positioning Embeddings (RoPE): This feature aids in better understanding context within input sequences, improving the model’s ability to handle complex language tasks</li></ol><p>We will dive deeper into each one later.</p><h3>PaliGemma Model</h3><p>Now that we have skimmed through the Language and Vision part lets take a sneek peak at the architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jy06ob90507B6LRC.png" /></figure><p>The architecture looks simple yet is very effective. The model takes in an `image input` and a `text input` and generates a text-output. The given image is passed through the SigLIP Image Encoder, which is built on top of a <strong>Vision Transformer (ViT)</strong> architecture. The process begins with the <strong>Vision Embeddings</strong>, where the image is divided into fixed-sized patches, each of which is flattened and linearly projected into an embedding vector. Additionally, <strong>positional embeddings</strong> are added to the patch embeddings to retain spatial information about the image.</p><p>Next, the embeddings are passed into the Vision Encoder, which consists of <strong>self-attention layers</strong> and <strong>feed-forward layers</strong>. These layers refine the image representation by attending to relationships between different patches and applying nonlinear transformations. Residual connections and layer normalization are incorporated to stabilize training and improve convergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSEx_6TkJmyode1CfdzrjA.png" /></figure><p>Finally, the processed embeddings go through the <strong>post-layer normalization</strong> step, producing the final image representation in the latent space. This representation encodes the semantic and spatial information of the image.</p><p>The text input, on the other hand, is passed through the <strong>Gemma Text Encoder</strong>, which begins by embedding the input tokens using the embed_tokens layer. This layer maps each token in the input sequence to a high-dimensional space, resulting in a tensor of shape (Batch Size, Sequence Length, Hidden Size).</p><p>Next, the embeddings are normalized by adding a <strong>normalizer</strong> based on the square root of the hidden size to ensure <strong>stable gradient flow during training</strong> and to improve the <strong>scaling of the model&#39;s output. </strong>These normalized embeddings are then passed sequentially through multiple <strong>Text Decoder Layers</strong>, each of which consists of:</p><ol><li><strong>Self-Attention Layer with Rotary Positional Embeddings (RoPE):</strong><br>The attention mechanism attends to relevant parts of the sequence by applying <strong>Rotary Positional Embeddings</strong> to enhance positional awareness. A causal mask is also applied to ensure attention respects the sequential nature of the input.</li><li><strong>Residual Connections:</strong><br>The input embeddings are added back to the output of the attention mechanism to stabilize the learning process.</li><li><strong>RMSNorm Layers:</strong><br>Root Mean Square Layer Normalization (RMSNorm) is applied before and after the attention mechanism to normalize the inputs and outputs.</li><li><strong>Feed-Forward Network (MLP):</strong><br>A Multi-Layer Perceptron with a GELU activation projects the outputs of the attention mechanism to an intermediate size and back to the hidden size.</li></ol><p>These layers are stacked n times (as defined in the configuration), enabling the model to capture complex dependencies in the input sequence.</p><p>Finally, the output of the last decoder layer is passed through a <strong>final RMSNorm layer</strong> to produce the hidden states. These hidden states are then fed into a <strong>language modeling (LM) head</strong>, which projects them into a distribution over the entire vocabulary. This allows the model to predict the next token in the sequence or perform other causal language modeling tasks.</p><h3>KV Cache</h3><p>The <strong>KV Cache</strong> is a fascinating component of the Gemma models because it represents a practical solution to one of the key computational challenges of autoregressive modeling. In tasks like text generation, models need to predict one token at a time while preserving the context of all previously generated tokens. Without caching, the model would have to recompute the entire attention mechanism for the entire sequence at every step, which becomes computationally expensive as the sequence grows longer. This inefficiency arises from the quadratic complexity of the self-attention mechanism, where each token attends to all others in the sequence.</p><p>The KV Cache addresses this issue by storing the intermediate representations, specifically the <strong>key</strong> and <strong>value</strong> tensors generated during the attention computation. These tensors encapsulate the essential contextual information for each token in the sequence. Mathematically, in the self-attention mechanism, the output is computed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OXaP2gSzt2OKTdvX" /></figure><p>Here, Q (queries), K (keys), and V (values) are derived from the input embeddings via linear projections. For a new token added to the sequence, the query vector Q changes, but the K and V matrices for previously processed tokens remain the same. The KV Cache leverages this property by caching the K and V matrices from previous steps and only computing them for the new token, dramatically reducing redundant computation. Instead of recalculating the attention for all tokens, the model simply concatenates the cached K and V with the new token’s K and V, forming the updated matrices for the attention computation.</p><p>The importance of this mechanism lies not only in reducing computational complexity but also in its impact on memory usage. Without caching, the model must store all intermediate activations for every token in the sequence, which becomes infeasible for very long sequences. By caching only the K and V tensors, which are much smaller representations of the input, memory usage is minimized, enabling the model to scale effectively to longer contexts. Moreover, the KV Cache ensures that the model adheres to the autoregressive property, where a token can only attend to itself and the tokens that precede it. This is achieved by applying a causal mask to the cached KK and VV tensors, blocking attention to any future tokens. This combination of caching and masking makes the KV Cache not only efficient but also critical for maintaining the sequential nature of tasks like text generation.</p><h3>How Image and Text Are Integrated in PaliGemma</h3><p>Now that we’ve examined how PaliGemma handles images and text independently, let’s dive deeper into how these two modalities are combined to enable the model to process multimodal inputs effectively. This integration is at the core of PaliGemma’s ability to understand and generate coherent outputs that span both text and visual data.</p><h4>Aligning Image and Text Embeddings</h4><p>Before combining the two modalities, the <strong>image embeddings</strong> are projected into the same dimensional space as the text embeddings. This is achieved using the a simple linear transformation made by the multi modal projector layer. The goal here is to ensure that the image and text embeddings have the same size and scaling, allowing them to be merged seamlessly. Without this step, the embeddings would not align properly, and the model would struggle to process the multimodal input.</p><ul><li><strong>Text Embeddings:</strong> (Batch Size, Sequence Length, Hidden Size)</li><li><strong>Image Embeddings:</strong> (Batch Size, Number of Patches, Hidden Size)</li><li><strong>Aligned Embeddings:</strong> (Batch Size, Sequence Length + Number of Patches, Hidden Size)</li></ul><h4>Merging Modalities</h4><p>The merging process happens in the _merge_input_ids_with_image_tokens function. Here, the image embeddings are inserted into the sequence of text embeddings at positions corresponding to a special &lt;image&gt; token. For instance, if the input text is &quot;Describe this image&quot; and the input image is a photo of a dog, the combined sequence might look like this:</p><p>[Describe, this, image, &lt;image&gt;, image_patch_1, image_patch_2, ..., image_patch_N]</p><p>Here, &lt;image&gt; acts as a placeholder in the text sequence, signaling where the image embeddings should be inserted. The patches (image_patch_1, image_patch_2, etc.) are the actual image embeddings derived from the Vision Encoder.</p><p>The function also ensures that each type of token — text, image, and padding — is handled appropriately. <strong>Masks</strong> are created to guide the model during processing:</p><ul><li><strong>Text Mask:</strong> Identifies positions corresponding to text tokens.</li><li><strong>Image Mask:</strong> Identifies positions for image tokens.</li><li><strong>Padding Mask:</strong> Ensures padding tokens are ignored during computations.</li></ul><p>These masks are expanded to match the dimensionality of the embeddings, allowing the model to handle each token type correctly. The merging process creates a unified sequence of embeddings that contains both text and image information, ready for processing by the <strong>Text Encoder</strong>.</p><h4>Attention Mechanism and Causal Masking</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Iq64kYD48X-Rrkkf.png" /></figure><p>Once the merged embeddings are prepared, they are passed through the <strong>Text Encoder</strong> (essentially a large Transformer model). The encoder uses an <strong>attention mechanism</strong> to model relationships between all tokens in the sequence — whether they come from the text or the image. This is a critical step, as it allows the model to learn how the text and image relate to each other. For example, in the earlier example, the model might learn that “dog” in the text corresponds to certain patches in the image.</p><p>A <strong>causal mask</strong> is applied during this process to enforce the autoregressive property of the model. This mask ensures that each token can only attend to itself and the tokens that came before it, preserving the sequential nature of tasks like text generation. For example, while generating a caption for an image, the model can only look at the image and the text generated so far, not future tokens.</p><h4>Position IDs and Attention Handling</h4><p>Position IDs are updated dynamically based on the merged sequence. Text tokens retain their original positions, while image tokens are assigned new positions that follow the text. This positional information is crucial for the model to understand the order of tokens and their roles in the sequence. For example, it helps the model differentiate between “the image shows a” and “shows the image a” even when the same tokens are used.</p><h4>Unified Processing</h4><p>With the embeddings, masks, and positional information ready, the combined sequence is passed through the encoder layers. The encoder uses the self-attention mechanism to process the sequence holistically, capturing interactions between text and image tokens. This allows the model to integrate information from both modalities deeply. For example, it can understand that the phrase “brown dog” corresponds to certain patches in the image that contain a brown-colored animal.</p><h4>Generating Outputs</h4><p>After processing, the model outputs embeddings that capture the combined meaning of the text and image input. These embeddings can then be fed into the <strong>language modeling (LM) head</strong> to generate outputs like:</p><ul><li>Captions describing the image.</li><li>Answers to questions about the image.</li><li>Text completions that incorporate visual context.</li><li>Detection and Segmentation of Images.</li></ul><p>For tasks like image captioning, the LM head generates tokens one at a time, using the integrated multimodal embeddings and the causal mask to ensure the autoregressive flow of text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YJ75or6fuRi8p0nV.png" /></figure><p>PaliGemma can detect entities in an image using the detect [entity] prompt, outputting bounding box coordinates as &lt;loc[value]&gt; tokens. Each detection includes normalized coordinates (y_min, x_min, y_max, x_max) and the detected label. To convert, divide each value by 1024, then multiply y by the image height and x by the image width to get the bounding box coordinates relative to the original image.</p><h3>Conclusion</h3><p>PaliGemma represents a remarkable step forward in the realm of Vision-Language Models (VLMs), blending advanced vision and language understanding into a cohesive framework capable of tackling a wide range of multimodal tasks. Its innovative use of SigLIP for image encoding and the robust Gemma language model allows it to seamlessly merge text and image data, delivering unparalleled performance in tasks such as image captioning, visual question answering, and object detection. By incorporating cutting-edge techniques like KV caching, rotary positional embeddings, and RMSNorm, PaliGemma not only ensures computational efficiency but also maintains scalability and accuracy across long contexts.</p><p><strong><em>If you’re as excited about this technology as I am, check out my GitHub repository, where I’ve implemented PaliGemma from scratch in PyTorch: </em></strong><a href="https://github.com/SRDdev/PaliGemma"><strong><em>PaliGemma GitHub Repository</em></strong></a><strong><em>. The repository provides a detailed, hands-on approach to understanding and experimenting with PaliGemma’s architecture, making it an excellent resource for researchers, developers, and AI enthusiasts.</em></strong></p><p>This blog wouldn’t have been possible without the pioneering work of the researchers at <strong>Google DeepMind</strong>, particularly <strong>Lucas Byers</strong>, whose contributions have been instrumental in the development of this transformative model. I also want to extend my gratitude to <strong>Umar Jamil</strong> for his insightful video that shed light on the nuances of PaliGemma, making it easier to understand and appreciate the complexity behind this groundbreaking innovation.</p><p>Thank you for reading, and here’s to the continued evolution of multimodal AI!</p><p>Thank you for reading, and here’s to the continued evolution of multimodal AI!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d44cfbdb10f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Multi-Headed Yolo-v9 for Object Detection and Segmentation]]></title>
            <link>https://medium.com/@srddev/understanding-multi-headed-yolo-v9-for-object-detection-and-segmentation-8923ee21b652?source=rss-5a5bc853a7b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8923ee21b652</guid>
            <category><![CDATA[yolov9]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shreyas Dixit]]></dc:creator>
            <pubDate>Mon, 20 May 2024 16:19:09 GMT</pubDate>
            <atom:updated>2024-05-21T02:51:10.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_AGMaRXYhuAEM5t_ZIWKg.png" /></figure><h3>Introduction</h3><p>YOLOv9, short for “You Only Look Once, version 9,” is the latest iteration in the YOLO series, published in February 2024 by Chien-Yao Wang, I-Hau Yeh, and Hong-Yuan Mark Liao. This blog aims to explain the architecture of YOLOv9 in a straightforward and detailed manner. We’ll start by exploring the smaller components and gradually piece them together to understand the entire model.</p><h4><strong>Conv Block</strong></h4><p>As we all know one of the main components of any Image Processing model is Convolutional block. Yolo v9 has a convolutional block which contains a 2d convolution layer and batch normalization coupled with SiLU activation function. The convolutional layer takes in 3 parameters (k,s,p). K is number of kernel , S is Stride , P is Padding.</p><p><em>If not given Padding is calculated automatically using Kernels (p=k//2)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*qL_andSwDqIL0zjHG6N5Jw.png" /></figure><h4>RepConvN Block</h4><p>The RepConvN Block, or “Repetitive Convolutional N Block,” involves multiple Conv Blocks repeated in a specific pattern. In this block, the input is duplicated and fed into two separate Conv Blocks, with the outputs summed and then passed through a SiLU activation. The first Conv Block uses 𝑘=3<em>k</em>=3, while the second uses 𝑘=1<em>k</em>=1. This block is inspired by the “RepVGG” architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*Jw-8frNOTFc0dSlG5oG_gg.png" /></figure><h4>RepNBottelneck</h4><p>The RepNBottleneck (Repeated Normalized Bottleneck) block is crucial in YOLOv9’s backbone network. This block is an advanced version of the traditional bottleneck architecture, consisting of a series of operations: a bottleneck layer, normalization layer, activation function, and convolutional layers. The bottleneck layer reduces input feature map dimensionality for computational efficiency, while the normalization layer stabilizes training and enhances performance. The inclusion of a shortcut connection helps in gradient flow, mitigating vanishing gradient issues and enabling deeper network training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*DtfHAndTk8HwkV1XtiMpLA.png" /></figure><h4>RepNCSP</h4><p>The RepNCSP (Repeated Normalized Cross Stage Partial) block is another key component in the YOLOv9 model’s backbone network. It is an extension of the RepNBottleneck block, incorporating additional features to further improve the model’s performance and efficiency. The RepNCSP block consists of a series of repeated operations, similar to the RepNBottleneck block, including a bottleneck layer, normalization layer, activation function, and convolutional layers. However, the RepNCSP block introduces a unique feature: the Cross Stage Partial (CSP) module.The CSP module splits the input feature maps into two parts. One part undergoes the repeated operations of the RepNBottleneck block, while the other part is directly concatenated with the output of the repeated operations. This split-and-merge approach allows the model to learn both local and global features simultaneously, enhancing the feature representation and improving the overall performance of the model. Like the RepNBottleneck block, the RepNCSP block also includes a shortcut connection that bypasses the repeated operations and directly merges the input feature maps with the output. This shortcut connection helps to alleviate the vanishing gradient problem and facilitates the training of deeper networks.By incorporating the RepNCSP block multiple times within the backbone network, YOLOv9 can effectively extract hierarchical features at various scales and resolutions, further enhancing the model’s ability to detect objects accurately and efficiently in real-time scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*ISGsgoTPSoBwg_E-aQBjuA.png" /></figure><h4><strong>RepNCSP-ELAN 4</strong></h4><p>The RepNCSP-ELAN 4 (Repeated Normalized Cross Stage Partial with Efficient Large Kernel Attention Network) block is a sophisticated component in the YOLOv9 model’s backbone network. It builds upon the RepNCSP block by incorporating an additional module called the Efficient Large Kernel Attention Network (ELAN).The RepNCSP-ELAN 4 block consists of the following key components:</p><ol><li>RepNBottleneck: This block is similar to the one described earlier, with a series of repeated operations including a bottleneck layer, normalization layer, activation function, and convolutional layers.</li><li>Cross Stage Partial (CSP) module: The CSP module splits the input feature maps into two parts. One part undergoes the RepNBottleneck operations, while the other part is directly concatenated with the output.</li><li>Efficient Large Kernel Attention Network (ELAN): The ELAN module is a novel attention mechanism that aims to capture long-range dependencies in the feature maps. It uses a combination of large kernel convolutions and channel-wise attention to efficiently model these dependencies.</li></ol><p>The ELAN module consists of two main components:</p><ul><li>Large kernel convolutions: These convolutions use large kernel sizes (e.g., 7x7, 9x9) to capture a wider context and model long-range dependencies in the feature maps.</li><li>Channel-wise attention: This attention mechanism selectively emphasizes important channels in the feature maps, allowing the model to focus on the most informative features for object detection.</li></ul><p>The RepNCSP-ELAN 4 block combines the strengths of the RepNCSP block and the ELAN module to create a powerful feature extraction mechanism. By incorporating this block multiple times in the backbone network, YOLOv9 can effectively capture both local and global features at various scales and resolutions, leading to improved object detection performance and efficiency</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*NLxBNSV4DN519gtMaMIegg.png" /></figure><h4><strong>Adown</strong></h4><p>The Adown (Asymmetric Downsampling) block is a unique component in the YOLOv9 model, specifically designed for efficient downsampling of feature maps. Unlike traditional downsampling methods, such as max pooling or strided convolution, the Adown block aims to maintain important spatial information while reducing the feature map size. The Adown block consists of two main components:</p><ol><li>Asymmetric convolution: This component uses a combination of 1x3 and 3x1 convolutions to perform down sampling along the spatial dimensions (height and width). By using asymmetric kernels, the Adown block can effectively capture spatial information in both horizontal and vertical directions, while reducing the feature map size.</li><li>Normalization and activation: After the asymmetric convolution, the feature maps pass through a normalization layer (e.g., batch normalization) and an activation function (e.g., ReLU) to introduce non-linearity and improve the model’s learning capabilities.</li></ol><p>The Adown block is strategically placed in the YOLOv9 model’s backbone network to perform downsampling at specific stages. By using asymmetric convolutions instead of traditional down sampling methods, the Adown block can maintain important spatial information while reducing computational complexity and memory footprint. The use of the Adown block in the YOLOv9 model contributes to its overall efficiency and performance in object detection tasks. By effectively downsampling feature maps while preserving spatial information, the model can focus on the most relevant features for accurate object localization and classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*8blrtQAU5MLR6rgJ9mw4SA.png" /></figure><h3>Architecture Overview:</h3><p>Backbone Network:</p><ul><li>Utilizes RepNCSP-ELAN 4 blocks for feature extraction.</li><li>Incorporates RepNBottleneck and RepNCSP blocks for hierarchical feature representation.</li><li>Includes Adown blocks for efficient downsampling while preserving spatial information.</li></ul><p>Neck:</p><ul><li>Integrates PANet modules to enhance feature representation and aggregation.</li></ul><p>Head:</p><ul><li>Generates object detection outputs:</li><li>Bounding Box Regression: Predicts bounding box coordinates.</li><li>Class Prediction: Estimates class probabilities.</li><li>Objectness Score: Determines the confidence of object presence.</li></ul><p>Loss Function:</p><ul><li>Customized loss function combines bounding box regression, class prediction, and objectness score losses for optimization.</li></ul><p>Inference:</p><ul><li>Processes input images through the backbone network, neck, and head.</li><li>Applies non-maximum suppression (NMS) to refine detection results.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*3ylCivClMi8pknpotb5u9w.png" /></figure><h3>Overall Functionality:</h3><p>The YOLOv9 architecture leverages the RepNCSP-ELAN 4, RepNBottleneck, RepNCSP, and Adown blocks to extract hierarchical features efficiently while maintaining spatial information. The PANet modules in the neck enhance feature representation, leading to more accurate object detection. The head generates precise object detection outputs, including bounding box coordinates, class probabilities, and objectness scores. By utilizing a custom loss function and NMS during inference, YOLOv9 optimizes performance and ensures reliable object detection results.</p><blockquote><strong>Code to finetune your own segmentation or Detection model using Yolo-v9</strong></blockquote><blockquote><strong>https://github.com/SRDdev/MultiHead-Yolov9</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8923ee21b652" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swin Transformers for Semantic Segmentation : Part 1]]></title>
            <link>https://medium.com/@srddev/swin-transformers-for-semantic-segmentation-part-1-bd85bad7e051?source=rss-5a5bc853a7b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd85bad7e051</guid>
            <category><![CDATA[semantic-segmentation]]></category>
            <category><![CDATA[swin-transformer]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Shreyas Dixit]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 06:04:22 GMT</pubDate>
            <atom:updated>2024-04-09T06:04:22.175Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swin Transformers for Semantic Segmentation : Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zxsqKnjifJX_h6jhXB9HwA.png" /></figure><h4>Introduction</h4><p>Swin Transformers , born out of the research paper “Swin Transformer: Hierarchical Vision Transformer using Shifted Windows,” Swin Transformers mark a paradigm shift in transformer-based architectures. Unlike their predecessors like the Vision Transformer (ViT), Swin Transformers introduce a hierarchical structure and shifted windows approach, addressing limitations in processing long-range dependencies efficiently. This architecture not only improves computational performance but also enhances scalability, making Swin Transformers a compelling choice for various computer vision tasks.</p><p>In this blog we will try to understand and code one ourselves. So without any further adieu let’s dive in.</p><p>The Swin-Transformer is a Vision Transformer with some additional features. You can check out my implementation of ViT <a href="https://github.com/SRDdev/Vision-Transformer"><strong>here</strong></a><strong>.</strong></p><ol><li>SwinEmbedding (Patch partition &amp; Linear Embedding)</li><li>Patching Merging</li><li>Relative Embeddings</li><li>Shifted Window Attention Mechanism</li><li>SwinEncoder &amp; Final Architecture</li></ol><h4>Swin Embedding</h4><p>This code snippet defines a <strong>SwinEmbedding</strong> class, which acts as an embedding function to convert input RGB images into patches, similar to how it’s done in Vision Transformers (ViT). The input RGB image is split into non-overlapping patches, with each patch considered as a “<strong>token</strong>.” These patches are then projected into a higher-dimensional space using a linear embedding layer, effectively converting each patch’s raw pixel RGB values into a feature representation. In this implementation, a patch size of 4x4 is used, resulting in a feature dimension of 48 for each patch. Finally, a layer normalization and ReLU activation are applied to the embedded patches before returning them.</p><pre>class SwinEmbedding(nn.Module):<br>    &quot;&quot;&quot;<br>    Acts as an Embedding function to convert input RGB images into patches.<br>    Args:<br>        Input : RGB image with 96*96 image dimensions (size: b,c,h,w)<br>        Output: Patche vectors with dimensions (size: b,(h/4 * w/4),c)<br>    &quot;&quot;&quot;<br>    def __init__(self,patch_size=4,C=96):<br>        super().__init__()<br>        self.linear_embedding = nn.Conv2d(in_channels=3,out_channels=C,kernel_size=patch_size,stride=patch_size)<br>        self.layer_norm = nn.LayerNorm(C)<br>        self.relu = nn.ReLU()<br><br>    def forward(self,x):<br>        x = self.linear_embedding(x)<br>        x = rearrange(x,&#39;b c h w -&gt; b (h w) c&#39;)<br>        x = self.relu(self.layer_norm(x))<br>        return x</pre><h4>Patching Merging</h4><pre>class PatchMerging(nn.Module):<br>    &quot;&quot;&quot;<br>    Acts as the merging block to reduce the number of patches in each deeper layer.<br>    Args:<br>        Input: Patch (b, (h*w), C)<br>        Output: Patch (b, (h/2 * w/2), C*2)<br>    &quot;&quot;&quot;<br>    def __init__(self,C):<br>        super().__init__()<br>        self.linear = nn.Linear(in_features=4*C,out_features=2*C)<br>        self.layer_norm = nn.LayerNorm(2*C)<br><br>    def forward(self,x):<br>        height = width = int(math.sqrt(x.shape[1])/2)<br>        x = rearrange(x, &#39;b (h s1 w s2) c -&gt; b (h w) (s2 s1 c)&#39;,s1=2, s2=2, h=height, w=width)<br>        x = self.layer_norm(self.linear(x))<br>        return x</pre><p><strong>PatchMerging </strong>class, which serves as a merging block aimed at reducing the number of patches at each deeper layer of the model. Given an input patch tensor of shape <strong>(batch_size, num_patches, channels)</strong>, where <strong>num_patches </strong>represents the total number of patches and <strong>channels</strong> denotes the number of channels in each patch, the class outputs a merged patch tensor with reduced patch count and doubled channel dimensionality.</p><p>To achieve this, the input patches are reshaped into a grid format, effectively reducing the grid size by half in both height and width dimensions (h/2 ,w/2) . This effectively chnges the dimensions form (<strong>b, (h*w), C</strong>) to (<strong>b, (h/2 * w/2), C*2</strong>) . Then, a linear transformation is applied to expand the channel dimension by a factor of 2. Finally, layer normalization is performed to stabilize the output.</p><h4>Relative Position Embeddings</h4><p>In the process of computing self-attention, we add a relative position bias to each head’s calculation of similarity. This bias helps the model understand the positional relationships between tokens. Here, the attention formula involves query (Q), key (K), and value (V) matrices, with ‘d’ representing their dimensions, and ‘M2’ indicating the number of patches in a window. To make the calculation more efficient, we use a smaller-sized bias matrix that captures relative positions within a window range. Additionally, instead of relying on preset sinusoidal frequencies for position embeddings, we opt to learn them during training. These embeddings are added to the query-key product and must match the shape of the query and key matrices. Importantly, since a token’s position within each attention window can only differ by a certain range, we only need to keep track of parameters for this smaller-sized matrix, simplifying the process and making it more efficient.</p><pre>class RelativeEmbeddings(nn.Module):<br>    &quot;&quot;&quot;<br>    Module to incorporate relative position bias into self-attention computation.<br>    The relative position bias (B) is added to each head in computing similarity:<br>    Attention(Q, K, V) = SoftMax((QK^T) / sqrt(d) + B) * V,<br>    and M is the number of patches in a window.<br><br>    Since the relative position along each axis lies in the range [-M + 1, M - 1],<br>    we parameterize a smaller-sized bias matrix B_hat, and values in B are taken from B_hat.<br>    &quot;&quot;&quot;<br>    def __init__(self, window_size=7):<br>        super().__init__()<br>        # Initialize a learnable parameter B<br>        B = nn.Parameter(torch.randn(2 * window_size - 1, 2 * window_size - 1))<br>        <br>        # Generate relative positions along x and y axes<br>        x = torch.arange(1, window_size + 1, 1 / window_size)<br>        x = (x[None, :] - x[:, None]).int()<br>        y = torch.cat([torch.arange(1, window_size + 1)] * window_size)<br>        y = (y[None, :] - y[:, None])<br>        <br>        # Take values from B_hat based on relative positions<br>        self.embeddings = nn.Parameter(B[x[:, :], y[:, :]], requires_grad=False)<br><br>    def forward(self, x):<br>         <br>        # Add relative position bias to input<br>        return x + self.embeddings</pre><h4>Shifted Window Attention</h4><p>Shifted Window attention is the novel to the swin transformer, But before understanding the shifted window let us take a quick look at the windowed attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*fZqtBl3o5_Ut59hC.png" /></figure><p>In windowed attention we calculate the attention scores in parallel for non-overlapping patches of the image, like shown above.</p><blockquote>So one might ask why use shifted window if the windowed attention is working fine ?</blockquote><p>Shifted window attention offers an advantage over traditional window attention by introducing a shift mechanism that allows for overlapping and reusing tokens between adjacent windows. This enables the model to capture long-range dependencies more effectively while maintaining spatial coherence. Unlike window attention, where tokens are processed in non-overlapping windows, shifted window attention exploits overlapping windows, thereby enhancing the model’s ability to attend to contextual information across different scales without increasing computational complexity significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*1RY6ho9MV-T0LrGA.png" /></figure><p>In simpler words , the idea of shifted window attention is that on alternating attention computation layers we shift our windows so that our shifted windows overlap over the previous layers windows to allow cross window communication for the model.</p><p>This approach is promising! Nonetheless, a potential challenge arises when employing cyclic shift for shifted window attention. Since attention is computed on the shifted image, the model may struggle to determine the original positions of sections A, B, and C within the image. To address this, we can mitigate the issue by implementing a masking mechanism to restrict communication between tokens that should not be adjacent in the original image. Since we’ll be shifting our image size by half of the window size, only the last half of the rows and columns of windows will be impacted. To address this, we can apply the left mask to all of the last rows and the right mask to all of the last columns of the image.</p><p>Enough theory , Lets code</p><pre>&quot;&quot;&quot;<br>The idea of shifted window attention is that on alternating attention computation layers we shift our windows so that our shifted windows overlap over the previous layers windows to allow cross window communication for the model. We can achieve this efficiently by a cyclic shift as depicted in the image above. PyTorch has a function torch.roll we can use that will perform our cyclic shift of size window_size/2 on our input.<br>This is great! However one issue will come from using the cyclic shift to perform shifted window attention. Because we are now computing attention on the new shifted image, the model will be confused on where sections A,B,C in the above example actually belong in the image. We can solve this issue by masking the communication between tokens that should not be next to each other in the original image.<br>Because we will shift our image size by window_size/2, only half of the last row and column of windows will be affected. For this reason, we can apply the left mask shown below to all of the last rows and the mask on the right to all of the last columns of the image.<br>&quot;&quot;&quot;<br>class ShiftedWindowMSA(nn.Module):<br>    &quot;&quot;&quot;<br>    Shifted window self attention module.<br>    Detailed description can be found in the &#39;Notes&#39; section under SWMSA.<br>    &quot;&quot;&quot;<br>    def __init__(self, embed_dim, num_heads, window_size=7, mask=False):<br>        super().__init__()<br>        self.embed_dim = embed_dim<br>        self.num_heads = num_heads<br>        self.window_size = window_size<br>        self.mask = mask<br><br>        self.proj1 = nn.Linear(in_features=embed_dim, out_features=embed_dim*3)<br>        self.proj2 = nn.Linear(in_features=embed_dim, out_features=embed_dim)<br>        self.embeddings = RelativeEmbeddings()<br><br>    def forward(self, x):<br>        # Calculate height and width of input feature map<br>        height = width = int(math.sqrt(x.shape[1]))<br>        # Project input to keys, queries, and values<br>        x = self.proj1(x)<br>        # Rearrange input for multi-head self attention<br>        x = rearrange(x, &#39;b (h w) (c K) -&gt; b h w c K&#39;, K=3, h=height, w=width)<br><br>        # Shifted window masking<br>        if self.mask:<br>            x = torch.roll(x, (-self.window_size//2, -self.window_size//2), dims=(1,2))<br><br>        # Further rearrange for applying shifted window self attention<br>        x = rearrange(x, &#39;b (h m1) (w m2) (H E) K -&gt; b H h w (m1 m2) E K&#39;, H=self.num_heads, m1=self.window_size, m2=self.window_size)<br>        Q, K, V = x.chunk(3, dim=6)<br>        Q, K, V = Q.squeeze(-1), K.squeeze(-1), V.squeeze(-1)<br>        # Calculate attention scores<br>        att_scores = (Q @ K.transpose(4,5)) / math.sqrt(self.embed_dim / self.num_heads)<br><br>        # Apply row and column masks for the last rows and columns of windows<br>        &#39;&#39;&#39;<br>          shape of att_scores = (b, H, h, w, (m1*m2), (m1*m2))<br>          we simply have to generate our row/column masks and apply them<br>          to the last row and columns of windows which are [:,:,-1,:] and [:,:,:,-1]<br>        &#39;&#39;&#39;<br>        if self.mask:<br>            row_mask = torch.zeros((self.window_size**2, self.window_size**2)).cuda()<br>            row_mask[-self.window_size * (self.window_size//2):, 0:-self.window_size * (self.window_size//2)] = float(&#39;-inf&#39;)<br>            row_mask[0:-self.window_size * (self.window_size//2), -self.window_size * (self.window_size//2):] = float(&#39;-inf&#39;)<br>            column_mask = rearrange(row_mask, &#39;(r w1) (c w2) -&gt; (w1 r) (w2 c)&#39;, w1=self.window_size, w2=self.window_size).cuda()<br>            att_scores[:, :, -1, :] += row_mask<br>            att_scores[:, :, :, -1] += column_mask<br><br>        # Apply softmax to get attention weights and multiply with values<br>        att = F.softmax(att_scores, dim=-1) @ V<br>        # Rearrange back to original shape<br>        x = rearrange(att, &#39;b H h w (m1 m2) E -&gt; b (h m1) (w m2) (H E)&#39;, m1=self.window_size, m2=self.window_size)<br><br>        # Reverse shifting if masking was applied<br>        if self.mask:<br>            x = torch.roll(x, (self.window_size//2, self.window_size//2), (1,2))<br><br>        # Rearrange back to original shape and project to final output<br>        x = rearrange(x, &#39;b h w c -&gt; b (h w) c&#39;)<br>        return self.proj2(x)</pre><p>We start by initializing ‘self.proj1’ which is our projection from inputs to Queries, Keys, and Values which we do in one parallel projection so the output size is set to 3*C. The second projection layer is used for communication between the attention scores after they are calculated.</p><p>In the forward pass we get the height , width and pass it to get our K,Q,V and rearrange it using `(<strong>b (h w) (c K) -&gt; b h w c K)</strong>` for multi-head self attention. Then we apply masking over them and again rearrange for applying shifted window self attention. Perform the SWSA and apply SoftMax to the attention scores. Finally we rearrange them back into `<strong>(b (h w) c) </strong>and apply the projection layer 2 for interpatch communication.</p><h4>SwinEncoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*-3PJP8JrYLqHjCWBqvA8UQ.png" /></figure><pre>class SwinEncoderBlock(nn.Module):<br>    def __init__(self,embed_dim, num_heads, window_size, mask):<br>        super().__init__()<br><br>        self.layer_norm = nn.LayerNorm(embed_dim)<br>        self.dropout = nn.Dropout(0.1)<br>        self.WMSA = ShiftedWindowMSA(embed_dim=embed_dim, num_heads=num_heads, <br>                                     window_size=window_size, mask=mask)<br>        self.MLP1 = nn.Sequential(<br>            nn.Linear(embed_dim, embed_dim*4),<br>            nn.GELU(),<br>            nn.Linear(embed_dim*4, embed_dim)<br>        )<br><br>    def forward(self, x):<br>        height, width = x.shape[1:3]<br>        res1 = self.dropout(self.WMSA(self.layer_norm(x)) + x)<br>        x = self.layer_norm(res1)<br>        x = self.MLP1(x)<br>        return self.dropout(x + res1)</pre><pre>class AlternatingEncoderBlock(nn.Module):<br>    def __init__(self, embed_dim, num_heads, window_size=7):<br>        super().__init__()<br>        self.WSA = SwinEncoderBlock(embed_dim=embed_dim, num_heads=num_heads, window_size=window_size, mask=False)<br>        self.SWSA = SwinEncoderBlock(embed_dim=embed_dim, num_heads=num_heads, window_size=window_size, mask=True)<br>    <br>    def forward(self, x):<br>        return self.SWSA(self.WSA(x))</pre><p>The <strong>SwinEncoderBlock </strong>upon receiving the input tensor, it undergoes layer normalization to standardize feature distributions. Subsequently, the tensor enters the Shifted Window Multi-Head Self-Attention (WMSA) module, where self-attention mechanisms allow tokens to attend to each other’s representations, facilitating contextual understanding. Following the WMSA module, a residual connection is established between the output of WMSA and the original input tensor, aiding in gradient flow and preserving valuable information. Another layer normalization step stabilizes feature distributions before the tensor is passed through a Multi-Layer Perceptron (MLP), enabling the model to learn complex transformations of features. The output of the MLP is then added to the output of the residual connection, forming another residual connection. Finally, dropout regularization is applied to prevent overfitting, yielding the final output tensor of the SwinEncoderBlock.</p><h4>SwinTransformer</h4><p>Now finally we will combine all the above blocks to build our Swin Transformer</p><pre>class SwinTransformer(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.Embedding = SwinEmbedding()<br>        self.PatchMerge1 = PatchMerging(96)<br>        self.PatchMerge2 = PatchMerging(192)<br>        self.PatchMerge3 = PatchMerging(384)<br>        self.Stage1 = AlternatingEncoderBlock(96, 3)<br>        self.Stage2 = AlternatingEncoderBlock(192, 6)<br>        self.Stage3_1 = AlternatingEncoderBlock(384, 12)<br>        self.Stage3_2 = AlternatingEncoderBlock(384, 12)<br>        self.Stage3_3 = AlternatingEncoderBlock(384, 12)<br>        self.Stage4 = AlternatingEncoderBlock(768, 24)<br><br>    def forward(self, x):<br>        x = self.Embedding(x)<br>        x = self.PatchMerge1(self.Stage1(x))<br>        x = self.PatchMerge2(self.Stage2(x))<br>        x = self.Stage3_1(x)<br>        x = self.Stage3_2(x)<br>        x = self.Stage3_3(x)<br>        x = self.PatchMerge3(x)<br>        x = self.Stage4(x)<br>        return x</pre><p>In this we call the Swin Embeddings , then pass through Patch Merge twice (can change depending upon choice) , then through Alternating Encoder Blocks to generate the output.</p><p>Test out the architecture is working by passing dummy inputs like below</p><pre>x = torch.randn((1,3,224,224)).cuda()<br>model = SwinTransformer().cuda()<br>print(model(x).shape)</pre><blockquote>That is it , you have built a SwinTransformer in PyTorch !!!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd85bad7e051" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A life-changing Experience]]></title>
            <link>https://medium.com/@srddev/a-life-changing-experience-8197d7fe9ac6?source=rss-5a5bc853a7b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8197d7fe9ac6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[teaching]]></category>
            <category><![CDATA[lead-learn-inspire]]></category>
            <dc:creator><![CDATA[Shreyas Dixit]]></dc:creator>
            <pubDate>Fri, 26 Nov 2021 14:18:47 GMT</pubDate>
            <atom:updated>2021-11-26T14:18:47.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9apEGfBE5YJ1R0NrhcgsGg.png" /></figure><p>Recently got an opportunity to teach in a Python Bootcamp, It was my first time teaching for such a big crowd (300+ registrations). I was a bit nervous but then I remembered when I first started with python, I had a lot of confusion in my head. For a beginner like me, it was difficult to understand what was going on and how to use it in the correct way. But thankfully with the help of some experts and mentors around me, I have learned how to use python and make sense of all its basics.</p><p>Learning to use Python was a long-term goal for me. I didn’t have any hard skills in programming and I wanted to learn how to code. I started out by taking a couple of introductory courses on Python from Udemy, Coursera. It felt really good to get my hands dirty with coding. But at the same time, it also felt overwhelming because of the sheer volume of information that I was trying to take in — syntaxes, keywords, etc. As a programming language, Python has been around for decades and is used in many fields like data analysis and machine learning. It’s time to take the plunge!</p><p>Today, I get immense joy when someone tells me that they are able to understand all that I taught them of Python.</p><blockquote><em>Teaching Python is a great way to explore your knowledge of Python itself!</em></blockquote><p>We covered topics like data structures, functions, and loops to give participants an idea of what it means to learn Python Basics. I taught the intermediate course of Python Libraries. It covered the libraries such as Tkinter, OS learn, Numpy, Pandas, Matlplotlib, Seaborn. Throughout the BootCamp, we had a lot of fun and got to learn a lot.</p><p>It was a really fulfilling and life-changing experience for me!</p><p><em>Lead Learn Inspire</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8197d7fe9ac6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>