<?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 Ksheer Sagar Agrawal on Medium]]></title>
        <description><![CDATA[Stories by Ksheer Sagar Agrawal on Medium]]></description>
        <link>https://medium.com/@ksheer.agrawal?source=rss-4502a438fcdd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*97EGG0U6BVcqzTJJ_pKGtA.jpeg</url>
            <title>Stories by Ksheer Sagar Agrawal on Medium</title>
            <link>https://medium.com/@ksheer.agrawal?source=rss-4502a438fcdd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 00:35:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ksheer.agrawal/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[ML Systems]]></title>
            <link>https://medium.com/@ksheer.agrawal/ml-systems-73c4757ac981?source=rss-4502a438fcdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/73c4757ac981</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[ml-system]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ksheer Sagar Agrawal]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 02:22:37 GMT</pubDate>
            <atom:updated>2026-06-28T02:22:37.179Z</atom:updated>
            <content:encoded><![CDATA[<p>Three years ago, nobody wanted to be an ML systems engineer. Researchers wanted to build models. Engineers wanted to ship products. Systems work — compilers, kernels, memory management, distributed training — was the unglamorous plumbing underneath.</p><p>Then the economics changed.</p><p>When OpenAI published GPT-3 in 2020 and proved that scaling works — more compute, better model, no ceiling in sight — every major tech company made the same bet simultaneously. The bottleneck was no longer “can we build a smarter model.” It was “can we afford to run it.” Training a frontier model costs hundreds of millions of dollars. Serving it to millions of users costs more. A 10% improvement in how efficiently you use your GPUs is worth tens of millions of dollars at that scale.</p><p>Suddenly the plumbing was the most valuable thing in the building.</p><p>That’s why every sharp student in the last two to three years has quietly pivoted toward ML systems. Not because the research got more interesting — though it did — but because the economic stakes got enormous. The people who understand how to make matrix multiplications run faster, how to keep GPUs busy serving thousands of users simultaneously, how to train a model that doesn’t fit on one GPU across thousands of GPUs — those people are now among the most sought-after engineers in the industry.</p><p>This course is about becoming one of them.</p><h3>1. Deep Learning Recap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IEPGxXzup_WoiR5V_pMMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDr2Gkt04xj-xK37FLY8vQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWmEsqG28BZW3pwOJLn5mA.png" /><figcaption><strong>MLSys ~= Matmul Sys (punchline)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ohRpbW6Lw4MtuCzvEb5nOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRMqwKunwbBY-Bi981GkXw.png" /></figure><h3>2. DataFlow Graph Representation &amp; AutoDiff</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPBs8O-qPPUw4Oi9C7TEtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcTz1d1Debpd0lNB5WvRmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNQGLxL0IF_tKS4m4ULUwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ep7oV_0thqp1QQdzDKF1w.png" /><figcaption>Tensorflow v1 (classic) was built explicitly around an explicit dataflow graph (define-then-run). PyTorch used <strong>define-by-run</strong> (dynamic graphs).</figcaption></figure><p>Modern ML frameworks relies heavily on JIT. The problem with JIT is that it works best on static, predictable computations, while many real programs are dynamic and only reveal their behavior at runtime. SOTA systems like PyTorch 2.x and JAX Compile the predictable parts and handle the dynamic parts separately (piecewise compilation).</p><h3>3. Operator Optimisation Part — 1</h3><p>Matmul is mathematically fixed. But there are many ways to execute it:</p><ul><li>One core vs many cores (<strong>parallelization</strong>)</li><li>Scalar operations vs vector operations (<strong>vectorization</strong>)</li><li>Bad memory layout vs good memory layout (<strong>data layout</strong>)</li><li>No tiling vs cache/register-aware tiling (<strong>data reuse</strong>)</li><li>CPU vs GPU (<strong>hardware choice</strong>)</li></ul><p>All produce the same answer, but some can be 100×–1000× faster because they reduce memory movement and increase hardware utilization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nx26RNrJ9zM4vkjfkMU4dQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guhv3Q2g1G-fGFcgo2tKHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rY836sjStVrptMRoxl2jMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKHg45WBsUXnrbklZIgjXQ.png" /><figcaption><strong>general(CPU) operator optimisation</strong></figcaption></figure><h3>3. GPU Recap</h3><p>Every operation in CPU/GPU is ultimately performed by turning transisotr switched on and off. More transistors means more compute, cache, register and complex logic. Early 1990’s every 2 years, CPU chips got much faster. Hardware engineers did the hard work and software mostly benefited for free. As transistors got smaller, signals travelled shorted distances, switching became faster and clock speeds kept increasing. But switchnig consumes energy. More switching more power consumed. Almost all electrical power used by chip eventually becomes heat. Eventualy cooling became a bottleneck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wW2M0ngC6G2atiqexeXzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UG2xxlt8796HZ0tVhlUOlQ.png" /><figcaption>Faced with the end of easy scaling, NVIDIA, Groq, and Apple each chose a different optimization target: throughput, latency, and efficiency, respectively.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LBtJ6tzDl1jCm2itaKt0cQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_mbhk4m7z-YmOCTPs4pEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRMhj_GqkVSq5Qsi3bDgtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZBNyzxrzvYauMyRO-tRzQ.png" /><figcaption>ref: <a href="http://youtube.com/watch?v=h9Z4oGN89MU">http://youtube.com/watch?v=h9Z4oGN89MU</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUWnYZjUFQIBz6SOngg9_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqtLwTVbaPbA0EwPEbCAKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*XnGGMyEGdc0NnjDv4uH0hw.png" /></figure><p>Nvidia released CUDA in 2006. Researchers must explicity define #blocks, #threads, data partitioning to program. CPU handles control, OS, networking, scheduling whereas GPU handled massive math. But soon people discovered moving data is a bigger bottleneck than doing the math.</p><h3>4. Operator Optimisation Part — 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gm6UkToF7SP00o0OFlJQqQ.png" /><figcaption><strong>gpu operator optimisation</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*CFwyPPdL7mHMiIeUfwLcxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*ezP8b4InkRtrXsiNYB6MgQ.png" /><figcaption>v1. thread | v2. cache | v3. sram tiling</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*NoAkt4mddgt9iMI8gvpC5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*g07iMDX70L-P1E__nZCtFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_nVHtOVfkp7o7sgiUPpUzQ.png" /><figcaption><strong>operation cuda-ing recipe</strong></figcaption></figure><p>Nvidia team of GPU performance engineers, mantained cuBLAS who hand tuned kernels per GPU architecture (kepler, pascal, volta, ampere, hopper) — a closed source, continuously updated craftsmanship — Nvidia’s moat. But as deep learning exploded, people needed fast kernerls not just for matmuls but other operators. Hand tuning was practically impossible and others responded with compiler based autotuning.</p><h3>5. ML Compilers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V80EytH--V0_qe_4zDdoQg.png" /><figcaption>The pre-graph-IR landscape. models expressed in frameworks dispatched op-by-op to vendor specific kernel libraries, each hand tuned for specific hardware.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hAwE5ocYeBNslUsUHuN8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQLNsQ9xI2HiMEHd2CAr6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*qckQHclG4ShyRH7zIG37QA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTQ7DXHzxUU6XC4HIFLPLQ.png" /></figure><ol><li><strong>Halide</strong> (<strong>2012)</strong> first introduced the idea of seperating the algrothmic compute and the optimisation which inspired TVM and Triton design philosophy.</li><li><strong>Apache TVM</strong> <strong>(2018)</strong> pioneered ML specific autotuning (AutoTVM, later Ansor) — automatic search over tiling/loop schedules per hardware target. However it lost its ground due to (1) required model out of Pytorch visa ONNX, an extra conversions step. (2) a single operator could take hours. It lost its grounds and got acquired by Nvidia.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*U1P7U-lziA3STzi2rSST4w.png" /></figure><p><strong>3. XLA (2017) </strong>from google looks the whole computation before running and fuses it into one optimised kernel. It is widely adopted in backends of JAX, Tensorflow and is tied to TPU’s future.</p><p><strong>4. Triton (2019). </strong>Now it is the default backend for <strong>Pytorch 2.0</strong>. Highly used in AI labs to write custom fused kernels without hand-writing CUDA. It hits the sweet spot — it is simpler than CUDA but more expressive than pure graph compilers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFgWWHhJDZqNzvCBG2jDsg.png" /><figcaption><strong>Triton trades some of CUDA’s expressiveness for ease of use, and some of a graph compiler’s automation for the ability to express custom kernels</strong></figcaption></figure><p><strong>5. TensorRT (2016). </strong>It is different from others as it compiles down all the way to actual GPU assembly instructions (even below PTX — nvidias intermediate assembly, similar to LLVM IR). It only targets NVIDIA, and only inference.</p><p><strong>6. Mojo / MAX (2022).</strong> Created by Chris Lattner (creator of LLVM and Swift), it’s a Python-like language that compiles to native, hardware-portable code via MLIR — the same compiler infrastructure underlying XLA. It carries technical credibility from Lattner’s track record but adoption lags because ecosystem wins on gravity. To date, 90% market share is Nvidia’s, so people dont feel the pain Mojo is built to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2v7wsWOOb07RiKKyV3nNqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxPvY_3F8yRsgzeV_SJtQw.png" /></figure><p>Bottleneck shifted from who’s the best hand tuner to which intermediate language/compiler best captures researchers new ideas. Triton gives near CUDA speed without necessity of becoming CUDA experts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPaTWLar1E32887WlJyTtg.png" /></figure><h3>6. Graph Optimisation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMLEEFJDmccvhOIkc7JA5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zyB4ZBKkhPZ_lfWr-doukQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGPIV9HDWVNHxG4aWxRAEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2eRLgQbqZ7rPeF5iua2ig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHTKly6VaVt4psqD21i_tA.png" /><figcaption>First-gen ML compilers (TVM, XLA, Halide-era) did introduce graph IRs, but were largely manually written rule sets.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YafoIJKQpJIwggwRLtg_XQ.png" /><figcaption>2019~ish</figcaption></figure><p><strong>TASO</strong> sits at the <strong>graph-level</strong> layer from the “Grand Problems” framework (programming-level / graph-level / op-level) — it’s a concrete real example of “automatic graph transformations to make it faster,” sibling to XLA’s fusion approach but with a much stronger emphasis on formally <em>verified</em> correctness rather than just hand-written fusion patterns.</p><h3>7. Runtime and Scheduling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8m5GWd-aRYf2N7C9hg5-OA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYetNtF9x9rS0X00mRv1PA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XfcUBaL9T0XkhRxuZ4aFkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*c_fNsEiVEqFuFmsBS2LAtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*dhZBONlEzqv9hB2jE9Dxsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*CNxgMbt87HFjIyZAfeYXhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*gdMxxr9yCAd2SOBIKCXRwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8HYa1ZTj8CMN-cEeVDfww.png" /><figcaption>checkpointing and rematerialisation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BUKhOiHLzj37QI-WDvu4g.png" /><figcaption>gradient accumulation with micro batching</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*m58-QokhNE0kumYJNgSekw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*nOt6xmrCNEfQFTvatBqnug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cp8SIoBJVRmnTnD1cUVrQQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqnCuqUrv4g9Gxwswa8AJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GEN67xdGHyxe_7JYjv_3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uSCtWmSjh81zS8aSp5UFOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XyNEXyuR0yk1qDZTddbYRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*8izRLFd5EdKlK-KqLw_tTw.png" /><figcaption>Some layers are more sensitive to dynamic range/precision</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akNH6yUS0nYs3b28VQQqwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-e37sNKTtk3LKfkaAMvDnQ.png" /></figure><h3>8. LLM Internals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQNHmq9IILdy278lP1V_Dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*oigsgfB88oK9Zel1vCMjDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*ifHhMa3Hz0Zc9sUu5J0q_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*q51P75E6fcmnNJEAerOTPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_su5VxLUIp5ZP4NJm4hQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*wzW2Qsa5H0x3osMZ4mH2GA.png" /><figcaption>#number of parameters for llm training</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*0dkfgCjt0lwMN1se9wJ2rA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4iLxDNN5nBRqszI-XRdCQ.png" /><figcaption>#number of flops for llm training</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*PBJ0RbCV_cULGAe_ur9uJA.png" /></figure><h3>9. Scaling Law</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2FDZfaNNQ53yHNkdO77hQ.png" /></figure><p>Suppose, if we have a fixed compute budget (GPU hours which translates roughly to a fixed dollar budget), we can spend it in two ways — bigger model &amp; less data or smaller model &amp; more data. Both consume the same total compute (FLOPs) but produce models with very different final quality.</p><p>Earlier, OpenAI thought fore a fixed compute, one should mostly scae model size. But later Deepmind’s chinchilla paper (2022) found a flaw and the actual compute~optimal answer was different: model size and training tokens should scale roughly equally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9W3N-t_ay6hr6aE2l94mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEqe4fyiN4AJsyWUZPMTmw.png" /></figure><p>Scaling laws are the physics of ML — these are emperical fitted laws standing as proofs math cant yet provide. Now instead of trying new architecture trick and see if it works, researchers now run small controlled experiments, fit a law, and extrapolate to predict whether a much larger investment is worth it.</p><p><strong>BONUS: </strong>Because now we can predict that a 100 million dollar training run will produce a specific quality of model, the incentive to actually build the infra capable of running that job becomes very real and all the ML systems work (efficient training infra, distributed compute) is worth it.</p><h3>10. Serving &amp; Inferencing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMrYSPBYrPnGZpmeJj1nkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5heYxk66__j1mK_nrApdMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzIZJ8PDEQmnFCoT7KqfIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pW9xSirjCXTLX7_XPrxAg.png" /></figure><p>In single user interface (b=1), we care about latency. With s = 1, the GPU does almost no useful parallel work per step. Its heavily memory bandwidth bound, not compute bound. Also, we will be moving a lot of data to do very little compute per step, so the GPU is underutilised — most raw FLOPs go waste. That is exactly why speculative decoding was introduced (2022). It tries to amortize the memory moving cost by guessing several tokens AOT and verifying them in parallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFU1VZTWt3FARcrmLVObZw.png" /></figure><p>For large b, we care about throughput/cost per query. Batching many users decoder steps together, the single memory load of model weights gets amortised across many steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJlMhC6JEvju-7KUD8ScRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6YmQwQy1uVXoIb5IDgWpw.png" /></figure><p>Static batching has numerous issues (1) how do you batch seq of different length : <strong>pre-fill problem</strong>— different prompts have different length. (2) how to keep batch full : <strong>continuous batching</strong>— different requests finish at different time (3) <strong>paged attention/vLLM:</strong> handling KV cache growing linearly with batch size b.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5Ntk6CbrAESYdWvcnYLvg.png" /><figcaption>Keeping the GPU batch full and busy at all times</figcaption></figure><p>(1) In prefill, we process the full prompt in one forward pass, like training, just with different lengths handled via padding/packing. (2) Decoding generates tokens autoregressively, one at a time. During decode, the attention step completes by attending the new token’s query against all previously cached keys and values rather than recomputing them. The KV cache grows by one entry per layer at each decode step. Since each query must attend only to its own request’s KV cache, which differs in length per request, attention can’t be computed as one uniform matmul across the batch — it must be handled per-request, even though all requests run in the same step. MLP layers, by contrast, are sequence-agnostic: they apply the same weights independently to each token, so different requests can be stacked and batched freely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDGVImG1TnQv8Jdt8tmcDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PbkoPs4aH2OY6uFT3PpBJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1cpiTdTXbuumUbxwm7-dA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JmbPJYJcgXSbwHT7EKjCNg.png" /><figcaption>vLLMs splits each KV cache into fixed-size blocks eliminating fragmentation. <strong>Bonus</strong>: if multiple requests share common prefix, they can share same cache blocks.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36OIwCYUdnV4lu5bYNPUzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KqgJ2r4vqsMCAxacCAUwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TxXDGnmVQwymkLo8h43RXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ya1ilz8Qb0wMpzc9HU76MQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*soh9OAJASC2TTyU2j9clag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHuKQfpDPWyjD5dt_z5cvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JKm1NYoojr7yyaJnnP8ZPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhCmpOX6-G-dFDcIBTILBg.png" /><figcaption>Since <strong>FlashAttention</strong> makes attention IO-efficient, during backward we don’t store the full attention/softmax matrix. We only store the softmax normalization factors from forward, and recompute the needed attention blocks in backward.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtEUBa2bKsVdPDZ82jP-NA.png" /></figure><h3>11. Parallelisation</h3><p>From scaling laws, model kept growing in size.Now we cant even load frontier model onto one GPU, let alone train them. Moreover, from KV cache we saw GPU hitting memory boundaries leading to only 40–60% MFU. Thats why we need some form of model parallelism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_LRIDPpbSxA34fAzCmdQ4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJng7UmHfKFpKP3Cbj7coQ.png" /><figcaption>No way out but to parallelize these workloads !</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wp-5MjAiN77VajImk_NMiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVFg9vGFAtXieIsm4IVZCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aSIaPeGveZ1wfbj4DQyIHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fXAuysoZIJg1f-d2hVNyqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2yYRXSv4GmBmmT7gSsW4lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23tNwigG5MBna1XqNSKpBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52Um37qyapvp3aChonljQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVBBqmFlkwvFuwKjqLSw4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RqrWkHJsxcOe4G3TgOC-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ke7l9Dl_wPlx-IW8jqgBkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*580r_zv68pbD2Tz_j4xkBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5hYGiqqkvDv-mCBS6c5-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AnZPf8PYbT8bC4DabWScew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U42L8Cwk4oHZhoOlOPVHgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZuvx4gupJLseVreVGQXdA.png" /></figure><p>Models grew too big to fit on one GPU, so you must spread them across GPUs. The naive way (inter-op: different layers on different GPUs (InfiniBand)) wastes GPU time to idle. The smarter way (intra-op: split one layer across GPUs) keeps everyone busy but pays communication costs (NVLink) via all-reduce. Within intra-op, each operator has multiple valid split strategies depending on which loops you partition — spatial loops are free to split, reduction loops cost an all-reduce. Across a whole graph, you must pick strategies for all operators jointly to minimize total computation + communication including re-partition costs between operators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPkn0Rgh-fPbnJjwzauAIw.png" /></figure><p>Modern systems (Alpa, GSPMD, FlexFlow) automate this search — the same “expert craft → automated compilation”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhv9tZfNyd22N7sAwef37g.png" /><figcaption><strong>Tofu (UW):</strong> first paper to formally say “this is an optimization problem — minimize node costs + edge costs across the graph.”; <strong>FlexFlow (Stanford):</strong> expanded the strategy space and used randomized search <strong>; GSPMD (Google):</strong> compiler-based approach</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8R3U55XXJs2ttkvJ6cewsg.png" /><figcaption>first time anyone hand-split a model across GPUs.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3u1MKgK_7fL2k17VlWrNg.png" /><figcaption>hand-designed tensor parallel strategy specifically for transformers.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJilztJQbnvaPm6tnu27Fw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmRT9h6ZNeJVRcI1r3xQMQ.png" /><figcaption><strong>ZeRO</strong> (Microsoft, 2020) solves this differently: instead of splitting the <em>computation</em>, split the <em>storage</em>. Shard optimizer states, then gradients, then parameters across GPUs.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*01bUKlB_K1ahcFE89Z19XQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKOxU-RCbGoN-oWaIAGGWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjZkvL-woYHpKRwTIWpmBg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73c4757ac981" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attention Based Interpretability With Concept Transformer]]></title>
            <link>https://medium.com/@ksheer.agrawal/attention-based-interpretability-with-concept-transformer-bcac21d50646?source=rss-4502a438fcdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcac21d50646</guid>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[interpretability]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ksheer Sagar Agrawal]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 22:58:06 GMT</pubDate>
            <atom:updated>2026-06-06T23:00:56.342Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>With the rise of deep neural networks, understanding model decisions has become increasingly important, especially in high-stakes domains. This article explores <em>Attention-Based Interpretability with Concept Transformers</em> by Rigotti et al. (IBM Research, 2022). While transformers have driven recent advances in deep learning, attention over low-level features is difficult for humans to interpret. The paper introduces a transformer layer that provides explanations through human-defined concepts. Instead of linking predictions to low-level artifacts, the model aligns its reasoning with concepts used by domain experts, emphasizing interpretability by design.</p><h3>Background and Related Work</h3><p>Concept Transformers build on the traditional transformer architecture. In transformers, tokens interact through self-attention. Each token is mapped to learned key, query, and value representations, allowing it to attend to other tokens in the sequence. Attention scores are computed using scaled dot products between queries and keys, producing weighted representations of the input. Multi-head attention enables the model to capture different relationships between tokens.</p><p>Interpretability concerns understanding why a model produces a prediction. Two key properties are plausibility and faithfulness. Plausibility measures whether an explanation is understandable to humans, while faithfulness measures whether it accurately reflects the model’s decision process.</p><p>Most post-hoc interpretability methods analyze trained models using techniques such as activation maximization or saliency visualization. However, these explanations may not faithfully represent the model’s reasoning. Attention-based approaches improve transparency but still rely on low-level features that are difficult for humans to interpret. Concept-based methods, such as TCAV (Kim et al., 2018) and ProtPNet (Chen et al., 2019), address this issue by incorporating human-understandable concepts. Concept Transformers extend these ideas by integrating concepts directly into the architecture, providing explanations that are both interpretable and faithful by design.</p><h3>Approach</h3><p>To achieve inherent interpretability without sacrificing performance, we replace the standard classification head of a Deep Learning architecture (such as a CNN or ViT) with the Concept Transformer (CT) module. This module generates cross-attention between the input features and a learned set of embeddings representing domain-relevant concepts.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sqdijRJVE3PoS7D8.png" /></figure><h3>Feature and Concept Representation</h3><p>An input image is processed by a backbone network and divided into P patches represented as X ∈ ℝ^(P × dᵢₙ) represent this sequence of image patches. We also define C domain-relevant concepts with embeddings E ∈ ℝ^(C × dₑ).</p><h3>Learning the Query, Key, and Value Projections</h3><p>We project both image features and concepts into a shared latent space of dimension dₘ via learned weight matrices.</p><p><strong>Projecting the Queries (Q):</strong> We project image patches X using a learned weight matrix W_Q ∈ ℝ^(dᵢₙ × dₘ):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/0*M4U7iU0B0xCzLFK7.png" /></figure><p><strong>Projecting the Keys (K) and Values (V):</strong> We project concept embeddings E using two separate learned matrices Wₖ and Wᵥ (both ∈ ℝ^(dₑ × dₘ)):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/0*3fExn99W41r1ztMJ.png" /></figure><h3>The Cross-Attention Mechanism</h3><p>The core of the CT is the cross-attention computed between the input patches (Q) and the concepts (K). This generates an attention map A defining the relationship between every spatial patch and every concept:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*hGaJVp6jlXDg-nvf.png" /></figure><p>Let A = [αₚ꜀], where αₚ꜀ is the attention weight of the p-th patch to the c-th concept.</p><h3>Interpretable Logits and Class Probabilities</h3><p>The output is obtained by multiplying A, the value matrix V, and an output projection O ∈ ℝ^(dₘ × n꜀). Averaging over all P patches, the raw logit for class i is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*mVdY9l07B2q3a2d0.png" /></figure><p>To understand <em>why</em> the model made a prediction, we decompose this logit into two interpretable components:</p><p><strong>Concept Relevance Score γ꜀(x):</strong> How relevant concept c is to the input image x, averaged over all patches:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*q8ybr5nmnr2XbA_J.png" /></figure><p><strong>Class Component Value (β꜀)ᵢ:</strong> How much concept c contributes to class i:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/0*fpiTc9pmCU-8QZhR.png" /></figure><p>Substituting these, we get a strictly linear relationship for the logit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*tv9TVIMV9UXfwFFZ.png" /></figure><p>This linearity is key — the explanation is exactly the computation used to make the decision, satisfying the technical definition of <strong>faithfulness</strong>.</p><p>Finally, applying Softmax across all n꜀ classes gives the predicted probability for class i:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*Q6BDbktG9ytQFP3N.png" /></figure><p>Because the exponential is strictly increasing, a higher logit always guarantees a higher probability.</p><h3>Injecting Domain Knowledge: The H Matrix</h3><p>To align attention with human reasoning, the model uses a ground-truth attention target H∈ ℝ^(P × C) derived from spatial annotations. Patches inside a concept’s region are assigned 1, and all others 0. During training, the difference between (A) and (H) is penalized using the Frobenius norm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*Xg6uok9jmHQ1ZkUa.png" /></figure><p>The final loss is a weighted sum of classification loss and explanation loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*Ecg6GYzN5JU_35MM.png" /></figure><p>The hyperparameter λ controls the trade-off between predictive accuracy and alignment with human annotations.</p><h3>Experiments and Setup</h3><h3>Reproducing the Paper</h3><p>We focused on reproducing results for the MNIST even/odd and CUB-200–2011 datasets using the authors’ GitHub repository. For MNIST, we targeted Figure 2 (training samples vs. test accuracy for λ=0 and λ=2) and Figure 3 (correct/incorrect prediction examples). For CUB-200–2011, we reproduced the end-to-end training accuracies from Table 1, where Concept Transformers achieved 87.6–88.4% accuracy.</p><h3>Challenges</h3><p>Reproduction was complicated by outdated dependencies requiring older library versions incompatible with modern GPU architectures. We evaluated reproduction quality both quantitatively (accuracy trends) and qualitatively (concept-based explanations).</p><h3>Additional Experiments</h3><p>To address compatibility issues, we modernized the software stack for better reproducibility on platforms like Google Colab and DataHub. We also conducted hyperparameter studies (learning rate, epochs, batch size), evaluated using accuracy on CUB-200–2011 and loss curves on MNIST.</p><h3>New Ideas</h3><p>We explored the interpretability–performance trade-off by applying top-k sparsity (k ∈ {1, 3, 5}) over concept attention at inference time, hypothesizing that restricting attention to fewer concepts yields more concise explanations with minimal accuracy loss.</p><h3>Evaluation</h3><h3>Accuracy</h3><p>Test accuracy across different k values</p><h3>Interpretability</h3><p>Number of active concepts per prediction.</p><h3>Setup</h3><p>To reproduce the released implementation, we updated deprecated dependencies and training-framework APIs to support current PyTorch and PyTorch Lightning versions while preserving the original ConceptTransformer architecture.</p><p>Our top-k analysis was performed only at inference time. Using the trained model, we replaced dense concept attention with a sparse evaluation path that retains only the k highest-scoring concepts, masks the rest before softmax, and evaluates accuracy using the original learned weights without retraining.</p><pre>scores = (q @ k.transpose(-2, -1)) * self.scale<br>shared_mask = topk_mask_from_scores(scores.mean(dim=1), self.top_k)<br>scores = scores.masked_fill(~shared_mask.unsqueeze(1), float(&quot;-inf&quot;))<br>attn = scores.softmax(dim=-1)</pre><p>This design keeps the dense model as the baseline, ensuring that top-k accuracy changes result from restricting concept evidence during evaluation rather than retraining.</p><p>Implementation details, setup instructions, dataset preparation steps, and evaluation scripts are available in our GitHub repository:</p><p><strong>GitHub:</strong><a href="https://github.com/bhavyagupta98/concept_transformer"> https://github.com/bhavyagupta98/concept_transformer</a></p><h3>Reproducing the Reported Outputs</h3><p>Complete setup instructions, dataset preparation steps, and checkpoint paths are provided in README_VM.md (Linux setup) and README_COLAB.md (Google Colab setup).</p><h3>Guide for first-time VM/instance setup (GPU), downloading datasets separately, and running experiments</h3><p>Prerequisites:</p><pre>1) Linux / macOS or any VM with GPU drivers installed<br>2) CUDA runtime matching PyTorch (recommended: CUDA 11.8 for this repo&#39;s wheels)<br>3) git, python3 (3.10+), python3-venv, pip<br>4) curl and unzip for downloading/extracting datasets (install via apt-get install curl unzip on Linux)</pre><p><strong>Step 1: Clone the Repo</strong></p><pre>git clone https://github.com/bhavyagupta98/concept_transformer.git<br>cd concept_transformer</pre><p><strong>Step 2: Create &amp; Activate Virtual Environment</strong></p><pre>python3 -m venv venv<br>. venv/bin/activate<br>pip install - upgrade pip<br>pip install - no-cache-dir -r requirements.txt</pre><p>Verify the venv is active (you should see (venv) in your shell prompt).</p><p><strong>Step 3: Prepare Datasets</strong></p><p>Create a workspace data directory (persistent location for all datasets):</p><pre>mkdir -p /workspace/data<br>cd /workspace/data</pre><p><strong>Option A: Automatic download (MNIST only)</strong></p><p>If you only need MNIST (quick smoke test):</p><pre>. venv/bin/activate # Ensure venv is active<br>cd concept_transformer<br>sh scripts/setup.sh</pre><p>This automatically downloads MNIST to /root/data/mnist/.</p><p><strong>Option B: Download &amp; extract CUB dataset using curl</strong></p><p>For CUB dataset, download and extract manually:</p><pre>Install dependencies (if not already installed):<br># Linux (Ubuntu/Debian)<br>apt-get update<br>apt-get install -y curl unzip<br># macOS<br>brew install curl unzip # Usually pre-installed</pre><p>Download the CUB-200–2011 dataset and extract:</p><pre>cd /workspace/data<br># If download is already a .tgz file:<br>curl -L -o CUB_200_2011.tgz \<br>&quot;https://data.caltech.edu/records/65de6-vp158/files/CUB_200_2011.tgz&quot;</pre><pre>tar -xzf CUB_200_2011.tgzcurl -L -o segmentations.tgz \<br>&quot;https://data.caltech.edu/records/w9d68-gec53/files/segmentations.tgz&quot;tar -xzf segmentations.tgz<br># You should now have: /workspace/data/CUB_200_2011/ls /workspace/data/CUB_200_2011/ # Should see: images/, attributes/, parts/, *.txt files</pre><p>Verify extraction:</p><pre>ls -la /workspace/data/CUB_200_2011/ # Should see: images/, attributes/, parts/, *.txt files</pre><p><strong>Step 4: Run Experiments</strong></p><p>Always activate the venv first:</p><pre>cd /path/to/concept_transformer<br>. venv/bin/activate</pre><p><strong>To run top_k with MNIST and CUB:</strong></p><pre>#MNIST<br>cd /workspace/concept_transformer<br>source venv/bin/activate<br>python run_topk_phase1_mnist.py - run_path mnist_ctc/ExplanationMNIST_expl5.0/binary_mnist_best_ckpt.ckpt - k_values 1,3,5<br>#CUB<br>cd /workspace/concept_transformer<br>source venv/bin/activate<br>python run_topk_phase1_cub.py - run_path ./cub_cvit/CUB2011Parts_expl1.0/binary_mnist_best_ckpt.ckpt - k_values 1,3,5 - data_dir /workspace/data/ - batch_size 16</pre><p><strong>Figure 2 + Example Images (Wrong/Right)</strong></p><p>These outputs are generated by scripts/generate_figures.py. Create the output directory first:</p><pre>mkdir -p /workspace/data/figs</pre><p>Wrong/Right example images (MNIST)</p><pre>cd /workspace/concept_transformer<br>. venv/bin/activate<br>PYTHONPATH=/workspace/concept_transformer python scripts/generate_figures.py \<br> - run_path ./mnist_ctc/ExplanationMNIST_expl5.0/ \<br> - output_dir /workspace/data/figs</pre><p>Example outputs:</p><pre>/workspace/data/figs/correct_0_idx0.png<br>/workspace/data/figs/wrong_0_idx151.png</pre><p><strong>Figure 2 (two-panel scaling plot)</strong></p><p>If you already have scaling checkpoints under /workspace/concept_transformer/binary_mnist_scaling_ES/, rebuild the JSON and plot:</p><pre>cd /workspace/concept_transformer<br>. venv/bin/activate<br>mkdir -p /workspace/concept_transformer/experiments</pre><pre>PYTHONPATH=/workspace/concept_transformer python scripts/rebuild_scaling_json.py \<br> - runs_root /workspace/concept_transformer/binary_mnist_scaling_ES \<br> - output_json /workspace/concept_transformer/experiments/binary_mnist_scaling_ES.json</pre><pre>PYTHONPATH=/workspace/concept_transformer python scripts/generate_figures.py \<br> - skip_examples \<br> - scaling_json /workspace/concept_transformer/experiments/binary_mnist_scaling_ES.json \<br> - output_dir /workspace/data/figs \<br> - scaling_lambdas 0.0,2.0</pre><p>Expected output:</p><pre>/workspace/data/figs/figure2.png</pre><p>If scaling checkpoints are unavailable, run the full scaling experiments first. This requires approximately 8 hours on an NVIDIA A10 and launches 80 training runs: 2 values of expl_lambda (0.0, 2.0), 20 training-set sizes (100–10,000 samples), and 2 random seeds (4 and 5).</p><pre>cd /workspace/concept_transformer<br>. venv/bin/activate<br>mkdir -p /workspace/concept_transformer/experiments</pre><pre>PYTHONPATH=/workspace/concept_transformer python run_mnist_scaling_experiments.py</pre><p>Then plot Figure 2 from the generated JSON:</p><pre>PYTHONPATH=/workspace/concept_transformer python scripts/generate_figures.py \<br> - skip_examples \<br> - scaling_json /workspace/concept_transformer/experiments/binary_mnist_scaling_ES.json \<br> - output_dir /workspace/data/figs \<br> - scaling_lambdas 0.0,2.0</pre><h3>Concept Transformer — Colab Implementation Guide</h3><p>Refer to Colab_Concept_Transformer.ipynb and execute all cells. We recommend using an A100 or G4 GPU, as execution can be slow on lower-end hardware.</p><p>These workflows reproduce all reported results: MNIST scaling and explanation examples from the original paper, CUB evaluations demonstrating the impact of concept supervision and generating explanation visualizations, and our top-k experiments measuring the accuracy–sparsity tradeoff.</p><h3>Results</h3><h3>Original Paper Results: What We Tried to Reproduce</h3><p>We use the original ConceptTransformer results as reference points for our reproduction. The paper reports approximately 99% accuracy on MNIST and improves CUB accuracy from 76.9 ± 3.0% to 88.0 ± 0.4% with concept supervision. Our section focuses on MNIST and CUB because aPY was not accessible, then extends the analysis with an inference-time top-k concept-attention experiment.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t2fOK1q3A44ysMeb.png" /></figure><p>Original paper results used as reproduction targets.</p><h3>Quantitative Reproduction: Recovering the Main Trends</h3><p>We first reproduce the MNIST scaling experiment to test whether explanation supervision improves concept alignment. We compare models without explanation supervision, λ_expl = 0.0, and with explanation supervision, λ_expl = 2.0.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*OrRAT_WJUEJkFBMe.jpeg" /></figure><p>Reproduced MNIST scaling analysis with and without explanation supervision.</p><p>The reproduced MNIST curves show that both models approach approximately 99% accuracy, but explanation supervision gives much lower explanation loss. This shows that similar accuracy does not necessarily imply equally meaningful concept alignment.</p><p>We next compare our reproduced accuracies with the paper’s reported results. MNIST closely matches the paper’s approximately 99% accuracy, while CUB is lower in absolute accuracy but still shows the key effect of concept supervision.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E-orfoB4ryYL7tiN.png" /></figure><p>Original vs reproduced test accuracy.</p><p>We recover the central trend: concept supervision improves CUB accuracy from 74.03% to 83.57%, a gain of 9.54 percentage points. This shows that concept supervision provides useful learning signals for fine-grained classification, not just interpretable evidence.</p><h3>Qualitative Explanations: Successes and Failures</h3><p>Accuracy alone does not show whether the model uses meaningful concepts, so we inspect individual MNIST and CUB predictions. On MNIST, the correct example aligns with the intended digit concept, while the error case exposes digit-concept confusion behind the parity mistake.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-iSLt3dctXGl2y04.png" /></figure><p>MNIST concept explanation examples.</p><p>CUB is harder because bird species recognition depends on multiple global and localized attributes. In the correct example, the model highlights meaningful color and body-part concepts for Black-footed Albatross. In the error example, the same species is predicted as Sooty Albatross because attention shifts toward darker attributes.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lmVxaHasAspMwVBW.png" /></figure><p>Correct CUB explanation example.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yaLHhA-mSWG1lMdk.png" /></figure><p>Incorrect CUB explanation example.</p><p>Together, these examples show that concept attention helps diagnose model behavior: MNIST errors reveal digit-concept confusion, while CUB errors reveal shifts toward misleading visual attributes.</p><h3>Additional Experiment: Inference-Time Top-k Concept Attention</h3><p>The original paper shows that concept attention can explain predictions, but not how many concepts are needed to preserve accuracy. We test this with an inference-time top-k experiment: keep only the k highest-scoring eligible concepts, mask the rest, and compare against the dense model.</p><p>For MNIST, masking is applied over ten digit concepts. For CUB, masking is applied only over thirteen global concepts, while spatial attention remains unchanged.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HlK1VOxE2DbRHOFf.png" /></figure><p>MNIST accuracy under inference-time top-k concept attention.</p><p>MNIST is robust to sparsity: top-3 keeps only three digit concepts while matching dense accuracy.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UQSa_2a1UWI2fOJy.png" /></figure><p>CUB top-k global concept accuracy.</p><p>CUB behaves differently: aggressive pruning hurts accuracy, with top-1 dropping to 15.15% and top-3 reaching only 65.12%. Accuracy improves as more global concepts are retained, with top-8 reaching 81.08%.</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6Cf-q5NV5YmEsrFh.png" /></figure><p>Accuracy vs retained concept fraction.</p><p>The top-k experiment shows that sparse concept attention is task-dependent. MNIST relies on a few dominant concepts, whereas CUB requires multiple complementary attributes. Explanations should therefore be concise, but not maximally sparse.</p><h3>Limitations and Reproduction Challenges</h3><p>Our analysis has three main limitations. We could not reproduce aPY because the dataset was not accessible. Our CUB accuracy remains below the paper’s reported score, although it recovers the same improvement trend. Finally, the top-k experiment is inference-time only, so it does not train a sparse model or demonstrate faster inference.</p><h3>Discussion, Strengths and Weaknesses</h3><p>Overall, the results show that ConceptTransformer is strongest when its concept structure matches the task. Its main strength is that explanations are built into the model rather than added after prediction, so concept relevance scores are directly tied to the decision process. However, the method depends on predefined concepts and concept-level supervision, which may limit scalability when useful concepts are unknown or difficult to label. This suggests that concept-based explanations are most useful when the concept vocabulary is meaningful, available, and aligned with the task.</p><h3>Conclusion</h3><p>Our reproduction supports the paper’s central claim that concept supervision can improve concept alignment and predictive performance. MNIST closely matches the original result, and CUB recovers the main improvement trend with a 9.54 percentage point gain from concept supervision. Our top-k extension shows that sparse concept attention is task-dependent: explanations should be concise when possible, but not at the cost of removing evidence needed for reliable prediction.</p><h3>References</h3><p>• Mattia Rigotti, Christoph Miksovic, Ioana Giurgiu, Thomas Gschwind, and Paolo Scotton. “Attention-based Interpretability with Concept Transformers.” ICLR 2022. <a href="https://openreview.net/forum?id=kAa9eDS0RdO">https://openreview.net/forum?id=kAa9eDS0RdO</a></p><p>• Ankit Gupta, Guy Dar, Shaya Goodman, David Ciprut, and Jonathan Berant. “Memory-efficient Transformers via Top-k Attention.” SustaiNLP 2021, pp. 39–52. <a href="https://aclanthology.org/2021.sustainlp-1.5/">https://aclanthology.org/2021.sustainlp-1.5/</a></p><p>• Di Xiu, Hongyin Tang, Bolin Rong, Lizhi Yan, Jingang Wang, Yifan Lu, and Xunliang Cai. “A Preliminary Study on the Promises and Challenges of Native Top-k Sparse Attention.” arXiv preprint arXiv:2512.03494, 2025. <a href="https://arxiv.org/abs/2512.03494">https://arxiv.org/abs/2512.03494</a></p><p>• Kim, B., Wattenberg, M., Gilmer, J., Cai, C., Wexler, J., Viegas, F., and Sayres, R. “Interpretability beyond feature attribution: Quantitative testing with concept activation vectors (tcav)”. arXiv:1711.11279, 2018. <a href="https://arxiv.org/abs/1711.11279">https://arxiv.org/abs/1711.11279</a></p><p>• Chen, C., Li, O., Tao, C., Barnett, A. J., Su, J., and Rudin, C. “This looks like that: Deep learning for interpretable image recognition”. arXiv:1806.10574, 2019. <a href="https://arxiv.org/abs/1806.10574">https://arxiv.org/abs/1806.10574</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcac21d50646" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Deep Learning Part -4]]></title>
            <link>https://medium.com/@ksheer.agrawal/understanding-deep-learning-part-4-ec9319f0c0f5?source=rss-4502a438fcdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec9319f0c0f5</guid>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[normalizing-flow]]></category>
            <category><![CDATA[gans]]></category>
            <dc:creator><![CDATA[Ksheer Sagar Agrawal]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 00:53:58 GMT</pubDate>
            <atom:updated>2026-01-23T00:53:58.002Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous <a href="https://medium.com/@ksheer.agrawal/understanding-deep-learning-part-3-69a5401f3398">part</a>, we explored transformers and their applications in NLP and computer vision. In this part, we focus on <strong>unsupervised learning</strong>, where models learn patterns from data without labels. A key application of this paradigm is <strong>generative modeling</strong>, which enables machines to create new data that resembles the real world.</p><pre>Learning paradigms<br> ├── Supervised        → classical + deep<br> ├── <strong>Unsupervised</strong>      → classical + <strong>deep</strong><br> ├── Self-supervised   → mostly deep<br> ├── Semi-supervised   → classical + deep<br> ├── Weak supervision  → classical + deep<br> ├── Reinforcement     → classical + deep (Deep RL)<br> ├── Online learning   → classical + deep<br> └── Transfer learning → mostly deep</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLCbyPpcxERyso57pyQLLw.png" /></figure><p>Unsupervised learning refers to learning without labels and focuses on characterising the distribution of the data. Generative modelling is primarily about learning a mapping between the observed input x and latent variables z.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ue4v2zKSV15elovibKkfqA.png" /><figcaption>There are four major types of generative models: <strong>GANs</strong>, <strong>VAEs</strong>, <strong>normalizing flows</strong>, and <strong>diffusion models</strong>.</figcaption></figure><p>These models are considered good if they can generate sampled data that looks like real data, cover a wide variety of training examples, have a disentangled latent space (where changing each latent variable corresponds to an interpretable property of the data), and can accurately compute the likelihood of new examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kn0yTxaytGIypk2V3-3qng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*Kvgi2eWPqzcoRTUprCwNOQ.png" /><figcaption>Common quantitative measures of performance include test likelihood, Inception Score (diversity), Fréchet Distance, and manifold precision/recall (realism and diversity).</figcaption></figure><h3>GANs</h3><p>GANs consist of two networks trained jointly:</p><ul><li>A <strong>Generator</strong> that maps latent noise z to generated samples</li><li>A <strong>Discriminator</strong> D that classifies samples as real or fake</li></ul><p>Training is formulated as a <strong>minimax game</strong>, where the generator tries to fool the discriminator while the discriminator learns to distinguish real from generated data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBwHEowEJfFFHR12H-YNyw.png" /></figure><h4>Conditional GANs</h4><p>Standard generative models produce realistic samples but do not allow explicit control over attributes. <strong>Conditional generative models</strong> address this by conditioning generation on auxiliary information (e.g., class labels), making them far more useful in practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUGek342xwtGgSuFR4n6pw.png" /></figure><h4>Image Translation</h4><p>Although adversarial discriminators were introduced with GANs for unconditional generation, they are also widely used in <strong>image-to-image translation</strong> tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-urgvhqyWl-rePQifA-NUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGLm9PDcaKs1qAI6qkpLtg.png" /><figcaption>(a) Pix2Pix maps one image c to a different style image x. The discriminator tries to distinguish whether before/after pairs in an image translation tasks were plausible. (b) SRGAN discriminator distinguishes between upsampled vs real high resolution image.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zz_Sq6PWtubKAeksRNevcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*7zFticphGP7PmFUPym-70Q.png" /><figcaption>(a) In absence of before/after labelled images — Cycle GANs exploits the situation that converting an image in one direction and then back again should recover the signal. (b) StyleGAN is a more contemporary GAN, it controls the output image at different scales and separates style from noise; the closer these random variables are to the output, the finer scale details they represent.</figcaption></figure><h3>Normalising Flows</h3><p>In GANs, we do not explicitly define a probability distribution over data samples. In <strong>normalizing flows</strong>, we define a <strong>simple base distribution</strong> and learn an <strong>invertible mapping</strong> that transforms it into a complex data distribution. This mapping is reversible and learned using neural networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*nj03pkAX1nDo88GGBomeJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jy4pW8Y6PFes3KY9w_SRMg.png" /><figcaption>The <strong>inverse (normalizing) direction</strong> maps data to latent variables and enables likelihood computation.</figcaption></figure><h4>Coupling Flows</h4><p>For structured data such as images, channels are split into two parts. One part remains unchanged while the other is transformed, with permutations (e.g., 1×1 convolutions) applied between layers to increase expressivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STV8jAofsWjqZiwcAGriqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mseOmjGgTiZCZJhS1NTjvg.png" /><figcaption>(a) non-linear flows (b) coupling flows</figcaption></figure><h4>Autoregressive Flows</h4><p>Autoregressive flows generalize coupling flows by treating each dimension as a separate block. The transformation functions <em>g</em> are called <strong>transformers</strong>, and the parameter-generating networks <em>ϕ </em>are called <strong>conditioners</strong>. If both are sufficiently expressive, autoregressive flows are <strong>universal density approximators</strong>. Using masking, the forward (normalizing) direction can be computed in parallel; however, inversion (sampling) is sequential and slow.</p><h4>Inverse Autoregressive Flows (IAF)</h4><p>Inverse autoregressive flows reverse the computational trade-off of masked autoregressive flows (MAF). They are <strong>difficult to train using likelihood</strong>, but enable <strong>fast parallel sampling</strong>, whereas MAFs are easy to train but slow to sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytNuTt4EJ2HUYoI_wtK4PA.png" /><figcaption>autoregressive flows</figcaption></figure><h4><strong>Residual Flows</strong></h4><p>Residual flows are more parallelizable than autoregressive flows because their inverse does not require sequential, dimension-by-dimension computation. However, this comes at the cost of <strong>expensive Jacobian determinant estimation</strong> and <strong>strict Lipschitz constraints</strong>, which can reduce expressivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcshO2ktgCuuKmXTYeSs5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GS2vbR3K3_UMYtRKFR9Nw.png" /><figcaption>(a) residual flows (b) contraction mapping</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iE9CroBJlMevmX2eU0YWA.png" /><figcaption>Multiscale architectures factor out variables at different resolutions, improving both <strong>density estimation efficiency</strong> and <strong>sampling speed</strong>.</figcaption></figure><h4>Applications of Normalizing Flows</h4><p><strong>Density modeling (explicit likelihood):</strong> learning an exact probability density.</p><p><strong>Synthesis / generation (sampling):</strong> generating new data samples from latent noise.</p><p><strong>Approximating / distilling other density models:</strong> e.g., distilling an autoregressive model using IAF for faster sampling and generation</p><h3>Variational Autoencoders</h3><p>VAEs use an indirect approach to describe a probablity distribution using latent variables. Unlike normalising flows, VAEs approximate posterior and optimise a lower bound on the likelyhood.</p><p>Unlike VAEs, normalizing flows use an invertible transformation that allows exact likelihood computation, whereas VAEs rely on an approximate posterior and optimize a lower bound on the likelihood — pθ(x).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaAmDktCtUlJMbZDo04GQA.png" /><figcaption>We can’t compute pθ(z∣x) because it is intractable.</figcaption></figure><p>In normalising flows, we forced invertibility to make the likelihood tractable. VAEs give up invertibility for flexibility and use approximations instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8xGWMKAp8enfeTIkiljDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNMEQv2c7whMsENzSLeD6Q.png" /></figure><p>We approximate the intractable posterior by choosing a chosing a <strong>variational posterior distribution q(z∣x;θ)</strong> and learning the member of that family that minimizes KL divergence to the true posterior.</p><p>Since the log-likelihood of the data — is intractable to compute in latent-variable models like VAEs, we use a lower bound to optimise. Once we do this, Jensen’s inequality gives us a lower bound on the log-likelihood, called the Evidence Lower Bound (ELBO). Maximizing the ELBO serves two purposes at the same time — First, because the ELBO is a lower bound on the log-likelihood, increasing it also increases a guaranteed lower limit on how well the model explains the data. Second, the gap between the true log-likelihood and the ELBO is exactly the KL divergence between the variational distribution and the true posterior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nad26IxSw0vzmNPevLh1ug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Gb_o-xNYKlIFtf72N5PEA.png" /><figcaption>The act of maximizing the ELBO is what simultaneously improves the generative model and learns the best possible approximation to the intractable posterior within the chosen family of distributions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTsNMY6Sy-fvWrtTSwbYyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlnMaFXD5BwzpiiBULtz0g.png" /><figcaption>VAEs generate new data by sampling a latent variable from a learned distribution and decoding it into data space through a probabilistic decoder. One trick to improve generation quality is to use aggregated posterior.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRcaVONAUPruLwKbs1kOUQ.png" /><figcaption><strong>Resynthesis: </strong>Beyond pure generation, VAEs are also useful for modifying existing data, a process known as resynthesis.</figcaption></figure><p>Once data points are represented in latent space, we can analyze how semantic properties correspond to directions in that space. To modify an image, we encode it into latent space and then add or subtract these semantic direction vectors. VAEs aim to learn latent representations where different dimensions correspond to independent, interpretable factors of variation in the data. To encourage <strong>disentanglement</strong>, researchers add additional regularization terms to the training objective.</p><h3>Diffusion Models</h3><p>Like VAE’s, diffusion models approximates the data likelihood using a lower bound. Like normalising flows, there is a non-linear mapping from latent variable to the observed data. However, in diffusion models, the decoder is fixed. The goal is to learn a decoder model, that is inverse of this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C1Srzq2zbUIb1v9rxJ14dg.png" /><figcaption><em>Diffusion models.</em></figcaption></figure><p>The diffusion forward pass (<strong>encoder/mixing process</strong>) maps a data example x through a series of interim variables z1,z2..,zT. The <strong>diffusion kernel </strong><em>q(zt|x)</em><strong> </strong>trains the <strong>decoder </strong>(reverse process) to invert this process. There is a closed-form expression for q(zt|x), which allows us to directly draw samples zt given initial data point x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9t-Md9Rv-xhN3KHKjlPdmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNNqm7JsmtrPcLXwV3kVvw.png" /><figcaption><em>The loss function can be used to train a network for each diffusion time step</em></figcaption></figure><h4>Applications</h4><p>Diffusion models only assume that noisy images look like “original image + Gaussian noise.” Because of this, we can design many different ways to add and remove noise without changing the training loss. Some of these ways let us skip steps or remove randomness during sampling, which dramatically speeds up image generation. Models like DDIM exploit this by using fewer, deterministic steps while keeping high image quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdWUIavzMLitiPXcXRJV8A.png" /></figure><h4>Conditional Generation</h4><p>Conditional diffusion steers the denoising process toward a desired class or prompt, either by using an external classifier to bias sampling (<strong>classifier guidance</strong>) or by training the diffusion model itself to handle both conditional and unconditional generation (<strong>classifier-free guidance</strong>), allowing controllable trade-offs between diversity and quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*5Jfzh-Tw7kT5KgBF443uXw.png" /></figure><h4>Improving generation quality</h4><p>High-quality diffusion image generation comes from combining careful step-wise variance prediction, optimized noise schedules, progressive cascaded generation for high resolution, and conditional guidance (class or text), allowing the same model to produce realistic, diverse, and controllable images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zw1dkTHyFfc0VeBLh-JP1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*KqAjK9Ql0u32LOZ1MfOuQQ.png" /></figure><p>Parts of the texts are taken from : <a href="https://udlbook.github.io/udlbook/">https://udlbook.github.io/udlbook/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec9319f0c0f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Deep Learning Part -3]]></title>
            <link>https://medium.com/@ksheer.agrawal/understanding-deep-learning-part-3-69a5401f3398?source=rss-4502a438fcdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/69a5401f3398</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Ksheer Sagar Agrawal]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 03:37:15 GMT</pubDate>
            <atom:updated>2026-01-10T03:37:15.082Z</atom:updated>
            <content:encoded><![CDATA[<p>Like in the previous part, CNNs and RNNs were widely used in computer vision. We are now exploring <strong>transformers</strong>, which were initially targeted at NLP problems, but have since become state-of-the-art across many domains, including computer vision. Consider this article a revision read rather than ground-up learning.</p><pre>Learning paradigms<br> ├── <strong>Supervised </strong>       → <strong>classical + deep</strong><br> ├── Unsupervised      → classical + deep<br> ├── <strong>Self-supervised   → mostly deep</strong><br> ├── Semi-supervised   → classical + deep<br> ├── Weak supervision  → classical + deep<br> ├── Reinforcement     → classical + deep (Deep RL)<br> ├── Online learning   → classical + deep<br> └── <strong>Transfer learning</strong> → <strong>mostly deepwwww</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7oCkQagekR-XQd1rhREy1A.png" /></figure><h3>Processing Text Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqsb02P9P-D2v97PCqzC7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phJlV6Li8DQhSd2snwejOw.png" /><figcaption>a model for processing text will (i) use parameter sharing to cope with long message (ii) contain connections between word representations that depend on the word itself.</figcaption></figure><h3>Self Attention</h3><p>A self attention block takes n-inputs of dimension D and returns N output of dimension D. A set of values are computed for each input word / word fragment. The nth outpur of self attention block is a weighted sum of these values v1,v2..vn. The scalar weight a[xm, xn] is the attention that the nth output pays to the input xn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nwxa3OcO2qo9hf1zeZAIPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_fHTozYkAz6dQr1V-puwEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1QyGvkRtwM7qhMfJfZTqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9K9u9KpJ80IFCtakPYkDw.png" /><figcaption>Dot product = measure of similarity</figcaption></figure><h3>Positional Encoding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i62qjyCqcjiaRwiK6lyiVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RLmJ1dj3Ho3Po4O39lJJw.png" /><figcaption><em>The input to a self-attention mechanism may be an entire sentence, many sentences, or just a fragment of a sentence and positional encoding pi.</em></figcaption></figure><h3>Multi Head Self Attention</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzXDNeGgM39WbY19f2Wvfg.png" /><figcaption>In multihead, H different sets of keys, values and queries are generated. Multiple heads seem to be necessary to make attention work well. (generalise)</figcaption></figure><h3>Transformer Layers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8IPmiSqVYhyFcJyQTvP1Ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kih4FEps42XbUo83juxOhQ.png" /><figcaption><em>The input consists of a the D-dimensional word embeddings for each of the N input tokens. The output is a matrix of the same size.</em></figcaption></figure><h3>NLP Pipeline</h3><p>An NLP pipeline starts with a tokenizer that splits the text into words or word fragment, then each of these tokens is mapped to a word embedding. These embeddings are passed through a series of transformer layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22CC1QL4yTHcVOyddLgU5g.png" /><figcaption>sub-word <strong>tokenizer</strong>; this splits the texts into small constituent units (tokens) from a vocabulary of possible tokens.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kv8guyfG7upHWkFyg1OOIQ.png" /><figcaption>The input embedding matrix X contains N embeddings of length D is created by multiplying a matrix — embeddings for the entire vocabulary with a matrix T — one-hot vectors that correspond to the word indices.</figcaption></figure><h3><em>Transformer model</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_pMUJvTEg-JsguDvd_0ow.png" /><figcaption>Encoder transforms the text embedding into a representation that can support a varity of tasks, decoder predicts the next token to continue the input, encoder-decoder are used in seq-seq tasks where one string is converted into another.</figcaption></figure><h3>BERT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSysA0VZWg57QeNnMYeY6g.png" /><figcaption><strong>Pretraining</strong>: In BERT-like encoder, the network is trained using self-supervision. <em>Predicting missing words forces the transformer network to understand some syntax.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yF9Oa9HzfxJ5NWvJZpnV_A.png" /><figcaption>In the <strong>fine tuning stage</strong>, the model params are adjusted to specialise the network to a particular task — (a) sentiment classfication (b) word classification.</figcaption></figure><h3>Decoder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jgpTmwxE2sPdsrm_28Jzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0HxygrwkRMxo27cZNGnhw.png" /><figcaption>The basic architecture is very similar to encoder model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPnI6mSm17oYpIn0anuEcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1rk-qG7qX7eq1qAenGoZg.png" /><figcaption>Text → Token → Embeddings → Masked Self-Attention → Decoder Layers → Output Embeddings → Linear Layer → Softmax → Next-Token Probabilities → Cross-Entropy Loss (all positions)</figcaption></figure><p>To train a decoder, we seek params that maximises the log probablity of the input text under the autoregressive model. When, we feed the sentence, we want the system to learn to predict the next word. So we purposely set the dot products in self attention computations to negative infinity before they are passed through self attention, so that the embeddings can only attend to current and previous tokens.</p><p>In practice, strategies like <strong>beam search</strong> (tracks multiple possible sentence completion to find the overall most likely sequence of words) and <strong>top-k-sampling </strong>to prevent the system leading to a linguistic dead end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ID675Avv0uK8FSsvSdPsAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ItGSmwi2mTh1pIpAp5eSYg.png" /></figure><h3>Encoder-Decoder Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1eE36OwURPBNSjN5zZYZA.png" /><figcaption>Translating between languages is an example of <strong><em>seq-to-seq</em></strong> tasks. A common approach is to use an encoder-decoder model. Encoder processes english sentences to create an output representation for each token. Decoder using masked self-attention to predict the next french word.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*xUCxd1Mz_okBsfa5wvPivw.png" /><figcaption>Cross Attention: Decoder layer also attend to output of the Encoder. Consequently, each french word output is also conditioned on previous output words and source english sentences.</figcaption></figure><h3>Transformer For Long Seq</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGbmNvwWH2LMq-xaOMtIwQ.png" /><figcaption>sparse attention</figcaption></figure><h3>Transformer Models For Images</h3><p>Treat image pixels like words and predict them autoregressively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYYKGwy97bERJ-NPjvb77A.png" /><figcaption><em>(a)Images generated from the autoregressive </em><strong><em>ImageGPT</em></strong><em> model. The top-left pixel is drawn from the estimated empirical distribution at this position. Subsequent pixels are generated in turn. (b) b) Image completion.</em></figcaption></figure><p>Replace pixels with patches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVMGXg_x4PfSa0T9xoH1Vg.png" /><figcaption><strong>ViT</strong>: Image ↓ Patchify (16×16) ↓ Linear embed ↓ Add position ↓ Add &lt;CLS&gt; ↓ Transformer encoder ↓ &lt;CLS&gt; token ↓ Linear head ↓ Softmax ↓ Class probs</figcaption></figure><p>Add CNN-like pyramids to transformers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9N0DvU4o22gqkrX_760oPQ.png" /><figcaption><strong>SWin (MultiScale)</strong>: Image → Patches → Windows → Local attn → Shift windows → Local attn → Patch merge → Bigger windows → Shift windows → Repeat → Avg pool → Linear head → Softmax</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*uoxlFLtvQ-mJ7gIm.png" /><figcaption><strong>DaVit</strong>: SoTa ; Attend across space <strong>and</strong> channels.</figcaption></figure><p>Transformers initially struggled on images due to scale and lack of inductive bias, but patching, hierarchy, and multi-scale attention allowed them to surpass convolutional networks on ImageNet.</p><p>Parts of the texts are taken from : <a href="https://udlbook.github.io/udlbook/">https://udlbook.github.io/udlbook/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69a5401f3398" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Deep Learning Part -2]]></title>
            <link>https://medium.com/@ksheer.agrawal/understanding-deep-learning-part-2-b845432b2171?source=rss-4502a438fcdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b845432b2171</guid>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[imagenet]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[rnn]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Ksheer Sagar Agrawal]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 08:33:47 GMT</pubDate>
            <atom:updated>2026-01-07T08:33:47.854Z</atom:updated>
            <content:encoded><![CDATA[<p>In this part, we will talk about CNNs and RNNs in supervised learning, with applications in computer vision such as object detection, image segmentation, and classification. Much of modern computer vision also involves generative modeling — see Part 4 for that, which covers unsupervised learning. We will also touch on transfer learning, which is commonly used in image segmentation.</p><pre>Learning paradigms<br> ├── <strong>Supervised </strong>       → <strong>classical + deep</strong><br> ├── Unsupervised      → classical + deep<br> ├── Self-supervised   → mostly deep<br> ├── Semi-supervised   → classical + deep<br> ├── Weak supervision  → classical + deep<br> ├── Reinforcement     → classical + deep (Deep RL)<br> ├── Online learning   → classical + deep<br> └── <strong>Transfer learning</strong> → <strong>mostly deep</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wl6DjrNqmMGgUlAHsk3Blw.png" /></figure><h3>Invariance Equivariance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sdhJWGZuTyva-fRVoJggBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHiUkYdHgGWR1g8G-O1U0w.png" /><figcaption><strong>Image classification</strong> should be invariant to transformations <strong><em>f[t[x]]= f[x]</em></strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PC6bdBXGg1_zxEva62PWHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XraFycJQvCQEluGv1R8PfQ.png" /><figcaption><strong><em>Image Segmentation</em></strong><em> should be equivariant to transformations </em><strong><em>f[t[x]]= t[f[x]].</em></strong></figcaption></figure><h3>Convolution Neural Networks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xiyoBW-HGl6GZZ93a6fz4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJO69y8QLgqnucoYAy72pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fP51kEjs3qS01LuClr9RQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iM7GHhaprleTuCQixHf1Hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6c083EYo_bJEMT2-ijysQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*ilp02gk5wK70oI4XBzh75A.png" /><figcaption>convolution layer+ filter → feature map</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*76WIDhAyhOctoiC-y6pQ6w.png" /></figure><h3>Upsampling and DownSampling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgGXREPj6LmM87_2lYRRiw.png" /><figcaption>downsampling increases receptive field size</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpi89m6M4jKBFWXiIgZUBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydNSMdsD-ZmcQNYVLQ7o4w.png" /><figcaption>upsampling is useful to scale up, when output is also an image.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZNdhzazf-7VlM1wjdlg0g.png" /></figure><h3>Applications ( Image Classification )</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mDb6OF5cBHzsbXH-9DZbBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6Ojo_0XK2LwF8Su-_kW_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTod_CjURotRqHmheHqpLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPQKByPd3eMtWa9xisGlQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3wH_3cPJjalnX11Pu7DGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8DintZFhDgXhJNEvWbnPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yA2rzeNRjPaYrzhwPp6Bag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YmgyC-fnGnFr710kZ-Ieg.png" /></figure><h3>Applications ( Object Detection )</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IwFz8NLFFG9yYT8iAaVLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*892IBlVqH060czEWCEwSwA.png" /><figcaption><em>Transfer learning is employed; the network is initially trained on the ImageNet classification task and is then fine-tuned for object detection</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VI7V4gmiklW9LLZKCDm-dQ.png" /><figcaption>Example of transfer learning</figcaption></figure><h3>Applications ( Semantic Segmentation )</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqGIyco9haI6Tw0sNGW_lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U74gO74hzI5KeqezTMEHxg.png" /><figcaption>The first part of the network is small version of VGG; encoder-decoder or hourglass network due to their shape</figcaption></figure><h3>Residual Networks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3LHH5KeDXRHbU2QhtViZw.png" /><figcaption>image classification performance decreases again as further layers are added; In deep networks nearby inputs tend to “<strong>shatter</strong>” produce uncorrelated gradients, so backprop loses structure.</figcaption></figure><p>Shattered gradients arise because changes in early network layers modify the output in an increasingly complex way as the network becomes deeper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgSuTWFMJO59HLQ-k6DtwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ril3j1Ob8fjsF_VKVVnqFg.png" /><figcaption>Order of operations in residual blocks matter as only non-negative quantities can be added. Residual connections complicate variance math slightly,<br> but the intuition still holds: <strong>BatchNorm stabilizes things.</strong></figcaption></figure><p>Batchnorms make the networks invariant to weight scaling adds back the γ and δ — extra parameters. With γ = 1, δ = 0 initialisations, variance stays roughly constant, still in residual connections grows linearly (w/o it exponential). Overall, BN makes learning smooth. During inference, BN takes a running average, and hence acts like regularisation.</p><h3>Common Residual Connections</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbAndrsLgyR6x407053CmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9I2xHbYJKSbf8llhvtF9vQ.png" /><figcaption>For <strong>very deep networks</strong> (like ResNet-50, 101, 152, 200), a regular residual block would require too many convolution parameters. A <strong>bottleneck architecture (b)</strong> reduces convolution parameter requirements.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdwXhiT7oY7wp8-j8XOh8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*cQcfy_nxcrERBmrIr-Lh7A.png" /><figcaption>DenseNet improves smoothness</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xoS6vvyTSBH2J1oSDyzeYg.png" /><figcaption>U-net; the encoder remembers big picture, the repeatedly downsamples and increases receptive field. Learns the global semantic info.</figcaption></figure><p>The tiny bottleneck must somehow remember <strong>both global meaning (what is where) </strong>and <strong>fine details ( exact boundaries ) </strong>through residual connection (<strong>concatenated</strong>, not added like DenseNet).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYa69x5TEykHMWtu9Deh9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRUfie2lNzHD6EWmwbTp9Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b845432b2171" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Deep Learning Part-5]]></title>
            <link>https://medium.com/@ksheer.agrawal/understanding-deep-learning-part-5-47e40347db60?source=rss-4502a438fcdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/47e40347db60</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[monte-carlo]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[temporal-difference]]></category>
            <category><![CDATA[q-learning]]></category>
            <dc:creator><![CDATA[Ksheer Sagar Agrawal]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 00:27:39 GMT</pubDate>
            <atom:updated>2026-01-05T00:27:39.501Z</atom:updated>
            <content:encoded><![CDATA[<p>In Part 5, we’ll talk about what classical and deep RL methods for MDP processes, reviewing tabular approaches which includes DP, Monte Carlo methods and temporal difference methods. Treat this like a notebook you can skim/revise anytime. It’s not meant for RL foundations — for that, you should take a standalone RL course, like I find the stanford deep RL course pretty complete.</p><pre>Learning paradigms<br> ├── Supervised        → classical + deep<br> ├── Unsupervised      → classical + deep<br> ├── Self-supervised   → mostly deep<br> ├── Semi-supervised   → classical + deep<br> ├── Weak supervision  → classical + deep<br> ├── <strong>Reinforcement</strong>     → <strong>classical</strong> + <strong>deep</strong> (Deep RL)<br> ├── Online learning   → classical + deep<br> └── Transfer learning → mostly deep</pre><h3>What is Reinforcement Learning?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GuGXk1ParRTCiiwnIM3v3g.png" /><figcaption>Agent → Action → Reward → Learn → Repeat</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*WzkdBEzBSRmEXtPFhCo3jQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*IxfgbER3XvRzisgDoHQ5iA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*x58bmOi4i0YAR89DE-spEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xSltSn4-ZpcRHqMVISrvYQ.png" /><figcaption>The Markov property, or “memorylessness,” states that the future of a <a href="https://www.google.com/search?q=stochastic+process&amp;oq=markov+property&amp;gs_lcrp=EgZjaHJvbWUqCQgAEEUYOxiABDIJCAAQRRg7GIAEMgcIARAAGIAEMgcIAhAAGIAEMgcIAxAAGIAEMgcIBBAAGIAEMgcIBRAAGIAEMgcIBhAAGIAEMgcIBxAAGIAEMg0ICBAAGIYDGIAEGIoFMgoICRAAGKIEGIkF0gEIMTkzM2owajeoAgCwAgA&amp;sourceid=chrome&amp;ie=UTF-8&amp;ved=2ahUKEwjE39-cjvGRAxXTie4BHXRnA2kQgK4QegYIAQgAEAQ">stochastic process</a> depends only on its <strong>present state</strong>, not on the sequence of events that led to it.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hTNTR0M2xj8mXRx5RLFuw.png" /></figure><h3>Markov Decision Process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VG50FzaKoqjr9zTmfjStjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUZNTwpHepcYkWYA1yi3QQ.png" /></figure><h3>Policies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aaEhytOMFXZ_woM-bBNQEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/0*Sfz1Ce8JmpBswEOB.png" /><figcaption>A <strong>policy</strong> is a function that tells an agent which is the best action to choose in each state. A policy can be <strong>deterministic</strong> or <strong>stochastic</strong>.</figcaption></figure><h3>Trajectories</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6WtSMu91s7pRtl99Szv2A.png" /></figure><h3>Value function and Q-value function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMl-GSQq_iA330-vh4OL4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wz09EJbEHfHuzQYEHDCwyw.png" /></figure><h3>Bellman Equations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzbxzFu6yTmmFwqhE3WPyw.png" /></figure><h3>A Taxonomy for RL Algorithms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*AbVMtjifBPZjI8p3.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*zGIW_IAui4xHUENK" /><figcaption>upside to having a model is that <strong>it allows the agent to plan</strong> by thinking ahead, seeing what would happen for a range of possible choices. Transition model <strong>P(s′∣s,a)</strong> and Reward model <strong>r(s,a)</strong> are the rules of the MDP.</figcaption></figure><h3>Dynamic Programming (Model Based)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4HEVWjZ6xlOcYuG-.png" /><figcaption>Policy Iteration vs Value Iteration</figcaption></figure><h3>Monte Carlo Methods (Model Free)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qA6Dael-daVTiWE51P7dfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYT9pdyWl7zwfQuFXp1F8w.png" /><figcaption>Monte-Carlo evaluation runs episodes and average returns: Vπ​(s)= a∑​π(a∣s)*Qπ​(s,a)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3pt4W0WbnOypxVsf9IIbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AAbO4lEfW3xYSBwSCFmuQ.png" /><figcaption>on-policy method based on epsilon greedy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRfzr4ybIOZMBHVN_WQ8Zw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQ73rE4LLVgi29D0p6GlOQ.png" /><figcaption><strong>Black Jack</strong> or “21” is considered as one of the world’s most popular gambling games played with cards.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31P_x7aE4uL-_NDi7YuYMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4a5vrPCshuGGhF81LaLGA.png" /><figcaption>in off-policy the target policy is deterministic and behaviour policy is stochastic; <strong>b</strong> is usually a “soft” policy (like random or epsilon-greedy) ; <strong>pi</strong> is updated take the best action</figcaption></figure><h3>Temporal Difference (Bootstrapping)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTgFEGfrOOhz4ky30fhAUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*luWS2rpJgahVEGc6GdvcJQ.png" /><figcaption>TD method updates the values and policy while the agent traverses the states of the MDP</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kjiE22FcHBrBv8SAZUKaqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YoJ_m1wza7b0SilFvGD53g.png" /><figcaption>SARSA on-policy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZc80cnDFjxjpveup7Psqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzPe4rIBIufFpsDhVucwZw.png" /><figcaption>Q-Learning off-policy; <strong>generating policy </strong>is usually a “soft” policy (like random or epsilon-greedy) ; <strong>target policy</strong> is updated take the best action</figcaption></figure><h3>Fitted Q-Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TY2BZv1E48VJRl70HiC5Mw.png" /><figcaption>Q-learning: Use a function approximator to estimate the action-value function; Q (s, a; 0) = Q*(s, a)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g3y9aDawZaSLUurX0OvN7Q.png" /><figcaption>the max action helps us set the <strong>Target (the Goal)</strong>, and the gradient is just the tool used to reach that goal.</figcaption></figure><h3>Deep Q-Networks (TD)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jklEGNfkbFCdScEyqlBgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chQNI_42G6DecWBDrRQ3ig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OoogbJ14wuYOK1fFyvF_-w.png" /><figcaption>the agent saves everything it sees into a database and learns from <strong>random samples</strong> drawn from that database, reducing correlations between samples in the batch that arises due to the similarity of adjacent frames</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/0*W9ky_vHX6zwm3S53.png" /><figcaption>Standard Q-Learning tends to be overly optimistic about how good actions are. Double Q-Learning fixes this by using <strong>two separate “brains” </strong>to check each other’s work. <strong>Brain 1 </strong>for<strong> </strong>Selection (argmax) &amp; <strong>Brain 2</strong> for Evaluation.</figcaption></figure><h3>Policy Gradients (Reinforce — MC)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeUllQqN8xU0F_8SuoTHjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mn_vpXmWKv6Dbtnjs_Rb1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*hRprGUWfneGbH9zlpyRKHA.png" /><figcaption>policy-based methods directly learn a stochastic policy π[at|st, θ] with trainable parameters θ that maps a state st to a distribution Pr(at|st) over actions at</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KFCL91B8ilnAJRPi-nvdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8M05zqVId5Vt53lwht6YdA.png" /></figure><h3>Actor-Critic (TD)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYkvJUhozRKmo4N5JKQxiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*kipmUYpvRvg0wOgZ1q0Bpw.png" /><figcaption>The policy network π[st, θ] that predicts Pr(a|st) is termed the actor. The value network v[st,ϕ] is termed the critic.</figcaption></figure><h3>Offline Reinforcement Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u9GX5iQt76xuwAEDpkA-oQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmYbsuQYYQOpVdNS_tuL9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSxRiUnA8m6rWygFQhgi_A.png" /><figcaption>Decision Transformer treats offline RL as sequence predictor task. Inputs are returns-to-go, states and actions. At each time step, network predicts next action. During inferencing, the returns-to-go are unknown and an initial estimate is made.</figcaption></figure><p>In this article, most illustrations have been taken from 🫡 .</p><ol><li><a href="https://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture14.pdf">https://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture14.pdf</a></li><li><a href="https://spinningup.openai.com/en/latest/spinningup/rl_intro.html">https://spinningup.openai.com/en/latest/spinningup/rl_intro.html</a></li><li><a href="https://www.youtube.com/playlist?list=PLzvYlJMoZ02Dxtwe-MmH4nOB5jYlMGBjr">https://www.youtube.com/playlist?list=PLzvYlJMoZ02Dxtwe-MmH4nOB5jYlMGBjr</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47e40347db60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Deep Learning (2025) Part 1]]></title>
            <link>https://medium.com/@ksheer.agrawal/understanding-deep-learning-2025-part-1-ed9b1cf1c5e6?source=rss-4502a438fcdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed9b1cf1c5e6</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[training]]></category>
            <dc:creator><![CDATA[Ksheer Sagar Agrawal]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 03:58:09 GMT</pubDate>
            <atom:updated>2026-01-03T04:05:58.518Z</atom:updated>
            <content:encoded><![CDATA[<p>Illustrations have been taken from : <a href="https://udlbook.github.io/udlbook/">https://udlbook.github.io/udlbook/</a></p><pre>Learning paradigms<br> ├── <strong>Supervised</strong>        → classical + <strong>deep</strong><br> ├── Unsupervised      → classical + deep<br> ├── Self-supervised   → mostly deep<br> ├── Semi-supervised   → classical + deep<br> ├── Weak supervision  → classical + deep<br> ├── Reinforcement     → classical + deep (Deep RL)<br> ├── Online learning   → classical + deep<br> └── Transfer learning → mostly deep</pre><p>In Part 1, we’ll talk about what deep neural networks are in supervised learning, how they’re trained, how to measure their performance, and how to improve it. Treat this like a notebook you can skim anytime. It’s not meant for building foundations — for that, you should take a statistics- and linear-algebra-heavy course to really internalize the concepts.</p><h3><strong>1. Introduction</strong></h3><p>Fitting deep neural networks = “Deep Learning”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJpSlyhcrFH_Ij3nGzROzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBPHZ39iqbH4VKhqefSCSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81nqbuHhGquwej3Q_dT8ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRfgDF-z7_n8JoB0rKsu2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pztq_ECL_MahYkI3xXqNMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OweXGB31kClGoSuJ7x9sKg.png" /></figure><h3>3. Shallow neural networks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3FuegZHtdFQPqtkduV-qKg.png" /></figure><blockquote><strong>Universal Approximation Theorem</strong>: A neural network with <strong>at least one hidden layer</strong> and a suitable activation function can approximate <strong>any continuous function</strong> on a bounded input space, <strong>as accurately as you want</strong> — if it has enough neurons in that layer.</blockquote><h3>4. Deep neural networks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwDb4h1mCRWPSZp5liM6xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xb-1wq93qRHODFL8scWZSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRqEne9GiCdr4P1D_F9YpA.png" /><figcaption>With the same number of parameters, deeper networks create MANY more regions.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1v9FlM7NOIiu6CvOPjXmjg.png" /><figcaption>Deep Neural networks fit and generalize better.</figcaption></figure><h3>5. Loss functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gXWBrkiAPDUjs5x4Vi5tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGG1DbEgA8VirJY87qDR9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0kA2jYwAUhZWU2oy1MJRoA.png" /></figure><h3>6. Training models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbFOq-BsuJuY8Nhn400izA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNDxMz9xSZetJHBnEqFcXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VABWwdvBRiRXz1sJjxeeXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pp_-4V-sYSzkuvHvUw4Rgw.png" /></figure><h3>Gradients and Initialization:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bz4xrHZEKYyH_LtwjTyxvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4bZXppo1rfbeXWGPAbMAQ.png" /><figcaption>“What does the network predict?” and “How should each parameter change to reduce error?”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-Hluq8EbFQSLTfRqOmcLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*GeNrqGAm8BkoD2D8M1C60g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaHCsrTXXXb8JtVJrjs95A.png" /></figure><h3>Measuring performance</h3><pre>Expected Test Error = Bias² + Variance + Noise</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*UpWKvtGivWaLocuDqp54aQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*69NoNLhs2tF5BLUAMsTPbA.png" /><figcaption>variance and bias</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNAICkp1-qR5GN6YofuyFA.png" /><figcaption><strong>Bias</strong>: Error because our model is too simple or mis-specified. (classic <strong>underfitting</strong>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1IARyerHcx4zKj3y_UFvCw.png" /><figcaption><strong>Variance</strong>: How much the model changes when training data changes (classic <strong>overfitting</strong>)</figcaption></figure><h3>Regularization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIZWfmyXPfs7Q7sXoNlYow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEMMlvVxZH_du_LAHvBRGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGT43tXL36wTAh_rAMRNTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thHZJpIamfSdW2ikMWmdqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tUL2_-rKtnfJYdXWHkNDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3JzmiYCSj_JB57t1dyZaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_qv3TuOAeM6BSdbJXzvyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NuxWr-Du_AUZNv_CJVV7uQ.png" /></figure><p>Regularization is anything that prevents the model from memorizing training labels and forces it to learn general structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZiKXOCUf-e9gW_mfyFqN_A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed9b1cf1c5e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lets Compare Programming Languages]]></title>
            <link>https://medium.com/@ksheer.agrawal/lets-compare-programming-languages-de18c9c334c3?source=rss-4502a438fcdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/de18c9c334c3</guid>
            <category><![CDATA[low-level-programming]]></category>
            <category><![CDATA[high-level-programming]]></category>
            <category><![CDATA[language]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ksheer Sagar Agrawal]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 04:09:12 GMT</pubDate>
            <atom:updated>2025-12-31T04:09:12.910Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered why team’s prefer to use some languages over others. Like enterprise teams would stick to OOPs style Java, ML teams would prototype with python, systems heavy teams are trying Rust and Go, Front-end just cant get over from JavaScript, robotics and quant’s just love C/C++.</p><p>So, let’s compare <strong>Python, Java, C++, JavaScript, Erlang, Go, C, Ruby, Rust.</strong></p><h3><strong>Ahead-of-time compiled</strong> <em>(C, C++, Rust, Go)</em></h3><pre>Your source code<br>        |<br>        v<br>+-------------------+<br>|   Compiler (AOT)  |<br>+-------------------+<br>        |<br>        v<br> Machine code binary  (program.exe / a.out)<br>        |<br>        v<br>+-------------------+<br>|  OS + CPU execute |<br>+-------------------+</pre><pre>Low-Level Control                        High-Level Convenience<br>(Hardware Focus)                            (Developer Focus)<br>       |                                           |<br>       V                                           V<br>[ C →  C++ →  Rust  →  Go  →  Java  →  Python  →  JS  →  Ruby ]</pre><p>I find <strong>C/C++ unsafe</strong> as the programmer has to handle memory mgmt and concurrency themselves, otherwise we may easily break things ( leaks/crashes ). Since its fast and powerful its popular among kernel, embedded and HFT programmers.</p><p><strong>Rust</strong> has the best of both the worlds. It gives the C/C++ performance but with strong safety gurantees — it catches memory and race conditions bugs at compile time. So it refuses to build <em>unsafe</em> code.</p><pre>Domain:   Single Machine Focus              Distributed / Web Focus<br>                  |                                     |<br>                  V                                     V<br>      [ C / Rust / C++ ] ----&gt; [ Go / Erlang / Java ] ----&gt; [ JS / Python ]</pre><p><strong>Go </strong>is very popular among cloud developers. But why — they actually solved the memory and concurrency harships of C/C++. All of this was possible by addition of a <strong>Go runtime,</strong> which provides both the garbage collector and its own scheduler for goroutines. In Go, deployment is also ridiculously easy: no VM, no interpreter, fewer environment issues, minimal dependency headaches — and it compiles very fast. Because of this, it became popular at big companies, and it grew even more with the rise of cloud computing, containers, DevOps, and microservices.</p><h3>2. Bytecode + VM / JIT <em>(Java, JavaScript, Erlang, sometimes Python alternatives)</em></h3><p>Everyone knows <strong>Java</strong> is famous in enterpise backend. But why ? So instead of compiling directly to machine code, <strong>Java</strong> compiles into bytecode, which can run anywhere a JVM is installed. Like other languages that moved away from C and C++, Java removed manual memory management and relies on a garbage collector. It also has a Just-In-Time (JIT) compiler that detects “hot” code paths at runtime and compiles them into native machine code. Since native machine code runs faster, Java is optimised for long-running distributed systems.</p><p>You must have heard Java’s name with foundational systems like Hadoop, Cassandra, Elasticsearch, Spark, Kafka. All of these — are built on the JVM ecosystem.</p><p>Everyone knows <strong>JavaScript</strong> as the language of the browser. Over time, it escaped the browser and now runs on servers too, thanks to engines like Node.js. JavaScript doesn’t compile ahead of time like Go or C++; instead, it runs on a virtual machine inside the browser or Node, where an interpreter and JIT compiler optimize it while the program runs. It is built around the event-loop model, which makes async programming very natural — great for APIs, real-time apps, chats, dashboards and anything web-based, which is why it dominates front-end development and powers much of the modern web.</p><pre>Your source code<br>        |<br>        v<br>+-------------------+<br>|  Front-end compiler|<br>|   (javac, etc.)    |<br>+-------------------+<br>        |<br>        v<br>      Bytecode<br>        |<br>        v<br>+---------------------------+<br>| Virtual Machine (JVM/VM)  |<br>|   - Interpreter           |<br>|   - Profiler             |<br>|   - JIT compiler         |<br>+---------------------------+<br>        |<br>        v<br>   Native machine code<br>        |<br>        v<br>     CPU runs it</pre><h3>3. Bytecode + Interpreter <em>(Python (CPython), Ruby)</em></h3><p><strong>Python </strong>was my goto coding language at school. It is very safe, mainly because it takes most low-level control away from the programmer. Memory management is handled automatically by the runtime. In CPython, only one thread can execute Python code at a time because of the GIL. Multiprocessing works by launching multiple processes, each with its own interpreter and its own GIL. These processes don’t share memory, which means race conditions from shared variables don’t occur.</p><p>Despite these limits, how does ML workloads run so fast. Its because the heavy computation happens inside highly optimized C, C++, and CUDA libraries. Python is mostly a convenient wrapper that calls into those libraries, and they run in parallel on CPUs and GPUs.</p><pre>   Your source code<br>        |<br>        v<br>+-------------------+<br>|   Python compiler |<br>| (produces bytecode)<br>+-------------------+<br>        |<br>        v<br>     .pyc bytecode<br>        |<br>        v<br>+-------------------------+<br>|   Interpreter (VM)      |<br>|  executes bytecode step |<br>|           by step       |<br>+-------------------------+<br>        |<br>        v<br>  CPU (indirectly)</pre><pre>AOT (C/Rust)          JIT (Java)               Interpreted (Python)<br>-------------         -----------------        ----------------------<br>source                source                   source<br>  |                     |                        |<br>compile AOT             compile → bytecode       compile → bytecode<br>  |                     |                        |<br>native binary           VM + JIT                 interpreter<br>  |                     |                        |<br>CPU runs directly       CPU runs optimized       CPU runs step-by-step</pre><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gr51_Iqaz2CtRdmc66-WsA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de18c9c334c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do You Learn AI/ML?]]></title>
            <link>https://medium.com/@ksheer.agrawal/how-do-you-learn-ai-63d146ab85c0?source=rss-4502a438fcdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/63d146ab85c0</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[uc-san-diego]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ksheer Sagar Agrawal]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 05:41:52 GMT</pubDate>
            <atom:updated>2026-07-11T21:28:51.572Z</atom:updated>
            <content:encoded><![CDATA[<p>I miss the time I had my JEE coaches teaching me physics, chemistry, and maths. They made me fall in love with those subjects. I can still recall the basics I learned. The same is true for data structures and algorithms — it’s embedded inside me. As I move forward in my studies, I, like many others, feel the FOMO of not knowing the domain. All the VCs are pouring money into AI startups, software engineering is getting revolutionised, institutes are selling ML degrees, and ChatGPT is becoming the next Google. I just can’t stand not knowing its building blocks. I chose to leave my software engineering job to master the fundamentals of machine learning at UC San Diego. My perspective shifted during my first semester in a Scalable Data Systems course under Prof. Hao Zhang. It served as an accelerated crash course on how modern tech companies actually evolve. I have to admit, this is one of the most accelerated crash courses on what tech companies are building and how they evolved. This course forced me to read research papers that make Big Tech the leaders in AI and infra innovation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iLy_HSC79WIHF6YZKYuJw.png" /><figcaption>On which infrastructure does your application run? Pick one option from each layer, or are you building one of these infrastructures yourself?</figcaption></figure><p>This forced me to map out a clear mental model of how the entire tech ecosystem fits together. I believe most companies are currently either trying to build cloud/edge infrastructure or support the building blocks that make that services possible. And then there are AI companies that have super-genius researchers building ML solutions.</p><p>Now, what’s an ML solution? I feel that any basic ML solution can be classified by three orthogonal axes: <strong>paradigm, modality, and modelling</strong>. When companies elegantly combine these three axes to solve real-world problems, it crosses the line from engineering into art. There are companies building this art, and there are companies constantly improving the resources required to build the art. That’s the infra.</p><p>Nvidia, Databricks, Snowflake, AWS, and Cisco are leaders in infra. The AI race, on the other hand, is led by OpenAI, Google, Anthropic, xAI, Tesla, Meta, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5BlBOgK_6l9EIvzwvZVYBA.png" /><figcaption>If you are an AI researcher, can you explain your work in terms of the paradigms, modalities, and modeling approaches you use?</figcaption></figure><p>I feel that nobody is a superman. As an individual, if you’re someone like me who feels FOMO about not knowing everything but still has the itch to understand what others are building, I find this recipe pretty cool. Not just that — I strongly believe in leverage. Using your past work, you can always switch from AI to infra or the opposite, because both need each other in this new AI-hyped world.</p><p>As Naval said, it is most difficult to understand what you want in life. Because if you know what to work on and whom to work with, life is not that tough. If you have high-level clarity on what you want to build, leave the low-level details to ChatGPT or just outsource them for a few bucks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63d146ab85c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Full Marathon: What Happened When I Tried 42K With No Training]]></title>
            <link>https://medium.com/@ksheer.agrawal/my-first-full-marathon-what-happened-when-i-tried-42k-with-no-training-fab3d09cbd32?source=rss-4502a438fcdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/fab3d09cbd32</guid>
            <category><![CDATA[first-marathon]]></category>
            <category><![CDATA[full-marathon]]></category>
            <category><![CDATA[half-marathon]]></category>
            <category><![CDATA[athletes]]></category>
            <category><![CDATA[mental-toughness]]></category>
            <dc:creator><![CDATA[Ksheer Sagar Agrawal]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 09:07:48 GMT</pubDate>
            <atom:updated>2025-12-11T08:18:30.319Z</atom:updated>
            <content:encoded><![CDATA[<p>February in Delhi was cold, and I was about to do something crazy — I was going to run my first full marathon. I hadn’t really trained for it. It was an impromptu run, which I registered to meet my friends in Delhi. I wanted to raise the bar and try something more challenging after HM. I had already trained hard for different sports in my high school, so I was not afraid to push my body beyond limits. Adding to that, my manager once said me — “You are not ready, until you yourself are ready.”</p><h3>The Pre-Race Rituals</h3><p>I woke up at 3am in the morning and started with a simple breakfast: two bananas and a piece of bread with peanut butter. I immediately booked my cab, put my AirPods on, listened to <a href="https://music.apple.com/us/artist/illenium/645420096"><em>illenium</em></a>, and gazed out of the car window, with a blank mind as the silent roads slipped by under the yellow streetlights.</p><p>It was cold, and I hadn’t taken a jacket or carried any water or snacks because I didn’t want to hold anything extra. As I got down, I had to walk 2.5 km to reach the entry gate, which actually helped my body acclimate to the chilly weather. There were a lot of people there — some first-timers, some regular runners, and the really fast ones gathered at the front.</p><p>It was 4:00 a.m., and the race was about to begin. I quickly set a 5-hour timer on my Apple Watch. My plan was simple: run the first half of the marathon in 2 hours and the second half in 3 hours. Honestly, on paper, it felt doable since I could run an HM in around 2:15. I knew I would be tired after that first HM, but the extra 45-minute buffer for the second one sounded reasonable to naive me.</p><h3>The First Half: Confidence</h3><p>As the race began, during the first few kilometers, I felt like I had underestimated my capabilities. When the 10 km mark arrived, I was already 30 minutes ahead of my target pace. I joined a group aiming to finish in 4 hours and 30 minutes, and in my overexcitement, I even thought I might be able to beat them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4Rfu5YOnpKI7qBy0tp_7g.jpeg" /><figcaption>The first half was full of over-ambitious strides.</figcaption></figure><p>From 10 km to 15 km, I sped up even more to catch the sub-4 group. But at 15 km, I started to feel tired and hungry. Even though I tried to eat black salt–sprinkled oranges, jaggery sweets, and drink a bit as I went, by 17 km my legs had started to hurt. <em>Ahh, not again.</em> This was the point where I forced myself to slow down, but my breathing grew heavy and my body felt like it was running at 80% CPU capacity with no free credits left — definitely not a good state to be in with 25 km still to go.</p><p>I quickly realized that the 45 minutes I had gained earlier were starting to fade. To maintain momentum, I switched to a hybrid mode — a mix of running and walking. But each time I walked, it became harder to start running again. I call this the <em>mental trap</em>. At this point, I made a mistake: I allowed my mind to register that I was tired, and once that happened, my body stopped cooperating. Every time I walked, it got harder to run again.</p><p>Regardless, I continued, and by 20 km I was only 30 minutes ahead of my projected time, still alternating between running and walking to reach the halfway mark. I finished the first 21 km in 2 hours and 20 minutes — a time I once would have celebrated, but this one felt like one of my toughest halves yet.</p><p>My legs had given up — they were sore. My stomach was begging for food. I’m the kind of runner who loves to sprint the last few steps for the thrill, but here I was, having to run another entire HM. It made me a bit sad to see the pre-race, motivated Ksheer now struggling to even walk. How was I supposed to achieve my 5-hour target like this? All the time I had saved was gone, and I was walking in deficit, with no energy left.</p><p>Honestly, it wasn’t a good feeling to watch other runners move past me while I struggled just to keep going. Even the 5-hour pace group — the one I had overtaken long ago — passed me. I felt ashamed of my inconsistency. And to make things worse, it was disheartening to see the elite sub-3-hour runners flying past in the opposite direction, already on their second lap at full speed.</p><h3>The Struggle: Mental Games</h3><p>By now, I had given up on my earlier plan. Letting it go, I knew I had only one choice left: to finish the race. So I decided to re-strategize and mentally prepare myself again for the second lap. Some thoughts from my past failures resurfaced — RIMC, Olympiads, the JEE exam, district/state and InterIIT sports disappointments — all reflecting the same pattern of inconsistency. Back then, I definitely had the fire in me, but what I lacked were consistency and commitment. It felt like a knife stabbing me when I recognized that same pattern emerging again.</p><p>This marathon had become personal now — I wanted to prove my mental strength. I called upon every past failure and frustration — from my JEE rank to InterIIT disappointments and heartbreaks — and used that anger as fuel. And beyond the emotional fuel, I also powered myself up with actual energy: electrolytes and fruits.</p><p>This got me moving again. I tried to run consistently, but I couldn’t manage more than 400 meters at a stretch. My legs were in terrible pain, and running slowly only made it worse. I was exhausted. More than pain, my legs felt jammed from the knees down — what I presume were silent cramps. The stretch from 21 to 30 km was the slowest run of my life. It took me over an hour just to reach that mark.</p><p>It was 3:45 now, and I still had 12 km to go. On paper, it still looked realistic to hit the 5:00 target. Had it been the naive, confident Ksheer, I might have agreed. But by this point, I had lowered my expectations to simply finishing within 6 hours. It was an on-the-spot estimate — just like how I had earlier imagined I could finish in 4 hours after the first 10 km.</p><p>Anyway, the reality was that none of these projections or estimates made sense anymore because I was running in such a jittery, unstable state. All I knew was that I had to reach the finish line as soon as possible.</p><h3>Last Stretch</h3><p>I continued to slog on until I reached the 34 km mark, and the timer on my watch read 4:30. I was now about 30 minutes behind my 5-hour target. But even that calculation felt wrong — at my current pace, I knew I wouldn’t finish before 6:00. So, for one last time, I decided to go against what my mind was telling me. I told myself that no matter what, I was going to run. A marathon is best celebrated when you give it your all.</p><p>Since I was no longer short of energy or breath, I decided to switch strategies: sprint 500 meters, then brisk-walk 100–200 meters. This combination actually outpaced my target pace. I was slowly recovering from the 30-minute delay — even if the recovery was happening in mere seconds. Somehow, this sprint–walk approach felt better than slow jogging. It was like taking one big bullet instead of enduring continuous stabs.</p><p>Regardless, my legs were hurting badly. The 34 to 42 km stretch quite literally felt like the last leg. <em>(Pain alert!)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*Wyiq6ozbIV8noPmsDbb8Eg.jpeg" /><figcaption>At the 35th kilometer, I was running as hard as I could and feeling happy.</figcaption></figure><p>When I reached the 40 km mark, it was around 5:10; I sensed that I had finally beaten the clock. It’s an incredible feeling when you manifest something and actually do it. Your confidence surges, and the reward is pure dopamine. I rode that high. Realizing it was the last 2 km — my signature distance — I felt more confident than I had at any point in the run. My friends were already calling, waiting at the finish line to capture the winning moment. I ran those last 2 km with everything I had left.</p><p>As I approached the finish line, I found myself surrounded by thousands of runners from the 5 km, 10 km, and 21 km circuits. I knew I was among the last to complete the 42 km, but I was still genuinely happy because I had gone against my mind and beaten the clock in my own way. The 5-hour target had passed, but I was on track to achieve the sub-5:30 goal.</p><p>The last 200 meters were the most beautiful moments of the entire run. My friends welcomed me with cameras, cheers, and so much support. I literally felt on top of the world. Funny enough, I ran my fastest pace in those final meters. And the result? I completed the full marathon in <strong>5 hours and 28 minutes</strong>.</p><h3>What I Learned</h3><p>Even though I wasn’t ready for a marathon, I still finished. It wasn’t easy, but I had decided to see it through. And somehow, I managed to figure everything out at runtime (pun intended — I’m a software engineer!). Would I tell you to run a full marathon with no training? Absolutely not. But do I regret doing it? Not at all. It was tough, painful, and somehow amazing in the end.</p><p>That day taught me something important: if you know that playing a particular game has a high reward and low risk, just go for it. Attempt it like a lion. There are only two possibilities — you either win and uncover your true potential, or you fail completely. And honestly, I pray that failure visits me often, because it helps me understand my weaknesses and gives me the chance to figure out what went wrong. Why wasn’t the game in my favor?</p><p><strong>Think of life as a game of poker — you get to play multiple rounds.</strong> In each round, you put in something: time, effort, or emotion. Sometimes you win, sometimes you lose. But every loss teaches you something, and every lesson makes you better prepared for the next big round. And you want to be ready for that big win, because time is limited.</p><p>Cheers!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZIYQ38YbtKIsUotBbkYPg.jpeg" /><figcaption><em>This is the photo of my finish — my friends and I will never forget it. </em>Chip time: 5:28</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fab3d09cbd32" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>