<?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 Aadishagrawal on Medium]]></title>
        <description><![CDATA[Stories by Aadishagrawal on Medium]]></description>
        <link>https://medium.com/@aadishagrawal?source=rss-4354164acdff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QuOMiQ7Kd1RXDPuJ.jpg</url>
            <title>Stories by Aadishagrawal on Medium</title>
            <link>https://medium.com/@aadishagrawal?source=rss-4354164acdff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:05:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aadishagrawal/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[DP, TP, PP and EP: How LLM Parallelism Actually Fits Together]]></title>
            <link>https://pub.towardsai.net/dp-tp-pp-and-ep-how-llm-parallelism-actually-fits-together-2cc4e611da72?source=rss-4354164acdff------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cc4e611da72</guid>
            <category><![CDATA[mixture-of-experts]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Aadishagrawal]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 08:44:58 GMT</pubDate>
            <atom:updated>2026-11-22T06:53:19.401Z</atom:updated>
            <content:encoded><![CDATA[<h4>A worked example: serving Qwen3.5–35B-A3B, a 256-expert MoE model, on 8 GPUs</h4><h3>How this started</h3><p>I was looking at a GPU trace of a Mixture-of-Experts model served on 8 GPUs, and one thing didn’t make sense to me.</p><p>The model has 256 experts. I had always pictured MoE serving with the experts spread out, a few dozen on each GPU, and tokens travelling to wherever their experts live. That’s not what the trace showed. <strong>Every GPU was running all 256 experts, and each one was a thin 1/8 slice of the real expert.</strong> The matrix multiplications were narrow, and there were a lot of them.</p><p>That raised a set of questions I couldn’t answer:</p><ul><li>Why slice every expert instead of giving each GPU its own experts?</li><li>Is one layout faster than the other, and does it depend on prefill versus decode?</li><li>How does this “expert parallelism” interact with the tensor, pipeline and data parallelism I already knew?</li><li>And why does nobody draw all four together in one picture?</li></ul><p>This post is what I found. I’ll explain each kind of parallelism, when you need it and how they combine, then work through one real model on 8 GPUs with actual numbers.</p><h3>The model we’ll use throughout</h3><p><strong>Qwen3.5–35B-A3B</strong>: about 35B parameters in total, about 3B active per token.</p><pre>Layers          40  (30 linear-attention &quot;GDN&quot; layers + 10 full-attention layers)<br>Attention       16 query heads, 2 KV heads, head dim 256<br>MoE             every layer: 256 experts, each token uses the top 8<br>Hidden size     H = 2048<br>Expert MLP      SwiGLU, intermediate size I = 512<br>                  gate_up: 2048 x 1024   (2.10 M params)<br>                  down:    512  x 2048   (1.05 M params)<br>                  ≈ 3.15 M params per expert</pre><p>One number explains most of what follows:</p><pre>256 experts x 3.15 M params x 40 layers ≈ 32.2 B params</pre><p>So <strong>about 32 of the 35 billion parameters are experts</strong>, yet each token touches only 8 of the 256 experts per layer. Memory is dominated by experts, while compute per token is small. Keep that in mind.</p><h3>1. The different kinds of parallelism</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LwiHZ-EnurkCG0GPvfv5A.png" /></figure><p>Each form of parallelism answers one question: <strong>which part of the work do we split across GPUs?</strong></p><pre>                          ┌── the batch ──────────► Data Parallel     (DP)<br>  the work of one step ───┼── the weight matrices ► Tensor Parallel   (TP)<br>                          ├── the layers ─────────► Pipeline Parallel (PP)<br>                          └── the experts ────────► Expert Parallel   (EP, MoE only)</pre><p>There are also a few variants you’ll see in configs:</p><ul><li><strong>Sequence Parallel (SP).</strong> A companion to TP that splits activations along the sequence dimension outside the matmuls. It saves activation memory, not weights.</li><li><strong>Context Parallel (CP).</strong> Splits a very long sequence across GPUs for attention. It’s used for 100K+ token contexts.</li><li><strong>ZeRO / FSDP.</strong> Not a new dimension. These shard DP’s redundant copies (optimizer states, gradients, weights) across the DP group.</li><li><strong>DP-attention.</strong> An inference pattern: attention runs data-parallel while the MoE layers run expert-parallel. This turns out to be the key for our model.</li></ul><p>The four core strategies differ mainly in <strong>what they communicate, and how often</strong>:</p><pre>Strategy   Collective                     How often                    On the critical path?<br>--------   ----------------------------   --------------------------   ---------------------<br>DP         all-reduce of gradients        once per training step       no (overlapped)<br>TP         all-reduce of activations      every layer                  YES<br>PP         point-to-point send/recv       once per stage boundary      partly (idle &quot;bubble&quot;)<br>EP         all-to-all of routed tokens    twice per MoE layer          YES</pre><p>Almost every layout decision follows from this table.</p><h3>2. Each kind of parallelism, explained</h3><h3>2.1 Data Parallelism (DP): split the batch</h3><p>Each GPU holds a <strong>full copy of the model</strong> and processes different samples.</p><pre>global batch ──┬──► GPU 0: full model ──► gradients₀ ──┐<br>               ├──► GPU 1: full model ──► gradients₁ ──┼──► all-reduce (average)<br>               ├──► GPU 2: full model ──► gradients₂ ──┤        │<br>               └──► GPU 3: full model ──► gradients₃ ──┘        ▼<br>                                                     every GPU applies the same update</pre><ul><li><strong>Training.</strong> One gradient all-reduce per step. Frameworks bucket the gradients and overlap the all-reduce with the backward pass, so it’s usually hidden.</li><li><strong>Inference.</strong> No communication at all. DP replicas are just independent servers behind a load balancer.</li><li><strong>Limitation.</strong> It doesn’t reduce memory per GPU. Every GPU still holds the whole model (unless you add ZeRO-3 / FSDP).</li></ul><p>Training memory with mixed-precision Adam is about 16 bytes per parameter: 2 for bf16 weights, 2 for bf16 gradients and 12 for the fp32 master copy plus Adam’s two moments. ZeRO shards these across the DP group:</p><pre>Plain DP   16 B/param on every GPU<br>ZeRO-1     4 + 12/DP      (shard optimizer states)<br>ZeRO-2     2 + 14/DP      (also shard gradients)<br>ZeRO-3     16/DP          (also shard weights; all-gather them layer by layer)</pre><h3>2.2 Tensor Parallelism (TP): split the weight matrices</h3><p>TP splits <strong>each layer’s weight matrices</strong> across GPUs so they compute every layer together. The standard trick (from Megatron-LM) pairs a column split with a row split so that only <strong>one</strong> sync is needed per block:</p><pre>MLP:  Y = act(X · A) · B          with TP = 2  <br><br>A split by COLUMNS:  A = [A₀ | A₁]      GPU r computes  Zᵣ = act(X · Aᵣ)    ← no communication<br>B split by ROWS:     B = [B₀ ; B₁]      GPU r computes  Yᵣ = Zᵣ · Bᵣ<br>                                          Y = Y₀ + Y₁                       ← one all-reduce</pre><p>Attention works the same way. Q/K/V are split <strong>by heads</strong>, so each GPU owns a subset of heads, and the output projection is row-split and followed by one all-reduce.</p><p>For Qwen3.5–35B-A3B with TP = 2, each GPU owns 8 of the 16 query heads and 1 of the 2 KV heads.</p><p><strong>Cost.</strong> Every all-reduce moves the full activation, T tokens x 2048 x 2 bytes, which is <strong>4 KB per token per all-reduce</strong>. It happens every layer, and nothing can proceed until it finishes. That is why TP needs very fast GPU-to-GPU links (NVLink, xGMI and similar) and almost always stays <strong>inside one server</strong>.</p><p><strong>The KV-head limit.</strong> This one surprised me. TP splits attention by KV heads, so it can’t usefully go beyond the number of KV heads:</p><pre>Qwen3.5-35B-A3B has 2 KV heads.<br><br>TP = 2   →  GPU 0 gets KV head 0, GPU 1 gets KV head 1        clean split<br>TP = 8   →  8 GPUs, only 2 KV heads → each head copied to 4 GPUs<br>            → the KV cache is stored 4 times</pre><p>Keep this in mind. It’s the main reason the 8-GPU example below doesn’t simply use TP = 8.</p><p><strong>Sequence Parallelism (SP)</strong> comes paired with TP. Outside the matmuls (LayerNorm, residual adds), activations are split along the sequence instead of being copied. The all-reduce becomes a reduce-scatter plus an all-gather. The traffic is the same, but activation memory per GPU drops by the TP factor.</p><h3>2.3 Pipeline Parallelism (PP): split the layers</h3><p>Each GPU (or group of GPUs) owns a contiguous block of layers, called a <strong>stage</strong>. Activations flow forward through the stages and gradients flow back.</p><pre>stage 0: layers 0-19  ──activations──►  stage 1: layers 20-39<br>                      ◄──gradients────</pre><p>The problem is the <strong>bubble</strong>. With a single batch, stage 1 waits while stage 0 works, and the reverse happens on the way back. The fix is to cut the batch into many <strong>micro-batches</strong> and interleave them:</p><pre>1F1B schedule, 2 stages, 4 micro-batches    (F = forward, B = backward, .. = idle)<br><br> stage 0:  F1 F2 F3 F4 .. B1 B2 B3 B4<br> stage 1:  .. F1 B1 F2 B2 F3 B3 F4 B4<br>           ^^                      ^^   bubble</pre><pre>bubble fraction = (p - 1) / (m + p - 1)        p = stages, m = micro-batches<br>p = 2, m = 16   →   1/17 ≈ 6 %</pre><ul><li><strong>Cost.</strong> Only one activation tensor crosses each stage boundary per micro-batch. That’s low bandwidth, so PP works fine <strong>across servers</strong> over slower links.</li><li><strong>Price.</strong> Idle time from the bubble, and the stages have to be balanced (roughly equal compute per stage).</li><li><strong>Inference.</strong> Every token passes through every stage in sequence, so PP adds latency. Use it only when the model doesn’t fit in one server.</li></ul><h3>2.4 Expert Parallelism (EP): split the experts</h3><p>In a MoE layer, the dense MLP is replaced by many expert MLPs plus a small <strong>router</strong>. The router picks the top-k experts for each token, and the token’s output is a weighted sum of what those experts produce:</p><pre>y = Σ  gᵢ(x) · Expertᵢ(x)      over the top-8 experts chosen for token x</pre><p>EP gives each GPU <strong>a subset of whole experts</strong>. With 256 experts and EP = 8, that’s 32 experts per GPU. Tokens are then sent to wherever their experts live:</p><pre>     GPU 0            GPU 1                       GPU 7<br>  its tokens        its tokens       ...        its tokens<br>      │                 │                           │<br>   router            router                      router        top-8 of 256 per token<br>      │                 │                           │<br>  ════════════════ all-to-all DISPATCH ══════════════════════   token → GPU (expert_id ÷ 32)<br>      │                 │                           │<br>  experts 0-31     experts 32-63     ...      experts 224-255   one grouped GEMM per GPU<br>      │                 │                           │<br>  ════════════════ all-to-all COMBINE  ══════════════════════   results go back home<br>      │                 │                           │<br>  weighted sum      weighted sum                weighted sum</pre><p><strong>Cost.</strong> There are two all-to-alls per MoE layer. A token is 4 KB (2048 values in bf16). Good kernels (for example DeepEP) send one copy per destination <strong>GPU</strong>, not per expert. With 8 experts out of 256 spread across 8 GPUs, a token lands on about <strong>5.3 distinct GPUs</strong> on average:</p><pre>distinct GPUs per token = EP · (1 - C(E - E/EP, k) / C(E, k))<br>                        = 8  · (1 - C(224, 8) / C(256, 8))<br>                        ≈ 8  · (1 - 0.338)  ≈ 5.3</pre><p><strong>The weakness is load imbalance.</strong> If the router sends a lot of tokens to a few popular experts, the GPUs holding them become stragglers, and everyone waits at the combine step. The usual fixes:</p><ul><li><strong>Training:</strong> a load-balancing loss, or a capacity limit per expert.</li><li><strong>Inference:</strong> EPLB, which replicates hot experts on more than one GPU and rebalances periodically.</li></ul><p><strong>EP versus TP on the experts.</strong> This was my original question. Without EP, frameworks apply TP to the MoE layers too: every GPU holds <strong>all</strong> experts, each one sliced. That’s exactly what my trace showed.</p><pre>                               TP = 8 on experts          EP = 8<br>                               ------------------         ------------------<br>experts per GPU                256 (each 1/8 slice)       32 (whole)<br>gate_up GEMM per expert        2048 x 128                 2048 x 1024<br>down GEMM per expert           64   x 2048                512  x 2048<br>expert weight bytes per GPU    1/8 of total               1/8 of total     ← same!<br>collective per MoE layer       all-reduce, all tokens     2 x all-to-all, routed tokens only<br>load balance                   perfect                    depends on router</pre><p>For a fixed batch, the <strong>expert weight bytes per GPU are the same</strong>, and so is the average number of rows each expert processes. What EP changes is:</p><ol><li>the <strong>GEMM shapes</strong> (whole experts, 8x wider),</li><li>the <strong>communication pattern</strong>, and</li><li>through DP-attention (shown below), <strong>how big a batch you can afford</strong>.</li></ol><h3>3. When is each kind of parallelism needed?</h3><p>A practical way to decide, in order:</p><pre>1. Does the model (plus optimizer / KV cache) fit on one GPU?<br>      YES → use DP only. Done.  (training: add ZeRO if optimizer states don&#39;t fit)<br>2. Is it a MoE model?<br>      YES → use EP for the expert weights. Experts dominate memory, and EP divides them.<br>            Keep the EP group inside one server if possible (all-to-all is latency-critical).<br>3. Attention / dense layers still too big, or need lower latency?<br>      → use TP inside one server, up to the number of KV heads.<br>      → beyond that, use DP-attention instead of more TP (avoids copying the KV cache).<br>4. Still doesn&#39;t fit, or the job spans several servers?<br>      → add PP across servers (cheap on bandwidth). Use many micro-batches to keep<br>        the bubble small.<br>5. Very long sequences (100K+ tokens)?<br>      → add CP to split the sequence for attention.<br>6. Fill whatever GPUs remain with DP (and, for experts, expert-DP).</pre><p>The rule underneath all of this:</p><blockquote><strong><em>Put the collectives that run every layer (TP, EP) on the fastest links. Let the ones that run rarely (DP, PP) cross the slower network.</em></strong></blockquote><p>Some symptoms and their usual fixes:</p><pre>Symptom                                       Usual fix<br>-------------------------------------------   ------------------------------------------------<br>TP all-reduce dominates the timeline          lower TP; keep it in-node; switch attention to DP<br>All-to-all dominates prefill                  overlap comm with compute; keep EP in-node<br>All-to-all dominates decode                   low-latency dispatch kernels, CUDA graphs, bigger batch<br>One GPU is always the slowest in MoE layers   expert imbalance → EPLB / redundant experts<br>GPUs idle at the start/end of each step       pipeline bubble → more micro-batches, interleaving<br>Out of KV-cache memory with TP &gt; KV heads     DP-attention</pre><h3>4. How the strategies work together</h3><h3>The counting rules</h3><p>For <strong>dense layers</strong>, the GPUs form a grid:</p><pre>total GPUs = TP x PP x DP</pre><p>For <strong>MoE layers</strong>, here is the part that took me longest to see. <strong>EP is not an extra dimension of the grid.</strong> It reuses the same GPUs as TP and DP (inside each pipeline stage) and regroups them for the expert weights:</p><pre>TP x DP  =  ETP x EP x EDP<br>ETP  = tensor parallelism inside each expert (usually 1 for small experts)<br>EP   = how many GPUs the experts are spread over<br>EDP  = expert data parallelism: how many copies of each expert shard exist<br>       (expert gradients are averaged only across these copies)</pre><p>So a single GPU belongs to several groups at once: a TP group and a DP group for attention, an EP group and an EDP group for experts, and one pipeline stage.</p><h3>Which groups land on the same server</h3><p>Frameworks number GPUs in a fixed nesting order. Megatron-LM uses tp → cp → ep → dp → pp, with TP varying fastest. GPUs with neighbouring rank numbers sit in the same server, so <strong>TP and EP naturally stay inside a server, while DP and PP span servers.</strong> That&#39;s exactly what we want.</p><h3>All four at once: training on 32 GPUs (4 servers x 8 GPUs)</h3><p>Before the 8-GPU serving example, here is what a layout with <strong>all four</strong> strategies looks like when training this model:</p><pre>PP = 2    one pipeline stage per 2 servers, 20 layers each (15 GDN + 5 full-attention)<br>TP = 2    matches the 2 KV heads exactly<br>DP = 8    32 / (2 x 2)<br>EP = 8    one server = one EP group → 32 experts per GPU<br>EDP = 2   because TP x DP = 16 = ETP(1) x EP(8) x EDP(2)</pre><pre>PP stage 0 (layers 0-19)                     PP stage 1 (layers 20-39)<br>        ┌───────── Node 0 ─────────┬───────── Node 1 ──────────┐ ┌── Node 2 ──┬── Node 3 ──┐<br>rank:     0  1  2  3  4  5  6  7   │  8  9 10 11 12 13 14 15     16 ...... 23  24 ...... 31<br>TP=2:    [0 1][2 3][4 5][6 7]      │ [8 9][10 11][12 13][14 15]    (same pattern)<br>DP=8:    one TP pair = one DP replica → pairs {0,1},{2,3},...,{14,15}<br>         dense DP groups: {0,2,4,...,14} and {1,3,5,...,15}<br>EP=8:    group A = {0..7}          │ group B = {8..15}             {16..23}    {24..31}<br>         r0: E0-31   r1: E32-63   r2: E64-95  ...  r7: E224-255   (r8..r15 use the same split)<br>EDP=2:   (0,8) (1,9) (2,10) ... (7,15)   ← ranks holding the same experts, on different nodes<br>PP p2p:  rank i ⇄ rank i+16              ← stage boundary, inter-node</pre><p>One training step on this layout:</p><pre>DP: global batch split 8 ways → each TP pair gets its own micro-batches<br> │<br> ▼ stage 0, for each of its 20 layers:<br> │    attention / GDN on the TP pair          → reduce-scatter   [2 GPUs, in-server]<br> │    router picks top-8 experts per token<br> │    all-to-all DISPATCH                     → 8 GPUs           [in-server]<br> │    grouped GEMM on 32 local experts<br> │    all-to-all COMBINE                      → 8 GPUs           [in-server]<br> │    all-gather for the next attention       → 2 GPUs           [in-server]<br> │<br> ▼ PP: send activations, rank i → rank i+16                      [cross-server]<br> │ stage 1 runs layers 20-39 → loss<br> │<br> ▼ backward: same collectives in reverse (1F1B, m = 16 → bubble ≈ 6 %)<br> │<br> ▼ gradient sync, overlapped with backward:                      [cross-server]<br>      attention / dense grads → all-reduce across DP  = 8<br>      expert grads            → all-reduce across EDP = 2</pre><p>The collectives that run <strong>every layer</strong> (TP and EP) never leave a server. Only the pipeline hand-off and the once-per-step gradient sync cross the network.</p><p>What EP buys here:</p><pre>per GPU, experts:   32 experts x 20 layers x 3.15 M ≈ 2.0 B params ≈  4 GB (bf16)<br>without EP:        256 experts x 20 layers x 3.15 M ≈ 16  B params ≈ 32 GB (bf16)</pre><h3>5. Worked example: Qwen3.5–35B-A3B on 8 GPUs (serving)</h3><p>Now the case that started all of this: <strong>serving the model on one 8-GPU server.</strong></p><h3>Step 1: Do we need PP?</h3><pre>35 B params x 2 bytes (bf16) ≈ 70 GB of weights</pre><p>That fits comfortably across 8 GPUs, so <strong>no PP</strong>. Everything stays inside one server, which is great for latency.</p><h3>Step 2: The default, TP = 8</h3><p>The simplest launch is TP = 8 for everything. This is what my original trace was:</p><pre>Attention:  TP = 8   → 16 q heads / 8 = 2 per GPU<br>                       2 KV heads / 8 → not possible → each KV head copied to 4 GPUs<br>MoE:        TP = 8   → every GPU holds all 256 experts, each sliced to 1/8<br>                       gate_up per expert: 2048 x 128,  down: 64 x 2048</pre><p>Two problems:</p><ol><li><strong>The KV cache is stored 4 times.</strong></li><li><strong>The expert GEMMs are small and fragmented</strong>: 256 thin matrices per layer per GPU.</li></ol><h3>Step 3: The better layout, DP-attention plus EP</h3><pre>Attention:  DP = 4 x TP = 2   → 4 independent request groups; TP = 2 matches the 2 KV heads<br>MoE:        EP = 8            → each GPU holds 32 whole experts<br>PP:         1</pre><p>The rank layout:</p><pre>One server, 8 GPUs (PP = 1)<br>        ┌──────────────────────────────────────────────────────────────────┐<br>rank:      0     1     2     3     4     5     6     7<br>ATTENTION (DP = 4 x TP = 2):<br>           [ 0  1 ]    [ 2  3 ]    [ 4  5 ]    [ 6  7 ]<br>            DP grp 0    DP grp 1    DP grp 2    DP grp 3   ← different requests in each<br>            r0: kv head 0 + q heads 0-7,  r1: kv head 1 + q heads 8-15  (same in every pair)<br>MoE (EP = 8, one group spanning the whole server):<br>           r0: E0-31     r1: E32-63    r2: E64-95    r3: E96-127<br>           r4: E128-159  r5: E160-191  r6: E192-223  r7: E224-255<br>Same GPU, two roles:  rank 5 = &quot;TP rank 1 of DP group 2&quot; for attention<br>                             = &quot;owner of experts 160-191&quot; for MoE<br>        └──────────────────────────────────────────────────────────────────┘</pre><h3>Step 4: Why this layout wins on memory</h3><p>KV cache per token, across the 10 full-attention layers:</p><pre>2 (K and V) x 2 KV heads x 256 dim x 2 bytes x 10 layers = 20 KB per token</pre><pre>KV stored per token (all 8 GPUs)    duplication<br>TP = 8                   80 KB                               4x   (each KV head on 4 GPUs)<br>DP = 4 x TP = 2          20 KB                               1x   (each request lives in one pair)</pre><p>That’s <strong>about 4x more tokens in the KV cache</strong>, which means more concurrent requests.</p><p>Weight memory per GPU:</p><pre>TP = 8                    DP-attn + EP = 8<br>experts                   32.2 B / 8 ≈ 4.0 B        32.2 B / 8 ≈ 4.0 B       ≈ 8 GB<br>attention / other         ≈ 2.8 B / 8 ≈ 0.35 B      ≈ 2.8 B / 2 ≈ 1.4 B      (copied in each DP group)<br>total weights             ≈ 8.7 GB                  ≈ 10.8 GB</pre><p>The EP layout spends about 2 GB more per GPU on weights, because the attention weights are copied across the 4 DP groups. In exchange it saves 4x on the KV cache, which is usually the much larger number. (The 30 GDN layers also keep a fixed-size recurrent state per sequence. It’s split differently in the two layouts, but it’s similar in total.)</p><h3>Step 5: Following one decode step</h3><p>Suppose 64 requests are running, 16 in each DP group. Each request produces one token per step:</p><pre>each DP group: its own batch of B_g tokens (1 per running request)     B_g = 16, B_total = 64<br>   │<br>   ▼ attention / GDN in the TP pair → all-reduce (2 GPUs)<br>   │       each pair works only on its own 16 requests&#39; KV cache<br>   │<br>   ▼ router: top-8 per token<br>   │       16 tokens x 8 = 128 (token, expert) pairs per group<br>   │<br>   ▼ all-to-all DISPATCH across all 8 GPUs  (tokens from all 4 DP groups mix here)<br>   │       each GPU sends ≈ 8 tokens x 5.3 GPUs x 4 KB ≈ 170 KB  → tiny, latency-bound<br>   │<br>   ▼ each GPU: grouped GEMM on its 32 experts<br>   │       rows per expert ≈ (Σ B_g) · 8 / 256 = B_total / 32 = 2<br>   │       experts actually hit per step ≈ 256 · (1 - (1 - 1/32)^64) ≈ 222 of 256<br>   │<br>   ▼ all-to-all COMBINE → tokens return to their DP group<br>   │<br>   ▼ weighted sum of 8 expert outputs + residual → next layer<br>         (x 40 layers → 80 all-to-alls per generated token)</pre><p>What decode tells us:</p><ul><li><strong>Two rows per expert is tiny.</strong> Each GPU reads about 28 of its 32 experts’ weights from memory just to do two rows of math. Decode MoE is <strong>memory-bandwidth bound</strong>, so time ≈ bytes of expert weights read ÷ HBM bandwidth.</li><li><strong>The expert weight bytes per GPU are the same as with TP = 8.</strong> EP doesn’t reduce them.</li><li><strong>The real win is the batch.</strong> The 4x KV saving lets B_total grow. Rows per expert grow linearly with it (B_total / 32), and the same weight read gets spread over more tokens. That is where throughput comes from.</li><li><strong>All-to-all at decode is about latency, not bandwidth.</strong> It’s 170 KB per layer, but 80 times per token. Fused, low-latency dispatch kernels and CUDA graphs matter more here than link bandwidth.</li></ul><h3>Step 6: Following one prefill step</h3><p>Now suppose each DP group is prefilling 4 prompts of 1,024 tokens, which is 4,096 tokens per group and 16,384 in total:</p><pre>each DP group: 4 prompts x 1,024 tokens = 4,096 tokens<br>   │<br>   ▼ attention / GDN in the TP pair → all-reduce (2 GPUs)<br>   │       4,096 tokens x 4 KB = 16 MB per all-reduce → bandwidth matters now<br>   │<br>   ▼ router: top-8 per token<br>   │<br>   ▼ all-to-all DISPATCH across all 8 GPUs<br>   │       each GPU sends ≈ 2,048 tokens x 5.3 GPUs x 4 KB ≈ 42 MB per layer<br>   │<br>   ▼ each GPU: grouped GEMM on its 32 experts<br>   │       rows per expert ≈ 16,384 x 8 / 256 = 512<br>   │       gate_up: [512 x 2048] · [2048 x 1024]   ← a real, compute-bound GEMM<br>   │       down:    [512 x 512]  · [512 x 2048]<br>   │<br>   ▼ all-to-all COMBINE → same ≈ 42 MB back</pre><p>What prefill tells us:</p><ul><li><strong>512 rows per expert means the MoE is compute bound.</strong> Now the full, unsliced expert shapes from EP pay off: one 2048 x 1024 GEMM per expert instead of eight 2048 x 128 slices.</li><li><strong>The all-to-all is now about bandwidth.</strong> About 42 MB each way per layer. Overlapping it with compute (for example, splitting the batch into two halves and ping-ponging) is the main optimization.</li><li><strong>Load balance shows up.</strong> With 512 rows on average, a popular expert might get 1,500. The GPU that owns it sets the pace for everyone.</li></ul><h3>Step 7: Side by side</h3><pre>                                TP = 8                      DP-attn (4x2) + EP = 8<br>----------------------------    -------------------------   ---------------------------<br>attention split                 2 q heads, KV copied 4x     8 q heads, 1 KV head, no copy<br>KV cache per token (total)      80 KB                       20 KB<br>experts per GPU                 256 slices (1/8 each)       32 whole experts<br>expert GEMM shape (gate_up)     2048 x 128                  2048 x 1024<br>expert weight bytes per GPU     same                        same<br>rows per expert (same batch)    same                        same<br>MoE collective                  all-reduce of all tokens    2 x all-to-all, routed only<br>load balance                    perfect                     router-dependent<br>weights per GPU                 ≈ 8.7 GB                    ≈ 10.8 GB<br>main win                        simplicity, balance         4x KV room → bigger batches,<br>                                                            better expert GEMM shapes</pre><h3>Step 8: When one server isn’t enough</h3><p>If you need more throughput, there are two directions:</p><ul><li><strong>More replicas (DP across servers).</strong> Simple, and there’s no cross-server traffic at all.</li><li><strong>EP = 16 across 2 servers.</strong> 16 experts per GPU frees memory for even bigger batches, but the all-to-all now crosses the network. It’s worth it only with fast interconnects and optimized dispatch kernels.</li></ul><p>PP only enters the picture if a single replica can’t fit in one server, which isn’t the case for this model.</p><h3>Key takeaways</h3><ol><li><strong>Each strategy splits something different:</strong> batch (DP), matrices (TP), layers (PP), experts (EP).</li><li><strong>Communication frequency decides placement.</strong> TP and EP run every layer, so keep them in-server. DP and PP run rarely, so let them cross servers.</li><li><strong>TP is capped by the number of KV heads.</strong> Past that point you copy the KV cache. Use DP-attention instead.</li><li><strong>EP reuses the TP x DP GPUs.</strong> It isn’t an extra dimension: TP x DP = ETP x EP x EDP.</li><li><strong>EP doesn’t reduce the expert bytes each GPU reads.</strong> It changes the GEMM shapes and the communication pattern, and combined with DP-attention it frees memory for bigger batches. The bigger batch is the real throughput win.</li><li><strong>Decode MoE is memory bound and its all-to-all is latency bound. Prefill MoE is compute bound and its all-to-all is bandwidth bound.</strong> Optimize them differently.</li></ol><p>What I originally saw in the trace (every GPU running thin slices of all 256 experts) wasn’t wrong. It was simply TP = 8 applied everywhere. Once you see the four strategies as four different ways of splitting the work, the better layout for this model is clear.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cc4e611da72" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/dp-tp-pp-and-ep-how-llm-parallelism-actually-fits-together-2cc4e611da72">DP, TP, PP and EP: How LLM Parallelism Actually Fits Together</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unified Radix Cache Explained: One Tree for Full Attention, Sliding Window and Mamba]]></title>
            <link>https://pub.towardsai.net/unified-radix-cache-explained-one-tree-for-full-attention-sliding-window-and-mamba-be2035121ddc?source=rss-4354164acdff------2</link>
            <guid isPermaLink="false">https://medium.com/p/be2035121ddc</guid>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[sglang]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Aadishagrawal]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 17:26:45 GMT</pubDate>
            <atom:updated>2026-11-18T03:06:22.610Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A walkthrough of how SGLang caches prefixes for hybrid LLMs.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HlGugzvDK5esIO0SFe9Jg.png" /></figure><p>If you serve LLMs, you already know the cheapest token is the one you never recompute. Prefix caching makes that possible: when two requests start with the same text, the second one reuses the work done for the first.</p><p>That trick is easy for classic transformers. It gets tricky for <strong>hybrid models</strong> that mix different kinds of layers. SGLang’s answer is the <strong>Unified Radix Cache (URC)</strong>, introduced by the LMSYS team in August 2026. This post explains the problem, the design, and how it behaves in practice, using small examples you can follow by hand.</p><p><strong>What you’ll learn</strong></p><ol><li>Why one cache rule no longer fits all models</li><li>What full attention, sliding window attention (SWA) and Mamba each need to remember</li><li>How URC uses one tree with pluggable components</li><li>How HiCache spreads that cache across GPU, CPU and external storage</li><li>How a prefix is accepted or rejected, with examples</li><li>How session-aware eviction beats plain LRU</li><li>An end-to-end example that ties everything together</li></ol><blockquote><strong><em>A note on the numbers.</em></strong><em> Token counts in the examples are small round numbers I chose for readability. The rules and the benchmark results come from the </em><a href="https://www.lmsys.org/blog/2026-08-11-unified-radix-cache"><em>LMSYS announcement</em></a><em> and the SGLang docs. I haven’t verified every internal detail against the source code, and I flag the spots where I’m inferring.</em></blockquote><h3>1. Background: why a unified tree is needed</h3><h3>Prefix caching in one minute</h3><p>When an LLM processes a prompt, it computes a <strong>KV cache</strong>: key/value tensors for every token that later tokens attend to. If a new request begins with the same tokens as an earlier one (a system prompt, a chat history, a code repository), those tensors don’t need to be recomputed.</p><p>SGLang tracks which prefixes are cached with a <strong>radix tree</strong> (a compressed prefix tree). Each edge is labeled with a run of tokens. To serve a new request, SGLang walks the tree, finds the longest cached prefix, and only prefills the rest.</p><pre>              root<br>               │<br>        [You are a helpful assistant ...]        &lt;- shared system prompt<br>          ┌────┴─────┐<br>   [User: hi ...]  [User: fix my bug ...]        &lt;- two different conversations</pre><p>For a plain full-attention transformer this works perfectly, because cached KV for a prefix stays valid no matter what is appended later.</p><h3>Where it breaks: hybrid models</h3><p>Many recent models mix layer types in one network. A request now carries several kinds of cached state, and each has its own notion of “reusable”:</p><ul><li>Full attention KV is reusable across the <strong>whole</strong> matched prefix.</li><li>Sliding window attention KV only covers the <strong>trailing window</strong>.</li><li>A recurrent (Mamba-style) state is valid only at an <strong>exact checkpoint</strong>.</li></ul><p>All three share the same token prefix, but <strong>not the same reusable boundary</strong>. If you force one boundary on all of them, you either throw away valid reuse or, worse, allow invalid reuse and get wrong outputs.</p><h3>The old approach: a class for every combination</h3><p>Early on, SGLang handled this with separate cache classes, such as RadixCache, MambaRadixCache and SWARadixCache. Each re-implemented matching, insertion, locking and eviction. Add an orthogonal feature like HiCache (hierarchical caching) and the number of combinations multiplies.</p><pre>               Full only     + SWA       + Mamba      + all three<br>  no HiCache   Cache A      Cache B      Cache C      Cache D<br>  + HiCache    Cache E      Cache F      Cache G      Cache H     &lt;- the &quot;class matrix&quot;</pre><p>URC replaces this matrix with <strong>one tree</strong> and <strong>pluggable components</strong>. A new model family picks a combination instead of requiring a new tree.</p><h3>2. Three kinds of memory, in plain words</h3><p>Before looking at the design, here is what each layer type actually needs to remember, and why.</p><h3>Full attention: remember every past token</h3><p>In full attention, each new token looks back at <strong>all</strong> earlier tokens. So the cache holds a key/value pair for every token so far, and it grows linearly with context length.</p><p>Because attention is causal (a token only depends on tokens before it), the KV for tokens 1..N stays correct no matter what comes next. That is why any prefix length is a valid reuse point.</p><h3>Sliding window attention (SWA): remember only the recent tail</h3><p>In sliding window attention, each token only looks at the last <strong>W</strong> tokens. Older keys and values will never be read again by these layers, so only a <strong>trailing window</strong> is kept.</p><p>To resume from position <em>p</em>, you need the KV for tokens <em>p-W+1 … p</em>, and they must be <strong>contiguous</strong>. Memory is bounded by W instead of growing with the sequence.</p><h3>Mamba (recurrent state): remember one checkpoint</h3><p>Recurrent layers don’t store per-token keys and values. They fold the entire history into one fixed-size <strong>state</strong>, updated token by token. That makes memory constant regardless of length.</p><p>The catch: the state at position 550 is a blend of all 550 tokens. You can’t “subtract” tokens to get the state at position 300. So a Mamba state is only reusable at the <strong>exact position where it was saved</strong>. That position is called a checkpoint.</p><h3>Side by side</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqiQNulImjjHhZQ0i-4NoQ.png" /></figure><p>Hybrid models combine these. According to the LMSYS post, DeepSeek-V4 uses full attention plus SWA, Kimi-K3 uses full attention plus a recurrent (KDA) state, and Inkling uses all three.</p><h3>3. What is the Unified Radix Cache?</h3><p>URC is built on one separation of concerns:</p><ul><li><strong>Prefix identity</strong> (which tokens is this?) lives in <strong>one</strong> shared radix tree.</li><li><strong>Reuse validity</strong> (is the cached data usable here?) lives in <strong>components</strong> that attach to tree nodes.</li></ul><p>Here is the picture. One tree, three kinds of attached data:</p><p>one token-keyed radix tree (the shared topology)</p><pre>    root ──► n1 ──► n2 ──► n3 ──► n4<br>              │      │      │      │<br>   FULL       ●      ●      ●      ●     KV for every token on the path<br>   SWA        ○      ○      ○      ●     trailing window only (○ = tombstone)<br>   MAMBA      ○      ○      ○      ●     checkpoint only where saved (○ = none)</pre><pre>   ● = data present      ○ = empty slot, node still in the tree</pre><p>Each tree node stores <strong>references</strong> (indices) into separate memory pools: one for full-attention KV, one for SWA KV, one for Mamba state. The tensors live on the GPU in those pools, and the node only records where they are. This is my reading of the design; the older MambaRadixCache documented the same pattern of independent pools with independent eviction.</p><h3>Three layers of code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2K4MiSK3srTQ0ZdLJ00ShQ.png" /></figure><p>URC doesn’t make KV smaller. Full KV is still stored for every cached token. The win is architectural: one implementation of the tree plus small components, so new combinations don’t need new trees. Benefits like tiered storage and smarter eviction come from what that unified design makes possible.</p><h3>4. The components, one by one</h3><h3>FULL: path reuse</h3><p>The FULL component is always present. It keeps KV for every token in the matched prefix and protects the whole <strong>path</strong> of ancestor nodes while a request uses it.</p><h3>SWA: window reuse</h3><p>SWA needs a <strong>contiguous trailing window</strong> before the boundary. Older SWA slots can be freed. Their nodes stay in the tree as <strong>tombstones</strong>: empty slots that keep the topology intact.</p><h3>MAMBA: checkpoint reuse</h3><p>MAMBA needs <strong>one recurrent checkpoint</strong> at the boundary. Because a request will keep updating the state as it runs, URC <strong>copies</strong> the shared checkpoint into a private slot for that request before use. Otherwise one request would corrupt the state another one depends on.</p><h3>The component contract (hooks)</h3><p>The tree core stays generic because every component implements the same hooks across the node lifecycle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhUQzHv68deoD_9ZUbsvBw.png" /></figure><h3>Tombstones and eviction cascade</h3><p>Removing one component’s data doesn’t necessarily remove the node. Other components may still use the node as an anchor.</p><p>The SGLang docs describe how eviction cascades between components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGJ6Z1nZ_I3zmkUJvWPuVQ.png" /></figure><p>In short, Mamba state is the cheapest thing to lose and FULL is the most structural.</p><h3>Anchors and sidecars</h3><p>Not every memory pool deserves to be a component. URC distinguishes:</p><ul><li><strong>Components (anchors)</strong> define reuse rules or supply the page indices that other pools follow.</li><li><strong>Sidecars</strong> store extra payloads but reuse the indices of a declared source pool. They move with their source and never vote on boundaries.</li></ul><p>DeepSeek-V4 is the worked example in the announcement. FULL and SWA are components, and they use independent index spaces (the allocator maps tail slots in the FULL pool onto slots in the SWA pool). Compressed KV pools, indexer buffers and compressor states are sidecars, with three following FULL and two following SWA.</p><pre>   components (vote on reuse)         sidecars (just follow)<br>   ┌───────┐                          ┌──────────────────────┐<br>   │ FULL  │◄─────────────────────────│ 3 auxiliary pools    │<br>   └───────┘                          └──────────────────────┘<br>   ┌───────┐                          ┌──────────────────────┐<br>   │ SWA   │◄─────────────────────────│ 2 auxiliary pools    │<br>   └───────┘                          └──────────────────────┘</pre><h3>5. HiCache: the same tree across memory tiers</h3><p>GPU memory is fast but small. <strong>HiCache</strong> adds slower, larger tiers so reusable prefixes survive longer:</p><pre>   ┌────────────────────────────┐<br>   │ L1  GPU memory             │   fastest, smallest<br>   └─────────────┬──────────────┘<br>                 │  demote ▼      ▲ promote<br>   ┌─────────────┴──────────────┐<br>   │ L2  Host (CPU) memory      │   slower, larger<br>   └─────────────┬──────────────┘<br>                 │  demote ▼      ▲ promote<br>   ┌─────────────┴──────────────┐<br>   │ L3  External store         │   slowest, largest (e.g. Mooncake)<br>   └────────────────────────────┘</pre><p>Think of a long-running chat. Early turns stop fitting in GPU memory, but the user may come back to them. Without lower tiers, those prefixes would be recomputed.</p><h3>Why URC makes this clean</h3><p>Components decide <strong>what</strong> can be reused. HiCache decides <strong>where</strong> the payload lives. Since URC carries the same component identity across all three tiers, moving data down or up never changes its prefix identity or reuse rule. Components describe the transfers they need, and a controller (HybridCacheController) performs the actual I/O.</p><h3>Benchmark results</h3><p>The LMSYS team compared three setups on multi-turn chat workloads: GPU only, GPU plus host memory, and GPU plus host plus an external L3 store (Mooncake).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9R7Fw8Hch-XU3jClZmDavg.png" /></figure><p>Two reading tips. First, “effective input tokens per second” credits tokens served from cache, so it measures serving progress under reuse rather than raw compute. Second, the two models used different hardware and workloads, so compare tiers <strong>within</strong> a model, not across models.</p><h3>6. How a prefix is accepted: the voting walk</h3><p>This is the core algorithm. When a request arrives:</p><ol><li>Walk the <strong>FULL path</strong> down the tree, following the request’s tokens.</li><li>Treat <strong>every visited node as a candidate boundary</strong>.</li><li>Each active component builds a <strong>validator</strong>.</li><li>A candidate is accepted only if <strong>all validators agree</strong>.</li><li>A rejection does <strong>not</strong> stop the walk, because a deeper node might still pass.</li><li>Keep the <strong>deepest accepted</strong> node as the reuse point.</li></ol><p>In pseudocode (my paraphrase, not the real source):</p><pre>def match_prefix(tokens):<br>    validators = [c.create_match_validator() for c in components]<br>    best = root<br>    for node in walk_full_path(tokens):      # every node is a candidate<br>        if all(v.accepts(node) for v in validators):<br>            best = node                      # deepest safe boundary so far<br>    result = MatchResult(best)<br>    for c in components:<br>        c.finalize(result)                   # e.g. copy a Mamba checkpoint<br>    return result                            # reuse len(best) tokens</pre><p>A node’s checkpoint or window is judged <strong>only against that node’s own boundary</strong>. A tombstone on n1 doesn’t hurt a candidate at n4.</p><h3>Example A: the standard case</h3><p>Each node holds 128 tokens, and the SWA window is 128 tokens. The cumulative length is shown in brackets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKzJ9ayFlU19eVCHPnFxDQ.png" /></figure><p>The walk reaches n4, but the deepest node every component accepts is <strong>n2</strong>. The request reuses 256 tokens and prefills the remaining ones. This matches the announcement’s own figure, where traversal depth and reusable depth are different things.</p><h3>Example B: a later node rescues the match</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWm_d8wCSKzH0ikUq-snUg.png" /></figure><p>Because the walk keeps going, n4 is accepted and <strong>all 512 tokens are reused</strong>. This is common in practice: after a request finishes, typically only the deepest node has a fresh SWA window and a Mamba checkpoint, while shallower nodes keep just their full KV.</p><h3>Example C: the veto</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8XsEdj0Mwt-eTWQ49LL-g.png" /></figure><p>n4 has a Mamba checkpoint, but there’s no valid SWA window. The best accepted boundary is the root, so <strong>zero</strong> tokens are reused even though all the full KV is cached. A boundary must satisfy every component.</p><h3>Example D: a window that straddles two nodes</h3><p>If a node holds fewer tokens than the window W, the window spans the node and part of its parent. If the parent’s SWA slots are tombstoned, the window isn’t complete. I expect the validator to reject in that case, since the announcement requires a contiguous trailing window, but I haven’t confirmed how the code tracks this.</p><h3>What happens after acceptance</h3><ul><li>The FULL path up to the boundary is <strong>locked</strong> so it can’t be evicted mid-request.</li><li>SWA locks the <strong>trailing window</strong>, and Mamba locks its <strong>single checkpoint</strong>.</li><li>The Mamba checkpoint is <strong>copied</strong> into a private slot before the request mutates it.</li></ul><h3>7. Session-aware eviction vs plain LRU</h3><h3>The problem with LRU</h3><p>LRU evicts whatever was used least recently. But recency isn’t the same as likelihood of reuse. Consider a coding agent: it sends a request, then spends 30 seconds running tools. Its cached prefix looks “cold”, yet the next request is about to need it. Under memory pressure, LRU can evict exactly that prefix while keeping unrelated one-off entries that were touched more recently.</p><h3>How session awareness works</h3><ol><li>The application attaches a stable session_id to <strong>every request</strong> in a session. The ID only labels cache references; each request must still contain its full prompt.</li><li>When a request finishes, URC registers its reusable region under that session: FULL records its prefix path, SWA its trailing window, and MAMBA its reusable frontier.</li><li>Under memory pressure, <strong>unreferenced entries are evicted first</strong>.</li><li>Referenced entries are only <strong>soft-protected</strong>, not pinned. If evicting unreferenced entries isn’t enough, referenced ones can still go.</li><li>When the session ends, /close_session removes the references. The data is <strong>not</strong> deleted immediately; it just returns to the normal eviction order.</li></ol><p>Per the docs, FULL orders candidates by whether they are referenced, then by session reference count, then by base eviction priority. SWA and MAMBA do two passes: unreferenced first, then referenced if more room is needed. The policy currently covers GPU (L1) and host (L2) tiers, not external L3.</p><pre>Memory is full. Who gets evicted?<br><br> Plain LRU                           Session-aware<br> ─────────                           ─────────────<br> oldest-touched first                unreferenced first, then referenced<br> [A idle 30s]  ← evicted!            [one-off C]    ← evicted first<br> [B active]                          [A idle 30s]   ← kept (referenced)<br> [one-off C]                         [B active]     ← kept (referenced)</pre><h3>Measured benefit</h3><p>On SWE-bench agent workloads, the LMSYS team reported 2.9% to 16.6% lower time-to-first-token (TTFT) than ordinary HiRadixCache with LRU. Device cache hit ratio improved too, for example about 5% to 34% for Qwen3.5–397B at batch size 32, and about 42% to 51% for DeepSeek-V4-Pro at batch size 128.</p><p>An important caveat from the authors: the comparison changes both the cache implementation and the eviction policy, so it isn’t an isolated test of session awareness alone.</p><h3>Turning it on</h3><pre>SGLANG_ENABLE_UNIFIED_RADIX_TREE=1 python3 -m sglang.launch_server ... --enable-session-radix-cache</pre><p>Then send the same session_id on every request in a session, and call /close_session when it ends, including on error and cancellation paths.</p><h3>8. An end-to-end example</h3><p>Let’s follow two agent sessions on a model with <strong>FULL + SWA + MAMBA</strong>. Assumptions for the example: the SWA window is <strong>100 tokens</strong>, one system prompt <strong>S</strong> is 300 tokens, and the GPU cache is small enough to fill up. Shallow SWA windows and Mamba checkpoints are freed after later turns to save memory, which is an assumption about typical behavior.</p><h3>Step 1: Session A, turn 1</h3><p>Request: S (300) + question A1 (200) = 500 tokens. The model generates 50 more.</p><pre>root ──► n1 [tokens 1–550]<br>          FULL ● KV for 550 tokens<br>          SWA  ● window = tokens 451–550<br>          MAMBA● checkpoint at 550</pre><p>Cache is cold, so all 500 prompt tokens are prefilled. Session A is registered on n1.</p><h3>Step 2: Session A, turn 2 (a hit)</h3><p>New prompt = previous 550 + 100 new tokens = 650.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RA4LPcXCB69GfX2xYSagGw.png" /></figure><p>n1 is accepted, so <strong>550 tokens are reused</strong> and only 100 are prefilled. The Mamba checkpoint is copied into a private slot first. After the turn (50 more generated), a child node is added:</p><pre>root ──► n1 [1–550] ──► n2 [551–700]<br>          FULL ●          FULL ●<br>          SWA  ○ (freed)  SWA  ● window = 601–700<br>          MAMBA○ (freed)  MAMBA● checkpoint at 700</pre><h3>Step 3: Session B, turn 1 (a split)</h3><p>Session B uses the same system prompt S but a different question B1 (150 tokens), for a prompt of 450. The walk goes into n1, matches the first 300 tokens (S), then diverges. n1 <strong>splits</strong> into [S: 1–300] and [301–550]:</p><pre>root ──► nS [1–300] ──► nA1 [301–550] ──► n2 [551–700]<br>                    └─► (B1 inserted after B finishes)</pre><p>Each component’s split hook decides where its data goes. FULL KV for the first 300 tokens moves to the parent nS. The SWA window and the Mamba checkpoint belonged to the end of the sequence, so they stay with the children. That leaves <strong>nS with FULL only</strong>.</p><p>Now the match for B at boundary nS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*768nwai_hJ7bdEVFOwkHJg.png" /></figure><p>Rejected, so B reuses nothing in this simplest case and prefills all 450 tokens. This is the honest cost of hybrid models: a shared prefix is only reusable where a window and a checkpoint were saved. Text matching alone isn’t enough.</p><h3>Step 4: Memory pressure (where session awareness matters)</h3><p>The GPU pool fills up. Entries in the cache:</p><ul><li>Session A’s path (referenced, idle while A’s agent runs a tool)</li><li>Session B’s path (referenced, active)</li><li>An old one-off request C from a user who never returned (unreferenced)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYatlOm5ksexmuzRs5gGyw.png" /></figure><p>Eviction also follows the cascade rules. Dropping a Mamba checkpoint frees only that checkpoint. Dropping an internal FULL node would also take its SWA and Mamba data with it, so those are the last things to go.</p><h3>Step 5: Session A, turn 3</h3><p>A’s tool call returns and it sends turn 3. Because its prefix survived, the walk accepts n2 (700 tokens), and almost the whole prompt is a cache hit. With LRU, that prefix might have been evicted and fully recomputed.</p><h3>Step 6: Close the session</h3><p>When A’s agent finishes, the app calls /close_session. The references are removed, but the KV stays. It returns to normal eviction order and can still serve a future request with the same prefix. If memory is tight, it becomes a natural eviction candidate.</p><h3>The whole story in one table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJgxSHZBCUYNY5yfQzyOfg.png" /></figure><h3>9. Recap and what’s next</h3><p><strong>The key ideas</strong></p><ul><li>Hybrid models have <strong>no single reusable boundary</strong>. Full attention, SWA and Mamba each need different things from the same prefix.</li><li>URC keeps <strong>one token-keyed tree</strong> for identity and moves reuse rules into <strong>components</strong> (FULL, SWA, MAMBA) with a shared hook contract.</li><li>A prefix boundary is accepted only when <strong>every component’s validator agrees</strong>. The walk continues past rejections and keeps the deepest safe node.</li><li><strong>HiCache</strong> is native: the same identity spans GPU, host and external storage, which keeps hit rates high on long multi-turn workloads.</li><li><strong>Session-aware eviction</strong> uses soft references so active sessions’ entries are evicted last, without pinning memory.</li><li>URC mainly unifies the design. It doesn’t reduce per-token KV storage; the gains come from tiering, smarter eviction, and easier support for new model families.</li></ul><p><strong>On the roadmap</strong>, according to the announcement: an experimental Rust tree core to cut scheduler overhead (L1-only for now, with up to 42% lower TTFT on one SWA benchmark), direct GPU-to-L3 connections, and cache identity shared across routers and prefill/decode workers for agentic workloads.</p><h3>Sources and further reading</h3><ul><li>LMSYS, <a href="https://www.lmsys.org/blog/2026-08-11-unified-radix-cache">Unified Radix Cache: One Tree for Hybrid Model Prefix Caching</a> (August 2026), the primary source for the design, benchmarks and component hooks</li><li>SGLang docs, <a href="https://docs.sglang.io/docs/advanced_features/session_radix_cache">Session-Aware Radix Cache</a></li><li>LMSYS, <a href="https://www.lmsys.org/blog/2025-09-10-sglang-hicache">SGLang HiCache</a>, for background on hierarchical caching</li><li>Unified Radix Cache pull request: <a href="https://github.com/sgl-project/sglang/pull/21206">sgl-project/sglang#21206</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be2035121ddc" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/unified-radix-cache-explained-one-tree-for-full-attention-sliding-window-and-mamba-be2035121ddc">Unified Radix Cache Explained: One Tree for Full Attention, Sliding Window and Mamba</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Physical AI: A Deep Dive into VLA Architectures, Action Chunking, and Split Inference]]></title>
            <link>https://pub.towardsai.net/demystifying-physical-ai-a-deep-dive-into-vla-architectures-action-chunking-and-split-inference-6dad217b250a?source=rss-4354164acdff------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dad217b250a</guid>
            <category><![CDATA[physical-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[visual-language-model]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Aadishagrawal]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 16:36:08 GMT</pubDate>
            <atom:updated>2026-11-21T05:47:35.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCxgQotv0WPMk05ZTDnp7Q.png" /></figure><p>Imagine taking a state-of-the-art 2-billion-parameter Vision-Language Model (VLM) and forcing it to control a multi-joint robotic arm in real time. If you query the language backbone for every single motor adjustment, your robot stutters along at a fragile, high-latency 2 Hz — likely knocking over a coffee cup long before it reaches its target.</p><p>The fundamental challenge of <strong>Physical AI</strong> isn’t just multimodal understanding; it’s translating high-level semantic reasoning into high-frequency, continuous physical control.</p><pre>TRADITIONAL VLM                              PHYSICAL AI (VLA)<br>┌───────────────────────────┐                ┌───────────────────────────┐<br>│ High-Level Reasoning      │                │ High-Level Reasoning      │<br>│ Text / Image → Text Tokens│                │ Text / Image → Embeddings │<br>└─────────────┬─────────────┘                └─────────────┬─────────────┘<br>              │ Low Frequency                              │ Bottleneck Bridge<br>              ▼                                            ▼<br>┌───────────────────────────┐                ┌───────────────────────────┐<br>│ Discrete Text Output      │                │ Continuous Action Expert  │<br>│ (Too slow for control)    │                │ Flow Matching / CVAE      │<br>└───────────────────────────┘                └─────────────┬─────────────┘<br>                                                           │ High Frequency (50Hz+)<br>                                                           ▼<br>                                             ┌───────────────────────────┐<br>                                             │ Joint Angles / Torques    │<br>                                             │ Real-Time Control Loops   │<br>                                             └───────────────────────────┘</pre><p>To bridge this gap, AI researchers and robotics engineers are moving beyond standard token generation toward specialized <strong>Vision-Language-Action (VLA)</strong> architectures. From continuous flow-matching action experts (<em>π</em>0​) and CVAE latent style sampling (ACT) to non-generative, latent-space predictive world models (VLA-JEPA), the physical AI stack is evolving at breakneck speed.</p><p>In this deep dive, we will unroll the architectural blueprints behind modern VLAs, deconstruct how multi-view vision encoders, language backbones, and continuous action heads interface, and explore how <strong>split inference</strong> enables multi-billion-parameter foundation models to run off-board while maintaining sub-20ms closed-loop execution on real hardware.</p><h3>1. Physical Intelligence π0​ / π0.5​: The Modular VLA Pipeline</h3><p>Physical Intelligence’s <em>π</em>0​ and <em>π</em>0.5​ represent a groundbreaking architectural approach: adapting pre-trained Vision-Language Models into real-time, highly dexterous controllers without losing their pre-trained semantic grounding.</p><h3>High-Level Architecture Diagram</h3><pre>┌────────────────────────┐      ┌────────────────────────┐<br>│ Multi-View Images      │      │ Text Prompt &amp;          │<br>│ (RGB Cameras)          │      │ Proprioception         │<br>└───────────┬────────────┘      └───────────┬────────────┘<br>            │                               │<br>            ▼                               │<br>┌────────────────────────┐                  │<br>│ SigLIP Encoder (~400M) │                  │<br>└───────────┬────────────┘                  │<br>            │ Image Embeddings              │ Text Tokens / State<br>            └───────────────┬───────────────┘<br>                            ▼<br>           ┌─────────────────────────────────┐<br>           │Concatenation &amp; Linear Projection│<br>           └────────────────┬────────────────┘<br>                            ▼<br>           ┌────────────────────────────────┐<br>           │ Gemma 2B Transformer Backbone  │<br>           └────────────────┬───────────────┘<br>                            │ Key-Value (KV) Cache<br>                            ▼<br>           ┌────────────────────────────────┐<br>           │ Action Expert (~300M)          │<br>           │ (Flow-Matching Decoder)        │<br>           └────────────────┬───────────────┘<br>                            ▼<br>                   Action Chunk Sequences</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Kh_KmWFPjrnBTcFEDHSrQ.png" /></figure><h3>Module Breakdown</h3><ol><li><strong>SigLIP Vision Encoder (~400M parameters):</strong><br>Multi-view camera inputs pass through a SigLIP (Sigmoid Loss for Language-Image Pre-Training) vision backbone. Unlike traditional CLIP variants (which rely on softmax normalization across a global batch), SigLIP utilizes pairwise sigmoid loss. This optimizes memory during inference and preserves granular fine-grained visual details — crucial for estimating object distances, clutter, spatial orientations, and fine grasp affordances.</li><li><strong>Gemma 2B Language Backbone (~2.6B parameters):</strong><br>Visual patch embeddings from SigLIP, tokenized text instructions (e.g., <em>“Fold the laundry smoothly”</em>), and low-dimensional robot proprioceptive states (joint positions, arm velocities, gripper status) are projected into a shared embedding space. They are concatenated along the sequence dimension and passed through a Gemma-2B decoder-only Transformer. Gemma acts as the high-level cognitive engine, maintaining spatial commonsense, cross-modal attention, and goal alignment.</li><li><strong>Action Expert (~300M parameters):</strong><br>Standard language models output discrete tokens, but hardware motor drives require continuous, high-frequency physical state vectors (e.g., 50 Hz joint positions or torques). The output Key-Value (KV) states from Gemma 2B are fed directly into a specialized, non-causal <strong>Action Expert</strong>. Utilizing <strong>Flow-Matching</strong> (a continuous-time formulation of diffusion generative modeling), this expert rapidly computes continuous trajectory distributions.</li></ol><h3>Three Operational Modes: Training, Execution, and Action Chunking</h3><pre>Training Mode                     Inference / Action Mode           Action Chunking<br> ┌───────────────────────┐        ┌───────────────────────┐     ┌───────────────────────┐<br> │ Full Backprop Through │        │  KV-Cache Frozen      │     │  Predict N Steps Ahead│<br> │ SigLIP + Gemma 2B +   │        │  Fast Re-sampling     │     │  [a_t, a_t+1, ... ]   │<br> │ Action Expert         │        │  Action Expert at 50Hz│     │  smoothly overlapped  │<br> └───────────────────────┘        └───────────────────────┘     └───────────────────────┘</pre><p><strong>1. Training Mode:</strong><br>The system is trained end-to-end on massive, heterogeneous datasets comprising human teleoperation and multi-robot interaction logs. Trajectory paths are supervised via continuous flow-matching loss functions, aligning visual-semantic representations with physical actuation dynamics.</p><p><strong>2. Execution / Action Mode (Queue-Based Inference):</strong><br>Evaluating a full 2-billion+ parameter VLM at 50 Hz is computationally unfeasible on edge hardware. In action mode, the Gemma 2B backbone evaluates inputs at a lower frequency (e.g., 2–5 Hz), populating and updating a frozen Key-Value (KV) cache. The lightweight 300M Action Expert queries this frozen KV-cache at 50 Hz, sampling control vectors in milliseconds.</p><p><strong>3. Action Chunking:</strong><br>Instead of predicting a single action <em>at</em>​, the Action Expert outputs an entire <em>action chunk</em> trajectory horizon <em>A</em>=[<em>at</em>​,<em>at</em>+1​,…,<em>at</em>+<em>k</em>​] (e.g., 30 to 50 steps into the future). The robot’s low-level execution layer consumes these vector sequences from a fast local queue.</p><h3>2. ACT (Action Chunking with Transformers) Architecture</h3><p>Pioneered by Tony Z. Zhao et al. (Stanford ALOHA), the <strong>Action Chunking with Transformer (ACT)</strong> model directly addresses two core issues in imitation learning: compounding error during sequential execution and non-Markovian human teleoperation data.</p><h3>Structural Flowchart: Training vs. Inference</h3><pre>TRAINING (CVAE Pipeline)<br>                     <br> ┌──────────────────────┐      ┌──────────────────────┐<br> │ Current Observation  │      │ Ground Truth Action  │<br> │ (Images + Joint Pos) │      │ Sequence (a_{t:t+k}) │<br> └──────────┬───────────┘      └──────────┬───────────┘<br>            │                             │<br>            ▼                             ▼<br>┌──────────────────────────────────────────────────────┐<br>│  CVAE Encoder (Transformer / ResNet Backbone)        │<br>└──────────────────────────┬───────────────────────────┘<br>                           │<br>                           ▼  Latent Variable z ~ N(μ, σ)<br>┌──────────────────────────┴───────────────────────────┐<br>│  CVAE Decoder (Transformer Decoder)                  │<br>└──────────────────────────┬───────────────────────────┘<br>                           │<br>                           ▼<br>              Predicted Action Chunk (a_{t:t+k})</pre><pre>INFERENCE MODE<br>                     <br>┌──────────────────────┐       ┌──────────────────────┐<br>│ Current Observation  │       │  Latent Vector z     │<br>│ (Images + Joint Pos) │       │  (Set to Mean z = 0) │<br>└──────────┬───────────┘       └──────────┬───────────┘<br>           │                              │<br>           └──────────────┬───────────────┘<br>                          ▼<br>┌──────────────────────────────────────────────────────┐<br>│  CVAE Decoder (Transformer Decoder)                  │<br>└──────────────────────────┬───────────────────────────┘<br>                           │<br>                           ▼<br>              Predicted Action Chunk (a_{t:t+k})</pre><h3>Core Components</h3><ol><li><strong>Conditional Variational Autoencoder (CVAE):</strong><br>Human teleoperation data contains multimodality — a human operator might wipe a surface by moving left first or right first. Standard MSE loss averages these multi-modal distributions, leading to disastrous middle-path collisions. ACT uses a CVAE to condition predictions on a latent style variable <em>z</em>, capturing execution variations.</li><li><strong>Transformer Encoder &amp; Decoder:</strong></li></ol><ul><li><strong>CVAE Encoder:</strong> Operates during training only. It processes current observations alongside future ground-truth action targets <em>At</em>:<em>t</em>+<em>k</em>​ to compress trajectory style into <em>z</em>∼N(<em>μ</em>,<em>σ</em>2).</li><li><strong>Transformer Decoder:</strong> Combines visual features (from ResNet/ViT backbones), joint position states, and the style variable <em>z</em> to output an entire trajectory chunk in a single forward pass.</li></ul><p><strong>3. Temporal Ensemble Smoothing:</strong><br>To prevent jerky movements when transitioning between action chunks, ACT re-computes overlapping predictions at every timestep <em>t</em>. Overlapping action predictions for the same future instant are combined using an exponential weighting scheme:</p><p><em>at</em>​=<em>i</em>=1∑<em>K</em>​<em>wi</em>​⋅<em>at</em>(<em>i</em>)​</p><p>This temporal ensembling smooths out sudden trajectory shifts, enabling precise multi-joint manipulation.</p><h3>3. VLA-JEPA: Predictive World Models in Latent Space</h3><p>Traditional VLA models map pixels straight to actions via supervised imitation. However, pixel space contains significant task-irrelevant noise (shadows, background movement, lighting changes). The <strong>Joint-Embedding Predictive Architecture VLA (VLA-JEPA)</strong> avoids pixel generation altogether, shifting training into <strong>latent world dynamics prediction</strong>.</p><h3>Training vs. Inference Asymmetry</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGa-6AQDua9r8M0IHX38eg.png" /></figure><pre>TRAINING ARCHITECTURE (JEPA World Model)<br> <br>Target Path:       ┌────────────────────┐    ┌─────────────────┐<br>(Future Frame)     │Future Image (x_t+k)│───&gt;│ Target Encoder  │──┐<br>                   └────────────────────┘    └─────────────────┘  │<br>                                                                  ▼<br>                                                   Target Latent State (s_t+k)<br>                                                                  │<br> Context Path:     ┌────────────────────┐    ┌─────────────────┐  │  L_2 / Cosine Loss<br> (Current Frame)   │ Current Image (x_t)│───&gt;│ Context Encoder │  │  (No Pixel Decoding)<br>                   └────────────────────┘    └────────┬────────┘  │<br>                                                      │           │<br>                                                      ▼           │<br>                   ┌────────────────────┐    ┌─────────────────┐  │<br> Proposed Action:  │ Candidate Action   │───&gt;│ World Predictor │──┴─&gt; Match Target!<br>                   │ Command (a_t)      │    │ Model (Transformer)<br>                   └────────────────────┘    └─────────────────┘</pre><pre>INFERENCE ARCHITECTURE (Policy Execution)<br>   <br>                   ┌───────────────────────┐<br>                   │ Current Image (x_t)   │<br>                   └───────────┬───────────┘<br>                               │<br>                               ▼<br>                   ┌───────────────────────┐<br>                   │ Context Encoder       │<br>                   └───────────┬───────────┘<br>                               │<br>                               ▼ Latent State (s_t)<br>                   ┌───────────────────────┐<br>                   │ Action Head / Policy  │<br>                   └───────────┬───────────┘<br>                               │<br>                               ▼<br>                    Action Command Sequence (a_{t:t+k})</pre><h3>The World Model Concept</h3><p>A <strong>World Model</strong> learns the transition dynamics of physical reality: <em>P</em>(<em>st</em>+1​∣<em>st</em>​,<em>at</em>​). Rather than predicting exact RGB values, it models how physical state representations (object affordances, spatial boundaries, movement vectors) evolve given specific motor inputs.</p><p><strong>Training Phase (Self-Supervised Latent Dynamics):</strong></p><ul><li><strong>Zero Pixel Reconstruction:</strong> Unlike classical VAEs or Diffusion models, JEPA predicts exclusively in representation space.</li><li><strong>Target &amp; Context Encoders:</strong> The Context Encoder processes current observation <em>xt</em>​, while the Target Encoder processes target future frame <em>xt</em>+<em>k</em>​.</li><li><strong>World Predictor:</strong> Takes latent state <em>st</em>​ and proposed action sequence <em>at</em>​ to predict future representation <em>s</em>^<em>t</em>+<em>k</em>​. Parameters are optimized by minimizing embedding distance (<em>L</em>2​ or Cosine Loss) against actual target representation <em>st</em>+<em>k</em>​.</li></ul><p><strong>Inference Phase (Fast Policy Execution):</strong></p><ul><li>The computational heavy Target Encoder and World Predictor are detached.</li><li>Only the trained <strong>Context Encoder</strong> and a lightweight <strong>Action Head</strong> run on the physical robot. Because the backbone was optimized to extract structural dynamics rather than transient textures, the representations generalize robustly across novel environments and lighting conditions.</li></ul><h3>4. Architectural Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smEPeZ9DlrYRB8eaRtFMkQ.png" /></figure><h3>5. Split Inference: Edge-Cloud Co-Design for Physical AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfrnuz3E1Yu1Y3g5thZ6wQ.png" /></figure><p>Deploying massive multi-billion parameter VLA models on mobile hardware creates an engineering trade-off: onboard compute is bounded by power draw, thermal constraints, and payload weight. Yet closed-loop robot control demands low-latency execution (20ms to 1ms response loops).</p><p>The solution gaining rapid adoption across modern robotics is <strong>Split Inference</strong>.</p><pre>SPLIT INFERENCE ARCHITECTURE<br> ┌────────────────────────────────────────────────────────────────────────┐<br> │                   OFF-BOARD SERVER / EDGE GPU CLUSTER                  │<br> │                                                                        │<br> │  ┌───────────────────────┐        ┌─────────────────────────────────┐  │<br> │  │ Camera Feeds &amp; Goals  │───────&gt;│ Heavy VLA Backbone              │  │<br> │  │ (Ingested via Wi-Fi)  │        │ (SigLIP + Gemma-2B / VLA-JEPA)  │  │<br> │  └───────────────────────┘        └────────────────┬────────────────┘  │<br> │                                                    │                   │<br> │                                                    ▼                   │<br> │                                  Generates 50-Step Action Chunks       │<br> │                                  at 2-5Hz Low Frequency                │<br> └─────────────────────────────────────────┬──────────────────────────────┘<br>                                           │<br>                        Low-Latency Network Transmission (gRPC/WebSockets)<br>                                           │<br> ┌─────────────────────────────────────────▼──────────────────────────────┐<br> │                      ON-BOARD EMBEDDED ROBOT COMPUTE                   │<br> │                      (e.g., NVIDIA Jetson Orin)                        │<br> │                                                                        │<br> │                                  ┌─────────────────────────────────┐   │<br> │                                  │ Action Trajectory Queue         │   │<br> │                                  │ (Buffers dynamic commands)      │   │<br> │                                  └────────────────┬────────────────┘   │<br> │                                                   │                    │<br> │                                                   ▼                    │<br> │  ┌───────────────────────┐        ┌─────────────────────────────────┐  │<br> │  │ Onboard Micro-Policy  │───────&gt;│ High-Frequency Motor PD Control │  │<br> │  │ (Local Reflex Layer)  │        │ (100Hz–1kHz Torque Drives)      │  │<br> │  └───────────────────────┘        └─────────────────────────────────┘  │<br> └─────────────────────────────────────────┴──────────────────────────────┘</pre><h3>1. Off-Board Server (Asynchronous High-Capacity Inference)</h3><p>An off-board workstation or local GPU cluster housing enterprise accelerators (e.g., NVIDIA H100/L40S) hosts the heavy Vision-Language backbone. It processes multi-view camera streams and text instructions, outputting long <strong>Action Chunks</strong> (e.g., <em>N</em>=50 future trajectory points) at a low rate of 2 Hz to 5 Hz.</p><h3>2. Low-Latency Network Pipeline</h3><p>Computed action vectors are streamed over high-bandwidth, ultra-low-latency wireless links (Wi-Fi 6E, private 5G, or local network protocols) as lightweight structured tensor payloads.</p><h3>3. On-Board Robot Execution (Real-Time Queueing)</h3><p>An embedded edge device (e.g., NVIDIA Jetson Orin) maintains a synchronized <strong>Action Trajectory Queue</strong>. The robot’s internal motor control loop pops commands from this queue at <strong>50 Hz to 1000 Hz</strong>, feeding motor drivers, torque loops, and joint controllers.</p><h3>4. Handling Network Jitter and Safety Reflexes</h3><ul><li><strong>Trajectory Interpolation:</strong> If network jitter delays an incoming packet, the local motor controller smoothly interpolates along the tail of the existing action chunk buffer.</li><li><strong>Hardware Reflex Layer:</strong> Onboard rangefinders and tactile sensors run lightweight, deterministic safety scripts that override server commands if an unexpected physical barrier is encountered.</li></ul><h3>Summary for Physical AI Developers</h3><ol><li><strong>Continuous Action Heads:</strong> Bridging language foundation models to physical hardware requires replacing discrete token outputs with continuous flow-matching or diffusion decoders.</li><li><strong>Latent Predictive Learning:</strong> Models like VLA-JEPA demonstrate that predicting future representation states is often more robust than performing full pixel reconstruction.</li><li><strong>Split Inference Strategy:</strong> Decoupling high-level semantic reasoning (off-board GPU server) from low-level execution (onboard embedded queue) provides a viable path toward running massive VLA foundation models on real-world robotics hardware.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dad217b250a" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/demystifying-physical-ai-a-deep-dive-into-vla-architectures-action-chunking-and-split-inference-6dad217b250a">Demystifying Physical AI: A Deep Dive into VLA Architectures, Action Chunking, and Split Inference</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Physical AI with LeRobot: Why It Matters Now, and How to Run It Yourself]]></title>
            <link>https://blog.gopenai.com/physical-ai-with-lerobot-why-it-matters-now-and-how-to-run-it-yourself-3f72bbb8356e?source=rss-4354164acdff------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f72bbb8356e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[physical-ai]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Aadishagrawal]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 21:26:18 GMT</pubDate>
            <atom:updated>2026-09-24T12:07:34.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0BUYpI5o0X_6X-E2.png" /><figcaption>LeRobot</figcaption></figure><h3>Why Physical AI, and why now</h3><p>Today’s best AI models can pass the bar exam, write production code, and walk you through quantum mechanics. <strong>None of them can reliably fold a towel.</strong></p><p>That gap is the most interesting unsolved problem in AI right now, and the field closing it has a name: <strong>Physical AI</strong> — systems that don’t just generate text <em>about</em> the world but perceive it and act in it. Machines with bodies.</p><p>For a decade this was a specialist’s game: custom hardware, custom software, a $50,000 arm, and a PhD to operate it. That has changed with startling speed. As of today:</p><ul><li>A <strong>3.6-billion-parameter robot foundation model</strong> is one from_pretrained() call away</li><li>The weights sit on Hugging Face; the framework is Apache-2.0 and pulls <strong>233,700 downloads a month</strong></li><li>A capable robot arm costs <strong>less than a laptop</strong></li><li>And the lag between “paper published” and “you can run it” has collapsed from years to weeks</li></ul><p>That last point is the real tell. <strong>NVIDIA, Physical Intelligence, AllenAI and a dozen other labs now publish their models <em>into a shared open format</em> rather than shipping bespoke repositories.</strong> When competitors voluntarily standardize on common infrastructure, a field has stopped being research and started being an industry.</p><p>Every wave of AI has this moment — where the technology stops being a demo and becomes infrastructure. Language models hit it around 2022. <strong>Physical AI is hitting it right now.</strong></p><p>And here is the part that should interest anyone who builds systems: <strong>the problems still standing are, to an unusual degree, engineering problems.</strong> Latency budgets. Memory footprints. Kernel fusion. Numerical precision. Deployment on ARM. These are not “wait for a bigger model” problems — they are “someone needs to profile this and fix it” problems. The leverage on offer right now doesn’t require a robotics PhD. It requires showing up.</p><p>This post is the on-ramp, in four parts:</p><ol><li><strong>What Physical AI actually is</strong> — and why it’s genuinely harder than chatbots</li><li><strong>Why it needs an open-source framework</strong> — and what fragmentation was costing everyone</li><li><strong>A technical deep dive into LeRobot</strong> — the model zoo, and how ACT, Diffusion Policy, π₀ and VLAs are built</li><li><strong>Working code</strong> — step by step, running π₀.₅ on a single A100</li></ol><p>One ground rule throughout: the numbers here are measured, not quoted. We profiled π₀.₅ on an A100 ourselves — and in two places the received wisdom turned out to be wrong.</p><h3>1. What Is Physical AI?</h3><p><strong>Physical AI is AI that closes a loop with the physical world.</strong> It takes in sensor data — camera frames, joint angles, force readings — and puts out <em>actions</em>: motor commands, gripper positions, wheel velocities. Then the world changes, and it does it again, typically dozens of times per second.</p><p>That last sentence is the whole difference. A language model is a function: text in, text out, done. A physical AI system is a <strong>controller inside a feedback loop</strong>, and that changes everything downstream.</p><h3>Three things that make it fundamentally harder</h3><p><strong>1. There is a clock, and it doesn’t wait.</strong> If ChatGPT takes four seconds to answer, you’re mildly annoyed. If a robot’s control policy takes four seconds while the arm is mid-motion, the arm has already collided with something. Latency isn’t a quality metric in Physical AI — it’s a <strong>hard deadline</strong>. A policy that’s 5% more accurate but 3× slower is often strictly worse.</p><p><strong>2. Mistakes are not editable.</strong> You can regenerate a bad paragraph. You cannot un-drop a glass or un-dent a car door. This pushes the field toward conservatism, extensive simulation, and a deep suspicion of benchmarks that measure anything other than closed-loop success on real hardware.</p><p><strong>3. Data is the bottleneck, and it’s expensive.</strong> The internet is a free, pre-existing dump of text and images. There is no internet of robot trajectories. Every training example is a human physically teleoperating a robot through a task, in real time, one demonstration at a time. Text data is measured in trillions of tokens; robot data is measured in <strong>thousands of hours</strong> — and it was gathered by hand.</p><p>There’s a name for the counterintuitive part: <strong>Moravec’s paradox</strong>. Things humans find hard (chess, calculus, passing the bar exam) turn out to be easy for computers. Things humans find trivially easy — picking up a soft object, folding a towel, walking across a cluttered room — turn out to be extraordinarily hard. We are currently very good at the bar exam and still working on the towel.</p><h3>The shift that made progress possible</h3><p>Classical robotics decomposed the problem into a pipeline: <strong>perceive → model the scene → plan a path → execute with a controller.</strong> Every stage was hand-engineered, and every stage was a place where assumptions broke. It works beautifully in a factory cell where the part arrives at the same position every time. It falls apart in a kitchen.</p><p>The modern approach collapses the pipeline into a single learned function:</p><pre>observation  ──►  [ neural network ]  ──►  action<br>(camera + joints)      &quot;the policy&quot;      (motor commands)</pre><p>This is called an <strong>end-to-end policy</strong>, and it’s trained by <strong>imitation learning</strong> — show it a few hundred human demonstrations of a task, and it learns the mapping directly. No explicit scene model, no planner. The policy learns that “the sponge is there, so move the gripper this way” without ever representing “sponge” as a concept you could inspect.</p><h3>Four words you need</h3><ul><li><strong>Policy</strong> — the neural network. Observation in, action out.</li><li><strong>Action chunk</strong> — the policy predicts the <em>next 50 actions</em> at once, not one. More on why below.</li><li><strong>VLA</strong> — <strong>Vision-Language-Action</strong> model. A policy built on a pretrained vision-language model, so it can be told <em>in English</em> what to do.</li><li><strong>Embodiment</strong> — the specific robot body. A policy trained on one arm doesn’t automatically transfer to another.</li></ul><p><strong>Action chunking deserves a moment</strong>, because it’s the single trick that makes any of this deployable. If your model takes 279 ms to run, you can only issue commands at 3.6 Hz — far too slow for smooth motion. But if each of those 279 ms inferences returns <strong>50 future actions</strong>, you can replay them at 179 Hz while the next chunk computes. The model thinks slowly; the robot moves smoothly. (Those are real measured numbers from an A100 — we’ll get to them.)</p><p>The <strong>VLA</strong> part is the reason this field suddenly accelerated. Instead of training a robot policy from scratch on your 500 demonstrations, you start from a vision-language model that has already seen most of the internet — it already knows what a sponge is, what “wipe” means, what a countertop looks like — and you teach it to output motor commands instead of words. You inherit common sense for free. That’s the unlock.</p><h3>2. Why Physical AI Needs an Open-Source Framework</h3><p>Here’s what the field looked like until very recently. Ten labs publish ten impressive robot papers. Each one ships:</p><ul><li>Its own data format for recording demonstrations</li><li>Its own training script</li><li>Its own definition of “success rate”</li><li>Its own inference entrypoint, usually undocumented</li><li>Its own hardware drivers, for hardware you don’t own</li></ul><p>The LeRobot paper (<em>“LeRobot: An Open-Source Library for End-to-End Robot Learning,”</em> <a href="https://arxiv.org/abs/2602.22818">arXiv:2602.22818</a>, Cadene et al., 17 authors, Hugging Face) names the problem in its first sentence:</p><blockquote><em>“development in the field of robot learning is often slowed by fragmented, closed-source tools designed to only address specific sub-components within the robotics stack.”</em></blockquote><p>Concretely, fragmentation costs four things:</p><p><strong>Reproducibility.</strong> If every lab writes its own evaluation harness, published success rates are not comparable. A “78% success rate” from one paper and “71%” from another may differ entirely in how they define an attempt.</p><p><strong>Comparability.</strong> Want to know whether model A or model B is better for your robot? With bespoke repos you have to install two conflicting environments, write two inference harnesses, and hope you got both right. The comparison — the thing you actually wanted — is buried under weeks of plumbing.</p><p><strong>The hardware floor.</strong> Robotics research used to require a $50,000 arm. That excluded essentially everyone. Open frameworks that support <strong>$200–$500 arms</strong> (SO-101, LeKiwi, Koch v1.1) changed who is allowed to participate.</p><p><strong>Deployment.</strong> Research code assumes a workstation, a warm GPU, and no deadlines. Robots have none of those. Somebody has to build the async inference layer, the action queue, the chunk-stitching — and it shouldn’t be every lab separately.</p><h3>The strongest signal: the network effect already happened</h3><p>Stars are a weak metric, so here’s the number that actually matters. <strong>Other labs are publishing into LeRobot’s format instead of asking you to adopt their repo:</strong></p><ul><li><strong>NVIDIA</strong> ships GR00T N1.7 checkpoints as nvidia/gr00t17-lerobot-*</li><li><strong>AllenAI</strong> ships allenai/MolmoAct2-LIBERO-LeRobot</li><li><strong>Physical Intelligence’s</strong> π₀, π₀-FAST, π₀.₅ and π₀.₅-2 are ported as first-class policies</li><li>Plus X-VLA, WALL-OSS, Lingbot-VA, EO-1, Being-H0, FastWAM, VLA-JEPA</li></ul><p>That’s the difference between a popular library and a <strong>standard</strong>. Coverage grows without anyone writing loaders.</p><p>The supporting numbers, verified in September 2026:</p><ul><li><strong>GitHub stars / forks</strong> — 27,608 / 5,676</li><li><strong>PyPI downloads, last 30 days</strong> — <strong>233,700</strong></li><li><strong>Policy architecture families</strong> — <strong>19</strong>, all behind one API</li><li><strong>License / Python</strong> — Apache-2.0 / &gt;=3.12</li><li><strong>Backing</strong> — Hugging Face, first-party and staffed</li></ul><h3>The honest caveats</h3><p>Two, because a post that only sells is not useful.</p><p><strong>Adoption is concentrated in open research, education, and low-cost hobby robotics.</strong> Production industrial deployment still runs vendor stacks. Read 27.6k stars as “the standard for open work,” not “the standard on factory floors.”</p><p><strong>The API churns.</strong> 909 open issues, and the module path moved from lerobot.common.policies to lerobot.policies mid-project — which broke our code. Pin a version (0.6.1) or a commit SHA for anything you intend to keep working.</p><h3>3. Technical Deep Dive: LeRobot</h3><p>LeRobot is three things bundled together:</p><ul><li><strong>Policies</strong> — 19 architecture families behind one interface</li><li><strong>Data</strong> — LeRobotDataset v3: synchronized video + action/state, streams from the Hub</li><li><strong>Hardware</strong> — robot drivers (SO-101, LeKiwi, Koch v1.1, humanoids), teleoperators, cameras</li></ul><h3>3.1 The keystone: one interface, nineteen architectures</h3><p>This is the design decision that makes everything else work. The base class PreTrainedPolicy declares these as <strong>abstract methods</strong>:</p><pre>forward(batch)               -&gt; (loss, loss_dict)   # TRAINING path<br>predict_action_chunk(batch)  -&gt; Tensor              # full chunk  ← inference<br>select_action(batch)         -&gt; Tensor              # one action, queue-backed<br>reset()</pre><p>Because they’re abstract, <strong>every policy must implement them.</strong> A 52-million-parameter ACT model and a 6-billion-parameter world model are called exactly the same way. One line of code changes: the class name.</p><p>That single property is why you can benchmark, profile, or deploy across the whole zoo without writing per-model adapters.</p><p>Policies are also <strong>enumerable at runtime</strong> — PreTrainedConfig.get_known_choices() returns the registered names, and the model class is resolved by naming convention (DiffusionConfig → DiffusionPolicy). So a sweep can discover its own target list instead of hardcoding one.</p><p>Devices: <strong>CUDA, XPU, MPS, CPU</strong>, selected centrally.</p><h3>3.2 The model zoo</h3><p>Every one of these is a from_pretrained() call. Params measured from safetensors metadata; downloads from the HF API, September 2026.</p><pre>POLICY     CHECKPOINT                            PARAMS     DISK DOWNLOADS<br>----------------------------------------------------------------------------<br>  vqbet      vqbet_pusht                          0.040 B  0.2 GiB       173<br>  act        act_aloha_sim_transfer_cube_human    0.052 B  0.2 GiB     2,872<br>  diffusion  diffusion_pusht                      0.263 B  1.0 GiB     2,772<br>* smolvla    smolvla_base                         0.450 B  0.8 GiB   159,287<br>  xvla       xvla-base                            0.880 B  3.3 GiB     3,969<br>  being_h05  being_h05_base                       2.808 B 10.5 GiB        20<br>  pi0_fast   pi0fast-base                         2.923 B 10.9 GiB     1,562<br>  vla_jepa   VLA-JEPA-Pretrain                    3.081 B  5.7 GiB     1,042<br>  groot      nvidia/gr00t17-lerobot-libero_10-640 3.144 B 11.7 GiB       611<br>  pi0        pi0_base                             3.501 B 13.0 GiB    41,435<br>&lt; pi05       pi05_base                            3.617 B 13.5 GiB    20,319<br>  eo1        eo1-base                             3.772 B  7.1 GiB       342<br>  pi052      pi052_base                           4.143 B 15.4 GiB        41<br>  wall_x     wall-oss-0.5                         4.162 B  7.8 GiB        51<br>  lingbot_va lingbot_va_base                      5.089 B  9.5 GiB       260<br>  molmoact2  MolmoAct2-LIBERO-LeRobot             5.442 B 20.3 GiB        92<br>  fastwam    fastwam_base                         6.021 B 11.2 GiB       404<br>----------------------------------------------------------------------------<br>  openvla    openvla/openvla-7b                   7.541 B 14.1 GiB   434,598<br>             (external, not a LeRobot policy)<br><br>* most-downloaded        &lt; profiled later in this post</pre><p><strong>Note the inversion.</strong> The runaway download leader inside LeRobot — smolvla_base, 159k downloads — is also the <strong>smallest model in the table</strong> at 0.45 B. That is not an accident. It&#39;s the only one plausibly deployable on a robot without a discrete GPU. In Physical AI, deployability beats capability more often than in any other ML domain.</p><p><em>(Four families — </em><em>tdmpc, </em><em>multi_task_dit, </em><em>evo1, </em><em>lawam — have no published base checkpoint yet.)</em></p><h3>3.3 The taxonomy that actually matters: inference shape</h3><p>Parameter count tells you memory. <strong>Inference shape tells you latency, and latency is the deadline.</strong> Four classes:</p><ul><li><strong>A · Single-pass BC</strong> — one forward pass, static shapes → act, vqbet</li><li><strong>B · Iterative denoise, flow matching</strong> — prefix once + N × denoise → pi0, pi05, smolvla, groot, xvla, eo1, wall_x, +3 more</li><li><strong>B′ · Iterative denoise, DDPM</strong> — UNet, N × denoise → diffusion</li><li><strong>C · Autoregressive token decode</strong> — prefill + per-token loop, <strong>dynamic shapes</strong> → pi0_fast, molmoact2, OpenVLA</li><li><strong>D · Hybrid latent-predictive</strong> — encoder + flow head, single pass → vla_jepa</li></ul><p>Class B is the mainstream today and it’s pleasingly uniform — smolvla defines <em>the same method names</em> as pi05 (sample_actions, denoise_step, embed_prefix, embed_suffix), so an optimization written for one transfers to the family.</p><h3>3.4 ACT — the baseline everyone starts from</h3><p><strong>ACT (Action Chunking Transformer)</strong>, from the ALOHA paper (<a href="https://arxiv.org/abs/2304.13705">arXiv:2304.13705</a>). At <strong>52 M parameters</strong> it’s the smallest serious policy here, and it’s the model that popularized action chunking.</p><pre>per-camera images ──► ResNet-18 ──► patch features ┐<br>joint positions ─────────────────────────────────► ├──► Transformer<br>latent style variable z (from CVAE encoder)  ──────┘     encoder-decoder<br>                                                              │<br>                                              fixed query embeddings<br>                                                              ▼<br>                                                 k × action_dim  (chunk)</pre><p>Two ideas worth carrying forward:</p><ul><li><strong>It’s a CVAE.</strong> A transformer encoder compresses the demonstrated action sequence into a latent z during training. That latent absorbs the <em>style</em> variation between human demonstrations — which is what stops the model from averaging two valid strategies into one invalid one. At inference z is set to the prior mean.</li><li><strong>Chunking + temporal ensembling.</strong> It predicts k actions at once (k=100 in the paper), and overlapping predictions from consecutive chunks are blended for smoothness.</li></ul><p>No language, no pretraining, no internet knowledge. Train it on 50 demonstrations of one task and it does that one task, well.</p><h3>3.5 Diffusion Policy — generate the trajectory</h3><p><strong>Diffusion Policy</strong> (<a href="https://arxiv.org/abs/2303.04137">arXiv:2303.04137</a>) reframes action prediction as <em>generation</em>: start from a noisy action sequence and iteratively denoise it, conditioned on the observation. Usually a 1-D temporal UNet over the action-sequence axis.</p><h3>3.6 VLAs — how a language model learns to move</h3><p>A <strong>VLA</strong> starts from a pretrained vision-language model and gives it a body. The interesting engineering question is entirely: <strong>how do you get continuous motor commands out of something that only emits tokens?</strong> Two answers, and they define the two dominant VLA architectures.</p><h4>Answer 1: Discretize the actions into tokens (autoregressive)</h4><p>Chop each action dimension into 256 bins, map each bin to a rarely-used token in the vocabulary, and let the model generate motor commands the same way it generates text. This is what <strong>RT-2</strong> (<a href="https://arxiv.org/abs/2307.15818">arXiv:2307.15818</a>) introduced and what <strong>OpenVLA</strong> (<a href="https://arxiv.org/abs/2406.09246">arXiv:2406.09246</a>) made the open reference implementation.</p><p>OpenVLA is 7.5 B params — a SigLIP + DINOv2 fused visual encoder on a Llama-2 7B backbone — and with <strong>434,598 downloads</strong> it’s the single most-downloaded VLA checkpoint anywhere. It’s the field’s standard baseline.</p><p>It also has an obvious problem: <strong>autoregressive decoding is slow.</strong> One forward pass <em>per token</em>, and an action chunk is a lot of tokens. <strong>π₀-FAST</strong> (<a href="https://arxiv.org/abs/2501.09747">arXiv:2501.09747</a>) attacks this with a smarter tokenizer — discrete cosine transform plus byte-pair encoding, so a whole chunk compresses into far fewer tokens.</p><h4>Answer 2: Bolt on a continuous action head (flow matching)</h4><p>Don’t discretize at all. Attach a small module that outputs continuous action vectors directly, and train it with <strong>flow matching</strong>. This is π₀’s approach and it’s now the dominant one.</p><p><strong>Flow matching in one paragraph.</strong> You want to turn random noise into a valid action chunk. Train a network to predict a <strong>velocity field</strong>: given a partially-denoised chunk and a “time” value τ ∈ [0,1], it predicts which direction to move to get closer to a real action. At inference you start from pure noise and take N Euler steps along that field. It’s diffusion’s cousin, with straighter paths — so it needs far fewer steps. <strong>π₀ uses 10.</strong></p><h3>3.7 π₀ and π₀.₅ — the frontier open VLA</h3><p><strong>π₀</strong> (<a href="https://arxiv.org/abs/2410.24164">arXiv:2410.24164</a>, Physical Intelligence) is three subsystems, ~3.6 B parameters total:</p><ul><li><strong>Vision encoder — SigLIP</strong> · RGB camera → patch tokens</li><li><strong>VLM backbone — </strong><strong>gemma_2b</strong> · fuses scene + instruction</li><li><strong>Action expert — </strong><strong>gemma_300m</strong> · flow-matching trajectory decode</li></ul><p>The <strong>action expert</strong> is the clever bit. It isn’t a head bolted on the end — it’s a second, smaller set of transformer weights that participates in the <em>same attention operation</em> as the VLM. Image and text tokens are processed by the 2 B weights; action tokens by the 300 M weights; they attend to each other jointly. So actions see the full scene understanding, but the expensive backbone doesn’t have to be re-run for every denoising step.</p><p><strong>π₀.₅</strong> (<a href="https://arxiv.org/abs/2504.16054">arXiv:2504.16054</a>) keeps the architecture and changes the training: co-training on deliberately heterogeneous data — web images, verbal instructions, high-level subtask labels, multiple robot embodiments — to buy open-world generalization instead of task-specific skill.</p><p>It also has an implementation detail that makes people blink. Here’s the verified config for lerobot/pi05_base:</p><pre>observation.images.base_0_rgb          (3, 224, 224)<br>observation.images.left_wrist_0_rgb    (3, 224, 224)<br>observation.images.right_wrist_0_rgb   (3, 224, 224)<br>observation.state                      (32,)   ──►  action (32,)</pre><pre>chunk_size 50 · n_action_steps 50 · num_inference_steps 10<br>tokenizer google/paligemma-3b-pt-224 · tokenizer_max_length 200</pre><p><strong>π₀.₅ has no state-embedding layer.</strong> The 32 joint values are discretized into 256 bins and <strong>injected into the prompt as text tokens.</strong> Proprioception reaches the model the same way the instruction does — as language. It’s an unusual choice, and it means the text tokenizer is load-bearing for the control loop.</p><h4>What actually executes at inference</h4><pre>predict_action_chunk(batch)<br>└─ model.sample_actions()<br>   ├─ embed_prefix()   ONCE   SigLIP + gemma_2b over 968 tokens → KV cache<br>   └─ denoise_step()   × 10   gemma_300m over 50 action tokens, reading that cache</pre><p>π₀.₅ is <strong>not three models in a pipeline</strong> — it is one transformer stack over one token sequence, with different <em>segments</em> of that sequence processed by different weights:</p><pre>══ STAGE 1 · embed_prefix() ═══════════════════ RUNS ONCE ══</pre><pre>  camera ×3 ──► SigLIP ──────────► 768 image tokens  ──┐<br>                256 patches each                       │<br>                                                       ├─► 968<br>  instruction ──┐                                      │   tokens<br>                ├──► PaliGemma ──► 200 language ───────┘  (prefix)<br>  joint state ──┘    tokenizer      tokens<br>  as 256 bins                  │<br>                               ▼<br>              ╔══════════════════════════════════╗<br>              ║   gemma_2b   ·   VLM BACKBONE    ║<br>              ║   18 layers                      ║<br>              ╚═════════════════╤════════════════╝<br>                                │<br>                     ► PREFIX KV CACHE ◄<br>              keys + values, one set per layer<br>         ─── this is the only thing handed forward ───<br>                                │<br>══ STAGE 2 · denoise_step() ════════════════════ RUNS 10× ══<br>                                ▼<br>   50 noisy      ╔══════════════════════════════════╗<br>   action  ─────►║  gemma_300m  ·  ACTION EXPERT    ║<br>   tokens        ║  18 layers                       ║<br>      ▲          ║  · self-attn over the 50 actions ║<br>      │          ║  · attends INTO the prefix KV    ║<br>      │          ╚═════════════════╤════════════════╝<br>      │                            │<br>      │                   velocity field  v<br>      │                            │<br>      └────── A ← A + v · Δτ ──────┘      τ : 0 ──► 1<br>                     │<br>                     ▼  after the 10th step<br>          action chunk   (1, 50, 32)</pre><p>Two things to read off that diagram. The backbone consumes <strong>one flat sequence of 968 tokens</strong> — 768 image tokens (3 cameras × 256 SigLIP patches) plus 200 language tokens — and the joint state is <em>inside</em> those language tokens as discrete bins, not a separate input stream. What reaches the action expert is the <strong>prefix KV cache</strong>: keys and values, one set per layer. Not a pooled feature vector.</p><p>The prefix can be computed once because the attention mask is block-causal — action tokens attend to the prefix, but <strong>the prefix never attends to the actions.</strong> So its keys and values don’t depend on the noisy actions, and are identical on denoise step 1 and step 10.</p><p><strong>That asymmetry — 1 × prefix, 10 × denoise — is the most important fact for anyone optimizing this model.</strong> Vision and language run once per chunk. The action expert runs ten times. Optimization effort spent on denoise_step is amortized 10× more than effort spent anywhere else.</p><h3>4. The Code: π₀.₅ on an A100, Step by Step</h3><p>Here’s the whole thing. <strong>25 lines for a 4-billion-parameter VLA</strong> — and the same five stages work for any of the other 18 families, changing only the class name in step 3.</p><h3>Step 0 — Install</h3><pre>python3.12 -m venv venv &amp;&amp; source venv/bin/activate<br>pip install &quot;torch==2.11.*&quot; --index-url https://download.pytorch.org/whl/cu128<br>pip install &quot;lerobot[pi]&quot;<br>huggingface-cli login     # google/paligemma-3b-pt-224 is GATED — accept the license</pre><p>LeRobot requires <strong>Python ≥ 3.12</strong> and pins <strong>torch&gt;=2.7,&lt;2.12</strong>. Installing a CPU wheel, or torch 2.12+, is the most common way to lose an afternoon. The tokenizer repo is gated separately from the checkpoint — open its model page and accept, or step 3 dies with a 403.</p><h3>Step 1 — Load and patch the config</h3><pre>import torch<br>from lerobot.configs import PreTrainedConfig<br>from lerobot.policies import make_pre_post_processors<br>from lerobot.policies.pi05.modeling_pi05 import PI05Policy<br>from lerobot.utils.constants import OBS_STATE<br><br>device = torch.device(&quot;cuda&quot;)<br>CKPT = &quot;lerobot/pi05_base&quot;<br>config = PreTrainedConfig.from_pretrained(CKPT)<br>config.device = str(device)     # checkpoint ships &quot;mps&quot; - patch BEFORE constructing<br>config.dtype = &quot;bfloat16&quot;       # checkpoint default is &quot;float32&quot; (13.5 GiB of weights)</pre><p><strong>Why patch before constructing, not after?</strong> PI05Policy.__init__ calls self.model.to(config.device) internally. By the time you have a policy object, the decision is made. And lerobot/pi05_base genuinely ships &quot;device&quot;: &quot;mps&quot; in its config.json, so on a CUDA box the default is wrong.</p><p>config.dtype matters just as much: the checkpoint default is float32, which is <strong>13.5 GiB of weights</strong>. In bf16 it&#39;s 8.7 GiB. The checkpoint value wins over any flag you pass elsewhere unless you set it here — we lost an entire profiling run to exactly this.</p><h3>Step 2 — Load the weights</h3><pre>policy = PI05Policy.from_pretrained(CKPT, config=config)<br>policy.to(device)<br>policy.eval()</pre><p>Downloads ~14 GB on first run, then remaps <strong>812 state-dict keys</strong> from OpenPI naming to LeRobot’s layout. from_pretrained already calls .eval(), but being explicit costs nothing.</p><h3>Step 3 — Build the processors (do not skip this)</h3><pre>preprocessor, postprocessor = make_pre_post_processors(<br>    policy_cfg=config,<br>    pretrained_path=CKPT,<br>    preprocessor_overrides={&quot;device_processor&quot;: {&quot;device&quot;: str(device)}},<br>)</pre><p>This is what loads the <strong>dataset normalization statistics</strong>, runs the state discretization, and calls the PaliGemma tokenizer. The full pipeline is rename → add_batch_dim → normalize → discretize state into the prompt → tokenize → to(device).</p><p>It is the step that looks optional and isn’t. Omit it and the model receives out-of-distribution inputs and returns confident nonsense — <strong>no error, no warning.</strong> This is the single easiest way to conclude that a working model is broken.</p><h3>Step 4 — Build one observation</h3><pre>h, w = config.image_resolution                                      # (224, 224)<br>obs = {k: torch.rand(3, h, w) for k in config.image_features}        # 3 images, [0,1], CHW<br>obs[OBS_STATE] = torch.rand(config.input_features[OBS_STATE].shape[0])   # 32 joints<br>obs[&quot;task&quot;] = &quot;pick up the sponge and wipe the counter&quot;</pre><p>Note what’s driving the shapes: <strong>config.image_features and </strong><strong>config.input_features, not hardcoded numbers.</strong> That&#39;s what makes this same block work for a different policy with a different image count.</p><p>Images are float in [0,1] and [C, H, W] — the preprocessor adds the batch axis, and the policy rescales to [-1,1] for PaliGemma internally. obs[&quot;task&quot;] is a plain str for batch size 1 (a list[str] once a batch axis exists). Swap torch.rand for real camera frames and real joint readings and you have a real control loop.</p><h3>Step 5 — Run inference</h3><pre>with torch.inference_mode():<br>    batch   = preprocessor(obs)                   # normalize → discretize → tokenize<br>    chunk   = policy.predict_action_chunk(batch)  # (1, 50, 32)<br>    actions = postprocessor(chunk)                # un-normalize into robot units</pre><p>preprocessor(obs) turns 3 raw image tensors + 32 floats + a string into what the model actually consumes:</p><pre>observation.images.base_0_rgb          (1, 3, 224, 224)  float32  cuda:0<br>observation.images.left_wrist_0_rgb    (1, 3, 224, 224)  float32  cuda:0<br>observation.images.right_wrist_0_rgb   (1, 3, 224, 224)  float32  cuda:0<br>observation.language.tokens            (1, 200)          int64    cuda:0<br>observation.language.attention_mask    (1, 200)          bool     cuda:0<br>observation.state                      (1, 32)           float32  cuda:0</pre><p>Output is (1, 50, 32) — <strong>50 future timesteps × 32 action dimensions.</strong> One inference, fifty commands.</p><h3>Step 6 — The real control loop</h3><pre>policy.reset()<br>for _ in range(horizon):<br>    obs = read_cameras_and_joints()                    # your robot I/O<br>    with torch.inference_mode():<br>        action = policy.select_action(preprocessor(obs))<br>    send_to_robot(postprocessor(action))</pre><p>select_action is backed by an internal 50-deep action queue. The first call runs the model and fills it; <strong>the next 49 pop from the deque and never touch the GPU.</strong> That&#39;s not a quirk to work around — it <em>is</em> action chunking, and it&#39;s the reason a 3.6 Hz model can command a robot at 179 Hz.</p><p>(For chunk-boundary stalls, LeRobot ships <strong>RTC (Real-Time Chunking)</strong> in policies/rtc, which blends a new chunk into the executing one instead of pausing. Check policy.supports_rtc().)</p><h3>5. What It Actually Costs: Measured on an A100</h3><p>Vendor claims are one thing. Here is lerobot/pi05_base on an <strong>A100</strong>, bf16, batch 1, 3 × 224×224 cameras:</p><pre>parameters       : 4.143 B          weight memory : 8.71 GiB<br>backbone/expert  : gemma_2b / gemma_300m<br>cameras          : 3 @ (224, 224)   chunk_size    : 50<br>flow-match steps : 10               output shape  : (1, 50, 32)<br>latency mean     : 279.2 ms   (p50 279.1 / p90 283.0)<br>throughput       : 3.6 inferences/s<br>chunk covers     : 50 action steps → 179 Hz open-loop replay budget<br>peak VRAM        : 8.87 GiB allocated, 9.20 GiB reserved</pre><h3>Sizing: precision decides the floor</h3><ul><li><strong>float32</strong> (the checkpoint default) — ~13.5 GiB of weights → <strong>16 GB minimum</strong>, 24 GB comfortable</li><li><strong>bfloat16</strong> — ~8.7 GiB of weights → <strong>10–12 GB</strong> comfortable</li></ul><p><strong>Compute capability ≥ 8.0 (Ampere) is the real requirement</strong> — bf16 tensor cores and efficient attention kernels need it. That means RTX 30/40/50, A4000+, L4, L40S, A100, H100, or Jetson Orin/Thor. A 16 GB T4 (Turing, no bf16) runs it in fp32, slowly.</p><p>The widely-repeated “8 GB / RTX 4090 is enough” figure <strong>only holds in bf16.</strong> At the checkpoint’s default fp32, the weights alone are 13.5 GiB and an 8 GB card cannot load the model at all.</p><h3>6. Where to Start</h3><p>If you want to actually get into this — and the argument of this post is that now is the time — here’s the shortest path:</p><ol><li><strong>Start with ACT, not a VLA.</strong> 52 M params, trains in hours on one GPU, and it will honestly tell you whether your demonstration data is good. Most robot-learning failures are data failures wearing a model costume.</li><li><strong>Then </strong><strong>smolvla_base.</strong> 450 M params, the most-downloaded policy in the framework, and the only one in its class that runs without a big GPU. This is where the deployable frontier is.</li><li><strong>Then π₀.₅ if you have ≥ 12 GB.</strong> It’s the most capable open VLA with real robot deployment behind it, and the code in §4 is all you need.</li><li><strong>Profile before you optimize.</strong> The measured numbers in §5 contradicted our own written assumptions twice. Assume yours are wrong too.</li><li><strong>Pin your version.</strong> 0.6.1 or a commit SHA. The API moves.</li></ol><p>The models are open. The weights are downloadable. The arms are affordable. The remaining problems are latency, memory, generalization, and data — and every one of them is a problem you can work on this week.</p><h3>References</h3><p><strong>Framework</strong></p><ul><li>LeRobot: An Open-Source Library for End-to-End Robot Learning — <a href="https://arxiv.org/abs/2602.22818">arXiv:2602.22818</a> <em>(Cadene et al., Hugging Face)</em></li><li>Code: <a href="https://github.com/huggingface/lerobot">github.com/huggingface/lerobot</a> · Apache-2.0</li></ul><p><strong>Policies and architectures</strong></p><ul><li><strong>ACT / ALOHA</strong> — <em>Learning Fine-Grained Bimanual Manipulation with Low-Cost Hardware</em>, Zhao et al., <a href="https://arxiv.org/abs/2304.13705">arXiv:2304.13705</a></li><li><strong>Diffusion Policy</strong> — <em>Visuomotor Policy Learning via Action Diffusion</em>, Chi et al., <a href="https://arxiv.org/abs/2303.04137">arXiv:2303.04137</a></li><li><strong>π₀</strong> — <em>A Vision-Language-Action Flow Model for General Robot Control</em>, Black et al., <a href="https://arxiv.org/abs/2410.24164">arXiv:2410.24164</a></li><li><strong>π₀.₅</strong> — <em>A Vision-Language-Action Model with Open-World Generalization</em>, Physical Intelligence, <a href="https://arxiv.org/abs/2504.16054">arXiv:2504.16054</a></li><li><strong>π₀-FAST</strong> — <em>FAST: Efficient Action Tokenization for Vision-Language-Action Models</em>, Pertsch et al., <a href="https://arxiv.org/abs/2501.09747">arXiv:2501.09747</a></li><li><strong>OpenVLA</strong> — <em>An Open-Source Vision-Language-Action Model</em>, Kim et al., <a href="https://arxiv.org/abs/2406.09246">arXiv:2406.09246</a></li><li><strong>SmolVLA</strong> — <em>A Vision-Language-Action Model for Affordable and Efficient Robotics</em>, Shukor et al., <a href="https://arxiv.org/abs/2506.01844">arXiv:2506.01844</a></li><li><strong>RT-2</strong> — <em>Vision-Language-Action Models Transfer Web Knowledge to Robotic Control</em>, Brohan et al., <a href="https://arxiv.org/abs/2307.15818">arXiv:2307.15818</a></li></ul><p><em>All framework statistics, checkpoint sizes and download counts verified against the GitHub, PyPI and Hugging Face Hub APIs in September 2026. All latency, memory and op-count figures are our own measurements on an A100 with </em><em>lerobot 0.6.1</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f72bbb8356e" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/physical-ai-with-lerobot-why-it-matters-now-and-how-to-run-it-yourself-3f72bbb8356e">Physical AI with LeRobot: Why It Matters Now, and How to Run It Yourself</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Which Thread Holds Which Number?]]></title>
            <link>https://blog.gopenai.com/which-thread-holds-which-number-7dd2f13db2bf?source=rss-4354164acdff------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dd2f13db2bf</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[triton]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[cuda]]></category>
            <dc:creator><![CDATA[Aadishagrawal]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 19:44:23 GMT</pubDate>
            <atom:updated>2026-09-08T11:59:26.030Z</atom:updated>
            <content:encoded><![CDATA[<h3>A gentle introduction to Gluon, Triton’s low-level frontend, and the XOR algebra that powers it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VraiZjHImPwG1-GQzKgg-w.png" /></figure><p>If you have ever written a GPU kernel in <a href="https://github.com/triton-lang/triton">Triton</a>, profiled it, found it 30% slower than you hoped, and then discovered there was no knob left to turn — this post is about the thing you were missing.</p><p>Gluon is a second Python DSL that ships <em>inside</em> Triton. It exists to let you answer one question explicitly, a question classic Triton hides from you completely:</p><blockquote><strong><em>Which thread holds which element of my tensor?</em></strong></blockquote><p>And the surprising part is the answer’s shape. It is never a lookup table. It is always a <strong>linear map over bits</strong>, where “addition” means XOR. Once that clicks, swizzles, broadcasts, matrix-multiply fragment layouts and layout conversions all stop being separate topics and become one small piece of linear algebra.</p><p>We’ll build up to it with a worked example small enough to do on paper.</p><h3>First, a 60-second vocabulary</h3><p>You need five words. If you already write GPU Kernels, skip this.</p><p>A GPU runs thousands of <strong>threads</strong>. They are grouped into <strong>warps</strong> of 32 threads (64 on AMD CDNA), and warps execute in lockstep — all 32 threads run the same instruction at the same time on different data. A thread’s position inside its warp is its <strong>lane</strong> (0–31). Warps are grouped into a <strong>block</strong> (also called a CTA), which is the unit you launch.</p><p>Each thread has private <strong>registers</strong> — a handful of fast slots that hold the values it is working on. All threads in a block also share a small, fast scratchpad called <strong>shared memory</strong> (SMEM).</p><p>Now: suppose you have a 256-element array and 128 threads. Somebody has to decide which two elements each thread keeps in its registers. That decision is a <strong>layout</strong>.</p><pre>the data:   256 elements, indexed 0..255<br>   ┌────┬────┬────┬────┬────┬────┬────┬────┬─── ... ──┐<br>   │  0 │  1 │  2 │  3 │  4 │  5 │  6 │  7 │          │<br>   └────┴────┴────┴────┴────┴────┴────┴────┴─── ... ──┘<br>     └── t0 ──┘ └── t1 ──┘ └── t2 ──┘ └── t3 ──┘<br>        ^<br>        thread 0 keeps elements 0 and 1 in its registers</pre><p>Layout choice is not cosmetic. It decides whether a load becomes one wide memory instruction or eight narrow ones, whether a reduction needs shared memory or is free, and whether 32 lanes hit 32 different memory banks or queue up behind one.</p><h3>Part 1 — What Gluon actually is</h3><h3>Triton decides for you. Gluon lets you decide.</h3><p>Classic Triton is deliberately abstract. You write <em>tile-level</em> code — “load 128 contiguous floats, add them, store them” — and a series of compiler passes chooses the physical realisation: which thread holds which element, whether loads are vectorised to 32/64/128 bits, when to stage data through shared memory, where to insert layout conversions, how to pipeline a loop.</p><p>That automation is Triton’s whole value proposition: one readable kernel, good performance, many backends.</p><p>It is also Triton’s ceiling. When the heuristics pick a suboptimal layout, the classic frontend gives you almost no handle. You can nudge num_warps, num_stages, block sizes — and then you are out of vocabulary. The thing you actually want to say (&quot;put these 8 values in these registers so the hardware&#39;s matrix-multiply instruction can eat them with zero shuffling&quot;) has no spelling in triton.language.</p><p>Gluon adds that vocabulary. In Gluon:</p><ul><li>Every tensor’s <strong>layout is part of its type</strong>, and you write it.</li><li>Shared memory is <strong>explicitly allocated</strong>, explicitly read and written.</li><li>Async copies, barriers and warp specialisation are <strong>explicit operations</strong>.</li><li>Layout mismatches are <strong>compile errors</strong>, not silently-inserted data movement.</li></ul><p>The mental shift is one line:</p><blockquote><strong><em>Triton:</em></strong><em> you describe </em>what<em> to compute; the compiler decides </em>where the data lives.<em> </em><strong><em>Gluon:</em></strong><em> you describe </em>what<em> to compute </em><strong><em>and where the data lives</em></strong><em>; the compiler verifies it and emits code.</em></blockquote><p>Gluon is what you reach for when you were about to give up on Triton and go write raw CUDA or PTX. It keeps Python, tiles, the type checker, the autotuner and the launcher — and hands you back the placement decisions CUDA would have given you.</p><p><strong>Status check:</strong> Gluon is explicitly experimental. It lives at triton.experimental.gluon, and signatures do move between Triton releases. Treat every API detail below as &quot;verify against your installed version&quot;.</p><h3>Where Gluon plugs into the compiler</h3><p>Triton compiles through a stack of MLIR dialects. Simplified:</p><pre>@triton.jit  Python<br>         │<br>         ▼<br>      TTIR          tiles, no notion of threads or layouts<br>         │          (&quot;a [128, 64] tensor of f32&quot;)<br>         │   &lt;-- layout assignment, coalescing, pipelining ...<br>         ▼<br>      TTGIR         every tensor type now carries a LAYOUT<br>         │          (&quot;tensor&lt;128x64xf32, #blocked&lt;...&gt;&gt;&quot;)<br>         │   &lt;-- lowering, shuffles, swizzles, instr. selection<br>         ▼<br>    LLVM IR  ──►  PTX / AMDGCN  ──►  cubin / hsaco</pre><p>The interesting bit is that first &lt;--. <strong>Everything you struggle to control in classic Triton happens in the TTIR → TTGIR transition.</strong> That&#39;s where layouts get chosen, and where convert_layout operations get quietly inserted.</p><p>Gluon’s design move is to let you write TTGIR-level semantics directly from Python:</p><pre>@gluon.jit  Python  ────────────►  TTGIR  ──►  LLVM  ──►  PTX<br>                      (layouts already<br>                       specified by you)</pre><p>You skip the inference pass because there is nothing left to infer. This is why Gluon’s layout objects map one-to-one onto TTGIR attributes: ttgl.BlockedLayout <em>is</em> #ttg.blocked&lt;...&gt;. Reading TTGIR and writing Gluon become the same skill — which is also why dumping TTGIR is the primary Gluon debugging tool:</p><pre>TRITON_ALWAYS_COMPILE=1 MLIR_ENABLE_DUMP=1 python your_kernel.py</pre><h3>The same kernel, both ways</h3><p>Vector add over 256 elements, 4 warps.</p><p><strong>Classic Triton</strong> — no layout appears anywhere:</p><pre>import triton<br>import triton.language as tl<br><br>@triton.jit<br>def add_triton(x_ptr, y_ptr, out_ptr, BLOCK: tl.constexpr):<br>    offs = tl.arange(0, BLOCK)<br>    x = tl.load(x_ptr + offs)<br>    y = tl.load(y_ptr + offs)<br>    tl.store(out_ptr + offs, x + y)<br>add_triton[(1,)](x, y, out, BLOCK=256, num_warps=4)</pre><p><strong>Gluon</strong> — the layout is an argument:</p><pre>from triton.experimental import gluon<br>from triton.experimental.gluon import language as ttgl<br><br>@gluon.jit<br>def add_gluon(x_ptr, y_ptr, out_ptr,<br>              BLOCK: ttgl.constexpr, layout: ttgl.constexpr):<br>    offs = ttgl.arange(0, BLOCK, layout=layout)  # layout is MANDATORY<br>    x = ttgl.load(x_ptr + offs)                  # inherits offs&#39;s layout<br>    y = ttgl.load(y_ptr + offs)<br>    ttgl.store(out_ptr + offs, x + y)            # x, y layouts must match<br>layout = ttgl.BlockedLayout(size_per_thread=[2], threads_per_warp=[32],<br>                            warps_per_cta=[4], order=[0])<br>add_gluon[(1,)](x, y, out, BLOCK=256, layout=layout, num_warps=4)</pre><p>For <em>this</em> kernel, Gluon bought you nothing but typing. That is the honest comparison. The payoff arrives when the kernel is a fused attention with a matrix-multiply pipeline, and the compiler’s layout choice inserts four convert_layout operations that you can see in the TTGIR and cannot remove.</p><h3>Gluon vs Triton, at a glance</h3><pre>Triton (tl)              Gluon (ttgl)<br> ───────────────────────────────────────────────────────────────────<br> decorator            @triton.jit              @gluon.jit<br> abstraction          tiles (~TTIR)            tiles + layouts (~TTGIR)<br> layouts              inferred, invisible      explicit, in every type<br> arange               tl.arange(0, N)          ttgl.arange(0, N, layout=L)<br> layout mismatch      cannot happen            compile error<br> layout conversion    auto-inserted            you call convert_layout<br> shared memory        implicit                 allocate_shared_memory<br> loop pipelining      automatic (num_stages)   manual: async + mbarriers<br> warp specialisation  automatic heuristic      ttgl.warp_specialize<br> portability          high                     low (encodes hardware)<br> lines of code        fewer                    noticeably more<br> failure mode         compiles, runs slow      won&#39;t compile until coherent<br> debug artefact       stare at PTX and shrug   read TTGIR, it mirrors you</pre><p><strong>Identical in both:</strong> the JIT and launch syntax (kernel[grid](...)), constexpr specialisation, triton.autotune, the compilation cache, dot semantics, pointer arithmetic and masking — and the fact that you write <em>tile</em>-level code, not per-thread code. Gluon is <strong>not</strong> CUDA. You still never write threadIdx to address your data. You write a layout, and the layout tells the compiler what the thread indices mean.</p><p>Beyond layouts, Gluon also makes explicit: shared memory as a real resource (allocate_shared_memory, .store(), .load()), asynchronous copies and mbarrier synchronisation instead of an automatic pipelining pass, and ttgl.warp_specialize so you can put a producer warp group on TMA loads while a consumer group runs the matrix-multiply. Hardware-specific operations live in honest hardware-specific namespaces (...gluon.language.nvidia.hopper, ...blackwell, ...amd).</p><h3>When to use which</h3><p><strong>Use classic Triton</strong> for elementwise, reduction and fusion kernels, for prototyping, when you’re targeting several GPU generations from one source, or when the kernel is memory-bound (the compiler’s coalescing is usually right).</p><p><strong>Reach for Gluon</strong> only when all four of these are true:</p><ol><li>You have profiled and <em>know</em> you’re leaving real performance on the table.</li><li>You have read the TTGIR and can point at the specific problem — a convert_layout in the inner loop, a non-vectorised load, bank conflicts, a pipeline that isn&#39;t overlapping.</li><li>You know what the layout <em>should</em> be, usually because a hardware instruction dictates it.</li><li>You accept that the result is tied to one architecture.</li></ol><p><strong>The pragmatic hybrid:</strong> write it in Triton, profile, dump TTGIR, and port only the hot kernel to Gluon — reusing the layouts the compiler already chose as your starting point, and fixing the one thing that was wrong.</p><h3>Part 2 — Linear layouts</h3><h3>A layout is a function</h3><p>Formally, a layout is a function from a <strong>hardware location</strong> to a <strong>tensor coordinate</strong>:</p><pre>(register, lane, warp, block)   ───────►   (d0, d1, ..., dn)<br>   &quot;where in the machine&quot;                     &quot;which element of the tensor&quot;<br><br>register  which of the several values one thread holds     1–16<br> lane      thread within a warp                             32 (NVIDIA)<br> warp      warp within the block                            num_warps<br> block     block within a cluster (Hopper+)                 usually 1</pre><p>Read a layout as answering: <em>“Thread 37, in its second register — which element of my [16,16] tile is that?”</em></p><p>Every distributed-tensor layout in Triton is one of these functions. BlockedLayout, SliceLayout, NVMMADistributedLayout, DotOperandLayout are all convenient <em>spellings</em> of such a function. They compile down to the same representation.</p><h3>The XOR trick</h3><p>Here’s the observation the entire system rests on. Write every coordinate in binary. Then essentially every layout real GPUs care about has this property:</p><blockquote><strong><em>Flipping one bit of the input flips a fixed set of output bits — the same set, no matter what the other input bits are.</em></strong></blockquote><p>Take the layout in our diagram earlier: each thread owns 2 adjacent elements, so going from lane 0 to lane 1 always moves you 2 elements along the array. Bit 0 of lane controls bit 1 of the index. Always. Unconditionally.</p><p>That property has a name: <strong>linearity over 𝔽₂</strong>, the two-element field, where addition is <strong>XOR</strong> (1 + 1 = 0, no carry) and multiplication is <strong>AND</strong>.</p><p>Why does that help so much? Because a linear map is <em>completely determined</em> by what it does to the basis vectors of its input space — and for “an integer viewed as bits”, the basis vectors are just the individual bits: 1, 2, 4, 8, 16…</p><p>So an entire layout collapses to a small list:</p><blockquote><strong><em>For each input bit, one vector saying which tensor coordinates that bit flips.</em></strong></blockquote><p>Those vectors are called the <strong>bases</strong>, listed least-significant-bit first. And evaluating the layout is a one-liner:</p><pre>index(reg, lane, warp, block) = XOR of every basis whose input bit is 1</pre><p>That’s the whole formalism. Now let’s actually do it.</p><h3>The worked example</h3><p>To keep every number on screen, we’ll invent a <strong>toy GPU</strong>: warps of <strong>4 lanes</strong>, and <strong>2 warps</strong>. (Real NVIDIA hardware has 32 lanes; we’ll switch to real numbers in a moment, and nothing changes but the digit count.)</p><p><strong>The goal.</strong> Spread a <strong>16-element array</strong> across those 8 threads, giving each thread <strong>2 adjacent</strong> elements. Adjacency is the point: two contiguous floats in one thread means the compiler can emit <em>one</em> 64-bit load instead of two 32-bit loads.</p><h3>Step 1 — check the budget</h3><pre>2 registers/thread  ×  4 lanes  ×  2 warps  =  16 hardware slots<br>   the tensor has                                 16 elements<br>   16 == 16  ✓  a perfect one-to-one mapping is possible</pre><p>In bits: 1 register bit + 2 lane bits + 1 warp bit = <strong>4 input bits</strong>. And log2(16) = <strong>4 output bits</strong>. Same count — a good sign.</p><h3>Step 2 — derive one basis per input bit</h3><p>For each hardware bit, ask exactly one question: <em>“If I flip only this bit, how far do I move in the tensor?”</em></p><pre>bit   why                                            moves you   basis<br> ────────────────────────────────────────────────────────────────────────<br> r0    a thread&#39;s two elements are adjacent               +1        [1]<br> l0    the next lane starts 2 elements later              +2        [2]<br> l1    two lanes further along = 2 × 2                    +4        [4]<br> w0    a whole warp covers 4 lanes × 2 elems = 8          +8        [8]</pre><p>That’s it. That is the layout:</p><pre>reg_bases  = [[1]]<br>lane_bases = [[2], [4]]<br>warp_bases = [[8]]<br>shape      = [16]</pre><p>Notice the strides form a clean doubling chain 1, 2, 4, 8. That&#39;s not a coincidence — each level of the hierarchy exactly consumes the one below it. Registers cover 2 elements, so lanes must step by 2; lanes cover 8, so warps must step by 8.</p><h3>Step 3 — evaluate one slot by hand</h3><p>Let’s ask: <strong>which element does register 1 of lane 2 in warp 1 hold?</strong></p><p>Write the coordinates in binary: reg = 1, lane = 2 = 0b10, warp = 1. Then select the bases whose bit is set, and XOR them:</p><pre>evaluate slot: reg=1 (0b1), lane=2 (0b10), warp=1 (0b1)<br>   r0: bit=1  basis=[1]<br>   l0: bit=0  basis=[2]   (bit clear -&gt; skipped)<br>   l1: bit=1  basis=[4]<br>   w0: bit=1  basis=[8]<br>   XOR of selected bases:<br>     dim0:  0001 ^ 0100 ^ 1000  =  1101 = 13<br>   =&gt; tensor index (13,)</pre><p><strong>Element 13.</strong> Let’s sanity-check against ordinary arithmetic: 8·warp + 2·lane + reg = 8 + 4 + 1 = 13. ✓</p><p>And notice <em>why</em> the check works: the selected bases were <strong>disjoint powers of two</strong>. No two of them share a bit, so there are no carries to lose, and XOR behaves exactly like +. This is the general rule — <em>when bases are disjoint powers of two, the layout is &quot;boring&quot; and XOR is just addition.</em> Most layouts you write are exactly this boring. XOR only earns its keep when bases overlap, which we&#39;ll come back to at the end.</p><h3>Step 4 — the full picture</h3><p>Evaluate all 16 slots and you get the complete ownership map:</p><pre>element   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15<br> ──────────────────────────────────────────────────────────<br> warp      0  0  0  0  0  0  0  0  1  1  1  1  1  1  1  1<br> lane      0  0  1  1  2  2  3  3  0  0  1  1  2  2  3  3<br> register  0  1  0  1  0  1  0  1  0  1  0  1  0  1  0  1<br> thread    0  0  1  1  2  2  3  3  4  4  5  5  6  6  7  7<br>                                          ^^^^^<br>                                     element 13 lives here</pre><p>Or per thread:</p><pre>t0  [0, 1]     t4  [8,  9]<br> t1  [2, 3]     t5  [10, 11]<br> t2  [4, 5]     t6  [12, 13]<br> t3  [6, 7]     t7  [14, 15]</pre><p>Each row of that strip is a direct read-out of one basis. register alternates every 1 element → basis [1]. lane changes every 2 → basis [2] and [4]. warp changes every 8 → basis [8]. The bases <em>are</em> the picture.</p><h3>Step 5 — the 𝔽₂ matrix</h3><p>Now the representation that makes the algebra possible. Lay the bases out as columns of a matrix: <strong>one row per output bit, one column per input bit.</strong></p><pre>F2 matrix: 4 output bits x 4 input bits<br>            r0  l0  l1  w0<br>     d0b0    1   .   .   .<br>     d0b1    .   1   .   .<br>     d0b2    .   .   1   .<br>     d0b3    .   .   .   1</pre><p>Reading the labels: d0b2 means <strong>dim 0, bit 2</strong> — the bit worth 4 in the index. A 1 at row d0b2, column l1 means <em>&quot;flipping lane bit 1 flips index bit 2.&quot;</em></p><p>There are three ways to read this matrix, and all three are useful:</p><ul><li><strong>Down a column</strong> (l0): <em>what does this hardware bit control?</em> The 1s are the index bits it flips.</li><li><strong>Across a row</strong> (d0b3): <em>what controls this index bit?</em> The 1s are the hardware bits that flip it.</li><li><strong>The shape:</strong> rows = log2(number of elements), columns = log2(number of hardware slots).</li></ul><p>Evaluation is now literally a matrix–vector product, with AND for multiply and XOR for sum:</p><pre>output_bits = M · input_bits</pre><p>And <strong>column <em>k</em> of M is just basis vector <em>k</em>, spelled out in binary.</strong> The matrix isn’t a new thing — it’s the basis list, transposed.</p><p>This particular matrix is the <strong>identity</strong>. Which tells us something crisp: the layout is nothing but a <em>relabelling of bits</em>. Concatenate the hardware bits in the order r0 l0 l1 w0 and you have the element index:</p><pre>index bits:   [ w0 | l1 l0 | r0 ]<br>                   ^^   ^^^^^   ^^<br>                  warp   lane   reg</pre><h3>Step 6 — run it yourself</h3><p>The whole formalism fits in 25 lines of dependency-free Python. Paste this into a file and run it:</p><pre>BASES = {                      # one entry per hardware bit, LSB first<br>    &quot;r0&quot;: [1],                 # register bit 0  -&gt; move 1 element<br>    &quot;l0&quot;: [2],                 # lane bit 0      -&gt; move 2 elements<br>    &quot;l1&quot;: [4],                 # lane bit 1      -&gt; move 4<br>    &quot;w0&quot;: [8],                 # warp bit 0      -&gt; move 8<br>}<br>NAMES = list(BASES)            # bit order: r0, l0, l1, w0<br><br>def evaluate(hw_bits, rank=1, verbose=True):<br>    &quot;&quot;&quot;hw_bits: an int whose bit i corresponds to NAMES[i].&quot;&quot;&quot;<br>    total = [0] * rank<br>    for i, name in enumerate(NAMES):<br>        on = (hw_bits &gt;&gt; i) &amp; 1<br>        if verbose:<br>            print(f&quot;  {name}: bit={on}  basis={BASES[name]}&quot;<br>                  f&quot;{&#39;&#39; if on else &#39;   (skipped)&#39;}&quot;)<br>        if on:<br>            for d in range(rank):<br>                total[d] ^= BASES[name][d]      # XOR, not +<br>    if verbose:<br>        print(f&quot;  =&gt; tensor index {tuple(total)}&quot;)<br>    return tuple(total)<br># reg=1, lane=2 (0b10), warp=1 -&gt; bits r0=1,l0=0,l1=1,w0=1 -&gt; 0b1101<br>print(&quot;slot reg=1, lane=2, warp=1:&quot;)<br>evaluate(0b1101)<br>print(&quot;\nownership map:&quot;)<br>for warp in range(2):<br>    for lane in range(4):<br>        for reg in range(2):<br>            bits = reg | (lane &lt;&lt; 1) | (warp &lt;&lt; 3)<br>            elem = evaluate(bits, verbose=False)[0]<br>            print(f&quot;  warp={warp} lane={lane} reg={reg} -&gt; element {elem}&quot;)</pre><p>Output:</p><pre>slot reg=1, lane=2, warp=1:<br>  r0: bit=1  basis=[1]<br>  l0: bit=0  basis=[2]   (skipped)<br>  l1: bit=1  basis=[4]<br>  w0: bit=1  basis=[8]<br>  =&gt; tensor index (13,)<br><br>ownership map:<br>  warp=0 lane=0 reg=0 -&gt; element 0<br>  warp=0 lane=0 reg=1 -&gt; element 1<br>  warp=0 lane=1 reg=0 -&gt; element 2<br>  ...<br>  warp=1 lane=3 reg=1 -&gt; element 15</pre><p>Change one basis and re-run. That’s the entire mental model, and you now own it.</p><h3>Step 7 — the same thing, on a real GPU</h3><p>Swap the toy machine for real NVIDIA hardware — 32 lanes, 4 warps, 2 registers per thread, a [256] array — and <em>nothing changes but the digit count</em>:</p><pre>LinearLayout(shape=[256],<br>             reg_bases=[[1]],<br>             lane_bases=[[2], [4], [8], [16], [32]],<br>             warp_bases=[[64], [128]])<br><br>F2 matrix: 8 output bits x 8 input bits<br>            r0  l0  l1  l2  l3  l4  w0  w1<br>     d0b0    1   .   .   .   .   .   .   .<br>     d0b1    .   1   .   .   .   .   .   .<br>     d0b2    .   .   1   .   .   .   .   .<br>     d0b3    .   .   .   1   .   .   .   .<br>     d0b4    .   .   .   .   1   .   .   .<br>     d0b5    .   .   .   .   .   1   .   .<br>     d0b6    .   .   .   .   .   .   1   .<br>     d0b7    .   .   .   .   .   .   .   1</pre><p>Same doubling chain, same identity matrix, closed form index = 64·warp + 2·lane + reg. Register 1 of lane 13 in warp 2:</p><pre>evaluate slot: reg=1 (0b1), lane=13 (0b01101), warp=2 (0b10)<br>   r0: bit=1  basis=[1]<br>   l0: bit=1  basis=[2]<br>   l1: bit=0  basis=[4]     (skipped)<br>   l2: bit=1  basis=[8]<br>   l3: bit=1  basis=[16]<br>   l4: bit=0  basis=[32]    (skipped)<br>   w0: bit=0  basis=[64]    (skipped)<br>   w1: bit=1  basis=[128]<br>   dim0: 00000001 ^ 00000010 ^ 00001000 ^ 00010000 ^ 10000000<br>       = 10011011 = 155<br> =&gt; tensor index (155,)</pre><p>Cross-check: 64·2 + 2·13 + 1 = 155. ✓</p><p>And this exact layout is what BlockedLayout(size_per_thread=[2], threads_per_warp=[32], warps_per_cta=[4], order=[0]) compiles to. The friendly wrapper and the bases are the same object.</p><h3>Step 8 — why any of this mattered</h3><p>Three performance facts fall straight out of the bases:</p><ul><li>Each thread’s two elements are <strong>contiguous</strong> (reg_bases=[[1]]) → the compiler emits one ld.global.v2.f32 instead of two scalar loads.</li><li>Consecutive lanes hold consecutive 8-byte chunks (lane_bases start at [2]) → lanes 0–31 cover 256 contiguous bytes → <strong>fully coalesced</strong>, one or two memory transactions.</li><li>256 elements in 256 slots, one each → no register wasted on duplicate data.</li></ul><p>Now change one number. Keep everything else, but make the register basis [[128]]:</p><pre>LinearLayout(shape=[256],<br>             reg_bases=[[128]],                       # &lt;-- the only change<br>             lane_bases=[[1], [2], [4], [8], [16]],<br>             warp_bases=[[32], [64]])<br><br><br>distinct elements reached: 256/256   (each element in 1 slot = bijection)<br> thread -&gt; elements it owns:<br>   t0    [0, 128]<br>   t1    [1, 129]<br>   t2    [2, 130]<br>   t127  [127, 255]</pre><p><strong>Still a perfect bijection.</strong> Still covers every element exactly once. And meaningfully worse: each thread’s two values are 128 elements apart, so there is nothing to vectorise — twice the memory instructions for the same data.</p><p>Identical coverage, different performance. <em>That</em> is the decision Gluon puts in your hands, and it is invisible in classic Triton.</p><h3>Example 2 — two dimensions</h3><p>Same machine, now an <strong>8×8 tile</strong>, 4 warps of 8 lanes, each thread holding 2 elements adjacent <strong>along dim 1</strong> (the columns — the contiguous direction in a row-major tensor) so loads still vectorise.</p><p>In BlockedLayout terms: size_per_thread=[1,2], threads_per_warp=[2,4], warps_per_cta=[4,1], order=[1,0].</p><pre>size_per_thread  [1, 2]   each thread holds a 1×2 patch (1 row, 2 cols)<br> threads_per_warp [2, 4]   the 8 lanes form a 2×4 grid of those patches<br> warps_per_cta    [4, 1]   the 4 warps stack vertically<br> order            [1, 0]   dim 1 is fastest-varying: fill dim 1 bits first</pre><p>Now each basis is a <strong>vector with one entry per tensor dimension</strong> — [d0, d1]. Deriving them, consuming dim 1 first as order demands:</p><pre>bit   dim   why                                        basis [d0, d1]<br> ─────────────────────────────────────────────────────────────────────<br> r0     1    the 2 elements per thread are adjacent cols   [0, 1]<br> l0     1    next lane = next 2-col patch -&gt; +2 cols       [0, 2]<br> l1     1    two patches -&gt; +4 cols. dim 1 now full (8)    [0, 4]<br> l2     0    dim 1 exhausted -&gt; move down a row            [1, 0]<br> w0     0    one warp covers 2 rows -&gt; next warp is +2     [2, 0]<br> w1     0    two warps -&gt; +4 rows                          [4, 0]</pre><pre>LinearLayout(shape=[8, 8],<br>             reg_bases=[[0, 1]],<br>             lane_bases=[[0, 2], [0, 4], [1, 0]],<br>             warp_bases=[[2, 0], [4, 0]])</pre><p>The matrix:</p><pre>F2 matrix: 6 output bits x 6 input bits<br>            r0  l0  l1  l2  w0  w1<br>     d0b0    .   .   .   1   .   .<br>     d0b1    .   .   .   .   1   .<br>     d0b2    .   .   .   .   .   1<br>     d1b0    1   .   .   .   .   .<br>     d1b1    .   1   .   .   .   .<br>     d1b2    .   .   1   .   .   .</pre><p>This is a <strong>permutation matrix</strong> — still exactly one 1 per row and per column, but shuffled relative to the identity. That shuffle <em>is</em> the layout: the low hardware bits (r0, l0, l1) drive the <strong>column</strong> index, the high bits (l2, w0, w1) drive the <strong>row</strong> index. Flipping order to [0,1] would swap those two blocks.</p><p>Evaluating lane 5 (0b101) of warp 1, register 0:</p><pre>evaluate slot: reg=0 (0b0), lane=5 (0b101), warp=1 (0b01)<br>   r0: bit=0  basis=[0, 1]   (skipped)<br>   l0: bit=1  basis=[0, 2]<br>   l1: bit=0  basis=[0, 4]   (skipped)<br>   l2: bit=1  basis=[1, 0]<br>   w0: bit=1  basis=[2, 0]<br>   w1: bit=0  basis=[4, 0]   (skipped)<br>   XOR of selected bases:<br>     dim0:  000 ^ 001 ^ 010  =  011 = 3<br>     dim1:  010 ^ 000 ^ 000  =  010 = 2<br>   =&gt; tensor index (3, 2)</pre><p>Look at how the two dimensions were computed <strong>completely independently</strong> — each dim gets its own XOR column, and no hardware bit contributed to both. That independence is precisely what the permutation structure told us in advance.</p><p>Here’s who owns what:</p><pre>owning thread for each (row, col):<br>         c0   c1   c2   c3   c4   c5   c6   c7<br>   r0    0    0    1    1    2    2    3    3<br>   r1    4    4    5    5    6    6    7    7<br>   r2    8    8    9    9    10   10   11   11<br>   r3    12   12   13   13   14   14   15   15<br>   r4    16   16   17   17   18   18   19   19<br>   r5    20   20   21   21   22   22   23   23<br>   r6    24   24   25   25   26   26   27   27<br>   r7    28   28   29   29   30   30   31   31</pre><p>Three observations, each traceable to exactly one basis:</p><ol><li><strong>Every thread number appears twice, side by side.</strong> That’s reg_bases=[[0,1]]: one thread, two adjacent columns → vectorised load. ✓</li><li><strong>Each row holds 4 distinct threads, ascending left to right.</strong> That’s lane_bases [0,2] and [0,4]: lanes sweep across a row → consecutive lanes, consecutive addresses → coalesced. ✓</li><li><strong>Row <em>r</em> starts at thread </strong><strong>4r.</strong> Rows 0–1 are threads 0–7 = warp 0, rows 2–3 are warp 1, and so on. That&#39;s l2=[1,0] (2 rows within a warp) plus w0=[2,0], w1=[4,0] (warps stacked in 2-row bands). ✓</li></ol><p>And now the algorithmic consequence: <strong>each warp owns a contiguous 2×8 horizontal band.</strong> That’s a great shape for a row-wise reduction — every warp reduces its own rows with no cross-warp communication. It’s a bad shape for a column-wise reduction — every column spans all four warps, forcing a shared-memory round trip.</p><p>Layout choice <em>is</em> algorithm choice.</p><h3>Two more things the bases can say</h3><p>The two examples above are the layouts you’ll write 95% of the time. Two further tricks are worth being able to recognise when you meet them in TTGIR, and each is a one-line change to the bases.</p><p><strong>A zero basis means broadcast.</strong> A basis of all zeros says <em>“flipping this hardware bit moves you nowhere in the tensor”</em> — so two hardware slots hold the same element. That’s how Triton represents the result of a reduction: reduce a [16,16] tile along dim 1 and the 16 answers sit replicated across all 128 threads.</p><pre>LinearLayout(shape=[16],<br>             lane_bases=[[1], [2], [4], [8], [0]],  # l4 moves nowhere<br>             warp_bases=[[0], [0]])                 # every warp identical</pre><p>Three zero bases → 2³ = 8 copies of every element. Why you care: in softmax, the row-sum you divide by is <em>already</em> sitting in every thread that needs it — no shuffle, no shared memory. Triton knows that because the zero bases say so. (The zeros are mandatory, not optional: lane_bases must have exactly log2(warp_size) entries — 5 on NVIDIA — so padding with [0] is <em>how</em> you spell replication.)</p><p><strong>Two 1s in one column means a swizzle.</strong> Every basis so far touched one dimension. But nothing stops one hardware bit from flipping bits in <em>two</em> dimensions at once — say l0 = [1, 2], which moves you down one row <em>and</em> XORs 2 into the column. Do that systematically and you get physical_col = logical_col XOR f(row): every row&#39;s columns permuted differently. That is exactly the classical bank-conflict-avoiding shared-memory swizzle. (Without it, 32 lanes reading a column of a row-major tile all land in the same one of SMEM&#39;s 32 banks and serialise 32×.)</p><p>This is where XOR stops being a curiosity. Adding 2 to a column that already holds 2 gives 4, and eventually overflows the column range; XOR-ing gives 0 — it <em>cancels</em>, there are no carries, and the map stays a perfect bijection for free. It’s also why ttgl.SwizzledSharedLayout and ttgl.NVMMASharedLayout use the same formalism as register layouts: a swizzle isn&#39;t a feature bolted on, it&#39;s just a linear layout whose bases overlap. And it&#39;s the reason DistributedLinearLayout exists at all — BlockedLayout is a hierarchy of nested rectangular tilings, which always gives exactly one 1 per row, so it can never produce a column with two.</p><h3>Patterns you learn to recognise at a glance</h3><p>You just met all of these:</p><pre>identity matrix          simplest blocked layout: hw bit i is index bit i<br> permutation matrix       still blocked, different order / tiling<br> all-zero column          that hw bit changes nothing -&gt; BROADCAST<br> two 1s in one column     XOR coupling -&gt; a SWIZZLE. Not a BlockedLayout.<br> square and invertible    perfect bijection: no waste, no duplication<br> more columns than rank   redundant slots -&gt; replication<br> rank &lt; number of rows    layout does NOT cover the tensor. Bug.</pre><h3>Why bother with an algebra at all?</h3><p>Fair question. A layout is, in full generality, an arbitrary function (reg, lane, warp, block) → index. You could just store it as a lookup table. For a [128,128] tile on 8 warps that&#39;s 16,384 entries — per layout, per shape.</p><p>That representation answers exactly one question (“what does slot <em>i</em> hold?”) and nothing else usefully:</p><ul><li><em>Do these two layouts agree?</em> → compare 16,384 entries.</li><li><em>Compose the shared-memory layout with the register layout?</em> → 16,384 chained lookups.</li><li><em>Which thread owns element (37, 12)?</em> → brute-force scan.</li><li><em>Does this generalise to a </em><em>[256,128] tile?</em> → it doesn&#39;t. Build a new table.</li></ul><p>A compiler cannot work like that. Layout queries happen inside optimisation passes, thousands of times, and the answers must be symbolic, exact and cheap. So you don’t represent arbitrary functions — you pick a <em>restricted class</em> with good algebraic properties, and design the abstraction to stay inside it.</p><p>𝔽₂-linear maps are that class, and the reason is that GPUs are built out of powers of two and move data with exactly the operations 𝔽₂-linear maps are generated by: <strong>select bits</strong> (deriving row/col from a thread index), <strong>permute bits</strong> (prmt), <strong>XOR bits</strong> (butterfly shuffles, SMEM swizzling), <strong>group low bits</strong> (vectorised access), and <strong>ignore bits</strong> (broadcast). The class isn&#39;t an approximation of what GPUs do — it&#39;s the algebraic closure of the primitives they give you.</p><p>And then every compiler question becomes a matrix question:</p><pre>does this layout cover the tensor?      rank == number of output bits<br> how replicated is the data?             2^(dim of null space)<br> which thread owns element x?            solve M·s = x<br> are these two layouts identical?        matrix equality (so a no-op<br>                                         convert_layout can be deleted)<br> layout of a tile read from SMEM         matrix product of the two layouts<br> broadcast [N] to [M,N]?                 extend with zero bases — free</pre><p>Notice the pattern: the <em>questions</em> are about memory systems and instruction selection; the <em>answers</em> are all rank, null space, product and solve. A handful of routines covers the whole surface. Each of those rows used to be a bespoke special case in Triton’s C++, written once per layout <em>pair</em> — an O(n²) maintenance problem. That compression is why the representation replaced thousands of lines of pairwise logic.</p><p><strong>The honest cost of the restriction:</strong> power-of-two shapes only (non-power-of-two tiles get padded and masked, outside the layout system), and no non-power-of-two strides — a stride of 3 is not 𝔽₂-linear, so Triton handles arbitrary tensor strides in pointer arithmetic instead. A flat bit list also loses explicit hierarchy: “a 4×2 tile of 8×8 tiles” is <em>implicit</em> in how the bits group, not stated. Readable to a compiler, less readable to you — which is exactly why the BlockedLayout sugar still exists.</p><h3>Using a hand-written layout for real</h3><pre>import torch, triton<br>from triton.experimental import gluon<br>from triton.experimental.gluon import language as ttgl<br><br>@gluon.jit<br>def add_kernel(x_ptr, y_ptr, out_ptr,<br>               BLOCK: ttgl.constexpr, layout: ttgl.constexpr):<br>    offs = ttgl.arange(0, BLOCK, layout=layout)   # layout REQUIRED<br>    x = ttgl.load(x_ptr + offs)      # propagates through pointer arithmetic<br>    y = ttgl.load(y_ptr + offs)<br>    ttgl.store(out_ptr + offs, x + y)   # x and y must share a layout<br><br>coalesced = ttgl.DistributedLinearLayout(<br>    reg_bases=[[1]],<br>    lane_bases=[[2], [4], [8], [16], [32]],<br>    warp_bases=[[64], [128]],<br>    block_bases=[],<br>    shape=[256],<br>)<br>x = torch.randn(256, device=&quot;cuda&quot;)<br>y = torch.randn(256, device=&quot;cuda&quot;)<br>out = torch.empty_like(x)<br>add_kernel[(1,)](x, y, out, BLOCK=256, layout=coalesced, num_warps=4)</pre><p>The verifier enforces: each basis vector has one entry per tensor dimension; len(lane_bases) == log2(warp_size) exactly; len(warp_bases) == log2(num_warps) from the launch config; shape dims are powers of two. And a DistributedLinearLayout is tied to <strong>one shape</strong>, unlike BlockedLayout, which is a reusable recipe. In TTGIR it prints as:</p><pre>#ttg.linear&lt;{register = [[1]], lane = [[2],[4],[8],[16],[32]],<br>             warp = [[64],[128]], block = []}&gt;</pre><p>Two things to internalise.</p><p><strong>Layouts are </strong><strong>constexpr.</strong> They&#39;re compile-time values, part of the tensor&#39;s type. Changing a basis triggers a recompile, and the layout participates in the cache key.</p><p><strong>Mismatches are explicit.</strong> x + y with different layouts is a compile error, never an implicit shuffle. To move data between layouts, you say so:</p><pre>strided = ttgl.DistributedLinearLayout(<br>    reg_bases=[[128]],                      # same 256 elements,<br>    lane_bases=[[1], [2], [4], [8], [16]],  # different assignment<br>    warp_bases=[[32], [64]],<br>    block_bases=[],<br>    shape=[256],<br>)<br>z = ttgl.convert_layout(x, strided)   # lowers to shuffles / SMEM roundtrip</pre><p>The compiler works out the data movement by composing the two 𝔽₂ matrices — and the cost follows directly from <em>which</em> bits differ:</p><pre>only reg_bases differ          FREE — renaming registers at compile time<br> within lane_bases (same warp)  shfl / prmt instructions<br> across warp_bases              shared-memory round trip + barrier<br> across block_bases             distributed shared memory (Hopper+), or worse</pre><p>That cost model is visible to you precisely <em>because</em> the layouts are.</p><h3>When to hand-write a linear layout</h3><p>Most of the time: don’t. Use the sugar — BlockedLayout, SliceLayout, NVMMADistributedLayout, NVMMASharedLayout, AutoLayout(). They&#39;re shorter, self-documenting and shape-generic.</p><h3>Pitfalls, and what they actually mean</h3><pre> expected N lane bases          len(lane_bases) must equal log2(warp_size)<br>                                EXACTLY — 5 on NVIDIA, 6 on AMD CDNA.<br>                                Pad with [0,...] to broadcast.<br> expected N warp bases          must equal log2(num_warps) from the launch.<br>                                Changing num_warps invalidates the layout.<br> covers only half the tensor    matrix rank &lt; number of output bits<br> unexpected register pressure   accidental replication from an unintended<br>                                zero basis — duplicate values per thread<br> loads not vectorising          reg_bases aren&#39;t contiguous along the fastest<br>                                dim. You want [[1]], not [[128]].<br> uncoalesced loads              consecutive lanes map to distant addresses.<br>                                Check the low lane_bases step.<br> bank conflicts in SMEM         you need XOR coupling, or just<br>                                SwizzledSharedLayout<br> basis length mismatch          one entry per TENSOR DIMENSION, not per<br>                                hardware level<br> non-power-of-2 shape rejected  pad the tile and mask</pre><h3>A footnote for the CUTLASS crowd</h3><p>If this design feels familiar, it should:</p><blockquote><strong><em>Gluon is to Triton what CuTe is to CUDA.</em></strong></blockquote><p>Both ecosystems hit the same wall from opposite directions. CUDA gave you total control but no tile abstraction, so CUTLASS 3.x introduced <strong>CuTe</strong> — Layout objects describing placement algebraically. Triton started with a great tile abstraction and hidden placement, and added Gluon so you can pin the placement down. Both converged on <em>&quot;make the layout a first-class, composable, algebraic object.&quot;</em> That convergence is decent evidence this is the right abstraction, not a quirk of either project.</p><p>The one real difference is the number system. CuTe is <strong>affine over the integers</strong> (shapes and strides, evaluated by inner product), so it can express a stride of 3 — Triton can’t. Triton is <strong>linear over 𝔽₂</strong> (bases, evaluated by XOR), so col = col XOR row is just another layout — while CuTe needs Swizzle&lt;B,M,S&gt; as a separate composed functor. Two opposite trade-offs on the same axis.</p><h3>Takeaways</h3><ol><li><strong>Gluon is Triton with the layout decisions handed back to you.</strong> Same JIT, same autotuner, same launcher — you just also write down where the data lives, and the compiler verifies it instead of guessing.</li><li><strong>A layout is a function</strong> from (register, lane, warp, block) to a tensor coordinate. That&#39;s all it ever is.</li><li><strong>That function is linear over bits.</strong> So it’s fully described by “for each hardware bit, where does flipping it move me?” — a short list of <strong>bases</strong>.</li><li><strong>Evaluate by XOR-ing the bases whose bit is set.</strong> Six lines of Python. You wrote it above.</li><li><strong>Write the bases as matrix columns and every question becomes linear algebra.</strong> Zero column = broadcast. Two 1s in a column = swizzle. Rank &lt; rows = bug.</li><li><strong>Coverage is not correctness.</strong> Two layouts can both be perfect bijections and differ by 2× in memory instructions. That difference is the entire reason Gluon exists.</li></ol><p>Don’t reach for Gluon first. Write Triton, profile, dump TTGIR, and port only the hot kernel — with a layout you chose on purpose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dd2f13db2bf" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/which-thread-holds-which-number-7dd2f13db2bf">Which Thread Holds Which Number?</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SGLang-Omni: The Model Was Never the Hard Part]]></title>
            <link>https://pub.towardsai.net/sglang-omni-the-model-was-never-the-hard-part-062a2d24af05?source=rss-4354164acdff------2</link>
            <guid isPermaLink="false">https://medium.com/p/062a2d24af05</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[sglang]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[inference]]></category>
            <dc:creator><![CDATA[Aadishagrawal]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 19:14:01 GMT</pubDate>
            <atom:updated>2026-09-08T05:34:59.513Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How SGLang serves a model that sees, hears, and talks back — and why it needed a whole new runtime on top of SGLang.</em></h4><h3>The misconception I started with</h3><p>When I first heard about <strong>SGLang-Omni</strong>, I assumed I knew what it was.</p><p>SGLang, the core project, is famous for making a single large language model <em>fast</em> — RadixAttention for KV-cache reuse, speculative decoding, a zero-overhead scheduler, all the clever tricks that squeeze more tokens per second out of a GPU. So “Omni,” I figured, must be the same bag of tricks applied to other modalities. Some radix-cache-like reuse for audio. Some speculative decoding for image tokens. Modality-specific algorithmic wins.</p><p>That guess was wrong, and the way it was wrong turned out to be the interesting part.</p><p>SGLang-Omni is <strong>not</strong> a set of per-modality algorithm optimizations. It’s a <strong>systems-level orchestration play</strong>. Its whole reason to exist is to take a model that isn’t one model at all — it’s a little committee of models that talk to each other — and <em>decouple</em> it into independent stages, so you can:</p><ul><li>put each stage on the right hardware,</li><li>give each stage the scheduler it actually needs,</li><li>scale up only the stage that’s the bottleneck,</li><li>and contain a crash to one stage instead of taking down the whole request.</li></ul><p>In other words, the hard problem was never “make the model faster.” The model math was mostly already solved. The hard problem was <strong>serving</strong> it: how do you run a graph of cooperating models, streaming state between them in real time, across multiple GPUs, without the whole thing turning into a tangle?</p><p>This post walks through how SGLang-Omni answers that, using <strong>Qwen3-Omni</strong> as the running example. We’ll follow one request from HTTP call to audio waveform, and along the way see why a plain script couldn’t do the job, how the pipeline is wired, and — importantly — how Omni leans on plain old SGLang for the heavy lifting rather than reinventing it.</p><h3>What Qwen3-Omni actually demands</h3><p>To see why Omni needed a new runtime, you have to look at what a modern omni-modal model actually <em>is</em>. Core SGLang is built to serve <em>one</em> autoregressive model behind one scheduler and one KV cache. Qwen3-Omni is a committee.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N7afOks_GKAoBniYGPObwQ.png" /><figcaption><strong>Diagram 1 — The mental shift: one model vs a pipeline of stages.</strong></figcaption></figure><p>Qwen3-Omni isn’t a single autoregressive model. It’s built around <strong>two large decode backbones</strong> that hand off to each other:</p><ul><li><strong>Thinker</strong> — the “understanding” brain. It takes text, images, video, and audio, fuses them, and generates text tokens. This is where the reasoning lives.</li><li><strong>Talker</strong> — the “speaking” brain. It takes Thinker’s output <em>as it’s being produced</em> and turns it into a stream of speech codec tokens, which a vocoder later turns into an actual waveform.</li></ul><p>Around those two, there’s a supporting cast: a vision encoder, an audio encoder, an aggregation step, a code predictor that fills in the fine detail of the audio codes, and a final vocoder. But the two things that dominate everything are Thinker and Talker.</p><p>Here’s what makes this genuinely different from serving one LLM:</p><ul><li><strong>Two backbones of roughly equal size.</strong> This is the crux. It’s not “one big model plus some small helpers.” Thinker and Talker are both heavy, both need continuous batching, both maintain a KV cache. The moment you have two comparably-sized models, you have a <em>placement and resource-partitioning</em> problem: do they share a GPU or not? If they share, how do you split GPU memory and KV cache between them — is 50/50 even right? If they don’t, how do you coordinate the traffic between devices? This is the real engineering pressure, far more than “supporting a vocoder.”</li><li><strong>Dual output.</strong> A single request can produce <em>two</em> results — a text answer <em>and</em> an audio answer. The system can’t just return whichever finishes first; it has to gather both.</li><li><strong>Real streaming between models.</strong> Talker doesn’t wait for Thinker to finish. It consumes Thinker’s hidden states token by token, so audio can start playing while the text is still being generated.</li><li><strong>A feedback loop.</strong> Talker and the Code Predictor play ping-pong: Talker emits one codec token, waits for the Code Predictor to send back an aggregated embedding, and only then takes its next step.</li></ul><p>None of these is a “just add a component” problem. They’re all about <strong>timing and coordination</strong> — who can run when, who’s waiting on whom, and where the intermediate state lives. That’s a scheduling and dataflow problem, and it’s exactly the kind of thing a single-model server isn’t built to express.</p><h3>Why a serial script — or even asyncio — can’t do it</h3><p>The natural first reaction is: <em>if core SGLang doesn’t handle this, why not just write a function that chains the models together?</em></p><pre># The most naive serial approach<br>def process_request(request):<br>    state        = preprocess(request)                 # CPU<br>    image_embeds = image_encoder(state)                # GPU<br>    audio_embeds = audio_encoder(state)                # GPU — only starts after image_encoder finishes<br>    merged       = aggregate(state, image_embeds, audio_embeds)  # CPU<br>    text_tokens  = thinker(merged)                     # GPU:0 — next step only after thinker fully finishes<br>    text_result  = decode(text_tokens)                 # CPU<br>    codec_tokens = talker(text_tokens)                 # GPU:1 — only starts after thinker fully finishes<br>    codes        = code_predictor(codec_tokens)        # GPU:1<br>    audio        = code2wav(codes)                     # GPU:1<br>    return text_result, audio</pre><p>This <em>runs</em>. It’s also a performance disaster, and the reason is subtle enough to be worth a number.</p><p>Talker has to wait until Thinker is completely done before it starts. Say Thinker generates 100 tokens at 30 ms each, and Talker takes 20 ms per step. Serial time-to-first-audio is roughly <strong>3000 ms + 20 ms ≈ 3020 ms</strong>. But if Talker could consume Thinker’s tokens <em>as they arrive</em>, time-to-first-audio drops to about <strong>30 ms + 20 ms ≈ 50 ms</strong>. That’s a ~60× difference in perceived latency, and it comes entirely from <em>overlapping</em> work that the serial version forces into a line.</p><p>So the next instinct is: <em>fine, use asyncio, fire the encoders off in parallel, stream Thinker into Talker.</em> That’s better — it at least admits the stages can advance concurrently. But single-process async only pushes the real problems back one layer. Five of them survive:</p><ol><li><strong>GPU-memory isolation.</strong> Thinker is on GPU:0, Talker on GPU:1. Managing multiple large models across multiple GPUs <em>in one process</em> couples their CUDA contexts, memory allocation, and error handling. One model’s OOM becomes everyone’s problem. Separate processes give each stage its own clean device view.</li><li><strong>Different scheduling policies.</strong> Thinker needs continuous batching, KV-cache management, and dynamic batch changes. The Code Predictor is a lightweight step-by-step forward. Cramming both into one scheduler means either a monstrous unified abstraction or a pile of special-cased local logic. Split into stages, each stage picks the executor and policy that fits it.</li><li><strong>Fault isolation.</strong> In production, one model hanging or crashing shouldn’t kill the whole request chain. Process boundaries turn a stage crash into a <em>stage</em> crash.</li><li><strong>Bottleneck-only scaling.</strong> If Thinker is the bottleneck, you want to scale <em>just Thinker</em>. If a request doesn’t need speech, you want to drop Talker / Code Predictor / vocoder entirely. Stages make that a config change, not a rewrite.</li><li><strong>Control/data separation.</strong> Multi-process doesn’t <em>have</em> to mean “copy tensors everywhere.” The trick — which we’ll get to — is to send tiny <em>metadata</em> between stages (“the data is at this shared-memory slot”) while the big tensors move over shared memory or CUDA IPC, near zero-copy.</li></ol><p>Put together, these push you toward a specific shape: a <strong>multi-process, asynchronous producer–consumer pipeline</strong>, where each stage is its own process, upstream stages produce incremental results, and downstream stages consume them at their own pace.</p><p>That shape is SGLang-Omni.</p><h3>The answer: a pipeline of stages</h3><p>At the top, SGLang-Omni is three layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Md3BX4sVzNTFNCyakIRd6Q.png" /><figcaption><strong>Diagram 2 — The three-layer runtime.</strong></figcaption></figure><ul><li><strong>The Coordinator</strong> is the front door and the mailroom. It does exactly three things: wrap the incoming request and hand it to the first stage; wait for the terminal stages to report back and merge their results; and, if the user disconnects, broadcast an “abort” to everyone. Crucially, <strong>it does not route between stages</strong> — it doesn’t decide “where does the encoder’s output go next.” Each stage decides that for itself via its own get_next. The Coordinator is a gatekeeper and a gatherer, not a traffic cop.</li><li><strong>Stage → Worker → Executor</strong> is where a request actually gets computed. The <em>Stage</em> is a runtime shell: it receives messages, aggregates inputs when several upstream stages feed into it, and manages routing. The <em>Worker</em> is the execution unit inside a stage. The <em>Executor</em> is the thing that finally calls the model.</li><li><strong>Control plane + Data plane</strong> is how stages communicate — and this split is the single most important idea in the whole system.</li></ul><h3>The waiter and the food runner</h3><p>Here’s the intuition. In a restaurant, the <strong>waiter</strong> carries the <em>order ticket</em> — small, fast, “table 4 wants the salmon.” The <strong>food runner</strong> carries the <em>plate</em> — big, heavy, needs care. You don’t make the waiter carry plates, and you don’t make the runner memorize orders.</p><p>SGLang-Omni splits communication exactly this way:</p><ul><li><strong>Control plane (ZMQ):</strong> the order tickets. Tens of bytes, microsecond latency. “Stage A finished; the result for request 7 is sitting in shared-memory slot 2.” That’s it.</li><li><strong>Data plane (the Relay):</strong> the plates. The actual tensors — encoder outputs, hidden states — move over shared memory, CUDA IPC, or NCCL, essentially zero-copy. They never touch ZMQ.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kl31nFSQvNQNqS3xcJwqdw.png" /><figcaption><strong>Diagram 3 — Control plane vs data plane, and the credit system.</strong></figcaption></figure><p>The reason to separate them is that notifications and bulk data have opposite requirements. ZMQ is great for small control messages and terrible for moving giant tensors; shared memory and CUDA IPC are the reverse. Try to make one channel do both and you do neither well.</p><p>The Relay also needs <em>flow control</em>, and it uses a beautifully simple mechanism: <strong>credits</strong>, which is really just a semaphore. Picture a fixed number of serving trays between two kitchen stations — say two trays. A “credit” is an empty tray.</p><ul><li>Upstream wants to send data → it takes a credit (grabs a tray), writes the tensor into that shared-memory slot, and sends a “data ready” ticket over ZMQ.</li><li>Downstream reads the data → releases the credit (returns the tray) so upstream can reuse the slot.</li><li>When all trays are full and downstream hasn’t caught up → upstream <em>blocks</em>. That’s <strong>backpressure</strong>, and it’s exactly what you want: a slow downstream naturally throttles a fast upstream instead of blowing up memory.</li></ul><p>This is why downstream stages are built to read incoming data as fast as they can — every read frees a tray and keeps the line moving.</p><h3>Add a model without touching the backbone</h3><p>One design choice makes this framework more than a Qwen3-Omni special case: the pipeline topology isn’t hardcoded. It’s <strong>declarative config</strong>. A model doesn’t inherit a fixed set of steps — it <em>declares its own stage graph</em>, and the framework compiles that into a runnable pipeline.</p><pre># sglang_omni/models/qwen3_omni/config.py  (trimmed)<br>class Qwen3OmniSpeechPipelineConfig(PipelineConfig):<br>    entry_stage     = &quot;preprocessing&quot;<br>    terminal_stages = [&quot;decode&quot;, &quot;code2wav&quot;]        # two ends: text + speech<br>    gpu_placement   = {&quot;thinker&quot;: 0, &quot;talker_ar&quot;: 1, &quot;code_predictor&quot;: 1, &quot;code2wav&quot;: 1}<br>    stages = [<br>        StageConfig(&quot;preprocessing&quot;, get_next=preprocessing_next, ...),<br>        StageConfig(&quot;image_encoder&quot;, get_next=encoder_next, ...),<br>        StageConfig(&quot;audio_encoder&quot;, get_next=encoder_next, ...),<br>        StageConfig(&quot;mm_aggregate&quot;,  get_next=aggregate_next,<br>                    input_handler=AggregatedInput(sources=[&quot;preprocessing&quot;,<br>                                                           &quot;image_encoder&quot;,<br>                                                           &quot;audio_encoder&quot;])),<br>        StageConfig(&quot;thinker&quot;, get_next=thinker_next_speech,<br>                    stream_to=[&quot;talker_ar&quot;]),               # stream hidden states<br>        StageConfig(&quot;decode&quot;, get_next=None),               # terminal<br>        StageConfig(&quot;talker_ar&quot;, get_next=talker_ar_next,<br>                    stream_to=[&quot;code_predictor&quot;]),<br>        StageConfig(&quot;code_predictor&quot;, get_next=code_predictor_next,<br>                    stream_to=[&quot;code2wav&quot;, &quot;talker_ar&quot;]),   # dual path: output + feedback<br>        StageConfig(&quot;code2wav&quot;, get_next=None),             # terminal<br>    ]</pre><p>Notice how much of the system’s behavior is <em>data</em> here: which stage is the entry, which are terminals, which GPU each stage lives on, which stages stream to which. compile_pipeline() turns this into live processes.</p><p>The payoff showed up when the team later added <strong>Ming-Omni</strong>, whose speech path uses a completely different approach (CFM/DiT flow-matching instead of Qwen3-Omni’s RVQ codec). The framework backbone barely changed — they wrote a new PipelineConfig and the model-specific executors, and the pipeline machinery just carried it. Model differences got pushed into config and executors, not into the runtime&#39;s core. There&#39;s even a <em>variant</em> mechanism so the same model can expose a 6-stage text-only pipeline and a 9-stage text-plus-speech pipeline, chosen at startup with --variant speech.</p><h3>Walk one request through the nine stages</h3><p>Let’s follow a “text + image + audio” request through Qwen3-Omni’s full speech pipeline. With speech output on, it’s <strong>nine stages</strong>:</p><pre>STAGE            ROLE               DEVICE   WHAT IT DOES<br>─────────────    ────────────────   ──────   ────────────────────────────────────────────────────<br>preprocessing    Entry              CPU      Tokenize text; parse image/audio/video into tensors<br>image_encoder    Encode             GPU      Vision Transformer → image embeddings<br>audio_encoder    Encode             GPU      Mel-spectrogram encoder → audio embeddings<br>aggregate        Fan-in             CPU      Merge text tokens with encoder outputs into one input<br>thinker          Inference          GPU:0    MoE Transformer; generates text tokens (then fans out)<br>decode           Output (terminal)  CPU      Turn token ids back into text<br>talker_ar        Speech             GPU:1    Autoregressively generate speech codec tokens<br>code_predictor   Speech             GPU:1    Fill in remaining RVQ code layers (feedback loop)<br>code2wav         Speech (terminal)  GPU:1    Vocoder synthesizes the final audio waveform</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fh03Xc9-XUfgLccIfzLNrw.png" /><figcaption><strong>Diagram 4 — The Qwen3-Omni 9-stage pipeline.</strong> Note the fan-out (one input, many branches) at preprocessing and the fan-in (many branches, one input) at aggregate — plus the second fan-out at Thinker, where text and speech split.</figcaption></figure><p>Reading the flow:</p><ol><li><strong>Preprocessing (CPU)</strong> turns raw input into tensors and metadata. The instant it’s done, the result fans out to <em>three</em> places at once — the image encoder, the audio encoder, and the aggregate stage. True parallelism starts here, not at the model.</li><li><strong>Image &amp; audio encoders (GPU)</strong> run independently and in parallel. The image encoder is a Vision Transformer; the audio encoder is a Transformer over Mel-spectrogram features. Each sends its embeddings to aggregate.</li><li><strong>Aggregate (CPU)</strong> is the classic fan-in node. It waits until <em>all</em> its upstream inputs have arrived, then merges the text tokens with the encoder outputs into a single input Thinker can consume in one shot. It does little compute — its job is <em>synchronization</em>.</li><li><strong>Thinker (GPU:0)</strong> is the semantic center. It embeds the tokens, injects the encoder outputs at the right placeholder positions, runs its Transformer stack, and generates text tokens. Then it fans out again — the most important branch in the system, because this is where text and speech formally split: <br>A. the <strong>text branch</strong> sends the full result to decode;<br>B. the <strong>speech branch</strong> <em>streams</em> to talker_ar token by token, passing along not just the token ids but Thinker&#39;s embeddings and a chosen layer&#39;s hidden states, so Talker can align to what Thinker meant.</li><li><strong>Decode (CPU, terminal)</strong> turns Thinker’s token ids back into text and reports completion.</li><li><strong>Talker AR → Code Predictor → Code2Wav (GPU:1)</strong> is the speech chain. Talker autoregressively generates codec tokens; the Code Predictor fills in the fine-grained RVQ layers (and feeds information back to Talker, more on that below); Code2Wav — a neural vocoder — accumulates codes and streams out 24 kHz audio chunks.</li></ol><p>When both terminals — decode and code2wav — report done, the Coordinator merges the text and the audio and returns them together.</p><h3>How Omni rides on SGLang</h3><p>Here’s the part I most misjudged at the start, and the part worth being precise about: <strong>SGLang-Omni is not a fork of SGLang.</strong> It’s an orchestration layer that sits <em>on top</em> of SGLang and treats it as a library for the compute-heavy work.</p><p>Think of it as a division of labor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*LEDJuS__ea2XQDXRt_VBug.png" /><figcaption><strong>Diagram 5 — Omni owns the pipeline; SGLang owns the AR math</strong></figcaption></figure><p>The heavy autoregressive stages — Thinker and Talker — are the ones that need everything core SGLang is good at: continuous batching, KV-cache management, fast attention. So Omni doesn’t rebuild any of that. Those stages run through an <strong>EngineExecutor</strong> wrapping <strong>OmniEngine</strong>, a compact serving loop with its own Scheduler (picks requests, builds batches) and ModelRunner (runs the forward). And that ModelRunner stands on SGLang&#39;s shoulders — the Thinker model, for example, reuses:</p><ul><li><strong>RadixAttention</strong> for efficient KV-cache management,</li><li>SGLang’s <strong>fused kernels</strong> (like a fused QK-norm + RoPE kernel for a big speedup),</li><li>and the same <strong>ModelRunner / forward / sampling</strong> machinery SGLang uses to serve a plain LLM.</li></ul><p>The lighter stages don’t need any of this. An image encoder is a one-shot operator: input in, forward once, output out. It runs through a much thinner DirectModelExecutor — no request state, no KV cache, no scheduler. This is the whole point of the Executor abstraction:</p><pre>class Executor(ABC):<br>    async def add_request(payload) -&gt; None    # submit<br>    async def get_result() -&gt; StagePayload     # collect<br>    async def abort(request_id) -&gt; None        # cancel<br>    def set_stream_fn(fn) -&gt; None              # streaming hook</pre><p>Same interface, wildly different implementations — a stateless forward for encoders, a stateful multi-step engine for Thinker and Talker. The pipeline doesn’t care which; it just calls add_request and awaits get_result.</p><p>One more detail earns a single sentence: OmniEngine supports an <strong>overlap mode</strong> that runs the current step&#39;s GPU work while the CPU processes the previous step&#39;s results, the same GPU/CPU pipelining trick that made core SGLang&#39;s scheduler &quot;zero-overhead.&quot; Omni reuses the idea rather than the exact code.</p><p>So the mental model is: <strong>Omni owns <em>when</em> and <em>where</em> things run; SGLang owns <em>how</em> the autoregressive math runs.</strong> Everything speech-specific — encoders, vocoders, streaming audio, the pipeline itself — is Omni’s. The transformer decode loop is SGLang’s.</p><h3>The two clever tricks</h3><p>Most of the pipeline is boring in a good way: stage finishes, next stage picks up. But two relationships aren’t like that, and they’re where “temporal orchestration” stops being a phrase and starts being code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hb7w95bVp4m9_R7dOhgU-Q.png" /><figcaption><strong>Diagram 6 — Streaming (Thinker→Talker) and the feedback loop (Talker↔Code Predictor).</strong></figcaption></figure><p><strong>① Streaming (</strong><strong>stream_to).</strong> Thinker doesn&#39;t hand Talker a finished paragraph. Every time it generates a token, it immediately pushes the corresponding hidden states out. Talker consumes them as a true producer–consumer stream:</p><ul><li>If Thinker is faster, a few tokens queue up and Talker catches up at its own pace.</li><li>If Talker is faster, the queue empties and Talker simply awaits the next token.</li><li>When Thinker finishes, it appends an end-of-text marker to the stream, and once Talker consumes it, Talker knows the text is done.</li></ul><p>There’s even a nice optimization on startup: if Talker finds several tokens already waiting when it begins, it prefills on the whole batch at once instead of crawling forward one token at a time.</p><p><strong>② The feedback loop (</strong><strong>WAITING_FEEDBACK).</strong> This is the most intricate state transition in the system. Every time Talker emits a codec token, it <em>can&#39;t</em> just barrel ahead. It sends the token to the Code Predictor and deliberately parks itself in a WAITING_FEEDBACK state — and while it&#39;s parked, the scheduler won&#39;t pick it. The Code Predictor does its work, sends back a summed_embeddings, and only then does the engine flip Talker back to WAITING so it can take its next step. It&#39;s genuine ping-pong: step, pause, wait for the partner, resume. Expressing that cleanly is <em>why</em> the runtime needs an explicit notion of request state with pause and resume points — a plain streaming pipe couldn&#39;t capture it.</p><p>Both patterns are invisible in a static DAG drawing. The DAG tells you the topology; these tell you the <em>timing</em>. And the timing is the actual product.</p><h3>Takeaways</h3><p>Coming back to where I started: SGLang-Omni taught me that for this class of model, the interesting engineering isn’t in the algorithms — it’s in the <em>serving system</em>.</p><ul><li><strong>It’s decoupling, not a new algorithm.</strong> The core move is splitting one logical model into independent stages that run as separate processes. That’s what unlocks everything else.</li><li><strong>Right hardware, right scheduler, per stage.</strong> Two equal-sized decode backbones make <em>placement</em> and <em>KV-cache/GPU-memory partitioning</em> the central problem. Encoders and vocoders get lightweight one-shot executors; Thinker and Talker get full serving loops. One size does not fit all.</li><li><strong>Scale and trim by stage.</strong> Bottleneck at Thinker? Scale Thinker. No speech needed? Drop the whole speech chain via config. The pipeline bends to the workload.</li><li><strong>Separate the ticket from the plate.</strong> The control-plane / data-plane split — tiny ZMQ notifications alongside zero-copy tensor transport with credit-based backpressure — is what makes multi-process cheap instead of copy-heavy.</li><li><strong>Compose, don’t fork.</strong> The compute-heavy autoregressive stages delegate to SGLang and reuse RadixAttention, fused kernels, and its ModelRunner. Omni adds orchestration around SGLang; it doesn’t replace it.</li></ul><p>I came in expecting a bag of modality-specific speed tricks. What I found was a runtime whose entire job is <em>coordination in time</em> — getting a committee of models to see, think, and speak in a smooth, streamed, fault-tolerant flow. The model was never the hard part. The pipeline was.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=062a2d24af05" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/sglang-omni-the-model-was-never-the-hard-part-062a2d24af05">SGLang-Omni: The Model Was Never the Hard Part</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XPUGraph vs torch.compile: Why I Was Wrong About Them Competing]]></title>
            <link>https://blog.gopenai.com/xpugraph-vs-torch-compile-why-i-was-wrong-about-them-competing-f9933dd9f3d8?source=rss-4354164acdff------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9933dd9f3d8</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Aadishagrawal]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 17:11:01 GMT</pubDate>
            <atom:updated>2026-07-08T17:11:01.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*75UqMmF5D8VY8USz" /><figcaption>Photo by <a href="https://unsplash.com/@brechtcorbeel?utm_source=medium&amp;utm_medium=referral">Brecht Corbeel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’d heard “<strong>XPUGraph</strong>” and “<strong>CUDAGraph</strong>” thrown around for a while but never sat down to actually understand them. I also had a persistent misconception: I assumed <strong>XPUGraph</strong> and <strong>torch.compile</strong> were competing approaches to the same problem. They’re not – they solve different bottlenecks, and once you understand what each one actually does, it becomes obvious they’re meant to stack on top of each other.</p><h3>The problem both are solving</h3><p>Every time PyTorch launches a kernel on the GPU, there’s CPU-side overhead: Python dispatch, eager-mode op-by-op execution, the kernel launch call itself. For small ops or high-frequency inference loops, this launch overhead can dominate over actual GPU compute time – the GPU sits idle waiting for the CPU to issue the next instruction.</p><p>Two very different tools have grown up around fixing this, and it’s easy to conflate them if you’ve only skimmed the docs.</p><h3>What XPUGraph actually does</h3><p>XPUGraph is Intel’s analog of CUDA Graphs, built for Intel GPUs (the xpu device backend) on top of the SYCL runtime. It shipped as a PyTorch feature to let users capture a sequence of XPU operations into a runtime execution graph and replay it repeatedly, specifically to cut CPU overhead like kernel launch and Python runtime cost.</p><p><strong>The mechanics, at a high level:</strong></p><p>•	<strong>First run (capture)</strong>: instead of executing operations immediately, PyTorch records the entire sequence – kernels, memory allocations, everything – into a graph object.</p><p>•	<strong>Every subsequent run (replay)</strong>: you replay the captured graph directly on the GPU. No Python dispatch, no per-kernel launch calls, no CPU in the loop.</p><p>A rough sketch of how this looks in code (mirroring the CUDA Graph API, which XPUGraph is modeled after):</p><pre>import torch<br><br># Static input buffer — address must stay fixed across replays<br>static_input = torch.randn(batch_size, features, device=&quot;xpu&quot;)<br><br>g = torch.xpu.XPUGraph()<br><br># Warmup: let kernels JIT/stabilize before capture<br>s = torch.xpu.Stream()<br>s.wait_stream(torch.xpu.current_stream())<br>with torch.xpu.stream(s):<br>    for _ in range(3):<br>        output = model(static_input)<br>torch.xpu.current_stream().wait_stream(s)<br><br># Capture the graph once<br>with torch.xpu.graph(g):<br>    output = model(static_input)<br><br># Replay as many times as you want — copy new data into the static buffer first<br>static_input.copy_(new_data)<br>g.replay()  # no CPU launch overhead per kernel<br></pre><h3>Three design pieces make this safe and efficient:</h3><p>1.	<strong>Private memory pools: </strong>Each graph capture gets an isolated memory pool, because the captured graph stores raw memory addresses used during recording – those addresses have to stay valid on every replay. A private pool structure prevents the allocator from handing that memory to anything else while the graph is alive. Pools can also be shared across multiple graphs to reduce overall memory footprint.</p><p>2.	<strong>RNG state handling:</strong> Random ops like dropout or sampling need their generator state captured and advanced consistently across replays, since the generator’s internal offset effectively becomes part of the graph itself.</p><p>3.	<strong>SYCL runtime integration: </strong>Capture and instantiation are implemented through SYCL APIs – mirroring how CUDA Graphs work under the CUDA Runtime, but adapted to Intel’s device/stream/event/generator abstractions.</p><h3>Where torch.compile fits in – and why it isn’t competing</h3><p>torch.compile is a compiler, not a launch mechanism. Under the hood it runs a pipeline:</p><p>•	<strong>TorchDynamo</strong> – analyzes Python bytecode and captures FX graphs (control flow it can’t handle becomes a “graph break”)</p><p>•	<strong>AOTAutograd</strong> – traces the joint forward/backward graph and decomposes it into lower-level ops</p><p>•	<strong>Inductor</strong> – lowers everything into optimized, fused kernels, generated via Triton</p><p>This gives you fused operators and eliminates Python-level dispatch overhead. It’s a genuinely different axis of optimization than graph capture.</p><p>Here’s the part I originally had backwards: even a fully compiled model still launches each optimized kernel individually on every call. Compilation happening once (and being cached) doesn’t remove the per-call launch cost – it just means you’re launching fewer, better kernels instead of many small eager ones. There’s still a CPU in the loop issuing launch commands every single run.</p><p>That’s precisely the gap XPUGraph closes. Once torch.compile has produced its optimized kernel sequence, that sequence can itself be captured into an XPUGraph. Replay then bypasses kernel launch overhead entirely, on top of the fusion benefits compilation already gave you.</p><h3>So the mental model:</h3><pre>torch.compile -&gt; what runs – fuses ops, generates efficient kernels<br><br>XPUGraph -&gt; how it gets launched – captures and replays kernel sequences with zero per-call CPU overhead</pre><h3>Why this matters in practice</h3><p>This combination matters most for inference workloads with small batch sizes or tight latency budgets – exactly the cases where launch overhead is a large fraction of total wall-clock time. On NVIDIA hardware, torch.compile(model, mode=”reduce-overhead”) already does this pairing automatically by wrapping compiled kernels in CUDA Graphs. XPUGraph brings the equivalent capability to Intel GPUs, so the same compiler-plus-graph-capture pattern now works across both ecosystems instead of being CUDA-exclusive.</p><p>Complementary, not competitive – and understanding that distinction changed how I think about optimizing inference pipelines end to end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9933dd9f3d8" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/xpugraph-vs-torch-compile-why-i-was-wrong-about-them-competing-f9933dd9f3d8">XPUGraph vs torch.compile: Why I Was Wrong About Them Competing</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Helion: The Missing Layer Between PyTorch and Triton]]></title>
            <link>https://blog.gopenai.com/helion-the-missing-layer-between-pytorch-and-triton-a0d50c557f7a?source=rss-4354164acdff------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0d50c557f7a</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[triton]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Aadishagrawal]]></dc:creator>
            <pubDate>Tue, 05 May 2026 19:01:10 GMT</pubDate>
            <atom:updated>2026-05-07T11:43:14.770Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How Meta’s new DSL makes high-performance GPU kernel development feel like writing normal Python — and outperforms hand-written Triton in the process.</em></p><p>Large companies today maintain <strong>thousands of custom GPU kernels</strong>. Each one is technical debt: hard to port to new hardware, painful to maintain, and tightly coupled to a specific GPU architecture. For years, developers have faced an uncomfortable choice — write fast kernels in low-level, hardware-specific code, or use high-level frameworks and accept limited control.</p><p><strong>Helion</strong> is Meta’s answer to that dilemma. Released as an open-source PyTorch project in 2025, it’s a Python-embedded domain-specific language (DSL) that compiles to Triton, giving you PyTorch’s ease of use with performance that often <em>beats</em> hand-written Triton kernels.</p><h3>1. The Basics: What Is Helion?</h3><p>Helion is a Python-embedded DSL for authoring machine learning GPU kernels. The simplest way to understand it is through two equivalent descriptions:</p><ul><li><strong>PyTorch with Tiles</strong> — write normal PyTorch operations, add tile-based loops for GPU parallelism, and Helion handles everything else.</li><li><strong>Higher-level Triton</strong> — Triton without the manual boilerplate: no explicit grid/block sizes, no pointer arithmetic, no stride calculations.</li></ul><blockquote><strong><em>Name origin:</em></strong><em> Triton refers to hydrogen-3 (³H). Helion refers to the nucleus of a helium-3 atom (³He) — one level up in the periodic table, just as Helion sits one level above Triton in the software stack.</em></blockquote><p>Helion was created by PyTorch Compilers team at Meta. It reached public beta at PyTorch Conference 2025 and hit 1.0 shortly after.</p><h4>The Problem It Solves</h4><p>Here’s how the current landscape stacks up across the dimensions that matter most:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_6-HX26fGoFahRleJw1og.png" /></figure><p>Helion doesn’t replace PyTorch or Triton — it fills the gap between them. When torch.compile can&#39;t automatically generate the custom kernel you need, and you don&#39;t want to write raw Triton by hand, Helion is the answer.</p><h3>2. Where Helion Lives in the Software Stack</h3><p>Helion occupies a precise and deliberate position — <strong>above Triton, but below PyTorch</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HDEMmckRl3-UrEn84zctZw.png" /></figure><p>Each layer in this stack trades control for productivity. CUDA gives you everything but demands you manage every thread. Triton abstracts threads into blocks but still requires manual indexing and grid definitions. PyTorch is intuitive, but doesn’t let you specify exact fusion strategies.</p><p>Helion sits precisely at the intersection where that tradeoff disappears — you get PyTorch-level expressiveness and Triton-level (or better) performance.</p><h3>3. The Lowering Flow: From Helion to GPU Machine Code</h3><p>Let’s trace exactly what happens when you call a Helion kernel, using a matrix multiplication as our running example.</p><h4>The Source Kernel</h4><pre>import torch, helion, helion.language as hl<br>@helion.kernel()<br>def matmul(x: torch.Tensor, y: torch.Tensor) -&gt; torch.Tensor:<br>    # HOST CODE — runs on CPU<br>    m, k = x.size()<br>    k2, n = y.size()<br>    assert k == k2, f&quot;size mismatch {k} != {k2}&quot;<br>    out = torch.empty([m, n], dtype=x.dtype, device=x.device)<br>    # DEVICE CODE - compiles to a single Triton GPU kernel<br>    for tile_m, tile_n in hl.tile([m, n]):<br>        acc = hl.zeros([tile_m, tile_n], dtype=torch.float32)<br>        for tile_k in hl.tile(k):<br>            acc = torch.addmm(acc, x[tile_m, tile_k], y[tile_k, tile_n])<br>        out[tile_m, tile_n] = acc<br>    return out</pre><p>Everything <strong>outside</strong> the outer hl.tile loop is host (CPU) code: tensor allocation, shape checks. Everything <strong>inside</strong> becomes a single GPU kernel. Now here&#39;s the 7-step journey from those 15 lines to GPU machine code:</p><h4><strong>Step 1 — Python AST Parsing &amp; Type Propagation</strong></h4><p>Helion parses the decorated function into an abstract syntax tree and runs type propagation to determine tensor shapes (m×k, k×n), data types (float32), and data-flow dependencies between values.</p><p><em>Example: the function signature and size() calls tell Helion that x is [m, k] float32 and y is [k, n] float32.</em></p><h4><strong>Step 2 — Host / Device Split</strong></h4><p>Code is separated into host (CPU) and device (GPU) regions. The boundary is the outermost hl.tile loop. Tensor allocations and shape math stay on the host; the tiled loop body becomes the GPU kernel body.</p><p><em>Example: </em><em>out = torch.empty([m, n]) → HOST | </em><em>for tile_m, tile_n in hl.tile([m, n]) → DEVICE</em></p><h4><strong>Step 3 — FX Graph Capture via TorchInductor</strong></h4><p>The device region is captured using PyTorch’s FX system. Standard PyTorch operators like torch.addmm, torch.sum, and torch.exp are traced into an FX graph. TorchInductor then maps each operator to its Triton equivalent.</p><p><em>Example: </em><em>torch.addmm(acc, x[tile_m, tile_k], y[tile_k, tile_n]) → </em><em>tl.dot(a, b, acc)</em></p><h4><strong>Step 4 — Configuration Space Construction</strong></h4><p>Helion builds the full implicit search space. For our matmul, this includes: block sizes [32/64/128] × [32/64/128] × [32/64/128], loop orders, L2 groupings, indexing strategies (pointer / block_ptr / tensor_descriptor), num_warps, num_stages, and more. This yields <strong>thousands of candidate configurations</strong> from those 15 lines.</p><p><em>Example: </em><em>hl.tile([m, n]) → search space: {block_sizes: [32..128], flatten: [T/F], loop_order: [0,1] or [1,0], l2_grouping: [1,4,8], ...}</em></p><h4><strong>Step 5 — Triton Code Generation (per config)</strong></h4><p>For each candidate configuration, Helion generates the complete Triton source: pointer arithmetic or block_ptr or TMA access patterns, masking, grid definitions, program ID calculations, and kernel argument management — all the boilerplate you’d otherwise write manually.</p><p><em>Example: indexing=’block_ptr’, block_sizes=[64,64,64] → full Triton kernel with </em><em>tl.make_block_ptr, grid lambda, stride arguments, etc.</em></p><h4><strong>Step 6 — Autotuning Search</strong></h4><p>Each generated Triton kernel is compiled and benchmarked on actual hardware. Search algorithms like <strong>Differential Evolution</strong> and <strong>Pattern Search</strong> intelligently navigate the space, spending roughly 10 minutes evaluating ~1,500 configs to find the optimal one for your specific GPU and input shapes.</p><p><em>Example output:</em></p><pre>[586s] Autotuning complete after searching 1520 configs.<br>Best: block_sizes=[64, 64, 64], indexing=&#39;block_ptr&#39;, num_warps=8, num_stages=6</pre><h4><strong>Step 7 — Triton → PTX / LLVM IR → GPU Machine Code</strong></h4><p>The winning Triton kernel is compiled by the Triton compiler into PTX (NVIDIA) or LLVM IR (AMD), then to native GPU machine code. The result is <strong>cached</strong> — subsequent calls with matching tensor signatures skip all previous steps and run instantly.</p><h4>What Helion Saves You From Writing</h4><p>To appreciate the automation, here’s a partial view of the Triton code Helion generates from those 15 lines (visible via HELION_PRINT_OUTPUT_CODE=1):</p><pre>@triton.jit<br>def matmul_kernel(<br>    x_ptr, y_ptr, out_ptr,<br>    m, k, n,<br>    stride_xm, stride_xk,   # ← Helion generates all of this<br>    stride_yk, stride_yn,<br>    stride_om, stride_on,<br>    BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr<br>):<br>    # Program ID with L2 swizzling for cache locality<br>    pid = tl.program_id(0)<br>    num_pid_m = tl.cdiv(m, BLOCK_M)<br>    pid_m = pid % num_pid_m<br>    pid_n = pid // num_pid_m<br># Block pointer setup (auto-selected based on config)<br>    x_block_ptr = tl.make_block_ptr(<br>        base=x_ptr, shape=(m, k), strides=(stride_xm, stride_xk),<br>        offsets=(pid_m * BLOCK_M, 0), block_shape=(BLOCK_M, BLOCK_K), order=(1, 0)<br>    )<br>    # ... similar for y and out ...<br>    acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)<br>    for k_idx in range(tl.cdiv(k, BLOCK_K)):<br>        acc += tl.dot(tl.load(x_block_ptr), tl.load(y_block_ptr))<br>        x_block_ptr = tl.advance(x_block_ptr, (0, BLOCK_K))<br>        y_block_ptr = tl.advance(y_block_ptr, (BLOCK_K, 0))<br>    tl.store(out_block_ptr, acc)<br># Grid lambda - also auto-generated<br>grid = lambda META: (triton.cdiv(m, META[&#39;BLOCK_M&#39;]) * triton.cdiv(n, META[&#39;BLOCK_N&#39;]),)  </pre><p>All of that — strides, block pointers, grid lambdas, masking, argument threading — is <strong>auto-generated</strong>. You write the algorithm; Helion handles the plumbing.</p><h3>4. All the Important Features</h3><h4>hl.tile — The Core Primitive</h4><p>hl.tile([m, n]) is the fundamental language construct. It tells Helion to parallelize computation over the m×n space in tiles. The crucial insight: you only specify <em>what</em> to parallelize. The <em>how</em> — tile sizes, iteration order, memory layout — is determined entirely by the autotuner.</p><p>A single hl.tile call implicitly instructs the autotuner to explore different block sizes, loop orderings, and whether to flatten the iteration space into a single dimension.</p><h4>Implicit Search Spaces</h4><p>In Triton, developers manually enumerate every configuration to test. In Helion, the search space is constructed <strong>automatically</strong> from your source code. One Helion kernel definition maps to thousands of Triton configurations, giving the autotuner a much richer space to find genuinely superior setups.</p><h4>Ahead-of-Time Autotuning Engine</h4><p>Helion’s ~10-minute AOT autotuning uses <strong>Differential Evolution</strong> or <strong>Pattern Search</strong> to evaluate thousands of candidate Triton implementations.</p><h4>Hardcoding the Best Config (Production Mode)</h4><p>After autotuning, Helion prints the winning configuration.</p><p>Copy it into your decorator for zero-overhead, deterministic production runs:</p><pre>@helion.kernel(config=helion.Config(<br>    block_sizes=[64, 64, 64],<br>    loop_orders=[[0, 1]],<br>    l2_groupings=[4],<br>    num_warps=8,<br>    num_stages=6,<br>    indexing=&#39;block_ptr&#39;,<br>    pid_type=&#39;flat&#39;<br>))<br>def matmul(x: torch.Tensor, y: torch.Tensor) -&gt; torch.Tensor:<br>    # same kernel body — zero autotuning overhead in production</pre><h4>PyTorch Operator Reuse</h4><p>Standard PyTorch operators (torch.addmm, torch.sum, torch.softmax, pointwise ops, reductions) work directly inside Helion kernels. TorchInductor automatically maps them to Triton primitives.</p><blockquote><strong><em>If you know PyTorch, you already know most of Helion.</em></strong></blockquote><h4>Kernel Templating via Closures</h4><p>Lambda functions that capture external tensors can be passed as kernel arguments. Helion automatically promotes captured variables to kernel arguments — enabling generic kernels with customizable epilogues without any boilerplate.</p><pre># The bias tensor is captured from the outer scope — Helion handles argument passing<br>epilogue = lambda acc, bias: acc + bias<br>result = fused_matmul(x, y, epilogue=epilogue)</pre><h4>Multi-Indexing Strategy Search</h4><p>Helion auto-selects between three Triton memory access patterns from the same source code:</p><ul><li>pointer — classical pointer arithmetic</li><li>block_ptr — block pointer API for better performance on most hardware</li><li>tensor_descriptor — Tensor Memory Accelerators (TMA) on NVIDIA Hopper/Blackwell</li></ul><p>Switching between these in raw Triton requires a significant code rewrite. In Helion, it’s one config parameter.</p><h4>Performance Portability</h4><p>The same Helion source runs optimally on NVIDIA H100, A100, Blackwell, and AMD MI300/MI350. The autotuner finds different optimal configurations for each — you don’t write hardware-specific code.</p><h4>The Full Configuration Space</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DKMHKJxEuXQgHoPoBwzIw.png" /></figure><h4>Reduction &amp; Split-K Support</h4><p>For large reduction dimensions, Helion can automatically distribute work across multiple thread blocks (split-K strategy) and reduce partial results. The autotuner decides whether persistent or split-K reduction is faster for your specific problem shape.</p><h4>TileIR Backend</h4><p>Helion includes a dedicated backend for NVIDIA Blackwell GPUs (compute capability 10.x/12.x) using Triton-TileIR, with additional tuning knobs specific to that architecture.</p><h3>5. Performance: Does It Actually Beat Hand-Written Triton?</h3><p>Yes — and often by a significant margin. The reason is search: Helion explores configurations that humans rarely try manually.</p><p><strong>Speedup over eager mode execution (AMD MI350X, geomean):</strong></p><ul><li>Helion: <strong>2.37×</strong></li><li>torch.compile (max-autotune): 2.26×</li><li>Hand-written Triton kernels: 1.65×</li></ul><p>Helion also delivers <strong>1.05× speedup over torch.compile</strong> and <strong>1.44× over Triton</strong> on average on AMD hardware.</p><p>For specific kernels, the advantage is more dramatic:</p><ul><li><strong>int4_gemm kernel:</strong> Helion outperforms hand-written Triton by <strong>4.5×</strong></li><li><strong>jsd kernel:</strong> <strong>4.4×</strong> over hand-written Triton</li><li><strong>RMSNorm backward:</strong> Written in less than a day, matches a highly hand-optimized CuTe DSL (C++) implementation</li><li><strong>Mamba-2 chunk-scan (H100):</strong> 2.12×–2.63× faster than TileLang, 1.2×–1.85× faster than Triton</li></ul><p>The FlashAttention-style kernel is 30 lines in Helion vs. 120 in Triton and thousands in CUDA.</p><h4>Hardware Support</h4><ul><li><strong>NVIDIA</strong> — Ampere, Hopper (TMA), Blackwell (TileIR)</li><li><strong>Intel: </strong>Data Centre GPU Max, Arc, and other XPU devices</li><li><strong>AMD: </strong>MI300X, MI350X on ROCm 6.2+</li><li><strong>Future:</strong> Any hardware Triton targets, since Helion compiles through it</li></ul><h3>6. Debugging, Tooling &amp; Getting Started</h3><h4>Developer Tools</h4><pre># See the generated Triton source for any Helion kernel<br>HELION_PRINT_OUTPUT_CODE=1 python my_kernel.py<br><br># Run in eager/Python mode for debugging (no GPU compilation needed)<br>HELION_EAGER_MODE=1 python my_kernel.py</pre><p>You can also supply a list of configs directly to restrict the autotuner’s search:</p><pre>@helion.kernel(configs=[<br>    helion.Config(block_sizes=[64, 64, 64], num_warps=8),<br>    helion.Config(block_sizes=[128, 128, 32], num_warps=4),<br>])<br>def my_kernel(...):<br>    ...</pre><h4>Installation</h4><pre>pip install helion</pre><p>Or from source:</p><pre>git clone https://github.com/pytorch/helion<br>cd helion &amp;&amp; pip install -e .</pre><h4>When Should You Use Helion?</h4><p><strong>Reach for Helion when:</strong></p><ul><li>You need a custom kernel that torch.compile can&#39;t automatically generate or fuse</li><li>You want Triton-level performance without Triton-level boilerplate</li><li>Your team knows PyTorch but not low-level GPU programming</li><li>You need the same kernel to perform well across NVIDIA, Intel and AMD hardware</li><li>You’re building reusable, generic kernels with parameterized epilogues</li></ul><p><strong>Stick with raw Triton when:</strong></p><ul><li>Autotuning time is unacceptable for your workflow</li><li>You have highly specific micro-optimization requirements outside Helion’s config space</li><li>You’re targeting experimental hardware not yet covered by Helion’s backends</li></ul><h3>Closing Thoughts</h3><p>Helion represents a genuine shift in how GPU kernels are written. The fact that a 15-line Helion kernel can routinely outperform carefully hand-tuned 80-line Triton kernels isn’t magic — it’s the result of a search space that’s simply too large for any human to explore manually.</p><p>The deeper implication: the right level of abstraction for kernel authoring isn’t the one that gives you the most control. It’s the one that gives the <em>compiler</em> the most room to optimize.</p><p>Helion is that level.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0d50c557f7a" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/helion-the-missing-layer-between-pytorch-and-triton-a0d50c557f7a">Helion: The Missing Layer Between PyTorch and Triton</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AutoKernel: Stop Hand-Tuning GPU Kernels. Let AI Do It While You Sleep.]]></title>
            <link>https://blog.gopenai.com/autokernel-stop-hand-tuning-gpu-kernels-let-ai-do-it-while-you-sleep-8e879ac3bee6?source=rss-4354164acdff------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e879ac3bee6</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Aadishagrawal]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 12:24:50 GMT</pubDate>
            <atom:updated>2026-09-25T12:23:22.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIWmapzEJ5IpgHf4F1vltA.jpeg" /></figure><h3><strong>How an autonomous agent turned weeks of expert GPU optimization into overnight experiments</strong></h3><p>You’ve built a PyTorch model. It works. But when you deploy it, the GPU bills are eye-watering, and latency is killing your user experience.</p><p>You know the solution: optimize those GPU kernels. Write custom Triton or custom Kernel. But here’s the reality:</p><ul><li><strong>Writing high-performance kernels takes weeks</strong> — even for experts</li><li><strong>Each operation needs deep architecture knowledge</strong> — H100 vs A100? Different tuning.</li><li><strong>Trial and error is tedious</strong>— change block size, recompile, benchmark, repeat 100 times</li><li><strong>One mistake breaks everything</strong>— and debugging GPU kernels at 3 AM is nobody’s idea of fun</li></ul><p>What if instead of spending weeks tuning kernels, you could just… go to sleep? And wake up to optimized code?</p><p>Enter <strong>AutoKernel</strong>.</p><h3><strong>What is AutoKernel?</strong></h3><p>AutoKernel is <strong>autonomous research for GPU kernels</strong>. Think of it as a tireless engineer that:</p><p>1. <strong>Profiles your PyTorch model</strong> to find bottlenecks</p><p>2. <strong>Extracts those bottlenecks</strong> into standalone Triton or custom kernels</p><p>3. <strong>Optimizes each kernel autonomously</strong> — edit, test, benchmark, keep or revert — forever</p><p>4. <strong>Verifies correctness end-to-end</strong> and reports your total speedup</p><p>Each experiment takes ~90 seconds. That’s <strong>~40 experiments per hour, ~320 overnight</strong>, systematically exploring optimization strategies that would take humans weeks.</p><p>&gt; Inspired by Andrej Karpathy’s autoresearch for LLM training, AutoKernel applies the same philosophy to GPU optimization: agent modifies one file, runs a fixed evaluation, keeps or reverts, repeats forever.</p><h3><strong>How It Works: The Three-Phase Pipeline</strong></h3><h4><strong>Phase A: Model Profiling</strong></h4><p>AutoKernel starts by profiling your entire PyTorch model with <em>torch.profiler:</em></p><pre>uv run profile.py -model models/llama_7b.py \<br> --class-name LlamaModel --input-shape 1,512 --dtype float16</pre><p>It ranks every operation by GPU time and uses <strong>Amdahl’s law</strong> to prioritize: a 1.5× speedup on a kernel using 60% of runtime (1.25× end-to-end gain) beats a 3× speedup on a 5% kernel (1.03× gain).</p><p>This <strong>model-centric approach</strong> is key — why waste time optimizing irrelevant operations?</p><h4><strong>Phase B: Iterative Agent Loop</strong></h4><p>Once bottlenecks are identified, the agent enters a tight optimization loop:</p><pre>Agent reads program.md<br>↓<br>(Comprehensive instructions: 6-tier playbook)<br>↓<br>Edits kernel.py<br>↓<br>(Single file to modify)<br>↓<br>Runs bench.py<br>↓<br>(5-stage correctness + performance)<br>↓<br>PASS → Keep (git commit)<br>FAIL → Revert (git reset - hard)</pre><p>Every 90 seconds, the agent tries a new optimization strategy. <strong>The benchmark is fixed</strong> — the agent can’t game its own evaluation.</p><h4><strong>Phase C: Correctness Firewall</strong></h4><p>Before any performance measurement, the kernel must pass <strong>five verification stages</strong>:</p><p>1. <strong>Smoke test</strong> — Does it run at all?</p><p>2. <strong>Shape sweep</strong> — Works across 10+ different input sizes?</p><p>3. <strong>Numerical stability</strong> — Output matches PyTorch reference within tolerance?</p><p>4. <strong>Determinism</strong> — Same inputs → same outputs every time?</p><p>5. <strong>Edge cases</strong> — Handles zeros, ones, tiny batches, huge dimensions?</p><p>&gt; Only after passing all five stages is performance measured. <strong>Fast but wrong kernels are immediately reverted.</strong> No garbage output, ever.</p><h3><strong>The Agent’s Playbook: From Novice to Expert</strong></h3><p>AutoKernel doesn’t randomly guess. It follows a <strong>six-tier optimization playbook</strong> encoded in <em>program.md</em>:</p><ul><li><strong>Tier 1: Block Size Tuning</strong></li></ul><p>Try BLOCK_M=64, 128, 256. Easy wins, ~1.2–1.5× typical speedup.</p><ul><li><strong>Tier 2: Memory Access Patterns</strong></li></ul><p>Coalesce global memory reads, minimize bank conflicts.</p><ul><li><strong>Tier 3: Occupancy &amp; Warps</strong></li></ul><p>Tune <em>num_warps</em>, balance shared memory usage.</p><ul><li><strong>Tier 4: Instruction-Level Optimization</strong></li></ul><p>Eliminate redundant loads, fuse operations.</p><ul><li><strong>Tier 5: Architecture-Specific Features</strong></li></ul><p>Tensor cores (FP16 matmul), async copies, warp specialization.</p><ul><li><strong>Tier 6: Advanced Techniques</strong></li></ul><p>Pipeline double buffering, multi-stage pipelines, kernel fusion.</p><p>The agent starts simple and escalates as it exhausts easier strategies. This mirrors how human experts actually optimize kernels.</p><h3><strong>Real-World Results: How Fast is Fast?</strong></h3><p>AutoKernel has been deployed on models like GPT-2, LLaMA, and BERT. Here are results from <strong>NVIDIA H100</strong>:</p><h4><strong>RMSNorm</strong></h4><ul><li>PyTorch Eager: 1.0×</li><li>torch.compile: 1.87×</li><li><strong>AutoKernel: 5.29×</strong> (2.83× over compiled)</li></ul><h4><strong>Softmax</strong></h4><ul><li>PyTorch Eager: 1.0×</li><li>torch.compile: 0.82×</li><li><strong>AutoKernel: 2.82×</strong> (3.44× over compiled)</li></ul><h4><strong>Cross-Entropy</strong></h4><ul><li>PyTorch Eager: 1.0×</li><li>torch.compile: 0.75×</li><li><strong>AutoKernel: 2.21×</strong> (2.94× over compiled)</li></ul><p>Note that for memory-bound operations, <em>torch.compile</em> sometimes <em>slows things down</em>. AutoKernel’s iterative approach consistently finds faster implementations.</p><h4><strong>Community Wins</strong></h4><ul><li><strong>FP4 matmul</strong> kernel: 1.63–2.15× speedup over CUTLASS (NVIDIA’s optimized library)</li></ul><p>These aren’t toy benchmarks — these are production-grade kernels beating vendor-optimized code.</p><h3><strong>Why AutoKernel is Different</strong></h3><h4><strong>1. Dual Backend: Triton + C++</strong></h4><p>Start with <strong>Triton</strong> for rapid iteration (Python-like syntax, compiles in seconds). When you need maximum performance, switch to <strong>C++</strong> for direct tensor core access via <em>wmma</em>, PTX intrinsics, and bank-conflict-free shared memory layouts.</p><p>Both backends share the same interface —<em> bench.py</em> runs identically on either.</p><h4><strong>2. Single Agent, Linear History</strong></h4><p>Unlike complex multi-agent systems with coordinators and specialists, AutoKernel is beautifully simple: <strong>one agent, one file (<em>kernel.py</em>), one loop.</strong></p><p>Every experiment gets a git commit. Want to see what the agent tried? Just <em>git log</em>. Want to revert to experiment 42? Just checkout the right commit.</p><h4><strong>3. Reproducible, Logged, Git-Friendly</strong></h4><p>Results go to <em>results.csv</em> — plain tab-separated values. Human-readable, git-diffable, trivially parseable, no infrastructure needed:</p><pre>experiment tag throughput speedup correctness<br>0 baseline 18.2 1.00× PASS<br>1 block_128 23.7 1.30× PASS<br>2 block_256 26.1 1.43× PASS<br>3 pipeline_v1 22.9 1.26× PASS (revert)<br>4 tensor_cores 34.8 1.91× PASS (keep!)</pre><h4><strong>4. Integrates with KernelBench</strong></h4><p>AutoKernel integrates with <a href="https://github.com/ScalingIntelligence/KernelBench">KernelBench</a>, Stanford’s standard benchmark for evaluating AI-generated GPU kernels (250+ problems across 4 difficulty levels).</p><p>While most approaches use <strong>one-shot generation</strong> (“here’s a prompt, give me a kernel”), AutoKernel runs <strong>50–300+ iterative refinement experiments per problem</strong>— systematically exploring the optimization space.</p><h3><strong>Getting Started in 5 Minutes</strong></h3><p><strong>Requirements:</strong> NVIDIA GPU (H100/A100/RTX 4090), Python 3.10+, <a href="https://docs.astral.sh/uv/">uv</a></p><pre># Install uv<br>curl -LsSf https://astral.sh/uv/install.sh | sh<br># Clone and setup<br>git clone https://github.com/RightNow-AI/autokernel.git<br>cd autokernel<br>uv sync<br># One-time setup<br>uv run prepare.py<br># Profile a model (LLaMA example)<br>uv run profile.py --model models/llama_7b.py \<br> --class-name LlamaModel --input-shape 1,512 --dtype float16<br># Extract top 5 bottleneck kernels<br>uv run extract.py --top 5<br># Verify benchmark works<br>uv run bench.py</pre><p>Now spin up Claude (or any coding agent) in this directory:</p><p>&gt; “Read program.md and let’s kick off a new experiment. Start with setup.”</p><p>The agent will profile your model, create an optimization branch, and start the experiment loop.</p><p><strong>Go to sleep. Wake up to optimized kernels.</strong></p><h3><strong>What’s Supported?</strong></h3><h4><strong>9 Kernel Types (Core Deep Learning Operations)</strong></h4><ul><li><strong>matmul</strong> — Dense matrix multiplication (TFLOPS)</li><li><strong>flash_attention</strong>— Scaled dot-product attention with causal masking (TFLOPS)</li><li><strong>fused_mlp</strong>— SwiGLU-style fused MLP (TFLOPS)</li><li><strong>softmax</strong> — Numerically stable row-parallel softmax (GB/s)</li><li><strong>layernorm</strong> — Layer normalization (GB/s)</li><li><strong>rmsnorm</strong> — RMS normalization, LLaMA-style (GB/s)</li><li><strong>cross_entropy</strong> — Fused cross entropy loss (GB/s)</li><li><strong>rotary_embedding</strong>— Rotary position embeddings, RoPE (GB/s)</li><li><strong>reduce</strong> — Parallel reduction sum (GB/s)</li></ul><h4><strong>Included Models (No HuggingFace Required)</strong></h4><ul><li><strong>GPT-2 Small</strong> (124M params)</li><li><strong>LLaMA</strong> (160M compact / 7B full)</li><li><strong>BERT-base</strong> (110M)</li><li><strong>Custom template</strong> for your own models</li></ul><h4><strong>GPU Hardware Support</strong></h4><p>AutoKernel currently supports <strong>NVIDIA GPUs</strong> (H100, A100, RTX 4090, and more) with both Triton and CUDA C++ backends.</p><p><strong>Extensible to Intel GPUs</strong>: The architecture is designed to be vendor-agnostic. AutoKernel can be extended to support <strong>Intel Data Center GPUs</strong> (Ponte Vecchio, Battlemage and Upcoming GPUs):</p><ul><li>Adding Intel GPU detection and specifications to the profiler</li><li>Supporting Intel’s GPU specific sycl or C++ kernels</li><li>Adapting the benchmark harness for Intel’s performance metrics</li></ul><p>The same autonomous optimization loop — profile, extract, optimize, verify — works regardless of hardware vendor. The agent reads GPU specifications, applies architecture-specific optimizations, and measures against vendor libraries</p><p><strong>Multi-GPU vendor support means you can optimize once and deploy everywhere</strong>, whether you’re running on cloud (AWS, GCP, Azure), on-premise data centers, or edge devices.</p><h3><strong>Design Philosophy: Simple, Robust, Autonomous</strong></h3><h4><strong>Correctness First</strong></h4><p>Fast but wrong is useless. The 5-stage verification harness ensures every optimization is <strong>correct before it’s measured</strong>. A kernel that produces garbage is immediately reverted, no exceptions.</p><h4><strong>Amdahl’s Law Orchestration</strong></h4><p>The <em>orchestrate.py</em> scheduler prioritizes by <strong>actual impact on end-to-end performance</strong>. When diminishing returns set in on one kernel, it automatically moves to the next bottleneck.</p><h4><strong>Single File Scope</strong></h4><p>The agent only modifies <em>kernel.py</em>. No sprawling changes across dozens of files. Diffs stay reviewable, reverts stay clean, humans stay sane.</p><h4><strong>Infrastructure-Free</strong></h4><p>No databases, no message queues, no dashboards, no Kubernetes. Just:</p><ul><li>Git (for versioning and history)</li><li>Bash scripts (for orchestration)</li></ul><p>It runs anywhere you can run Python.</p><h3><strong>Export and Share Your Kernels</strong></h3><p>Optimized something amazing? Export it to the <a href="https://huggingface.co/docs/kernels">Hugging Face Kernels</a> :</p><pre># Export an optimized kernel<br>uv run export_hf.py --name my_blazing_fast_matmul<br># Upload to Hub<br>cd workspace/hf_export/my_blazing_fast_matmul<br>kernels upload . --repo_id your-username/my_blazing_fast_matmul</pre><p>Now anyone can use your kernel with one line:</p><pre>from kernels import get_kernel<br>module = get_kernel(&quot;your-username/my_blazing_fast_matmul&quot;)</pre><h3><strong>Who Should Use AutoKernel?</strong></h3><h4><strong>Perfect for:</strong></h4><ul><li><strong>ML engineers</strong> who want faster inference without PhD-level GPU knowledge</li><li><strong>Researchers</strong> prototyping models and need quick performance wins</li><li><strong>Teams</strong> shipping latency-critical applications (real-time inference, etc.)</li><li><strong>Anyone</strong> who’s ever stared at <em>nsys </em>profiles wishing kernels were faster</li></ul><p><strong>Not for:</strong></p><ul><li>Models already running at 95%+ of theoretical peak (rare!)</li><li>Situations where 2–5× speedup doesn’t justify the setup time (~30 min)</li></ul><h3><strong>The Future: Autonomous GPU Optimization</strong></h3><p>AutoKernel represents a shift in how we think about performance optimization.</p><h4><strong>Instead of:</strong></h4><ul><li><strong>Weeks</strong> of expert time tuning one kernel</li><li><strong>Fragile</strong> hand-coded solutions that break on new hardware</li><li><strong>Undocumented</strong> knowledge locked in senior engineers’ heads</li></ul><h4><strong>We get:</strong></h4><ul><li><strong>Overnight</strong> optimization across all bottlenecks</li><li><strong>Reproducible</strong> experiments with full git history</li><li><strong>Transferable</strong> knowledge encoded in the optimization playbook</li></ul><p>The agent doesn’t get tired. It doesn’t miss edge cases. It tries things humans wouldn’t think of. And critically, <strong>it learns from every experiment</strong> — both successes and failures are logged.</p><h3><strong>Try It Today</strong></h3><p>AutoKernel is open source (MIT license) and ready to use: <a href="https://github.com/RightNow-AI/autokernel"><strong>GitHub</strong></a></p><p><strong>Stop hand-tuning GPU kernels. Let AI do it while you sleep.</strong></p><p><em>Built by </em><a href="https://www.rightnowai.co/"><em>RightNow AI</em></a><em>. Inspired by </em><a href="https://github.com/karpathy/autoresearch"><em>@karpathy/autoresearch</em></a><em>. Integrates with </em><a href="https://github.com/ScalingIntelligence/KernelBench"><em>KernelBench</em></a><em> from Stanford’s Scaling Intelligence Lab.</em></p><p><em>Special thanks to the AutoKernel paper authors for their work on autonomous GPU kernel optimization research.</em></p><p><strong>If you found this helpful, follow me for more content on AI.</strong></p><p><strong>Got questions? Drop them in the comments below!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e879ac3bee6" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/autokernel-stop-hand-tuning-gpu-kernels-let-ai-do-it-while-you-sleep-8e879ac3bee6">AutoKernel: Stop Hand-Tuning GPU Kernels. Let AI Do It While You Sleep.</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nemotron 3: A Hybrid Mamba-Transformer Revolution for Agentic AI]]></title>
            <link>https://blog.gopenai.com/nemotron-3-a-hybrid-mamba-transformer-revolution-for-agentic-ai-8addf4af280b?source=rss-4354164acdff------2</link>
            <guid isPermaLink="false">https://medium.com/p/8addf4af280b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[mamba]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Aadishagrawal]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 18:31:08 GMT</pubDate>
            <atom:updated>2026-02-06T10:48:26.218Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How NVIDIA’s groundbreaking hybrid architecture achieves 3.3× throughput over 30B-parameter models while processing 1M token contexts — and why pure Transformers are now legacy technology</em></p><h3><strong>1. Mamba Recap: Why Transformers Finally Have a Worthy Rival</strong></h3><h4><strong>The Mamba Revolution: A Quick Refresher</strong></h4><p><em>If you read my previous post </em><a href="https://medium.com/@aadishagrawal/mamba-the-breakthrough-that-makes-transformers-look-expensive-30611294d575"><em>Mamba: The Breakthrough That Makes Transformers Look Expensive</em></a><em>, you witnessed the birth of a paradigm shift in deep learning architecture. But let me recap the key breakthroughs that made Mamba the most significant challenger to the Transformer dynasty.</em></p><p><strong>Transformers’ Achilles Heel</strong>: For nearly a decade, Transformers dominated NLP and beyond. But their self-attention mechanism suffers from a fundamental flaw — <strong>quadratic complexity</strong>. Processing a sequence of length N requires O(N²) operations and O(N²) memory. This means:</p><ul><li><strong>10,000 tokens</strong> → 100 million attention computations</li><li><strong>100,000 tokens</strong> → 10 billion computations (100× worse!)</li><li><strong>1 million tokens</strong> → Forget about it without extreme engineering</li></ul><p><strong>Mamba’s Elegant Solution</strong>: Enter <strong>Structured State Space Models (SSMs)</strong>— a mathematically beautiful approach inspired by control theory and signal processing. Mamba reimagined sequence modelling through continuous-time state representations:</p><pre># Conceptual Mamba-1 State Space Equation<br>h(t) = A·h(t) + B·x(t) # Continuous state evolution<br>y(t) = C·h(t) + D·x(t) # Output projection</pre><p>By discretising these equations with <strong>selective mechanisms</strong> (input-dependent parameters), Mamba achieved something remarkable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHt6iXrKZNyjmMxB44wagQ.png" /></figure><p><strong>Real-World Proof</strong>: Trained on 1T+ tokens, Mamba matched <strong>Llama-7B’s perplexity</strong> on language modelling while demolishing it on efficiency. The architecture processed sequences in <strong>linear time</strong>— meaning 2× longer sequences took only 2× longer (not 4×).</p><h4><strong>The Unfinished Revolution: Mamba-1’s GPU Problem</strong></h4><p>Despite these achievements, Mamba-1 had a critical bottleneck that prevented it from fully replacing Transformers: <strong>GPU underutilization</strong>.</p><p><strong>Key Insight</strong>: Mamba-1 was mathematically elegant with O(N) complexity, but wasted 65% of GPU hardware due to sequential dependencies.</p><p>The core issue? Mamba-1’s selective scan operation was fundamentally <strong>sequential</strong>:</p><pre># Mamba-1&#39;s Sequential Bottleneck<br>for t in range(sequence_length):<br>h[t] = A * h[t-1] + B * x[t] # Must wait for h[t-1]!<br>y[t] = C * h[t] # Can&#39;t parallelize across time</pre><p>While mathematically elegant and theoretically O(N), this recurrence couldn’t leverage modern GPU architecture:</p><ul><li><strong>Tensor cores</strong> (designed for massive matrix multiplications) sat <strong>70% idle</strong></li><li><strong>Memory bandwidth</strong> became the bottleneck, not the compute</li><li><strong>Training speed</strong> was good, but not “Transformer-competitive” on modern hardware</li><li><strong>Scaling to 100B+ parameters</strong> hit hardware limits</li></ul><p>This is where <strong>Mamba-2</strong> enters the story — a complete architectural reimagining that makes Mamba truly hardware-native. And it’s this breakthrough that <strong>Nemotron 3</strong> leverages to build the first production-scale hybrid LLM that outperforms pure Transformers on both speed AND accuracy.</p><h3><strong>2. Mamba-2: The State Space Duality Revolution</strong></h3><p><strong><em>What you’ll learn</em></strong><em>: How mathematical duality transforms sequential operations into parallel GEMM computations, achieving 95% GPU utilisation and 5.3× speedup over FlashAttention.</em></p><h4><strong>2.1 The Mathematical Breakthrough: State Space Duality (SSD)</strong></h4><p><strong>Mamba-2 isn’t just an optimisation — it’s a complete mathematical reimagining</strong> that achieves something extraordinary: proving that <strong>State Space Models and Transformers are dual representations of the same computation</strong>. This discovery, called <strong>State Space Duality (SSD)</strong>, enables Mamba-2 to be <strong>2–8× faster</strong> than Mamba-1 with <strong>16× larger state sizes</strong> while maintaining exact equivalence to attention mechanisms.</p><h4><strong>2.2 Understanding the Mamba-1 Limitations</strong></h4><p><strong>The Bottleneck</strong>: Mamba-1’s sequential recurrence (`h_t = A·h_{t-1} + B·x_t`) prevents parallelisation across tokens — each step must wait for the previous state. This creates four critical problems:</p><p>1. <strong>Sequential Dependency</strong>: Can’t parallelise across sequence dimension (token-by-token processing)</p><p>2. <strong>Memory Bandwidth Bottleneck</strong>: Non-coalesced memory access patterns waste GPU cycles</p><p>3. <strong>Underutilised Tensor Cores</strong>: Element-wise operations don’t map to GEMM-optimised hardware (35% GPU utilisation vs 88%+ for Transformers)</p><p>4. <strong>Small State Dimension</strong>: N=16 state size limits modelling capacity vs Transformer’s implicit full attention</p><p><strong>Result</strong>: Linear O(N) complexity but only 35% GPU utilisation — faster than Transformers in walltime, but wastes 65% of hardware capability.</p><h4><strong>2.3 Mamba-2’s SSD: Transforming Recurrence into Pure Matrix Math</strong></h4><p><strong>State Space Duality (SSD)</strong> reformulates sequential SSMs as <strong>structured masked attention</strong> computed via pure matrix multiplications (GEMMs), eliminating sequential scans.</p><blockquote><strong>The Breakthrough: Chunk-Based Parallelism</strong></blockquote><p><strong>The Core Innovation</strong>: SSD decomposes SSM computation into <strong>intra-chunk parallelism</strong> (process 128 tokens simultaneously via GEMM) + <strong>inter-chunk recurrence</strong> (sequential only at chunk boundaries).</p><p><strong>Impact</strong>(16k sequence, chunk size 128):</p><ul><li><strong>Before</strong>: 16,384 sequential steps → 35% GPU utilisation</li><li><strong>After</strong>: 128 sequential steps (chunks processed in parallel) → 95% GPU utilisation</li><li><strong>Result</strong>: O(N) complexity maintained, 128× reduction in sequential depth, exact mathematical equivalence</li></ul><blockquote><strong>How SSD Works</strong></blockquote><p><strong>Three-Step Process</strong>:</p><p>1. <strong>Chunk Sequence</strong>: Split L tokens into m chunks of size k (e.g., 16,384 = 128 chunks × 128 tokens)</p><p>2. <strong>Intra-Chunk (Parallel)</strong>: Reformulate recurrence x[i] = A·x[i-1] + B·u[i] as batched GEMM:</p><pre>x_{t+i} = A^i·x_t + Σ(j=0 to i-1) A^j·B·u_{t+i-1-j}</pre><ul><li>Precompute A powers [I, A, A², …, A^(k-1)] in parallel</li><li>All k states computed simultaneously via tensor cores</li></ul><p>3. <strong>Inter-Chunk (Sequential)</strong>: Only chunk boundaries require sequential processing:</p><pre>x_{chunk[c+1]} = A^k · x_{chunk[c]} + contribution[c]</pre><p>Sequential steps = m chunks (not L tokens!)</p><blockquote><strong>”Duality” = Same Computation, Two Views</strong></blockquote><pre>Recurrent SSM (sequential) ⬄ Structured Convolution (parallel)</pre><p>Same output, mathematically exact, but parallel view enables 95% GPU utilisation vs 35%.</p><blockquote><strong>SSD vs Selective Scan</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-kr7XFm3R-bLxV8FBF_gw.png" /></figure><p><strong>Key Takeaway</strong>: SSD is <strong>not a new model</strong> — it’s a <strong>mathematically equivalent but far more efficient execution strategy</strong>.</p><blockquote><strong>SSD vs Transformer Attention</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXXlfPlsLn05HgiuoEV20A.png" /></figure><p><strong>Result</strong>: Mamba-2 = Transformer quality with predictable linear costs.</p><blockquote><strong>Why SSD Enables Production LLMs</strong></blockquote><p><strong>1. Native 1M Context</strong>: 1M tokens = 8GB memory (vs 2TB for Transformer) → feasible on H100 80GB</p><p><strong>2. Training Speed</strong>: 340k tokens/sec vs 180k for Transformer (1.9× faster)</p><p><strong>3. Inference Efficiency</strong>: Same quality as 30B-param model with 3.2B active params (3.3× throughput)</p><p><strong>4. Hardware Match</strong>: GEMM-based operations → 95% tensor core utilisation vs 35% for Mamba-1</p><blockquote><strong>Three Approaches Compared</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*enGNcsPIM_w6vJIPcowjdw.png" /></figure><blockquote><strong>Why SSD Enables Production-Scale Long Context</strong></blockquote><p><strong>Memory Scaling Example</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMsn-a8DVY2DzDY63AOnFA.png" /></figure><p><strong>Real Production Example</strong> (Nemotron 3 Nano on H100 80GB):</p><pre># Configuration<br>context_length = 1_048_576 # 1M tokens<br>chunk_size = 256<br>num_chunks = 4096<br># Memory breakdown<br>input_embeddings = 1M × 2688 × 2 bytes = 5.4 GB<br>state_memory = 4096 chunks × 128 state × 2 bytes = 1 MB (!)<br>output_buffers = 5.4 GB<br><br>Total: ~11 GB (fits comfortably on H100 80GB)<br># Compare to Transformer<br>transformer_attention_matrix = 1M × 1M × 2 bytes = 2 TB<br>^ Physically impossible to store!</pre><p><strong>Throughput Scaling</strong>:</p><pre>Nemotron 3 Nano (SSD):<br>- 8k context: 142 tokens/sec<br>- 16k context: 128 tokens/sec (90% of baseline)<br>- 32k context: 115 tokens/sec (81% of baseline)<br>- 128k context: 92 tokens/sec (65% of baseline)<br>- 1M context: ~40 tokens/sec (estimated)<br>Llama-3.3–70B (Transformer):<br>- 8k context: 18 tokens/sec<br>- 16k context: 14 tokens/sec<br>- 32k context: 9 tokens/sec<br>- 128k context: OOM (out of memory)<br>- 1M context: Impossible</pre><p><strong>Linear scaling = predictable costs!</strong></p><h4><strong>2.4 Architecture Innovations: Making SSD Production-Ready</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghNjlrKHDGNU5UImhDWT5A.png" /></figure><h4><strong>2.5 SSD’s Key Architectural Choice</strong></h4><p><strong>The Genius</strong>: Mamba-2 restricts state matrix A to scalar × Identity (seemingly severe constraint), which:</p><ul><li>Reduces parameters from O(N) to O(1) for state transition</li><li>Enables structured algorithms computing attention-like outputs in O(N) time</li><li>Proves mathematical equivalence to softmax attention</li><li>Allows reformulation as pure GEMM operations (95% GPU utilisation vs 35%)</li></ul><h4><strong>2.6 Why State Space Duality Matters</strong></h4><p><strong>Theoretical Impact</strong>: SSD proves SSMs and Transformers are <strong>dual views of the same computation</strong> — not competing paradigms. This enables:</p><ul><li>Same representational power as attention (proven equivalence)</li><li>SSM states are interpretable as compressed attention patterns</li><li>Free mixing of SSM/attention layers (Nemotron 3’s hybrid strategy)</li><li>Use O(N) SSMs wherever long context matters, no quality trade-off</li></ul><h4><strong>2.7 Performance: Mamba-1 vs Mamba-2 vs Transformers</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJnzgTAUfr7ochTq7eKxVw.png" /></figure><p><strong>Conclusion</strong>: Mamba-2 achieves Transformer quality with linear scaling and optimal hardware utilisation — this powers 55.8% of Nemotron 3’s layers.</p><h4><strong>2.8 Nemotron 3: First Production Deployment at Scale</strong></h4><p>Nemotron 3 deploys Mamba-2 at 31.6B-235B parameter scale with a strategic hybrid design:</p><ul><li><strong>55.8% Mamba-2 layers</strong>: Linear O(N) throughput for local dependencies</li><li><strong>11.5% GQA attention</strong>: Strategic placement every ~8 layers for global reasoning</li><li><strong>Result</strong>: 3.3× faster than Qwen3–30B with equal/better accuracy across all benchmarks</li></ul><h3><strong>3. Nemotron 3: Production-Scale Hybrid Architecture Deep Dive</strong></h3><p><strong><em>What makes Nemotron 3 special</em></strong><em>: Seven groundbreaking innovations working in concert — from LatentMoE routing to 9-environment simultaneous RL training that solves catastrophic forgetting.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZAGNz3deKbGUg0rScp2D4A.png" /><figcaption><em>Comprehensive Nemotron 3 Architecture &amp; Training Methodology</em></figcaption></figure><p><strong>Nemotron 3</strong> represents a bold architectural bet: that the future of LLMs isn’t pure Transformers OR pure SSMs, but an <strong>intelligently designed hybrid</strong> that leverages each architecture’s strengths. The result? The <strong>first production LLM family</strong> achieving <strong>3.3× throughput</strong> over competing models while matching or exceeding accuracy across benchmarks.</p><h4><strong>3.0 Architecture Blueprint: Understanding the Complete System</strong></h4><p>The diagram above reveals Nemotron-3’s complete engineering blueprint — a dense architecture and results summary that showcases seven groundbreaking innovations working in concert.</p><blockquote><strong>Core Architectural Innovations</strong></blockquote><p><strong>1. Hybrid Mamba-Transformer MoE</strong></p><ul><li><strong>Mamba-2 layers</strong> (55.8%): O(N) linear complexity for constant-state, low-cost sequence modelling — replacing expensive attention for local dependencies</li><li><strong>Strategic attention layers</strong> (11.5%): Grouped-Query Attention (GQA) inserted every ~8 layers for high-fidelity global reasoning</li><li><strong>MoE layers</strong> (32.7%): Sparse activation via Mixture of Experts enables parameter scaling without proportional FLOPs increase</li><li><strong>Result</strong>: Transformer-level quality with dramatically lower computational cost</li></ul><p><strong>2. LatentMoE (Super/Ultra Variants)</strong></p><ul><li><strong>Problem</strong>: Standard MoE routing in high-dimensional token space (4096 dims) leads to overfitting and high memory bandwidth</li><li><strong>Solution</strong>: Compress tokens to latent space (1024 dims, 4× reduction) → route → expand back</li><li><strong>Benefits</strong>: 52% less communication overhead, +4% accuracy improvement (MMLU-Pro), better load balancing</li><li><strong>Counterintuitive win</strong>: Less information for routing = better generalisation</li></ul><p><strong>3. Multi-Token Prediction (MTP)</strong></p><ul><li><strong>Standard approach</strong>: Predict 1 token per forward pass (sequential bottleneck)</li><li><strong>Nemotron-3 approach</strong>: Predict multiple future tokens simultaneously via specialised prediction heads</li><li><strong>Mechanism</strong>: Speculative decoding validates multiple tokens in a single verification pass</li><li><strong>Impact</strong>: 1.5–2.4× inference throughput with zero quality degradation</li></ul><p><strong>4. NVFP4 Training</strong></p><ul><li><strong>Innovation</strong>: 4-bit floating-point precision for weights, activations, and gradients</li><li><strong>Training efficiency</strong>: 22% faster training, 20% less memory vs BF16</li><li><strong>Quality</strong>: Loss curves nearly identical to BF16 — minimal accuracy trade-off</li><li><strong>Scalability</strong>: Enables training Ultra (235B total params) on affordable GPU clusters</li></ul><p><strong>5. Native 1M Context</strong></p><ul><li><strong>Enabled by</strong>: Mamba-2’s O(N) complexity vs Transformer’s O(N²)</li><li><strong>Performance</strong>: Stable negative log-likelihood through full 1M token sequences</li><li><strong>Use cases</strong>: Full codebases, long documents, extended conversations, multi-agent memory</li><li><strong>Memory</strong>: Linear scaling (8GB for 1M context vs 2TB for Transformer attention matrix)</li></ul><p><strong>6. Multi-Environment RL Post-Training</strong></p><ul><li><strong>Simultaneous training across 9 environments</strong>: Math (AIME), code (HumanEval), tool use (BFCL), long-context (RULER), chat, commonsense, reasoning</li><li><strong>Methods</strong>: GRPO (Group Relative Policy Optimisation), asynchronous training, MTP-accelerated rollouts</li><li><strong>Key innovation</strong>: No catastrophic forgetting — accuracy improves across all domains simultaneously</li><li><strong>Result</strong>: Steady accuracy gains confirmed across benchmarks</li></ul><p><strong>7. Granular Reasoning Budget Control</strong></p><ul><li><strong>Mechanism</strong>: `&lt;think&gt;` token with explicit budget parameter controls reasoning depth</li><li><strong>User control</strong>: Specify computation budget → model generates thinking trace → final response</li><li><strong>Trade-off</strong>: Low budget (fast, direct answers) vs high budget (deep reasoning, step-by-step)</li><li><strong>Application</strong>: Optimize latency vs quality for specific use cases</li></ul><blockquote><strong>Empirical Performance Results</strong></blockquote><p><strong>Throughput-Accuracy Frontier</strong></p><ul><li>Nemotron-3 Nano: ~3.3× throughput vs Qwen-3 (30B) at equivalent or better accuracy</li><li>Establishes new Pareto frontier for speed-quality trade-offs</li></ul><p><strong>LatentMoE Validation</strong></p><p>Consistently outperforms standard MoE across all benchmarks:</p><pre>- MMLU-Pro: +4.57% (68.21% vs 63.64%)<br>- HumanEval (code): +3.5% (82.7% vs 79.2%)<br>- AIME 2025 (math): +2.5% (92.3% vs 89.8%)<br>- BFCL (tool use): +2.1% (76.2% vs 74.1%)<br>- RULER@256k: +2.8% (72.1% vs 69.3%)</pre><p><strong>NVFP4 Training Efficiency</strong></p><ul><li>Training loss curves overlap with BF16 (validates quality preservation)</li><li>22% reduction in training time, 20% reduction in memory usage</li><li>Critical for democratising large-scale LLM training</li></ul><p><strong>Long-Context Stability</strong></p><ul><li>Flat perplexity from 4k through 1M tokens</li><li>No quality degradation at extreme lengths</li><li>Validates Mamba-2’s linear scaling advantage</li></ul><blockquote><strong>Model Family Design Philosophy</strong></blockquote><p><strong>Nano</strong> (31.6B total, 3.2B active)</p><pre>- Target: Single-GPU deployment, agentic AI, edge inference<br>- Innovation: Granular MoE (128 experts, 4.69% utilization)<br>- Use case: Fast, efficient, 1M context on H100/A100</pre><p><strong>Super</strong> (73B total, 8B active)</p><pre>- Target: IT automation, multi-agent systems, enterprise<br>- Innovation: LatentMoE for accuracy boost at same FLOPs<br>- Use case: Balance of capability and efficiency</pre><p><strong>Ultra</strong> (235B total, 22B active)</p><pre>- Target: Research, SOTA reasoning, complex tasks<br>- Innovation: Full stack (LatentMoE + MTP + NVFP4 + tensor parallelism)<br>- Use case: Maximum capability with manageable inference cost</pre><blockquote><strong>The Paradigm Shift</strong></blockquote><p>Nemotron 3 proves the future isn’t <strong>Transformers vs SSMs</strong> — it’s <strong>intelligent hybrids</strong>:</p><ul><li>Use <strong>Mamba-2</strong> for O(N) throughput on local dependencies (80% of computation)</li><li>Insert <strong>attention</strong> strategically for global reasoning (20% of computation)</li><li>Scale parameters via <strong>sparse MoE</strong> without scaling FLOPs</li><li>Optimise training with <strong>NVFP4</strong> quantisation</li><li>Accelerate inference with <strong>MTP</strong> speculative decoding</li></ul><p>This architecture blueprint pushes the efficiency frontier while maintaining full open-source accessibility.</p><h4><strong>3.1 Model Family: Nano, Super, Ultra</strong></h4><p>The team built three variants targeting different deployment scenarios, all sharing a common architectural philosophy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SyV5RE483FbC1XUWSWCGA.png" /></figure><p><strong>Universal Features</strong> (all variants):</p><ul><li><strong>1M native context</strong> (no sliding window hacks)</li><li><strong>&lt;think&gt; token budget control</strong> (controllable reasoning depth)</li><li><strong>9-environment simultaneous RL</strong> (math+code+tools+chat+LC without forgetting)</li><li><strong>Fully open-source</strong> (weights, training data, RL infrastructure)</li></ul><h4><strong>3.2 Nano Deep Dive: The “Mamba Swarm” Architecture</strong></h4><p>Let’s dissect Nemotron 3 Nano’s <strong>52-layer hybrid architecture</strong>, which achieves remarkable efficiency through strategic layer placement:</p><blockquote><strong>3.2.1 Layer Orchestration Strategy</strong></blockquote><pre>Total: 52 layers (indexed 0–51)<br>Distribution:<br>- Mamba-2 layers: 29 (55.8%)<br>- GQA attention: 6 (11.5%)<br>- MoE FFN layers: 17 (32.7%)<br>Pattern (repeating blocks):<br>Block Type 1 (25 layers, 5 repetitions):<br>Mamba2 → Mamba2 → MoE → Mamba2 → GQA → MoE<br>Block Type 2 (9 layers, 3 repetitions):<br>Mamba2 → GQA → MoE<br>Block Type 3 (8 layers, 4 repetitions):<br>Mamba2 → MoE</pre><p><strong>Why This Specific Pattern?</strong></p><p>1. <strong>Mamba-2 Dominance</strong> (55.8%): Linear scaling for throughput</p><ul><li>Handles local dependencies efficiently</li><li>Provides “highway” for information flow</li><li>O(N) complexity enables 1M context</li></ul><p>2. <strong>Strategic GQA Placement</strong> (11.5%): Global reasoning checkpoints</p><ul><li>Every ~8 layers → ensures long-range interaction</li><li>Grouped-Query Attention (not full MHA) → 8× cheaper</li><li>Acts as “deliberation points” in the network</li></ul><p>3. <strong>Granular MoE</strong> (32.7%): Parameter scaling without cost</p><ul><li>128 experts, activate only 6 → <strong>4.69% utilization</strong></li><li>Shared experts (2) + routed experts (4) for stability</li><li>Sparse activation keeps FLOPs equivalent to dense 3.2B</li></ul><blockquote><strong>3.2A LatentMoE: Routing in Compressed Space (Super/Ultra)</strong></blockquote><p><strong>Problem</strong>: Standard MoE routes tokens in high-dimensional space (4096 dims), allowing routers to overfit training patterns and causing poor generalisation.</p><p><strong>Counterintuitive Discovery</strong>: Less information for routing = better generalisation (+4.57% accuracy boost)</p><p><strong>Solution</strong>: LatentMoE compresses tokens to a 1024-dimensional latent space (4× reduction) before routing, then processes experts in this compressed space.</p><blockquote><strong>Mechanism</strong></blockquote><p><strong>Standard MoE (Nano)</strong>: Token (4096D) → Router → Select 6/128 experts → Process in 4096D → Combine</p><p><strong>LatentMoE (Super/Ultra)</strong>: Token (4096D) → <strong>Compress to 1024D</strong> → Router → Select 12–24 experts → Process in 1024D → Expand to 4096D</p><blockquote><strong>Why It Works</strong></blockquote><p><strong>1. Information Bottleneck</strong>: Compression forces the router to learn semantic patterns, not noise — only robust features survive 4× reduction</p><p><strong>2. Memory Efficiency</strong>: Processing 1024D instead of 4096D reduces bandwidth from ~16 GB to ~4 GB per forward pass (4× reduction)</p><p><strong>3. Load Balancing</strong>: Compressed routing prevents narrow specialisation, achieving 0.5–2% expert variance vs 1–90% in standard MoE</p><blockquote><strong>Results</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*vYHBfjQIXpR1gc1KLyBm6w.png" /></figure><p><strong>Training</strong>: 22% faster, 20% less memory, 52% less communication — same FLOPs</p><p><strong>Scaling</strong>: Maintain 4× compression ratio across all model sizes (empirically optimal)</p><h4><strong>3.2B Multi-Token Prediction (MTP): Speculative Decoding</strong></h4><p><strong>Problem</strong>: Standard autoregressive generation is sequential — must wait for token N before generating token N+1, wasting parallel compute.</p><p><strong>Speed Breakthrough</strong>: 4 tokens from 2 forward passes = 3.3× throughput with zero quality loss</p><p><strong>Solution</strong>: Train K=4 prediction heads to speculate future tokens simultaneously, then verify in one parallel pass.</p><blockquote><strong>Mechanism</strong></blockquote><p><strong>Training</strong>:</p><ul><li>Add 4 prediction heads (predict 1, 2, 3, 4 tokens ahead)</li><li>Loss: 70% standard next-token + 30% multi-token (0.9^i discount for farther predictions)</li><li>Schedule: 80% training without MTP, 20% with MTP heads added</li></ul><p><strong>Inference</strong>:</p><p>1. <strong>Speculate</strong>: MTP heads predict next 4 tokens in parallel (1 forward pass)</p><p>2. <strong>Verify</strong>: Run main model with all 4 tokens to check accuracy (1 forward pass)</p><p>3. <strong>Accept</strong>: Keep longest matching prefix (all 4, or fall back to verified token)</p><p><strong>Example</strong>: Context “The capital of France is” → Speculate [“Paris”, “,”, “which”, “is”] → Verify matches → Accept all 4</p><p><strong>Result</strong>: 4 tokens from 2 forward passes instead of 4 (2× speedup). Quality is <strong>identical</strong> because only verified tokens are accepted.</p><blockquote><strong>Performance</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*SlgYVyC60NAgwtpfffsMUQ.png" /></figure><p><strong>Acceptance Rates</strong>: Code 72%, Math 68%, Writing 65%, Overall 65% (k=4 optimal — diminishing returns beyond)</p><h4><strong>3.2C NVFP4: 4-Bit Floating Point Training</strong></h4><p><strong>Problem</strong>: Training 235B parameter models needs ~2TB memory (BF16), requiring 25× H100 GPUs.</p><p><strong>Cost Savings</strong>: 25 GPUs → 17 GPUs with &lt;0.2% accuracy loss</p><p><strong>Solution</strong>: NVFP4 uses 4-bit floating point (1 sign + 2 exp + 1 mantissa) with per-channel scaling, reducing memory 1.54× while maintaining &lt;0.2% accuracy loss.</p><blockquote><strong>Format &amp; Quantization</strong></blockquote><p><strong>FP4 Representation</strong>: 9 values (0, ±0.25, ±0.375, ±0.5, ±0.75, ±1.0, ±1.5, ±2.0, ±3.0)</p><p><strong>Per-Channel Scaling</strong>:</p><p>1. Find absmax per output channel (row)</p><p>2. scale = absmax / 3.0 (map to FP4 range)</p><p>3. Quantize: value → value/scale → round to nearest FP4</p><p>4. Store: scales (BF16) + quantized values (FP4)</p><p><strong>Example</strong>: 4096×4096 matrix: 33.6 MB (BF16) → 8.4 MB (FP4) = 4× compression</p><blockquote><strong>Dual-Precision Training</strong></blockquote><p><strong>Strategy</strong>: Store in FP4, compute in BF16</p><p>1. <strong>Forward</strong>: Dequantize FP4 weights → BF16 → compute → loss</p><p>2. <strong>Backward</strong>: Compute gradients (BF16) → quantize to FP4 for storage</p><p>3. <strong>Optimizer</strong>: Maintain BF16 master weights + momentum/variance → dequantize gradients → update (BF16) → requantize weights</p><p><strong>Why It Works</strong>:</p><ul><li>Computation in BF16 (no accumulation errors)</li><li>Optimiser in BF16 (handles tiny updates like 1e-8)</li><li>Storage in FP4 (memory savings)</li><li>H100/H200 native FP4 ↔ BF16 conversion</li></ul><blockquote><strong>Results</strong></blockquote><p><strong>Memory</strong> (Ultra 235B): 2TB (BF16) → 1.3TB (NVFP4) | 25 GPUs → 17 GPUs</p><p><strong>Accuracy</strong>: &lt;0.2% degradation (converges to 1.851 vs 1.847 loss on 25T tokens)</p><p><strong>Speed</strong>: 1.6× faster training (less memory traffic, FP4 tensor cores, larger batches)</p><h4><strong>3.2D Granular Budget Control: &lt;think&gt; Token System</strong></h4><p><strong>Problem:</strong> Standard LLMs have no middle ground — either answer directly (fast, less accurate) or use a full Chain-of-Thought (slow, more accurate).</p><p><strong>User Control</strong>: Explicitly trade computation budget for reasoning depth — optimise latency vs quality per query</p><p><strong>Solution</strong>: Special &lt;think budget=N&gt; tokens allow explicit control over reasoning depth.</p><blockquote><strong>Mechanism</strong></blockquote><p><strong>Format</strong>:</p><pre>Input: &lt;think budget=150&gt;[query]&lt;/think&gt;<br>Output: &lt;think tokens_used=142&gt;[reasoning]&lt;/think&gt;Answer: [response]</pre><p><strong>Training</strong>:</p><ul><li><strong>Loss components</strong>: Standard LM loss + structure penalty (use tokens correctly) + overuse penalty (budget × 0.01) + underuse penalty (encourages 50–100% utilization)</li><li><strong>Data augmentation</strong>: Train each example at 4 budget levels (50%, 75%, 100%, 125% of optimal)</li><li><strong>Result</strong>: Model learns to adapt reasoning depth to available budget</li></ul><p><strong>Auto-Budget Prediction</strong>: Small MLP (256→64 neurons) predicts optimal budget from query features (length, math symbols, code keywords, reasoning words, multi-step indicators)</p><p><strong>Examples</strong>:</p><ul><li>“What is the capital of France?” → 25 tokens (factual)</li><li>“Solve 3x² — 5x + 2 = 0” → 112 tokens (medium math)</li><li>“Prove infinitely many primes” → 287 tokens (complex proof)</li></ul><blockquote><strong>Performance Trade-off (MATH-500)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*Kzen35FMHSWNBUrzC3ol9Q.png" /></figure><p><strong>Optimal</strong>: 100–150 tokens (diminishing returns beyond — 75% → 76% for 5× compute)</p><blockquote><strong>Technical Specifications</strong></blockquote><pre># Nano Architecture Details<br>model_dim = 2688 # Hidden dimension<br>num_layers = 52<br>num_attention_heads = 32 # Q heads<br>num_kv_heads = 2 # GQA: 16:1 Q/KV ratio<br>head_dim = model_dim // num_attention_heads = 84<br># Mamba-2 Configuration<br>mamba_state_size = 128 # N in SSD formulation<br>mamba_num_groups = 8 # Group state space<br>mamba_conv_kernel = 4 # Local conv before SSD<br># MoE Configuration<br>num_experts = 128<br>experts_active = 6 # Per token<br>shared_experts = 2 # Always active<br>expert_capacity = None # No hard limits<br>router_type = &quot;learned_mlp&quot; # Not simple linear<br>router_activation = &quot;squared_relu&quot;<br>gating_fn = &quot;sigmoid&quot; # Sparse routing<br># Context &amp; Training<br>max_position = 1_048_576 # 1M native context<br>vocab_size = 256_000 # BPE tokenizer<br>no_rope = True # Mamba doesn&#39;t need RoPE<br>no_dropout = True # RL-trained models<br>no_bias = True # Cleaner optimization</pre><h4><strong>3.3 Training Pipeline: 25T Tokens + Long-Context Mastery</strong></h4><blockquote><strong>3.3.1 Pretraining (23.5T + 1.5T tokens)</strong></blockquote><p><strong>Phase 1: Diverse Foundation (23.5T tokens)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wlb3slo0s3VmkgfGSBYerQ.png" /></figure><p><strong>Phase 2: Quality Refinement (1.5T tokens)</strong></p><p>22% STEM-SFT, 20% synthetic crawl, 18% math CoT, 15% code solutions, 12% dialogues, 13% tool use</p><p><strong>Key Innovations</strong>: Nemotron-CC-v2.1 (40% deduplication, LLM quality filter, PII removal), CC-Code-v1 (execution-based filtering, open licenses only)</p><blockquote><strong>3.3.2 Long-Context Training (121B specialised tokens)</strong></blockquote><p><strong>Progressive Context Scaling</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yinJLrP48DG-r53rZ3QoA.png" /></figure><h4><strong>3.4 Revolutionary 9-Environment Simultaneous RL</strong></h4><p><strong>Industry First</strong>: Train on 9 objectives simultaneously without catastrophic forgetting — all capabilities improve together</p><p><strong>The Catastrophic Forgetting Problem</strong>:</p><p>Traditional LLM training suffers from a fundamental issue:</p><pre>Train on Math → Math ↑ 15%, Chat ↓ 8%<br>Train on Chat → Chat ↑ 12%, Math ↓ 10%<br>Sequential training = endless back-and-forth!</pre><p><strong>Solution</strong>: Train on 9 objectives simultaneously using Group Relative Policy Optimisation (GRPO), preventing interference between tasks.</p><blockquote><strong>3.4.1 The 9 Training Environments</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78PoReoY5GhCh6_BErTS1A.png" /></figure><p><strong>Weights sum to 100%</strong>, balancing diverse objectives.</p><blockquote><strong>3.4.2 GRPO: Preventing Catastrophic Forgetting</strong></blockquote><p><strong>Mechanism</strong>: Sample all 9 environments → compute group-relative advantages (per-env baseline) → PPO clipping (0.9–1.1) → weighted loss → single update</p><p><strong>Why it works</strong>: Independent normalisation prevents task interference, clipping prevents destructive updates, shared value head learns universal returns</p><blockquote><strong>3.4.3 Results: No Forgetting Achieved</strong></blockquote><p><strong>Comparison</strong>: Post-SFT → Single-Env RL → 9-Env Simultaneous RL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*cFXiLQWcCeGsX0dKlxpY7A.png" /></figure><p><strong>Key Result</strong>: Single-environment RL shows classic forgetting (↑ on target, ↓ on others). <strong>9-environment RL improves ALL tasks simultaneously</strong>— first LLM to achieve this.</p><h4><strong>3.5 Performance Benchmarks: Speed + Accuracy</strong></h4><blockquote><strong>3.5.1 Throughput Analysis</strong></blockquote><p><strong>Test</strong>: Batch=1, 8k context, 512 token generation, H200 80GB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*C2XJhq5WgwdVdZiaPPPW3A.png" /></figure><p><strong>Context Scaling</strong> (Nemotron-3 vs Transformers):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*wOcjwDLWoSPBFAtKiw3_PQ.png" /></figure><p><strong>Result</strong>: Linear O(N) scaling enables graceful degradation vs Transformer memory walls.</p><blockquote><strong>3.5.2 Key Accuracy Benchmarks</strong></blockquote><p><strong>Core Capabilities</strong> (Nano/Super/Ultra vs Frontier Models):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjMCkaOqNrvkb30mWpKrJA.png" /></figure><p><strong>Key Insights</strong>:</p><ul><li><strong>Competitive with frontier models</strong> despite 3.2B active params (vs 70B+)</li><li><strong>Dominates long context</strong> (RULER: 54% vs GPT-4’s 31% at 1M tokens)</li><li><strong>Strong STEM + coding</strong> (AIME 89%, HumanEval 78%)</li></ul><h4><strong>3.6 Architecture Philosophy: Why Hybrid Wins</strong></h4><p><strong>Key Design Principles</strong>:</p><p>1. <strong>Mamba-2 for Throughput</strong> (55.8% of layers)</p><ul><li><strong>O(N) scaling</strong> enables 1M context without memory explosion</li><li><strong>SSD formulation</strong> provides attention-equivalent expressivity</li><li><strong>Hardware-native GEMM</strong> operations maximise GPU utilisation (95%)</li></ul><p>2. <strong>GQA for Global Reasoning</strong> (11.5% of layers)</p><ul><li><strong>Strategic placement</strong> every ~8 layers acts as “deliberation checkpoints”</li><li><strong>Grouped-Query Attention</strong> (16:1 Q/KV ratio) reduces cost by 8×</li><li><strong>Necessary for multi-hop reasoning,</strong> where Mamba-2 alone struggles</li></ul><p>3. <strong>LatentMoE for Efficient Scaling</strong> (32.7% of layers)</p><ul><li><strong>31.6B total capacity, 3.2B active</strong> → specialist experts without cost</li><li><strong>Latent routing</strong> (4× compression) improves generalisation (+4% accuracy!)</li><li><strong>Sparse activation</strong> maintains efficiency (same FLOPs as dense 3.2B)</li></ul><p><strong>Emergent Properties</strong>:</p><ul><li><strong>Linear context scaling</strong>: 1M tokens feasible in production</li><li><strong>No catastrophic forgetting</strong>: 9-env RL trains all capabilities simultaneously</li><li><strong>Hardware efficiency</strong>: 95% tensor core utilisation, 3.3× faster than competitors</li><li><strong>Deployable</strong>: 3.2B active params fit on a single A100/H100</li><li><strong>Fully open</strong>: Weights + data + code available</li></ul><p><strong>The Future</strong>: Mamba-2 + Transformer + MoE hybrids represent the <strong>new SOTA paradigm</strong>. Pure Transformer-only models are now legacy architecture.</p><h3><strong>Conclusion: The Hybrid Era Begins</strong></h3><p>After this deep dive into Nemotron 3’s architecture, training methodology, and performance, one conclusion is undeniable: <strong>the future of LLMs is hybrid architectures</strong>.</p><p><strong>Final Thought</strong>: Nemotron 3 isn’t just another model release — it’s the architectural blueprint that makes pure Transformers obsolete.</p><p><strong>What Nemotron 3 proves once and for all</strong>:</p><ul><li><strong>Mamba-2’s</strong> <strong>O(N) scaling</strong> enables true 1M context windows in production</li><li><strong>Strategic attention placement</strong> (11.5% of layers) provides global reasoning without quadratic costs</li><li><strong>LatentMoE’s compressed routing</strong> counter-intuitively improves both efficiency AND accuracy</li><li><strong>9-environment simultaneous RL</strong> solves catastrophic forgetting — the first LLM to achieve this</li><li><strong>Radical openness</strong> (weights + 10T tokens data + training code) enables reproducible research</li></ul><p><strong>The Bigger Picture</strong>:</p><p>Nemotron 3 marks the end of the <strong>”pure Transformer” era</strong>. Just as ResNets established residual connections as standard in computer vision, Nemotron 3 establishes the hybrid SSM-Transformer-MoE pattern as the <strong>new baseline</strong> for LLMs.</p><p><strong>Pure Transformers are now expensive nostalgia.</strong> The future is:</p><p>1. <strong>Hybrid cores</strong> (55% Mamba-2 + 11% Attention)</p><p>2. <strong>Sparse scaling</strong> (MoE with LatentMoE routing)</p><p>3. <strong>Multi-objective training</strong> (9+ simultaneous environments)</p><p>4. <strong>Linear context scaling</strong> (O(N) throughput to 1M+ tokens)</p><p>Nemotron 3 didn’t just deliver a faster model — it <strong>redefined what’s possible</strong> in production LLM architecture.</p><h4><strong>What’s Next?</strong></h4><p><strong>The weights are open. The data is released. The blueprint is clear.</strong></p><p>Nemotron 3 represents the most significant shift in LLM architecture since the Transformer paper. Whether you’re building agentic systems, processing long documents, or optimising inference costs, the hybrid era has begun.</p><p><em>What will you build with 1M context windows and 3.3× speedup?</em></p><h3><strong>References</strong></h3><ul><li><a href="https://research.nvidia.com/labs/nemotron/Nemotron-3/">Nemotron 3 Technical Reports</a></li><li><a href="https://research.nvidia.com/labs/nemotron/files/Nemotron-3-Nano-Technical-Report.pdf">Nemotron 3 Nano Paper</a></li><li><a href="https://goombalab.github.io/blog/2024/mamba2-part1-model/">Mamba-2 SSD Paper</a></li><li><a href="https://medium.com/@aadishagrawal/mamba-the-breakthrough-that-makes-transformers-look-expensive-30611294d575">My Previous Mamba Post</a></li><li>NeMo Framework (<a href="https://github.com/NVIDIA/NeMo">GitHub</a>)</li><li><a href="https://huggingface.co/datasets/nemotron-cc-v2.1">Nemotron-CC-v2.1 Dataset</a></li></ul><h3><strong>Let’s Connect</strong></h3><p><strong>Found this deep dive valuable?</strong></p><ul><li>👏 <strong>Clap</strong> if Nemotron 3’s architecture blew your mind</li><li>💭 <strong>Comment</strong> with your questions — I respond to every one</li><li>🔗 <strong>Follow</strong> for more deep dives into cutting-edge AI architectures</li></ul><p><strong>Connect with me</strong>: <a href="https://www.linkedin.com/in/aadish-agrawal-740bb48b">LinkedIn</a> | <a href="https://medium.com/@aadishagrawal">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8addf4af280b" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/nemotron-3-a-hybrid-mamba-transformer-revolution-for-agentic-ai-8addf4af280b">Nemotron 3: A Hybrid Mamba-Transformer Revolution for Agentic AI</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>