<?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 Samarth Narang on Medium]]></title>
        <description><![CDATA[Stories by Samarth Narang on Medium]]></description>
        <link>https://medium.com/@samarth.colleges?source=rss-26469bc63d9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*AbovuM29MplfeJpd</url>
            <title>Stories by Samarth Narang on Medium</title>
            <link>https://medium.com/@samarth.colleges?source=rss-26469bc63d9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:29:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samarth.colleges/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[Security for Agentic ML Compilers]]></title>
            <link>https://medium.com/@samarth.colleges/security-for-agentic-ml-compilers-c76186df12a6?source=rss-26469bc63d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c76186df12a6</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Samarth Narang]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 17:55:48 GMT</pubDate>
            <atom:updated>2026-04-24T17:57:54.706Z</atom:updated>
            <content:encoded><![CDATA[<h3>Security for Agentic ML Compilers: When Optimization Becomes an Attack Surface</h3><p>Modern ML Compilers are already doing something that looks something like magic.</p><p>You write Python. Somewhere below that, a compiler captures your model, rewrites tensor programs, fuses operations, chooses memory layouts, generates kernels, schedules execution, and targets HW you may never directly program. In PyTorch, for example, torch.compile uses compiler machinery to capture and optimize graphs, with TorchInductor as the default backend. MLIR, meanwhile, was designed as reusable and extensible compiler infrastructure for heterogeneous HW and domain-specific compilation.</p><p>Now add an AI agent to that loop.</p><p>Not just an autocomplete assistant. Not just a chatbot that explains compile errors. Imagine an agent that can modify MLIR passes, generate Triton kernels, tune pass pipelines, change fusion heuristics, adjust quantization policies, and benchmark perf.</p><p>That sounds useful.</p><p>It also sounds dangerous.</p><p>Because in an ML Compiler, a malicious change does not have to look like malware; it could very much.. look like an optimization.</p><h4><strong>The Optimizer is becoming an actor</strong></h4><p>Traditionally, compilers are tools. They take a program as input and produce another program as output. The programmer, build system, or deployment pipeline decides when to invoke them.</p><p>But agentic systems can change that relationship: an agent is not just passively invoked. It can observe, decide, call tools, edit code, run tests, compare outputs, and loop around to try again. Recent work on secure agentic systems has argued that prompt-level rules are not enough for enforcing safety policies; systems such as <a href="https://arxiv.org/abs/2602.16708"><em>PCAS</em></a><em> </em>propose deterministic policy enforcement using dependency graphs, Datalog-style policies, and a reference monitor that blocks unauthorized actions before execution.</p><p>That framing is useful, but ML Compilers introduce a more specialized problem.</p><p>For a general software agent, the security questions might be:</p><ol><li>Can the agent access this file?</li><li>Can the agent call this API?</li><li>Can the agent send this email?</li><li>Can the agent execute this command?</li></ol><p>For an agentic ML Compiler, the analog looks like:</p><ol><li>Can the agent apply this rewrite?</li><li>Can it change the pass ordering?</li><li>Can it alter this precision boundary?</li><li>Can it generate the kernel? If so, which variants?</li><li>Can it deploy this target-specific <em>fast path?</em></li><li>Can it disable verifiers?</li></ol><p>We are no longer only protecting files, APIs, or user data but we are protecting the <strong>semantics of computation</strong> itself.</p><h4><strong>In ML Compilers, attacks could look like performance wins (?)</strong></h4><p>Compiler-level attacks do not need to look like</p><pre>steal_user_data();</pre><p>It can do something subtler:</p><pre>Rewrite softmax using a numerically unstable approximation.<br>Change quantization scales for a narrow class of inputs.<br>Fuse two operations and accidentally remove a precision boundary.<br>Add a fast path for a specific tensor shape.<br>Change a layout transformation so one channel is misindexed.<br>Disable a verifier because it “slows down compilation.”<br>Generate a kernel that behaves differently on one GPU architecture.</pre><p>Any of these could sneak past your unit testing framework, some might even improve mean benchmarks. Hence, the crux: In ML compilers, the attack may not look like code injection. It may look like optimization.</p><blockquote>In ML compilers, the attack may not look like code injection. It may look like optimization.</blockquote><p>This is true because ML Compiler correctness is does not always have a binary answer. This is a fuzzy space: floating-point reassociation, approximate math, mixed precision, quantization, layout conversion, and backend-specific CodeGen.</p><h4><strong>Why ML Compilers are a special attack surface</strong></h4><p>We wish these were just C compilers with Tensors, but the following gives attackers — or simply unsafe agents — many places to hid mistakes</p><ol><li><strong>Tensor semantics are rich. </strong>A rewrite involving broadcast, reshaping, transpose, etc. can preserve types but change meaning. For example, two tensors may have compatible shapes but different layout interpretations, which could lead to wrong indexing.</li><li><strong>The fragility of floating point. </strong>FP arithmetic is not real-number arithmetic, reordering operations can simply change results.</li><li><strong>Dynamic shapes create hidden corners. </strong>An agent that tunes for benchmark inputs might accidentally, or maliciously, create a shape-specific <em>fast path</em> that behaves outside the testing envelope.</li><li><strong>Quantization. </strong>Changing quantization params can subtly degrade accuracy; on top, it might not be uniform, it could affect particular classes, tokens, prompts, or input ranges. It could be wild to detect these transformations with small regression tests.</li><li><strong>Target specific CodeGen. </strong>Correct on one accelerator, incorrect on another :)</li></ol><h4><strong>The malicious transformation threat model</strong></h4><p>The malicious model is NOT malicious code, it is <em>malicious transformations.</em></p><blockquote>A malicious transformation is a compiler action that appears to be a valid optimization but violates some intended semantic, numerical, security or deployment policy.</blockquote><p>In my opinion, this is a powerful threat model because it covers accidental agentic failures. An AI agent does not need to have the intent to be malicious, it could simply <em>over-optimize, </em>misunderstand an invariant, or “fix” a failing test by weakening the test.</p><h4><strong>Create compiler action spaces</strong></h4><p>One way to secure agentic ML Compilers is stop treating the agent as a free-form code editor. Instead, expose a constrained<strong> compiler action space.</strong></p><p>Consider:</p><pre>Allowed action:<br>Apply rewrite pattern X to op Y if verifier V succeeds.<br><br>Allowed action:<br>Change tiling factor within a bounded range and rerun numerical checks.<br><br>Allowed action:<br>Generate a candidate kernel, but only deploy if it passes reference comparison.<br><br>Allowed action:<br>Change pass ordering only if declared pass dependencies are preserved.<br><br>Allowed action:<br>Use lower precision only inside regions annotated with an acceptable tolerance policy.</pre><p>Unsafe actions should be blocked or escalated:</p><pre>Blocked action:<br>Disable verifier.<br><br>Blocked action:<br>Remove regression test.<br><br>Blocked action:<br>Change quantization scale without calibration metadata.<br><br>Blocked action:<br>Introduce target-specific fast path without reference validation.<br><br>Blocked action:<br>Deploy generated kernel without provenance record.<br><br>Blocked action:<br>Modify layout conversion without inverse-layout check.</pre><p>This assigns the role of <em>policy-constrained optimizer</em> to the agent.</p><h4>A compiler action firewall</h4><p>A possible architecture is a <em>compiler action firewall.</em></p><p>The agent proposes an action, the firewall decides whether the action is allowed. If allowed, the compiler allows it and the validation layer checks the before-and-after behavior.</p><pre>                 ┌────────────────────┐<br>                 │ Agentic Optimizer   │<br>                 │ LLM / Search Agent  │<br>                 └─────────┬──────────┘<br>                           │ proposes action<br>                           ▼<br>              ┌──────────────────────────┐<br>              │ Compiler Action Firewall │<br>              │ - policy checks          │<br>              │ - provenance tracking    │<br>              │ - capability limits      │<br>              │ - action allowlist       │<br>              └─────────┬────────────────┘<br>                        │ approved action<br>                        ▼<br>              ┌──────────────────────────┐<br>              │ ML Compiler Pipeline     │<br>              │ - rewrite patterns       │<br>              │ - lowering passes        │<br>              │ - kernel generation      │<br>              │ - scheduling decisions   │<br>              └─────────┬────────────────┘<br>                        │ before/after IR<br>                        ▼<br>              ┌──────────────────────────┐<br>              │ Validation Layer         │<br>              │ - IR verifier            │<br>              │ - translation validation │<br>              │ - numerical oracle       │<br>              │ - fuzz tests             │<br>              │ - backend comparison     │<br>              └─────────┬────────────────┘<br>                        │ signed artifact<br>                        ▼<br>              ┌──────────────────────────┐<br>              │ Runtime Deployment       │<br>              │ - target guard           │<br>              │ - telemetry              │<br>              │ - rollback               │<br>              └──────────────────────────┘</pre><p>Some things to note:</p><ol><li><strong>Translation validation becomes a security primitive</strong>. Every agent-proposed transformation should produce a proof obligation or validation obligation:</li></ol><pre>Before IR: tensor program A<br>After IR: tensor program B<br>Claim: B is equivalent to A under constraints C<br>Validation: prove, test, or reject</pre><p>2. <strong>Numerical contracts should be first class. </strong>Numerical tolerance is NOT an afterthought. A trusted agentic ML Compiler should make numerical expectations explicit:</p><pre>Region: attention softmax<br>Allowed precision: fp32 accumulation<br>Approximation allowed: no<br>Maximum relative error: 1e-5<br>Target-specific lowering: requires reference comparison</pre><pre>Region: feed-forward matmul<br>Allowed precision: int8 inputs, int32 accumulation<br>Quantization metadata: required<br>Calibration profile: required<br>Backend-specific kernels: allowed with validation</pre><p>The agent can optimize inside the contract but cannot rewrite the contract. The policy is attached to the computation.</p><p>3. <strong>Provenance matters. </strong>If an agent changes a compiler pipeline, we should have full visibility, not just take the “win” of “<strong>Performance improved by 8%” </strong>but a verbose log like</p><pre>Agent changed pass order from P1 → P2 → P3 to P1 → P3 → P2.<br>Agent applied rewrite pattern R to linalg.generic op at location L.<br>Agent generated Triton kernel K from template T.<br>Agent changed block size from 128 to 256.<br>Agent ran validation suite V.<br>Agent passed numerical tolerance policy N.<br>Artifact was signed and deployed to target A.</pre><p>This makes debugging possible and allows us to ask questions in production, such as:</p><ol><li>Which agent action introduced this kernel?</li><li>Which IR transformation changed this layout?</li><li>Which validation checks passed?</li><li>Which target-specific guards were active?</li></ol><h4>Closing Notes: Just Say No</h4><p>The most underrated feature of a secure compiler agent is refusal, a good agentic compiler agent would sometimes say</p><p>“I found a faster rewrite, but it violates the numerical policy.”</p><p>This area is still young and there are, of course, unsolved questions:</p><ol><li>Can every agent-proposed compiler transformation emit a proof obligation?</li><li>Can MLIR passes be wrapped with security policies?</li><li>How well can we detect suspicious optimizations?</li><li>Can generated kernels be signed with validation evidence?</li></ol><p><strong>Disclaimer:</strong> The views expressed here are my own and do not represent the views of my employer, past employers, or any affiliated organizations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c76186df12a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Triton on NPUs: What Changes When You Leave the GPU World]]></title>
            <link>https://medium.com/@samarth.colleges/triton-on-npus-what-changes-when-you-leave-the-gpu-world-31408c1c0ca5?source=rss-26469bc63d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/31408c1c0ca5</guid>
            <category><![CDATA[triton]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mlir]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Samarth Narang]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 03:08:15 GMT</pubDate>
            <atom:updated>2025-12-09T03:08:15.743Z</atom:updated>
            <content:encoded><![CDATA[<h4>A systems-oriented walkthrough of what changes when you bring Triton’s programming model from GPUs to NPUs: execution model, memory hierarchy, tiling, and compiler responsibilities.</h4><p>If you have written Triton kernels before, you probably have a mental model that looks like this:</p><ol><li>There is a <strong>grid of blocks</strong>, each block is a small <em>Single Program Multiple Data (SPMD) </em>program.</li><li>Inside a block, you operate on <strong>vectors of elements </strong>using tl.arange , tl.load , tl.store .</li><li>Under the hood, the compiler maps this onto a <strong>GPU execution model: <br>- </strong>Warps/Wavefronts<br>- Global vs shared vs local memory<br>- Hardware threads and <em>Single Instruction Multiple Threads (SIMT) execution</em></li></ol><p>Now imagine taking that same Triton kernel and asking:</p><p><strong>“What would it take to run this on a Neural Processing Unit (NPU) instead of a GPU?”</strong></p><p>A small backend tweak? It isn’t.</p><p>This post is about that gap:</p><blockquote>What changes when you leave the GPU world, and what extra work does the compiler have to do to make Triton fit an NPU?</blockquote><p>I’ll focus on four axes:</p><ol><li>Execution model: warps vs tiles</li><li>Memory hierarchy: shared memory vs SRAM + DMA</li><li>Tiling and shapes: flexible vs fixed-size engines</li><li>Control and scheduling: latency-hiding vs explicit orchestration</li></ol><h3>Triton’s “GPU Mental Model” in 60 seconds</h3><p>Let’s briefly fix terms.</p><p>In the usual GPU world, a Triton kernel looks like a <strong>block program:</strong></p><pre>@triton.jit<br>def add_kernel(X_ptr, Y_ptr, Z_ptr, N,<br>               BLOCK_SIZE: tl.constexpr):<br>    pid = tl.program_id(0)  # which block am I?<br>    offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)<br>    mask = offsets &lt; N<br>    x = tl.load(X_ptr + offsets, mask=mask)<br>    y = tl.load(Y_ptr + offsets, mask=mask)<br>    tl.store(Z_ptr + offsets, x + y, mask=mask)</pre><p>Your mental model:</p><ol><li>One <strong>program instance </strong>per block ( program_id() ).</li><li>Each program instance handles BLOCK_SIZE elements in parallel.</li><li>The hardware has:<br>- A large global memory.<br>- A smaller <strong>shared memory region</strong> per block.<br>- Hardware threads that execute the SPMD code in lockstep groups (warps).</li></ol><p>Under the hood, the Triton compiler:</p><ul><li>Maps tl.arange vectors to <strong>lanes in a warp/wavefront.</strong></li><li>Uses <strong>GPU shared memory</strong> to implement explicit tiling and reuse.</li><li>Relies on the GPU to hide latency via massive threading and HW scheduling.</li></ul><p>So far, so good.</p><h3>What an NPU looks like from a compiler’s POV</h3><p>“NPU” is a fuzzy term I think, but a lot of NPUs share some traits:</p><ol><li>They are <strong>tile-oriented:<br>- </strong>Matrix cores that operate on, say, 16x16 or 32x32 blocks at a time.<br>- Data often must be explicitly staged into <strong>on-chip SRAM </strong>in specific layouts.</li><li>They have <strong>limited </strong>or no <strong>general-purpose threads:<br>- </strong>Less like SIMT threads, more like <strong>coarse-grained kernels</strong> or <strong>commands</strong> to a fixed-function unit.</li><li>The memory story is more like:<br>- DRAM/HBM off-chip.<br>- One or more levels of SRAM/scratchpad memory on-chip.<br>- Tiny buffers inside the compute units themselves.</li></ol><p>There might <em>still </em>be something like:</p><ul><li>A grid of cores/tiles,</li><li>Some concept of “parallel workers”,</li></ul><p>… but the details differ enough that your implicit GPU assumptions break.</p><h3>Execution Model: from warps to tiles</h3><p>On a GPU:</p><ul><li>Your Triton block can <strong>assume </strong>a bunch of hardware threads execute in lockstep.</li><li>You get <strong>lane-wise parallelism</strong> for free:<br>- tl.arange gives you a vector of indices.<br>- Each lane does loads/stores/arithmetic.</li><li>The compiler can map this to warps and vector units in a fairly generic way.</li></ul><p>On an NPU:</p><ul><li>There may be no <strong>general-purpose warp/thread machinery.</strong></li><li>You often have <strong>matrix/tensor cores that want:<br>- </strong>fixes shapes ( MXK , KxN )<br>- specific data layouts (e.g., blocked, interleaved)</li><li>“One block of Triton” may need to be interpreted as “<strong>one tile’s worth of work”, </strong>i.e., the compiler is responsible for mapping:<strong><br>- </strong>program_id<strong> </strong>→ tile coordinates in an activation/output tensor.<br>- tl.arange → elements inside that tile, arrange to match the NPU’s vector/tensor instructions.</li></ul><p>This shifts responsibility:</p><blockquote>On GPUs, the hardware provides the thread + warp abstractions. On NPUs, the compiler often has to <strong>build</strong> an equivalent abstraction, or bypass it and map directly to tile-level instructions.</blockquote><p>Practically, your backend needs to answer questions like:</p><ul><li>“What does BLOCK_SIZE even mean when our hardware works in 16x16 tiles?”</li><li>“Is program_id mapping to output tiles, channels, or something else?</li><li>“Do we treat each Triton kernel as a single tile, or as a small loop over multiple tiles?”</li></ul><h3>Memory hierarchy: shared memory vs SRAM + DMA</h3><p>Triton on GPUs:</p><ul><li><strong>Global Memory: </strong>large, high-latency, high-bandwidth DRAM.</li><li><strong>Shared memory: </strong>per-block on-chip RAM, explicitly addressable.</li><li><strong>Registers: </strong>per-thread, not directly addressable but used by the compiler.</li></ul><p>You commonly write patterns like:</p><pre># Load a tile from global to shared<br>a_tile = tl.load(A_ptr + a_offsets)<br>b_tile = tl.load(B_ptr + b_offsets)<br><br># Do compute using the tiles<br>...</pre><p>The Triton compiler, with GPU backend, maps:</p><ul><li>The tl.load with certain strides and shapes to global loads and staging in shared memory.</li><li>Reuse inside the block uses that shared memory.</li></ul><p>On NPUs:</p><ul><li>The “Shared Memory” is usually an explicit <strong>SRAM </strong>region that you manage via:<br>- explicit loads/stores, or<br>- explicit DMA-like copy ops, or<br>- specialized “load tile” instructions.</li><li>The boundary between “global” and “local” is sharper:<br>- You <em>must </em>move tiles into SRAM before certain ops,<br>- or the op simply isn’t legal (e.g., matrix cores need data in SRAM).</li></ul><p>This means your Triton→NPU pipeline needs:</p><ol><li>A way to <strong>interpret </strong>tl.load / tl.store <strong>patterns </strong>as:<br>- “global DRAM access” vs<br>- “local SRAM access”.</li><li>A <strong>promotion/tiling </strong>strategy:<br>- Decide which tensors/tiles to stage into SRAM.<br>- Insert explicit copy ops (e.g., MLIR linalg.copy / memref.copy — like patterns in your internal IR).</li><li>Concrete Mapping:<br>- “This region of the Triton kernel corresponds to ‘global → SRAM’ stage.”<br>- “This region corresponds to ‘compute tile in SRAM’.”<br>- “This region corresponds to ‘write tile back’.”</li></ol><p>On GPUs, a lot of this can be done “by convention”; however, on NPUs, the <strong>IR and backend </strong>must make these movies explicit for hardware cooperation.</p><h3>Tiling and shapes: flexible block sizes vs fixed engines</h3><p>On GPUs, Triton gives you freedom:</p><ul><li>BLOCK_SIZE can be 128, 256, 512.</li><li>You try sizes empirically, use attuning, and let the compiler map them to warps and memory transactions.</li></ul><p>On NPUs, you often do not have the same degree of freedom:</p><ul><li>The hardware says:<br>- “I like 16x16 tiles”<br>- or “I have 32-wide dot-product lanes”<br>- or “I want 64 elements per tile with this specific layout”</li><li>Your blocking strategy is constrained by:<br>- tile sizes,<br>- SRAM capacity,<br>- alignment rules.</li></ul><p>This has knock-on effects for Triton:</p><ul><li>Your BLOCK_SIZE and indexing logic needs to be compatible with hardware requirements.</li><li>Some Triton kernels that flexibly iterate over odd-tailed sizes mayb need:<br>- more complex cleanup code, or<br>- separate “main loop vs tail loop” code paths, or<br>- an NPU backend that explicitly <strong>pads </strong>or <strong>masks</strong> work into full tiles.</li></ul><p>So a backend might:</p><ul><li>Force or suggest certain BLOCK_SIZEs to Triton,</li><li>Rewrite certain indexing patterns into:<br>- a main region that runs on exact tile multiples, and<br>- a scalar-ish tail region that runs on a fallback engine or in software.</li></ul><p><strong>Control and scheduling: latency hiding vs orchestration</strong></p><p>On GPUs:</p><ul><li>You count on:<br>- hardware thread scheduling, <br>- massive parallelism,<br>- warp-level latency hiding.</li><li>Your Triton kernel is mostly <strong>local reasoning:<br>- “</strong>My block does this.”<br>- “The grid operates on the full tensor.”</li><li>The global scheduler (CUDA runtime + GPU hardware) handles:<br>- when blocks run,<br>- how they overlap.</li></ul><p>On NPUs:</p><ul><li>You cannot always assume:<br>- a hard “block scheduler” that hides latency,<br>- or thousands of in-flight threads.</li><li>Scheduling might be <strong>coarser and more explicit:<br>- </strong>You must submit tiles/commands to an engine.<br>- You orchestrate copies and compute so that SRAM isn’t overcommitted. <br>- You might even have to schedule different pipelines: DMA engine vs compute engine vs post-processing.</li></ul><p>Implication for Triton→NPU compiler:</p><ul><li>The Triton kernel IR is <strong>necessary but not sufficient.<br>- </strong>It describes what one logical block of work does.<br>- The backend still needs a “second tier” or orchestration: global tiling, work distribution across cores/engines, overlap between copy and compute (hardware permitting).</li><li>Leverage another IR framework, such as MLIR to:<br>- describe pipeline stages<br>- marking regions as “compute on tile” vs. “move data around”.</li></ul><h3>What stays the same: why Triton is still attractive on NPUs</h3><p>With all those caveats, the reader might ask: “Why even use Triton on NPUs?”</p><p>There are real advantages:</p><ul><li>Triton’s <strong>block-level programming model</strong> is still a convenient way to express:<br>- <strong>per-tile compute,<br>- </strong>patterns of reuse,<br>- coalesced-ish access patterns.</li><li>You get:<br>- a <strong>Pythonic <em>Domain Specific Language (DSL)</em></strong><em> </em>with decent ergonomics<em>,<br>- </em>a well-understood set of primitives ( tl.load , tl.store , tl.dot , etc.)<br>- a familiar mental model for many compiler and ML engineers.</li></ul><p>If your NPU backend is well designed, you can:</p><ul><li>Treat a Triton block as a “program for one tile or small tile group”,</li><li>Use a separate scheduling layer to:<br>- tile the whole tensor,<br>- assign tiles to cores,<br>- manage data movement.</li><li>Reuse a lot of Triton’s <strong>front-end</strong> and <strong>mid-level IR</strong> analysis machinery:<br>- shape reasoning, <br>- type checking,<br>- vectorized index computations.</li></ul><p>The hard part is <strong>the mapping layer:</strong></p><blockquote>Taking “I operate on BLOCK_SIZE elements with these offsets” and turning it into “I operate on these NPU’s tile shapes with this SRAM layout and these instructions.”</blockquote><h3>What this means for compilers (and for you)</h3><p>If you are a compiler engineer thinking about Triton on NPUs, here’s the distilled checklist:</p><ol><li><strong>Execution model mapping, </strong>decide what one Triton “block” means:<br>- one tile,<br>- a strip of tiles,<br>- or something else.<br>- map program_id dims to a physical core/tile coordinates.</li><li><strong>Memory hierarchy modeling<br>- </strong>Represent global vs SRAM vs any special buffers in your IR (MLIR memref spaces, for example). <br>- Insert explicit promotion/demotion (copy) patterns where needed.</li><li><strong>Shape and tiling constraints<br>- </strong>Enforce or auto-tune BLOCK_SIZE / tile size to match hardware constraints. <br>- Handle tails explicitly (masking, padding, or fallback paths).</li><li><strong>Scheduling and orchestration<br>- </strong>Decide where global tiling and inter-core scheduling lives: directly in the Triton IR, in an MLIR dialect, or in a separate runtime. <br>- Exploit any overlap between DMA and compute that the hardware supports.</li><li><strong>Debuggability</strong><br>- Dump intermediate IRs for tile extraction, SRAM promotion, compute, NPU-specific codegen<br>- When performance is odd, you will end up staring at these a lot.</li></ol><p>The punchline:</p><blockquote><em>Triton’s model is “CUDA, but nicer.”<br>For NPUs, you want “Tile compute, but nicer,” with a compiler stack that translates between the two worlds.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31408c1c0ca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modeling Memory Hierarchies in MLIR: From DRAM to SRAM]]></title>
            <link>https://medium.com/@samarth.colleges/modeling-memory-hierarchies-in-mlir-from-dram-to-sram-ebe9b505149e?source=rss-26469bc63d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebe9b505149e</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[llvm]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Samarth Narang]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 02:06:34 GMT</pubDate>
            <atom:updated>2025-12-08T02:06:34.298Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical walkthrough of how to represent global memory, local scratchpads, and tiles in MLIR using memref types, memory spaces, and explicit copies.</h4><p>On real hardware, “memory” is not one thing:</p><ul><li>On CPUs: DRAM, multiple cache levels, registers.</li><li>On GPUs: global memory, on-chip <strong>shared</strong> / <strong>local</strong> memory, register files.</li><li>On NPUs: DRAM, on-chip SRAM, tiny “matrix core” buffers.</li></ul><p>Performance most often depends more on <em>where </em>the data lives and <em>how </em>it moves between levels than on raw <em>Floating Operations per Seconds (FLOPs).</em></p><p>Most compiler <em>Intermediate Representations (IRs) </em>hide beyond pointers and intrinsics. MLIR allows you to do better:</p><blockquote>Model the <strong>memory hierarchy explicitly </strong>in the IR, and make “copy tile to fast memory and compute there” a first-class transformation.</blockquote><p>This post is a tour of how to do that:</p><ol><li>memref types and memory spaces</li><li>Subviews and tiles</li><li>Explicit copies between DRAM and SRAM-like buffers</li><li>A full “load tile → compute → store tile” example</li><li>How promotion passes fit into the landscape</li><li>How this maps to heterogeneous hardware</li></ol><h3>memref and memory spaces: one type, many levels</h3><p>The workhorse for modeling memory in MLIR is the <strong>memref </strong>type:</p><pre>memref&lt;1024xf32&gt;      // 1D buffer of 1024 floats<br>memref&lt;64x64xf16&gt;     // 2D buffer of 64x64 half-precision floats</pre><p>By default, that memref lives in some “default” memory (usually address space 0 under the hood).</p><p>MLIR lets you attach a <strong>memory space </strong>(address space) to the type:</p><pre>memref&lt;1024xf32, 0&gt;   // memory space 0 (e.g., DRAM / global)<br>memref&lt;128xf32, 1&gt;    // memory space 1 (e.g., on-chip SRAM / shared)<br>memref&lt;16x16xf16, 2&gt;  // memory space 2 (e.g., tensor-core tile buffer)</pre><p>You, your dialect, and your backend decide what these spaces <em>mean</em>:</p><ol><li>0 — global DRAM/High Bandwidth Memory (HBM)</li><li>1 — on-chip scratchpad memory/shared memory</li><li>2 — special per-core buffer</li></ol><blockquote>The important bit: Different memory levels become different <strong>types, </strong>NOT just comments, which means:</blockquote><ul><li>You can write passes that only operate on certain memory spaces.</li><li>You can enforce that certain ops only accept memref&lt;..., 1&gt; (e.g., a “tensor core” op that only works on local tiles).</li><li>You can statically track where data lives.</li></ul><h3>Subviews and tiles: carving out chunks</h3><p>To make memory hierarchy matter, you usually <strong>tile:</strong></p><ul><li>Work on a block of the matrix that fits in faster memory.</li><li>Compute there.</li><li>Write results back.</li></ul><p>MLIR has memref.subview for carving out sub-buffers:</p><pre>// Given A : memref&lt;MxNxf32&gt;<br>%tile = memref.subview %A[%i, %j] [Tm, Tn] [1, 1]<br>  : memref&lt;?x?xf32&gt; to memref&lt;?x?xf32&gt;</pre><p>Interpretation:</p><ul><li>Start at (%i, %j) in A .</li><li>Take a tile of size [Tm, Tn] .</li><li>Stride of [1,1] .</li></ul><p>%tile is a <em>view: </em>a window into the original A ; no copy yet, just indexing sugar.</p><p>You can similarly take subviews of larger matrices, such as B and C for tiled matrix multiplies, convolutions, etc.</p><h3>Explicit Copies: DRAM ↔ SRAM</h3><p>To model “load tile from DRAM into local SRAM”, you use explicit <strong>copy </strong>operations:</p><p>Assume</p><pre>%A   : memref&lt;MxNxf32, 0&gt;      // global<br>%tile: memref&lt;TmxTnxf32, 1&gt;    // local</pre><p>You can do an initial copy</p><pre>// Copy a subview of A in DRAM (space 0) to a tile in local SRAM (space 1).<br>linalg.copy(%A_subview, %tile)<br>  : memref&lt;TmxTnxf32, 0&gt;, memref&lt;TmxTnxf32, 1&gt;</pre><p>And after computation, copy back</p><pre>linalg.copy(%tile, %C_subview)<br>  : memref&lt;TmxTnxf32, 1&gt;, memref&lt;TmxTnxf32, 0&gt;</pre><p>This seems analogous to cache blocking, but instead of praying that the “hardware prefetcher/cache zone hit”, we take finer-control and say “I am explicitly staging data into a faster memory level, doing compute there, and then writing back.”</p><p>The IR becomes a <em>script</em> for memory movement.</p><h3>A full example: tiled 2D add with local tiles</h3><p>Let’s walk a simple example that still shows the pattern.</p><p>We’ll take a 2D add:</p><blockquote><em>C[i, j] = A[i, j] + B[i, j]</em></blockquote><p>and do it in tiles:</p><ul><li>A, B, C live in DRAM-like memory (space 0).</li><li>We allocate a tile in faster memory (space 1).</li><li>For each tile:<br>- Copy a block of A and B into local tiles.<br>- Compute C_tile = A_tile + B_tile inside the fast memory.<br>- Copy C_tile back to the global C.</li></ul><h4>Setup: Global Buffers + Local Tiles</h4><pre>module {<br>  func.func @tiled_add_2d(<br>      %A : memref&lt;?x?xf32, 0&gt;,<br>      %B : memref&lt;?x?xf32, 0&gt;,<br>      %C : memref&lt;?x?xf32, 0&gt;,<br>      %M : index, %N : index) {<br><br>    %Tm = arith.constant 64 : index   // tile height<br>    %Tn = arith.constant 64 : index   // tile width<br><br>    // Local tiles in memory space 1 (e.g., SRAM).<br>    %A_tile = memref.alloc() : memref&lt;64x64xf32, 1&gt;<br>    %B_tile = memref.alloc() : memref&lt;64x64xf32, 1&gt;<br>    %C_tile = memref.alloc() : memref&lt;64x64xf32, 1&gt;<br><br>    %c0 = arith.constant 0 : index<br>    %c1 = arith.constant 1 : index<br><br>    // Outer loops over tiles.<br>    scf.for %ii = %c0 to %M step %Tm {<br>      scf.for %jj = %c0 to %N step %Tn {<br>        // Edge-handling: adjust tile sizes at boundaries.<br>        %M_rem = arith.subi %M, %ii : index<br>        %N_rem = arith.subi %N, %jj : index<br>        %tm = arith.minui %Tm, %M_rem : index<br>        %tn = arith.minui %Tn, %N_rem : index<br><br>        // Subviews into global memrefs (space 0).<br>        %A_sub = memref.subview %A[%ii, %jj] [%tm, %tn] [1, 1]<br>          : memref&lt;?x?xf32, 0&gt;<br>            to memref&lt;?x?xf32, strided&lt;[?, 1], offset: ?&gt;, 0&gt;<br>        %B_sub = memref.subview %B[%ii, %jj] [%tm, %tn] [1, 1]<br>          : memref&lt;?x?xf32, 0&gt;<br>            to memref&lt;?x?xf32, strided&lt;[?, 1], offset: ?&gt;, 0&gt;<br>        %C_sub = memref.subview %C[%ii, %jj] [%tm, %tn] [1, 1]<br>          : memref&lt;?x?xf32, 0&gt;<br>            to memref&lt;?x?xf32, strided&lt;[?, 1], offset: ?&gt;, 0&gt;<br><br>        // Subviews into local tiles (space 1) of the same logical size.<br>        %A_tile_sub = memref.subview %A_tile[0, 0] [%tm, %tn] [1, 1]<br>          : memref&lt;64x64xf32, 1&gt;<br>            to memref&lt;?x?xf32, strided&lt;[64, 1]&gt;, 1&gt;<br>        %B_tile_sub = memref.subview %B_tile[0, 0] [%tm, %tn] [1, 1]<br>          : memref&lt;64x64xf32, 1&gt;<br>            to memref&lt;?x?xf32, strided&lt;[64, 1]&gt;, 1&gt;<br>        %C_tile_sub = memref.subview %C_tile[0, 0] [%tm, %tn] [1, 1]<br>          : memref&lt;64x64xf32, 1&gt;<br>            to memref&lt;?x?xf32, strided&lt;[64, 1]&gt;, 1&gt;<br><br>        // 1) Copy A, B from global (space 0) to local tiles (space 1).<br>        linalg.copy<br>          ins(%A_sub : memref&lt;?x?xf32, strided&lt;[?, 1], offset: ?&gt;, 0&gt;)<br>          outs(%A_tile_sub : memref&lt;?x?xf32, strided&lt;[64, 1]&gt;, 1&gt;)<br><br>        linalg.copy<br>          ins(%B_sub : memref&lt;?x?xf32, strided&lt;[?, 1], offset: ?&gt;, 0&gt;)<br>          outs(%B_tile_sub : memref&lt;?x?xf32, strided&lt;[64, 1]&gt;, 1&gt;)<br><br>        // 2) Compute C_tile = A_tile + B_tile in local memory.<br>        linalg.generic {<br>            indexing_maps = [<br>              affine_map&lt;(i, j) -&gt; (i, j)&gt;,<br>              affine_map&lt;(i, j) -&gt; (i, j)&gt;,<br>              affine_map&lt;(i, j) -&gt; (i, j)&gt;<br>            ],<br>            iterator_types = [&quot;parallel&quot;, &quot;parallel&quot;]<br>          }<br>          ins(%A_tile_sub, %B_tile_sub<br>              : memref&lt;?x?xf32, strided&lt;[64, 1]&gt;, 1&gt;,<br>                memref&lt;?x?xf32, strided&lt;[64, 1]&gt;, 1&gt;)<br>          outs(%C_tile_sub<br>              : memref&lt;?x?xf32, strided&lt;[64, 1]&gt;, 1&gt;) {<br>        ^bb0(%a : f32, %b : f32, %c_in : f32):<br>          %sum = arith.addf %a, %b : f32<br>          linalg.yield %sum : f32<br>        }<br><br>        // 3) Copy C_tile back to global C.<br>        linalg.copy<br>          ins(%C_tile_sub<br>              : memref&lt;?x?xf32, strided&lt;[64, 1]&gt;, 1&gt;)<br>          outs(%C_sub<br>              : memref&lt;?x?xf32, strided&lt;[?, 1], offset: ?&gt;, 0&gt;)<br>      }<br>    }<br>    memref.dealloc %A_tile : memref&lt;64x64xf32, 1&gt;<br>    memref.dealloc %B_tile : memref&lt;64x64xf32, 1&gt;<br>    memref.dealloc %C_tile : memref&lt;64x64xf32, 1&gt;<br><br>    return<br>  }<br>}</pre><p>How to read this:</p><ul><li>memref&lt;...,0&gt; = DRAM/global space.</li><li>memref&lt;64x64xf32, 1&gt; = local scratchpad memory space.</li><li>Outer loops pick each tile (i1, j1) .</li><li>memref.subview carves out that tile from global buffers and from local tiles.</li><li>linalg.copy + linalg.generic express:<br>- Load tile into SRAM<br>- Do computation entirely in SRAM<br>- Write tile back to DRAM</li></ul><p>You have successfully made promotion into a <em>first-class pattern </em>in the IR.</p><h3>Promotion Passes: doing this automatically</h3><p>Writing the above MLIR by hand could quickly increase in tediousness as complexity of the kernels increases. The real power comes from <strong>passes</strong> that</p><ol><li>Look at high-level linalg ops on global memrefs.</li><li>Insert memref.subview and linalg.copy before the compute.</li><li>Insert linalg.copy after the compute.</li><li>Use subviews of the tiles as the inputs/outputs to the computation.</li></ol><p>Conceptually,</p><pre>Before:<br>  linalg.generic on %A : memref&lt;..., 0&gt;, %B : memref&lt;..., 0&gt;, %C : memref&lt;..., 0&gt;<br><br>After:<br>  for each tile:<br>    subview globals      -&gt; subview locals<br>    copy global -&gt; local<br>    linalg.generic on local memref&lt;..., 1&gt;<br>    copy local -&gt; global</pre><p>Because <strong>memory spaces are part of the type</strong>, the pass can:</p><ul><li>Assert that the local space is actually mapped to a physical fast memory.</li><li>Avoid mixing up buffers from different spaces.</li><li>Make the backend’s job straightforward: “this buffer must go into local SRAM, don’t spill it to DRAM.”</li></ul><p>From a performance engineer’s perspective, this is great:</p><blockquote><em>You can literally “diff” the IR and see memory traffic decisions.</em></blockquote><h3>How this maps to real hardware</h3><p>This all gets more interesting when you imagine specific targets.</p><h4>GPUs</h4><ul><li>memref&lt;..., 0&gt; → global memory (device DRAM)</li><li>memref&lt;..., 1&gt; → block-level shared memory</li><li>memref&lt;..., 2&gt; → per-thread local memory (or some special scratchpad)</li></ul><p>A typical pattern:</p><ul><li>Stage blocks of the input into shared memory (space 1).</li><li>Use GPU-specific ops (e.g., gpu.thread_id, gpu.block_id) to index into tiles.</li><li>Optionally use vector ops or “mma” style ops for tensor cores.</li></ul><p>You might have a pass that:</p><ul><li>Promotes linalg.matmul operands into shared memory.</li><li>Generates loops over tiles.</li><li>Then lowers to gpu.launch + device code in the GPU dialect.</li></ul><h4>NPUs / custom accelerators</h4><p>Many NPUs expose:</p><ul><li>A big off-chip DRAM.</li><li>A mid-sized on-chip SRAM.</li><li>Tiny fixed-size buffers inside matrix-multiply engines.</li></ul><p>Mapping:</p><ul><li>memref&lt;..., 0&gt; → DRAM</li><li>memref&lt;... tile shape..., 1&gt; → on-chip SRAM</li><li>memref&lt;... tile shape..., 2&gt; → per-PE or per-engine tile buffer</li></ul><p>You can even make ops that <em>require</em> space 2:</p><pre>my_accel.matmul_tile<br>  ins(%A_tile : memref&lt;16x16xi8, 2&gt;, %B_tile : memref&lt;16x16xi8, 2&gt;)<br>  outs(%C_tile : memref&lt;16x16xi32, 2&gt;)</pre><p>Now the lowering pipeline is forced to:</p><ul><li>Allocate/prepare tiles in space 2,</li><li>Copy from DRAM/SRAM into them,</li><li>Call my_accel.matmul_tile,</li><li>Copy results back.</li></ul><h4>CPUs</h4><p>CPUs have caches, which are usually <strong>not</strong> directly addressable in the IR. But:</p><ul><li>You can still model tiling as separate levels:<br>- Outer tile loops: “should fit into L2 or L3”<br>- Inner tile loops: “should fit into L1”</li><li>You might use different memory spaces to hint:<br>- memref&lt;..., 0&gt; = “regular heap”<br>- memref&lt;..., 1&gt; = “stack / alloca region likely to be cached tightly”</li><li>memref&lt;..., 0&gt; = “regular heap”</li></ul><p>Even if the hardware doesn’t expose SRAM directly, modeling memory in this way:</p><ul><li>Makes your blocking/tiling explicit.</li><li>Makes it easier to reason in a cost model: “this loop nest performs K loads from DRAM and L loads from small tiles.”</li></ul><h3>Interactions with Layout and Vectorization</h3><p>Memory hierarchy doesn’t live alone. It interacts with:</p><ul><li><strong>Layout</strong> (row-major vs column-major vs blocked layouts).</li><li><strong>Vectorization</strong> (alignment, contiguous elements).</li><li><strong>Parallelism</strong> (which threads/cores share which tile).</li></ul><p>In MLIR, you can express layout with:</p><ul><li>Multi-dimensional memref types.</li><li>Custom layout maps or attributes.</li><li>Pack/unpack patterns that convert between “logical” and “physical” layouts.</li></ul><p>When you combine that with memory spaces, you get “stacked” transformations:</p><ol><li>Start with high-level tensor / linalg ops on global buffers.</li><li>Apply <strong>layout transforms</strong> (e.g., pack to blocked layout).</li><li>Apply <strong>tiling and promotion</strong>:<br>- Global blocked buffers → local SRAM tiles.</li><li>Apply <strong>vectorization</strong> inside the tiles.</li><li>Lower to LLVM or GPU/accelerator dialects.</li></ol><p>Each stage is visible in the IR. Each one is debuggable and optimizable.</p><h3>Takeaways</h3><p>The big point:</p><blockquote><em>MLIR doesn’t force you to treat memory as “just a pointer.”<br>It gives you the tools to model </em><strong><em>memory hierarchy as a first-class part of the IR</em></strong><em>.</em></blockquote><p>Concretely:</p><ul><li>memref&lt;shape, space&gt; encodes which memory level a buffer lives in.</li><li>memref.subview and linalg.copy model tiles and explicit movement.</li><li>Passes can <em>promote</em> from global to local memory in a structured way.</li><li>That structure makes it easier to reason about performance, and easier for backends to map to real SRAM/shared memory.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebe9b505149e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLIR for People Who Already Know LLVM: A Guided Tour]]></title>
            <link>https://medium.com/@samarth.colleges/mlir-for-people-who-already-know-llvm-a-guided-tour-51197102ece8?source=rss-26469bc63d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/51197102ece8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[llvm]]></category>
            <dc:creator><![CDATA[Samarth Narang]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 17:00:44 GMT</pubDate>
            <atom:updated>2025-12-01T17:00:44.640Z</atom:updated>
            <content:encoded><![CDATA[<h4>If you’re fluent in LLVM IR, MLIR feels both familiar and weird. This post builds a direct mapping: from modules, functions, and basic blocks to dialects, regions, and patterns.</h4><p>If you already speak <strong>LLVM IR, </strong>MLIR can feel like a cousin who redesigned the house while you were out:</p><ul><li>Still <em>Static Single Assignment </em>(SSA).</li><li>Still modules, functions, blocks, and values.</li><li>Still a pass pipeline.</li></ul><p>…but suddenly there are <strong>dialects, regions inside operations, </strong>and IR that looks like:</p><pre>#map0 = affine_map&lt;(i) -&gt; (i)&gt;<br><br>module {<br>  func.func @foo(%arg0: tensor&lt;4xf32&gt;,<br>                 %arg1: tensor&lt;4xf32&gt;,<br>                 %arg2: tensor&lt;4xf32&gt;) {<br>    %out = linalg.generic<br>      {<br>        indexing_maps = [#map0, #map0, #map0],<br>        iterator_types = [&quot;parallel&quot;]<br>      }<br>      ins(%arg0, %arg1 : tensor&lt;4xf32&gt;, tensor&lt;4xf32&gt;)<br>      outs(%arg2 : tensor&lt;4xf32&gt;) {<br>        ^bb0(%a : f32, %b : f32, %c : f32):<br>          %sum = arith.addf %a, %b : f32<br>          linalg.yield %sum : f32<br>      } -&gt; tensor&lt;4xf32&gt;<br>    return<br>  }<br>}</pre><p>This post is a <strong>guided tour of MLIR from an LLVM-IR mental model. I’ll assume:</strong></p><ul><li>You are comfortable with LLVM IR concepts, such as modules, functions, basic blocks, passes.</li><li>You have use opt and stared at IR for debugging or performance work.</li></ul><p>The goal is to leave you thinking:</p><blockquote><em>“Ah, MLIR is basically SSA + nested regions + pluggable instruction sets, with a nicer way to stage transformations.”</em></blockquote><h3>TL;DR: The Mental Mapping</h3><p>If you want the short version, here’s the dictionary:</p><ul><li><strong>LLVM Module </strong>⟶ MLIR module operation (plus other top-level ops).</li><li><strong>Function </strong>⟶ MLIR func.func (or llvm.func, gpu.func , etc.).</li><li><strong>Instruction </strong>⟶ MLIR operation (an “op”).</li><li><strong>Basic Block </strong>⟶ MLIR block (same idea, but lives <em>inside </em>regions<em>).</em></li><li><strong>SSA Value </strong>⟶ MLIR value (same idea, but block args are more pervasive).</li><li><strong>Instruction Set (incl. intrinsics) </strong>⟶ <strong>dialects: </strong>arith , memref , linalg , llvm , gpu ,..</li><li><strong>Single flat CFG </strong>⟶ nested regions: ops can contain regions, which contain blocks, which contain ops, which can contain more regions, etc.</li></ul><p>With that map in your head, let’s go piece by piece.</p><h3>Modules, functions, blocks, and values</h3><p>Start with the comforting part: MLIR is still SSA, and the top-level shape will feel familiar.</p><h4>LLVM IR Mental Model</h4><p>In LLVM, you think of:</p><ul><li>A <strong>Module</strong> containing:<br>- Globals <br>- Functions</li><li>A <strong>Function</strong> containing:<br>- <strong>Basic Blocks</strong></li><li>A <strong>Basic Block</strong> containing:<br>- <strong>Instructions</strong></li><li><strong>SSA Values</strong> defined by instructions or block arguments (for phi nodes).</li></ul><h4>MLIR Mental Model</h4><p>In MLIR, the basic hierarchy is:</p><ul><li>A module operation containing:<br>- Other top-level operations (e.g., func.func, memref.global, etc.)</li><li>A func.func operation containing:<br>- One or more <strong>regions.</strong></li><li>A <strong>region</strong> containing:<br>- One or more <strong>blocks.</strong></li><li>A <strong>block</strong> containing:<br>- One or more <strong>operations (ops).</strong></li><li><strong>SSA values</strong> produced by:<br>- Operations<br>- Block arguments</li></ul><p>So instead of “module → function → block → instruction,” you can think:</p><blockquote><strong><em>Operations are all you need!</em></strong><em> A module is an op with regions, functions are ops with regions, blocks contain ops, and ops produce values.</em></blockquote><h4>Example: Hello, function</h4><p><strong>LLVM IR:</strong></p><pre>define i32 @add(i32 %a, i32 %b) {<br>entry:<br>  %sum = add i32 %a, %b<br>  ret i32 %sum<br>}</pre><p><strong>MLIR</strong> ( func + arith dialects):</p><pre>module {<br>  func.func @add(%a: i32, %b: i32) -&gt; i32 {<br>    %sum = arith.addi %a, %b : i32<br>    return %sum : i32<br>  }<br>}</pre><p>Same structure, but note:</p><ul><li>The module is an <strong>op</strong>.</li><li>func.func is an <strong>op</strong> in the func dialect.</li><li>arith.addi is an <strong>op</strong> in the arith dialect.</li></ul><p>Once you internalize “everything is an op,” MLIR stops feeling alien.</p><h3>Dialects: Instruction Sets for Different Domains</h3><p>LLVM IR has a fixed instruction set, plus <strong>intrinsics</strong> as escape hatches.</p><p>MLIR instead has <strong>dialects</strong>: collections of operations and types under a namespace.</p><h4>Dialects as Namespaces</h4><p>A <strong>dialect</strong> is essentially a namespace + instruction set + type system. Some common ones:</p><ul><li>builtin – core stuff like module, unrealized_conversion_cast.</li><li>func – functions, calls, returns.</li><li>arith – scalar arithmetic, comparisons, constants.</li><li>memref – memory references, loads/stores, allocations.</li><li>tensor – value-semantic tensors.</li><li>linalg – structured linear algebra: linalg.matmul, linalg.generic.</li><li>scf – structured control flow: scf.for, scf.if, scf.while.</li><li>gpu – GPU launching, blocks, threads.</li><li>llvm – an MLIR encoding of LLVM-like IR.</li></ul><p>You see them as prefixes:</p><pre>%0 = arith.addi %a, %b : i32<br>%1 = memref.load %ptr[%idx] : memref&lt;1024xf32&gt;<br>%2 = linalg.matmul<br>      ins(%A, %B : memref&lt;...&gt;, memref&lt;...&gt;)<br>      outs(%C : memref&lt;...&gt;)</pre><p>LLVM mental model:</p><ul><li>Intrinsics like llvm.memcpy.* are one-off extensions to a fixed core.</li><li>MLIR dialects are <strong>whole instruction sets</strong> for specific domains:<br>- Structured linear algebra (linalg)<br>- GPU programming (gpu)<br>- Quantization (quant)<br>- And, if needed, a “raw LLVM” world (llvm dialect)</li></ul><p>Why this matters:</p><ul><li>You can define <strong>new ops</strong> with custom semantics.</li><li>You keep <strong>domain-specific transforms</strong> local to a dialect.</li><li>You <strong>lower dialects in stages</strong>: from high level (linalg) to mid-level (scf/memref) to low-level (llvm).</li></ul><h3>Operations, Regions, and Nested Control Flow</h3><p>Here’s the other major structural shift.</p><p><strong>In LLVM</strong>:</p><ul><li>An instruction always lives <em>inside</em> a basic block.</li><li>Instructions never contain blocks.</li></ul><p><strong>In MLIR</strong>:</p><ul><li>An <strong>operation</strong> can contain <strong>regions</strong>.</li><li>A <strong>region</strong> contains blocks.</li><li>Blocks contain operations again.</li></ul><p>This lets you express <strong>nested control flow</strong> and <strong>hierarchical IR</strong>.</p><h4>Regions in Practice</h4><p>Take a simple loop in the scf dialect:</p><pre>scf.for %i = %c0 to %cN step %c1 {<br>  %val = memref.load %A[%i] : memref&lt;?xf32&gt;<br>  %two = arith.constant 2.0 : f32<br>  %result = arith.mulf %val, %two : f32<br>  memref.store %result, %A[%i] : memref&lt;?xf32&gt;<br>}</pre><p>What’s happening here:</p><ul><li>scf.for is an op that contains a region.</li><li>The region contains a block with the loop body.</li></ul><p>If you think in LLVM IR terms,</p><ul><li>The scf.for is roughly sugar for a small Control Flow Graph (CFG) of basic blocks with branches.</li><li>Instead of materializing that CFG explicitly, MLIR keeps it as a structured loop op with a region.</li></ul><p>That lets transformations reason about loops at a higher level, e.g., loop unrolling, fusion, etc.</p><h4>Nested IR everywhere</h4><p>Other examples of ops with regions:</p><ul><li>func.func contains a region for the function body.</li><li>linalg.generic contains a region for the computation body.</li><li>gpu.launch contains regions for kernel code.</li><li>scf.if contains regions for the “then” and “else” branches.</li></ul><p>Once you accept:</p><blockquote>Op ⟶ Regions ⟶ Blocks ⟶ Ops ⟶ …</blockquote><p>…the rest of MLIR starts to feel more natural.</p><h3>Types and Attributes</h3><p>MLIR’s type system will look familiar, but with more structure on top.</p><h4>SSA Value Types</h4><p>You’ll see things like:</p><pre>%0 = arith.addi %a, %b : i32<br>%1 = memref.load %A[%i] : memref&lt;1024xf32&gt;<br>%2 = tensor&lt;4x4xf32&gt;<br>%3 = vector&lt;8xf32&gt;</pre><p>Broadly:</p><ul><li>i32, f32, i64 – scalars, just like LLVM.</li><li>memref&lt;shape x element_type&gt; – memory references (pointers + shape/strides).</li><li>tensor&lt;shape x element_type&gt; – value-semantic tensors.</li><li>index – a special type for loop indices and sizes.</li><li>vector&lt;…&gt; – SIMD-style vectors.</li></ul><p>LLVM mental model:</p><ul><li>memref ≈ a more strongly typed, shaped pointer.</li><li>tensor ≈ multi-dimensional value (think SSA “array”; not just a pointer).</li></ul><h4>Attributes</h4><p>Attributes are <strong>immutable metadata values</strong> attached directly to ops and types. They’re part of the syntax, not an afterthought.</p><p><strong>Examples:</strong></p><pre>%0 = arith.constant 4 : i32<br>%1 = arith.constant dense&lt;0.0&gt; : tensor&lt;4xf32&gt;<br><br>#map0 = affine_map&lt;(i) -&gt; (i)&gt;<br><br>%2 = linalg.generic<br>  { indexing_maps = [#map0, #map0, #map0],<br>    iterator_types = [&quot;parallel&quot;] }<br>  ins(%A, %B : tensor&lt;?xf32&gt;, tensor&lt;?xf32&gt;)<br>  outs(%C : tensor&lt;?xf32&gt;) {<br>    ^bb0(%a : f32, %b : f32, %c_in : f32):<br>      %sum = arith.addf %a, %b : f32<br>      linalg.yield %sum : f32<br>  } -&gt; tensor&lt;?xf32&gt;</pre><ul><li>dense&lt;0.0&gt; is a <strong>dense elements attribute</strong>.</li><li>#map0 is an <strong>affine map attribute</strong>.</li><li>indexing_maps and iterator_types are <strong>named attributes</strong> on linalg.generic.</li></ul><p>LLVM mental model:</p><ul><li>Think of attributes as <strong>first-class metadata</strong>, in the same conceptual space as !dbg/!tbaa… but not just for debugging. They often <strong>define semantics</strong> of the op (especially in linalg, affine, etc.).</li></ul><h3>A Side-by-Side Example</h3><p>Let’s put it together with a simple vector add.</p><h4>LLVM IR</h4><pre>define void @vec_add(float* %a, float* %b, float* %c, i64 %N) {<br>entry:<br>  br label %loop<br><br>loop:<br>  %i = phi i64 [ 0, %entry ], [ %i_next, %loop ]<br><br>  %a_i_ptr = getelementptr float, float* %a, i64 %i<br>  %b_i_ptr = getelementptr float, float* %b, i64 %i<br>  %c_i_ptr = getelementptr float, float* %c, i64 %i<br><br>  %a_i = load float, float* %a_i_ptr<br>  %b_i = load float, float* %b_i_ptr<br>  %sum = fadd float %a_i, %b_i<br>  store float %sum, float* %c_i_ptr<br><br>  %i_next = add i64 %i, 1<br>  %cmp = icmp slt i64 %i_next, %N<br>  br i1 %cmp, label %loop, label %exit<br><br>exit:<br>  ret void<br>}</pre><p><strong>MLIR (High-Level)</strong></p><pre>module {<br>  func.func @vec_add(<br>      %A : tensor&lt;?xf32&gt;,<br>      %B : tensor&lt;?xf32&gt;,<br>      %C : tensor&lt;?xf32&gt;,<br>      %N : index) {<br>    %result = linalg.generic<br>      {<br>        indexing_maps = [<br>          affine_map&lt;(i) -&gt; (i)&gt;,<br>          affine_map&lt;(i) -&gt; (i)&gt;,<br>          affine_map&lt;(i) -&gt; (i)&gt;<br>        ],<br>        iterator_types = [&quot;parallel&quot;]<br>      }<br>      ins(%A, %B : tensor&lt;?xf32&gt;, tensor&lt;?xf32&gt;)<br>      outs(%C : tensor&lt;?xf32&gt;) {<br>        ^bb0(%a : f32, %b : f32, %c_in : f32):<br>          %sum = arith.addf %a, %b : f32<br>          linalg.yield %sum : f32<br>      } -&gt; tensor&lt;?xf32&gt;<br><br>    return<br>  }<br>}</pre><h3>What Changed?</h3><ul><li>The <strong>loop</strong> over i is implicit in:<br>- iterator_types = [&quot;parallel&quot;] <br>- The affine maps (i) -&gt; (i) telling us how to index inputs/outputs.</li><li>Address arithmetic (getelementptr) is replaced with <strong>affine indexing</strong>.</li><li>Loads/stores are implicit in the semantics of linalg.generic.</li></ul><p>The compiler can later:</p><ol><li>Lower linalg.generic → explicit scf.for loops.</li><li>Lower loops + tensors → memref loads/stores.</li><li>Lower to the llvm dialect, then to LLVM IR.</li></ol><p>You’re not losing control; you’re <strong>delaying commitment</strong> to low-level IR until later in the pipeline.</p><h3>Passes and Pipelines</h3><p>You’re probably used to opt:</p><pre>$ opt -mem2reg -loop-vectorize -instcombine ...</pre><p>MLIR’s analogue is mlir-opt, but the mindset shifts from “apply optimizations to a fixed IR” to <strong>“convert and simplify dialects in stages.”</strong></p><p>Example pipeline:</p><pre>mlir-opt input.mlir \<br>  -convert-linalg-to-loops \<br>  -lower-affine \<br>  -convert-scf-to-cf \<br>  -convert-func-to-llvm \<br>  -reconcile-unrealized-casts</pre><p>Rough story:</p><ul><li>-convert-linalg-to-loops: turn linalg ops into scf.for + memref ops.</li><li>-lower-affine: lower affine.for/affine.if into scf/cf plus arith.</li><li>-convert-scf-to-cf: turn structured control-flow into raw control-flow dialect.</li><li>-convert-func-to-llvm: map func.func to llvm.func.</li><li>-reconcile-unrealized-casts: clean up conversion casts.</li></ul><p>LLVM mental model:</p><ul><li>Instead of one monolithic IR, you have <strong>layers</strong> of IR.</li><li>Passes often say “take dialect X and translate it to dialect Y,” plus some canonicalization.</li></ul><p>This makes it much easier to:</p><ul><li>Share high-level passes across backends.</li><li>Maintain separate early/mid/late pipelines.</li><li>Plug in your own dialects and conversion steps.</li></ul><h3>Pattern Rewrites: Opt Passes With a Twist</h3><p>In LLVM, you write passes that:</p><ul><li>Walk functions/blocks/instructions.</li><li>Pattern-match sequences and rewrite them.</li></ul><p>MLIR leans heavily on <strong>pattern-based rewrites</strong> as a first-class mechanism.</p><p>Conceptually;</p><pre>pattern FuseMulAdd:<br>  match:   %p = arith.mulf %a, %b<br>           %s = arith.addf %p, %c<br>  rewrite: %f = mydialect.fma %a, %b, %c</pre><p>MLIR provides:</p><ul><li><strong>Declarative pattern languages.</strong></li><li>Infrastructure to <strong>apply patterns greedily</strong> or in customizable ways.</li><li>Dialect-specific pattern libraries that you can register in passes.</li></ul><p>LLVM mental model:</p><ul><li>Imagine if a large chunk of instcombine were expressed declaratively,<br>and you could ship private pattern bundles per domain, per dialect.</li></ul><p>This is how many MLIR passes are written: “here’s a bag of patterns; now walk the IR and apply them wherever they match.”</p><h3>The LLVM Dialect and “Real” LLVM IR</h3><p>At some point, codegen wants <strong>real LLVM IR</strong>.</p><p>MLIR typically funnels down through the <strong>LLVM dialect</strong>:</p><pre>llvm.func @add(%a: i32, %b: i32) -&gt; i32 {<br>  %sum = llvm.add %a, %b : i32<br>  llvm.return %sum : i32<br>}</pre><p>The llvm dialect:</p><ul><li>Uses LLVM-like types (!llvm.ptr, !llvm.struct, etc.).</li><li>Has ops corresponding to LLVM instructions.</li><li>Still obeys the MLIR structure (ops/regions/blocks).</li></ul><p>From there, a translation step converts llvm-dialect MLIR into actual LLVM IR, which the existing LLVM toolchain understands.</p><p>Typical high-level story:</p><pre>High-level dialects (linalg, tensor, scf, gpu, …)<br>                ⬇<br>     Mid-level (scf, memref, cf, arith, …)<br>                ⬇<br>          LLVM dialect (llvm.func, llvm.add, …)<br>                ⬇<br>              LLVM IR<br>                ⬇<br>            Machine code</pre><p>So MLIR does <strong>not</strong> replace LLVM IR; it just gives you more runway <strong>before</strong> you commit to it.</p><h3>How to Read MLIR as an LLVM Person</h3><p>When you first open a big .mlir file, it can feel noisy. Here’s a simple checklist:</p><ol><li><strong>Find the </strong><strong>module op and functions<br>- </strong>Look for module { ... }.<br>- Inside, search for func.func or llvm.func.</li><li><strong>Treat each op like an instruction<br>- </strong>arith.addi, memref.load, linalg.matmul are “instructions” in different dialects.</li><li><strong>Watch for regions<br>- </strong>Any op with { … } and labels like ^bb0 is holding a region with blocks.<br>- That’s your “structured CFG.”</li><li><strong>Identify abstraction level by dialects<br>- </strong>Mostly linalg/tensor? You’re at a high, algebraic level.<br>- Mostly scf/memref/arith? Mid-level; loops and memory are explicit.<br>- Mostly llvm dialect? You’re one translation away from LLVM IR.</li><li><strong>Use pass dumps<br>- </strong>Run mlir-opt with -print-ir-after-all to see how IR evolves.<br>- Watch linalg.generic turn into scf.for, then llvm ops.</li></ol><p>After a bit of exposure, you’ll start to “see through” the dialects and regions, the same way you eventually learned to ignore some of LLVM’s syntax and just see the CFG.</p><h3>So… Why MLIR?</h3><p>From an LLVM IR perspective, MLIR’s value is:</p><ul><li><strong>Layered abstraction: </strong>Work on tensors, loops, and structured algebra before dropping to raw pointers and blocks.</li><li><strong>Extensibility via dialects</strong>: Add new instructions and types without changing a monolithic core.</li><li><strong>Staged lowering</strong>: Encode your compilation strategy as a sequence of dialect conversions and cleanups.</li><li><strong>Reusability</strong>: Share high-level transformations across many backends (CPU, GPU, accelerators).</li><li><strong>Interoperability with LLVM</strong>: Still end in LLVM IR for codegen, or even import LLVM IR into MLIR via the llvm dialect.</li></ul><p>If you already live in LLVM-land, the trick is <strong>not</strong> to unlearn LLVM IR, but to treat MLIR as:</p><blockquote><em>“LLVM’s bigger, more structured, and more opinionated older sibling.”</em></blockquote><p>You still get your SSA, CFGs, and optimization passes — just wrapped in a system that makes high-level transformations far more pleasant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51197102ece8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can I Beat Clang’s Auto-Vectorizer on Apple Silicon? A SAXPY Case Study]]></title>
            <link>https://medium.com/@samarth.colleges/can-i-beat-clangs-auto-vectorizer-on-apple-silicon-a-saxpy-case-study-3c3926b5bfe3?source=rss-26469bc63d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c3926b5bfe3</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[aarch64]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[llvm]]></category>
            <dc:creator><![CDATA[Samarth Narang]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 03:53:26 GMT</pubDate>
            <atom:updated>2025-11-23T03:53:26.928Z</atom:updated>
            <content:encoded><![CDATA[<p>On modern CPUs, the “slow” part of your code often isn’t the math — it’s how you <em>feed</em> the math units. Compilers try to fix this with clever optimizations like <strong>auto-vectorization</strong>: transforming scalar loops into <strong>SIMD</strong> (Single Instruction, Multiple Data) operations that process multiple data points in parallel.</p><p>I wanted to know:</p><blockquote><em>If I hand-write NEON intrinsics on Apple Silicon, tune the loop unrolling, and stare at the assembly… can I beat Clang’s auto-vectorizer?</em></blockquote><p>Short answer: <strong>not easily.</strong></p><p>This post walks through:</p><ul><li>A tiny <strong>vectorization playground</strong> for the SAXPY kernel on Apple Silicon.</li><li>Benchmark results for <strong>scalar vs auto-vectorized vs manual NEON</strong> implementations.</li><li>How changing loop <strong>unroll factors</strong> affects performance.</li><li>A look at the <strong>AArch64 assembly</strong> Clang emits for the auto-vectorized version.</li><li>What this says about hand-written vector code vs compiler auto-vectorization.</li></ul><h3>The Code: A Tiny Vectorization Playground</h3><p>All the code in this post lives here:</p><pre>https://github.com/snarang181/vector-playground</pre><p>The core binary is vec_bench, a microbenchmark that runs different kernels/variants and prints performance metrics like total time and GFLOP/s.</p><p>vec_bench supports:</p><ul><li><strong>Kernels<br>-</strong>saxpy: Y = A * X + Y (Single-Precision A·X Plus Y)<br>- dot: result = sum(X[i] * Y[i])</li><li><strong>Variants<br>- </strong>scalar: scalar implementation with vectorization explicitly disabled.<br>- auto: uses Clang’s auto-vectorization.<br>- neon / manual: hand-written NEON intrinsic implementation with configurable loop unrolling.</li></ul><p>The CLI looks like:</p><pre>./vec_bench \<br>  --kernel saxpy \<br>  --variant auto \<br>  --n 2000000 \<br>  --iters 200</pre><p>and prints something like:</p><pre>Benchmark Results:<br>  Kernel: saxpy<br>  Variant: auto<br>  Size: 2000000<br>  Iterations: 200<br>  Unroll Factor: 2<br>  Total Time (s): 0.0592365<br>  Performance (GFLOPS): 13.5052<br>  Checksum: -93580.5\</pre><ul><li>--n: vector length.</li><li>--iters: number of iterations to run the kernel.</li><li>GFLOP/s assumes <strong>2 FLOPs per element</strong> for SAXPY (1 multiply + 1 add).</li></ul><h3>Building on Apple Silicon</h3><p>On an Apple Silicon Mac (M-series), I build with:</p><pre>cmake -DCMAKE_BUILD_TYPE=Release \<br>      -DCMAKE_CXX_FLAGS_RELEASE=&quot;-O3 -ffast-math -march=native&quot; \<br>      ..<br>cmake --build </pre><p>This basically means: <strong>optimize aggressively, assume fast-math, and target the native microarchitecture</strong>.</p><h3>SAXPY: Three Variants</h3><p>The kernel I focus on is SAXPY:</p><pre>for i in 0..n-1:<br>    y[i] = a * x[i] + y[i]</pre><p>I implemented three versions: scalar, auto-vectorized, and hand-written NEON with different unroll factors.</p><h3>1. Scalar: Vectorization Disabled</h3><p>The scalar baseline uses a plain for loop with vectorization explicitly disabled:</p><pre>void saxpy_scalar(float* y, const float* x, float a, std::size_t n) {<br>#pragma clang loop vectorize(disable)<br>    for (std::size_t i = 0; i &lt; n; ++i) {<br>        y[i] = a * x[i] + y[i];<br>    }<br>}</pre><p>This is essentially “textbook” C++.</p><h3>2. Auto-Vectorized: Let Clang Decide</h3><p>Next, the auto-vectorized version:</p><pre>void saxpy_auto(float* y, const float* x, float a, std::size_t n) {<br>#pragma clang loop vectorize(enable)<br>    for (std::size_t i = 0; i &lt; n; ++i) {<br>        y[i] = a * x[i] + y[i];<br>    }<br>}</pre><p>Same loop, but now the compiler is free to:</p><ul><li>Use NEON SIMD instructions.</li><li>Unroll the loop.</li><li>Use FMA (fused multiply-add) when available.</li><li>Do alias checks and fall back to scalar if it can’t prove safety.</li></ul><h3>3. Manual NEON: Intrinsics + Loop Unrolling</h3><p>The manual variant uses NEON intrinsics with an explicit unroll_factor:</p><pre>void saxpy_manual_unrolled(float *y,<br>                           const float *x,<br>                           float a,<br>                           std::size_t n,<br>                           int unroll_factor);</pre><p>Internally, this dispatches to a few hard-coded implementations (unroll=1, 2, 4).</p><h4>Unroll = 1 (4 elements per iteration)</h4><pre>static void saxpy_manual_unroll1(float *y,<br>                                 const float *x,<br>                                 float a,<br>                                 std::size_t n) {<br>#if VECPLAY_HAS_NEON<br>  std::size_t i     = 0;<br>  float32x4_t a_vec = vdupq_n_f32(a);<br><br>  std::size_t limit = n &amp; ~3u; // multiple of 4<br>  for (; i &lt; limit; i += 4) {<br>    float32x4_t x0 = vld1q_f32(&amp;x[i]);<br>    float32x4_t y0 = vld1q_f32(&amp;y[i]);<br>    y0             = vmlaq_f32(y0, x0, a_vec);<br>    vst1q_f32(&amp;y[i], y0);<br>  }<br><br>  // scalar tail<br>  for (; i &lt; n; ++i) {<br>    y[i] = a * x[i] + y[i];<br>  }<br>#else<br>  (void)y; (void)x; (void)a; (void)n;<br>#endif<br>}</pre><p>This is a straightforward “one NEON vector per iteration” implementation.</p><h4>Unroll = 2 (8 elements per iteration)</h4><p>This version processes 8 elements per iteration (two NEON vectors):</p><pre>static void saxpy_manual_unroll2(float *y,<br>                                 const float *x,<br>                                 float a,<br>                                 std::size_t n) {<br>#if VECPLAY_HAS_NEON<br>  std::size_t i     = 0;<br>  float32x4_t a_vec = vdupq_n_f32(a);<br><br>  std::size_t limit = n &amp; ~7u; // multiple of 8<br>  for (; i &lt; limit; i += 8) {<br>    float32x4_t x0 = vld1q_f32(&amp;x[i]);<br>    float32x4_t y0 = vld1q_f32(&amp;y[i]);<br>    float32x4_t x1 = vld1q_f32(&amp;x[i + 4]);<br>    float32x4_t y1 = vld1q_f32(&amp;y[i + 4]);<br><br>    y0 = vmlaq_f32(y0, x0, a_vec);<br>    y1 = vmlaq_f32(y1, x1, a_vec);<br><br>    vst1q_f32(&amp;y[i],     y0);<br>    vst1q_f32(&amp;y[i + 4], y1);<br>  }<br><br>  for (; i &lt; n; ++i) {<br>    y[i] = a * x[i] + y[i];<br>  }<br>#else<br>  (void)y; (void)x; (void)a; (void)n;<br>#endif<br>}</pre><p>This ends up being the “sweet spot” on my machine.</p><h4>Unroll = 4 (16 elements per iteration)</h4><p>Finally, the more aggressive unroll-4 version, which processes 16 elements per iteration:</p><pre>static void saxpy_manual_unroll4(float *y,<br>                                 const float *x,<br>                                 float a,<br>                                 std::size_t n) {<br>#if VECPLAY_HAS_NEON<br>  std::size_t i     = 0;<br>  float32x4_t a_vec = vdupq_n_f32(a);<br><br>  std::size_t limit = n &amp; ~15u; // multiple of 16<br>  for (; i &lt; limit; i += 16) {<br>    float32x4_t x0 = vld1q_f32(&amp;x[i]);<br>    float32x4_t y0 = vld1q_f32(&amp;y[i]);<br><br>    float32x4_t x1 = vld1q_f32(&amp;x[i + 4]);<br>    float32x4_t y1 = vld1q_f32(&amp;y[i + 4]);<br><br>    float32x4_t x2 = vld1q_f32(&amp;x[i + 8]);<br>    float32x4_t y2 = vld1q_f32(&amp;y[i + 8]);<br><br>    float32x4_t x3 = vld1q_f32(&amp;x[i + 12]);<br>    float32x4_t y3 = vld1q_f32(&amp;y[i + 12]);<br><br>    y0 = vmlaq_f32(y0, x0, a_vec);<br>    y1 = vmlaq_f32(y1, x1, a_vec);<br>    y2 = vmlaq_f32(y2, x2, a_vec);<br>    y3 = vmlaq_f32(y3, x3, a_vec);<br><br>    vst1q_f32(&amp;y[i],      y0);<br>    vst1q_f32(&amp;y[i + 4],  y1);<br>    vst1q_f32(&amp;y[i + 8],  y2);<br>    vst1q_f32(&amp;y[i + 12], y3);<br>  }<br><br>  for (; i &lt; n; ++i) {<br>    y[i] = a * x[i] + y[i];<br>  }<br>#else<br>  (void)y; (void)x; (void)a; (void)n;<br>#endif<br>}</pre><p>A simple dispatcher picks the right implementation based on unroll_factor.</p><h3>Benchmarking: Scalar vs Auto vs Manual NEON</h3><p>All benchmarks below are on:</p><ul><li>Apple Silicon Mac (M1 Pro)</li><li>Compiler flags: -O3 -ffast-math -march=native</li><li>Kernel: saxpy</li><li>Vector size n = 2,000,000</li><li>Iterations iters = 200</li></ul><p>Commands:</p><pre>./vec_bench --kernel saxpy --variant scalar            --n 2000000 --iters 200<br>./vec_bench --kernel saxpy --variant auto              --n 2000000 --iters 200<br>./vec_bench --kernel saxpy --variant manual --unroll 1 --n 2000000 --iters 200<br>./vec_bench --kernel saxpy --variant manual --unroll 2 --n 2000000 --iters 200<br>./vec_bench --kernel saxpy --variant manual --unroll 4 --n 2000000 --iters 200</pre><p>Representative results:</p><pre>| Variant       | Unroll | Time (s) | GFLOP/s   |<br>| ------------- | ------ | -------- | --------- |<br>| scalar        | —      | 0.2482   | **3.22**  |<br>| auto          | —      | 0.0650   | **12.31** |<br>| manual (NEON) | 1      | 0.0871   | **9.19**  |<br>| manual (NEON) | 2      | 0.0552   | **14.50** |<br>| manual (NEON) | 4      | 0.0666   | **12.01** |</pre><h3>What jumps out</h3><ul><li>Moving from <strong>scalar → auto</strong> is a huge win (3.22 → 12.31 GFLOP/s) basically for free.</li><li>The naive manual NEON version (<strong>unroll=1</strong>) is actually <strong>slower than auto</strong> (9.19 vs 12.31 GFLOP/s).</li><li>With <strong>unroll=2</strong>, the manual NEON version finally <strong>beats auto</strong> (14.50 vs 12.31 GFLOP/s), about an <strong>18% speedup</strong>.</li><li>Pushing further to <strong>unroll=4</strong> hurts performance again (12.01 GFLOP/s), roughly back at the auto baseline.</li></ul><p>So unrolling behaves like a <strong>tuning knob</strong>:</p><ul><li>Too little unrolling → not enough instruction-level parallelism (ILP).</li><li>“Just right” unrolling → best throughput (unroll=2 here).</li><li>Too much unrolling → more register pressure and bigger loop body, which can slow you down.</li></ul><h3>Peeking Under the Hood: Clang’s Auto-Vectorized Assembly</h3><p>Why is the auto-vectorized version so strong, and what are we beating with unroll=2?</p><p>Here’s a (shortened) disassembly of saxpy_auto from kernels.cpp.o:</p><pre>0000000000000370 &lt;__ZN7vecplay10saxpy_autoEPfPKffm&gt;:<br>    ...<br>3e8: 4f801025      fmla.4s v5,  v1,  v0[0]   // y0 += a * x0<br>3ec: 4f801046      fmla.4s v6,  v2,  v0[0]   // y1 += a * x1<br>3f0: 4f801067      fmla.4s v7,  v3,  v0[0]   // y2 += a * x2<br>3f4: 4f801090      fmla.4s v16, v4,  v0[0]   // y3 += a * x3<br>3f8: ad3f1945      stp     q5, q6, [x10, #-32]<br>3fc: ac824147      stp     q7, q16,[x10], #64<br>400: f100416b      subs    x11, x11, #16     // processed 16 floats<br>404: 54fffea1      b.ne    0x3d8             // loop back</pre><p>Key points:</p><ul><li>The auto-vectorized loop processes <strong>16 floats per iteration</strong> (4 NEON vectors of 4 floats).</li><li>It uses fmla.4s (FMA) heavily.</li><li>It uses ldp/stp for paired loads/stores.</li><li>Surrounding code handles alias checks and tail elements.</li></ul><p>In other words, Clang is already generating a strong microkernel for SAXPY with zero intrinsics from you.</p><p>The unroll=2 manual NEON kernel ends up:</p><ul><li>Doing fewer elements per iteration (8 rather than 16),</li><li>But with a smaller, more compact loop body,</li><li>And a shape that happens to line up very well with the Apple Silicon pipeline for this problem size.</li></ul><p>On this workload, that’s just enough to pull ahead.</p><h3>So… Can You Beat Auto-Vectorization?</h3><p>Yes, but with caveats.</p><h3>1. Auto-Vectorization is a very strong baseline</h3><p>Clang on Apple Silicon:</p><ul><li>Uses NEON and FMA by default (with the right flags).</li><li>Emits a 16-element-wide vector loop.</li><li>Handles aliasing and tails safely.</li></ul><p>You get <strong>4× speedup</strong> vs scalar just by writing a clean loop and turning on optimizations.</p><h3>2. Hand-Written NEON can win, but not for free</h3><p>A naive NEON kernel (unroll=1) underperformed the auto version. Only after:</p><ul><li>Writing <strong>explicit</strong> unrolled kernels,</li><li>Tuning unroll_factor,</li><li>And checking both performance and correctness,</li></ul><p>did I find a configuration (unroll=2) that reliably beats auto by ~18%.</p><h3>3. Unroll factor is a real tuning parameter</h3><p>For this particular SAXPY on this particular Apple Silicon chip:</p><ul><li>unroll=1 → SIMD, but not enough ILP → worse than auto.</li><li>unroll=2 → sweet spot → best performance.</li><li>unroll=4 → too heavy → performance regresses.</li></ul><p>On another kernel or CPU, the story could be different. The pattern holds: <strong>unroll is a knob, not a magic number</strong>.</p><h3>How to Explore This Yourself</h3><p>If you want to replicate or extend this:</p><p>Clone the repo:</p><pre>git clone https://github.com/snarang181/vector-playground cd vector-playground</pre><p>Build:</p><pre>mkdir -p build<br>cd build<br>cmake -DCMAKE_BUILD_TYPE=Release \<br>      -DCMAKE_CXX_FLAGS_RELEASE=&quot;-O3 -ffast-math -march=native&quot; \<br>      ..<br>cmake --build .</pre><p>Run benchmarks:</p><pre>./vec_bench --kernel saxpy --variant scalar            --n 2000000 --iters 200<br>./vec_bench --kernel saxpy --variant auto              --n 2000000 --iters 200<br>./vec_bench --kernel saxpy --variant manual --unroll 1 --n 2000000 --iters 200<br>./vec_bench --kernel saxpy --variant manual --unroll 2 --n 2000000 --iters 200<br>./vec_bench --kernel saxpy --variant manual --unroll 4 --n 2000000 --iters 200</pre><p>Inspect the assembly for saxpy_auto:</p><pre>OBJ=./CMakeFiles/vecplay.dir/src/kernels.cpp.o<br>llvm-objdump -d --symbolize-operands --no-show-raw-insn &quot;$OBJ&quot; \<br>  | sed -n &#39;/&lt;__ZN7vecplay10saxpy_autoEPfPKffm&gt;/,/^$/p&#39;</pre><p>From there you can:</p><ul><li>Add more kernels (e.g., dot product, reductions),</li><li>Try different data types (float vs double),</li><li>Or explore what happens when you tweak compiler flags (-ffast-math, -march, etc.).</li></ul><p>At the end of the day, this little experiment reinforced something I already suspected:</p><blockquote><em>Modern compilers on modern CPUs are really good. Hand-tuned intrinsics can win — but only if you’re willing to get your hands dirty and </em>measure<em> rather than guess.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c3926b5bfe3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantization in MLIR: Types, Scales, and Where to Put the “q”]]></title>
            <link>https://medium.com/@samarth.colleges/quantization-in-mlir-types-scales-and-where-to-put-the-q-89336aaedf29?source=rss-26469bc63d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/89336aaedf29</guid>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlir]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Samarth Narang]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 04:20:06 GMT</pubDate>
            <atom:updated>2025-11-21T04:20:06.806Z</atom:updated>
            <content:encoded><![CDATA[<h4>This post walks through how to make quantization a first-class citizen in MLIR — from quantized types and quantize/dequantize ops to how it all plugs into linalg, fusion, and backend lowering</h4><p>Quantization is one of those things everyone agrees is “critical for deployment” but nobody really wants to think about at the IR level. Frameworks talk about int8 models, backends brag about TOPS/W, and somewhere in the middle there’s a messy pile of ad-hoc passes, custom ops, and fragile assumptions tying it all together.</p><p>MLIR sits right in that middle zone — and that’s exactly why it’s such a good place to make quantization a <em>first-class </em>concept instead of a bolted-on afterthought. With a rich type system and dialect infrastructure, you can make scales, zero-points, and quantized domains explicit, queryable, and optimizable.</p><p>In this post, we’ll walk through:</p><ol><li>A mental model for quantization in compilers</li><li>How to represent quantized tensors using MLIR’s type system</li><li>Where to introduce quantize / dequantize ops in the IR</li><li>How this interacts with the linalg dialect</li><li>Why fusion and vectorization matter for quantized graphs</li><li>A high-level “quantization pipeline” in MLIR</li><li>Open design questions worth arguing about</li></ol><h3><strong>Quick mental model: What are we even quantizing?</strong></h3><p>Most ML inference quantization schemes boil down to this:</p><p>- Store values in <strong>low-precision integers</strong> (e.g., int8, int4) to save memory and bandwidth.</p><ul><li>Interpret them using a <strong>scale</strong> (and sometimes a <strong>zero point</strong>) to map back to real numbers.</li></ul><p>The classic affine mapping is:</p><pre>real_value = scale * (quantized_value - zero_point)</pre><p>Where:</p><ul><li>quantized_value is the low-precision integer sitting in memory</li><li>scale is a floating-point “step size”</li><li>zero_point lets you represent real 0 exactly as some integer value</li></ul><p>If you want your compiler IR to <em>understand</em> this, you need to answer a few questions:</p><ul><li>Where do scale and zero_point live?</li><li>Are they part of the type? Attributes on ops? Side tables?</li><li>Where in the IR do you cross between floating-point and quantized domains?</li></ul><p>The rest of the post is essentially about chasing down those three questions.</p><h3><strong>Quantized types: putting scale and zero point in the type system</strong></h3><p>MLIR’s type system is rich enough that you don’t have to hide quantization metadata in comments or random attributes. You can put it right into the type.</p><p>A conceptual example using the quant dialect:</p><pre>// A quantized element type<br>!qint = !quant.uniform&lt;i8:f32, scale = 0.02, zero_point = -5&gt;<br><br>// A tensor using this quantized element type<br>!qtensor = tensor&lt;128x128x64x!qint&gt;</pre><p>Here:</p><ul><li>i8 is the storage type (what actually sits in memory/registers)</li><li>f32 is the logical real domain the integers map to</li><li>scale and zero_point are parameters baked into the type</li></ul><p>This buys you a bunch of nice properties:</p><ul><li><strong>Passes can cheaply distinguish “quantized” from “real” types</strong> just from the type system.</li><li><strong>Patterns can depend on quantization semantics</strong>, e.g., “only fuse these ops if they share scales and zero points.”</li><li><strong>Backends can read quantization parameters directly from types</strong> to choose specialized kernels or instructions.</li></ul><p>You can also represent more advanced schemes like per-channel quantization by extending the type payload:</p><pre>// Per-channel quantization along a chosen axis<br>!qconv_weight = tensor&lt;<br>  64x3x3x3x!quant.uniform&lt;i8:f32,<br>    scales = [0.01, 0.02, ...],<br>    zero_points = [0, 0, ...],<br>    axis = 0<br>  &gt;<br>&gt;</pre><p>Per-channel quantization is especially common for convolution weights, where each output channel can have its own dynamic range and, hence, its own scale.</p><h3>quantize / dequantize: switching between domains</h3><p>At some point, you need to move between floating-point and quantized worlds. That’s where explicit quantize and dequantize ops come in:</p><pre>%f = ... : tensor&lt;...xf32&gt;<br><br>// Float → quantized<br>%q = quant.quantize %f<br>     : tensor&lt;...xf32&gt; to tensor&lt;...x!qint&gt;<br><br>// Quantized → float<br>%f2 = quant.dequantize %q<br>      : tensor&lt;...x!qint&gt; to tensor&lt;...xf32&gt;</pre><p>The interesting design choice isn’t the ops themselves — it’s <strong>where in the IR</strong> they should live. There are two common strategies (plus a hybrid in the middle).</p><h4>Strategy 1: Early quantization, late dequantization</h4><ul><li>Insert quantize ops close to model import / calibration</li><li>Keep as much of the graph as possible in the quantized domain</li><li>Only insert dequantize ops at the very end or when you hit an op that can’t handle quantized inputs</li></ul><p><strong>Pros:</strong></p><ul><li>Maximizes time spent in low-precision land → performance and memory savings</li><li>Makes quantized types visible throughout the IR for global optimizations</li></ul><p><strong>Cons:</strong></p><ul><li>More transformations must be aware of quantized semantics</li><li>You may accumulate numerical error over long quantized pipelines</li></ul><h4>Strategy 2: Late, backend-driven quantization</h4><ul><li>Keep IR in f32 / f16 for most of the pipeline</li><li>Let backend-specific passes introduce quantized types and conversions near the end</li></ul><p><strong>Pros:</strong></p><ul><li>IR stays “clean” and mostly float-based</li><li>Centralizes quantization logic in backend passes</li></ul><p><strong>Cons:</strong></p><ul><li>Harder to perform global, quantization-aware optimizations upstream</li><li>You might be “too late” to exploit some layout or fusion opportunities</li></ul><p>In practice, a <strong>hybrid</strong> approach is compelling:</p><ul><li>A mid-level pass decides <em>what</em> to quantize and inserts quantize / dequantize strategically</li><li>Later backend passes refine those into concrete kernels or int8 GEMM / conv instructions</li></ul><h3>Quantization meets linalg: generic ops, concrete kernels</h3><p>The linalg dialect is a natural home for quantized computation: it expresses structured, generic operations (like matmul, conv, etc.) that you can specialize for different element types, including quantized ones.</p><p>For example, a quantized matmul might look like:</p><pre>linalg.matmul<br>  ins (%A_q, %B_q : tensor&lt;MxKx!qint&gt;, tensor&lt;KxNx!qint&gt;)<br>  outs (%C_q : tensor&lt;MxNx!qint&gt;)</pre><p>Semantically, you could interpret this in multiple ways:</p><ul><li>As an integer matmul followed by an appropriate rescaling</li><li>As directly mapping to hardware-specific INT8 GEMM primitives</li><li>As a pattern that <em>eventually</em> lowers into some combination of int32 accumulators + rescale back to int8</li></ul><p>A reasonable pattern is:</p><ol><li>Keep linalg ops mostly <strong>element-type generic</strong>.</li><li>Introduce passes that:<br>- Lower quantized linalg ops into integer kernels plus explicit rescale steps; or<br>- Directly lower them to backend-specific quantized kernels.</li><li>Use the quantization metadata in types to choose the right lowering.</li></ol><p>Pseudo-lowering sketch:</p><pre>%acc = linalg.matmul ins(%A_i8, %B_i8)<br>       : tensor&lt;MxKxi8&gt;, tensor&lt;KxNxi8&gt; -&gt; tensor&lt;MxNxi32&gt;<br><br>%out = quant.rescale %acc<br>       { scale = ..., zero_point = ... }<br>       : tensor&lt;MxNxi32&gt; -&gt; tensor&lt;MxNxi8&gt;</pre><p>linalg gives you the structured loops; quantization gives you additional semantic constraints. The compiler’s job is to reconcile the two.</p><h3>Quantization-friendly fusion and vectorization</h3><p>Quantized graphs are full of small, stereotyped patterns:</p><ul><li>quantize -&gt; conv -&gt; relu -&gt; dequantize</li><li>quantize -&gt; matmul -&gt; bias_add -&gt; activation -&gt; dequantize</li></ul><p>If you naively lower these, you end up with lots of tiny ops and extra conversions. The whole game is to:</p><ul><li>Fuse as many quantized ops as you can while staying in the quantized domain</li><li>Avoid unnecessary dequantize / quantize hops</li><li>Vectorize int8/uint8 arithmetic to fully exploit SIMD or tensor cores</li></ul><p>In MLIR terms, this can look like:</p><pre>%q = quant.quantize %f<br>     : tensor&lt;...xf32&gt; to tensor&lt;...x!qint&gt;<br><br>%y = &quot;mydialect.conv&quot;(%q, %w)<br>     : tensor&lt;...x!qint&gt;, tensor&lt;...x!qint&gt; -&gt; tensor&lt;...x!qint&gt;<br><br>%z = &quot;mydialect.relu&quot;(%y)<br>     : tensor&lt;...x!qint&gt; -&gt; tensor&lt;...x!qint&gt;<br><br>%out = quant.dequantize %z<br>       : tensor&lt;...x!qint&gt; to tensor&lt;...xf32&gt;</pre><p>…which a fusion pass might rewrite into:</p><pre>%out = &quot;mydialect.fused_conv_relu&quot;(%f, %w)<br>       : tensor&lt;...xf32&gt;, tensor&lt;...x!qint&gt; -&gt; tensor&lt;...xf32&gt;</pre><p>Similarly, the vector dialect and backends can be taught to handle quantized types as first-class citizens:</p><pre>%vA   = vector.transfer_read %A_q ...<br>        : tensor&lt;...x!qint&gt; to vector&lt;...xi8&gt;<br>%vB   = vector.transfer_read %B_q ...<br>        : tensor&lt;...x!qint&gt; to vector&lt;...xi8&gt;<br>%vAcc = &quot;vector.dot_qi8&quot;(%vA, %vB)<br>        : vector&lt;...xi8&gt;, vector&lt;...xi8&gt; -&gt; vector&lt;...xi32&gt;</pre><p>The pattern is consistent:</p><ul><li>Make quantization explicit in types and ops</li><li>Let fusion and vectorization passes “see” those semantics</li><li>Dequantize only at the boundaries where absolutely necessary</li></ul><h3>A plausible MLIR quantization pipeline</h3><p>Zooming out, you can imagine an MLIR-based quantization story along these lines:</p><p>1. <strong>Model Import</strong>: Load a floating-point model (e.g., from ONNX, TensorFlow).</p><p>2. <strong>Quantization Pass</strong>: Analyze the model, decide which tensors/ops to quantize, attach parameters to types, insert quantize / dequantize ops.</p><p>3. <strong>Quantized Optimization Passes</strong>: Fuse quantized ops, fold unnecessary conversions, vectorize quantized computations.</p><p>4. <strong>Structured Lowering</strong>: Lower linalgand other high-level ops to quantized kernels, respecting quantization semantics.</p><p>5. <strong>Backend Lowering</strong>:Final mapping to LLVM or target-specific codegen, leveraging quantized instructions.</p><p>This is not “the one true pipeline,” but it’s a useful mental scaffold to reason about where each piece fits.</p><h3><strong>Design questions to ponder</strong></h3><p>Quantization is a moving target, and MLIR gives you enough expressiveness that there isn’t a single obvious design. Some questions that are still very much alive:</p><ul><li>How much should the type system know?<br>- Do scales and zero-points always live in the type?<br>- Are attributes or side tables better for some backends?</li><li>Static vs. dynamic parameters<br>- How do you represent quantization schemes where scales are per-batch or computed on the fly?</li><li>Interaction with mixed precision<br>- How do fp16/bf16 and quantized domains coexist in the same IR?<br>- Where do you switch between these worlds?</li><li>Verification and correctness<br>- How do you check ranges, prevent overflows, and maintain numerical guarantees for quantized computations?</li></ul><p>These are precisely the kinds of questions that make quantization in MLIR interesting — not just as a set of APIs, but as a design space for compiler and systems folks to explore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89336aaedf29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How GPUs Talk: A Practical Guide to Multi-GPU Training and Communication]]></title>
            <link>https://medium.com/@samarth.colleges/how-gpus-talk-a-practical-guide-to-multi-gpu-training-and-communication-5c1b43a65f01?source=rss-26469bc63d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c1b43a65f01</guid>
            <category><![CDATA[nvlink]]></category>
            <category><![CDATA[nccl]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[distributed-training]]></category>
            <dc:creator><![CDATA[Samarth Narang]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 04:28:14 GMT</pubDate>
            <atom:updated>2025-11-16T04:28:14.037Z</atom:updated>
            <content:encoded><![CDATA[<h4>An in-depth exploration of multi-GPU training techniques and the communication patterns that enable efficient distributed machine learning.</h4><p>When people talk about scaling deep learning, they usually mean <strong>throwing more GPUs </strong>at the problem. However, horizontal scaling can only get you so far without efficient communication strategies.</p><p>Concretely, “using 8 GPUs instead of 1” will only help if GPUs can <em>talk</em> to each other fast enough. Under the hood, multi-GPU training is less about computation and more about <strong>communication</strong>.</p><p>In this post, I want to walk through how GPUs communicate during training:</p><ul><li>The hardware links (PCIe, NVLink, InfiniBand),</li><li>The core communication patterns (<em>all-reduce</em>, <em>all-gather</em>, <em>reduce-scatter</em>, <em>broadcast</em>),</li><li>And how they show up in <strong>data parallelism</strong>, <strong>fully sharded data parallelism (FSDP)</strong>, <strong>tensor parallelism</strong>, and <strong>pipeline parallelism</strong>.</li></ul><p>The goal is to provide a mental model that explains why your training job suddenly becomes <strong>network-bound</strong> instead of <strong>compute-bound</strong> as you scale up.</p><h3>1. Why Multi-GPU Training is a communication problem</h3><p>On a single GPU, training looks simple:</p><ol><li>Load a batch of data</li><li>Forward pass through the model</li><li>Compute loss</li><li>Backward pass to compute gradients</li><li>Update model parameters</li><li>Repeat</li></ol><p>Scaling to multiple GPUs sounds equally simple:</p><ul><li>Give each GPU a different mini-batch of data</li><li>Average gradients across GPUs,</li><li>Update model parameters</li></ul><p>That “averaging gradients across GPUs” step is where things get tricky.</p><p>At a small scale, communication overhead is negligible compared to computation; say, when you are doing a Matrix Multiply. At larger scales (32+ GPUs, or multi-node where GPUs are connected over a network), <strong>gradient sync and parameter updates</strong> can dominate the training time. Modern accelerators have extremely high compute throughput, which moves the bottleneck to:</p><ul><li>GPU ↔ GPU bandwidth,</li><li>GPU ↔ NIC bandwidth,</li><li>Or cross-node network bandwidth.</li></ul><p>To understand the trade-offs, we have to start from the hardware.</p><h3>2. How GPUs are wired: intra-node and inter-node</h3><p>Inside a single server (node), GPUs are connected via high-speed links:</p><ul><li><strong>PCIe</strong> : The standard peripheral interconnect, decent bandwidth but relatively high latency.</li><li><strong>NVLink</strong> : NVIDIA’s high-speed GPU-to-GPU interconnect, much higher bandwidth and lower latency than PCIe.</li><li><strong>NVSwitch</strong> : A high-speed switch that connects many NVLink ports, used in DGX systems so every GPU can talk to every other GPU at full NVLink speed.</li></ul><p>Across multiple servers (nodes), GPUs communicate over a network:</p><ul><li><strong>NICs (Network Interface Cards)</strong> (often InfiniBand or RDMA over Converged Ethernet — RoCE),</li><li>Connected via high-speed switches.</li></ul><p>The important bit: <strong>topology matters</strong>.</p><ul><li>In an 8-GPU setup with NVLink, some GPU pairs are directly connected, some can require multiple hops.</li><li>In a multi-node cluster, some nodes share a switch, others have to go through multiple switches.</li></ul><p>Libraries like <em>NCCL</em> (NVIDIA Collective Communications Library) probe this topology and build communication patterns (rings, trees) that optimize data transfer.</p><h3>3. Core communication patterns (collectives)</h3><p>Most multi-GPU training is built on a few core <strong>collective communication</strong> operations:</p><ul><li><strong>Broadcast</strong><br>One GPU has a tensor, and everyone else needs a copy.</li><li><strong>All-gather</strong><br>Each GPU has a chunk of data; in the end, every GPU has <strong>all</strong> chunks concatenated.</li><li><strong>Reduce-scatter</strong><br>The dual of all-gather. GPUs start with chunks that need to be <strong>reduced</strong> (e.g., summed) across all GPUs, and each GPU ends up with one <strong>shard of the reduction</strong>.</li><li><strong>All-reduce</strong><br>Each GPU has a full tensor; they want the <strong>element-wise sum (or other reduction) of all those tensors</strong>, and everyone ends up with the same result.</li></ul><p>Data-parallel training primarily uses <strong>all-reduce</strong> to average gradients.</p><h3>4. Multi-GPU training strategies</h3><h3>4.1 Distributed Data Parallel (DDP)</h3><p>In classic <strong>Distributed Data Parallel (DDP)</strong>:</p><ul><li>Each GPU stores a full copy of the model.</li><li>Split the training data across GPUs (batches).</li><li>Each GPU computes gradients on its mini-batch.</li><li>Use <strong>all-reduce</strong> to average gradients across GPUs.</li></ul><h3>4.2 Fully Sharded Data Parallel (FSDP)</h3><p>At some point, simply replicating the full model state (parameters + gradients + optimizer state) on every GPU stops working. That’s where <strong>Fully Sharded Data Parallel (FSDP)</strong> comes in.</p><p>Instead of full replication, FSDP:</p><ul><li><strong>Shards parameters</strong> across GPUs in the data-parallel group,</li><li><strong>Shards gradients</strong> the same way,</li><li><strong>Shards optimizer state</strong> as well.</li></ul><p>Roughly, for each FSDP-wrapped block or layer:</p><ol><li><strong>Before forward pass,</strong></li></ol><ul><li>GPUs run an <strong>all-gather</strong> to reconstruct the full parameters for that block locally.</li></ul><p><strong>2. Forward pass</strong></p><ul><li>Computed as usual with the gathered parameters.</li></ul><p><strong>3. Backward pass</strong></p><ul><li>Gradients are computed for those parameters.</li></ul><p><strong>4. Reduce-scatter</strong></p><ul><li>Gradients are <strong>reduced and scattered</strong> back so that each GPU ends up with the gradient shard corresponding to its parameter shard.</li></ul><p><strong>5. Optimizer step</strong></p><ul><li>Each GPU updates <strong>only its local shard</strong> of the parameters and optimizer state.</li></ul><p>Total communication volume is still proportional to the model size, but the pattern shifts from “one big all-reduce over gradients” to <strong>a series of all-gathers and reduce-scatters scattered through the forward/backward passes</strong>.</p><p>The trade-off:</p><ul><li><strong>More frequent, finer-grained communication</strong>,</li><li>In exchange for <strong>dramatically lower peak memory usage per GPU</strong>, enabling much larger models or batch/sequence sizes.</li></ul><h3>4.3 Tensor parallelism</h3><p>Data-parallel methods replicate the model and shard the data. <strong>Tensor parallelism</strong> shards the <em>tensors inside the model</em>.</p><p>For a big linear layer, i.e. Y = X @ W:</p><ul><li>Split the weight matrix across GPUs (e.g., by columns).</li><li>Each GPU holds a slice of the weights, W_i.</li><li>Input X is broadcast to all GPUs.</li><li>Each GPU computes its partial output Y_i = X @ W_i.</li><li>Finally, an <strong>all-gather</strong> combines the partial outputs Y_i into the full output Y.</li></ul><p>In practice, tensor parallelism is often combined with data parallelism to balance memory and computation. For example, in a multi-node setup, each node can run data parallelism, while within each node, tensor parallelism shards the model across GPUs. This is reasonable considering the high intra-node bandwidth (NVLink) compared to inter-node bandwidth (InfiniBand).</p><h3>4.4 Pipeline Parallelism</h3><p>There is a generic type of tensor parallelism called <strong>Model Parallelism</strong>, where different layers of the model are placed on different GPUs. Imagine a 32-layer transformer and 4 GPUs:</p><ul><li>GPU 0: layers 1–8</li><li>GPU 1: layers 9–16</li><li>GPU 2: layers 17–24</li><li>GPU 3: layers 25–32</li></ul><p>If you naively pass a batch through this pipeline, you get terrible utilization:</p><ul><li>While GPU 0 is working, GPUs 1–3 are idle.</li><li>Then GPU 1 works while 0, 2, 3 sit idle.</li><li>And so on.</li></ul><p>Pipeline parallelism fixes this by splitting the batch into <strong>micro-batches</strong> and feeding them through like an assembly line:</p><pre>| Time step | GPU 0 (L1–8) | GPU 1 (L9–16) | GPU 2 (L17–24) | GPU 3 (L25–32) |<br>| --------: | ------------ | ------------- | -------------- | -------------- |<br>|         1 | MB0          |               |                |                |<br>|         2 | MB1          | MB0           |                |                |<br>|         3 | MB2          | MB1           | MB0            |                |<br>|         4 | MB3          | MB2           | MB1            | MB0            |<br>|         … | …            | …             | …              | …              |</pre><p>Forward activations flow from GPU 0 → 1 → 2 → 3, and backward gradients flow in reverse.</p><p>Communication consists of:</p><ul><li><strong>Sending activations</strong> forward between pipeline stages,</li><li><strong>Sending gradients</strong> backward between stages.</li></ul><h3>5. Topology-aware communication: rings, trees, and fast links</h3><p>On a real machine, not all GPU pairs are equal:</p><ul><li>Some GPUs share direct NVLink connections,</li><li>Others require multiple hops via NVSwitch or PCIe,</li><li>Cross-node communication goes over NICs and switches.</li></ul><p>Libraries like NCCL:</p><ul><li>Discover the physical topology,</li><li>Build <strong>logical rings and trees</strong> that mostly use the fastest links,</li><li>Choose algorithms based on message size and number of GPUs.</li></ul><p>Examples:</p><ul><li>On an 8-GPU NVLink system, a ring all-reduce is arranged to walk only NVLink edges, avoiding slower PCIe hops.</li><li>For <strong>large tensors</strong>, ring all-reduce tends to win: it keeps all links busy and saturates bandwidth.</li><li>For <strong>small tensors</strong>, tree-based all-reduce (or double-tree variants) can reduce latency by making fewer hops, scaling like O(log N) instead of O(N) in depth.</li></ul><h3>6. Hiding communication latency</h3><p>To maximize GPU utilization, we want to <strong>hide communication latency</strong> behind computation. Some strategies include:</p><ul><li><strong>Overlapping communication and computation</strong>:</li><li>Kick off an all-reduce for gradients of layer L while computing the backward pass for layer L-1.</li><li><strong>Gradient bucketing</strong>:</li><li>Group many small tensors into bigger buckets before all-reduce to avoid per-call overhead.</li><li><strong>Mixed precision &amp; compression</strong>:</li><li>Gradients often travel in FP16/BF16.</li><li>Some systems apply methods like quantization to reduce message sizes further.</li></ul><h3>7. Conclusion</h3><p>When looking from afar, multi-GPU training is about two operations: compute and communicate. As models and datasets grow, communication increasingly becomes the bottleneck. Understanding the hardware topology, core communication patterns, and training strategies is crucial to designing efficient distributed training systems.</p><p>Starting to treat communication as a first-class citizen in your training architecture will pay dividends as you scale to larger models and datasets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c1b43a65f01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structure and Iterator Kung Fu in LLVM]]></title>
            <link>https://medium.com/@samarth.colleges/data-structure-and-iterator-kung-fu-in-llvm-42aa9657ff47?source=rss-26469bc63d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/42aa9657ff47</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[llvm]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Samarth Narang]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 02:36:52 GMT</pubDate>
            <atom:updated>2025-11-13T02:36:52.233Z</atom:updated>
            <content:encoded><![CDATA[<h4>Practical patterns, zero-copy views, and safe mutation loops for faster LLVM passes.</h4><p>If you’ve written more than one LLVM pass, you eventually hit the same wall: “Why does everyone keep using SmallVector , DenseMap , StringRef , and all these weird range helpers instead of the Standard Template Library (STL) I already know?”</p><p>LLVM’s <em>Abstract Data Types (ADT) l</em>ibrary looks intimidating from the outside, but once you internalize a handful of patterns, your code both speeds up <em>and </em>gets cleaner. This post is a tour of those patterns: when to reach for each data structure, how to iterate safely while mutating IR, and a few classic footguns to avoid.</p><h3>Why LLVM ships its own containers</h3><p>Compilers are a very particular workload:</p><ul><li>Lots of tiny objects (instructions, basic blocks, values)</li><li>Pointer-heavy graphs</li><li>Hot-path inner loops</li><li>Tons of string handling (names, debug info, diagnostics, etc.)</li></ul><p>STL <em>can</em> handle this, but it’s not tuned for it. LLVM’s ADTs exist to:</p><ul><li>Minimize heap allocations</li><li>Avoid unnecessary copies</li><li>Be cache-friendly for pointer keys and small integers</li><li>Encode common compiler idioms (non-owning views, arenas, hash-consing)</li></ul><h3>Core Value Types: They own nothing</h3><h4>StringRef</h4><ul><li>StringRef is a <em>non-owning </em>reference to a string, i.e., it does not own the underlying data. By storing just the pointer and length (it is basically a (char*, size_t) pair), it is <em>zero-copy </em>by design.</li><li><strong>APIs: </strong>front(), startswith(), contains(), drop_front(), consume_front(&quot;0x&quot;)and many more.</li><li><strong>Lifetime rule: </strong>The referenced memory must outlive the StringRef.</li></ul><h4>ArrayRef/MutableArrayRef</h4><ul><li>Similar to StringRef, ArrayRef&lt;T&gt; is a lightweight, non-owning reference to a contiguous array of elements of type T. ArrayRef ensures efficient access but the data is not modifiable; for that, use MutableArrayRef&lt;T&gt;.</li><li><strong>Gotcha</strong> : Don’t create an ArrayRef from a temporary container, as the data may be destroyed immediately after.</li></ul><h4>Twine</h4><ul><li>Twine is a lightweight way to concatenate strings without creating intermediate copies. It represents a concatenation of strings as a tree structure, allowing efficient construction of complex strings on-the-fly.</li><li><strong>Rule</strong> : Don’t store a Twine, materialize with SmallString or std::string if you need to keep the result.</li></ul><h3>Small-Size Optimized Containers</h3><h4>SmallVector&lt;T, N&gt;</h4><ul><li>What: std::vector semantics with inline storage for up to N elements.</li><li>Choose N: do profiling; balance spill overhead vs. stack usage.</li><li>In the event of exceeding N, it seamlessly falls back to heap allocation, i.e., it behaves like a regular std::vector beyond that point.</li><li><strong>APIs</strong>: push_back, emplace_back, reserve, append, pop_back_val, and more.</li></ul><pre>SmallVector&lt;Value*, 4&gt; WorkList; // Inline storage for 4 pointers<br>WorkList.push_back(NewValue); // No heap allocation until size &gt; 4<br>while (!WorkList.empty()) {<br>    Value *V = WorkList.pop_back_val(); // Pops the last element<br>    // Process V...<br>}</pre><h4>SmallString</h4><ul><li>A SmallVector&lt;char, N&gt; specialized for strings.</li><li>Some useful string helpers: str(), append(), push_back(), etc.</li></ul><h4>SmallPtrSet&lt;T*, N&gt;</h4><ul><li>A set optimized for storing a small number of pointers.</li><li>Linear for small sizes, hash table for larger sizes.</li><li><strong>Great for</strong> tracking visited nodes in graph algorithms.</li></ul><pre>SmallPtrSet&lt;BasicBlock*, 8&gt; Visited;<br>for (BasicBlock &amp;BB : Function) {<br>    if (Visited.insert(&amp;BB).second) {<br>        // First time visiting BB<br>    }<br>}</pre><h3>“Hashy” Workhorses</h3><h4>DenseMap&lt;KeyT, ValueT&gt; / DenseSet</h4><ul><li><strong>What</strong>: Open-addressing hash table with a compact memory layout.<br>- <em>Open addressing</em> is a collision resolution method where all elements are stored within the hash table itself, avoiding the need for pointers to separate nodes. This leads to better cache locality and reduced memory overhead.</li><li><strong>Shines with</strong>: pointer keys, small keys, and frequent lookups.</li><li><strong>APIs</strong>: try_emplace, insert, find, erase, etc.</li><li><strong>Perf Tips</strong>: Reserve capacity upfront via reserve(expectedSize); rebuild if tombstones explode (DenseMap::shrink_and_clear()).</li></ul><pre>DenseMap&lt;Value*, unsigned&gt; rank;<br>for (auto &amp;I : instructions(F)) {<br>    rank.try_emplace(&amp;I, rank.size()); // Assign unique rank if not present<br>}</pre><h4>Custom Keys providing DenseMapInfo&lt;Key&gt; with:</h4><ul><li>getEmptyKey() : A special key value representing an empty slot.</li><li>getTombstoneKey() : A special key value representing a deleted slot. <br>- Tombstones are special markers used in open-addressing hash tables to mean “this slot was occupied by a key but has since been deleted”. They help maintain the integrity of probing sequences during lookups and insertions.</li><li>getHashValue(const Key &amp;K) : A hash function for the key type.</li><li>isEqual(const Key &amp;LHS, const Key &amp;RHS) : Equality comparison.</li></ul><pre>struct MyKey {int a; int b;};<br>template&lt;&gt; struct DenseMapInfo&lt;MyKey&gt; {<br>  static MyKey getEmptyKey() { return {INT_MIN, INT_MIN}; } // Use unlikely values<br>  static MyKey getTombstoneKey() { return {INT_MIN + 1, INT_MIN + 1}; } <br>  static unsigned getHashValue(const MyKey &amp;K) {<br>    return hash_combine(K.a, K.b); // Combine fields for hash<br>  }<br>  static bool isEqual(const MyKey &amp;LHS, const MyKey &amp;RHS) {<br>    return LHS.a == RHS.a &amp;&amp; LHS.b == RHS.b;<br>  }<br>};</pre><h4>StringMap</h4><ul><li>A hash table mapping strings to values, optimized for string keys.</li><li><strong>Use when</strong>: when keys are owned and stable.</li></ul><pre>StringMap&lt;unsigned&gt; NameToID;<br>NameToID[&quot;foo&quot;]++; // Increment count for &quot;foo&quot;</pre><p><strong>Erasing While Iterating</strong></p><p>When erasing elements from DenseMap or StringMap during iteration, use the following pattern to avoid invalidating the iterator:</p><pre>for (auto It = Map.begin(); It != Map.end(); ) {<br>    if (it-&gt;second == 0) it = Map.erase(It); // erase returns the next valid iterator<br>    else ++It; // only increment if not erasing<br>}</pre><h3>Arenas, Uniquing, and more</h3><h4>BumpPtrAllocator</h4><ul><li>Fast linear allocator for short-lived objects.</li><li>Allocate many small objects quickly; free all at once.</li><li>Pair with StringSaver to own strings cheaply.</li></ul><pre>BumpPtrAllocator arena;<br>StringSaver saver(arena);<br>StringRef name = saver.save(&quot;temporary_name&quot;); // Owned by arena</pre><h3>FoldingSet</h3><ul><li><strong>What</strong>: hash-cons an object based on its structural identity.<br>- <em>Hash-consing</em> is a popular functional programming technique to canonicalize identical immutable structures so that these structures are represented by a single heap node. The usefulness stems from the fact that large data structures often contain many identical substructures; when we want to check for equality between two structures, we can simply compare their pointers instead of traversing the entire structure.</li><li><strong>Pattern</strong>: derive from FoldingSetNode, implement the Profile method, and use FoldingSet to store unique instances.</li></ul><pre><br>struct Key : public FoldingSetNode {<br>    int a;<br>    StringRef b;<br>    void Profile(FoldingSetNodeID &amp;ID) const {<br>        ID.AddInteger(a);<br>        ID.AddString(b);<br>    }<br>};<br><br>FoldingSet&lt;Key&gt; KeySet;<br>void insertOrGet(int a, StringRef b, BumpPtrAllocator &amp;arena) {<br>    Key Temp{a, b};<br>    void *InsertPos;<br>    if (Key *Existing = KeySet.FindNodeOrInsertPos(Temp, InsertPos)) { // hash-consed<br>        // Use Existing<br>    } else {<br>        Key *NewKey = new (arena.Allocate&lt;Key&gt;()) Key{a, saver.save(b)};<br>        KeySet.InsertNode(NewKey, InsertPos);<br>    }<br>}</pre><h3>Error handling the LLVM way</h3><p>LLVM provides a rich set of utilities for error handling, including Error, Expected&lt;T&gt;, and handleErrors. These abstractions allow for expressive and type-safe error propagation without relying on exceptions.</p><ul><li><strong>Return</strong> Expected&lt;T&gt; on success or error.</li><li><strong>Consume</strong>: if (!E) return E.takeError(); - By default, llvm::Error objects are move-only; takeError() allows transferring ownership of the error to the caller for handling.</li><li><strong>Helpers</strong>: cantFail(E), handleErrors(E, ...), joinErrors(...).</li></ul><pre>Expected&lt;std::unique_ptr&lt;Module&gt;&gt; loadModule(StringRef Path, LLVMContext &amp;Ctx) {<br>    SMDiagnostic Err;<br>    std::unique_ptr&lt;Module&gt; M = parseIRFile(Path, Err, Ctx);<br>    if (!M) return createStringError(inconvertibleErrorCode(), &quot;Failed to parse IR file&quot;);<br>    return std::move(M);<br>}</pre><h3>IR-Centric Must-Knows</h3><h4>Traversal Idioms</h4><pre>for (Function &amp;F : M) { // Look at all functions in Module M.<br>    for (BasicBlock &amp;BB : F) { // Look at all basic blocks in Function F.<br>        for (Instruction &amp;I : BB) { // Look at all instructions in BasicBlock BB.<br>            // Process instruction I<br>        }<br>    }<br>}<br><br>for (Use &amp;U : V-&gt;uses()) { // Look at all uses of Value v.<br>    if (auto *I = dyn_cast&lt;Instruction&gt;(U.getUser())) {<br>        // Process instruction I that uses V<br>    }<br>}<br><br>for (Value *op : I.operands()) { // Look at all operands of Instruction I.<br>    // Process operand op<br>}<br>for(Use &amp;U : I.operands()) { // Mutable access to operands<br>    // Mutate operand U<br>}</pre><h4>Mutation Safety</h4><ul><li><strong>Early-inc</strong>: Use make_early_inc_range when mutating a container while iterating over it.</li></ul><pre>for (Instruction &amp;I : make_early_inc_range(BB)) { // Safe to mutate BB while iterating<br>    I.eraseFromParent(); // Safe to erase while iterating<br>}</pre><h3>CFG Helpers</h3><ul><li>predecessors(BB), successors(BB): Iterate over predecessor/successor basic blocks.</li><li>LoopBlocksTraversal : DFS traversal of loop blocks.</li><li>ReversePostOrderTraversal : RPO traversal of CFG.</li></ul><pre>for (BasicBlock *Pred : predecessors(&amp;BB)) {<br>    // Process predecessor Pred<br>}<br><br>for (BasicBlock *BB : ReversePostOrderTraversal(&amp;F)) {<br>    // Process BB in RPO<br>}</pre><h3>Range and Iterator (Halloween!) Candy</h3><ul><li>enumerate(range): [index, element] pairs.</li><li>filter(range, predicate): Filter elements by predicate.</li><li>map_range(range, func): Transform elements by func.</li><li>zip(range1, range2, ...) : Tuple-wise iteration</li><li>reverse(range): Reverse iteration.</li></ul><h3>Choosing the Right Data Structure (A Decision Matrix)</h3><pre>| Situation / Requirement                                  | Recommended Type         | Notes                                                                                |<br>| -------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------ |<br>| Small list, hot path, typical size ≤ N                   | `SmallVector&lt;T, N&gt;`      | Inline storage for first N elements; avoid heap for common-case sizes.               |<br>| Small set of pointers (“seen” / “visited” set)           | `SmallPtrSet&lt;T*, N&gt;`     | Optimized for small pointer sets; grows to hash set when needed.                     |<br>| Many lookups with pointer or integer keys                | `DenseMap&lt;KeyT, ValueT&gt;` | Fast hash map with great cache locality; use `reserve()` when possible.              |<br>| Many lookups with pointer or integer elements            | `DenseSet&lt;T&gt;`            | Set version of `DenseMap`; same perf characteristics.                                |<br>| String keys that should be owned by the container        | `StringMap&lt;T&gt;`           | Owns key storage; efficient for lots of string-keyed lookups.                        |<br>| Non-owning view over a string                            | `StringRef`              | Cheap (ptr + length); underlying storage must outlive the `StringRef`.               |<br>| Non-owning view over a contiguous array of `T`           | `ArrayRef&lt;T&gt;`            | Read-only slice; works with `std::vector`, `SmallVector`, C arrays, etc.             |<br>| Non-owning *mutable* view over a contiguous array of `T` | `MutableArrayRef&lt;T&gt;`     | Like `ArrayRef` but lets you modify elements.                                        |<br>| Build log/debug strings without allocating repeatedly    | `Twine`                  | Only for temporary composition at call sites; don’t store it, materialize if needed. |<br>| Short, mutable strings with inline storage               | `SmallString&lt;N&gt;`         | `SmallVector&lt;char, N&gt;` with string helpers; pairs well with `StringRef`.             |<br>| Tons of short-lived small objects, freed all at once     | `BumpPtrAllocator`       | Arena allocator; great for pass-local structures and analyses.                       |<br>| Need interned / deduplicated structural keys/objects     | `FoldingSet&lt;T&gt;`          | Hash-consing; pointer equality implies structural equality.                          |</pre><h3>Common “Shooting Yourself in the Foot” Pitfalls</h3><ul><li><strong>Dangling</strong> StringRef: don’t reference temporaries. Instead, use StringSaver.</li><li><strong>Erasing while iterating</strong> : early_inc_range</li><li>SmallVector <strong>spill</strong> : choose N wisely.</li><li>DenseMap <strong>tombstone bloat</strong> : Use reserve(), and periodically rebuild().</li></ul><h3>Micro-Benchmarks</h3><p>Let’s look at a simple harness comparing DenseMap vs std::unordered_map for pointer keys.</p><pre>#include &quot;llvm/ADT/DenseMap.h&quot;<br>#include &lt;unordered_map&gt;<br>#include &lt;chrono&gt;<br>#include &lt;random&gt;<br><br>using namespace llvm;<br><br>int main() {<br>  constexpr size_t N = 100000;<br>  std::vector&lt;void*&gt; keys(N);<br>  for (size_t i=0;i&lt;N;++i) keys[i] = reinterpret_cast&lt;void*&gt;((i+1)*16);<br><br>  DenseMap&lt;void*, int&gt; dm; dm.reserve(N);<br>  auto t0 = std::chrono::high_resolution_clock::now();<br>  for (size_t i=0;i&lt;N;++i) dm.try_emplace(keys[i], (int)i);<br>  auto t1 = std::chrono::high_resolution_clock::now();<br><br>  std::unordered_map&lt;void*, int&gt; um; um.reserve(N);<br>  for (size_t i=0;i&lt;N;++i) um.emplace(keys[i], (int)i);<br>  auto t2 = std::chrono::high_resolution_clock::now();<br><br>  auto ns1 = std::chrono::duration_cast&lt;std::chrono::nanoseconds&gt;(t1-t0).count();<br>  auto ns2 = std::chrono::duration_cast&lt;std::chrono::nanoseconds&gt;(t2-t1).count();<br><br>  printf(&quot;DenseMap insert: %lld ns, unordered_map insert: %lld ns\n&quot;,<br>         (long long)ns1, (long long)ns2);<br>}</pre><p>When run, you should see DenseMap outperforming std::unordered_map significantly for pointer keys due to its cache-friendly design and lower overhead.</p><h3>Compile and Run</h3><pre>clang++ bench.cpp -O3 -I/path/to/llvm/include -o bench<br>./bench<br><br>DenseMap insert: 298833 ns, unordered_map insert: 50096584 ns</pre><p>From this simple benchmark, we observe that DenseMap is orders of magnitude faster than std::unordered_map for pointer keys, highlighting its efficiency for compiler workloads. Do more extensive benchmarking using perf!</p><h3>Conclusion</h3><p>LLVM’s ADT library provides a rich set of data structures and iterator patterns optimized for compiler workloads. By leveraging these tools effectively, you can write passes that are both efficient and maintainable. Understanding when and how to use these structures is key to mastering LLVM development. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42aa9657ff47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Rewriting works in MLIR: From Greedy Patterns to Dialect Conversions]]></title>
            <link>https://medium.com/@samarth.colleges/how-rewriting-works-in-mlir-from-greedy-patterns-to-dialect-conversions-a3dbac8064de?source=rss-26469bc63d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3dbac8064de</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[mlir]]></category>
            <dc:creator><![CDATA[Samarth Narang]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 18:54:26 GMT</pubDate>
            <atom:updated>2025-11-09T18:54:26.065Z</atom:updated>
            <content:encoded><![CDATA[<h4>An in-depth look at the rewriting mechanisms in MLIR and how they enable powerful optimizations.</h4><p><strong>TL;DR:</strong> Rewriting in MLIR is “find a pattern → make a change → repeat until nothing else matches.” You’ll mainly use:</p><ul><li><strong>Greedy pattern application</strong> for local canonicalization and peephole cleanups.</li><li><strong>Dialect conversion</strong> for legalizing/rewriting ops under explicit constraints.</li></ul><h3>Why this matters</h3><p>MLIR’s rewrite engine is the backbone for everything from tiny algebraic simplifications to whole-dialect migrations. If you can write a clean pattern and pick the right driver (greedy vs conversion), you can bend the IR to your will — safely.</p><h3>Part 1: The moving pieces</h3><h4>RewritePatternSet and PatternRewriter</h4><ul><li>RewritePatternSet is a container for your rewrite patterns. You populate it with instances of your custom patterns.</li><li>MLIR runs these patterns for you; you don’t directly loop over operations.</li><li>In your pattern’s matchAndRewrite, you<br>- Inspect the matched op.<br>- Optionally create the new IR (using the rewriter’s insertion point).<br>- Replace or erase the matched op.</li></ul><h4>Greedy vs. Conversion</h4><blockquote>Greedy (Canonicalization and Local Rewrites)</blockquote><ul><li>Think “peephole + algebraic simplification”.</li><li>Use applyPatternsGreedily to apply all patterns in a RewritePatternSet.applyPatternsGreedily(fop, std::move(patterns));</li></ul><blockquote>Conversion (Dialect Conversion)</blockquote><ul><li>Define legality constraints for ops via ConversionTarget.</li><li>Use TypeConverter to handle type conversions.</li><li>Use applyPartialConversion or applyFullConversion to convert ops while respecting legality.</li></ul><h3>Part 2: Your first greedy rewrite pattern</h3><p>Let’s fold away arith.addi %x, 0: i32 into just %x. Yeah, it’s trivial, and MLIR’s canonicalization already does this, but it’s a great starting point.</p><p><strong>Pattern</strong></p><pre>#include &quot;mlir/IR/PatternMatch.h&quot;<br>#include &quot;mlir/Dialect/Arith/IR/Arith.h&quot;<br>#include &quot;mlir/Pass/Pass.h&quot;<br><br>using namespace mlir;<br><br>namespace {<br>struct FoldAddIWithZeroPattern : OpRewritePattern&lt;arith::AddIOp&gt; {<br>  using OpRewritePattern::OpRewritePattern;<br><br>  LogicalResult matchAndRewrite(arith::AddIOp op,<br>                                PatternRewriter &amp;rewriter) const override {<br>    auto isZeroConst = [](Value v) {<br>      if (auto c = v.getDefiningOp&lt;arith::ConstantOp&gt;()) {<br>        if (auto intAttr = dyn_cast&lt;IntegerAttr&gt;(c.getValue()))<br>          return intAttr.getValue().isZero();<br>      }<br>      return false;<br>    };<br><br>    Value lhs = op.getLhs();<br>    Value rhs = op.getRhs();<br><br>    if (isZeroConst(lhs)) {<br>      rewriter.replaceOp(op, rhs);<br>      return success();<br>    }<br>    if (isZeroConst(rhs)) {<br>      rewriter.replaceOp(op, lhs);<br>      return success();<br>    }<br>    return failure();<br>  }<br>};<br>} // namespace<br><br>struct FoldAddIZeroPass<br>    : public PassWrapper&lt;FoldAddIZeroPass, OperationPass&lt;func::FuncOp&gt;&gt; {<br>  MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(FoldAddIZeroPass)<br>  StringRef getArgument() const override { return &quot;fold-addi-zero&quot;; }<br>  void runOnOperation() override {<br>    MLIRContext *ctx = &amp;getContext();<br>    RewritePatternSet patterns(ctx);<br>    patterns.add&lt;FoldAddIWithZeroPattern&gt;(ctx);<br><br>    if (failed(applyPatternsGreedily(getOperation(), std::move(patterns))))<br>      signalPassFailure();<br>  }<br>};<br><br>std::unique_ptr&lt;Pass&gt; mlir::createFoldAddIZeroPass() {<br>  return std::make_unique&lt;FoldAddIZeroPass&gt;();<br>}</pre><h3>Part 3: Tiny IR and run command</h3><p>Given this valid MLIR in test.mlir</p><pre>module {<br>  func.func @foo(%x : i32) -&gt; i32 {<br>    %c0 = arith.constant 0 : i32<br>    %y  = arith.addi %x, %c0 : i32<br>    return %y : i32<br>  }<br>}</pre><h4>Build and run</h4><ul><li>Register your pass via the PassRegistry .</li><li>Run with mlir-opt :</li></ul><pre>mlir-opt test.mlir --pass-pipeline=&quot;builtin.module(func.func(fold-addi-zero))&quot;</pre><p><em>Tip: Use </em><em>--mlir-print-ir-after-all/--mlir-print-ir-before-all to see IR after/before each pass.</em></p><p>Result</p><p>The output IR should have the addition arith.addi folded away, returning %x directly.</p><pre>// -----// IR Dump Before FoldAddIZeroPass (fold-addi-zero) //----- //<br>func.func @foo(%arg0: i32) -&gt; i32 {<br>  %c0_i32 = arith.constant 0 : i32<br>  %0 = arith.addi %arg0, %c0_i32 : i32<br>  return %0 : i32<br>}<br><br>module {<br>  func.func @foo(%arg0: i32) -&gt; i32 {<br>    return %arg0 : i32<br>  }<br>}</pre><h3>Part 4: Dialect Conversion in a nutshell</h3><p>Greedy patterns shine for local fixes. But when you need to <strong>legalize</strong> or <strong>migrate</strong> ops across dialects, use conversion.</p><h4>Core ingredients</h4><ul><li><strong>ConversionTarget</strong>: Define which ops are legal/illegal.</li><li><strong>TypeConverter</strong>: Handle type conversions.</li><li><strong>Patterns</strong>: Similar to greedy patterns but used in the conversion context.</li></ul><h4>Example: lower `toy.addi → arith.addi</h4><p><strong>Key differences vs greedy</strong></p><ul><li>You <strong>declare legality</strong>, and MLIR rewrites until the IR satisfies it.</li><li>You use a <strong>ConversionPatternRewriter</strong>, which works with already-converted operands/types.</li><li>A <strong>TypeConverter</strong> lets you change types as you go.</li></ul><h3>Part 5: Folding vs. Patterns</h3><ul><li><strong>Folding</strong>: lives on the op (Op::fold) for trivial constant simplifications.</li><li><strong>Patterns</strong>: more expressive — can replace multi-op structures, reshape regions, etc.</li><li>The <strong>greedy driver</strong> tries folding first, then applies patterns until a fixed-point.</li></ul><h3>Part 6: Match helpers, benefits and ordering</h3><ul><li>Use helpers like matchPattern and constant readers; but it’s okay to directly query ops too.</li><li>Patterns can be prioritized via the benefit parameter in the constructor. Higher benefit patterns are tried first.</li><li>Keep patterns <strong>local</strong> and <strong>type-correct</strong>; prefer creating new ops over mutating existing ones.</li></ul><h3>Part 7: Debugging and guardrails</h3><ul><li><strong>IR Printing</strong>: Use --mlir-print-ir-after-all to see IR after each pass.</li><li><strong>Generic Form</strong> : Use --mlir-print-op-generic to see full op details.</li><li><strong>Determinism</strong>: --mlir-disable-threading can help with non-deterministic issues during debugging.</li><li><strong>No use-after-erase</strong>: Never touch an operation after eraseOp has been called.</li><li><strong>Dominance/Insertion Point</strong>: Insert new ops at the correct insertion point, i.e., where all uses are dominated.</li><li><strong>Testing</strong>: Use FileCheck to write tests for your patterns and passes.</li></ul><h3>Part 8: Mini LIT test example</h3><pre>// RUN: mlir-opt %s --pass-pipeline=&quot;builtin.module(func.func(fold-addi-zero))&quot; | FileCheck %s<br>module {<br>  func.func @foo(%x : i32) -&gt; i32 {<br>    %c0 = arith.constant 0 : i32<br>    %y  = arith.addi %x, %c0 : i32<br>    return %y : i32<br>  }<br>}<br><br>// CHECK-LABEL: func @foo(<br>// CHECK-NOT: arith.addi<br>// CHECK: return [[X:%.*]] : i32<br>// CHECK: }</pre><p>This test ensures that after running the fold-addi-zero pass, there are no arith.addi operations left in the function.</p><h3>Conclusion</h3><ul><li>Rewriting in MLIR is a powerful mechanism that enables both local optimizations and complex dialect conversions.</li><li>Reach for dialect conversion when you need to enforce legality constraints across a set of ops.</li><li>Printing and testing are your friends when developing and debugging patterns.</li><li>Happy rewriting!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3dbac8064de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying GPU Terminology: A Compiler Engineer’s Field Guide]]></title>
            <link>https://medium.com/@samarth.colleges/demystifying-gpu-terminology-a-compiler-engineers-field-guide-43fe6af5add0?source=rss-26469bc63d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/43fe6af5add0</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[amd-rocm]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[cuda]]></category>
            <dc:creator><![CDATA[Samarth Narang]]></dc:creator>
            <pubDate>Fri, 07 Nov 2025 23:47:24 GMT</pubDate>
            <atom:updated>2025-11-07T23:47:24.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KITxFFvDqOQ3--ovtFFVw.png" /></figure><h4>GPUs aren’t mysterious — just picky. Most performance cliffs aren’t about the math; they’re about how warps step, how memory is fetched, and how often we spill. This guide decodes the jargon into choices you can actually make when you tile, fuse, and lay out your kernels.</h4><p><strong>TL;DR</strong></p><ul><li><strong>Think in warps</strong>, not threads.</li><li><strong>Coalesce or pay</strong>.</li><li><strong>Tile for reuse</strong> in shared memory, but watch the <em>register pressure</em>.</li><li><strong>Matrix units</strong> (Tensor Cores, FMAs, etc) love the <em>right</em> data types and tile sizes.</li><li><strong>Occupancy</strong> is a balancing act: a tool, not a goal. Just enough to hide latency.</li></ul><h3>1. Execution Model, Decoded</h3><h4>SIMT vs SIMD (why is it confusing?)</h4><ul><li><strong>SIMD (CPU):</strong> Single Instruction, Multiple Data. One instruction operates on a fixed-width vector (e.g., a single AVX-512 instruction processes 16 floats at once).</li><li><strong>SIMT (GPU):</strong> Single Instruction, Multiple Threads. Many threads execute the sae instruction <strong>in lockstep</strong> as a <em>warp</em> (NVIDIA) or <em>wavefront</em> (AMD); each thread has its own registers/control flow.</li></ul><h4>Warps/Wavefronts</h4><p>Smallest lockstep unit:</p><ul><li>NVIDIA: <strong>warp</strong> = 32 threads</li><li>AMD: <strong>wavefront</strong> = 32/64 threads (depending on architecture)</li></ul><p><strong>Tip:</strong> choose block sizes as multiples of warp size (e.g., 128, 256) to maximize utilization.</p><h4>CTA (Cooperative Thread Array) / Workgroup</h4><p>A cooperatively scheduled group of threads sharing on-chip memory and synchronization (barriers).</p><p><strong>Balance:</strong></p><ol><li>Enough warps to hide latency.</li><li>Avoid <strong>register pressure</strong> that causes spills.</li><li>Keep <strong>shared memory</strong> usage in check.</li></ol><h4>Occupancy (It’s not a religion)</h4><p>Active warps per Streaming Multiprocessor (SM) / Compute Unit (CU) relative to the maximum possible. This helps hide latency but chasing 100% occupancy can backfire due to increased register pressure and shared memory contention.</p><h3>2. Memory Hierarchy (where performance is won and lost)</h3><p><strong>Registers -&gt; Shared Memory (L1) -&gt; L2 Cache -&gt; Global Memory (HBM/DRAM)</strong></p><p>Latency increases and bandwidth decreases as you go down the hierarchy.</p><h4>Coalesced Access (the golden rule)</h4><p>Adjacent threads access adjacent addresses -&gt; fewer memory transactions -&gt; higher effective bandwidth.</p><p><strong>Layout Matters:</strong> NHWC/NCHW/blocked layouts decide whether threadIdx.x walks through contiguous memory.</p><p><strong>Quick Check:</strong> If indexing A[threadIdx.x] results in strided access, performance will suffer.</p><h4>Shared Memory (on-chip scratchpad)</h4><p>On-chip, software-managed cache memory.</p><ul><li>Perfect for <strong>tiling</strong> working sets to maximize data reuse.</li><li>Beware of <strong>bank conflicts</strong>: ensure threads access different memory banks to avoid serialization.</li></ul><p><strong>Trick:</strong> Add padding to spread accesses across banks.</p><h4>Spills (the invisible tax)</h4><p>Too many live variables lead to register spills to local memory (off-chip), causing massive slowdowns.</p><p><strong>Mitigation:</strong></p><ul><li>Shorten live ranges. (e.g. reorder, store intermediate results in shared memory)</li><li>Fuse judiciously to reduce temporary variables.</li><li>Split kernels if necessary.</li></ul><h3>3. Math Units: Matrix Engines, Precision, and Shapes</h3><p>Modern GPUs ship with specialized matrix units (Tensor Cores on NVIDIA, Matrix Cores on AMD) that accelerate matrix multiplications and convolutions.</p><ul><li><strong>NVIDIA:</strong> Tensor Core</li><li><strong>AMD:</strong> Matrix Core</li><li><strong>Intel:</strong> XMX (GPU) / AMX (CPU)</li></ul><p>They love:</p><ul><li><strong>Low precision types:</strong> FP16, BF16, INT8, etc.</li><li><strong>Right tile sizes:</strong> which vary by architecture, but mutliples aligning to MMA (Matrix Multiply-Accumulate) shapes are best (e.g., 16x16 for NVIDIA Tensor Cores).</li><li>Proper <strong>accumulation types</strong> to avoid precision loss. e.g., multiply in FP16, accumulate in FP32.</li></ul><p><strong>Compiler Move:</strong> Choose pack/layout + tile sizes that map <strong>exactly</strong> to these hardware shapes for maximum throughput. “Almost right” shapes silently leave throughput on the table.</p><h3>4. Scheduling and Latency Hiding</h3><h4>Warp Scheduling</h4><p>SMs/CUs keep several warps ready to execute. When one warp stalls (e.g., waiting for memory), another can run, hiding latency. If you under-provision warps (low occupancy), the GPU may sit idle.</p><h4>Divergence and Predication</h4><p>If a branch is hot and divergent (threads in a warp take different paths), the warp serializes execution, hurting performance. We can then “flatten” branches with <strong>predication</strong> or <strong>data-parallel</strong> transformations. If a branch is rare but heavy, split into separate kernels.</p><h3>5. Vendor Term Crosswalk</h3><pre>| Concept        | NVIDIA       | AMD               | Intel              |<br>| -------------- | ------------ | ----------------- | ------------------ |<br>| Lockstep unit  | Warp (32)    | Wavefront (32/64) | Sub-group (varies) |<br>| SM/CU block    | SM           | CU                | Xe-core            |<br>| Matrix engines | Tensor Cores | MFMA/WMMA         | XMX (GPU) / AMX    |</pre><p><em>Use the crosswalk to translate docs without changing mental models.</em></p><h3>6. Checklists you will actually use</h3><p><strong>Block size sweep (first pass):</strong></p><ul><li>Start at <strong>warp-size multiples</strong>.</li><li>Cap registers/thread; if spills occur, reduce tile size or split computation.</li><li>Keep shared memory &lt; threshold.</li></ul><p><strong>Coalescing Sanity:</strong></p><ul><li>Ensure threadIdx.x accesses contiguous memory.</li><li>If strided, consider layout transformations, add a <strong>pack</strong> step, or adjust indexing.</li></ul><p><strong>Shared Memory Tiling:</strong></p><ul><li>Tile only when <strong>reuse &gt; copy-in + copy-out cost</strong>.</li><li>Add <strong>padding</strong> to avoid bank conflicts. (even 1 element can help)</li></ul><p><strong>Matrix Unit Mapping:</strong></p><ul><li>Match <strong>dtypes</strong> and <strong>tile sizes</strong> to hardware specs.</li><li>Prefer <strong>fp32 accumulations</strong> when using low-precision inputs.</li></ul><h3>7. Quick Reference Cheat Sheet</h3><p><strong>Execution Stack</strong></p><p>Grid -&gt; Block (CTA) -&gt; Warp -&gt; Thread</p><p><strong>Memory Stack</strong></p><p>Registers -&gt; Shared Memory -&gt; L2 Cache -&gt; Global Memory</p><p><strong>Coalesced vs Non-coalesced</strong></p><p><em>Threads</em>: t0, t1, t2, t3, t4, t5, t6, t7</p><p><em>Coalesced</em>: A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7]</p><p><em>Non-coalesced</em>: A[0], A[8], A[16], A[24]…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43fe6af5add0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>