<?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 Oxotall on Medium]]></title>
        <description><![CDATA[Stories by Oxotall on Medium]]></description>
        <link>https://medium.com/@oxotall?source=rss-11db483088aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H5mWfyC73FAlto8yY7R2-g.jpeg</url>
            <title>Stories by Oxotall on Medium</title>
            <link>https://medium.com/@oxotall?source=rss-11db483088aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:42:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oxotall/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[Mixture Density Networks]]></title>
            <link>https://oxotall.medium.com/mixture-density-networks-bccf48edb4c3?source=rss-11db483088aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/bccf48edb4c3</guid>
            <category><![CDATA[mixture-density-network]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gaussian-mixture-model]]></category>
            <dc:creator><![CDATA[Oxotall]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 07:15:38 GMT</pubDate>
            <atom:updated>2026-07-21T07:15:38.864Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine a self-driving car approaching an obstacle in the middle of the road. Human drivers in the logs went around it on the left half the time and on the right half the time. Both answers are correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xhs_cAVe-B6fgFc7dliECQ.png" /></figure><p>Now train a regression network with MSE on this data and ask it what to do. It predicts the average of the two correct answers — and drives straight into the obstacle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0j3vD2OCgo-uvXP-SGIgw.png" /><figcaption>Obstacle avoidance data: one road, two ways around — train/test scatter of lateral position along the road, with the obstacle in the middle and two symmetric avoidance paths</figcaption></figure><p>This is the core problem this post is about. When the target distribution is multimodal — several distinct correct answers for the same input — any loss built on a unimodal assumption (and MSE is exactly that) pushes the model toward the mean of the modes. That mean sits <em>between</em> the correct answers and is often not a correct answer at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4KwyvSsyHY_FBCqTTMBvA.png" /><figcaption>MSE prediction as a flat line passing through the obstacle while test data splits into two arcs</figcaption></figure><p>A Mixture Density Network (MDN), introduced by Christopher Bishop in his classic <a href="https://publications.aston.ac.uk/id/eprint/373/1/NCRG_94_004.pdf">1994 technical report</a>, fixes this by changing what the network outputs. Rather than a single point, the network outputs the parameters of a full conditional distribution — a mixture of Gaussians — so it can say “left with probability 0.5, right with probability 0.5” and does not have to represent the two outcomes by a single compromise prediction.</p><h3><strong>The goal</strong></h3><p>We want to model the full conditional distribution of the target — one that is allowed to have several modes — as a mixture of Gaussians whose parameters a neural network predicts from the input 𝑥. Let’s first spell out what probabilistic model ordinary MSE regression already assumes.</p><h3><strong>The math</strong></h3><p>The clean way to see what MSE assumes is through maximum likelihood, so let’s state the probabilistic model behind ordinary regression explicitly. A network with parameters 𝜃 predicts 𝑦̂(𝑥), and we assume the observed target is that prediction plus Gaussian noise of fixed variance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dJ_LjVrI9AzvJxYkzDh3A.png" /></figure><p>where 𝜎² is a fixed constant, not something the model learns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVRQTQm2iB12Y23LDe8qyg.png" /><figcaption>Unimodal data: at any slice 𝑥₀ the targets scatter around a single center, so 𝑝(𝑦 | 𝑥₀) is well described by one Gaussian — exactly the model behind MSE, and its mean is a valid prediction</figcaption></figure><p>For a dataset of 𝑁 i.i.d. pairs (𝑥ᵢ, 𝑦ᵢ), we maximize the likelihood of the dataset, i.e. minimize its negative logarithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*222E_BG63p_1ywfESZhGWg.png" /></figure><p>After removing additive constants and positive factors that do not affect the optimizer, minimizing the negative log-likelihood is equivalent to minimizing the sum of squared errors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNS4iOD7vOhvL5-WwLHasg.png" /></figure><p>MSE, then, carries a built-in assumption: it is maximum likelihood under a <em>single</em> Gaussian with one mean per input — a strictly unimodal model of the target. And the minimizer of MSE is the conditional mean 𝔼[𝑦 | 𝑥], which for our road data is the middle of the obstacle.</p><p>The MDN keeps the exact same recipe and changes only the conditional density: the single Gaussian becomes a mixture of 𝐾 Gaussians:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxAQbaajRJTVb2c_oHFFLg.png" /></figure><p>where 𝜋ₖ are the mixing weights (non-negative, summing to 1), 𝜇ₖ are the component means, and 𝜎ₖ are the component standard deviations — all predicted by the network as functions of 𝑥.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyFEh-KqvM_VnHyA1oXDJQ.png" /><figcaption>The same two Gaussian components under three different 𝜋: the weights rescale each component’s contribution, shifting the mixture’s mass from one mode to the other without moving the modes themselves</figcaption></figure><p>We again maximize the likelihood of the i.i.d. dataset, i.e. minimize its negative logarithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yv0d07J-FnkZKoO0GWmuyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wn_pYd0skOE8QeJSJp5BtA.png" /><figcaption>Predicted 𝑝(𝑦 | 𝑥₀) at the obstacle: two modes over the avoidance paths, near-zero density at the obstacle itself</figcaption></figure><p>Note what this loss rewards: a training point 𝑦ᵢ only needs to be well explained by <em>some</em> component. A point on the left arc can be covered by component 1 and a point on the right arc by component 2. Once the components specialize, a point on one path gives most of its responsibility — and therefore most of its gradient — to the corresponding component. This greatly reduces the pressure to average the modes, although specialization is not guaranteed. That is the whole trick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leqx6IfLGaXOJn5xvMpr3w.png" /><figcaption>Two learned mean curves hugging the upper and lower avoidance arcs</figcaption></figure><h3><strong>Architecture</strong></h3><p>The body of the network can be anything — an MLP, a CNN, a transformer encoder. Only the head changes. The number of components 𝐾 is fixed in advance, and the network gets three groups of outputs:</p><ul><li>𝐾 outputs for the means 𝜇ₖ — raw linear outputs, no activation needed.</li><li>𝐾 outputs for the standard deviations 𝜎ₖ (or variances) — these must be positive, so pass the raw output through exp or softplus.</li><li>𝐾 outputs for the mixing weights 𝜋ₖ — these must be a valid categorical distribution, so normalize them with a softmax.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FA24u996mV_Rqj0xLpggEQ.png" /><figcaption>MDN head diagram — shared backbone splitting into three output branches (means, exp/softplus for sigmas, softmax for mixing weights)</figcaption></figure><p>Choosing 𝐾 up front is a real weakness. Too few components and the model cannot represent all the modes (underfitting — two behaviors forced through one Gaussian brings the averaging problem right back). Too many and components either duplicate each other or overfit noise. In practice, a moderately over-specified can work because unnecessary components may receive very small weights, but this behavior is not guaranteed and should be validated empirically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9t1cU-8BTBHDR2sRujiYpw.png" /><figcaption>Four components where two pairs share the arcs and the mixing weights redistribute along the road</figcaption></figure><h3><strong>Getting a prediction out of an MDN</strong></h3><p>At inference time the network outputs 𝐾 triples (𝜋ₖ, 𝜇ₖ, 𝜎ₖ). What happens with them depends on the consumer:</p><ul><li><strong>Sample.</strong> First draw a component index from the categorical distribution over 𝜋, then draw a point from that component’s Gaussian. This gives diverse, realistic outcomes — great for simulation and generation</li><li><strong>Highest-weight component heuristic.</strong> Take the component with the largest 𝜋ₖ and report its mean. A cheap, deterministic point estimate that is at least <em>on</em> one of the modes.</li></ul><p>And one thing that must never be done: reporting the weighted average — ∑ₖ 𝜋ₖ 𝜇ₖ. That is exactly the “in between” answer the MDN was built to avoid — it reintroduces the obstacle collision through the back door.</p><h3><strong>Failure modes</strong></h3><p>An important distinction first, because the word “collapse” hides two different diseases in the MDN world, and the remedies differ.</p><p><strong>Collapse to the mean.</strong> All components slide into the same point between the modes — regression to the mean returns, and the car hits the pole again. This happens when gradients from both modes pull every component simultaneously, which is common early in training or when 𝐾 is too small.</p><p><strong>Coverage collapse.</strong> All components settle on one popular mode (“everyone drives right”), and rare modes get no component at all. Because rare modes contribute proportionally fewer training examples, their influence on the total likelihood may be too small to secure a dedicated component.</p><p><strong>Variance collapse.</strong> A separate, purely numerical pathology: a component parks its mean on a training point and drives 𝜎 → 0. The density at that point blows up, the likelihood goes to infinity, and training NaNs out.</p><h4><strong>Fixes</strong></h4><p>For <strong>collapse to the mean</strong>, the classic family of remedies is Winner-Takes-All (WTA) training: for each training point, only the best-matching component receives a gradient. The idea originates in <a href="https://papers.nips.cc/paper_files/paper/2012/hash/cfbce4c1d7c425baf21d6b6f2babe6be-Abstract.html">Multiple Choice Learning by Guzmán-Rivera, Batra and Kohli</a> as the “oracle” set-loss — a set of predictions pays only for its most accurate member; the name WTA was attached by later works. Components specialize instead of all being dragged toward the average.</p><p>For <strong>coverage collapse</strong>, <a href="https://arxiv.org/abs/1906.03631">Makansi et al.</a> proposed <em>Evolving</em> WTA (EWTA): each training point updates the 𝑛 components closest to the target, and 𝑛 shrinks during training from 𝐾 to 1. Early on every component receives gradient, so none starves; by the end each settles on its own mode. A complementary, structural fix is to pin the modes in advance: <a href="https://arxiv.org/abs/1910.05449">MultiPath</a> clusters the data into a fixed set of anchors, and the network only classifies over them and regresses small offsets.</p><p>For <strong>variance collapse</strong>, the standard tool is a hard floor on 𝜎 (softplus plus a small constant ε, or an explicit clamp).</p><h3><strong>Conclusion</strong></h3><p>The one idea to take away: MSE is the maximum-likelihood loss of a single fixed-variance Gaussian, so whenever the conditional target distribution has several valid answers, the population-optimal MSE prediction is the conditional mean, which may lie between the valid modes and therefore be invalid. A Mixture Density Network keeps the usual backbone and swaps the head for 3𝐾 outputs — means, positive variances, softmax weights — trained by mixture negative log-likelihood; at inference the options are sampling, or taking the argmax-𝜋 mode, but never the weighted mean. An MDN is a natural option when the conditional target distribution contains several distinct modes — anywhere the average of several right answers is a wrong one.</p><h3><strong>Links &amp; References</strong></h3><ul><li><a href="https://publications.aston.ac.uk/id/eprint/373/1/NCRG_94_004.pdf">Mixture Density Networks — C. M. Bishop (1994)</a> — the original technical report introducing MDNs.</li><li><a href="https://arxiv.org/abs/1308.0850">Generating Sequences With Recurrent Neural Networks — A. Graves (2013)</a> — MDN head on an RNN for handwriting generation; practical notes on sampling and training stability.</li><li><a href="https://papers.nips.cc/paper_files/paper/2012/hash/cfbce4c1d7c425baf21d6b6f2babe6be-Abstract.html">Multiple Choice Learning: Learning to Produce Multiple Structured Outputs — Guzmán-Rivera, Batra, Kohli (NIPS 2012)</a> — the “oracle” set-loss that later works turned into Winner-Takes-All training.</li><li><a href="https://arxiv.org/abs/1906.03631">Overcoming Limitations of Mixture Density Networks — Makansi et al. (CVPR 2019)</a> — analysis of MDN collapse and the Evolving WTA + sampling-and-fitting framework.</li><li><a href="https://arxiv.org/abs/1910.05449">MultiPath: Multiple Probabilistic Anchor Trajectory Hypotheses for Behavior Prediction — Chai et al. (CoRL 2019)</a> — anchor-based structural fix for mode coverage in driving.</li><li><a href="https://github.com/Oxotall/MDNVisualization">Code repository for this post</a> — code that generated the figures in this article.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bccf48edb4c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing Attention in Text-to-Image Diffusion]]></title>
            <link>https://oxotall.medium.com/visualizing-attention-in-text-to-image-diffusion-1c61bba263a8?source=rss-11db483088aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c61bba263a8</guid>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <dc:creator><![CDATA[Oxotall]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 09:29:11 GMT</pubDate>
            <atom:updated>2026-06-23T09:29:11.827Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://oxotall.medium.com/how-text-to-image-diffusion-models-work-the-full-pipeline-04092e3f2480">previous post</a> we took a text-to-image diffusion model apart and looked at its three working parts: a CLIP <strong>text encoder</strong> that turns the prompt into token embeddings, a <strong>U-Net</strong> that denoises a latent image step by step, and a <strong>VAE</strong> that decodes the final latent into pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJYsZfMbPLqOcCkhPCYuAA.png" /></figure><p>In this post we will touch on the topic of <strong>model interpretability</strong>: the effort to explain <em>why</em> a trained network produces the output it does, rather than treating it as a black box that we can only poke from the outside. A diffusion model has billions of parameters and no built-in explanation for any image it makes, so when a generation goes wrong — the prompt said “a red cube on a blue sphere” but the colors swapped, or a requested object simply vanished — we usually have no idea which part of the computation is responsible. Interpretability tools give us a window into the internal decisions, turning<em> “it just came out wrong”</em> into “<em>this token never attended to that region”</em>.</p><p>Why this matters in practice: it lets you <strong>debug</strong> prompt failures like attribute binding and missing objects; it surfaces <strong>bias</strong> by showing what the model latches onto; it underpins <strong>control and editing</strong> methods (<a href="https://arxiv.org/abs/2208.01626">prompt-to-prompt</a> and its descendants literally manipulate the maps we are about to draw); and it builds the basic <strong>trust</strong> needed to deploy generative models responsibly. Attention is especially valuable here because, unlike most hidden activations, it is already a normalized, human-readable map of <em>“what looked at what”</em> — one of the few places where a transformer’s reasoning is legible almost for free.</p><p>In this post, we will build three complementary views over the same attention data — <strong>text-to-image</strong>, <strong>image-to-text</strong>, and <strong>image-to-image</strong> — write down exactly how each score is computed, and walk through the web service that makes it interactive.</p><h3><strong>Calculating the aggregated score matrix</strong></h3><p>Everything starts from a single object: the attention probability tensor. Inside each attention layer the U-Net forms queries <em>Q</em>, keys <em>K</em>, and values <em>V</em>, and computes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5zNjd1jztMYrePvPjihMg.png" /></figure><p>where <em>d</em> is the per-head dimension and the softmax is taken over the key axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Fj21Zc5ODhEhFNsRipjNg.png" /></figure><p>There are two forms.</p><p>In <strong>self-attention</strong>, queries and keys are both image latents, so <em>A</em> maps each patch to a distribution over the other patches — a <em>P×P</em> matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MePTqwr6XWRUKhTTcPgDVQ.png" /></figure><p>In <strong>cross-attention</strong>, queries come from image latents and keys from the CLIP text tokens, so <em>A</em> maps each of the<em> P</em> image patches to a distribution over the <em>T</em> tokens — a<em> P×T</em> matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZD8lwbArK2km6xV2apg1g.png" /></figure><p>A modern diffusers install computes this softmax inside a fused kernel that never exposes <em>A</em>. So the first job is to recompute attention the classic way and keep the matrix. We also store the <strong>pre-softmax logits </strong><em>S = QKᵀ/√d</em> — the raw scores before the softmax.</p><p>A single layer at a single step is noisy, so we average. Attention runs at several feature-map resolutions inside the U-Net, and only maps of the same size can be averaged together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AiMp3DjHg-ZAjvQXRGo1Q.png" /></figure><p>So we aggregate per resolution<em> r</em> — over heads <em>H</em>, steps 𝒯, and the layers <em>Lᵣ</em> at that resolution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNyyaurSMegtmqJy25HLhw.png" /></figure><p><em>Ā</em>ᵣ (and<em> S̄ᵣ</em>) has shape <em>r²×T</em> for cross-attention and<em> r²×r²</em> for self-attention. We never merge different resolutions into one map — you pick a single <em>r</em> and work with it.</p><h3><strong>Method 1. Image-to-text</strong></h3><p>Fix an image patch <em>p₀</em> and read<em> Āᵣ</em> along its row — the distribution over text tokens for that single location:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cmpfs7fvu2rF2nohikl-Jw.png" /></figure><p>restricted to the real word tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sV4CtM9MNf_FmR7KKQtqaA.png" /></figure><p>Normalizing across the word tokens and coloring each token chip by its weight answers a direct question: while the model was rendering this patch, which words was it consulting?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ESbmA-M9NecoaT8cuYN1Q.png" /><figcaption><em>Left: </em>Click on the cat’s chest<em>. “cat”</em> is the hottest chip. <em>Center: </em>Click firmly on the sofa cushion. <em>“sofa”</em> becomes the hottest chip. <em>Right: </em>Click near the cat’s lower body / sofa edge<em>. “cat”</em> (and <em>“sitting”</em>) stays warm even over the cushion.</figcaption></figure><p>Let’s look at an example with a prompt <em>“A cat sitting on a red sofa”. </em>The circle on the image highlights the selected area, and the tokens are colored according to the strength of the influence on this area of ​​the image. We can see clean attribute influence.</p><h3><strong>Method 2 . Text-to-image</strong></h3><p>Now read the data the other way. Fix a token t₀ and scan down its column over all image patches — the transpose of method 1. Here we read the <strong>pre-softmax</strong> map<em> S̄ᵣ</em> rather than<em> Āᵣ</em>, for the reason above: the softmax normalizes per query patch, so the raw logits compare more fairly across patches for a fixed token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M0_gRZ2IujWrdbaMDCcPQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDaimmFqgV6xNVAHR-F1Zg.png" /></figure><p>This slice holds one value per latent cell, so it reshapes to the r×r grid, min-max normalized to [0, 1], upsampled bilinearly to image size, and blended over the picture as a heatmap (the drawing step is detailed after the methods). The result is the familiar “the word cat lights up the cat” heatmap, and it reads cleanly because a token’s attention is genuinely localized in space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ic6zW5zTrNWG0Mks-QnVlQ.png" /><figcaption><em>Left</em>: token <em>“cat”</em>. Heat concentrates on the cat’s body and its outline. <em>Center</em>: token <em>“red”</em>. The sofa lights up. <em>Right:</em> token<em> “sitting”.</em> Heat spreads over the cat and the sofa surface beneath it.</figcaption></figure><h3><strong>Method 3. Image-to-image</strong></h3><p>Self-attention works purely within the image. For a query patch<em> p₀</em> we read its row of the self-attention map and view it back over image space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P6nw4Xtdtvobm9H3n4fmtg.png" /></figure><p>the same kind of slice — one value per latent cell — rendered as a spatial heatmap exactly like method 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mk1afqiISTi5ZTHn1ypx5g.png" /></figure><p>This shows the model’s internal sense of structure — clicking an eye often lights up the other eye, clicking wall lights up the rest of the wall — because self-attention groups patches that belong to the same object or texture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIBD3d6nStdzAcFgwr44-A.png" /><figcaption><em>Left: </em>Background point selected. The whole wall/background glows; the cat and sofa stay cold. <em>Center: </em>One eye selected. Both eyes light up. <em>Right: </em>One ear selected<em>.</em> Both ears light up.</figcaption></figure><h3><strong>Drawing the heatmap</strong></h3><p>All three methods produce their numbers — scores, the per-resolution averages <em>Āᵣ </em>and<em> S̄ᵣ</em>, the min-max normalization — at the <strong>native latent resolution</strong>, with no resizing whatsoever. The conversion to pixels described here is purely for visualization.</p><p>It applies to the two spatial views, text-to-image and image-to-image. Each ended with a slice g holding one value per latent cell; arranging those values on the r×r grid (row by row) gives the map <em>M</em>. To show <em>M</em> over the full image we scale it up to the image’s <em>N×N</em> by <strong>bilinear interpolation</strong>. Each output pixel<em> (i, j)</em> maps back to (<em>i/s, j/s)</em> in the small grid, with scale <em>s = N/r</em>, and takes a weighted blend of the four cells around it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yHDGgxwbl3j8p2GsJ4Brqw.png" /></figure><p>where, with fractional parts <em>fᵢ = i/s − ⌊i/s⌋</em> and <em>fⱼ = j/s − ⌊j/s⌋</em>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUclfZ_IHNUe7P-ne8_gqg.png" /></figure><p>The four weights sum to 1, so each pixel is a convex blend of its four nearest cells; the result is tinted with a colormap. Upsampling adds no detail — it only smooths between cell centers, which is why low-resolution layers give soft, blobby maps and high-resolution layers give crisp ones that trace edges.</p><h3><strong>The service</strong></h3><p><a href="https://github.com/Oxotall/Text2ImageAttnVisualization">This repository</a> ships a small Flask app. In <strong>Image → Text</strong> you click a spot on the picture and the token chips recolor by attention weight. In <strong>Text → Image</strong> you click a token chip and the heatmap appears. In <strong>Image → Image</strong> you click a spot and the related regions light up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTJkUmFZQhaPpTnOMXS1Lw.png" /></figure><h3><strong>Conclusion</strong></h3><p>What makes these maps worth the small effort is what they let you do once they are visible: when a prompt misfires — a color bound to the wrong object, a requested thing missing altogether — the heatmaps point straight at the token or region responsible, turning a vague “it came out wrong” into a concrete diagnosis; they expose what the model leans on, which is where bias tends to hide; and they offer the kind of plain, inspectable evidence that earns trust before a generative model is put in front of users.</p><h3><strong>Links &amp; References</strong></h3><ul><li><a href="https://arxiv.org/abs/2210.04885">DAAM: Interpreting Stable Diffusion Using Cross Attention</a> — the method behind upsampling and aggregating attention into word heatmaps.</li><li><a href="https://arxiv.org/abs/2112.10752">High-Resolution Image Synthesis with Latent Diffusion Models</a> — the Latent Diffusion / Stable Diffusion architecture this repo visualizes.</li><li><a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a> — the original scaled-dot-product attention these maps come from.</li><li><a href="https://arxiv.org/abs/2103.00020">Learning Transferable Visual Models From Natural Language Supervision (CLIP)</a> — the text encoder whose tokens the cross-attention attends to.</li><li><a href="https://arxiv.org/abs/2208.01626">Prompt-to-Prompt Image Editing with Cross-Attention Control</a> — the paper that popularized editing images by manipulating cross-attention maps.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c61bba263a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Text-to-Image Diffusion Models Work: The Full Pipeline]]></title>
            <link>https://oxotall.medium.com/how-text-to-image-diffusion-models-work-the-full-pipeline-04092e3f2480?source=rss-11db483088aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/04092e3f2480</guid>
            <category><![CDATA[text-to-image-generation]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <dc:creator><![CDATA[Oxotall]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 13:01:04 GMT</pubDate>
            <atom:updated>2026-06-26T15:11:58.519Z</atom:updated>
            <content:encoded><![CDATA[<p>Type<em> “a ferret reading a book by lantern light”</em> into Stable Diffusion and, a few seconds later, it returns an image that did not previously exist. That output is produced by a pipeline of several networks, each with a narrow role. These components pass data from one stage to the next.</p><p>At the center of the pipeline is one model, the denoiser. It is trained on a single task: take an image with random Gaussian noise added to it — and estimate that noise so it can be subtracted, yielding a slightly cleaner image. A network that reliably removes a small amount of noise can be applied repeatedly: starting from pure noise and denoising in small steps, dozens or hundreds of times, converts random noise into a coherent image. The prompt is supplied to the denoiser as an additional input at every step, steering which image the noise resolves toward, so the output matches the text. The other components exist to support this loop — encoding the prompt, compressing the image, and scheduling how much noise is removed at each step.</p><h3><strong>How an image is generated</strong></h3><p>Before introducing formulas, here is the inference process in plain terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuJ0E_iKhCiC3tFORiQWZQ.png" /></figure><p>Everything starts with the prompt. The <strong>text encoder</strong> reads it and converts it into a sequence of embedding vectors that encode its meaning; for the rest of the pipeline,<em> “a ferret reading a book by lantern light”</em> is represented solely by these embeddings.</p><p>In parallel, the system samples a small array of pure random (Gaussian) noise. This array is the starting point for the image and initially carries no information about the prompt.</p><p>The <strong>U-Net</strong> then runs. It takes the noisy array together with the encoded prompt and removes a small amount of the noise, conditioned on the text. A single pass removes only a little, so the process repeats: the slightly cleaner array is fed back into the U-Net dozens of times. Across passes, coarse structure appears first and fine detail later. The <strong>scheduler</strong> controls the loop, setting exactly how much noise is removed at each step so the sequence converges to a clean result.</p><p>One key efficiency point: all of this runs on a small, compressed representation of the image, which keeps each pass cheap. When the loop finishes, the <strong>VAE</strong> decoder maps the final latent back to a full-resolution image.</p><p>That is the complete process. The rest of the post adds precision: what each component does internally, the relevant formulas, and how each part is trained.</p><h3><strong>Component 1: the text encoder (CLIP)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R24hxq3UF729ab4eioHRZw.png" /></figure><p>A Transformer (CLIP’s text tower in Stable Diffusion 1.x) turns the tokenized prompt into a matrix of embeddings of shape L × d: the prompt is padded or truncated to L tokens, and each token is mapped to a d-dimensional embedding vector. CLIP (Contrastive Language–Image Pre-training) was pre-trained on hundreds of millions of image–caption pairs to place matching images and texts close together in a shared vector space, so its embeddings already encode visual meaning. It is frozen during diffusion training.</p><h4><strong>What CLIP is trained on</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eux1_07P5rmmais5qvGOyg.png" /></figure><p>CLIP is trained first, on a contrastive task that is entirely separate from diffusion. The inputs are (image, caption) pairs. Two networks are trained jointly: an image encoder maps each image to a single pooled embedding, and the text encoder maps each caption to a single pooled embedding (the hidden state at the end-of-sequence token), both in a shared vector space. The contrastive loss pulls each image embedding toward the embedding of its own caption and pushes it away from all other captions in the batch. After enough pairs, the embedding of <em>“a photo of a ferret”</em> and the embedding of an actual photo of a ferret lie close together in that space, so the text embeddings encode visual content.</p><h3><strong>Component 2: the VAE</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzFDiWCdV0eo0uf-F5Mzgg.png" /></figure><p>Why work in a latent space at all? For a picture of size H × W with three color channels, the pixel representation has <em>3·H·W</em> values, and running a large network over all of them dozens of times is expensive. The VAE encoder compresses the image by a factor of f per side into a latent of shape <em>M × N × c</em>, where <em>N = H/f, M = W/f</em>, and <em>c</em> is a small number of channels — far fewer values overall. All of the expensive diffusion computation happens in this latent space, and only at the end does the VAE decoder map the result back to pixels.</p><h4><strong>How the VAE is trained</strong></h4><p>In the conceptual training sequence, the VAE is trained before the UNet, because the UNet depends on a fixed latent space. The VAE is trained on images alone — captions play no role here. The full autoencoder runs end to end, but note the “variational” detail: the encoder does not output a latent directly. It outputs the <em>parameters</em> of a Gaussian over the latent — a mean and a log-variance per latent dimension — and a latent z is then sampled from that distribution. The decoder reconstructs the image from <em>z</em>, and the output is compared against the input.</p><p>This stage defines the latent space everything else operates in, which is why it must finish before U-Net training begins: if the latent space kept changing, the U-Net’s target would be non-stationary.</p><h3><strong>Component 3: the U-Net</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AiMp3DjHg-ZAjvQXRGo1Q.png" /></figure><p>The U-Net is the only network trained for diffusion itself. It has the characteristic U shape: a downsampling path that reduces spatial resolution while extracting features, a bottleneck, and an upsampling path that restores resolution, with skip connections passing features from each down level to its matching up level.</p><p>The timestep t enters as a sinusoidal embedding added inside every block, so the network knows the current noise level. The text enters through cross-attention layers, which warrant a closer look.</p><h4><strong>What the U-Net receives from the text encoder</strong></h4><p>This full L × d sequence of per-token hidden states — the output of CLIP’s final layer, one vector per token — is exactly what the U-Net’s cross-attention layers consume, as the keys and values. The pipeline does not collapse the prompt to a single vector; every token’s embedding is passed through, which is what lets different image regions attend to different words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZD8lwbArK2km6xV2apg1g.png" /></figure><p>The <strong>query (Q)</strong> comes from the image. Inside the U-Net, the image is a feature tensor of shape (h, w, c): a grid of h × w spatial positions, each holding a vector of c channel values. For a position (i, j), that c-dimensional vector summarizes what is currently represented at that location. A learned matrix Wq projects it into a query. The full grid therefore produces h·w queries — one per position.</p><p>The <strong>keys (K)</strong> come from the text. A second learned matrix Wk projects each of the L token embeddings into a key vector, encoding what that token represents. Keys are compared against queries.</p><p>The <strong>values (V)</strong> also come from the text. A third learned matrix Wv maps every token to a value vector — the content the token contributes: the textures, shapes, and colors associated with it. Keys determine how strongly each token is attended to; values determine the content that token contributes.</p><p>Note the asymmetry between the two: CLIP’s contrastive objective is defined on the <em>single pooled</em> embedding per caption, but <strong>diffusion</strong> discards that pooled vector and instead uses the <em>full per-token sequence</em> from CLIP’s final layer.</p><h4><strong>How it’s trained</strong></h4><p>With CLIP and the VAE frozen, training optimizes a single objective: given a noisy latent, the timestep, and the text, predict the noise that was added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gt-1CaFoMruGErKcDoCh-w.png" /></figure><p>Step by step: the image passes through the frozen VAE encoder to produce a clean latent <em>z₀</em>. The caption passes through the frozen text encoder to produce embeddings <em>c</em>.</p><p>The scheduler samples a random timestep <em>t</em> between 1 and <em>T</em> (the total number of noise levels), samples Gaussian noise <em>ε</em>, and mixes it into the latent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZzt7II3pFtdWr47Omj0Pg.png" /></figure><p>Here <em>ᾱₜ</em> is a value between 0 and 1 from a fixed table: at small <em>t</em> the latent is barely noisy, at large <em>t</em> it is nearly pure noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vK6VfDPmLTNtvhj5CTV-dA.png" /></figure><p>The U-Net receives noised latent <em>zₜ, </em>timestamp<em> t,</em> and text embedding <em>c</em>, and predicts the noise. The loss is mean squared error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQh_O9iT_ObngJzxb-5APA.png" /></figure><p>That is the entire training objective — a single regression task: predict the noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hz9_zi_-BlBevrWO6V4aPA.png" /></figure><p>One detail in the data: roughly 10% of the time the caption is replaced with an empty prompt, so the same U-Net also learns to denoise unconditionally — the prerequisite for classifier-free guidance at inference.</p><h3><strong>The training sequence</strong></h3><p>Stepping back, the system is built in a fixed order, one component at a time. <strong>CLIP is trained first</strong>, on its own contrastive task over image–caption pairs, then frozen. <strong>The VAE is trained second</strong>, on images alone, to compress and reconstruct them; freezing it fixes the latent space everything else depends on. <strong>The U-Net is trained third</strong> — the main training run — to predict the noise added to a frozen VAE’s latents, conditioned on frozen CLIP’s text embeddings. <strong>Optional fine-tuning comes last</strong> (full fine-tuning, LoRA, DreamBooth, ControlNet), centered on the U-Net but often also touching the text encoder, with the VAE left frozen. The scheduler is not a neural network and is not trained; it follows a fixed noise schedule and update rule.</p><h3><strong>The inference-time pipeline</strong></h3><p>Generation runs the process in reverse: starting from pure random noise, the U-Net progressively denoises it, conditioned on the text.</p><p>The prompt is encoded once into embeddings<em> c</em>. The starting latent is sampled as pure Gaussian noise. The loop then runs, typically 30–50 times: the U-Net predicts the noise in the current latent, and the scheduler uses that prediction to compute a slightly cleaner latent. After the final step, the VAE decoder maps the clean latent to the final image. At inference time, the VAE is used only as a decoder, and the text encoder runs once per prompt.</p><p>One important addition: <strong>classifier-free guidance (CFG)</strong>. At each step the U-Net runs twice — once with the prompt and once with an empty prompt — and the two predictions are combined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mrjkIvlBhTCLDwvOPyCHsA.png" /></figure><p>The guidance scale <em>s</em> amplifies the direction toward the prompt, which strengthens how closely the image follows the text. This is what the caption dropout during training enables: because the same U-Net learned both conditional and unconditional denoising, it can produce both predictions here.</p><h3><strong>Conclusion</strong></h3><p>A text-to-image diffusion model combines several components, each with a clear role. The text encoder converts the prompt into vectors, the VAE bridges pixel space and a compact latent space, the scheduler meters noise in and out, and the U-Net — the only component trained for diffusion — is optimized for a single task: predicting noise. Applied iteratively, starting from random noise and conditioned on text through cross-attention and classifier-free guidance, the pipeline can generate an image for an arbitrary text prompt.</p><h3><strong>Links &amp; References</strong></h3><p><a href="https://arxiv.org/abs/2006.11239">Denoising Diffusion Probabilistic Models (Ho et al., 2020)</a> — the DDPM paper that established the noise-prediction training objective.</p><p><a href="https://arxiv.org/abs/2112.10752">High-Resolution Image Synthesis with Latent Diffusion Models (Rombach et al., 2022)</a> — the Stable Diffusion paper; introduces doing diffusion in VAE latent space.</p><p><a href="https://arxiv.org/abs/2103.00020">Learning Transferable Visual Models From Natural Language Supervision (Radford et al., 2021)</a> — the CLIP paper behind the text encoder.</p><p><a href="https://arxiv.org/abs/2207.12598">Classifier-Free Diffusion Guidance (Ho &amp; Salimans, 2022)</a> — the method that makes prompts effectively steer the image.</p><p><a href="https://huggingface.co/docs/diffusers/index">Hugging Face Diffusers documentation</a> — implementation code for every component discussed here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04092e3f2480" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Agent Coordination Patterns]]></title>
            <link>https://oxotall.medium.com/multi-agent-coordination-patterns-875469cfc6d2?source=rss-11db483088aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/875469cfc6d2</guid>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Oxotall]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 10:12:27 GMT</pubDate>
            <atom:updated>2026-06-08T10:12:27.569Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>single agent </strong>— one model loop with access to tools, memory, and multi-step reasoning — can already handle a wide range of work: research, analysis, code changes, long-running tasks. For many problems, that is the right answer; adding more agents only increases cost and fragility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOfdspWMDMyfXzciTK1PFQ.png" /></figure><p>A <strong>multi-agent system</strong> becomes the better choice when at least one of the following holds:</p><ul><li><strong>The context required exceeds one window.</strong> The task involves more documents, code, or history than a single agent can hold and reason over reliably.</li><li><strong>Specialization improves output quality.</strong> Different subtasks benefit from agents tuned to a specific role — each with its own focused system prompt, its own tool set, and its own evaluation criteria.</li><li><strong>The work can proceed along independent tracks.</strong> Several subtasks have no ordering dependency, and concurrent execution provides a meaningful latency improvement.</li><li><strong>Collaboration between perspectives is the point.</strong> Negotiation, debate, or simulation requires multiple agents that represent distinct stances and exchange information directly.</li></ul><h3><strong>Problems to solve</strong></h3><p>Most of the difficulty in building AI agent systems is structural. The design patterns exist because new problems show up the moment a task outgrows a single agent.</p><p><strong>The decomposition.</strong> Complex tasks have to be broken into pieces that fit an agent’s context and capabilities. The wrong cut produces pieces that are too large to handle reliably or too small to be useful.</p><p><strong>The coordination.</strong> Once there are multiple agents, something must decide who does what, in what order, and how they hand work off. This may be a central orchestrator, a routing layer, a shared store, or a convention the agents follow themselves — but it cannot be left undefined.</p><p><strong>The context.</strong> A single agent’s context window can hold only a certain amount of tokens. Long tasks, large documents, and exploratory subtasks force the system to distribute information across agents, each carrying only what it needs.</p><p><strong>The information flow.</strong> When multiple agents work on related subtasks, findings discovered by one agent often matter to another. Getting the right information to the right agent at the right time — without losing detail to repeated summarization — is non-trivial.</p><p><strong>The aggregation.</strong> When multiple agents produce outputs about the same subject, the system needs an explicit policy for reconciling them. Conflicts without a resolution rule produce arbitrary results.</p><p><strong>The termination.</strong> Iterative and autonomous setups need to know when to stop. Without explicit termination conditions, evaluator loops chase diminishing improvements and shared-state systems consume tokens indefinitely.</p><p><strong>The reliability.</strong> Centralized coordinators are single points of failure. Some applications can tolerate this; others cannot, and the choice of pattern reflects that.</p><p>The patterns below cover most of what appears in production. They are not exclusive, and most real systems combine two or more. The general rule that holds across all of them: <strong>start with the simplest pattern that could plausibly work, observe where it fails, and let the failure mode determine the upgrade.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GIVzRYm_MXk5Hw5Moa7LRw.png" /></figure><h3><strong>Orchestrator-subagent</strong></h3><p>An orchestrator agent receives the request, plans the work, dispatches subtasks to specialist subagents, and combines their outputs into a final result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*7mDBDsWxTZC171g-3IynDA.png" /></figure><p>Subagents may be dispatched <strong>sequentially</strong> or in <strong>parallel</strong> — the orchestrator controls that decision based on whether the subtasks have ordering dependencies.</p><p>The orchestrator can also <strong>replan</strong> as work progresses: after inspecting subagent outputs, it can dispatch follow-up subagents to fill gaps, revise the original plan based on what was discovered, or terminate early if the existing results are sufficient.</p><p>The orchestrator agent performs editing and command execution directly, and dispatches subagents in the background. Each subagent operates with its own context window and returns a summary, which keeps the orchestrator’s context focused on its own task.</p><p><strong>Use when </strong>the task can be cleanly divided into pieces, each of which can be completed without needing to coordinate continuously with the others. This covers the next common shapes</p><ul><li><strong>Sequential dispatch</strong> when subtasks depend on each other’s outputs — <em>for example, planning dinners for the week: a first subagent picks the meals based on what’s already in the fridge and the family’s plans; a second subagent turns that menu into a grocery list of just the missing ingredients; a third subagent groups the grocery list by store.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*Y4NmYITIymj5XH8E8VBFxg.png" /></figure><ul><li><strong>Parallel dispatch — sectioning</strong> when independent subtasks each cover a different aspect of the work. <em>For example, reviewing a used car someone is thinking of buying: one subagent checks the mechanical condition, another checks the body and paintwork, another checks the asking price against similar cars for sale nearby, another reads the maintenance history. The four reports come back at roughly the same time and the orchestrator pulls them into a single buy-or-walk-away recommendation</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0mRemZhAHZtZOYBF5TAL5A.png" /></figure><ul><li><strong>Parallel dispatch — voting</strong> when multiple subagents perform the same task independently and the orchestrator aggregates their outputs to produce a more reliable result. Useful when the task is high-stakes, has known variance across runs, or benefits from ensemble agreement — <em>for example, classifying ambiguous content with several independent classifiers and taking the majority label</em>. The orchestrator’s aggregation rule (majority vote, averaged scores, preference for the most specialized agent) defines what voting actually means in the system.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vxmovksCDTwdN0recrRA9A.png" /></figure><p><strong>Avoid when</strong> the subagents need to share large volumes of intermediate findings. Information that one subagent discovers and another would benefit from must route through the orchestrator and is typically summarized in the process, losing detail. Throughput is also limited by sequential execution unless parallelism is explicit.</p><h3><strong>Hierarchical</strong></h3><p>Orchestrator-subagent extended to multiple tiers. A top-level lead delegates to mid-level managers, each of which coordinates its own group of workers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*lY9qS_iNqHKrWPfMnsp6yQ.png" /></figure><p>This pattern is appropriate when one orchestrator cannot maintain enough of the problem in context to dispatch and synthesize effectively. Distributing the coordination responsibility across two tiers allows each layer to reason at a different level of abstraction.</p><p><strong>Use when</strong> the problem is large and decomposes cleanly along domain boundaries, for example, an enterprise refactoring task with a global lead, per-service leads, and per-file workers.</p><p><strong>Avoid when</strong> the problem’s dependency structure does not match the hierarchy. Each tier introduces information loss — worker outputs are compressed for managers, manager summaries are compressed for the lead. Latency accumulates the same way. If a significant portion of tokens is spent routing information across tiers, the hierarchy is mismatched to the problem.</p><p><strong>Note:</strong> Add a tier only when the orchestrator’s context is demonstrably the bottleneck.</p><h3><strong>Generator-verifier</strong></h3><p>The pattern pairs two agents in opposite roles in a <strong>loop</strong>. The <strong>generator</strong>’s job is to write or build something. The <strong>verifier</strong>’s job is to test that output against a checklist of explicit conditions and either approve it or return back a specific objection. Each rejection becomes the generator’s next instruction; each new attempt becomes the verifier’s next subject. The cycle ends in one of two ways — the verifier accepts the result, or the system reaches the iteration budget and falls back to default output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*cI2mRTonCcAkkLhz0gRqqQ.png" /></figure><p><strong>Use when</strong> output quality is more important than throughput and correctness can be specified — <em>for example, a medication-schedule writer, paired with a reviewer that checks every pair of medications on the schedule against a list of known unsafe combinations, confirms doses sit within safe ranges for the patient’s age and weight, and flags any timing conflict before the schedule is printed.</em></p><p><strong>Avoid when</strong> first-attempt quality is sufficient, when the application requires real-time responses, when the task is simple classification, or when deterministic tools can perform the verification more reliably. Also avoid when correctness criteria cannot be specified in writing — a verifier without explicit standards approves arbitrary outputs.</p><p><strong>Note:</strong> Set an <strong>iteration limit</strong> with an explicit fallback — escalate to a human, return the best attempt with a confidence note, or revert to a simpler model. Loops without exits consume budget when the generator cannot address the verifier’s feedback, and the loop will continue identifying minor issues long after quality has plateaued unless termination is enforced.</p><h3><strong>Agent teams</strong></h3><p>The setup is built around a backlog of work. A <strong>coordinator</strong> seeds a <strong>queue</strong> with all the tasks that need to be done, then starts a fixed group of <strong>worker agents</strong>. Each worker reads the queue, takes the next task it can handle, runs through whatever sequence of operations the task requires, posts the result somewhere the coordinator can collect it, and goes back to the queue for the next one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5KZC6rtBUI8hsWtqvXcTRw.png" /></figure><p>Two features distinguish this pattern from orchestrator-subagent:</p><ul><li><strong>Long-lived workers</strong><em>.</em> Subagents in orchestrator-subagent terminate after one piece of work. Teammates remain active across many assignments — usually for the full duration of the job,<strong> accumulating context</strong> about their domain, which improves performance on subsequent tasks.</li><li><strong>Pull-based task assignment</strong><em>.</em> In orchestrator-subagent, the lead pushes tasks to specific subagents. In agent teams, workers <strong>pull</strong> tasks from a shared queue themselves: each teammate claims the next available task when it is ready. This removes the coordinator from the dispatch path and lets workers operate at their own pace, with naturally uneven completion times absorbed by the queue rather than blocking the lead.</li></ul><p><strong>Use when</strong> the subtasks are independent and benefit from sustained, multi-step work — <em>for example, a game studio localizing a large role-playing game into a dozen languages. The coordinator partitions the work by language — and seeds each language’s queue with batches of in-game text: menu labels, item names, character dialogue, lore entries. A worker (one worker per language) pulls one batch, reads each line in context, consults the running glossary it has built up across earlier batches.</em></p><p><strong>Avoid when</strong> the subtasks are not actually independent. Shared resources — a codebase, database, or filesystem — produce edit collisions.</p><p><strong>Note: Termination</strong> must be designed explicitly, because variable per-task durations make “done” non-obvious. The mechanism is a choice — a fixed work set where the system terminates once every task has a recorded outcome, a coordinator that polls or receives completion signals from each teammate, a global time or budget cap, or a designated agent that decides when enough work has been done. Whatever mechanism is chosen, per-task time limits and a policy for failed or stalled tasks (retry, escalate, mark incomplete) are usually required so that one stuck teammate cannot hold the whole system open.</p><h3><strong>Message bus</strong></h3><p>A shared event channel. Agents <strong>publish</strong> messages tagged with topics, other agents <strong>subscribe</strong> to topics they handle.<strong> There is no central coordinator</strong>; the workflow emerges from the events that occur.</p><p>The primary benefit is <strong>extensibility</strong>. Adding a new agent requires only a subscription, not changes to the existing topology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bRd-oLX5F9F_eNqg6UmEMQ.png" /></figure><p><strong>Use when</strong> the workflow is event-driven and the set of agents is expected to grow — <em>for example, citywide adaptive traffic-light control</em><strong><em>.</em></strong><em> Each intersection runs a controller that publishes its state — active phase, queue lengths, vehicle counts — and subscribes to the same events from its neighbors, alongside network-wide agents for flow, transit priority, weather, road incidents, and emergency vehicles.</em></p><p><strong>Avoid when</strong> the sequence of steps is fixed and known in advance; an orchestrator is easier to read and debug in that case. The main weakness of the message bus is <strong>traceability</strong>. A single triggering event can produce a cascade across multiple agents. When something goes wrong, working backward from the outcome to the original event takes structured tracing — every event needs a correlation identifier so the chain can be reassembled offline. Routing accuracy is also critical; if the router drops or misclassifies an event, the <strong>system fails silently</strong> rather than throwing an error.</p><h3><strong>Shared state</strong></h3><p>Coordination is replaced by a persistent store — a database, filesystem, or structured document — that all agents read from and write to. Some starting process places the initial material in the common workspace, the agents start operating on it, and the run ends when the defined stopping condition is met.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*hVLvQ_l7tYriyaJhFqNuqQ.png" /></figure><p><strong>Use when</strong> the agents need to build on each other’s findings continuously, in something close to real time — <em>for example, an investigative journalism case file. A financial-records agent, a person-profile agent, a document-collection agent, and a timeline agent work on one dossier in parallel. The profile agent reads the financial tables to add bank accounts to each biography; the timeline agent reads the document tags to place new events; the financial-records agent reads the biographies to decide which entities to dig into next. Each depends on the full output of the others, not summaries. </em>A secondary benefit is the removal of the coordinator as a single point of failure. If one agent stops, the others continue.</p><p><strong>Avoid when</strong> there is no clear <strong>termination condition</strong>. Agents can fall into a self-sustaining cycle of reactions, where the cycle continues with each new entry less informative than the last. Also, without explicit coordination, agents may do the same work.</p><h3><strong>All-to-all (mesh)</strong></h3><p>Every agent can communicate directly with every other agent. There is no central coordinator and no shared store as the medium. Messages move peer-to-peer, and each agent decides who to consult, broadcast to, or ignore.</p><p>Compared to shared state — which is asynchronous and store-mediated — all-to-all is synchronous and direct. Agents address each other by identity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*SWkDog8dKWw0UiBL5tYxWA.png" /></figure><p><strong>Use when</strong> a small set of agents needs to negotiate, debate, or otherwise exchange information in real time — <em>for example, red-team/blue-team exercises to simulate real-world attacks to test an organization’s defensive readiness.</em> Effective only for small groups.</p><p><strong>Avoid when</strong> the group is large. The number of possible connections grows as <em>O(N²)</em>. Five agents produce ten potential channels; ten agents produce forty-five. Token usage and context size grow correspondingly, and no individual agent can effectively track the full exchange. Convergence is also unreliable: without explicit termination rules, debates either continue indefinitely or collapse to the most assertive agent’s position.</p><p><strong>Note:</strong> Cap the number of agents, set a hard round limit, and designate one agent as the decision-maker responsible for terminating the exchange.</p><h3><strong>Decisions required before deployment</strong></h3><p>Independent of the chosen pattern, a number of decisions must be made explicitly before deployment.</p><p><strong>Failure handling.</strong> Retry logic, fallback behavior, escalations, and timeouts. Particularly important for orchestrator patterns, where a single failure stalls the system.</p><p><strong>Termination conditions.</strong> Iteration limits, time budgets, convergence rules, designated decision-makers. Required for any iterative loop, shared-state or message queue system, or all-to-all exchange. Termination must be a designed feature.</p><p><strong>Aggregation strategy.</strong> How conflicting outputs are reconciled.</p><p><strong>Measurement.</strong> A single-agent baseline against which the multi-agent system can be compared. Without measurement, improvement cannot be demonstrated and cost cannot be justified.</p><p><strong>Resource budgets.</strong> Latency and cost limits, which determine the maximum number of agents and iterations.</p><h3><strong>How to choose</strong></h3><p>Before reaching for any of these, run the cheapest tests first. If the full sequence of steps can be written down before the run, you don’t need a coordination pattern at all — that’s a <a href="https://claude.com/blog/common-workflow-patterns-for-ai-agents-and-when-to-use-them"><strong>workflow</strong></a>.</p><p>The right multi-agent pattern usually shows itself in the structure of the problem. Three properties do most of the work.</p><p><strong>How dispatch decisions are made.</strong> Whether a single lead decides what runs next, several leads, or workers select tasks by themselves.</p><p><strong>How information flows between agents. </strong>Whether the volume of data exchanges is small enough to summarize or large enough to require a store. Whether agents exchange results through a central lead, a shared workspace, an event channel, or peer-to-peer messages.</p><p><strong>Worker character and lifetime.</strong> Whether each worker is a one-shot specialist that runs a single task and exits, or a long-lived process that accumulates domain context across many tasks and would be worse if it had to start cold each time.</p><h3><strong>Links</strong></h3><ul><li><a href="https://claude.com/blog/common-workflow-patterns-for-ai-agents-and-when-to-use-them">Common workflow patterns for AI agents — and when to use them</a> — Anthropic. Foundational workflow patterns and when to use them.</li><li><a href="https://claude.com/blog/multi-agent-coordination-patterns">Multi-agent coordination patterns: Five approaches and when to use them</a> — Anthropic. Coordination patterns for multi-agent systems.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=875469cfc6d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is an Agent? Telling It Apart From an LLM, an LLM Workflow, and a Multi-Agent System]]></title>
            <link>https://oxotall.medium.com/what-is-an-agent-telling-it-apart-from-an-llm-an-llm-workflow-and-a-multi-agent-system-aab76f3d573e?source=rss-11db483088aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/aab76f3d573e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Oxotall]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 12:26:46 GMT</pubDate>
            <atom:updated>2026-06-01T12:26:46.036Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Agent</strong> is one of the most overloaded words in software right now. It gets applied to chatbots, to RAG pipelines, to any system that strings together more than one LLM call. That looseness makes it hard to reason about what you’re actually building, what it will cost, and where it will fail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYyM4q53qgMJ-eesViHtrQ.png" /></figure><p>The clearest way to define an agent is by contrast — by placing it on a ladder next to the patterns it’s often confused with. At the bottom sits a <strong>single LLM call</strong>: one prompt in, one block of text out. One rung up is an <strong>LLM workflow</strong>: several LLM calls (and tool calls, and plain code) wired together by the developer into a fixed sequence. Above that sits the <strong>agent</strong>: the model itself decides what to do next, which tools to call, and when the task is done. And one rung higher still is a <strong>multi-agent system</strong>, where the agent’s “tools” are other agents — each with its own loop, toolbox, and context.</p><p>The model doesn’t change as you climb. What changes is <strong>who owns computational flow control</strong>, and how that control is divided. With a single LLM call, there’s no workflow to own. With a workflow, your code owns it. With an agent, you hand the steering wheel to one model. With a multi-agent system, you hand it to a team of models that delegate to each other.</p><p>The rest of this article walks the four rungs in order, then compares them on concrete tasks so the differences become visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-fFBp2jlUI9QPwd2AA4yQ.png" /></figure><h3><strong>The LLM Call</strong></h3><p>At its core, calling an LLM is one round-trip: you send a prompt, the model returns text, the transaction ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVJyNetdFK7VGGCrwiL2Eg.png" /></figure><p>The model has no memory between calls, no access to the outside world, no ability to act — only to produce text. One shot to get it right.</p><p>This is the <strong>stateless-function</strong> pattern. It’s the right tool when the task is <em>self-contained in the prompt</em> — summarization, classification, translation, format conversion, “rewrite this in a friendlier tone.”</p><h4><strong>Where it breaks down</strong></h4><p>The moment your task requires any of the following, a single call stops being enough:</p><ul><li>Looking something up the model can’t know (today’s data, your database, a user’s calendar)</li><li>Multiple reasoning steps where each one depends on the previous result</li><li>Performing an action in the real world</li></ul><p>The natural next step is to orchestrate several calls together.</p><h3><strong>The LLM Workflow</strong></h3><p>An LLM workflow is what you build when one call isn’t enough but the path is still predictable. The developer hard-codes a sequence of steps at build time.</p><ul><li><strong>An LLM call</strong> — used as a smart subroutine for a specific NLP task (extract, classify, summarize, draft).</li><li><strong>A tool call</strong> — invokes an API, DB query, or function.</li><li><strong>Plain code</strong> — if/switch/loops that glue everything together, decide which branch to take, validate, retry.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTH3U7igKaNPdkBe0DwkbQ.png" /></figure><p>The key property: <strong>the computational flow’s topology is fixed by the code.</strong> The developer enumerates every step and every branch in advance. The model may choose <em>among</em> branches the developer wrote, but it cannot invent a new step, a new tool call, or a new path that the developer didn’t already wire up. The sequence, the branches, and the stopping condition all live in your code.</p><p>LLM workflows are powerful and underrated. <strong>They’re predictable, debuggable, cheap, and they cover most real-world tasks.</strong></p><h4><strong>Where workflows break down</strong></h4><p>A workflow assumes you can draw the flowchart in advance. The moment the task starts looking like <em>“figure out what to do based on what you find,”</em> the workflow shape breaks. You’d have to enumerate every branch, every fallback, every retry — and you can’t, because the <strong>branches depend on data the model only sees at runtime.</strong></p><p>That’s the cue to hand the steering wheel to the model.</p><h3><strong>The Agent</strong></h3><p>The agent is usefull when the set of possible next steps is <strong>too large or too dynamic to enumerate</strong>. An agent consists of three things:</p><ol><li><strong>An LLM</strong> that can choose to call instruments.</li><li><strong>A set of tools</strong> (functions, APIs, data sources, actions) the LLM is allowed to use.</li><li><strong>A loop</strong> that runs the LLM, executes the tool calls it requests, feeds results back, and repeats until the model decides the task is done.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIhHdhFZG6cgQ_bVk_Lh8A.png" /></figure><p>The <strong>LLM</strong> is no longer a subroutine called at a fixed step; it’s the <strong>planner</strong> that runs on every iteration of the loop. <strong>Tools</strong> are no longer called by your code; they’re called by the model, in whatever order it chooses. Your <strong>code</strong> shrinks to a thin loop: invoke the model, execute whatever tool calls it requested, feed the results back, repeat. <em>You don’t decide when the loop ends. The model does.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAFMpbGBSToTNiI58b410Q.png" /></figure><p>You no longer write the computational flow; you design the <strong>environment</strong> the agent operates in. An environment is everything outside the model that the agent can read from or act on: the tools it can call, the answers it gets back when it asks the user a clarifying question, the documents and files it can read.</p><h4><strong>Where it breaks down</strong></h4><p>Single agents have a predictable set of failure modes. Context bloats as every tool result piles into the window and never shrinks. Tool selection degrades as the toolbox grows past roughly a dozen entries. On long horizons the model loses the thread — forgets the goal, repeats itself, stops early. Mixed-concern prompts (“be a researcher <em>and</em> a writer <em>and</em> an analyst”) water down behaviour across the board. And steps that are logically independent still run sequentially, because a single agent can only process one step at a time. When several of these hit at once, the fix isn’t a better prompt or a smarter model — it’s splitting the work across multiple agents.</p><h3><strong>The Multi-Agent System</strong></h3><p>A single agent has a flat toolbox: a list of functions the one model can call. A multi-agent system replaces some of those tools with <strong>other agents</strong> — each one its own LLM with its own loop, its own toolbox, its own context window, and its own focused job. The agents collaborate: one can call another, hand work off, ask for a second opinion, or run side-by-side and merge their results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKfuC3gig81VEb_yehRBqw.png" /></figure><p>The crucial property is <strong>context isolation</strong>. It is what makes multi-agent systems worth the extra complexity. The other benefits follow from it:</p><ul><li><strong>Specialization.</strong> Each agent gets a focused system prompt and a small toolbox. Narrower scope means better tool use.</li><li><strong>Parallelism.</strong> Independent agents can run concurrently. Three pieces of work in parallel finish in the time of one.</li><li><strong>Replaceability.</strong> You can swap an agent’s implementation (different model, different prompt, even a deterministic function) without touching the rest of the system.</li></ul><h4><strong>Where it breaks down</strong></h4><p>A multi-agent system is the most expensive rung. Every sub-agent call is itself an entire agent loop, with its own token bill. Latency is bounded by the slowest agent (better) or by serial round-trips between agents (worse). And you’ve added a <strong>coordination problem</strong>: agents can misunderstand each other’s output, disagree, or get stuck in loops, and the trace you have to debug is now a tree of trees.</p><h3><strong>LLM Workflow vs. Agent — The Comparison</strong></h3><p>This is where the choice actually matters in real products. Same task, two approaches.</p><p><strong>Task:</strong> Reply to this customer email.</p><p><em>“Hi, I ordered #A2851 last week — it arrived yesterday but the wrong color. Can I exchange it for the blue one? Also, do you offer gift wrapping for my next order?”</em></p><h4><strong>The workflow approach</strong></h4><p>The developer hard-codes a fixed pipeline at build time. The sequence is decided once, in code, and runs the same way every time:</p><ol><li><strong>LLM call </strong><em>[decided by code]</em> — prompt the model to classify the intent into one of exchange / refund / question / other.</li><li><strong>Switch </strong><em>[decided by code]</em> — a switch on the intent picks the “exchange” branch.</li><li><strong>LLM call </strong><em>[decided by code]</em> — prompt the model to extract <em>order_id</em> and intent from the email.</li><li><strong>Tool call </strong><em>[decided by code]</em> — your code directly calls <em>db.lookup_order(“A2851”)</em>. The model never sees this; it’s just a function call in your pipeline.</li><li><strong>LLM call </strong><em>[decided by code]</em> — prompt the model to fill an <em>exchange_reply</em> template using the order data.</li></ol><p>Note what’s happening: the LLM is invoked <strong>as a subroutine</strong> at three specific steps. It does the NLP work (extract, classify, generate text), and in <em>step 1</em> its classification result steers the switch into one of four predefined branches — a small router. But that’s the limit of its agency: it picks among branches the developer enumerated. The shape of the pipeline was written once, in code, and runs the same way every request.</p><p>This works perfectly on the case the pipeline was designed for: a <strong>single-intent</strong> exchange email. It falls apart here because the customer asked <strong>two</strong> unrelated questions, and the pipeline only has one intent slot. The gift-wrap question is silently dropped — the workflow has no place to put it, and no way to notice it’s missing.</p><h4><strong>The agent approach</strong></h4><p>The developer doesn’t write the sequence at all. Instead, they expose three tools — <em>lookup_order, check_inventory, search_faq</em> — and hand the model the email. The model then plans and executes the steps at runtime:</p><ol><li><strong>LLM call </strong><em>[launched in the agent loop]</em> — reads the email, sees the tool list, plans: <em>“I need to look up the order, check whether blue is in stock, and check the FAQ for gift wrapping.”</em></li><li><strong>Tool call </strong><em>[chosen by model]</em> — <em>lookup_order(“A2851”)</em>.</li><li><strong>LLM call </strong><em>[launched in the agent loop]</em> — reads the order data, decides the next step itself: <em>“blue same SKU? need inventory check.”</em></li><li><strong>Tool call </strong><em>[chosen by model]</em> — <em>check_inventory(sku, “blue”)</em>.</li><li><strong>Tool call </strong><em>[chosen by model]</em> — <em>search_faq(“gift wrapping”)</em>.</li><li><strong>LLM call </strong><em>[launched in the agent loop]</em> — decides it has enough information, drafts a reply addressing both questions, and signals the loop is done.</li></ol><p>The developer wrote <strong>zero conditional logic</strong>. The model picked which tool, in what order, how many times — including discovering at runtime that this email needed an FAQ lookup the LLM workflow would never have triggered.</p><h3><strong>When to Use Which</strong></h3><p>A useful heuristic: <em>start with the simplest thing that works, and only add complexity when it earns its keep.</em> The full ladder:</p><ul><li><strong>LLM call</strong> — task fits in one prompt and the model has everything it needs. Translations, summaries, extraction, rewrites, classification.</li><li><strong>LLM workflow</strong> — task needs multiple steps, but every step and every branch is knowable in advance. RAG, prompt chains, routers (where the model picks among a fixed set of paths). This is where most real products live.</li><li><strong>Agent</strong> — the set of possible next steps is too large or too dynamic to enumerate, and you need the model to compose its own plan from a toolbox at runtime.</li><li><strong>Multi-agent</strong> — a single agent’s context is bloating with noisy tool output, the task naturally splits into parallel specialties, or the toolbox has grown so large the model picks badly. Carve it up into several focused agents.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uf5wexO4jJVaXR9Hpgk3kg.png" /></figure><h3><strong>Conclusion</strong></h3><p>The progression from LLM call to workflow to agent to multi-agent system is about <strong>who owns computational flow control</strong>, and how finely it’s divided.</p><p>Each step up the ladder gives you more capability and costs you more predictability.</p><p>Start simple. Climb only when your flowchart starts sprouting question marks. And when you do, build the observability before you build the cleverness.</p><h3><strong>Links</strong></h3><ul><li><a href="https://www.anthropic.com/research/building-effective-agents">Building Effective Agents</a> — Anthropic’s reference taxonomy of workflows vs. agents. The single best starting point.</li><li><a href="https://claude.com/blog/building-agents-with-skills-equipping-agents-for-specialized-work">Building agents with Skills</a> — Anthropic’s introduction to agent skills</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aab76f3d573e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP: An Introduction Overview With Examples]]></title>
            <link>https://oxotall.medium.com/mcp-an-introduction-overview-with-examples-71ed25c00554?source=rss-11db483088aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/71ed25c00554</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <dc:creator><![CDATA[Oxotall]]></dc:creator>
            <pubDate>Mon, 25 May 2026 08:46:38 GMT</pubDate>
            <atom:updated>2026-05-29T21:50:35.300Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The integration surface, before MCP</strong></h3><p>Every LLM-backed application eventually grows the same appendage: a layer of bespoke adapters connecting the model to external systems. The model needs to read files, query databases, hit internal APIs, call third-party services. Each integration is hand-written. Each is coupled to a specific host (Claude, ChatGPT, Cursor, your in-house agent). Each gets reimplemented when you switch models, or when a new tool shows up.</p><p>The cost is the classic <strong>M × N</strong> problem: <em>M</em> model hosts, <em>N</em> tools, and every host-tool pair is a separate piece of glue. Worse, the glue varies in quality — tool descriptions drift, schemas disagree, retries are inconsistent, observability is a coin flip.</p><p>The <strong>Model Context Protocol</strong> (MCP) is an attempt to collapse that matrix into <strong>M + N</strong> by defining a single wire protocol between a model host and a tool provider. Anthropic published the spec in November 2024. Eighteen months later, MCP is the default in essentially every major host, and the interesting questions have moved from “is this useful?” to “how do we run this at scale?”</p><h3><strong>What the protocol actually is</strong></h3><p>MCP is a <strong>JSON-RPC 2.0</strong> protocol with a small, deliberately constrained surface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ju7viLMTrWnU5VEmBW2VzQ.png" /></figure><h3><strong>Roles</strong></h3><p>A <strong>host</strong> is the process the user interacts with — an <em>IDE</em>, a <em>chat app</em>, an <em>agent runtime</em>. The host instantiates one or more <strong>clients</strong>, each of which maintains a stateful session with a <strong>server</strong>. Servers expose capabilities; clients consume them. Hosts mediate everything: they decide which servers to start, which capabilities to expose to the model, and which calls require user approval.</p><h3><strong>Transports</strong></h3><p>MCP defines two:</p><ul><li><strong>stdio</strong> — messages travel over stdin/stdout. Used for local servers (filesystem, git, local databases).</li><li><strong>Streamable HTTP</strong> — server runs as a remote service; request/response over HTTP POST, server-to-client notifications over a long-lived Server-Sent Events (SSE) stream on the same endpoint.</li></ul><h3><strong>Primitives</strong></h3><h4>Server primitives</h4><p>Primitives define what kinds of context can be provided to AI applications. A server can expose three kinds of capabilities, each shaped around a different purpose:</p><ul><li><strong>Tools</strong> are executable functions. The server declares a name, a human-readable title and description, and a JSON Schema for the arguments; invoking a tool produces a side effect, a computation, or an outbound API request, and returns a structured result. Examples: <em>github.create_pull_request, postgres.query, filesystem.write_file</em>.</li><li><strong>Resources</strong> are addressable, read-only pieces of content. Each is identified by a URI and tagged with a MIME type; fetching a resource returns its current contents without producing side effects. Examples<em>: file:///repo/README.md, postgres://db/users/42, https://internal.docs/runbook/onboarding</em>.</li><li><strong>Prompts</strong> are parameterized message templates. The server defines the parameters and the template body; expansion produces one or more ready-to-use messages — system instructions, multi-turn scaffolding, structured task framings — that can be dropped into a conversation. Example: a <em>review-pr</em> template that takes a PR number and emits a structured code-review prompt.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_JvZ5djARN6we0vbAzCCyA.png" /></figure><p>In the picture above <strong>user</strong> sends a request to the <strong>host</strong>, which owns the <strong>AI app</strong>, the <strong>LLM</strong> or <strong>agent loop</strong>, <strong>conversation state</strong>, and <strong>policy/permissions configuration</strong>. The host spins up one <strong>client</strong> per connected server — each client handles discovery (asking server about capabilities), and session lifecycle — and talks over JSON-RPC to an <strong>MCP server</strong> that exposes three kinds of capabilities: <strong>tools</strong>, <strong>resources</strong>, and <strong>prompts</strong>. MCP client exposes its own capabilities (<strong>sampling, roots, and elicitation</strong>), which we will discuss in the next chapter.</p><h4><strong>Client primitives</strong></h4><p>Primitives flow in both directions. The server-side primitives above describe what a server offers to the model; client primitives describe what a server can ask of the client. They run in the opposite direction — these are server-to-client requests, and a server may only issue them if the client advertised the matching capability during initialize.</p><ul><li><strong>Sampling</strong> (<em>sampling/createMessage</em>) — lets a server ask the host to run an LLM completion on its behalf. The server sends conversation messages, an optional system prompt, and model preferences; the host runs the inference and returns the result. This lets a server use a model without bundling its own model SDK or API keys, and keeps the server model-independent. Because it spends the user’s model on the server’s behalf, sampling is typically gated behind user approval.</li><li><strong>Roots</strong> (<em>roots/list</em>) — lets the client tell a server which filesystem locations it may operate within. Each root is a <em>file://</em> URI marking a workspace boundary, the server uses them to scope its work. When the set changes — the user opens a different folder — the client emits notifications/roots/list_changed and the server re-reads the list.</li><li><strong>Elicitation</strong> (<em>elicitation/create</em>) — lets a server pause mid-operation and ask the user for structured input through the host’s UI. The server sends a short message plus a JSON Schema describing the fields it needs; the host renders a form, collects the response, and returns it. Used for information that’s better gathered interactively than declared up front — confirming a destructive action, supplying a missing parameter, choosing among results.</li></ul><h3><strong>The session lifecycle</strong></h3><p>An MCP session is stateful and follows a fixed handshake:</p><ol><li><strong>Initialize</strong> — client sends protocol version, supported capabilities, and client info. Server responds with its protocol version, supported capabilities, and server info. Version mismatches are negotiated down to the highest mutually-supported version.</li><li><strong>Initialized</strong> notification — client confirms it’s ready.</li><li><strong>Capability discovery — </strong><em>tools/list, resources/list, prompts/list, </em>plus notifications like <em>tools/list_changed</em> when the server’s surface changes mid-session<strong>.</strong></li><li><strong>Capability use</strong> — <em>tools/call, resources/read, prompts/ge</em>t.</li><li><strong>Shutdown</strong> — clean teardown.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_L_WZsVUYAXum-8Z4PVAWw.png" /></figure><h3><strong>Examples</strong></h3><p>For a better understanding, let’s go through examples using different primitives.</p><p><strong>Prompts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_zci7LpyZG-Y-CE7I6SRg.png" /></figure><ul><li>The engineer asks the IDE (host) for help writing release notes. The MCP client is connected to the company’s MCP server but doesn’t yet know what it offers, so it issues <em>prompts/list</em>. The server responds with its catalog of named prompts.</li><li>The IDE hands that catalog to its model, and the model picks <em>release_notes</em> as the match for the user’s request. The MCP client then issues <em>prompts/get</em>, naming <em>release_notes</em> and passing the target PR as its argument.</li><li>The server expands that template — substituting the PR’s contents into the company’s instructions — and returns the result: a complete prompt ready to send to a model.</li><li>The IDE feeds the expanded prompt to the local LLM, which generates the draft, and the host returns it to the user.</li></ul><p><strong>Resources</strong></p><p>The company server, besides its prompts, also exposes a pile of <strong>read-only internal documentation</strong> as resources: API specs for every internal service, architecture docs, the service catalog. Each one has a stable URI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zH2N_BXZuyJzq-5XdcpiYA.png" /></figure><ul><li>An engineer asks a question that touches an internal service. The user is wiring up a call to the billing service and asks the assistant, “what’s the request shape for charging a customer?”</li><li>The IDE asks the server what resources exist<strong>.</strong> The MCP client sends <em>resources/list</em>. It gets back a catalog — every resource’s URI, name, and MIME type.</li><li>The IDE picks the relevant one. It shows the catalog itself to<em> </em>the local LLM — just the URIs, names, and descriptions, not the full contents — and lets the model say which resource it wants to read. The model replies “<em>read docs://services/billing/openapi</em>”. Only then the host sends <em>resources/read</em> for that URI.</li><li>The server returns the contents.</li><li>The IDE folds the spec into the model’s context as background material — labeled with its source — ahead of user’s question, then sends the whole thing to the local LLM.</li><li>The model answers using the actual spec that was just attached and the user gets a grounded answer.</li></ul><p><strong>Tools</strong></p><p>The company server also exposes <strong>tools</strong> — actions that touch real internal systems. For example: <em>run_tests</em>, which executes a test target on the company’s CI runners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwk258UK2mVx84XeRrfyrA.png" /></figure><ul><li>An engineer asks for help IDE with tests. “Run tests on my branch — Run the tests and if they fail, analyze the reason.”</li><li>The IDE creates mid-response the local LLM, which determines it can’t diagnose this from the diff alone; it needs to see an actual run.</li><li>The MCP client asks the server about actual tools: <em>tools/list</em>.</li><li>The server replies with catalog.</li><li>The local model emits a tool call for <em>run_tests</em> with your branch and the payments target.</li><li>The server actually runs the tests. On the company’s CI infrastructure, the payments target executes. The tool returns a structured result — which tests failed, with stack traces.</li><li>The IDE folds the tool result in as the model context. The model reads the stack traces and identifies the cause. It explains the bug.<br>The engineer gets the diagnosis.</li></ul><h3><strong>Conclusion</strong></h3><p>MCP’s idea is simple: agree on one format, and you stop writing a new connector for every model-and-tool pair. Write a tool once, and any app that speaks MCP can use it. The link goes both ways, too — a server can hand context to the model (<em>tools, resources, prompts</em>), and it can ask the app for help back: borrow a model, get the folders it’s allowed to touch, or ask the user a question (<em>sampling, roots, elicitation</em>).</p><p>What’s left to figure out is the everyday running of it: logins and permissions, trusting tools other people wrote, seeing what happened when one request hits many servers, and deciding who’s allowed to run what. MCP gave everyone a shared language. The job now is running it well at scale.</p><h3><strong>Links</strong></h3><ul><li><a href="https://modelcontextprotocol.io/">Model Context Protocol — official site &amp; docs</a> — start here; concepts, tutorials, and the full specification.</li><li><a href="https://www.anthropic.com/news/model-context-protocol">Introducing the Model Context Protocol — Anthropic</a> — the original announcement and the motivation behind the protocol.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71ed25c00554" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A visualization of how Context Parallelism works and how to combine it with Tensor and Sequence…]]></title>
            <link>https://oxotall.medium.com/a-visualization-of-how-contextual-parallelism-works-and-how-to-combine-it-with-tensor-and-sequence-45063e9071f6?source=rss-11db483088aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/45063e9071f6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[distributed-training]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[context-parallelism]]></category>
            <dc:creator><![CDATA[Oxotall]]></dc:creator>
            <pubDate>Sun, 17 May 2026 10:18:01 GMT</pubDate>
            <atom:updated>2026-05-17T10:18:23.253Z</atom:updated>
            <content:encoded><![CDATA[<h3>A visualization of how Context Parallelism works and how to combine it with Tensor and Sequence Parallelism</h3><p>In the <a href="https://oxotall.medium.com/tensor-and-sequence-parallelism-explained-with-pictures-bd2be13eea26">previous post</a> we split a transformer block two ways. Tensor Parallelism (TP) sliced the weight matrices along the hidden dimension so every matmul ran in parallel across devices, with reduction on the <em>Q, K, V</em> and internal MLP activation tensors. Sequence parallelism (SP) sliced the LayerNorm, the residual, and the Dropout along the sequence dimension so it reduces the activations at the boundaries of each block and computation time.</p><p>But TP+SP has a ceiling, and that ceiling is the sequence length. With hundreds of thousands of tokens even with TP+SP a single GPU runs out of memory inside the attention block itself. We also want to parallelize the computation to reduce wall-clock time. <strong>Context parallelism</strong> (CP) is the trick that knocks that wall down.</p><h3><strong>Attention</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Fj21Zc5ODhEhFNsRipjNg.png" /><figcaption>Inside a single attention block</figcaption></figure><p>The input is <em>X</em>. We project it to queries, keys, and values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruFl_RcJasBL8hnyxXzobw.png" /></figure><p>We use these values ​​to calculate the attention head:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEz4Z7VzJ8jip4XCWjBRjw.png" /></figure><p><em>S</em> is the attention-score matrix: for each sample and each head, a <em>s×s</em> block whose <em>(i, j) </em>entry is the score that query position <em>i</em> assigns to key position j. <em>A</em> is the softmax of along the key axis (same shape as <em>S</em>). <em>O</em> is the per-head output.</p><p>When we use the Multi-Head Attention, we count <em>H</em> such heads, concatenate them and project back out with <em>Wo</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6HdFw4Ry8ddaLrGJvOuiHQ.png" /></figure><p>That score matrix <em>S</em> is the problem. Its size is quadratic in the sequence length, and even with FlashAttention it materializes block-by-block on-chip — the FLOPs are unavoidable even when the bytes aren’t.</p><p><strong>Tensor + Sequence Parallelism</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inr2ZuMNkM3FH0Ho8aKGaA.png" /></figure><p>Tensor Parallelism shards the <strong>head</strong> dimension — <em>Wq, Wk, Wv</em> are column-parallel, so each device only owns <em>H/N</em> heads. That reduces the score-matrix budget by a factor of <em>N</em>. But each head that does live on the device is still full-sequence by full-sequence and the FLOPs are still <em>O(s²) </em>per device; the activations you keep for the backward pass (<em>Q</em>,<em> K</em>,<em> V</em>,<em> O</em>, plus the per-row softmax statistics) are all still full-sequence.</p><p>Sequence Parallelism shards sequence by factor of <em>N</em> at the boundaries of the block — LayerNorm, Dropout, residual. The moment the all-gather fires to assemble the full sequence for the matmul, you’re back to full <em>s</em> inside attention. SP is invisible to the attention interior.</p><p>You can read more about these types of parallelism in the <a href="https://medium.com/@oxotall/tensor-and-sequence-parallelism-explained-with-pictures-bd2be13eea26">previous post</a>.</p><p>So both TP and SP are powerless inside the attention kernel itself.</p><p>We want three things:</p><ol><li><strong>Spread token activation storage across devices, proportionally to the sequence length.</strong> Each device should hold a slice of the activations rather than the whole tensor, so per-device memory shrinks as we throw more ranks at the problem.</li><li><strong>Spread the attention compute across devices too.</strong> The <em>O(s²)</em> FLOPs per layer have to divide across the available ranks, so adding more devices actually shortens the wall-clock step. Memory parallelism without compute parallelism just lets you wait longer for the same answer on a bigger context.</li><li><strong>Overlap the cross-device communication with the local compute.</strong> Any scheme that splits attention across devices will have to move some bytes between them — the data isn’t all in one place anymore. That traffic has to hide behind the compute, or we trade a memory bottleneck for a communication bottleneck and gain nothing.</li></ol><p>The solution is to shard the sequence dimension <em>within</em> attention. That’s Context Parallelism.</p><h3><strong>Sharding inside attention — the obvious problem</strong></h3><p>Split the sequence across <em>C</em> devices: device <em>i</em> holds the chunk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r60z1UhISa_GISW-4LAU_Q.png" /></figure><p>Local attention is cheap — each device computes multiplication of <em>Qi</em> and <em>Ki</em> gets a (<em>s / C) × (s / C)</em> block of scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAjpcu5SY_M0M-PoKOiJnw.png" /><figcaption>Grouped K, V, Q by index on devices</figcaption></figure><p>But causal language modeling needs every query position <em>t</em> to attend to every key position <em>≤t</em>, and bidirectional attention needs every position to attend to every other. So query <em>Qi[t]</em> on device <em>i</em> must somehow see <strong>every</strong> key, not just the <em>Ki</em> sitting next to it. The keys it needs are scattered across the other <em>C - 1</em> devices.</p><p>The naive fix — <strong>all-gather</strong> <em>K</em> and <em>V</em> within the CP group at the start of attention — would defeat the entire point.</p><ul><li>Per-device memory would go from the sharded <em>O(s / C)</em> for <em>K </em>and <em>V</em> back up to the full <em>O(s)</em> per device. That’s a regression on exactly the tensors we sharded CP to fix, and the backward pass keeps the full <em>K, V</em> resident on every device for the rest of the step.</li><li>Worse, an all-gather is a synchronous burst right at the start of attention — there is no useful compute to hide it behind, so the comm shows up directly on the critical path.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4mOtUYKk3M_14L6lLEidg.png" /></figure><p>Ring attention, as we’ll see, sidesteps both: <em>K</em> and <em>V</em> stay <em>O(s / C)</em> resident at any one moment, and each block transfer overlaps with the previous block’s compute.</p><h3><strong>Ring attention</strong></h3><p>Arrange the <em>C</em> devices in a ring. Each device starts with its own <em>Qi</em>, <em>Ki</em>, <em>Vi</em>. Over <em>C</em> rounds, every device passes its current <em>K, V</em> block to its right neighbor and receives a <em>K, V </em>block from its left. After<em> C - 1</em> hops, the <em>K, V </em>blocks have made a full lap and every device has seen every block exactly once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRBrRrsmoyb6-JW2-q_Pjw.gif" /></figure><p>At each round <em>r</em>, device <em>i </em>is holding <em>Qi</em> (always) and some <em>Kj, Vj</em> (rotating). It runs exactly the same attention computation it would run on a single device, but only against this one block of keys:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VT7uXKUOKRUSk0E_mjATw.png" /></figure><p>The hard question is: how do we combine the contributions <em>Oij</em> from different <em>j</em> into the correct full-sequence attention output? You can’t just add them. The softmax denominator depends on <strong>all</strong> the scores across all the keys, and we’re seeing the scores one block at a time.</p><p>This is exactly the problem FlashAttention solves with the <strong>online-softmax accumulator</strong>. Ring attention reuses the same machinery, just at a coarser granularity — instead of tiling along the key dimension within a single device’s kernel, we tile along the key dimension <em>across</em> devices.</p><h3><strong>Online softmax</strong></h3><p>Softmax of a vector <em>s</em> is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6q7aD0YO6qG9m4aExQL8bA.png" /></figure><p>Numerically you always subtract the max first to keep things from overflowing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHyFDLMKmyy6GkCqqKjU3w.png" /></figure><p>Now suppose <em>s</em> arrives in two chunks. We want to compute <em>softmax(s) </em>· <em>v</em> where <em>v</em> is the corresponding vector of values, <strong>without</strong> ever having both chunks resident at the same time.</p><p>Maintain three running quantities, defined over the chunks seen so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMxEuZQjuUFlfRx28_mgfw.png" /></figure><p>When a new chunk <em>(s’, v’)</em> arrives, we want to fold it in.</p><p>The old running sums were normalized against the old max <em>m</em>. To rebase them against new max <em>m’</em>, multiply by <em>exp(m - m’)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqXcMRufhfx59E45H3nY0Q.png" /></figure><p>After all chunks, the answer is <em>o / l</em>. The whole thing is bit-exact equivalent to one-shot softmax on the full vector.</p><p>Every device holds its <em>Qi</em> block of size <em>s / C</em>, so it maintains <em>s / C</em> independent triples <em>(m, l, o)</em> — one for each local query token. Round by round, as new <em>Kj, Vj</em> blocks arrive, each query row’s accumulator gets updated. After all <em>C</em> rounds, every accumulator divides by its <em>l</em>, and the device has the correct full-sequence attention output for its <em>s / C</em> queries.</p><p>The per-device FLOPs over the full rounds add up to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGwtQuRkbnul7-mARoitoA.png" /></figure><p>Exactly the full attention FLOPs divided by <em>C</em>, which is the best we can hope for from <em>C</em>-way sharding.</p><h3><strong>Context Parallelism pipeline</strong></h3><p>Here’s a single attention head under Context Parallelism, drawn out across devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bftiyM5B5RDL-O1XPo8x9g.png" /></figure><p>Read it top to bottom, one column per device. The yellow bar at the top of each column is that device’s slice of the input — the orange-colored stripe shows <em>which</em> positions of the sequence this device owns; different devices, different positions. Below it sit the head’s projection weights <em>Wq, Wk, Wv</em>. In pure CP, weights are replicated, not sharded — every device holds the full set for this head. The local matmuls project the input slice into the device’s own <em>Q, K, V</em> for this head, sharded along the sequence axis at <em>s / C</em> rows each (the pink stripe inside each <em>Q, K, V</em> block shows the same sequence slice the input came from).</p><p>In Ring Attention local queries end up attending to every key in the sequence via the <em>K, V</em> rotation. The output bars at the bottom are each device’s <em>s / C</em> rows of contextualized attention output for this head — same sequence positions it started with, but now mixed over the entire sequence.</p><h3><strong>The causal-mask problem and how to fix it</strong></h3><p>The previous arithmetic assumed <em>Qi × Kj</em> every block produces useful work. For bidirectional (encoder) attention that’s true. For causal LM attention it isn’t.</p><p>The causal mask says position <em>t </em>can only attend to positions <em>≤t</em>. If we lay the sequence out contiguously and give <em>device 0</em> the first <em>s/C</em> tokens, <em>device 1</em> the next, and so on, then:</p><ul><li><em>Device 0&#39;s</em> queries (positions <em>0, …, s / C - 1</em>) can only attend to keys at positions <em>≤ s / C - 1</em>, which all sit on <em>device 0</em>. Every block it receives from <em>device j &gt; 0</em> is <strong>fully masked</strong> — pure wasted communication and idle compute.</li><li><em>Device</em> <em>C - 1&#39;</em>s queries (the last chunk) can attend to everything. Every block it receives is fully useful.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BB294HHo3d69NH3emSjQnA.png" /></figure><p>The work imbalance is linear in device index. The last device does roughly <em>C</em> times more useful attention than the first. Wall-clock per step is set by the slowest device, so a naive contiguous split gives you a 2<em>×</em> slowdown — the GPUs are sitting on their hands half the time<strong>.</strong></p><p>The standard fix is the <strong>zig-zag split</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clM6V4ygbWExw-03280GmQ.png" /></figure><p>Instead of contiguous chunks, slice the sequence into <em>2C</em> slabs and hand <em>device i —</em> <em>slab i</em> and <em>slab 2C - 1 - i</em> . Now every device gets one “early” slab and one “late” slab. The early slab has very few keys to attend to and the late slab has very many, and the totals come out roughly <strong>equal</strong> across devices.</p><p>This rebalancing is transparent to the attention math — you’re just permuting the sequence at the boundaries of the block.</p><h3><strong>Where the wire cost shows up</strong></h3><p>Each round of ring attention is one<em> Send</em> to the right neighbor and one <em>Recv</em> from the left, moving a <em>K, V</em> block of size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjCEbhCja7E3Un1nZov_NQ.png" /></figure><p>(the leading <em>2</em> is <em>K</em> and <em>V</em>, the trailing <em>2</em> is the bf16 byte count). Over <em>C - 1 </em>rounds the device sends a total of that, which to leading order is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EvMN3gCGPabEoFGDQJhl5Q.png" /></figure><p>— the size of one full <em>K, V</em> tensor for the heads the device owns.</p><p>Every hop is a point-to-point send/recv between neighbors<strong>.</strong> With a well-laid-out ring on a fast intra-node interconnect, the bytes for round <em>r + 1 </em>are moving on a separate stream while the compute for round <em>r</em> is still running.</p><h3><strong>Composing Context Parallelism with Tensor and Sequence Parallelism</strong></h3><p>CP is <strong>orthogonal</strong> to TP. TP shards the head dimension and CP shards the sequence dimension inside attention. The two never touch each other’s axes, so we can stack them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVGYnobVMOGg3c-Pvh7bYA.png" /><figcaption>2D device mesh of shape (T, C); <em>N = T </em>x<em> C</em></figcaption></figure><p>In practice you arrange your GPUs in a 2D mesh of shape <em>(T, C)</em>, where <em>T</em> is the size of the TP group. Each column of the mesh is one TP group; each row is one CP group. Every device participates in both — its TP group handles weight sharding and the per-block matmul collectives (all-gather / reduce-scatter at the SP boundaries), and its CP group handles the ring rotation of blocks inside attention.</p><p>Here’s what one transformer block looks like with all three stacked. Top SP boundary, TP+CP attention in the middle, bottom SP boundary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LHxLrmvH_e1FEchIH36PyA.png" /></figure><p>Walk it top-to-bottom.</p><p><strong>SP at the top.</strong> Each device starts with a small sequence shard — <em>s / (T · C)</em> tokens (orange lines). LayerNorm runs locally on each shard; it’s pointwise. The first <strong>All-Gather</strong> collective then assembles the full shard — <em>s </em>/ <em>C</em> CP chunk (orange strips) within each TP group, ready for the projection matmuls. Notice that the all-gathers come in groups of T arrows feeding one collective — one such collective per CP data chunk.</p><p><strong>TP + CP in the middle.</strong> The <em>Wq, Wk, Wv</em> projection weights now appear <em>layered</em> — that’s the TP sharding, with each device holding only a slice of the heads. The resulting <em>Q, K, V</em> blocks are sharded <strong>both</strong> ways: by head dimension (TP, columns) and by sequence dimension (CP, rows) — visible in the pink rectangles inside each block. <strong>RING ATTENTION</strong> is in the center — for each TP rank,<em> T</em> independent rings rotate <em>K, V</em> blocks within the CP group in parallel. The output matrix is still sharded both ways.</p><p>The output projection <em>Wo</em> is row-parallel TP — taking the partial outputs and producing per-device partial sums.</p><p><strong>SP at the bottom. Reduce-Scatter</strong> combines those partials within the TP group and re-shards along the sequence for Sequence Parallelism. Dropout runs locally on the resulting <em>s / (T · C)</em> shard.</p><h3><strong>Wrapping up</strong></h3><p>Tensor Parallelism shards the weights. Sequence Parallelism shards the activations at the boundaries. Both are powerless inside the attention kernel itself — once the matmul fires, every device that owns a head still sees the full sequence on that head.</p><p>Context Parallelism solves it by sharding the sequence dimension inside attention. Ring attention rotates the <em>K, V</em> blocks around a ring of devices, and each device folds the partial attention contributions into a running online-softmax accumulator.</p><p>That’s how you get million-token training and inference on a real cluster.</p><h3><strong>Links and references</strong></h3><ul><li><a href="https://medium.com/@oxotall/tensor-and-sequence-parallelism-explained-with-pictures-bd2be13eea26"><strong>Tensor and sequence parallelism — explained with pictures</strong></a><strong> </strong>— the previous post</li><li><a href="https://arxiv.org/abs/2310.01889"><strong>Ring Attention with Blockwise Transformers for Near-Infinite Context</strong></a> — Liu et al., 2023. The ring-attention algorithm at the heart of Context Parallelism.</li><li><a href="https://arxiv.org/abs/2311.09431"><strong>Striped Attention: Faster Ring Attention for Causal Transformers</strong></a> — Brandon et al., 2023. The zig-zag / striped permutation that load-balances the causal mask across the CP ring.</li><li><a href="https://arxiv.org/abs/2205.14135"><strong>FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness</strong></a> — Dao et al., 2022. The online-softmax / log-sum-exp block-attention machinery that ring attention reuses across devices.</li><li><a href="https://arxiv.org/abs/1805.02867"><strong>Online normalizer calculation for softmax</strong></a> — Milakov &amp; Gimelshein, 2018. The original streaming-softmax recurrence.</li><li><a href="https://arxiv.org/abs/2205.05198"><strong>Reducing Activation Recomputation in Large Transformer Models</strong></a> — Korthikanti et al., 2022. The TP+SP recipe CP composes on top of.</li><li><a href="https://github.com/NVIDIA/Megatron-LM"><strong>Megatron-LM repository</strong></a> — reference implementation of TP, SP, and CP together.</li><li><a href="https://huggingface.co/spaces/nanotron/ultrascale-playbook"><strong>The Ultra-Scale Playbook (Hugging Face)</strong></a> — end-to-end overview of large-scale training.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45063e9071f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tensor and sequence parallelism — explained with pictures]]></title>
            <link>https://oxotall.medium.com/tensor-and-sequence-parallelism-explained-with-pictures-bd2be13eea26?source=rss-11db483088aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd2be13eea26</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[sequence-parallelism]]></category>
            <category><![CDATA[tensor-parallelism]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <dc:creator><![CDATA[Oxotall]]></dc:creator>
            <pubDate>Fri, 08 May 2026 10:07:49 GMT</pubDate>
            <atom:updated>2026-05-09T15:47:37.751Z</atom:updated>
            <content:encoded><![CDATA[<p>A modern LLM does not fit on a single GPU. A 70B-parameter model in bf16 needs ~140 GB just for the weights, and during training the optimizer state and gradients add another 5–10× on top of that. An 80 GB H100 is not going to cut it, and even a full 8-GPU node only buys you so much breathing room.</p><p><a href="https://oxotall.medium.com/visualization-of-data-parallelism-for-llm-training-from-naive-data-parallelism-to-zero-3-8126e44e4b61">Data parallelism</a> is the first tool everyone reaches for. This type of parallelism replicates the model on every device and shards the <em>batch</em> — fine for throughput, useless for fitting a model that is bigger than one GPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9IMBnsGNae-Gi3p_5nI9w.png" /><figcaption>Naive data parallelism: the model is completely copied across devices</figcaption></figure><p>Modern training stacks fix this with <strong>FSDP</strong> (PyTorch’s Fully Sharded Data Parallel, conceptually the same thing as DeepSpeed ZeRO-3): parameters, gradients, and optimizer state are sharded across the data-parallel group, and each layer’s full weights are all-gathered on demand right before they are used, then released. Per-device weight memory drops by N and a 70B model becomes trainable on a single node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihLGiFN7eaH2Gk3Y9dDeKA.png" /><figcaption>Zero-3: the model is completely distributed across several devices</figcaption></figure><p>So why does anyone still bother with tensor parallelism? Two reasons.</p><p><strong>First, FSDP shards the weights, not the computation in space.</strong> At the moment a matmul runs, every device still executes the full matmul on its own slice of the batch, with the full per-layer activation tensor sitting in HBM. For wide models the activations alone overflow a single GPU, and a single matmul is bottlenecked by one device’s FLOPs and memory bandwidth — extra data-parallel replicas can’t help you finish that one matmul any faster.</p><p><strong>Second, FSDP is awkward at inference.</strong> Gathering every layer’s weights once per generated token is a latency disaster. Production inference engines almost universally reach for tensor parallelism instead — it shards both the weights <em>and</em> the work, so per-token latency goes <em>down</em> with more devices.</p><p>The two techniques in this post all split the model <em>across space</em> rather than time, and they apply equally to training and inference:</p><ul><li><strong>Tensor parallelism (TP)</strong> splits the <em>weight matrices</em> across devices, so every matmul is sharded and runs in parallel.</li><li><strong>Sequence parallelism (SP)</strong> splits the <em>sequence dimension</em> during the operations that don’t need it whole — basically free activation-memory savings on top of TP.</li></ul><p>In a real cluster you stack these on top of FSDP, not instead of it: FSDP shards the data-parallel replica group, TP/SP shard each replica internally. The math behind all of them is just clever block-matrix multiplication. Let’s start there.</p><h3><strong>Transformer block</strong></h3><p>What does each replica actually contain? A transformer is a stack of identical <strong>transformer blocks</strong>, and each block has two sub-blocks — a Multi-Head attention (MHA) sub-block and a feed-forward (MLP) sub-block. Both sub-blocks are bracketed the same way: a LayerNorm at the entrance, a residual connection from the input, and a Dropout on the output. The interior of each sub-block is where the FLOPs live — and the FLOPs are almost entirely matrix multiplications. Let’s start there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W82IfVnlfHTmN8MbNYG3XQ.png" /><figcaption>Transformer block</figcaption></figure><p>Almost every expensive op in a transformer is a matrix multiplication. Tokens get multiplied by <em>Wq, Wk, Wv, Wo</em> for attention and by <em>Win</em> and <em>Wout</em> in the MLP.</p><h4>Attention</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Fj21Zc5ODhEhFNsRipjNg.png" /><figcaption>One-Head attention</figcaption></figure><p><strong>MLP block</strong></p><p>Here’s the MLP inside a transformer block: a layer norm, an “up” projection <em>Win</em> that expands the hidden size from <em>d</em> to <em>f</em>, a nonlinearity (GELU, SwiGLU, whatever you fancy), a “down” projection <em>Wout</em> that brings it back, and a dropout.</p><p>X = LayerNorm(X)<br>X = X * Win<br>X = Nonlinearity(X)<br>X = X * Wout<br>X = Dropout(X)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EIpxpSDircED9taX4FwPA.png" /><figcaption>MLP block</figcaption></figure><p>If you can split a matmul across devices, you can split the model.</p><h3>Matrix Multiplication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hodQ7cFCcw1eTCOduMeXZA.png" /></figure><p>Two matrices in, A and B ( L x K and K x M), one matrix out, C (L × M). Each entry C[i, j] is the dot product of row i of A with column j of B:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZbxHH-rRTrhL_0l1uaCfpw.png" /></figure><p>Two things to notice, because they are the two ways tensor parallelism shards a matrix:</p><ol><li>Different output <strong>columns</strong> of C are completely independent of each other from the point of view of matrix B. Computing column j only touches column j of B — never column j+1. So you can hand each device a different slice of B’s columns and let them work in parallel without saying a word to each other.</li><li>The dot product itself — that big sum over k — is <strong>associative</strong>. You can split the inner index k into chunks, compute each chunk on a different device, and add the partial sums at the end. The result is identical.</li></ol><p>Those two observations give us the two flavors of tensor parallelism.</p><h3><strong>Tensor parallelism, take one: split the output dimension</strong></h3><p>The first option is <strong>column parallelism</strong>. We slice the right-hand matrix B along its M dimension into N pieces of width M/N, send one slice to each device, and replicate A. Every device computes its own narrow slab of the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYj-qg7hDMuR3d712669Aw.png" /><figcaption>Matrix multiplication with column parallelism</figcaption></figure><p>No communication is needed during the matmul itself. Each device just does its own smaller matmul: [L × K] × [K × M/N] = [L × M/N], and it takes 2LKM/N FLOPs. If anyone downstream actually needs the full L × M matrix, you’ll need an <strong>all-gather</strong> to stitch the slabs back together. About data exchange processes you can read in <a href="https://medium.com/@oxotall/collective-operations-used-in-llm-training-985709648302">Collective operations used in LLM training</a>.</p><h3><strong>Tensor parallelism, take two: split the inner dimension</strong></h3><p>The second option is <strong>row parallelism</strong>. Now we split the K dimension itself. Here two matrices in, A and B (L x M and M x K), one matrix out, C (L × K). We give each device a chunk of A’s columns and the matching chunk of B’s rows, then add up the partial results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDoRVrDfK0bqJNxd7vuHfw.png" /></figure><p>The same idea can be done with dividing matrix B by N row chunks. Each device computes a <em>full-shape</em> L × K partial output from its slice of the inner dimension (it takes 2LKM/N FLOPs), and we sum them across devices to get the final answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pf83hi3aZhH1MXc_HInquA.png" /><figcaption>Adding row parallelism</figcaption></figure><p>Row parallelism <em>requires</em> communication at the end: every device has only a partial sum, and the partials have to be combined across the group. There are different collective operations that can do this — we meet two of them later — and the choice of collective is exactly what distinguishes vanilla tensor parallelism from the tensor + sequence parallelism setup the diagrams in this post show.</p><h3><strong>Only Tensor parallelism</strong></h3><p>The recipe for the MLP block is:</p><ul><li><strong><em>Win</em> is column-parallel.</strong> Each device holds [d, f/N] and computes <em>X · Win</em>, getting an output of shape [batch, seq, f/N]. No comms needed yet — X is replicated across devices.</li><li><strong>The nonlinearity is applied locally.</strong> GELU is element-wise; sharding the hidden dimension doesn’t change anything.</li><li><strong><em>Wout</em> is row-parallel.</strong> Each device holds [f/N, d]. It takes its local [batch, seq, f/N] activations and produces a <em>partial</em> [batch, seq, d]. Add an <strong>all-reduce </strong>across devices and you have the full output.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z3bmUzPqCRtxP-ylWMFz3Q.png" /></figure><p>Two matmuls, one all-reduce. No communication at all between them, and the giant f-dimensional intermediate activation is sharded N ways automatically.</p><p>The same trick works for self-attention with <em>Wq, Wk, Wv</em> column-parallel — TP shards the <em>head</em> dimension, <em>Wo</em> row-parallel, one all-reduce per block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BvwkNqZINTCAR-T4UM8DA.png" /></figure><h3><strong>Add Sequence parallelism</strong></h3><p>Look at the MLP block again. Tensor parallelism sharded the hidden dimension across devices, but a few operations were left replicated on every device:</p><ul><li>LayerNorm, before <em>Win</em></li><li>Dropout, after <em>Wout</em></li><li>The residual connection that wraps the block</li></ul><p>These are all elementwise. They have nothing to do with the hidden dimension being whole — they just need each token’s vector to be intact at that position. So the sequence dimension is fair game.</p><p>The <a href="https://arxiv.org/abs/2205.05198">sequence-parallelism observation (Korthikanti et al., 2022)</a> is: <em>split these elementwise operations along the sequence dimension</em>. Device<em> i</em> only sees its sequence-length/N-token chunk during LayerNorm and Dropout. Activation memory for those layers drops by N× with no extra compute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHSopsixCDPXgNLoikPe0g.png" /></figure><p>Reading that diagram top to bottom: each device starts with its sequence shard. Apply LayerNorm locally. <strong>All-gather</strong> to get the full sequence. Run the column-parallel <em>Win</em>, the non-linearity, and the row-parallel <em>Wout</em> exactly as in plain TP. <strong>Reduce-scatter</strong> the output back to a sharded representation. Apply Dropout locally. Done. The whole transformer block stays in this SP → TP → SP pattern, with collectives only at the boundaries.</p><p>And here is the magic: an all-gather plus a reduce-scatter is exactly the same total volume as the all-reduce we already had to do for vanilla TP. Same wire cost, less activation memory.</p><p>And the same trick also works for self-attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inr2ZuMNkM3FH0Ho8aKGaA.png" /></figure><p>In production training stacks, TP+SP is the default: you almost always want it together.</p><h3><strong>Wrapping up</strong></h3><p>One transformer block, sharded across many devices. <em>Tensor parallelism</em> splits the weights along the hidden dimension — column-parallel up-projection, row-parallel down-projection — so per-device weight memory and the wide intermediate activation both shrink dramatically. <em>Sequence parallelism</em> splits the elementwise bookends (LayerNorm, Dropout, residual) along the sequence dimension; the <em>all-reduce</em> that closed pure tensor parallelism becomes an <em>all-gather</em> followed by a <em>reduce-scatter</em>, for the same wire cost and a matching shrink in replicated activation memory.</p><p>Together they form the default building block of modern training and inference stacks.</p><h3><strong>Links and references</strong></h3><ul><li><a href="https://oxotall.medium.com/visualization-of-data-parallelism-for-llm-training-from-naive-data-parallelism-to-zero-3-8126e44e4b61"><strong>Visualization of data parallelism</strong></a> post</li><li><a href="https://medium.com/@oxotall/collective-operations-used-in-llm-training-985709648302"><strong>Collective operations used in LLM training</strong></a> post</li><li><a href="https://arxiv.org/abs/1909.08053"><strong>Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism</strong></a> — Shoeybi et al., 2019. The original tensor-parallel MLP and attention partitioning</li><li><a href="https://arxiv.org/abs/2205.05198"><strong>Reducing Activation Recomputation in Large Transformer Models</strong></a> — Korthikanti et al., 2022. Introduces the SP + TP combination diagrammed above</li><li><a href="http://huggingface.co/spaces/nanotron/ultrascale-playbook"><strong>The Ultra-Scale Playbook (Hugging Face)</strong></a> — a very readable end-to-end overview of large-scale training</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd2be13eea26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collective Operations Used in LLM Training]]></title>
            <link>https://oxotall.medium.com/collective-operations-used-in-llm-training-985709648302?source=rss-11db483088aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/985709648302</guid>
            <category><![CDATA[collective-operations]]></category>
            <category><![CDATA[llm-training]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[distributed-training]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Oxotall]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 08:49:10 GMT</pubDate>
            <atom:updated>2026-04-25T10:21:44.582Z</atom:updated>
            <content:encoded><![CDATA[<p>Training large language models is not just about matrix multiplies and optimizer steps. Once a model is distributed across many GPUs, the real challenge becomes communication: how do devices exchange parameters, gradients, and activations efficiently?</p><p>That is where <strong>collective operations</strong> come in. Collectives are communication primitives that coordinate data movement across a group of devices. They are the hidden machinery behind <strong>data</strong>, <strong>tensor, sequence</strong>, and <strong>pipeline parallelism</strong>, and <strong>mixture-of-experts (MoE)</strong> training.</p><p>If you understand a small set of collectives, many distributed training systems suddenly become much easier to reason about. In practice, most LLM communication patterns boil down to some combination of:</p><p><strong>— broadcast <br>— gather <br>— all-gather <br>— reduce <br>— scatter <br>— reduce-scatter <br>— all-reduce <br>— all-to-all</strong></p><p>Let’s walk through each one and connect it to real LLM training workloads.</p><h3><strong>Why collective operations matter in LLM training</strong></h3><p>When a model fits on one device, life is simple: every tensor lives locally, every computation is local, and communication is almost irrelevant.</p><p>But modern LLMs rarely fit on a single GPU. Even when they do, training efficiently often requires many devices working together. That means tensors must move between ranks:</p><ul><li><strong>weights</strong> may need to be sharded and collected</li><li><strong>gradients</strong> must often be combined across devices</li><li><strong>activations</strong> may need to be collected from shards and may be routed to different experts</li></ul><p>Collective operations give us standard ways to perform these exchanges at high speed.</p><h3><strong>1. Broadcast</strong></h3><p><strong>Broadcast</strong> means one source rank sends the same tensor to every other rank. If some rank has a tensor X, after a <strong>broadcast</strong> all ranks end up with a copy of X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdUzOYtEnw_6QFvfCkZ-Yw.png" /></figure><h4><strong>What it does</strong></h4><p>This is a <strong>one-to-many</strong> communication pattern.</p><p>You start with: <br>— one rank holding the data <br>— the other ranks empty</p><p>You end with: <br>— every rank holding the same data</p><h3><strong>2. Gather</strong></h3><p><strong>Gather</strong> is the opposite direction: every rank sends its local tensor to one destination rank, which collects them together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70-8qJux9d0F2hvoGszoww.png" /></figure><h4><strong>What it does</strong></h4><p>This is a <strong>many-to-one</strong> communication pattern.</p><p>You start with: <br>— each rank holding one local piece</p><p>You end with: <br>— one rank holding all pieces in order <br>— the others keeping nothing new</p><h3><strong>3. All-Gather</strong></h3><p><strong>All-gather</strong> takes one shard from each rank and makes the full combined result available on every rank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4mOtUYKk3M_14L6lLEidg.png" /></figure><h4><strong>What it does</strong></h4><p>This is a <strong>many-to-many </strong>communication pattern.</p><p>You start with: <br>— each rank holding only its local shard</p><p>You end with: <br>— every rank holding the concatenation of all shards</p><h4>Examples in LLM training</h4><p>All-gather is extremely common in model-parallel training:</p><ul><li>reconstructing full activations in <em>tensor parallelism</em></li><li>materializing full tensors from sharded parameters in <em>ZeRO-3</em></li></ul><h3><strong>4. Reduce</strong></h3><p><strong>Reduce</strong> combines tensors across ranks using an operation such as sum, mean, max, or min, and stores the result on a single destination rank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UdRRUXIOeIfrWn5WjXhFGg.png" /></figure><h4><strong>What it does</strong></h4><p>This is a <strong>many-to-one</strong> aggregation pattern.</p><p>You start with: <br>— each rank holding different versions of the full tensor</p><p>You end with: <br>— one rank holding the full reduced tensor</p><h3><strong>5. Scatter</strong></h3><p><strong>Scatter</strong> is the mirror image of gather. One source rank starts with a full tensor, splits it into shards, and sends one shard to each rank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xh2RLUhpBEsaOyNkV96ARQ.png" /></figure><p><strong>What it does</strong></p><p>This is a <strong>one-to-many</strong> partitioning pattern.</p><p>You start with: <br>— one rank holding the full tensor</p><p>You end with: <br>— each rank holding one different piece</p><h3><strong>6. Reduce-Scatter</strong></h3><p><strong>Reduce-scatter</strong> first reduces tensors across ranks and then scatters the reduced result so that each rank keeps only one shard.</p><p>It is like combining <strong>reduce</strong> and <strong>scatter</strong> in one operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*amCsfHtzrbSQ7-3iHYk9CQ.png" /></figure><h4><strong>What it does</strong></h4><p>This is a <strong>many-to-many</strong> aggregation pattern.</p><p>Suppose every rank holds a full tensor-shaped contribution. First, those tensors are reduced elementwise. Then the reduced tensor is partitioned, and each rank receives only its assigned shard.</p><p>You start with: <br> — each rank holding different versions of the full tensor</p><p>You end with: <br>— the tensors being reduced elementwise across ranks <br>— each rank receiving only its assigned shard of the reduced result</p><h4>Examples in LLM training</h4><p>You see <strong>reduce-scatter</strong> in:</p><ul><li>reducing gradients in <em>ZeRO</em>-style sharded training</li><li>reducing activations in <em>tensor parallelism</em></li></ul><h3><strong>7. All-Reduce</strong></h3><p><strong>All-reduce</strong> combines tensors across all ranks and returns the final reduced tensor to every rank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQIuNhJuaUf4nDAK-7F4sA.png" /></figure><h4><strong>What it does</strong></h4><p>This is a <strong>many-to-many </strong>aggregation pattern.</p><p>Each rank starts with a local tensor. The system applies a reduction, usually sum, across all ranks. Then the final result is made available everywhere. For mean, you sum first and divide by the number of ranks.</p><p>You start with: <br> — each rank holding different versions of the full tensor</p><p>You end with: <br> — the tensors being reduced elementwise across ranks <br> — every rank receiving the full reduced result</p><h4>Examples in LLM training</h4><ul><li>reducing and collecting gradients in <em>data parallel</em> training (<em>ZeRO-1</em>)</li><li>synchronizing gradients in <em>context parallelism</em></li></ul><h4><strong>Ring realization of all-reduce</strong></h4><p>One of the most important implementation ideas in distributed training is that <strong>all-reduce can be realized as two phases</strong>:</p><ol><li><strong>reduce-scatter</strong></li><li><strong>all-gather</strong></li></ol><p>On a logical ring, <strong>all-reduce</strong> can be implemented as <strong>ring all-reduce.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpQHsbqu9n2v42hXzjU5aA.gif" /></figure><h4><strong>Phase 1: Reduce-Scatter</strong></h4><p>In the first phase, each tensor is split into chunks.<br>Then those chunks circulate around the ring. At each hop:</p><ul><li>a rank sends one chunk to its neighbor</li><li>receives another chunk from the other side</li><li>partially reduces the received chunk with its local contribution</li></ul><p>After enough steps, each rank ends up owning <strong>one fully reduced chunk</strong> of the final tensor.</p><h4><strong>Phase 2: All-Gather</strong></h4><p>Now each rank holds one reduced shard.<br>In the second phase, those reduced shards continue circulating around the ring. This time there is no further reduction; ranks simply exchange the already reduced pieces until everyone has collected all shards. After enough steps: <br>— every rank has every reduced shard <br>— therefore every rank has the full reduced tensor</p><p>That completes the all-reduce.</p><p>For <strong>ring all-reduce</strong> with <strong>N ranks/devices</strong>, the total number of communication steps is <strong><em>2 × (N — 1)</em></strong><em>.</em></p><p>Because it has two phases:<br>- <strong>reduce-scatter</strong>: <em>N — 1</em> steps<br>- <strong>all-gather</strong>: <em>N — 1</em> steps</p><h3><strong>8. Ring Attention</strong></h3><p><strong>Ring attention</strong> is a distributed way to compute attention when the sequence is split across multiple ranks.</p><p>Instead of keeping all keys and values simultaneously on each device, each rank keeps its local query block fixed and processes remote key/value blocks as they circulate around a logical ring.</p><p>If the sequence is sharded across ranks, ring attention allows each query block to attend to the full sequence without materializing all keys and values on one device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRBrRrsmoyb6-JW2-q_Pjw.gif" /></figure><h4><strong>What it does</strong></h4><p>This is a <strong>many-to-many communication</strong> pattern combined with chunked local computation.</p><p>You start with: <br>— each rank holding one shard of the sequence <br>— each rank having its local queries, keys, and values for that shard</p><p>You end with: <br>— each rank producing attention outputs for its own query tokens <br>— every query shard having attended to all key and value shards across the full sequence <br>— no rank needing to store the full attention matrix at once</p><h4>Examples in LLM training</h4><p><strong>Ring attention</strong> is useful in long-context training and inference, especially when the sequence dimension is partitioned across devices, including attention. This version of <em>sequence parallelism</em> is also called <em>context parallelism</em>.</p><h3>9. All-To-All</h3><p>All-to-all has the next idea: each rank sends a different shard to every other rank and receives one shard from every rank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzfMFBIXbW4d6ff3b8YEqQ.png" /></figure><h4><strong>What it does</strong></h4><p>This is a <strong>many-to-many </strong>communication pattern.</p><p>An <strong>ideal all-to-all</strong> is a clean, dense transpose: every rank sends the same amount of data to every other rank, message sizes are known in advance, traffic is perfectly balanced.</p><p>You start with: <br>— each rank holding data partitioned into shards, one shard intended for each destination rank</p><p>You end with: <br>— each rank receiving its assigned shard from every other rank</p><h4>Examples in LLM training</h4><p><strong>All-to-all</strong> is essential in <em>mixture-of-experts</em><strong> </strong>training.</p><p>But<strong> </strong><em>MoE</em><strong> all-to-all</strong> is usually much messier. In <em>mixture-of-experts</em> training, tokens are first routed by the gate, so each rank may need to send a different number of tokens to different peers, and some peers may receive much more traffic than others. That makes the communication <strong>sparse, imbalanced, and data-dependent</strong> rather than perfectly regular.</p><h3><strong>Conclusion</strong></h3><p>Collective operations are the core communication patterns behind distributed LLM training. Once you understand primitives like <strong>all-reduce</strong>, <strong>all-gather</strong>, <strong>reduce-scatter</strong>, and <strong>all-to-all</strong>, large-scale training becomes much easier to reason about.</p><p>Good distributed training systems try to <strong>overlap communication with computation</strong> as much as possible. Instead of waiting for one collective to fully finish before doing more math, frameworks often launch communication in parallel with independent GPU work. This overlap helps hide communication latency and makes collective operations feel cheaper in practice, which is one of the main reasons system design, scheduling, and kernel efficiency matter just as much as the collectives themselves.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=985709648302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Estimate resources for Training and Serving Large Language Models]]></title>
            <link>https://oxotall.medium.com/how-to-estimate-resources-for-training-and-serving-large-language-models-4135c4fc3d0c?source=rss-11db483088aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4135c4fc3d0c</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ml-system-design]]></category>
            <dc:creator><![CDATA[Oxotall]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 17:35:17 GMT</pubDate>
            <atom:updated>2026-05-01T11:37:30.044Z</atom:updated>
            <content:encoded><![CDATA[<p>Training or serving a large language model requires a large amount of compute, memory, and communication bandwidth. These requirements can look difficult to estimate at first because many details are involved: model architecture, number of parameters, sequence length, batch size, hardware, and numerical precision.</p><p>In this post, I will describe practical formulas for estimating the resources needed for both training and inference. The goal is not to produce a perfect simulator of every kernel and every hardware detail. The goal is to build a reliable first-order estimate. This estimate is useful when choosing a model size, planning a training run, or understanding how many requests an inference server can handle.</p><h3>Training</h3><p>Training cost can be estimated step by step: first we choose the model size and the number of training tokens, then we use these values to estimate total FLOPs, then we calculate memory for weights, gradients, optimizer states, and activations, and finally we estimate training time.</p><p><strong>Compute-optimal Chinchilla rule</strong></p><p>Scaling laws presented in the <a href="https://arxiv.org/abs/2203.15556"><em>Chinchilla</em></a><em> </em>paper from DeepMind describe how model quality changes when we increase training compute, model size, and dataset size.</p><p>A common takeaway is that for a standard transformer, optimal performance is achieved by training on roughly <strong>20 tokens per parameter</strong>.</p><p><strong>Compute FLOPs</strong></p><p>The classic training compute approximation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYIwyCMCO0tlsMd-zXWZxA.png" /></figure><p><strong><em>Why 6ND?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZAUtU9UZvOne5Gu_v6lJyg.png" /></figure><p><em>Forward</em></p><p>A single linear layer can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X778w8-HWnf8mZGQDi51_A.png" /></figure><p>For each token, the forward pass costs roughly <em>2N</em>. Because this matrix multiplication has N multiplications and approximately <em>N</em> additions.</p><p>A transformer is a stack of many such linear layers (attention, output, and feed-forward projections). If we sum over all linear layers, the forward pass costs roughly <em>2N</em> FLOPs per token.</p><p><em>Backward</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nhex1iP1wV-FqPxefPTAMQ.png" /></figure><p>Backward training costs about twice the forward pass: gradient with respect to W and gradient with respect to X. It costs 4N per token. So the forward-plus-backward costs 6N per token.</p><p><strong><em>Why 12SDLd?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Fj21Zc5ODhEhFNsRipjNg.png" /><figcaption>Attention with respect to a single token</figcaption></figure><p>The term <em>12SDLd</em> is the sequence-length-dependent training cost of self-attention per token, <em>4SDLd</em> comes from the forward attention matmuls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLQUlknLq36Q-GkNMF6Z7g.png" /></figure><p>And the factor 3 converts forward cost into forward-plus-backward training cost. This part of the formula becomes important when the context size is large.</p><p>The whole formula counts the dominant forward-and-backward model matmuls. It is a first-order estimate and usually excludes optimizer update FLOPs and parameter-update overhead; this omission is usually acceptable for large-batch training, because the optimizer cost is paid once per step, while the forward and backward cost scales with all tokens in the batch, so the optimizer contribution per token becomes relatively small.</p><p><strong>Training memory</strong></p><p>Training memory is usually the hard limit. Total training memory is roughly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQUSuV_fX_AXUOhowlUjDQ.png" /></figure><p><em>Memory for states</em></p><p>The common formulas are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYhVr1OfozJmwvSHrSWmtQ.png" /></figure><p>For mixed-precision Adam, a common estimate is:</p><pre>bf16/fp16 weight = 2 bytes<br>bf16/fp16 gradient = 2 bytes<br>fp32 master weight = 4 bytes<br>fp32 Adam momentum m = 4 bytes<br>fp32 Adam variance v = 4 bytes<br>---------------------------------<br>Bytes per parameter = 16 bytes<br>Total = 16N</pre><p>So a 7B model needs roughly <em>16 × 7e9 = 112 GB</em>.</p><p><em>Memory for activations</em></p><p>During training, the model must store intermediate values from the forward pass because they are needed later during the backward pass. These intermediate values are called <strong>activations</strong>.</p><p>For example, activations are needed for weight gradient computation in linear layers.</p><p>Activation memory is different from weight memory. Weight memory depends mainly on the number of model parameters. Activation memory depends mainly on the batch size, sequence length, hidden size, number of layers, and implementation details.</p><p>A useful high-level estimate is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPCBvW-_aeQ3nh8uWWLbQg.png" /></figure><p>In <a href="https://arxiv.org/abs/2205.05198"><em>Reducing Activation Recomputation in Large Transformer Models</em></a> paper the authors arrived at the following approximate formula for transformer architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2o6c9MPBd5fgUnJCv9j8A.png" /></figure><p>For a 7B model, distribution of memory components could look like this at training time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*654SqlbyLfCNkixf5alDiA.png" /><figcaption>N = 7e9, L = 32, d = 4096, H = 32, B = 4</figcaption></figure><p>There is a <a href="https://arxiv.org/abs/2205.14135"><strong>FlashAttention</strong></a> algorithm, which reduces the <strong>activation memory</strong>, especially at long sequence length, because the attention quadratic tensors no longer need to be kept in GPU memory across the forward-to-backward boundary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K23JRkqHvoA5xPhvGXpQKw.png" /></figure><p>The tradeoff is extra recomputation in backward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJPMTnMdebBTsDmjWDUuYg.png" /><figcaption>N = 7e9, L = 32, d = 4096, H = 32, B = 4, FlashAttention</figcaption></figure><p>With <strong>activation checkpointing</strong>, you can store fewer activations and recompute them during backward pass. This technique reduces training memory by not storing all forward activations until the backward pass. Instead, the training system saves only a selected subset of tensors, called checkpoints, and recomputes the missing intermediate activations when they are needed during backpropagation. This changes the memory estimate because the activation term becomes smaller, while the total training compute and step time increase due to the extra recomputation. In other words, gradient checkpointing trades memory for compute.</p><h3>Inference</h3><p>Inference has a different cost structure. During inference, we do not store gradients or optimizer states, and the model does not need to keep large activation tensors for backpropagation, so activation memory is much smaller than during training. But inference has its own bottlenecks. The KV-cache can become very large when many users are served at the same time or when the context length is long. The decode stage is often limited by memory bandwidth rather than raw FLOPs.</p><p>Inference has two phases:</p><ol><li><strong>Prefill</strong>: process the prompt.</li><li><strong>Decode</strong>: generate new tokens one at a time</li></ol><p><strong>Compute FLOPs</strong></p><p>Prefill FLOPs can be estimated similarly to a training step forward pass:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXGx5Msl3ueYejMbHLOCmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpphv-Mwp3PMaJMihmWS-w.png" /></figure><p>For generating one new token for sequences in a batch of size <em>B</em> at current context length <em>S:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fo1Q_6JfdNpmHp8Ko7c0LA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8N8oqvGqgAjX5rNWRqiHw.png" /></figure><p><strong>Inference memory</strong></p><p>Total serving memory is roughly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WXloSbr0PF17MJDu7K1Sdg.png" /></figure><p><em>Memory for weights</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQOJhJt6-Dv8fN5yxoKvHg.png" /></figure><p>A 7B model in bf16 needs <em>7e9 × 2 = 14 GB</em>.</p><p><em>Memory for KV-cache</em></p><p>During autoregressive inference, the model generates one new token at a time. At each layer, self-attention needs the keys and values of all previous tokens in the current context. Recomputing these tensors from scratch at every decoding step would be very expensive, so inference systems store them in memory after they are produced. This stored memory is called the <strong>KV-cache</strong>.</p><p>For each new token, the model computes its new key and value vectors, appends them to the cache, and then attends over the full set of cached keys and values. This makes decoding much faster because previous tokens do not need to pass again through the key and value projections. However, the KV-cache can become one of the largest memory costs during serving, especially for long contexts or large batches. Its size grows linearly with the number of layers, the hidden size of the key and value projections, and the total number of cached tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmESZXKq5cY_mAm4U3x_oA.png" /></figure><p>Several techniques can reduce the KV-cache cost. The most direct architectural change is to reduce the number of KV heads: <strong>multi-query attention (MQA)</strong> shares one key-value head across all query heads, and <strong>grouped-query attention (GQA)</strong> shares one KV head across a group of query heads. A second method is to limit how much past context must remain in the cache: <strong>sliding-window attention</strong> keeps only a local window of previous tokens instead of attending to the full history, which changes the effective cache growth from full-context storage to window-limited storage. A third method is <strong>KV-cache quantization</strong>, which stores keys and values in fewer bits and can substantially reduce memory footprint, although aggressive quantization may hurt quality if it is not done carefully. Finally, systems such as <strong>PagedAttention</strong> do not reduce the theoretical KV-cache size in the formula itself, but they reduce fragmentation and wasted allocation, which lowers the practical memory overhead of serving.</p><p><em>Memory for activations</em></p><p><em>Mtmp_act</em><strong> </strong>represents <strong>temporary forward-pass memory</strong>. It includes hidden states, attention intermediates, and kernel-local workspaces. Unlike model weights, it is not fixed. Unlike the KV-cache, it does not remain after the current forward pass finishes. It is usually much smaller than <em>Mweights</em> for large models and smaller than <em>Mkv</em> at long context lengths.</p><p>A practical estimate is the maximum live activation size inside one layer during prefill stage (with FlashAttention):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUgebfiJNSKrou2th0wH7w.png" /></figure><p>For a 7B model, the distribution of memory components could look like this at inference decoding time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BkQq3UoxQwqsqCvDZ6FHwA.png" /><figcaption>N = 7e9, L = 32, H = 32, dhead=128, B = 4, bkv=2, FlashAttention</figcaption></figure><h3>MoE corrections to the estimates</h3><p>For a mixture-of-experts model, the dense formulas should be corrected by separating <strong>total parameters</strong> from <strong>active parameters</strong>: in standard LLM-style MoE models, the attention layers remain dense while the FFN layers are replaced by experts, and only a small number of experts are selected for each token.</p><ul><li><strong>Compute FLOPs</strong> should be estimated from the <strong>active parameters</strong>, not from the full parameter count, because only the routed experts are executed for each token.</li><li><strong>Weight memory</strong> scales with the <strong>total stored parameters</strong>, because all experts must exist in memory even if they are not used by the current token. <strong>Optimizer-state memory</strong> and checkpoint size follow the same rule during training.</li><li><strong>Activation memory</strong> scales with the <strong>active experts</strong> plus router and dispatch buffers, not with all experts at once.</li><li><strong>KV-cache memory</strong> is unchanged compared with a dense model</li></ul><h3><strong>Conclusion</strong></h3><p>Estimating the cost of an LLM becomes much easier once we separate the problem into a few basic components. For training, the main questions are how many parameters to use, how many tokens to train on, how much memory is needed for weights, gradients, optimizer states, and activations, and whether the total step time is limited by computation or communication. For inference, the structure changes: weights become a fixed memory cost, the KV-cache grows with context length, and decoding is often limited by memory bandwidth rather than pure FLOPs. You can find more information about identifying bottlenecks in computing, data handling, and data transfer during different parallelization schemes in the guides <a href="https://jax-ml.github.io/scaling-book/"><em>“How to Scale Your Model”</em></a> and <em>“</em><a href="https://huggingface.co/spaces/nanotron/ultrascale-playbook"><em>The Ultra-Scale Playbook</em></a><em>”</em>. You can also read my post <em>“</em><a href="https://medium.com/@oxotall/visualization-of-data-parallelism-for-llm-training-from-naive-data-parallelism-to-zero-3-8126e44e4b61"><em>Visualization of Data Parallelism for LLM Training: From Naive Data Parallelism to ZeRO-3</em></a><em>”</em> where I tried to explain algorithms with detailed pictures.</p><p>The formulas in this post give a practical way to reason about these costs before running expensive experiments. Of course, real systems add extra details such as kernel efficiency, communication overhead, quantization, and parallelism strategy. But the first-order estimates are still useful.</p><h3>Links</h3><ul><li><a href="https://arxiv.org/abs/2203.15556">Chinchilla</a> paper from DeepMind</li><li><a href="https://arxiv.org/abs/2205.05198">Reducing Activation Recomputation in Large Transformer Models</a> paper</li><li><a href="https://arxiv.org/abs/2205.14135">Flash Attention</a> paper</li><li><a href="https://jax-ml.github.io/scaling-book/">“How to Scale Your Model”</a> guide with JAX code examples</li><li><a href="https://huggingface.co/spaces/nanotron/ultrascale-playbook">The Ultra-Scale Playbook</a> with an introduction in different types of parallelization.</li><li><a href="https://medium.com/@oxotall/visualization-of-data-parallelism-for-llm-training-from-naive-data-parallelism-to-zero-3-8126e44e4b61">Visualization of Data Parallelism for LLM Training: From Naive Data Parallelism to ZeRO-3</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4135c4fc3d0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>