<?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 Saurabh Arora on Medium]]></title>
        <description><![CDATA[Stories by Saurabh Arora on Medium]]></description>
        <link>https://medium.com/@sabu.for.ai?source=rss-8e33a2f4eafe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CfcWk5t8p889JF6D</url>
            <title>Stories by Saurabh Arora on Medium</title>
            <link>https://medium.com/@sabu.for.ai?source=rss-8e33a2f4eafe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:05:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sabu.for.ai/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[Distributed Training: Data, Tensor and Pipeline Parallelism]]></title>
            <link>https://medium.com/@sabu.for.ai/distributed-training-data-tensor-and-pipeline-parallelism-d60519d0fcfa?source=rss-8e33a2f4eafe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d60519d0fcfa</guid>
            <category><![CDATA[hpc]]></category>
            <category><![CDATA[ai-infrastructure]]></category>
            <category><![CDATA[distributed-training]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[parallelism]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 11:50:35 GMT</pubDate>
            <atom:updated>2026-08-28T11:50:35.682Z</atom:updated>
            <content:encoded><![CDATA[<p>Why one GPU is never enough, what all-reduce actually does, and how to plan TP, DDP and PP for the machines you really have.</p><p>The first time you hit `CUDA out of memory` on an 80 GB GPU, the instinct is to shrink the batch size. It works, for a while. Then you try a model with seven billion parameters and the error comes back at batch size one.</p><p>That moment is worth understanding, because it is not a bug and it is not your code. <strong>A model’s weights are the small part of what training needs to keep in memory.</strong> Once you see the real arithmetic, every choice about parallelism starts making sense on its own.</p><p>So let’s walk the whole path: why we split training across GPUs, the three ways to split it, the handful of communication primitives that make it work, how processes find each other in the first place, and the part people skip is how to decide what to use on the hardware sitting in front of you.</p><h3>The arithmetic that forces your hand</h3><p>Train with mixed precision and Adam, and each parameter costs you roughly <strong>16 bytes of persistent state</strong>:</p><ul><li>2 bytes for the bf16 weight the forward pass uses</li><li>2 bytes for the bf16 gradient</li><li>4 bytes for the fp32 “master” copy of the weight</li><li>4 + 4 bytes for Adam’s two running averages, the momentum and the variance</li></ul><p>That last group is worth staring at. <strong>The optimizer state is the largest single tenant on the GPU</strong>, bigger than the weights and gradients combined. Adam keeps two fp32 running averages per parameter, and mixed precision adds an fp32 master copy so that tiny updates are not lost to bf16 rounding. Twelve of the sixteen bytes are optimizer bookkeeping, not model.</p><p>That is also why <strong>the optimizer choice is a memory decision</strong>, not just a convergence one. Plain SGD keeps no running average at all, so the optimizer’s share falls from 12 bytes to the 4-byte master copy. SGD with momentum keeps one buffer instead of two. An 8-bit Adam keeps both buffers at one byte each rather than four. Changing optimizer can free more memory than anything you do to the model itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9P-SeHAUHTlKUlflsuplg.png" /><figcaption>Figure 1–1. What the persistent training state of a model actually weighs.</figcaption></figure><p>So a 7B model is <strong>7 × 16 = 112 GB</strong>, and a 70B model is <strong>70 × 16 = 1,120 GB</strong>. Unrolled for the 7B case, the four tenants look like this:</p><pre> 7B × 2 bytes = 14 GB bf16 weights<br> 7B × 2 bytes = 14 GB bf16 gradients<br> 7B × 4 bytes = 28 GB fp32 master copy<br> 7B × 8 bytes = 56 GB Adam m and v<br> - - - <br> 112 GB</pre><p>There are only two honest responses. Either <strong>give the job more GPUs</strong> or <strong>stop keeping a full copy of everything on every GPU</strong>. Every technique below is one of those two answers, dressed differently.</p><p>Speed is the other motive for going distributed. Even when a model fits, one GPU chewing through a trillion tokens is a calendar problem, not an engineering one. Splitting the data across 64 GPUs turns a month into half a day, if, and only if, the communication between them does not eat the gain.</p><h3>The other half of the bill: activations</h3><p>Everything above is fixed the moment you choose a model and an optimizer. Activations are not. <strong>They scale with your micro-batch size and sequence length,</strong> which are the two knobs people turn most casually.</p><p>An activation is any intermediate tensor the backward pass will need again. Every attention projection, every MLP output, every normalisation input gets kept alive from the forward pass until the gradient flows back through it.</p><p>For a transformer, the planning estimate is refreshingly simple. Stored activations run at roughly:</p><pre>batch size * sequence length * number of head * head dimension * number of layers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DP1P4hS7jD004hvyTbSASw.png" /><figcaption>Figure 1–2. Activation memory for a 7B-class model, with and without recomputation.</figcaption></figure><p><strong>Activation checkpointing is the biggest single lever.</strong> Keep only each layer’s input, throw the rest away, and recompute the interior during the backward pass. Memory drops by more than an order of magnitude — 18.3 GB becomes about 1.1 GB at 4k tokens — for roughly 30% extra compute. In PyTorch it is one wrapper, or fine-tuning with SFTtrainer API</p><pre>from torch.utils.checkpoint import checkpoint<br><br># instead of: h = block(h)<br>h = checkpoint(block, h, use_reentrant=False)   # recompute this block in backward</pre><pre>sft_config = SFTConfig(<br>    ## GROUP 1: Memory usage<br>    # These arguments will squeeze the most out of your GPU&#39;s RAM<br>    # Checkpointing<br>    gradient_checkpointing=True,    # this saves a LOT of memory<br>    # Set this to avoid exceptions in newer versions of PyTorch<br>    gradient_checkpointing_kwargs={&#39;use_reentrant&#39;: False}, </pre><h3>What a distributed job actually is</h3><p>Strip away the frameworks and a distributed training job is a set of ordinary processes, <strong>one process per GPU, each running the same script, each convinced it is training a model</strong>. They stay consistent because at fixed points in every step they stop and exchange tensors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmKaIUPuiP8ouI9CsTfVnQ.png" /><figcaption>Figure 1–3. The five stages of any distributed training job.</figcaption></figure><p>Five things happen, in this order, whether you run 2 GPUs or 2,000:</p><ol><li><strong>Launch</strong> one process per GPU.</li><li><strong>Rendezvous</strong>: agree on who is in the group and what number each process has.</li><li><strong>Build communicators</strong>: let NCCL work out how those GPUs are wired together.</li><li><strong>Split the work</strong>: by dataset, by tensor, or by layer.</li><li><strong>Step loop</strong>: compute, exchange, update over and over.</li></ol><p><strong>Stage 4, split the work is the interesting design decision</strong>, and most of this article lives there.</p><h3>Rendezvous: First things first: who am I?</h3><p>One process per GPU sounds harmless until you notice the catch, every one of those processes is running the <strong>same script</strong>. Same file, same code path, same variable names. Nothing in it says “you are the third one.” And yet, within the first step, they must divide the training data between them without overlapping, and exactly one of them must decide to write the checkpoint.</p><p>So before a single tensor moves, each process has to answer three questions about itself.</p><p><strong>How many of us are there?</strong> That is <strong>WORLD_SIZE </strong>— the total number of processes in the job, which for GPU training means the total number of GPUs.</p><p><strong>Which one am I?</strong> That is <strong>RANK</strong> — a number from `0` to `WORLD_SIZE — 1`, unique across the entire job.</p><p><strong>Which GPU do I drive?</strong> That is <strong>LOCAL_RANK </strong>— the index of the GPU on my own machine.</p><p>Start with one DGX-class server holding 8 GPUs. You launch, and eight processes come up:</p><pre>One DGX server, 8 GPUs -&gt; 8 processes<br>RANK: 0 1 2 3 4 5 6 7<br>LOCAL_RANK: 0 1 2 3 4 5 6 7<br>WORLD_SIZE: 8 8 8 8 8 8 8 8</pre><p>Look at the first two rows. They are identical, and that is a trap in disguise. On a single machine `RANK` and `LOCAL_RANK` are always the same number, so code that confuses the two works perfectly. The bill arrives the day someone adds a second server.</p><pre>Two DGX servers, 8 GPUs each -&gt; 16 processes<br>           | - - - - - server 0 - - - - - | | - - - - - server 1 - - - - - |<br>RANK:        0  1  2  3  4  5  6  7           8  9  10 11 12 13 14 15<br>LOCAL_RANK:  0  1  2  3  4  5  6  7           0  1  2  3  4  5  6  7<br>WORLD_SIZE:  16 16 16 16 16 16 16 16          16 16 16 16 16 16 16 16</pre><p>Think of it as travel documents. <strong>`RANK` is your passport number </strong>— unique in the world, and how anyone refers to you specifically. <strong>`LOCAL_RANK` is your seat number on this particular aircraft</strong> — every plane has a seat 3, so the number means nothing until you know which plane you are standing in.</p><p>One more term worth pinning down now, because it drives half the decisions later, a <strong>node</strong> is one physical server. That boundary is not bookkeeping, it is cabling. The 8 GPUs inside a DGX talk over NVLink/NVSwitch at hundreds of gigabytes per second.</p><h3>Rendezvous: how those numbers get handed out</h3><p>Notice that your script never <strong>computes</strong> `RANK`. It reads it. So who writes it and how do sixteen processes across two machines agree on who is who, without two of them claiming the same number?</p><p>That is the <strong>rendezvous</strong>, and it deserves a few minutes because it is where jobs hang before training ever begins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8YTMdhsRd8onZA2OBld6Q.png" /><figcaption>Figure 1–4. The rendezvous handshake, from launcher to NCCL communicator.</figcaption></figure><p><strong>One agent per node starts the workers.</strong> You run `torchrun` on each server. It spawns `nproc_per_node` processes locally and supervises them, eight on server 0, eight on server 1.</p><pre># one server, 2 GPUs -&gt; WORLD_SIZE = 2<br>torchrun --nproc_per_node=2 training_ddp.py<br><br># one DGX server, all 8 GPUs -&gt; WORLD_SIZE = 8<br>torchrun --nproc_per_node=8 training_ddp.py<br><br># two DGX servers, 8 GPUs each -&gt; WORLD_SIZE = 16.<br># Run this on BOTH servers, with the same endpoint pointing at server 0.<br>torchrun \<br>    --nproc_per_node=8 \<br>    --nnodes=2 \<br>    --rdzv_backend=c10d \<br>    --rdzv_endpoint=&quot;10.0.0.1:29500&quot; \<br>    training_ddp.py</pre><p><strong>The workers meet at a shared meeting point.</strong> With the default `c10d` backend, that meeting point is a small key-value server — a `TCPStore` — hosted by the first node. Every worker connects to the same `rdzv_endpoint` with the same `rdzv_id`, then waits until the required number of nodes has arrived. This is a barrier: nobody proceeds alone. Eight processes waiting quietly while the second server finishes booting is normal, not a hang.</p><p><strong>The store hands out identities.</strong> Once the group is complete, the numbers from those two tables are written into each process’s environment, ready for your script to pick up.</p><pre>WORLD_SIZE = int(os.environ.get(&quot;WORLD_SIZE&quot;, 1))   # 16, in our two-server job<br>RANK       = int(os.environ.get(&quot;RANK&quot;, 0))         # 0-15, unique across the job<br>LOCAL_RANK = int(os.environ.get(&quot;LOCAL_RANK&quot;, 0))   # 0-7, which GPU on my server<br>IS_MAIN_PROCESS = (RANK == 0)                       # the one that logs and saves</pre><p><strong>Then the NCCL communicator is built</strong>. Rank 0 creates a NCCL unique ID, publishes it into the same store, and every rank picks it up and joins. A <strong>communicator</strong> is just the group’s shared handle for talking to each other and only now do the GPUs discover the topology between them and open their channels.</p><h3>The six ways GPUs talk to each other</h3><p>The processes have found each other and opened their channels. Now they need something to say and the vocabulary is small enough to learn in one sitting.</p><p>Every exchange is a <strong>collective,</strong> an operation that every process in the group calls together, and that only completes once all of them have called it. Nobody sends a message to a partner who is not expecting it, everyone agrees to move data at the same moment. That single property explains both why distributed training is reliable and why it hangs rather than crashes when you get it wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5iD5S6RfZHm7ODTotUiLQ.png" /><figcaption>Figure 1–5. The collectives, as before-and-after pictures of GPU memory.</figcaption></figure><p>There are six worth knowing, and every technique later in this article is built from them:</p><ul><li><strong>Broadcast</strong> — one rank’s data goes to everyone. This is how initial weights and that NCCL unique ID get handed out. For example, GPU 0 (the master rank) initializes the model weights randomly or loads a checkpoint from the disk. It then Broadcasts these exact weights and optimizer states to all other GPUs in the cluster, ensuring every single GPU starts training from the exact same mathematical starting line.</li><li><strong>All-Reduce</strong> — combine a tensor across all ranks, and <strong>every</strong> rank ends up with the result. Aggregates data from all GPUs and distributes the final result back to all of them (crucial for updating AI model weights during training). All-Reduce sums up (aggregates) the gradients from every single GPU, divides by the total number of GPUs, and sends that exact averaged gradient back to everyone. Only then do the GPUs run the optimizer step to update their weights simultaneously.</li><li><strong>Reduce-Scatter</strong> — Reduce-Scatter sums up the gradients from all GPUs (the Reduce part), but instead of sending the full result back to everyone, it slices the final averaged gradients into chunks and hands exactly one chunk to each GPU (the Scatter part). Each GPU then only optimizes its assigned portion of the model.</li><li><strong>All-Gather</strong> — the mirror image, each rank contributes its chunk and everyone ends up holding all the chunks. All-Gather forces every GPU to share its specific chunk of the layer’s weights with every other GPU. For a brief moment, every GPU has a complete copy of that layer to do the math, after which the extra weights are immediately deleted from VRAM to save space.</li><li><strong>All-to-All </strong>— every rank sends a <strong>different</strong> slice to every other rank. Mixture-of-Experts routing shuffles tokens to the right expert this way.</li><li><strong>Send / Recv</strong> — plain point-to-point, one rank to one specific rank. The only non-collective in the list, and exactly what a pipeline boundary needs.</li></ul><p>Two rules make all six make sense.</p><p><strong>Rule one: all-reduce is not a primitive.</strong> It is a <strong>reduce-scatter followed by an all-gather, </strong>combine so each rank owns one finished chunk, then circulate the finished chunks. That is literally how it is executed, as the next section shows, and it is worth remembering because some techniques use the two halves separately and on purpose.</p><p><strong>Rule two: a collective is a contract.</strong> Every rank must call the same collective, in the same order, with the same shapes and dtypes. Break the contract and the job does not crash — it <strong>hangs</strong>, quietly, inside the collective, until a watchdog timeout fires. If your job freezes mid-training, look for a collective some rank skipped, inside an `if RANK == 0`, or on a branch only taken when a validation set is non-empty, or in an early `break` out of a loop that other ranks did not take.</p><h3>The factors that decide everything else</h3><p>You now have the pieces, a memory bill, a group of ranks, and six operations. Before we start splitting work between them, it is worth naming what you are actually trading, because every decision in the rest of this article comes back to one of these seven.</p><ul><li><strong>Memory per GPU -</strong> Persistent state plus activations plus the overhead nobody counts. The persistent half is fixed by your model and optimizer; the activation half is set by micro-batch and sequence length, and is the one you can trade against compute.</li><li><strong>Communication volume -</strong> How many bytes cross a wire per step. Some strategies exchange one large tensor once per step, others exchange smaller tensors many times per layer. The second kind is far more sensitive to everything below.</li><li><strong>Where the wire is</strong> - Inside a node, GPUs talk over NVLink or NVSwitch — hundreds of GB/s. Between nodes, InfiniBand or RoCE is fast but slower still, and plain Ethernet is far slower. <strong>The same collective can be cheap or ruinous depending on which link it lands on</strong>.</li><li><strong>Overlap -</strong> Communication that happens while the GPU is still computing is nearly free. The strategies that scale best are the ones that manage to overlap.</li><li><strong>Global batch size -</strong> More replicas means a larger effective batch, which changes your learning rate and warmup, not just your throughput.</li><li><strong>Stragglers -</strong> Collectives are barriers, as we just established. The slowest rank sets the pace for every other rank, every single step.</li><li><strong>Fault tolerance -</strong> More GPUs, more failures. Checkpoint often, and checkpoint in a form you can actually restore into a different topology.</li></ul><p>Keep those seven in mind and the rest of this article is mostly bookkeeping.</p><h3>Data parallelism: split the batch</h3><p>This is where everyone starts, and rightly so. <strong>Every GPU keeps a complete copy of the model and processes a different slice of each batch.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOX1_QuwsIcQUbkme_ct_g.png" /><figcaption>Figure 1–7. Data parallelism: replicate the model, split the batch, all-reduce the gradients.</figcaption></figure><p>For overall end to end code, please refer the below mentioned link</p><p><a href="https://github.com/saurabh922/DistributedTraining.git">https://github.com/saurabh922/DistributedTraining.git</a></p><p>Each rank computes gradients from its own samples, so those gradients all differ. <strong>All-reduce</strong> is exactly the fix, sum them across ranks and every rank ends up with the same combined gradient. Since every rank then applies the same update to weights that were already identical, the copies stay identical forever, which is the whole reason this works.</p><pre>from torch.nn.parallel import DistributedDataParallel as DDP<br><br>raw_model = AutoModelForSequenceClassification.from_pretrained(<br> &quot;google/mobilebert-uncased&quot;, num_labels=2<br>).to(device)<br><br>model = DDP(raw_model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK) \<br> if WORLD_SIZE &gt; 1 else raw_model</pre><p>The gradient all-reduce is not something you call. DDP registers hooks on the parameters and fires the collective <strong>as gradients become ready during the backward pass</strong>, in buckets, those staging buffers from the overhead section. By the time `loss.backward()` returns, most of the communication has already happened underneath the computation. That overlap is the whole trick, and it is why DDP is the fast option rather than merely the simple one.</p><pre>from torch.utils.data.distributed import DistributedSampler<br><br>train_sampler = DistributedSampler(<br> train_dataset, num_replicas=WORLD_SIZE, rank=RANK, shuffle=True<br>) if WORLD_SIZE &gt; 1 else None<br><br># shuffle must be False when a sampler is doing the partitioning<br>train_loader = DataLoader(<br> train_dataset, batch_size=4,<br> shuffle=(train_sampler is None),<br> sampler=train_sampler, collate_fn=collate_fn,<br>)<br><br>for epoch in range(n_epochs):<br> if train_sampler:<br> train_sampler.set_epoch(epoch) # reshuffle differently each epoch<br></pre><p>Without `set_epoch`, every epoch feeds each rank the same samples in the same order.</p><p><strong>Your metrics need the same treatment as your gradients.</strong> Each rank only saw part of the data, so its loss and accuracy are local:</p><pre>train_loss_tensor = torch.tensor(0.0).to(device)<br><br># … accumulate per-batch losses on this rank …<br>if WORLD_SIZE &gt; 1:<br> dist.all_reduce(train_loss_tensor, op=dist.ReduceOp.SUM)<br> avg_loss = (train_loss_tensor / (len(train_loader) * WORLD_SIZE)).item()<br>else:<br> avg_loss = (train_loss_tensor / len(train_loader)).item()</pre><p>The same pattern applies to a `torchmetrics` accuracy: all-reduce the sum, divide by `WORLD_SIZE`. Note that <strong>the reduce must be called on every rank</strong>, not just rank 0 — even though only rank 0 logs the result. Guarding a collective with `if RANK == 0:` is rule two’s contract violation, and the classic way to hang a job.</p><h3>The kilobytes that can ruin the run</h3><p>Remember the scheduler, the loss scaler and the RNG we set aside earlier? This is where they bite, and now the reason is visible.</p><p><strong>A scheduler is state, and it must advance identically on every rank.</strong> If it does not, different replicas train at different learning rates, which never raises an error, and quietly corrupts the run. Metric-driven schedulers are the trap, because their state depends on a number each rank computes locally from its own shard of the data:</p><pre># the metric is all-reduced first, so every rank passes the SAME number in<br>valid_metric = evaluate_fn(model, metric, valid_loader).item()<br><br># then every rank steps - never inside an `if RANK == 0:` block<br>scheduler.step(valid_metric)</pre><p>`ReduceLROnPlateau` carries `best`, `num_bad_epochs` and `cooldown_counter`. Feed one rank a slightly different validation number and it will drop its learning rate an epoch earlier than everyone else — from then on your “identical” replicas are not identical.</p><p><strong>And everything stateful has to be in the checkpoint</strong>, or a resumed run is not a continuation of the old one. Note the first line: save the *plain* model, because the DDP wrapper prefixes every key with `module.` and a plain model will refuse to load it back.</p><pre>unwrapped = model.module if WORLD_SIZE &gt; 1 else model<br><br>torch.save({<br> &quot;epoch&quot;: epoch,<br> &quot;model_state_dict&quot;: unwrapped.state_dict(),<br> &quot;optimizer_state_dict&quot;: optimizer.state_dict(), # the big one: Adam m and v<br> &quot;scheduler_state_dict&quot;: scheduler.state_dict(), # tiny, and easy to forget<br> &quot;scaler_state_dict&quot;: scaler.state_dict(), # if you use fp16 AMP<br> &quot;rng_state&quot;: torch.get_rng_state(), # for reproducible shuffles<br>}, &quot;checkpoint.pt&quot;)<br><br># and always tear the group down at the end<br>if WORLD_SIZE &gt; 1:<br> dist.destroy_process_group()</pre><p>Restore the weights but not the optimizer and you have thrown away Adam’s momentum, the loss visibly jumps. Restore the optimizer but not the scheduler and you resume at the wrong learning rate. Both failures look like “training went weird after the restart” rather than a bug, which is exactly what makes them expensive.</p><h4>What data parallelism does not fix</h4><p>It does nothing for activations. Every rank pushes its own micro-batch through the whole model, so the activation figure from earlier is exactly what each GPU still pays. Adding ranks buys you a bigger global batch, not headroom on any one card.</p><p>It also does nothing for persistent state, since every GPU holds a full copy. That is the next problem.</p><p>Still, DDP is the default for a reason: it scales the widest, it is the least intrusive, and one all-reduce per step is the cheapest communication pattern there is. <strong>Use it whenever the model fits.</strong></p><h3>When the model does not fit: shard the state</h3><p>DDP’s weakness is exactly its design — every GPU holds the full 112 GB (or 1,120 GB) of state. Sharding attacks that directly. Instead of every GPU keeping everything, <strong>each GPU owns a slice of the parameters, gradients and optimizer state</strong>, and borrows the rest only when needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gkQM_g0Z_BIdMG4ix9q_Wg.png" /><figcaption>Figure 1–8. Per-GPU memory under DDP versus the ZeRO / FSDP sharding stages</figcaption></figure><p>This comes in stages, and the naming is worth knowing because you will see both vocabularies:</p><ul><li><strong>ZeRO-1</strong> shards the optimizer state. Biggest win per unit of pain, because optimizer state is the largest slice.</li><li><strong>ZeRO-2</strong> also shards gradients.</li><li><strong>ZeRO-3</strong>, which PyTorch implements as <strong>FSDP</strong>, also shards the parameters themselves.</li></ul><p>Here is where rule one pays off. Under FSDP a layer’s weights are <strong>all-gathered</strong> just before they are used and thrown away immediately after; gradients are <strong>reduce-scattered</strong> so each rank keeps only its own shard. Those are the two halves of an all-reduce, used separately and deliberately, that is the trick that makes the memory drop. The cost is traffic, one all-gather per layer in the forward pass, another in the backward pass, plus the reduce-scatter, instead of DDP’s single bucketed all-reduce per step.</p><pre>from torch.distributed.fsdp import FullyShardedDataParallel as FSDP<br><br>model = FSDP(<br>    raw_model,<br>    device_id=LOCAL_RANK,<br>    # shard transformer blocks individually so only one layer is materialised<br>    auto_wrap_policy=my_transformer_wrap_policy,<br>)</pre><p>Mentally, <strong>FSDP is still data parallelism, </strong>one logical model, batch split across ranks with the memory footprint of a much smaller job. Reach for it before you reach for tensor or pipeline parallelism, because it does not change how your model is written.</p><p>One caveat that catches people out: <strong>sharding fixes the persistent half of the memory bill only.</strong> FSDP does nothing for activations, because each rank still processes its own micro-batch in full. If you shard a 7B model down to 14 GB per GPU and still run out of memory at 8k tokens, activations are what filled the card, reach for activation checkpointing, not a smaller shard.</p><h3>Tensor parallelism: split the layer</h3><p>Some layers are too large for one GPU no matter how much you shard the optimizer. Tensor parallelism cuts the <strong>weight matrix itself</strong> into pieces, and every GPU computes a partial result for the same input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBwxqUZVwsdy9_LAifd2-g.png" /><figcaption>Figure 1–9. Tensor parallelism: column-wise then row-wise sharding, closed by one all-reduce.</figcaption></figure><p>The pattern comes in pairs, and the pairing is the elegant part.</p><p><strong>Column-wise split.</strong> Take `Y = X · W1` and cut `W1` by columns. Every GPU has the full input `X` and a slice of the columns, so every GPU produces a slice of the output columns. <strong>No communication at all</strong> — the outputs simply live in different places.</p><p><strong>Row-wise split</strong>. Now `Z = Y · W2`, where `Y` already arrives in slices. So cut `W2` by rows to match. Each GPU multiplies its slice of `Y` by its slice of rows and gets a <strong>partial sum</strong> — a matrix of the right shape but the wrong values.</p><p><strong>One all-reduce closes the pair.</strong> Sum the partial sums across GPUs and every GPU has the true output of the block, ready for the next layer.</p><p>In a transformer this maps onto attention almost too neatly: `query`, `key` and `value` projections are column-wise; the output projection that follows is row-wise. In PyTorch you declare it as a plan and let DTensor do the surgery:</p><pre>from torch.distributed.device_mesh import init_device_mesh<br>from torch.distributed.tensor.parallel import (<br>    parallelize_module, ColwiseParallel, RowwiseParallel,<br>)<br><br>tp_mesh = init_device_mesh(&quot;cuda&quot;, (WORLD_SIZE,), mesh_dim_names=(&quot;tp&quot;,))<br><br>tp_plan = {&quot;classifier&quot;: ColwiseParallel()}<br>for name, module in raw_model.named_modules():<br>    if not isinstance(module, torch.nn.Linear):<br>        continue<br>    if any(k in name for k in (&quot;query&quot;, &quot;key&quot;, &quot;value&quot;)):<br>        tp_plan[name] = ColwiseParallel()      # split the output dimension<br>    elif &quot;output.dense&quot; in name:<br>        tp_plan[name] = RowwiseParallel()      # split the input dimension<br><br>model = parallelize_module(raw_model, tp_mesh, tp_plan)</pre><p>Three things to get right, or tensor parallelism will bite you.</p><p><strong>Every rank must see the same batch.</strong> There is no `DistributedSampler` here, TP is not data parallelism. All ranks process identical inputs, which is also why the loss is identical everywhere and needs no all-reduce. Since the ranks are separate processes, <strong>seed them explicitly</strong> rather than trusting the default shuffle order to match.</p><pre>torch.manual_seed(42)   # same seed on every rank, so every rank sees the same batch<br>train_loader = DataLoader(train_dataset, batch_size=4, shuffle=True,<br>                          collate_fn=collate_fn)</pre><p><strong>Keep the dimensions divisible.</strong> Sharded sizes should divide evenly by the TP degree. For attention this is a hard constraint: <strong>the number of heads must be divisible by the TP degree</strong>, or heads get split down the middle and the maths stops meaning anything.</p><p><strong>Watch your checkpoints.</strong> A TP model’s `state_dict` holds DTensors that know their global shape and their local slice. Save and load with the distributed checkpoint APIs, or gather to full tensors deliberately, do not assume a plain `torch.save` on rank 0 gives you a normal file.</p><p>The bonus nobody mentions: <strong>tensor parallelism shrinks activation memory too</strong>, because those sharded intermediates only ever exist as slices. Just do not expect it to divide by the TP degree. The normalisation inputs and the block inputs stay replicated on every rank, so the per-layer estimate from earlier goes from `34·s·b·h` to roughly `(10 + 24/t)·s·b·h`. At TP = 8 that is 13 instead of 34 — a saving of about **2.6×, not 8×**. <strong>Sequence parallelism exists precisely to shard that leftover 10</strong>, splitting the operations that tensor parallelism cannot along the sequence dimension.</p><p>And the cost, which drives every placement decision later: <strong>an all-reduce per block, in both the forward and backward pass, for every layer, every step.</strong> That is dramatically chattier than DDP’s single gradient exchange. It only works when the GPUs involved are joined by something very fast.</p><h3>Pipeline parallelism: split the layers</h3><p>The third cut is the most intuitive. Layers 1–8 on GPU 0, layers 9–16 on GPU 1, and so on. Each GPU holds only its own stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvO3t3MgooJB8JWylr32pg.png" /><figcaption>Figure 1–10. Pipeline parallelism and where the bubble comes from.</figcaption></figure><p>Communication is beautifully small, and it is the one place we use send and recv rather than a collective: at each stage boundary you send the <strong>activations</strong> forward and the <strong>gradients of those activations</strong> backward. Two point-to-point messages per boundary, nothing more. No all-reduce anywhere.</p><p>The catch is idle time. Naively, GPU 1 waits for GPU 0, GPU 2 waits for GPU 1, and most of your cluster is doing nothing. The fix is <strong>micro-batches</strong>: chop each batch into smaller pieces and keep them flowing, so every stage always has something to chew on. The idle time that remains is the <strong>bubble.</strong></p><pre>bubble fraction ≈ (stages - 1) / (micro-batches + stages - 1)</pre><p>Four stages with four micro-batches wastes about 43% of your GPU time. Four stages with 32 micro-batches wastes about 9%. <strong>More micro-batches is the single biggest lever in pipeline parallelism.</strong></p><p>But there is a memory bill attached to that lever, and it is the thing to watch. <strong>A stage must hold the activations of every micro-batch still in flight</strong>, because it cannot free them until that micro-batch’s backward pass comes back through. Under a naive GPipe schedule, all micro-batches go forward before any goes backward, so the first stage ends up holding 32 sets of activations for 32 micro-batches. You solved the bubble and created an out-of-memory error.</p><p>That is exactly what <strong>1F1B</strong> scheduling is for, after a short warm-up it alternates one forward with one backward, which caps the in-flight micro-batches at roughly the number of stages rather than the number of micro-batches. Same bubble, a fraction of the activation memory. It is the default worth using.</p><p>At its core the mechanism is just send and receive:</p><pre>if stage_rank &gt; 0:<br>    dist.recv(activations, src=stage_rank - 1)   # wait for the stage before me<br><br>out = my_stage(activations)<br><br>if stage_rank &lt; n_stages - 1:<br>    dist.send(out, dst=stage_rank + 1)           # hand off to the next stage</pre><p>In practice you use `torch.distributed.pipelining`, which builds the stages and runs a proper schedule for you instead of you hand-rolling the ordering. But the picture above is what it is doing.</p><h3>NCCL: the part you deliberately do not think about</h3><p>Read back over every code sample above. There is not one mention of NVLink, NVSwitch, InfiniBand, RoCE or Ethernet. You wrote `dist.all_reduce` and `backend=”nccl”`. That is the whole point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4bZn4gD0bDFy_0hGrdr4oQ.png" /><figcaption>Figure 1–11. One collective call, many possible transports</figcaption></figure><p>When the communicator is built — stage 3, back at the rendezvous — <strong>NCCL inspects the machine itself</strong>. It reads the PCIe tree, finds which GPUs share NVLink or an NVSwitch, notices which network interfaces exist and which are closest to which GPU. From that map it builds the rings and trees from earlier across a number of parallel “channels”, picks an algorithm, and decides which transport each hop should use:</p><ul><li><strong>NVLink / NVSwitch</strong> for GPU-to-GPU inside a node.</li><li><strong>PCIe peer-to-peer or shared memory</strong> when there is no NVLink.</li><li><strong>GPUDirect RDMA over InfiniBand or RoCE</strong> between nodes, moving data from GPU memory to the NIC without a detour through the CPU.</li><li><strong>TCP sockets</strong> when nothing better exists.</li></ul><p>Your code is identical in all four cases. On a DGX-class box with NVSwitch, an 8-GPU all-reduce runs entirely inside the node. Move that job to eight single-GPU servers on Ethernet and the same call becomes eight network transfers. Same line of Python, wildly different performance, which is why *where* you place each parallelism matters so much.</p><p>You mostly leave NCCL alone. What you should know is how to look:</p><pre># print the topology and algorithms NCCL chose (do this once, on any new cluster)<br>NCCL_DEBUG=INFO NCCL_DEBUG_SUBSYS=INIT,GRAPH torchrun --nproc_per_node=8 train.py<br><br># occasionally needed when a host has several interfaces or HCAs<br>export NCCL_SOCKET_IFNAME=eth0<br>export NCCL_IB_HCA=mlx5_0,mlx5_1</pre><p>That first command prints which rings it built and which transport each link uses. If someone claims NVLink is being used, this is how you check.</p><p>Two extras worth knowing by name: <strong>NVLS</strong>, which uses NVSwitch’s ability to do the reduction in the switch itself, and <strong>SHARP</strong>, which does in-network reduction on InfiniBand. Both are chosen automatically when the fabric supports them. Neither changes your code.</p><h3>So where does UCX come in?</h3><p>If NCCL already handles transports, why does UCX keep appearing in cluster documentation? Because they sit at <strong>different layers</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9eS6tmaZC7B3pIonru1NQ.png" /><figcaption>Figure 1–12. Where UCX sits relative to NCCL, UCC and MPI</figcaption></figure><p>Think of two questions. <em>What</em> should be moved, then sum this tensor across these ranks, this is the <strong>collective</strong> layer, everything we covered earlier. <em>How</em> should the bytes physically travel, which queue pair, which shared-memory segment, which RDMA operation, this is the <strong>transport</strong> layer.</p><p><strong>UCX is a transport framework</strong>, not a collective library. It offers one API (UCP on top of the UCT transport layer) over a long list of transports: shared memory, TCP, InfiniBand RC/UD/DC, RoCE, CUDA IPC, GPUDirect RDMA. Give it a message and a destination and it picks the best available path, including using several at once.</p><p>That gets used three ways in an AI cluster:</p><ul><li><strong>MPI implementations</strong> build their point-to-point and collective operations on UCX, which is why HPC-flavoured jobs on the same fabric perform well without knowing the hardware either.</li><li><strong>UCC</strong> is the collectives library that sits on UCX, giving MPI-style and framework-style collectives one tuned implementation. PyTorch even exposes a `ucc` backend alongside `nccl` and `gloo`.</li><li><strong>NCCL has a pluggable network layer.</strong> It ships with its own InfiniBand and socket implementation, but a site can drop in a plugin, libfabric-based or UCX-based, so all NCCL traffic rides the same tuned transport stack as everything else on the cluster.</li></ul><p>For you as the person writing the training script, the practical summary is short. <strong>You do not choose NVLink, NVSwitch, InfiniBand or UCX. You choose a backend as `nccl` and place your parallelism sensibly.</strong> The libraries below you negotiate the rest. UCX matters when you are the platform engineer making one transport stack serve PyTorch, MPI and RAPIDS at once, or when a plugin gets you better inter-node behaviour than the built-in path.</p><h3>Which one should you use?</h3><p>Work down the list, and only move to the next step when memory forces you:</p><ol><li><strong>Model fits on one GPU?</strong> Use <strong>DDP</strong>. Nothing else. It is simpler, faster and scales further.</li><li><strong>State does not fit, but a single layer does?</strong> Use <strong>FSDP / ZeRO-3</strong>. You keep one logical model and change almost no code.</li><li><strong>A single layer does not fit, or FSDP’s traffic is hurting?</strong> Add <strong>tensor parallelism</strong>, strictly inside a node.</li><li><strong>Still does not fit, or you have far more nodes than one TP group can use?</strong> Add <strong>pipeline parallelism</strong> across nodes, with plenty of micro-batches.</li></ol><p>Note what this ordering implies: <strong>DDP is not the beginner option and TP the advanced one.</strong> DDP is the <em>best</em> option, and TP and PP are what you accept when memory leaves you no choice.</p><h3>A worked plan, end to end</h3><p>Rules of thumb are easier to trust when you have seen the arithmetic once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsMpfeuDEhjDZqK7qrsGXg.png" /></figure><p><strong>The job:</strong> train a 70B-parameter model. <strong>The hardware:</strong> four DGX-class nodes, 8 × 80 GB GPUs each, NVSwitch inside a node, InfiniBand between them. 32 GPUs, 2,560 GB of VRAM in total.</p><p><strong>Step 1 — weigh the state.</strong> 70B × 16 bytes = <strong>1,120 GB</strong>. DDP is out immediately; it would need 1,120 GB on <em>every</em> GPU.</p><p><strong>Step 2 — count what you have.</strong> 32 × 80 GB = <strong>2,560 GB</strong>. Enough in aggregate, so the job is a placement problem, not a capacity problem.</p><p><strong>Step 3 — set the TP degree</strong>. A 70B model’s individual layers are large, so tensor parallelism earns its keep. <strong>TP = 8</strong>, one node, on NVSwitch. Not 16, that would cross a node boundary and put an all-reduce per layer on InfiniBand.</p><p><strong>Step 4 — add pipeline stages.</strong> One node’s 640 GB cannot hold 1,120 GB, so split the layers across a <strong>pair</strong> of nodes. <strong>PP = 2</strong>. Stage boundaries exchange activations only, which InfiniBand handles easily.</p><p><strong>Step 5 — use what is left for throughput.</strong> TP 8 × PP 2 = 16 GPUs per model replica, so 32 GPUs gives <strong>DP = 2</strong>. Two replicas, one gradient all-reduce per step, and shard the optimizer state across them with ZeRO-1 while you are at it.</p><p><strong>Step 6 — check the per-GPU budget, both halves.</strong> One replica’s 1,120 GB of persistent state spread over 16 GPUs is <strong>70 GB per GPU</strong>. Technically under 80 and completely unworkable, because nothing is left for activations, staging buffers or the CUDA context. ZeRO-1 across the two replicas brings the persistent half down to roughly <strong>44 GB</strong>.</p><p>Now add the transient half. A 70B model has a hidden size around 8192 and roughly 80 layers, so at 4k tokens and micro-batch 1 the stored activations are on the order of <strong>tens of GB per GPU</strong> before recomputationand only about a quarter of that is removed by TP = 8. Add 44 GB of state and you are over the line again.</p><p>So the plan needs one more decision: <strong>activation checkpointing on</strong>, which drops that transient figure by roughly an order of magnitude for about 30% more compute, plus <strong>1F1B scheduling</strong> so the two pipeline stages do not hoard in-flight micro-batches. Budget to about 70 GB of the 80, not all of it. That is the configuration that actually runs.</p><p><strong>The answer: TP 8 × PP 2 × DP 2 = 32 GPUs.</strong></p><h3>Key takeaways</h3><ul><li><strong>Persistent state is about 16 bytes per parameter</strong> with mixed precision and Adam, and <strong>12 of those 16 bytes are optimizer state</strong>, not model. Changing optimizer can free more memory than changing the model.</li><li><strong>Activations are the other half of the bill</strong>, roughly `34 × seq × micro-batch × hidden` bytes per layer. They scale with batch and sequence length while the weights do not, and past a few thousand tokens they are the bigger number.</li><li><strong>Activation checkpointing is the biggest single lever</strong> you have: about 10× less activation memory for about 30% more compute.</li><li><strong>Budget 85–90% of nameplate VRAM.</strong> Staging buffers, the CUDA context and allocator fragmentation take the rest.</li><li><strong>The rendezvous assigns identity.</strong> Startup hangs are rendezvous problems; mid-training hangs are collective problems.</li><li><strong>A collective is a contract. </strong>Same call, same order, same shapes, on every rank, or the job hangs instead of failing.</li><li><strong>All-reduce is reduce-scatter plus all-gather.</strong> On a ring, each GPU moves `2(N-1)/N` times the tensor — a factor that never reaches 2, however many GPUs you add.</li><li><strong>DDP replicates the model and splits the data</strong>, joined by one gradient all-reduce that overlaps with the backward pass. It is the default, not the beginner choice.</li><li><strong>Scheduler, scaler and RNG state cost no memory and can ruin a run.</strong> Step the scheduler on every rank with an all-reduced metric, and put all of it in the checkpoint.</li><li><strong>FSDP / ZeRO shards the state</strong> and buys memory with extra all-gather and reduce-scatter traffic.</li><li><strong>Tensor parallelism splits a layer</strong> (column-wise, then row-wise, closed by an all-reduce) and belongs inside an NVLink domain.</li><li><strong>Pipeline parallelism splits the layers</strong> into stages, communicates only activations, and needs many micro-batches to shrink the bubble.</li><li><strong>Each parallelism treats activations differently.</strong> DP does not reduce them, TP reduces them partially (sequence parallelism finishes the job), and PP can increase them because every in-flight micro-batch is held, which is why 1F1B scheduling matters.</li><li><strong>NCCL picks the topology and transport for you</strong>, and UCX is a transport framework under collective libraries, neither belongs in your training script.</li><li><strong>Place the chattiest parallelism on the fastest link</strong>: TP inside the node, PP across nodes, DP outermost.</li></ul><p>Distributed training feels like a dark art mostly because two very different concerns get taught together: how to split a model, and how bytes cross a wire. Separate them, and there are only three ways to split and six ways to communicate. That is a small enough vocabulary to hold in your head — and everything else is arithmetic you can do on a napkin before you burn a single GPU-hour.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d60519d0fcfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your GPUs Aren’t Slow. They’re Waiting. Meet NVIDIA Magnum IO]]></title>
            <link>https://medium.com/@sabu.for.ai/your-gpus-arent-slow-they-re-waiting-meet-nvidia-magnum-io-9de72dbbb5c6?source=rss-8e33a2f4eafe------2</link>
            <guid isPermaLink="false">https://medium.com/p/9de72dbbb5c6</guid>
            <category><![CDATA[high-performace-computing]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-infrastructure]]></category>
            <category><![CDATA[nvidia]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 16:25:31 GMT</pubDate>
            <atom:updated>2026-07-08T16:25:31.429Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The hidden bottleneck in AI isn’t the chip — it’s moving data. Here’s how NVIDIA fixes it.</em></p><p>You bought the best GPUs on the market. You wired them into a cluster. You hit “train” — and it crawls.</p><p>You check your monitoring, and there it is: your GPUs are busy only a fraction of the time. The rest of the time, they’re just… waiting. Waiting for data from a disk. Waiting for updates from other GPUs. Waiting for the network to catch up.</p><p>Here’s the uncomfortable truth about modern AI: <strong>the chip is almost never the bottleneck. Moving data is.</strong> And that’s exactly the problem NVIDIA Magnum IO was built to solve.</p><h3>What Magnum IO actually is</h3><p>Magnum IO is the collection of input/output (IO) technologies that make up the “plumbing” of an AI data center. Its entire mission fits in one sentence: <strong>eliminate bottlenecks by bypassing the CPU, so GPUs can talk directly to storage and to each other.</strong></p><p>If you’ve ever scaled a model to multiple GPUs or multiple servers, you’ve used it — probably without realizing it. It’s organized into four layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*us9L-NBsumhKRdoe1dhSEw.png" /><figcaption>Figure 1–1. NVIDIA Magnum IO groups the data center’s IO technologies into four functional layers.</figcaption></figure><ul><li><strong>Network IO</strong> — moving data between GPUs.</li><li><strong>Storage IO</strong> — getting data from disk into GPU memory.</li><li><strong>In-Network Compute </strong>— doing math inside the network itself.</li><li><strong>IO Management</strong> — keeping the whole fabric healthy.</li></ul><p>Notice the pattern that runs through all of them: at every layer, the trick is to get the CPU out of the way.</p><h3>The foundation: stop climbing the kernel</h3><p>Start with how data normally arrives at a machine. In a traditional network, incoming data has to climb up through the operating system’s networking stack, there it is copied and processed at each step, before your app can touch it. That’s slow, and it burns CPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfc0cX0h3C9RUNen4D9j-w.png" /><figcaption>Figure 1–2. How RDMA works: the network card talks straight to memory, bypassing the kernel.</figcaption></figure><p><strong>RDMA (Remote Direct Memory Access)</strong> throws that away. The network card writes data <em>directly</em> into your application’s memory, skipping the kernel entirely. This “kernel bypass” is the single most important idea in fast networking. It’s why one GPU can read another GPU’s memory across the data center without ever bothering a CPU.</p><p>This is the foundation everything else is built on.</p><h3>Write it once: let UCX pick the path</h3><p>Inside a cluster, there are several ways to move data. Same server? Use shared memory. Different servers? Use InfiniBand and RDMA. Just management traffic? Plain Ethernet is fine.</p><p>The nightmare is that each of these needs completely different code — and if the hardware changes, your software breaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXMOHzIp-xlV4sIEbsCLMw.png" /><figcaption>Figure 1–3. UCX gives one API and picks the fastest transport for you.</figcaption></figure><p><strong>UCX</strong> solves this beautifully. You write one line like “send this block to Node B” and UCX figures out the fastest physical path automatically. Whether it is a</p><ul><li>Same box? Shared memory.</li><li>Or, across a switch? RDMA.</li></ul><p>It’ll even split your data across four network cards at once to max out bandwidth. You never write hardware-specific networking code again.</p><h3>The clever bit: make the network do the math</h3><p>This one genuinely surprised me the first time I understood it.</p><p>When you train across hundreds of GPUs, they all have to average their results after every step, that is an operation called <strong>AllReduce</strong>. The old way: every GPU blasts its data to every other GPU, the network floods with duplicate traffic, and the GPUs waste cycles adding numbers up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DlccRjwjs2tjJ6twwtN_4g.png" /><figcaption>Figure 1–4. SHARP moves the AllReduce sum into the switch, roughly halving traffic.</figcaption></figure><p><strong>SHARP</strong> flips this. Instead of GPUs talking to each other, they send their numbers/gradients <em>up to the switch, </em>and the switch itself has a math engine that sums them and broadcasts back just the final answer. The result: <strong>roughly half the traffic on the fabric</strong>, and GPUs that never stop to do the boring aggregation. The network literally does the math in mid-air.</p><h3>Feeding the beast: skip the bounce buffer</h3><p>Now, storage. Getting data off a disk and into a GPU is painfully slow the traditional way.</p><p>The data leapfrogs: NVMe drive → CPU system RAM → across the bus → GPU memory. Two copies, and the CPU coordinating the whole dance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RwlCZyCaoJkH7QjYVSpjLw.png" /><figcaption>Figure 1–5. GPUDirect Storage streams data straight from NVMe into GPU memory.</figcaption></figure><p><strong>GPUDirect Storage</strong> cuts out the middleman. It creates a direct path straight from the NVMe drive into GPU memory. The CPU and system RAM are bypassed completely, and CPU usage for this drops by **up to 99%**. Best part: it’s baked into PyTorch, TensorFlow, and RAPIDS, so you often get it for free.</p><p>But where should that data live? You don’t want hot SSDs jammed into every GPU server. You want a shared network pool. The catch is that talking to network storage is usually complicated and CPU-heavy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJ6JAQUkxc4NjD2ODogQsA.png" /><figcaption>Figure 1–6. NVMe SNAP makes remote network storage look like a local disk</figcaption></figure><p><strong>NVMe SNAP</strong> pulls off a magic trick. Running on the BlueField DPU, it tells the host operating system, “I’m a local SSD.” The OS uses its normal disk drivers, none the wiser, and sees something like `/dev/nvme0n1`. Behind the scenes, the DPU intercepts every read and write and quietly routes it across the network to a central storage array. Remote storage that feels completely local.</p><h3>It all clicks together</h3><p>Here’s the payoff. Watch every layer cooperate on a single training step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYAOzkhDGt3ZlnmyyG33ig.png" /><figcaption>Figure 1–7. Every Magnum IO layer working together on one training step.</figcaption></figure><p>Management tools (UFM for InfiniBand, NetQ for Ethernet) keep the fabric healthy. NVMe SNAP and GPUDirect Storage stream data straight into GPU memory. MOFED and UCX drive the hardware and pick the fastest path. NVSHMEM and NCCL share memory and synchronize the math. And ASAP² and SHARP handle routing and gradient math right in the network hardware, keeping the CPU near 0% and the GPUs busy.</p><p>Every single piece is chasing the same goal: <strong>keep the data moving so the GPU never waits.</strong></p><h3>You can try it on one GPU</h3><p>The best part? You don’t need a giant cluster to start. NVIDIA ships a <strong>Magnum IO Developer Environment Container</strong> that bundles the whole stack, CUDA, NCCL, NVSHMEM, UCX, cuFile, all the headers into one image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Er8r3TwNbTdgpK5rRJWylg.png" /><figcaption>Figure 1–8. Prototype on one GPU, then ship the same code to the SuperPOD.</figcaption></figure><p>The workflow is simple. Pull the container onto a laptop or single-GPU box. Profile your script with NVIDIA Nsight Systems:</p><pre>nsys profile - trace=cuda,nvtx,osrt,ucx -o my_profile python train.py</pre><p>Then read the timeline. Every blank gap where the GPU drops to 0% is time it spent waiting on IO. Fix your code until those gaps close — then ship the exact same script to the bare-metal SuperPOD, confident it won’t stall.</p><h3>Key takeaways</h3><ul><li><strong>Your GPUs are probably waiting, not computing.</strong> Profile before you blame the chip.</li><li><strong>The whole game is bypassing the CPU</strong> — that’s the thread connecting RDMA, GPUDirect Storage, ASAP², and NVMe SNAP.</li><li><strong>RDMA + kernel bypass</strong> is the foundation of fast GPU networking.</li><li><strong>UCX</strong> lets you write networking code once and run it anywhere.</li><li><strong>SHARP</strong> makes the switch do the AllReduce math, halving fabric traffic.</li><li><strong>GPUDirect Storage</strong> streams data straight to the GPU; **NVMe SNAP** makes remote storage feel local.</li><li><strong>You can prototype and profile all of this on a single GPU</strong> before touching a cluster.</li></ul><p>If this helped the pieces click into place, follow me for more plain-English deep dives into the systems behind modern AI. And I’d love to know: what’s the worst IO bottleneck you’ve hit in a training run? Tell me in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9de72dbbb5c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[InfiniBand Explained: The Secret Networking Technology Behind the World’s Fastest AI Clusters]]></title>
            <link>https://medium.com/@sabu.for.ai/infiniband-explained-the-secret-networking-technology-behind-the-worlds-fastest-ai-clusters-36f0945fe07d?source=rss-8e33a2f4eafe------2</link>
            <guid isPermaLink="false">https://medium.com/p/36f0945fe07d</guid>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[infiniband]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[nvidia-gpu]]></category>
            <category><![CDATA[ai-infrastructure]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 12:44:14 GMT</pubDate>
            <atom:updated>2026-07-05T12:44:14.783Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why your GPU cluster’s network matters as much as the GPUs themselves and how InfiniBand makes the difference.</em></p><p>You’ve budgeted for the GPUs. You’ve configured the compute nodes. And then, the cluster is slower than you expected.</p><p>The GPUs aren’t the bottleneck. <strong>The network is.</strong></p><p>This is the situation that has surprised more than a few teams deploying their first serious AI training infrastructure. GPUs are fast. The network connecting them needs to keep up. And “keeping up” at GPU speed requires something that most people have never heard of: <strong>InfiniBand</strong>.</p><h3>What Is InfiniBand, and Why Should You Care?</h3><p>InfiniBand is a networking technology built for one purpose: <strong>moving data between compute nodes as fast as possible, with as little CPU involvement as possible.</strong></p><p>It connects more than <strong>50% of the world’s TOP500 supercomputers</strong>. Every major GPU cluster you’ve read about from NVIDIA’s DGX SuperPOD to the compute infrastructure behind modern frontier AI models, is almost certainly running InfiniBand under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIhm7lneLEsIPURcqeayaw.png" /><figcaption>InfiniBand connects a compute node to storage at 800 Gbps through a switch. Concept adapted from public NVIDIA documentation.</figcaption></figure><p>Standard Ethernet is a general-purpose technology. It was designed to serve web servers, databases, and video streams. InfiniBand was designed for a very different problem: the <strong>all-reduce operation</strong> at the heart of distributed AI training, where hundreds of GPUs must exchange gradient updates in tight synchrony, millions of times per training run.</p><p>During distributed training, every GPU computes its own gradient updates. Before the next training step, all GPUs must average those gradients together, this is the <strong>AllReduce</strong> operation.</p><h3>The Problem with Normal Networking</h3><p>Let me walk you through what happens when two servers exchange data over a standard TCP/IP network.</p><p>Server A has data it wants to send to Server B. Here’s the path that data takes:</p><ol><li>The GPU copies data from VRAM to system RAM.</li><li>The CPU processes the TCP/IP headers.</li><li>The OS kernel’s network stack handles the packet.</li><li>The network card transmits it.</li><li>On Server B’s side — the reverse process, in full.</li><li>Server B’s CPU copies the data into GPU B’s VRAM.</li></ol><p><strong>That’s four to six copy operations</strong>. Three kernel transitions. Sustained CPU involvement. And the GPU is sitting idle the entire time, waiting.</p><p>At the scale of AI training, thousands of tensors flowing between hundreds of GPUs every second, this CPU overhead doesn’t just slow things down. It can completely stall forward progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dfRiJAmtsH80HMjYf1IkQ.png" /><figcaption>Before GPU Direct: data travels through the OS kernel, CPU, and system RAM before reaching GPU VRAM.</figcaption></figure><h3>DMA and RDMA: The Core Ideas</h3><p>InfiniBand solves this with two foundational mechanisms.</p><p><strong>DMA (Direct Memory Access)</strong> is the ability of a hardware device — a GPU, a network card — to access system memory directly, without the CPU acting as an intermediary. The CPU sets up the transfer and then gets out of the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFH3MiwTSKJLF1a4w3pUHA.png" /><figcaption>DMA allows a GPU to access host memory without CPU involvement.</figcaption></figure><p><strong>RDMA (Remote Direct Memory Access)</strong> extends DMA across a network. With RDMA, a network card on Server A can reach directly into the memory of Server B, without interrupting Server B’s CPU at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCsOnx0dCR6gf1o9aDPp2A.png" /><figcaption>RDMA bypasses the OS kernel on both ends, enabling direct memory access between servers via the HCA hardware.</figcaption></figure><p>The InfiniBand network adapter called an <strong>HCA (Host Channel Adapter). </strong>It has dedicated silicon that handles all the transport-layer work: packet reliability, ordering, retransmission, flow control. None of that runs on the host CPU. It all runs on the HCA’s chip.</p><p>The result? <strong>Sub-microsecond latency</strong>. Under 1,000 nanoseconds, compared to tens of microseconds for TCP/IP.</p><h3>GPU Direct RDMA: Zero Copies, Zero CPU</h3><p>The standard RDMA described above still operates on <em>system RAM</em>. Moving data from GPU 1’s VRAM to GPU 2’s VRAM would still require</p><blockquote>GPU → system RAM → network → system RAM → GPU copies.</blockquote><p><strong>GPU Direct RDMA removes those remaining copies entirely.</strong></p><p>The HCA communicates directly with the GPU over the PCIe bus. It pulls data straight from GPU 1’s video memory, pushes it over the network, and writes it directly into GPU 2’s video memory, in a single operation. The CPU never touches the data. System RAM is not involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJW8tw4luQ40xrlnVbql8w.png" /><figcaption>GPU Direct RDMA: HCA transfers data directly between GPU VRAM on two servers, bypassing the OS, CPU, and system RAM entirely.</figcaption></figure><p>This is the fundamental performance architecture of every serious AI training cluster. Gradient exchange happens at network speed, not CPU speed.</p><h3>How InfiniBand Has Grown</h3><p>InfiniBand has roughly doubled its per-port bandwidth with every generation since 2002.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSrcAPMPj0Xk1UCwWT0Stw.png" /><figcaption>InfiniBand bandwidth by generation, from SDR (10 Gb/s) to NDR (400 Gb/s)</figcaption></figure><p>The current generation — <strong>NDR (Next Data Rate)</strong> — delivers <strong>400 Gb/s per port</strong>. The generation after that, <strong>XDR</strong>, will reach <strong>800 Gb/s</strong>. Each generation aggregates four physical lanes: NDR runs four 100 Gb/s lanes per link.</p><h3>The Components of an InfiniBand Network</h3><p>You can think of an InfiniBand fabric as having four key components.</p><h4>HCAs (Host Channel Adapters)</h4><p>These are the network cards that go into each server. The NVIDIA ConnectX-7 is the current standard for DGX H100 clusters, running at 400 Gb/s NDR. The newer ConnectX-8 SuperNIC runs at 800 Gb/s and brings InfiniBand-grade capabilities to Ethernet.</p><h4>Switches</h4><p>IB switches move packets between HCAs. NVIDIA’s Quantum-2 switches support NDR (400 Gb/s per port) and include hardware for SHARP in-network compute.</p><h4>The Subnet Manager (SM)</h4><p>The SM is a program that manages the entire IB fabric. It discovers topology, assigns Local IDs (LIDs) to every node, calculates routing paths, and programs forwarding tables into every switch. Without the SM, the fabric cannot route anything.</p><h4>Routers and Gateways</h4><p>IB routers connect multiple IB subnets (each can hold up to 48,000 nodes). IB gateways like the NVIDIA Skyway bridge the IB fabric to Ethernet networks.</p><h3>SHARP: When the Network Does the Math</h3><p>Here’s the feature that genuinely surprised me the first time I encountered it.</p><p>During distributed training, every GPU computes its own gradient updates. Before the next training step, all GPUs must average those gradients together, this is the <strong>AllReduce</strong> operation. In a traditional network, every GPU blasts its data to every other GPU. The network floods. The GPUs wait.</p><p><strong>SHARP (Scalable Hierarchical Aggregation and Reduction Protocol)</strong> moves the AllReduce computation into the switches themselves.</p><p>Instead of each GPU sending to every other GPU, all GPUs send their gradients <em>up</em> to the nearest switch. The switch has dedicated hardware on its ASIC that sums the numbers right there on the chip, then broadcasts only the final averaged result back down to the GPUs.</p><p>The impact: SHARP roughly <strong>halves the amount of data crossing the fabric</strong> during gradient synchronization. GPUs dump their data and receive the answer in a fraction of a second. Training throughput improves meaningfully at scale.</p><h3>InfiniBand Layers: A Quick Mental Model</h3><p>InfiniBand uses the same layered architecture as TCP/IP (physical, link, network, transport, application layer), but with a crucial difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2eFeEheBvKpdomASy_ObQ.png" /><figcaption>InfiniBand mirrors TCP/IP’s layered architecture but implements transport in HCA hardware instead of the OS kernel.</figcaption></figure><p>In TCP/IP, the transport layer runs in software on the OS kernel. Every packet transfer involves kernel crossings and CPU scheduling overhead.</p><p>In InfiniBand, the transport layer runs in the HCA’s ASIC. <strong>The OS kernel is never involved in the data path.</strong> This is what “kernel bypass” means in practice, and it is the single architectural decision that delivers InfiniBand’s latency advantage over standard networking.</p><h3>Verifying Your Cluster: The Diagnostic Commands</h3><p>Once you have an InfiniBand cluster, a handful of commands tell you immediately whether everything is healthy.</p><h4><strong>Check HCA status:</strong></h4><pre>ibstat</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*qXZ5shcX7PuV0Zx2Ok9Exg.png" /><figcaption>It will show similar output for all the HCA present in server</figcaption></figure><h4><strong>Check NVLink status (within each node):</strong></h4><pre>nvidia-smi nvlink --status</pre><p>On a DGX H100, you should see 18 links per GPU, all Active at 900 GB/s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*h4DaYt572HnXa3lZpJjzzw.png" /><figcaption>nvidia-smi nvlink — status confirming all 18 NVLink links active at 900 GB/s on a DGX H100.</figcaption></figure><h4><strong>Check all links in the fabric:</strong></h4><pre>iblinkinfo</pre><p>This maps every switch port to a connected HCA, showing speed and state. A link running at HDR instead of NDR means a bad cable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I53rJq44zbuWnxdoFTv8Xg.png" /></figure><h4><strong>Full fabric health scan:</strong></h4><pre>ibdiagnet</pre><p>Scans the entire fabric for topology errors, firmware mismatches, and hardware degradation. On a healthy cluster, it ends with: <em>No errors found</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMeJ9wn-ZyR89M9BDJoAtw.png" /></figure><h3>Key Takeaways</h3><ul><li><strong>InfiniBand is the networking technology behind most of the world’s top AI and HPC clusters. </strong>It is designed specifically for high-throughput, low-latency GPU-to-GPU data movement.</li><li><strong>RDMA</strong> lets the HCA move data between servers without CPU involvement on either end, achieving sub-microsecond latency.</li><li><strong>GPU Direct RDMA</strong> takes this further, the HCA talks directly to GPU VRAM via PCIe, eliminating all copies through system RAM.</li><li><strong>NDR InfiniBand delivers 400 Gb/s per port</strong>, with XDR at 800 Gb/s coming next.</li><li><strong>SHARP offloads AllReduce operations to the switches</strong>, cutting gradient exchange traffic roughly in half.</li><li><strong>The Subnet Manager</strong> automatically discovers, routes, and programs the entire fabric, as plug-and-play at cluster scale.</li><li><strong>A small toolkit of commands</strong> (`ibstat`, `iblinkinfo`, `ibdiagnet`, `nvidia-smi nvlink`) tells you immediately whether your fabric is healthy.</li></ul><p>If you’re working on GPU cluster infrastructure, or just trying to understand what’s happening under the hood of frontier AI training, InfiniBand is worth spending real time with. The concepts here will make everything from network topology decisions to performance debugging significantly more tractable.</p><p>What questions do you have about InfiniBand or GPU cluster networking? Drop them in the comments. I read every one.</p><p>If this was useful, consider following for more deep dives into AI infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36f0945fe07d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LLM GPU Training: Training Transformers Needs 6–8× More GPU Memory than Inference]]></title>
            <link>https://medium.com/@sabu.for.ai/understanding-llm-gpu-training-training-transformers-needs-6-8-more-gpu-memory-than-inference-b17aafb1f7e3?source=rss-8e33a2f4eafe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b17aafb1f7e3</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 13:21:02 GMT</pubDate>
            <atom:updated>2026-03-21T13:25:45.651Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous post on inference, I broke down how LLMs use GPU memory (weights + KV cache).</p><p><a href="https://medium.com/@sabu.for.ai/understanding-llm-gpu-inference-vram-kv-cache-and-vllm-explained-with-mistral-7b-ea73c562f312">Understanding LLM GPU Inference: VRAM, KV Cache, and vLLM Explained with Mistral-7B</a></p><blockquote>A model that fits comfortably during inference suddenly needs <strong>6–8× more memory</strong> during training.</blockquote><p>This blog explains <strong>why that happens</strong>, with both <strong>theory + real GPU measurements</strong> from my experiments.</p><h3>Inference vs Training Memory</h3><p>Let’s start with the fundamental difference:</p><p><strong>Inference memory</strong></p><blockquote>weights + KV cache + temporary buffers</blockquote><p><strong>Training memory</strong></p><blockquote>weights + gradients + optimizer states + activations</blockquote><h3>The Model I Used</h3><p>Instead of jumping to a 7B model, I built a small transformer with 39.6M parameters. Math behind this 39.6 parameters is explain below.</p><p>Please find the code required for this experiment</p><p><a href="https://github.com/saurabh922/llm-gpu-memory-deep-dive.git">https://github.com/saurabh922/llm-gpu-memory-deep-dive.git</a></p><pre>nn.Transformer(<br>    d_model=512,<br>    nhead=4,<br>    num_encoder_layers=4,<br>    num_decoder_layers=4<br>)</pre><p>And wrapped it in a simple NMT model class, the full pipeline is</p><pre>tokens → embedding → positional embedding → transformer → linear → output</pre><p>This allowed me to:</p><ul><li>compute exact parameters</li><li>measure memory step-by-step</li><li>control batch size</li></ul><h4>Understanding the Model (Exact Math)</h4><p>Before running anything, I computed the <strong>exact number of parameters</strong>.</p><h4>Embedding Layer</h4><pre>vocab_size × hidden<br>= 10,000 × 512<br>= 5,120,000</pre><h4>Encoder or decoder Layer</h4><p>Each encoder layer has: Self-attention</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*H0j8wJedpkavKa9C_OgFQA.png" /><figcaption>Attention layer</figcaption></figure><pre>4 × (512 × 512) = 1,048,576<br><br>Why 4 * (512 * 512)?<br>Q = XWq<br>K = XWk<br>V = XWv<br>Where Wq, Wk, Wv = respective weight matrix for Q/K/V, <br>and X = input vector(512)<br>So, the number for parameters for each is 512 * 512.<br>We have 4 such linear layers: Q, K, V, Output projections<br><br>Hence we got 4 * (512 * 512) = = 1,048,576</pre><h4>Feed Forward (FFN)</h4><p>We have two linear layers in FFN</p><pre>Code (hidden_size = 512 as we mentioned before)<br>self.linear1 = nn.Linear(hidden_size, dim_ffn)<br>self.linear2 = nn.Linear(dim_ffn, hidden_size)<br><br>Parameter count (by default nn.trasnformer dim_feedforward=2048)<br>512 × 2048 + 2048 × 512 = 2,097,152</pre><h4>LayerNorms</h4><pre>self.norm1 = nn.LayerNorm(input_dim_size)<br><br>So LN parameters ≈ 2,048</pre><h3>Output Layer (after transformer)</h3><pre>self.output = nn.Linear(Hidden_size, vocab_size)<br><br>hidden × vocab_size<br>= 512 × 10,000<br>= 5,120,000</pre><h4>Total per Encoder Layer</h4><pre>Self-attention -&gt; 4 × (512 × 512) = 1,048,576<br>Feed Forward (FFN) -&gt; 512 × 2048 + 2048 × 512 = 2,097,152<br>LayerNorms -&gt; 2,048<br><br>Total per encoder layer ≈ 3,147,776<br><br>We have 4 encoder layers, so total for all 4 encoder layers:<br>4 * 3,147,776 = 12,591,104</pre><h4>Total for Decoder Layer</h4><pre>Decoder has extra cross-attention:<br>Self-attention     = 1,048,576<br>Cross-attention    = 1,048,576<br>FFN                = 2,097,152<br>LayerNorms         ≈ 3,072<br><br>Total per decoder layer ≈ 4,197,376<br>Total decoder (4 layers) ≈ 16,789,504</pre><h4>Conclusion: Final Parameter Count</h4><pre>Encoder ≈ 12.6M <br>Decoder ≈ 16.8M <br>Embedding+Out ≈ 10.2M <br>-------------------------------- <br>Total ≈ 39.6M parameters</pre><h3>Understanding the GPU memory requirements</h3><h4>Training memory = weights + gradients + optimizer states + activations</h4><p>We will understand all the components</p><h4>Weights</h4><p>For mistral-7B with FP16 weights, we need 7B * 2 = 14GB memory, as FP16=2bytes</p><p>But for the tiny transformer we built had 39.6 parameters, then required memory for the weights is</p><pre>by default torch uses FP32, torch.float32 (FP32). So,<br><br>39.6M × 4 bytes ≈ 158.4 MB</pre><p>Approximately we will consider <strong>160MB</strong> for weights</p><h4>Activations</h4><p>During forward pass, compute outputs, the network computes <strong>intermediate tensors</strong> at every layer. Those are called <strong>Activations</strong>.</p><p>At this stage <strong>weights + activations will be stored in memory</strong>. Forward pass stores intermediate activations because they are needed for backward pass.</p><p>This depends on:</p><ul><li>batch_size</li><li>sequence_length</li><li>hidden_size</li><li>num_layers</li></ul><p>Activations = batch size × sequence length × hidden size × num layers</p><p><strong>Forward pass</strong>:</p><pre>z = wx + b<br>y = f(z)</pre><p>Where f is the activation function (ReLU, GELU, etc.).</p><p>During the test, we will check the calculations.</p><h4>Gradients</h4><p>During Backward Pass, gradients are computed, <strong>at this stage weights + activations + gradients will be stored in memory</strong>. During backprop each weight gets a gradient. Hence</p><pre>gradients ≈ same size as weights<br><br>gradients = weights = 160 MB</pre><h4>Optimizer States</h4><p>This is where memory <strong>really explodes</strong>. Example with <strong>Adam optimizer, Adam stores </strong>m (momentum) and v (variance). Optimizer states are NOT the new weights and NOT the gradient descent itself. They are <strong>extra variables the optimizer keeps to help compute the update.</strong></p><p>So optimizers like, <strong>SGD with momentum, Adam, NAdam (usually used in transformer) </strong>store <strong>extra information about past gradients</strong>.</p><p>This extra information is called <strong>optimizer state</strong>.</p><p>For NAdam, as it needs to store m and v, so, it size is twice of the weights</p><pre>optimizer states ≈ 2 × weights = 320 MB</pre><h4>Conclusion</h4><p>Activation will depend on batch size, sequence length, hidden size and number of layers, but weights/gradients/Optimizer states are fixed. So the total fixed part for the tiny transformer is:</p><p>weights + gradients + optimizer states = 160 + 160 + 320 = 640 MB (fixed)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*1NWO5kpovgQTx4wyS3Lu9Q.png" /><figcaption>Components which will be stores in memory during training</figcaption></figure><h3>The Experiment</h3><p>I instrumented my training loop:</p><pre>torch.cuda.memory_allocated()<br>torch.cuda.max_memory_allocated()</pre><p>and printed memory at:</p><ul><li>before forward</li><li>after forward</li><li>after backward</li><li>after optimizer step</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUcJMEWRTi4b1y2iqXQ58g.png" /><figcaption>Memory Utilized during training with different batch size</figcaption></figure><h4>Key Observations</h4><ul><li>Weights (after Model Creation) ~152.55 MB (constant across all batch sizes)</li><li>Activations, <strong>during forward pass</strong>, model compute outputs, the network computes <strong>intermediate tensors</strong> at every layer. <strong>Activations = batch size × sequence length × hidden size × num layers</strong>. In our experiment we kept sequence length = 128, number of layers = 4, hidden size = 512 and we tested with batch size 8, 16 and 32.</li></ul><pre>B = batch size, S = sequence length, H = hidden size<br>- Input = (B, S, H) = B × 128 × 512<br>- Q, K, V = 3 * (B, S, H) <br>- Attention output = (B, S, H)<br>- FNN = (B, S, 2048)<br>- S × H = 128 × 512 = 65,536<br><br>Encoder layer = input + Q + K + V + attn_out + FFN<br>Encoder layer = (1 + 3 + 1) × (B × S × H) + (B × S × 2048) = 9 × (B × S × H) = 9 * B * 65,536<br>Similary, Decoder Layer(self + cross attn) = 13 × (B × S × H) = 13 * B * 65,536<br>total = 88 * B * 65,536<br><br>Batch = 8 <br>Activations = 8 * 88 × 65,536 = 46,137,344<br>Activation with FP32 = 46,137,344 * 4 ≈ 184 MB<br><br>Batch = 16<br>Similary with FP32 ≈ 369 MB</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*X9yPs7MlZRlenF5zsOSaSA.png" /><figcaption>Memory variation with batch size</figcaption></figure><ul><li>Gradients (Backward Stage) roughly constant as ~330MB(small variation due to allocator behavior)</li><li>Optimizer (After optimizer.step()) nearly constant (~600 MB jump from backward)</li></ul><h3>Key takeaways</h3><h4>1. Training Memory ≠ Inference Memory</h4><pre>Inference = weights + KV cache + buffer<br>Training  = weights + gradients + optimizer states + activations</pre><p>The extra components (gradients, optimizer states, activations) are why training is significantly more expensive.</p><h4>2. Model Size Comes from hidden² (Matrix Multiplication)</h4><p>hidden size * hidden size</p><p>39.6M parameters → ~160 MB (FP32) This is the <strong>base cost</strong> of training.</p><h4>3. Fixed vs Variable Memory (Most Important Insight)</h4><pre>Fixed memory:<br>weights + gradients + optimizer states ≈ 640 MB<br><br>Variable memory:<br>activations (depends on batch size)</pre><pre>Variable memory:<br>activations (depends on batch size)</pre><p>This separation explains <strong>all GPU memory behavior during training</strong>.</p><h4>4. Activations Are the Only Component That Scales with Batch Size</h4><p>I expected training to be slightly heavier than inference. Instead, it was dramatically higher — and I wanted to understand exactly why.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b17aafb1f7e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LLM GPU Inference: VRAM, KV Cache, and vLLM Explained with Mistral-7B]]></title>
            <link>https://medium.com/@sabu.for.ai/understanding-llm-gpu-inference-vram-kv-cache-and-vllm-explained-with-mistral-7b-ea73c562f312?source=rss-8e33a2f4eafe------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea73c562f312</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 15:46:54 GMT</pubDate>
            <atom:updated>2026-03-10T16:22:36.137Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Goal</strong>: When running an LLM on GPU, where does the memory go?</h4><p>I ran experiments deploying Mistral-7B on a 24GB GPU<br>to understand how GPU memory is used during inference.</p><p><strong>STEP1: First if we have to estimate GPU VRAM for the LLM we are targeting.</strong></p><p>lets say we want to deploy Mistral 7B, so how much VRAM is required if we will use FP16/BP16 weights?</p><p><strong>GPU VRAM = M<em>odel weights + KV cache + activations + CUDA overhead</em></strong></p><p><strong>Model Weights</strong>: if Mistral has 7B billion parameters, and FP16 means 2 bytes, then for weights only, we need 14GB VRAM.</p><pre>7B params × 2 bytes (FP16) = 14GB</pre><p>Then we need extra VRAM for following purposes.</p><ul><li><strong>KV cache</strong></li><li><strong>Activations</strong></li><li><strong>CUDA overhead</strong></li><li><strong>Fragmentation</strong></li></ul><h4>KV Cache</h4><p>Mistral is a decoder-only transformer model. During generation it produces one token at a time. Each new token must attend to all previous tokens. One token is generated at a time step, for this it has to pay attention to previous tokens. The core function of attention layers is to compute</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMMaEfVtApPOmuUQlq7jAA.png" /></figure><p>So, for every token t, we need to compute Qt, Kt, Vt, and then compute dot product of Qt with K1 to Kt and then dot product of SoftMax output pr previous with V1 to Vt.</p><p>But with the help of cache we do not need to repeat computation of intermediate steps. For example for generation of third token, we do not need to compute K1, K2, V1 and V2 again.</p><ul><li>Compute Q3, K3, V3</li><li>Attention(Q3, [K1, K2, K3], [V1, V2, V3])) here K1, K2, V1 and V2 will be retrieved from cache.</li><li>Store K3 and V3 in cache</li></ul><p><strong>This is known as KV caching.</strong></p><p>KV cache can increase linearly with context length, let’s see how to calculate KV cache. Formulae is</p><p>Batch * Seq_len * Layers * KV_heads * head_dim * 2 (K,V) * dtype_bytes</p><p>In mistral 7B we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*GJaf2nfbcospY7RK6yvZpQ.png" /></figure><p>Mistral Uses <strong>Grouped Query Attention (GQA)</strong>, so instead of every query head having its own K and V, <strong>multiple query heads share the same KV head</strong>.</p><pre>batch * seq_len * layers * KV_heads * head_dim * 2 (K,V) * dtype_bytes<br>1 * 4096 * 32 * 8 * 128 * 2 * 2 = 536870912 bytes</pre><p><strong>Which is equal to approx. 0.5 GB. So for 1 sequence we need 0.5GB for KV cache.</strong></p><p>Now, lets say batch_size=4, which means 4 sequences in one batch, then the KV cache size will be 0.5 * 4 = 2GB</p><h4>Activations</h4><p>During a forward pass through a Neural Network, it prodcues tensors at every layer, these tensors are called activations.</p><ul><li>During training, all the activations must be stored for back propagation so that gradients are computed. So, memory usage becomes huge, as here we need to store activations of all layers</li><li>But during inference, as we only perform forward pass, so activations are temporary, and can be discarded after computation. For example, while working on layer3 activations we do not need layer1 activation. So layer1 activations can be disacrded. hence the memory usage will be much smaller as compare to training.</li></ul><h4>CUDA Overhead</h4><p>The extra work the CPU must do before the GPU can actually start computing. CUDA overhead is everything that happened</p><ul><li>Python calling PyTorch</li><li>PyTorch preparing the kernel</li><li>CPU launching the kernel</li><li>Sending the command to the GPU</li><li>GPU scheduling threads</li></ul><p>It is usually consumer VRAM between <strong>300–500MB</strong></p><h4>Fragmentation</h4><p>KV cache memory is allocated as <strong>large contiguous blocks</strong>. Example:</p><pre>request 1 → allocate KV memory<br>request 2 → allocate KV memory<br>request 3 → allocate KV memory<br><br>When request 2 is finished, memory related to request 2 will be freed<br>[req1][empty][req3]</pre><p>Now, we get request4 whose length was larger than request2, than the freed memory of request 2 cannot be used for request3, and like this it causes fragmentation and wasted memory.</p><p>But this could be avoided by using vLLM. vLLM is a fast and easy-to-use library for LLM inference and serving. It supports dynamic KV caching, avoids fragmentation by using paged attention. We will discuss this in more details in the end</p><h4>Conclusion</h4><p>If we have to deploy Mistral 7B model, the amount of required VRAM will be</p><ul><li>14GB for weights</li><li>CUDA Overhead around 300–500MB</li><li>KV cahce will depend on batch size and context length. As we calculated per sequuence we need approx. 0.5GB. But in case of vLLM, it is different, vLLM reserve around 7GB for dynamic KV cache for Mistral.</li><li>So, the we would require a 21GB VRAM for Mistal 7B model</li></ul><h3>STEP2: Choose GPU</h3><p>Here I am using AWS for testing purposes, so I will evaluate GPU accroding to that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJYfFbk3eQJ5SjSdmPHRxQ.png" /></figure><h4>Conclusion</h4><p><strong>g5.xlarge has 24Gb RAM, enough for 7B FP16. So we will go with this.</strong></p><h3>STEP3: Setup testing environment (AWS+vLLM)</h3><h4>Deploy an EC2 instance on AWS with following requirement.</h4><ul><li><strong>Application and OS image</strong>: We will use AMI (Amazon Machine Image) for Deep Learning AMI GPU PyTorch. It includes NVIDIA drivers, CUDA, PyTorch, GPU runtime libraries</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyRSzWUMofBnyIgcpCjiJQ.png" /></figure><ul><li><strong>Instance</strong>: g5.xlarge</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYtwCx88bep5R7P2Mep8PQ.png" /></figure><ul><li><strong>Storage</strong>: 100 GB</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQy9gNKpbxeH3IMlmqDY6g.png" /></figure><ul><li><strong>Security group</strong>: Allow SSH(22) and HTTP(8000)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6CrNbZRP8cYyzNTQsybEg.png" /></figure><p>Once instance is deployed and running. Connect to instance</p><pre>ssh -i your-key.pem ec2-user@your-public-ip</pre><p>Check</p><pre>nvidia-smi</pre><p>You should see similar output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mzxL9CBMWO8ZDeTHDuEdg.png" /></figure><p>Memory-Usage: 0MiB / 23028MiB</p><p>This means no CUDA application has initialized the GPU yet. The NVIDIA driver is loaded, but <strong>no CUDA context has been created</strong>.</p><p>When a CUDA application starts:</p><ol><li>CUDA runtime initializes</li><li>CUDA context is created</li><li>Memory pools are allocated</li></ol><p>At that point you might see: 300–700 MB used</p><h4>Prepare Environment</h4><p>Prerequisite: vLLM requires Python ≥ 3.10</p><pre>dnf search python3<br>sudo dnf install python3.11 -y<br>sudo dnf install python3.11-devel gcc -y<br>python3 --version</pre><ol><li>Setup virtual environment</li></ol><pre>python3.11 -m venv vllm-venv<br>source vllm-venv/bin/activate<br>pip install --upgrade pip</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYpB4ekBO4BUYfyWO1Z1Nw.png" /></figure><p>2. Install vLLM</p><pre>pip install vllm</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5fjju1FTXmxT43J5QMPwg.png" /></figure><p>This installs:</p><ul><li>PyTorch</li><li>CUDA kernels</li><li>vLLM runtime</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*KN1KeFxFRLTkm9NeWgN2ng.png" /></figure><p>3. Start vLLM server</p><p>Before loading the model check gpu utilization</p><pre>python -m vllm.entrypoints.openai.api_server \<br>--model mistralai/Mistral-7B-Instruct-v0.2 \<br>--max-model-len 4096</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iScailn2kJCtreec9fwW1A.png" /></figure><p>Before vLLM server start, GPU utilization and VRAM utilization both will be zero. When we will start <strong>vLLM</strong>, memory will jump in stages.</p><p><strong>Step 1</strong> — CUDA context creation -&gt; 0 MB → ~300–500 MB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_09C1uxPnxcbz2vDgjzHg.png" /></figure><p><strong>Step 2</strong> — Model weights load -&gt; ~500 MB → ~14 GB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obMa1nGaIGxVD7DNgiV1UQ.png" /></figure><p><strong>Step 3</strong> — Runtime buffers -&gt; ~14 GB → ~21 GB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NL-q5u6BeeLt4bGDniayzQ.png" /></figure><p>Total used: ~21 GB</p><p>Model weights: 14 GiB</p><p>Runtime / buffers ≈ 21–14 = 7 GB</p><p>This includes:</p><ul><li><strong>KV cache allocation pool</strong>: vLLM pre-allocates KV cache space aggressively<strong>. </strong>So the memory you’re seeing <strong>already includes KV cache capacity</strong>. Instead of dynamically growing KV cache, vLLM uses something similar to Paged Attention KV cache pool. This means it allocates a <strong>large memory region upfront</strong> to avoid fragmentation and latency spikes. So 7–8GB runtime memory is <strong>not wasted</strong> — it’s <strong>future KV cache space</strong>.</li><li>CUDA runtime</li><li>attention buffers</li></ul><h3>Testing</h3><h4>Test1: Observation of GPU and VRAM utilization during inference. Single user sending a prompt of 13–15 tokens, with max_token as 100</h4><p>Send request from same instance</p><pre>curl http://localhost:8000/v1/chat/completions \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{<br>&quot;model&quot;: &quot;mistralai/Mistral-7B-Instruct-v0.2&quot;,<br>&quot;messages&quot;: [<br>{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain transformers simply&quot;}<br>],<br>&quot;max_tokens&quot;: 100<br>}&#39;</pre><p>During token generation GPU utilization reached ~100%.<br>This indicates the GPU compute units were fully active<br>while the model was generating tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81fekcp9yTL4KKkYeLWuIg.png" /></figure><p>Once LLM will respond, then GPU utilization will gain be 0% from 100% if no other CUDA application is running</p><h4>Test2: Observation of GPU and VRAM utilization during inferencef ro concurrent users (4 user)</h4><pre>for i in {1..5}; do<br>curl http://localhost:8000/v1/chat/completions \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{<br>&quot;model&quot;: &quot;mistralai/Mistral-7B-Instruct-v0.2&quot;,<br>&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Explain attention&quot;}],<br>&quot;max_tokens&quot;:200<br>}&#39; &amp;<br>done</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v571Objyj1z7AkjNZpk8jw.png" /></figure><h3>Why vLLM Works Better</h3><p>Let us also understand how vLLM helps with fragmentation, and optimized use of VRAM.</p><p>vLLM is a fast and easy-to-use library for LLM inference and serving.</p><p>It uses paged attention, which is a memory management technique that divides KV cache into small memory pages, allowing dynamic allocation and reuse to reduce fragmentation and increase serving efficiency.</p><h4><strong>Concept: Without optimization(without dynamic KV allocation):</strong></h4><p>KV cache memory is allocated as <strong>large contiguous blocks</strong>.</p><pre>  Example:<br>  request 1 → allocate KV memory<br>  request 2 → allocate KV memory<br>  request 3 → allocate KV memory</pre><p>When processing finished forrequest 2, request 2 memory slot will bve freed. But memory becomes fragmented, such as [req1][empty][req3]</p><p>New request might need <strong>large continuous memory</strong>, which cannot fit. This causes <strong>fragmentation and wasted memory</strong>.</p><h4><strong>Paged attention</strong> (conceptually similar to virtual memory paging)</h4><p>Instead of allocating huge contiguous KV blocks -&gt; Memory is divided into <strong>small pages. Example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*CMdAUNsoJsxxJfoGMKcWfQ.png" /></figure><p>Now, request uses multiple pages from the available pool. When a request finished these pools are freed, and ready to reused. So, suppose even if request3 is greater than request2 in terms on context length, it can still use freed pages of request2 and some other free pages from the pool for request3.</p><ul><li>It divides KV into smaller pages</li><li>Allocates dynamically</li><li>Reuses freed blocks, so avoid fragmentation</li><li>Packs memory efficiently</li><li>Improve memory management</li></ul><h3>Key Takeaways</h3><ul><li>Model weights dominate GPU memory</li><li>KV cache grows linearly with context length</li><li>CUDA runtime consumes ~300–700MB</li><li>vLLM reduces memory fragmentation using paged attention</li></ul><p><strong>LLM inference consists of two phases:</strong></p><ul><li><strong>Prefill phase: </strong>During the prefill phase the entire prompt is processed in parallel. For example, if the prompt “What is transformer?” contains 13 tokens, the model processes all 13 tokens in a single forward pass. For each token the model computes the Query (Q), Key (K), and Value (V)<br>vectors. Since this is the first pass, no KV cache is read yet. Because the model processes many tokens simultaneously using large<br>matrix multiplications, the prefill stage is highly compute intensive. However, the computed K and V vectors are stored into the KV cache<br>for future decoding steps.</li><li><strong>Decode phase: </strong>After the prompt has been processed, the model starts generating new tokens one at a time. For each new token, the model computes the query vector for the current token and attends to all previously generated tokens by reading their Keys and Values from the KV cache. Because every decoding step requires reading a large amount of data from the KV cache stored in GPU memory, decoding becomes limited by memory bandwidth rather than compute.</li></ul><p>This is why LLM serving systems focus heavily on optimizing KV cache<br>management and memory bandwidth utilization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea73c562f312" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From PowerPoint to Professional eBooks: Building an AI-Powered Converter with Advanced Features]]></title>
            <link>https://medium.com/@sabu.for.ai/from-powerpoint-to-professional-ebooks-building-an-ai-powered-converter-with-advanced-features-29b4a87edbdc?source=rss-8e33a2f4eafe------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b4a87edbdc</guid>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 16:07:45 GMT</pubDate>
            <atom:updated>2025-06-29T05:24:49.619Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built a comprehensive tool that transforms presentations into beautiful eBooks using Gemini AI, with smart image integration and flexible chapter organization</em></p><h3>The Problem: PowerPoint Presentations Don’t Make Good Reading Material</h3><p>We’ve all been there. You have a fantastic PowerPoint presentation packed with valuable content, but when you try to share it as reading material, it falls flat. Bullet points that work great for presentations become choppy and hard to follow in document form. Images are scattered randomly, and the narrative flow just doesn’t work for a reading experience.</p><p>After struggling with this problem repeatedly in my work, I decided to build a solution: <strong>an AI-powered PowerPoint to eBook converter</strong> that doesn’t just extract content — it intelligently transforms it into a professional, readable document.</p><p>This is the slides screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9WDXqLRORTM1DsunWeb4zg.png" /></figure><p>This is the snapshot of generated eBook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhzp8w3MYLW-Yp-7esT3-Q.png" /></figure><h3>What Makes This Different?</h3><p>Most existing solutions simply dump slide content into a document. My approach is fundamentally different, focusing on creating a truly polished final product in both PDF and DOCX formats.</p><h3>AI-Powered Content Enhancement</h3><p>Instead of just copying text, the tool uses Google’s Gemini 2.5 flash AI to:</p><ul><li>Expand sparse bullet points into full, coherent paragraphs.</li><li>Add context and explanations to create a smooth narrative.</li><li>Maintain a consistent, professional tone throughout the entire document.</li><li>Intelligently structure the content with proper headings for optimal reading flow.</li></ul><h3>Smart Image Integration</h3><p>Rather than dumping all images at the end of a chapter, the system performs a more sophisticated integration:</p><ul><li>It extracts images while preserving their original slide context.</li><li>It places images <em>immediately after</em> their relevant slide heading within a chapter.</li><li>It uses the actual slide titles to generate meaningful, numbered figure captions (e.g., “Figure 3.1: Q3 Marketing Strategy”).</li><li>It even attempts to distinguish between regular images and diagrams for more accurate captioning.</li></ul><h3>Flexible Chapter Organization</h3><p>Every presentation is different. That’s why I built a user-friendly interface that offers three distinct organization methods:</p><ul><li><strong>Automatic Grouping</strong>: Group 2–20 slides per chapter using a simple slider.</li><li><strong>Custom Ranges</strong>: Define specific slide ranges (e.g., “1–5, 6–12, 13–18”) for topic-based chapters.</li><li><strong>One Slide Per Chapter</strong>: Achieve maximum granularity, perfect for detailed study guides.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkvozUVxN6akEbTFLooSRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRtcNwqrEeNVkNVVVDMmfQ.png" /></figure><h3>The Technical Journey</h3><p>Building this tool was a step-by-step process of adding layers of intelligence.</p><h3>Starting Simple: Basic Extraction</h3><p>The journey began with the fundamentals: extracting all text and image data from a .pptx file using the python-pptx library. The key was to store everything in a structured format, linking content and images back to their original slide number.</p><pre>def extract_ppt_content(self, ppt_file):<br>    presentation = Presentation(ppt_file)<br>    slides_content = []<br>    <br>    for i, slide in enumerate(presentation.slides):<br>        slide_content = {<br>            &#39;slide_number&#39;: i + 1,<br>            &#39;title&#39;: &#39;&#39;,<br>            &#39;content&#39;: [],<br>            &#39;images&#39;: []<br>        }<br>        <br>        for shape in slide.shapes:<br>            if hasattr(shape, &quot;text&quot;) and shape.text.strip():<br>                # Extract and structure text content<br>                ...<br>            elif shape.shape_type == MSO_SHAPE_TYPE.PICTURE:<br>                # Extract image bytes and associate with the slide number<br>                image_info = {<br>                    &#39;data&#39;: shape.image.blob,<br>                    &#39;slide_number&#39;: i + 1,<br>                    &#39;slide_title&#39;: slide_content[&#39;title&#39;] # Preserve context for captions<br>                }<br>                slide_content[&#39;images&#39;].append(image_info)</pre><h3>Adding Intelligence: Prompt Engineering with Gemini</h3><p>The breakthrough came from integrating Google’s Gemini API. The magic is in the prompt. I engineered a detailed prompt that instructs the AI to act as a professional content writer, transforming the raw slide data into a polished chapter.</p><pre>def enhance_content_with_gemini(self, slide_content, chapter_number=None):<br>    prompt = f&quot;&quot;&quot;<br>    You are a professional content writer creating an eBook chapter.<br>    <br>    Given this slide content for Chapter {chapter_number}:<br>    Title: {slide_content[&#39;title&#39;]}<br>    Content: {slide_content[&#39;content&#39;]}<br>    <br>    IMPORTANT INSTRUCTIONS:<br>    1. Start directly with the content - NO introductory phrases like &quot;Here is a chapter...&quot;<br>    2. Use &quot;# Chapter {chapter_number}: [Title]&quot; as the main heading.<br>    3. Expand on key points with detailed explanations in full paragraphs.<br>    4. Maintain a professional tone suitable for an eBook.<br>    5. Format the response as a cohesive chapter section that flows well.<br>    &quot;&quot;&quot;<br>    <br>    response = self.model.generate_content(prompt)<br>    return self._clean_ai_response(response.text) # Clean up the AI&#39;s output</pre><h3>The Image Integration Challenge</h3><p>This was the biggest technical challenge. To avoid a messy “image dump,” the solution required a multi-step process:</p><ol><li><strong>Preserve Context:</strong> During extraction, store images with their original slide number and title.</li><li><strong>Group by Slide:</strong> When building a chapter that combines multiple slides, group all extracted images by their source slide number.</li><li><strong>Inject and Place:</strong> As the AI-generated text is parsed, split it by slide sections. After writing a slide’s heading and text, inject the corresponding images for that specific slide.</li><li><strong>Caption Correctly:</strong> Use the preserved slide title to generate a meaningful and accurate caption for each image.</li></ol><p>This logic ensures that an image from slide 10 appears right after the content for slide 10, even if it’s part of a larger chapter.</p><pre>def _add_images_to_story_with_title(self, story, images, chapter_num, slide_number, slide_title):<br>    for img_idx, image_data in enumerate(images):<br>        # Process and resize the image for the PDF<br>        rl_image = RLImage(io.BytesIO(image_data[&#39;data&#39;]), width=new_width, height=new_height)<br>        story.append(rl_image)<br>        <br>        # Create a meaningful, numbered caption using the slide title<br>        image_type = image_data.get(&#39;type&#39;, &#39;image&#39;)<br>        if image_type == &#39;diagram&#39;:<br>            caption = f&quot;Diagram {chapter_num}.{img_idx + 1}: {slide_title}&quot;<br>        else:<br>            caption = f&quot;Figure {chapter_num}.{img_idx + 1}: {slide_title}&quot;<br>        <br>        story.append(Paragraph(caption, caption_style))</pre><h3>Key Features That Make It Professional</h3><p>The difference between a simple script and a professional tool lies in the details that enhance user experience and output quality.</p><h3>1. Robust Debugging and Logging</h3><p>I built a dynamic logging system that defaults to a clean INFO level but can be switched to a verbose DEBUG mode with a simple checkbox in the UI. This was invaluable for troubleshooting complex documents without cluttering the console for regular users.</p><pre>def set_logging_level(debug_mode=False):<br>    level = logging.DEBUG if debug_mode else logging.INFO<br>    logging.getLogger().setLevel(level)<br>    for handler in logging.getLogger().handlers:<br>        handler.setLevel(level)</pre><h3>2. Dynamic PDF Footers</h3><p>A professional eBook needs proper page footers. I created a custom ChapterMarker class for ReportLab — a tiny, invisible element added to the story. When the PDF generator encounters this marker, it updates a “current chapter” variable in the document, allowing the footer on each page to dynamically display the correct chapter number.</p><pre>class ChapterMarker:<br>    def __init__(self, chapter_num):<br>        self.chapter_num = chapter_num<br>    <br>    def drawOn(self, canvas, x, y, _sW=0):<br>        # This method is called by ReportLab during rendering<br>        if hasattr(canvas._doc, &#39;set_current_chapter&#39;):<br>            canvas._doc.set_current_chapter(self.chapter_num)</pre><h3>3. AI Response Cleaning</h3><p>AI models can be chatty, often adding conversational filler like “Of course, here is the chapter…”. I wrote a cleanup function that programmatically removes these unwanted phrases, ensuring the final text is clean and ready for the eBook.</p><pre>def _clean_ai_response(self, response_text):<br>    unwanted_phrases = [<br>        &quot;Of course. Here is a comprehensive eBook chapter&quot;,<br>        &quot;Here is a comprehensive eBook chapter&quot;,<br>        # ... more patterns<br>    ]<br>    cleaned_text = response_text.strip()<br>    for phrase in unwanted_phrases:<br>        if cleaned_text.lower().startswith(phrase.lower()):<br>            cleaned_text = cleaned_text[len(phrase):].strip()<br>    return cleaned_text</pre><h3>4. Flexible Chapter Organization UI</h3><p>A great feature is useless if it’s hard to configure. The Streamlit interface provides clear radio buttons, a slider, and a text area to handle all chapter organization scenarios, giving the user complete control with immediate visual feedback.</p><h3>Real-World Impact</h3><p>I’ve tested the tool with presentations of all sizes, and the flexible settings allow it to adapt perfectly:</p><ul><li><strong>Small Presentations (10–20 slides):</strong> Using the “One slide per chapter” setting turns a short deck into a detailed study guide, where each slide’s concept is fully explained.</li><li><strong>Medium Presentations (30–50 slides):</strong> “Automatic grouping” with 3–5 slides per chapter creates a professional eBook with a logical flow, perfect for a business whitepaper or training manual.</li><li><strong>Large Presentations (100+ slides):</strong> A 150-slide corporate training deck was flawlessly organized using “Custom ranges” to group modules into meaningful chapter divisions, creating a comprehensive, easy-to-navigate reference book.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quNqYMU7S1DsTlecTGIXKw.png" /></figure><h3>Lessons Learned</h3><ol><li><strong>User Experience is Everything:</strong> The Streamlit interface was just as important as the backend logic. Clear options, real-time progress indicators, and immediate download buttons make the tool a pleasure to use.</li><li><strong>Error Handling is Non-Negotiable:</strong> Between file uploads, external API calls, and complex document generation, things can go wrong. I implemented robust try-except blocks, graceful fallbacks (if the AI fails, it uses the raw text), and clear error messages to make the tool resilient.</li><li><strong>Prompt Engineering is a Superpower:</strong> The quality of the AI output is directly proportional to the quality of the prompt. Being highly specific, providing examples, and clearly stating “do’s” and “don’ts” in the prompt instructions made all the difference.</li></ol><h3>The Technology Stack</h3><ul><li><strong>Frontend</strong>: Streamlit for the interactive web interface.</li><li><strong>AI</strong>: Google Gemini API for content enhancement.</li><li><strong>Document Processing</strong>: python-pptx for PowerPoint, reportlab for PDF, and python-docx for Word.</li><li><strong>Image Processing</strong>: Pillow for image manipulation and resizing.</li><li><strong>Architecture</strong>: A modular, object-oriented design encapsulated in a single PPTToEBookConverter class.</li></ul><h3>Future Enhancements</h3><p>The roadmap is exciting and includes:</p><ul><li><strong>Multi-language support</strong> for international presentations.</li><li><strong>Batch processing</strong> to convert multiple files at once.</li><li><strong>Cloud integration</strong> for direct uploads from Google Drive or OneDrive.</li><li><strong>Customizable templates</strong> for different eBook styles.</li></ul><h3>Try It Yourself</h3><p>The complete source code is available on GitHub with comprehensive documentation. I invite you to clone it, experiment, and see the magic for yourself.</p><p><strong>Repository Link:</strong> <a href="https://github.com/saurabh922/PresentationToEbook.git">https://github.com/saurabh922/PresentationToEbook.git</a></p><p>Installation is straightforward:</p><pre># Clone the repository<br>git clone https://github.com/saurabh922/PresentationToEbook.git<br>cd PresentationToEbook<br><br># Install dependencies<br>pip install -r requirements.txt<br><br># Run the app<br>streamlit run app.py</pre><h3>Conclusion</h3><p>Building this PowerPoint to eBook converter taught me that the gap between a simple script and a professional tool is filled with thoughtful details: context-aware AI, a flexible user interface, and a focus on polished, high-quality output. It has transformed how I repurpose presentation content, turning static slides into engaging, readable eBooks.</p><p>Whether you’re an educator, a trainer, or a professional sharing knowledge, this approach can significantly improve how your content is consumed and retained.</p><h3>Connect With Me</h3><ul><li><strong>GitHub:</strong> <a href="https://github.com/saurabh922">https://github.com/saurabh922</a></li><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/saurabh-arora-0b7b0322/">https://www.linkedin.com/in/saurabh-arora-0b7b0322/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b4a87edbdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>