<?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 Asheesh Goja on Medium]]></title>
        <description><![CDATA[Stories by Asheesh Goja on Medium]]></description>
        <link>https://medium.com/@asheesh.goja?source=rss-8b819656b4a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UF_plnN-7858EFq8j7dpqQ.png</url>
            <title>Stories by Asheesh Goja on Medium</title>
            <link>https://medium.com/@asheesh.goja?source=rss-8b819656b4a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:08:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asheesh.goja/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[Prefill is Compute, Decode is Bandwidth: The Architectural Case for Disaggregated LLM Inference]]></title>
            <link>https://medium.com/@asheesh.goja/prefill-is-compute-decode-is-bandwidth-the-architectural-case-for-disaggregated-llm-inference-92c8b36d1a88?source=rss-8b819656b4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/92c8b36d1a88</guid>
            <dc:creator><![CDATA[Asheesh Goja]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 21:26:08 GMT</pubDate>
            <atom:updated>2026-03-23T21:26:08.003Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How the Roofline Model and the Von Neumann Bottleneck Explain Why NVIDIA, Google, and AWS Are Redesigning Inference From the Silicon Up</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkE1TngtNy4uYlIeRE7ZMw.jpeg" /></figure><p>GTC 2026, <a href="https://www.youtube.com/live/jw_o0xr8MWU?si=cCFLOOevIt430Iq0&amp;t=5310">Jensen Huang stood on the stage</a> and described an inference architecture that delivers, per NVIDIA’s claims, 35x higher TPS/MW at interactive latency, and a path to 700 million TPS in a single gigawatt factory. This isn’t an incremental GPU refresh. The Vera Rubin platform splits inference across two complementary engine types: Rubin GPUs handle compute-heavy prefill and KV-cache-bound attention during decode, while Groq 3 LPU-based LPX racks (SRAM-based, deterministic dataflow processors delivering 150 TB/s of on-chip bandwidth per LPU) handle the latency-sensitive FFN and MoE weight streaming. Dynamo orchestrates the split. Spectrum-X ties the racks together.</p><p>Whether those numbers hold across real-world workload diversity is a separate question, but the <em>architecture</em> behind them reflects something far more significant than a benchmark result. <a href="https://medium.com/p/ce397041dec2#e696">The roofline model</a>, a framework that maps achievable performance against arithmetic intensity, has long predicted that no single chip can simultaneously optimize for the compute-bound prefill phase and the bandwidth-bound decode phase of transformer inference. The prefill/decode split is the first-order consequence. But decode itself contains operations with incompatible hardware affinities (KV-cache-bound attention and weight-streaming FFN) and splitting those onto purpose-matched silicon is the second-order consequence. NVIDIA’s three-pool architecture is the first production-scale system that acts on both.</p><p>A year ago, I traced this prediction to its roots in <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-1-34ef63d95b6c">a two-part analysis</a> of the memory wall, the Von Neumann bottleneck, and the SRAM-DRAM tradeoff. The conclusion was that the path forward demands not just software optimization but fundamentally new compute architectures: dataflow execution models, specialized memory hierarchies, and domain-specific accelerators that bring compute closer to data. What’s unfolding now across NVIDIA, AWS, Google, and Cerebras is exactly that.</p><p>This article connects those theoretical foundations to the architectures now being built at scale, starting with the roofline model and the prefill/decode divergence that makes disaggregation inevitable, then explaining why software alone cannot close the gap, and finally mapping the industry’s response: homogeneous and heterogeneous disaggregation architectures, with NVIDIA’s three-pool Vera Rubin + Groq LPX system representing the most comprehensive strategy in the space.</p><h3>The Theoretical Foundation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p_bN0SgfqIr5vS7j" /></figure><h3>The Roofline Model and the Two Regimes of Transformer Inference</h3><p>The <a href="https://medium.com/p/ce397041dec2#e696">Berkeley Roofline Model</a> provides the analytical framework that makes the disaggregation thesis precise. It maps achievable performance (FLOPS) against arithmetic intensity (FLOPs/byte of data moved from memory), producing a characteristic “roof” shape bounded by two ceilings: the memory bandwidth limit (the sloped line at low arithmetic intensity) and the peak compute limit (the horizontal line at high arithmetic intensity).</p><p>Every accelerator has a ridge point, the arithmetic intensity at which the workload transitions from memory-bound to compute-bound. This ridge point is determined by the hardware’s ratio of peak compute to peak memory bandwidth. For an NVIDIA H100 SXM, using the dense FP16 Tensor Core peak (the relevant baseline for LLM workloads, since standard inference does not exploit 2:4 structured sparsity):</p><p><em>Dense FP16 Tensor Core: ~990 TFLOPS / HBM3 bandwidth: ~3.35 TB/s ≈ ~295 FLOPs/byte</em></p><p>(NVIDIA’s headline ~1,979 TFLOPS figure includes 2:4 structured sparsity, which effectively doubles the dense throughput for supported workloads. The ~990 TFLOPS dense figure is derived from the H100 SXM’s 132 SMs, each delivering 4,096 FP16 FLOPs/clock at the Tensor Core boost frequency of ~1,830 MHz.)</p><p>Any operation with arithmetic intensity below ~295 FLOPs/byte is bandwidth-bound and underutilizes compute. Any operation above it is compute-bound and underutilizes bandwidth. The critical insight: prefill and decode typically occupy very different positions on this roofline. Prefill generally operates in the compute-bound regime; decode, particularly at low batch sizes, falls deep into the bandwidth-bound region.</p><p>(Note: FP16 is used here as the analytical baseline for consistency with how these architectures are typically characterized. In practice, production inference has increasingly moved to FP8 quantization, at which the H100’s dense compute doubles to ~1,979 TFLOPS, pushing the ridge point to ~590 FLOPs/byte. This makes the roofline gap for decode <em>even wider</em>, further strengthening the disaggregation thesis.)</p><p><a href="https://medium.com/@asheesh.goja/34ef63d95b6c#5159">Prefill</a> processes the entire input prompt in a single forward pass. All tokens are processed in parallel through attention and FFN layers. The weight matrices are reused across many tokens simultaneously, producing high data reuse and high arithmetic intensity. Large batched GEMMs dominate. The workload sits at or near the compute roof, and the GPU’s Tensor Cores are well-utilized.</p><p><a href="https://medium.com/@asheesh.goja/34ef63d95b6c#5159">Decode</a> is autoregressive token generation. Each step reads the full model weights and the accumulated KV-cache, but performs only a single token’s worth of compute. The ratio of FLOPs to bytes moved collapses. Arithmetic intensity drops by orders of magnitude relative to prefill. The workload falls deep into the bandwidth-bound region of the roofline, and the GPU’s massive compute capacity sits idle, starved for data.</p><p>In practice, this means decode performance tracks the bandwidth slope of the roofline rather than approaching the horizontal compute ceiling. The GPU may be achieving high utilization of its <em>memory bandwidth</em>, but the compute units remain substantially underutilized because the workload simply doesn’t generate enough FLOPs per byte. The hardware is working hard on data movement; it’s the fundamental ratio of compute to memory access that limits performance.</p><p>This analysis assumes decode is dominated by pure GEMM operations (matrix-vector products against model weights and KV-cache entries). In practice, each decode step also executes non-linear operations (softmax, GeLU, LayerNorm) whose reduction-heavy memory access patterns, thread synchronization overhead, and low arithmetic intensity push actual GPU utilization below even what the bandwidth ceiling would predict. These operations are only partially amenable to fusion with the surrounding GEMMs (FlashAttention fuses softmax with attention, and GeLU fusion into FFN kernels is standard practice, but full fusion across all non-linear operations remains elusive), introducing residual kernel launch overhead and idle cycles that widen the gap between decode’s real-world throughput and the theoretical bandwidth roof. The roofline analysis in the sections that follow therefore represents an optimistic bound; the actual case for disaggregation is stronger than the GEMM-only picture suggests.</p><h3>Attention vs. FFN: Distinct Complexity Profiles That Deepen the Roofline Divide</h3><p>The prefill/decode distinction captures the macro-level roofline divergence, but it obscures a deeper structural asymmetry <em>within</em> each transformer layer, particularly during decode, that has direct architectural consequences. The two dominant computational primitives inside every transformer block (the self-attention mechanism and the <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#acec">feed-forward network</a>, or FFN) exhibit fundamentally different time complexity, space complexity, and memory access profiles. Understanding this distinction is essential for two reasons: it explains why decode’s bandwidth-bound character is not monolithic, and it predicts that even after disaggregating prefill from decode, the decode phase itself contains operations with incompatible hardware affinities. This is a prediction that NVIDIA’s Attention-FFN Disaggregation (AFD) architecture, later in this article, now validates in silicon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*27fCd6f55pknKvp0" /></figure><p>Self-attention computes pairwise interactions across all tokens in the sequence. As analyzed in detail in <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-1-34ef63d95b6c">Part 1 of my earlier blog series</a>, the time complexity of self-attention during the prefill phase is O(n²·d + n·d²). During autoregressive decode with a KV cache, however, the per-token complexity becomes O(n·d + d²), where <em>n</em> is the current sequence length and <em>d</em> is the embedding dimension. The n²·d term arises from computing the dot-product attention scores between all token pairs (the QKᵀ matrix multiplication produces an <em>n × n</em> attention matrix for each head) while the n·d² term accounts for the linear projections of the input into queries, keys, and values. The space complexity is O(n² + n·d): the <em>n²</em> term reflects the full attention score matrix (though FlashAttention-style tiling avoids materializing it in HBM), and <em>n·d</em> reflects the KV-cache that accumulates across decode steps. During decode, the attention operation’s <em>data footprint is dominated by the KV-cache</em>, the accumulated keys and values from all prior tokens, which grows linearly with context length and must be read in its entirety for every generated token. This makes decode-phase attention a <em>capacity-and-bandwidth</em> problem: the hardware needs large memory to hold the KV-cache and high bandwidth to stream it through the attention computation each step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gD7Hg9vvQwNL2stQ" /></figure><p>The feed-forward network, by contrast, operates on each token <em>independently</em>; there are no cross-token interactions. Each token’s embedding is projected up to a higher-dimensional space (typically 4×d), passed through a non-linearity (GeLU, SwiGLU), and projected back down. The time complexity per token is O(d²), dominated by two large matrix multiplications against the FFN weight matrices, and total per-layer cost across all tokens is O(n·d²). The space complexity for the FFN is dominated by the weight matrices themselves: O(d²) parameters per layer, which in modern architectures constitute roughly two-thirds of total model parameters. During decode, the FFN’s memory access pattern is <em>weight-dominated and entirely predictable</em>: each token streams the same static weight matrices through the compute units, performing a fixed number of FLOPs per byte of weight data read. There is no data-dependent indexing, no variable-length state to traverse; the access pattern is identical regardless of sequence position or context length.</p><p>These complexity profiles produce starkly different roofline signatures during decode:</p><ul><li><a href="https://medium.com/@asheesh.goja/34ef63d95b6c#377c">Attention</a> during decode is a matrix-vector product of the new query against the full KV-cache. The arithmetic intensity is fixed at ~1 FLOP/byte (one multiply-accumulate per KV element read), regardless of context length. But the <em>total bytes read</em> scale linearly with context: at 100K tokens with GQA and FP16 KV, a single attention step may stream 10+ GB of KV-cache. The hardware requirement is therefore <em>large memory capacity</em> to hold the KV state and <em>high aggregate bandwidth</em> to read it within the latency budget. GPU HBM, with its combination of high capacity (288 GB on Rubin) and high bandwidth (~22 TB/s per package), is architecturally well-matched to this profile. The KV-cache access pattern, while predictable in structure, is <em>context-length-dependent in volume</em>: more context means proportionally more data movement.</li><li><a href="https://medium.com/@asheesh.goja/34ef63d95b6c#acec">FFN</a> during decode is also a matrix-vector product (input activation × weight matrix), with similarly low arithmetic intensity at batch size 1, ~1–2 FLOPs/byte depending on precision. But the critical difference is in <em>what</em> is being streamed: FFN reads <em>static model weights</em>, not accumulated per-request state. The weight matrices are identical across all requests and all tokens. This makes FFN decode an ideal target for hardware with <em>massive on-chip memory bandwidth and deterministic dataflow</em>. The weights can be partitioned across on-chip SRAM, eliminating HBM access entirely. Hardware that provides SRAM-speed bandwidth (tens to hundreds of TB/s) with compiler-scheduled, deterministic execution can serve FFN weight reads at dramatically lower latency per byte than any DRAM-based system, even one with HBM4.</li></ul><p>The asymmetry extends to how each operation scales with emerging workload trends. As context windows grow from 32K toward 1M+ tokens, attention’s KV-cache footprint grows proportionally, demanding more memory <em>capacity</em> on the decode hardware. But the FFN weight footprint is <em>constant</em> regardless of context length. Conversely, as models move to MoE architectures, the FFN layer’s effective weight footprint <em>per token</em> may decrease (only top-k experts activated), but the total weight set that must be resident increases dramatically. The routing decision is dynamic, determined at runtime by each token’s hidden state, so the expert activation pattern is not statically known at compile time. SRAM-based architectures mitigate this not through scheduling predictability but through bandwidth abundance: keeping all experts resident on-chip and serving whichever subset the router selects at SRAM speed, rather than incurring the latency penalty of fetching dynamically-selected experts from DRAM.</p><p>This analysis reveals that the prefill/decode boundary, while critical, is only the <em>first-order</em> disaggregation opportunity. The <em>second-order</em> opportunity lies within decode itself: separating the KV-cache-bound attention computation (which demands large HBM capacity and bandwidth) from the weight-streaming FFN computation (which demands raw memory bandwidth at minimal latency, ideally from on-chip SRAM). These are not merely different points on the same roofline; they are workloads with fundamentally different memory hierarchy requirements. Any architecture that serves both from the same memory system is necessarily making a compromise, over-provisioning capacity for FFN or under-provisioning bandwidth for attention, or both. The theoretical case for splitting them onto purpose-matched hardware is, from a roofline perspective, at least as strong as the case for splitting prefill from decode. This case is strongest for MoE architectures, where expert parallelism already requires all-to-all communication patterns that can absorb the activation transfer overhead, making AFD nearly free at the network level. For dense models, the per-layer activation transfer cost is fully additive, and AFD remains an active research frontier. The industry’s convergence on MoE for frontier models makes this distinction increasingly academic for production workloads, but it bounds the generality of the argument. This is a thesis we will see realized in NVIDIA’s three-pool Vera Rubin + Groq LPX architecture later in this article.</p><p>But why do these mismatches exist at all? Why can’t a single memory system serve both the KV-cache’s capacity-and-bandwidth demands and the FFN’s latency-sensitive weight-streaming profile? The answer is not a quirk of current GPU design; it is an inherited constraint from the foundational architecture of digital computing itself.</p><h3>The Von Neumann Bottleneck: Why This Gap Exists</h3><p>Every accelerator in this article (GPU, TPU, LPU, and wafer-scale engine) descends from the Von Neumann architecture’s fundamental separation of compute and memory. That separation forces a choice: memory can be fast and small (SRAM, close to compute) or large and slow (DRAM, off-chip). It cannot be both. This is the architectural root of every roofline mismatch described above. Attention during decode needs large memory to hold the KV-cache and high bandwidth to stream it, a profile that maps to HBM, which is DRAM-based, high-capacity, and high-bandwidth but fundamentally latency-limited by capacitor physics. FFN during decode needs raw speed to stream static weights with minimal latency, a profile that maps to SRAM, which is fast and deterministic but capacity-limited to tens of megabytes per chip at viable cost. No single memory technology serves both profiles, because the <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-2-ce397041dec2#2d1d">SRAM-DRAM</a> tradeoff is not an engineering shortcoming; it is a direct consequence of the physics of two different storage mechanisms.</p><p>Despite decades of innovation, the gap between processor performance and memory performance has widened by orders of magnitude: compute capabilities have scaled far more aggressively than memory bandwidth or latency. More critically, accessing data from off-chip DRAM consumes 100–200x more energy than performing a floating-point operation.</p><p>GPUs mitigate this through <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-2-ce397041dec2#7840">hierarchical memory</a>: registers (near-instant access), L1/L2 SRAM caches (1–10 cycles), and HBM (high capacity, high bandwidth, but fundamentally limited by DRAM physics). HBM’s 3D die stacking and wide buses (1024-bit per stack through HBM3e, doubling to 2048-bit in HBM4) represent the state of the art in DRAM bandwidth, but the underlying 1T1C (one transistor, one capacitor) cell architecture still requires <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-2-ce397041dec2#998d">refresh cycles, still exhibits charge leakage</a>, and still cannot match SRAM’s access latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*khk5437i1xwWyQqa" /></figure><p>The <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-2-ce397041dec2#2d1d">SRAM-DRAM</a> tradeoff is the hardware designer’s dilemma: SRAM’s 6-transistor bistable latch provides 1–10 cycle access with no refresh overhead, but at roughly two orders of magnitude higher cost per bit. This gap is driven by the combination of SRAM’s ~6x larger cell area (6 transistors vs. 1T1C) and its fabrication on expensive leading-edge logic process nodes rather than dedicated memory processes. This makes on-chip SRAM caches fundamentally capacity-limited (tens of megabytes on current GPUs). HBM provides the density needed for large model weights (80–288 GB per device), but at bandwidth that, while impressive in absolute terms, cannot saturate compute for low-arithmetic-intensity workloads.</p><p>This is the memory wall, and it defines the ceiling for what any single architecture can achieve when a workload’s compute-to-memory ratio doesn’t match the hardware’s ridge point.</p><h3>Why Software Alone Cannot Close the Gap</h3><p>Given the theoretical picture, the natural question is: can software co-design close the gap without fundamentally new hardware?</p><p>The inference optimization community has produced remarkable software techniques over the past two years. FlashAttention reduces memory traffic for attention by fusing operations and exploiting the SRAM-HBM hierarchy. Paged attention (vLLM) manages KV-cache memory more efficiently. Continuous batching amortizes weight reads across requests. Speculative decoding reduces the number of serial autoregressive steps. KV-cache quantization and compression reduce the bytes moved per decode step.</p><p>Every one of these techniques is, at its core, a roofline-aware optimization: they either increase effective arithmetic intensity or reduce total memory traffic. And they deliver material improvements. But they face a structural ceiling that limits how far they can go on fixed hardware.</p><p>The core issue is that decode’s arithmetic intensity is structurally low at the batch sizes relevant to latency-sensitive workloads, and as established earlier, this is true of both dominant operations within each decode step. Attention during decode yields a fixed ~1 FLOP/byte regardless of context length (more context means proportionally more FLOPs and more bytes read; the ratio stays constant). FFN weight streaming at batch size 1 is similarly bandwidth-bound, with each step streaming roughly two-thirds of the model’s total parameters for a single token’s worth of computation. Both operations sit far below the ridge point of any current accelerator: the H100’s ~295 FLOPs/byte at dense FP16, or ~590 FLOPs/byte at FP8. What shifts with context length is the proportion of decode time consumed by each: at short-to-moderate contexts, FFN weight transfer dominates; at long contexts, KV-cache bandwidth eclipses it. But the decode phase as a whole remains firmly bandwidth-limited across all practical workloads, and increasingly so as contexts grow. No kernel fusion, memory layout optimization, or scheduling trick can fundamentally eliminate this mismatch for the weight-dominated operations at low batch sizes, though they can meaningfully reduce its severity. The primary software lever is batching: serving multiple requests simultaneously amortizes the weight reads across more tokens, effectively increasing arithmetic intensity. Continuous batching (iteration-level scheduling, as implemented in vLLM, SGLang, and TensorRT-LLM) has made this far more effective than static batching, enabling production decode to typically operate at effective batch sizes of 32–256+ while maintaining per-request latency within SLO. This raises FFN arithmetic intensity meaningfully above the batch-size-1 baseline of ~1–2 FLOPs/byte. But even at these batch sizes, decode arithmetic intensity remains well below the ridge point of current accelerators (~295 FLOPs/byte on H100 at FP16, ~590 at FP8), and the gap widens further on next-generation hardware like Rubin. Moreover, for latency-sensitive agentic workloads (coding assistants, interactive reasoning, voice agents), the maximum feasible batch size is constrained by both the application SLA and the KV-cache memory footprint scaling linearly with concurrent requests, keeping effective arithmetic intensity far from the compute roof.</p><p>Speculative decoding is clever: use a small draft model to predict multiple tokens, then verify in parallel with the large model. But the draft model itself is bandwidth-bound during its own decode, and the verification pass doesn’t fully eliminate the serial decode bottleneck.</p><p>The realization that has crystallized across the industry: for latency-sensitive workloads, you need hardware where the roofline ridge point better matches the workload’s arithmetic intensity. And since prefill and decode have very different arithmetic intensity profiles, particularly at the low batch sizes demanded by real-time applications, routing them to different hardware architectures yields substantial efficiency gains. This is the thesis of disaggregated inference, and it’s now being implemented at scale.</p><h3>The Industry Is Building Exactly This</h3><p>The question is no longer whether to disaggregate, but how, and the industry has split into two camps. Homogeneous disaggregation uses the same accelerator architecture for both phases, with software-defined scheduling dynamically allocating chip pools to prefill or decode based on real-time demand, trading per-phase hardware optimization for operational simplicity and flexible resource allocation. Heterogeneous disaggregation pairs fundamentally different chip architectures, each purpose-built for its phase’s compute or bandwidth regime, achieving tighter roofline matching at the cost of cross-architecture KV-cache transfer overhead and more complex orchestration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JKwjPRbzzRXiOwI2" /></figure><h3>Homogeneous Architectures</h3><h3>NVIDIA Vera Rubin NVL72</h3><p>The Vera Rubin NVL72 rack represents NVIDIA’s homogeneous disaggregation baseline: 72 Rubin GPU packages interconnected by NVLink 6.0 with NVSwitch 6.0 providing 3.6 TB/s of aggregate bidirectional bandwidth per GPU in a full all-to-all topology across the rack. Each Rubin GPU is a 336-billion-transistor dual-die design integrating 224 Streaming Multiprocessors equipped with enhanced fifth-generation Tensor Cores, delivering 50 PFLOPS of NVFP4 inference compute (via the third-generation Transformer Engine’s hardware-accelerated adaptive compression) and 35 PFLOPS of NVFP4 training compute per package. On the memory side, each GPU incorporates up to 288 GB of HBM4 with a doubled interface width compared to HBM3e, delivering up to 22 TB/s of aggregate memory bandwidth per GPU, nearly tripling Blackwell’s 8 TB/s. Each Vera Rubin superchip pairs two Rubin GPUs with one Vera CPU (88 custom-designed Olympus cores, 1.5 TB LPDDR5X at 1.2 TB/s) via second-generation NVLink-C2C at 1.8 TB/s of coherent bidirectional bandwidth, creating a unified CPU-GPU address space that enables techniques like KV-cache offload to LPDDR5X without explicit data movement. At the rack level, NVLink 6 switch trays integrate SHARP in-network compute delivering 14.4 TFLOPS of FP8 per tray, offloading collective reductions directly inside the fabric, a capability that accelerates the all-to-all communication patterns critical to MoE expert dispatch during both prefill and decode phases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*FwAS2IvsBCyJ7KiZ" /></figure><p>In this configuration, Dynamo routes prefill to a pool of Rubin GPUs that process the full input context in parallel, generating the KV-cache, while decode runs on a separate Rubin GPU pool where HBM4’s massive bandwidth serves the autoregressive token generation loop. Because the KV-cache handoff between prefill and decode pools occurs entirely within the NVLink 6 domain, with its 260 TB/s of aggregate rack-level bandwidth, the transfer overhead is minimal compared to cross-architecture approaches that rely on scale-out fabrics like EFA or InfiniBand. NVIDIA has further extended this disaggregation philosophy with the Vera Rubin NVL144 CPX rack, which pairs 144 purpose-built Rubin CPX GPUs (30 PFLOPS NVFP4, 128 GB GDDR7, with 3x attention acceleration over GB300 NVL72) for the compute-bound context phase alongside 144 Rubin GPUs and 36 Vera CPUs for generation, delivering 8 exaFLOPS of NVFP4 in a single rack.</p><p>The roofline tradeoff mirrors the fundamental limitation of homogeneous approaches: because the same Rubin GPU architecture serves both phases, there is no hardware-level ridge point optimization per phase. Rubin’s NVFP4 ridge point (peak compute / HBM bandwidth, ~50 PFLOPS / 22 TB/s, roughly 2,273 FLOPs/byte) is well-matched for compute-dense prefill but vastly over-provisioned for decode, where per-token arithmetic intensity at low batch sizes falls to ~1–2 FLOPs/byte. NVIDIA’s bet is that the enormous NVLink-connected domain compensates: allocate more GPUs to the decode pool, parallelizing the bandwidth-bound workload across more HBM4 stacks and aggregating bandwidth at the pool level. Spectrum-X Ethernet with co-packaged optics (Spectrum-6 at 102.4 Tb/s per switch chip) and ConnectX-9 SuperNICs (1.6 Tb/s per GPU) extend this beyond the rack, enabling multi-rack DGX SuperPOD deployments. For operators who value deployment flexibility and operational simplicity (a single architecture, a single software stack, elastic pool sizing) over per-phase silicon specialization, the Vera Rubin NVL72 represents the most capable homogeneous disaggregation platform in the industry. NVIDIA’s homogeneous strategy aggregates bandwidth across a 72-GPU NVLink domain to compensate for the ridge point mismatch; Google’s Ironwood TPU tests whether the same compensating logic holds, or yields fundamentally different tradeoffs, when the scale-up domain expands by two orders of magnitude to 9,216 chips.</p><h3>Google Ironwood TPU</h3><p>With Ironwood (TPU v7), explicitly positioned as Google’s first TPU designed for the ‘age of inference,’ Google answers that question by pursuing homogeneous disaggregation at a fundamentally different scale: the same chip architecture serves both prefill and decode, with software-defined scheduling determining which TPU pools handle which phase. The per-chip specifications are competitive with NVIDIA’s Blackwell generation: 4,614 TFLOPS of native FP8 compute, 192 GB of HBM3E, and ~7.4 TB/s of HBM bandwidth. Each chip is composed of two chiplets (a departure from the MegaCore architecture of prior generations) each containing one TensorCore, two SparseCores, and 96 GB of HBM, connected by a die-to-die interface running at 6x the speed of a single ICI link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CSIy-UZum9TrGxQK" /></figure><p>The critical differentiator is scale-up domain size. Ironwood superpods scale to 9,216 chips in a 3D torus topology using Google’s proprietary Inter-Chip Interconnect (ICI) at 9.6 Tb/s aggregate bidirectional bandwidth (~1.2 TB/s per chip), accessing 1.77 PB of shared HBM, dwarfing any NVLink domain in raw chip count. For disaggregated inference, this means the KV-cache handoff between prefill and decode pools occurs entirely within the ICI fabric, not over a scale-out network like EFA or InfiniBand. Google’s Optical Circuit Switching (OCS) technology adds further flexibility: it enables dynamic, reconfigurable slicing of the superpod into arbitrary topologies, allowing prefill and decode pools to be resized without physical recabling. The software stack, Pathways integrated with the JetStream inference engine, enables disaggregated serving by splitting prefill and decode across separate TPU slices, each independently scaling based on real-time demand.</p><p>The roofline tradeoff is explicit. Because the same chip serves both phases, there is no hardware-level ridge point optimization per phase, unlike NVIDIA’s Rubin + Groq LPX pairing or Cerebras’s all-SRAM decode engine. Ironwood’s FP8 ridge point (~623 FLOPs/byte) is well-matched for prefill but substantially over-provisioned for decode. Google’s bet is that the massive ICI-connected domain compensates: allocate <em>more chips</em> to the decode pool, parallelizing the bandwidth-bound workload across more memory systems and aggregating bandwidth at the pool level. Whether this works economically depends on TPU-level cost efficiency. Google’s vertically integrated supply chain yields a meaningfully lower all-in TCO per chip than comparable GPU servers, offsetting the utilization disadvantage of a single architecture spanning both regimes. Anthropic’s commitment to access up to one million Ironwood TPUs suggests the economics are compelling at sufficient scale.</p><h3>AWS Trainium3</h3><p>AWS’s Trainium3 represents a third homogeneous disaggregation approach, built on custom silicon and vertically integrated cloud infrastructure. Each Trainium3 chip, fabricated on TSMC’s 3nm process , delivers 2.52 PFLOPS of MXFP8 compute, 144 GB of HBM3e memory, and 4.9 TB/s of HBM3e bandwidth, achieved by pushing HBM3e pin speeds to 9.6 Gbps across four 12-high stacks. The chip contains 8 NeuronCore-v4 engines, each with a dual-array tensor engine consisting of a 128×128 BF16 systolic array and a 512×128 MXFP8/MXFP4 systolic array, plus 32 MB of explicitly compiler-managed SRAM. At UltraServer scale, the Gen2 configuration packs 144 Trainium3 chips behind a NeuronSwitch-v1 all-to-all fabric (NeuronLink-v4 at 2 TB/s per chip), aggregating 362 MXFP8 PFLOPS, 20.7 TB of HBM3e, and 706 TB/s of memory bandwidth, achieving rough FP8 compute parity with the current-generation GB300 NVL72 through a higher chip count at lower per-chip compute, with a meaningful lead in aggregate memory bandwidth (706 TB/s vs. ~576 TB/s for the GB300 NVL72’s 72 GPUs at 8 TB/s HBM3e each). The disaggregation capability is implemented through the NxD Inference framework integrated with vLLM, which separates prefill and decode onto distinct Trainium3 chip pools, each independently configurable for tensor parallelism, data parallelism, and batch size. The KV-cache handoff uses Neuron Runtime asynchronous send/receive APIs over EFA, performing zero-copy device-to-device RDMA transfers that bypass CPU DRAM staging (the data path traverses the EFA network fabric between NICs, not a direct memory interconnect like NVLink), and executing asynchronously so that the prefill worker can immediately begin processing the next request while the previous KV-cache is in flight. Because both pools use identical silicon, no format conversion or cross-architecture bridging is required, making the transfer a straightforward homogeneous memory-to-memory operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*mbML6xSj0oLrwv70" /></figure><p>The roofline tradeoff mirrors Vera Rubin NVL72 and Ironwood. Trainium3’s MXFP8 ridge point is ~514 FLOPs/byte (2.52 PFLOPS / 4.9 TB/s), well-matched for prefill but substantially over-provisioned for decode’s ~1–2 FLOPs/byte arithmetic intensity. AWS compensates through the same lever as Google: allocate more chips to the decode pool, aggregate bandwidth at the pool level, and scale resources independently based on traffic patterns. The NeuronSwitch-v1 all-to-all fabric is a meaningful upgrade over Trainium2’s 3D torus topology for disaggregated workloads, eliminating the latency asymmetries of nearest-neighbor-only communication and reducing KV-cache transfer variance across chip pairs within the UltraServer. At UltraCluster 3.0 scale, AWS extends this to hundreds of thousands of Trainium3 chips across a petabit-scale network, with Anthropic’s Project Rainier, which deployed nearly half a million Trainium2 chips and is scaling to over one million Trainium2 chips for training and inference, providing the demand signal that validates the economics of homogeneous disaggregation at hyperscale on custom silicon and establishing the operational foundation for Trainium3’s subsequent deployment into these clusters. All three homogeneous approaches share the same fundamental tradeoff: they over-provision compute during decode to aggregate bandwidth, compensating in silicon volume and software scheduling for what they cannot resolve in architectural specialization.</p><h3>Heterogeneous Architectures</h3><p>The engineering bet here is fundamentally different: instead of over-provisioning a single chip design and compensating in software, heterogeneous disaggregation pairs purpose-built silicon to each phase’s roofline regime. This means compute-dense, HBM-equipped accelerators for prefill, and bandwidth-optimized architectures (often SRAM-based) for decode. The potential efficiency gain is substantial, but it introduces a challenge that homogeneous systems avoid entirely: the KV-cache generated during prefill on one architecture must transfer to a different architecture for decode, and the latency and bandwidth of that cross-architecture handoff become a new first-order constraint on system performance. How each vendor navigates that handoff (the interconnect fabric, the transfer protocol, the resulting impact on TTFT) is what distinguishes the approaches below.</p><h3>AWS + Cerebras: Cross-Architecture Disaggregation</h3><p>AWS is pairing Trainium3 UltraServers for prefill with Cerebras CS-3 for decode, deployed in AWS data centers and accessed through Amazon Bedrock. Trainium3, AWS’s 3nm-process accelerator with 144 chips per UltraServer, each chip delivering 4.9 TB/s of HBM3e memory bandwidth, provides the compute-dense, high-bandwidth substrate well-suited for prefill’s parallel matrix multiplications. The CS-3’s Wafer Scale Engine 3 (WSE-3) is the most radical hardware bet in this space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*wRt_oyElITTi1GiU" /></figure><p>A critical architectural detail: the WSE-3’s ~44 GB of on-chip SRAM serves different roles depending on model size. For models whose weights <em>and</em> active KV-cache together fit within the SRAM envelope, inference runs entirely on-wafer. This is the high-performance mode that delivers Cerebras’s characteristic ultra-low-latency throughput, with no external memory access required. The practical ceiling is lower than raw weight capacity suggests: at deep context lengths (100K+ tokens), the KV-cache itself consumes multiple gigabytes of SRAM, realistically limiting on-wafer inference to models up to roughly ~14B parameters (FP16) or ~28B (FP8) before the combined weight + KV-cache footprint exhausts the 44 GB budget. For larger models, Cerebras employs pipeline parallelism across multiple CS-3 systems, splitting model layers so that each wafer’s SRAM holds its assigned portion of weights plus KV-cache. In this mode, all weights remain in on-chip SRAM distributed across wafers, preserving the massive bandwidth advantage at the cost of increased pipeline fill latency during the initial tokens. (Cerebras also offers a MemoryX/SwarmX weight-streaming architecture for training workloads, where weights are streamed from external DRAM to the wafer; however, the company’s documented inference approach for large models relies on pipeline parallelism to keep weights on-chip.) For a 70B model at FP8 (~70 GB of weights), the working set exceeds a single wafer’s SRAM, requiring pipeline parallelism across at least two CS-3 systems. Cerebras has publicly demonstrated throughput of up to ~2,500 TPS on Llama 3.3 70B in this configuration, roughly an order of magnitude faster than GPU-based decode, which provides the performance baseline against which the disaggregation overhead must be measured.</p><p>However, the prefill-to-decode handoff presents a real latency challenge. The KV-cache generated during prefill on Trainium must transfer to the CS-3 over AWS Elastic Fabric Adapter (EFA) networking. For a 70B model at 100K context, the KV-cache can reach 10–20+ GB (depending on GQA configuration, number of layers, head dimension, and precision). The per-chip EFA scale-out bandwidth is roughly 200 Gbps per Trainium3 device. However, since a 70B model necessarily distributes prefill across multiple Trainium3 chips (the model with KV-cache at long context exceeds a single chip’s 144 GB capacity), the aggregate EFA egress bandwidth scales with the number of participating devices. For example, prefill across 8 chips yields ~1.6 Tbps aggregate, across 16 chips ~3.2 Tbps. The effective KV-cache transfer time therefore depends on the specific parallelism configuration, but at aggregate bandwidths in the low-single-digit Tbps range, transferring 10–20 GB of KV-cache introduces a latency penalty on the order of tens to low hundreds of milliseconds, directly impacting Time-to-First-Token (TTFT).</p><p>The bet is quantitative: the CS-3’s decode speedup (roughly 10x over GPU-based decode based on Cerebras’s published benchmarks, ~2,500 tok/s vs. hundreds on GPUs) must generate enough cumulative time savings over the output sequence to overcome that transfer penalty. At ~2,500 tok/s, each token takes ~0.4 ms versus ~3–5 ms on a GPU, saving roughly 2.6–4.6 ms per token. For short outputs (tens of tokens), the EFA transfer latency likely dominates and the disaggregation hurts. For long reasoning chains (thousands of tokens from chain-of-thought, agentic loops, and code generation) the decode speedup compounds and overwhelms the one-time transfer cost. In standard inference terminology, this disaggregated architecture deliberately trades a higher TTFT (Time-to-First-Token), due to the EFA KV-cache transfer, for a dramatically lower TPOT (Time-per-Output-Token), due to Cerebras’s SRAM-speed decode. This trade-off profile is what makes the architecture particularly well-suited for reasoning models and agentic workloads, where output sequences span thousands of tokens and TPOT dominates the user experience, but potentially counterproductive for short-output, latency-sensitive chat queries where TTFT is the metric users feel most acutely. The Cerebras pairing demonstrates that cross-architecture disaggregation delivers order-of-magnitude decode gains, but the cross-architecture transfer of bulk KV-cache state remains the binding constraint on TTFT. NVIDIA’s approach sidesteps this entirely by restructuring what crosses the architecture boundary.</p><h3>NVIDIA Rubin + Groq 3 LPX: Two Levels of Disaggregation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MBuhxXjQW9CGOqz3" /></figure><p>Where the AWS+Cerebras pairing transfers the full KV-cache over EFA between racks, NVIDIA’s approach restructures the disaggregation boundary itself. The Vera Rubin platform with Groq 3 LPX implements what is arguably the most comprehensive disaggregation strategy in the industry, one that operates at two distinct levels of the inference pipeline, and critically, one that transforms the cross-architecture data exchange from a one-time bulk KV-cache transfer into a repeated but lightweight per-token activation exchange.</p><p>The first level is prefill/decode disaggregation, the same architectural principle motivating every system discussed in this article. Within the Vera Rubin NVL72 rack, Dynamo routes prefill to a pool of Rubin GPUs (~50 PFLOPS NVFP4 per package, 288 GB HBM4, ~22 TB/s HBM4 bandwidth per package) that process the full input context in parallel, generating the KV-cache. Decode then runs on a separate Rubin GPU pool, where HBM4’s massive bandwidth serves the autoregressive token generation loop. This alone matches the disaggregated prefill/decode pattern established across the industry, routing each phase to hardware pools optimized for its arithmetic intensity regime.</p><p>The second level goes further: disaggregation <em>within decode itself</em>. NVIDIA calls this Attention-FFN Disaggregation (AFD), and it recognizes that decode is not a monolithic workload; it is a repeated per-token loop containing operations with fundamentally different hardware affinities. As the <a href="https://developer.nvidia.com/blog/inside-nvidia-groq-3-lpx-the-low-latency-inference-accelerator-for-the-nvidia-vera-rubin-platform/">NVIDIA blog</a> describes it, GPUs handle decode work that benefits most from throughput and large memory capacity (specifically, full-context attention over the accumulated KV-cache). LPX accelerates the latency-sensitive execution within decode (specifically, FFN and sparse MoE expert layers). This is where the Groq 3 LPX rack enters the pipeline. Each LP30 chip contains 500 MB of on-chip SRAM serving as primary working storage, delivering 150 TB/s of on-chip memory bandwidth under deterministic, compiler-orchestrated execution where the compiler explicitly schedules computation, data movement, and synchronization rather than relying on dynamic hardware schedulers at runtime. At rack scale, 256 LPUs connected via a direct chip-to-chip (C2C) spine aggregate 128 GB of SRAM, 40 PB/s of on-chip bandwidth, 640 TB/s of scale-up bandwidth, and 315 PFLOPS of FP8 compute. (To put the per-chip bandwidth in roofline terms using this article’s analytical framework: 150 TB/s of SRAM bandwidth versus the Rubin GPU’s ~22 TB/s of HBM4 bandwidth means the LPU’s ridge point sits far lower on the arithmetic intensity axis, precisely where decode’s FFN layers operate.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*un-R69jVjA0Zowno" /></figure><p>In practice, each decode token traverses what NVIDIA describes as a two-engine loop: Rubin GPUs execute attention over the KV-cache, then intermediate activations are handed off to the LPX rack for FFN/MoE execution, and outputs return to the GPUs to continue token generation. Each individual activation exchange is far smaller than the one-time bulk KV-cache transfers that dominate TTFT in other disaggregated architectures (such as Trainium→Cerebras over EFA). But the exchange repeats every layer of every token: for a model with 80+ transformer layers, each generated token requires on the order of 160 cross-architecture round-trips (GPU→LPU and LPU→GPU per layer) over the Spectrum-X Ethernet interconnect. The cumulative per-layer latency, not the per-transfer data volume, is what makes interconnect design and Dynamo’s orchestration of the AFD loop a first-order constraint on TPOT. NVIDIA claims the combined Vera Rubin NVL72 + LPX system delivers up to 35x higher TPS/MW at 400 TPS per user interactivity compared to the GB200 NVL72, and up to 10x more revenue opportunity for trillion-parameter-class MoE models, by expanding the Pareto frontier to simultaneously sustain high AI factory throughput and highly responsive interactive experiences.</p><p>The result is a three-pool architecture (prefill GPUs, decode-attention GPUs, and decode-FFN LPUs) each matched to its workload’s position on the roofline. No other vendor currently implements disaggregation at this granularity. The AWS+Cerebras and Google Ironwood approaches separate prefill from decode; NVIDIA’s Vera Rubin + LPX architecture separates prefill from decode <em>and then</em> separates decode itself into its constituent bandwidth regimes.</p><h3>Software: NVIDIA Dynamo</h3><p>Hardware disaggregation without intelligent orchestration is useless, and the orchestration problem for a three-pool architecture is qualitatively harder than for a simple prefill/decode split. In a homogeneous system, the scheduler manages a single pool of identical chips and decides how many to allocate to each phase. In the Vera Rubin + Groq LPX configuration, Dynamo must orchestrate a fundamentally different data flow: not just the one-time KV-cache handoff between prefill and decode pools, but the repeated per-token AFD loop where Rubin GPUs execute attention, intermediate activations cross the Spectrum-X fabric to LPX racks for FFN/MoE execution, and outputs return to the GPUs, every single token. The latency budget for that round-trip is measured in fractions of a millisecond, and any scheduling jitter directly inflates TPOT across every concurrent user session. With KV-aware routing, low-overhead transfers, and latency-target-driven scheduling, Dynamo maintains stable tail latency as concurrency and request shapes vary, making heterogeneous decode predictable rather than brittle under production traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/0*o7ZSTGYuyYTyb2YY" /></figure><p>This is what makes Dynamo, an open-source inference framework released at GTC 2025, more than a serving layer. It’s the component that determines whether heterogeneous decode is operational or theoretical. Dynamo’s request router is KV-cache-aware: it understands which GPU pools hold which portions of the KV state and routes decode work accordingly, avoiding redundant cache transfers. Its GPU Planner elastically scales prefill and decode pool sizes based on real-time traffic, critical because the optimal prefill-to-decode GPU ratio shifts dramatically between workloads dominated by long-context prefill (document summarization, RAG) and those dominated by long-output decode (reasoning chains, code generation). NIXL, the NVIDIA Inference Transfer Library, manages the KV-cache handoff between prefill and decode hardware using a unified asynchronous data-movement API that spans GPU memory, CPU DRAM, SSDs, and networked storage via RDMA, with pipelined streaming that overlaps transfer with computation. And Dynamo’s memory manager offloads KV-cache to lower-cost memory tiers (CPU DRAM, local SSDs, networked object storage) without impacting user experience, which is what makes long-context inference possible without provisioning HBM proportional to context length for every active session.</p><p>Critically, none of these capabilities are exclusive to the heterogeneous configuration. For homogeneous Vera Rubin NVL72 deployments, where all 72 Rubin GPUs serve both phases, Dynamo manages the prefill/decode split and KV-cache transfer via NIXL within the NVLink domain. The same orchestration framework spans both deployment models, which means operators can start with homogeneous disaggregation and move to heterogeneous Rubin + LPX configurations without re-architecting their serving stack. This is a deliberate platform strategy: Dynamo is not a feature of the Groq partnership; it is the layer that makes disaggregated inference a deployment model rather than a research prototype.</p><p>NVIDIA’s own benchmarks quantify the impact. On GB200 NVL72 serving DeepSeek-R1 671B, a reasoning model with very long output sequences where decode dominates total compute, disaggregated serving with Dynamo delivered up to 30x higher TPS/GPU. On Llama 70B on Hopper, throughput more than doubled. These gains reflect the compound effect of disaggregated scheduling, dynamic pool rebalancing, KV-cache-aware routing, and multi-node scaling. With purpose-built Rubin for prefill and LPX for decode-FFN, these gains should compound further. As NVIDIA describes it, the heterogeneous architecture enables the system to sustain high AI factory throughput while delivering responsive interactive experiences, a combination that a single homogeneous platform forces into a tradeoff. NVIDIA’s own research paper, <em>“</em><a href="https://arxiv.org/pdf/2506.05508"><em>Beyond the Buzz: A Pragmatic Take on Inference Disaggregation</em></a><em>,”</em> tested hundreds of thousands of design points and found that disaggregation is most effective for prefill-heavy traffic and larger models, with dynamic rate matching and elastic scaling being critical for Pareto-optimal performance. Reasoning and agentic workloads benefit from both the decode acceleration and the elimination of prefill/decode contention, though the optimal hardware ratios differ from prefill-dominated traffic.</p><h3>The Synthesis</h3><p>The monolithic GPU era for inference is ending. The roofline model predicted this: no single architecture can simultaneously optimize for compute-bound prefill and bandwidth-bound decode. What forced the industry’s hand is the convergence of reasoning and agentic workloads into a demand profile that stresses every dimension at once. A multi-agent orchestration loop (planner, executor, critic agents invoking each other in sequence) turns every user interaction into a cascade of decode-heavy inference calls, each with its own latency budget, at volumes that demand high throughput and sustained bandwidth simultaneously. No monolithic architecture serves all three without a tradeoff that degrades at least one.</p><p>The homogeneous bet (Google’s Ironwood, NVIDIA’s Vera Rubin NVL72 in GPU-only mode) wagers that a single massively scaled chip architecture, paired with intelligent software scheduling, can span both regimes through over-provisioning and dynamic pool reallocation. The strengths are real: operational simplicity, elastic rebalancing, and KV-cache transfers that stay within a high-bandwidth scale-up domain. For operators who value deployment flexibility over per-phase roofline optimization, this may prove the most practical path.</p><p>The heterogeneous bet (AWS+Cerebras, and NVIDIA’s Vera Rubin + Groq LPX) wagers that matching each phase’s silicon to its roofline regime outweighs the orchestration complexity. NVIDIA’s strategy is the most structurally comprehensive: purpose-built silicon for each phase (Rubin GPUs for prefill and KV-cache-bound attention, Groq 3 LPX for FFN weight streaming), interconnect minimizing the disaggregation overhead, and Dynamo orchestrating both the prefill/decode split and the per-token AFD loop within decode. No other vendor currently implements disaggregation at two levels. Much of this is announced rather than shipping, and claims like the 35x TPS/MW figure await independent validation, but the architectural logic holds independent of any single benchmark, because the roofline model predicts that any system matching silicon to arithmetic intensity will outperform one that compromises.</p><p>The deeper implication is economic. Disaggregated inference, particularly heterogeneous disaggregation, is what makes the agentic inference regime economically viable rather than ruinously expensive. The vendors who ship production-grade disaggregated serving stacks will define the cost floor for the next generation of AI applications. The Vera Rubin + Groq LPX architecture is a bet that the hardware topology itself should be shaped by the arithmetic intensity profile of the workload, where the roofline model is no longer just an analysis tool but a design principle embedded in silicon. The <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-2-ce397041dec2">walls of silicon</a> haven’t fallen. We’re learning to engineer around them.</p><p>The deeper implication is economic. Disaggregated inference, particularly heterogeneous disaggregation, is what makes the agentic inference regime economically viable rather than ruinously expensive. The vendors who ship production-grade disaggregated serving stacks will define the cost floor for the next generation of AI applications. The Vera Rubin + Groq LPX architecture is a bet that the hardware topology itself should be shaped by the arithmetic intensity profile of the workload, where the roofline model is no longer just an analysis tool but a design principle embedded in silicon. The <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-2-ce397041dec2">walls of silicon</a> haven’t fallen. We’re learning to engineer around them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92c8b36d1a88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GRAFT: Graph-Augmented Framework of Thought — Part 3]]></title>
            <link>https://medium.com/@asheesh.goja/graft-graph-augmented-framework-of-thought-part-3-7753ec521831?source=rss-8b819656b4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7753ec521831</guid>
            <dc:creator><![CDATA[Asheesh Goja]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 18:43:52 GMT</pubDate>
            <atom:updated>2025-07-23T18:47:00.387Z</atom:updated>
            <content:encoded><![CDATA[<h3>GRAFT: Graph-Augmented Framework of Thought — Part 3</h3><h4>Platform Engineering</h4><h3>Introduction</h3><p>As we conclude this three-part series on the Graph-Augmented Framework of Thought (GRAFT), we transition from the conceptual and software aspects into the domain of platform engineering. In <a href="https://medium.com/p/92551b5969e9/">Parts 1</a> and <a href="https://medium.com/p/f0b5db5a7aea/">2</a>, we explored GRAFT’s ability to augment Large Language Models (LLMs) with graph-based reasoning, enabling deeper exploration and more robust problem-solving. We examined advanced prompt strategies and software patterns to address limitations in LLMs, building a system capable of complex reasoning tasks. Now, we turn to the practicalities of deploying and operating GRAFT at scale. (<a href="https://github.com/asheeshgoja/graft"><em>Source Code</em></a>)</p><p>This final installment focuses on how Kubernetes, along with its ecosystem tools like Kubernetes Operators and Kubernetes Event-Driven Autoscaling (KEDA), can be utilized to manage and optimize GRAFT effectively. By embracing containerization, automation, and dynamic scaling, this approach not only simplifies the operational complexity of GRAFT but also enhances its scalability and performance. We will explore how platform engineering with Kubernetes offers a seamless, scalable, and cost-efficient solution to advanced LLM inferencing, empowering ML engineers to deploy GRAFT in production environments with minimal overhead.</p><h4>Managing Complexity with Kubernetes</h4><p>The “Law of Conservation of Complexity” posits that complexity cannot be eliminated, only shifted. While GRAFT addresses the computational complexity of LLM-based reasoning by employing graph structures, it inevitably introduces operational complexity. Managing GRAFT involves coordinating multiple components, such as service endpoints, load balancers, message queues, caching, graph databases, and auto-scaling.</p><p>Kubernetes, with its orchestration and scaling capabilities, emerges as an ideal platform to handle this complexity. By leveraging Kubernetes features such as containerization, Operators, and autoscaling mechanisms like KEDA, we can automate and streamline GRAFT’s deployment and maintenance. Below, we delve into each step of the platform engineering process for GRAFT.</p><h4>Containerization: The First Step to Kubify GRAFT</h4><p>The first step in operationalizing GRAFT is to containerize each module of the system. Containerization ensures that each component has a consistent runtime environment with all dependencies packaged within a Docker container. This allows the GRAFT modules — Orchestrator, Thought Generator, Thought Evaluator, and Solution Validator — to be isolated, portable, and easily deployed across different environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMSwQiAhfVGNzOORbjDtPw.png" /></figure><p><strong>Key Kubernetes Resources:</strong></p><ul><li><strong>Pods</strong>: Represent the individual GRAFT modules, each running in its own container.</li><li><strong>Deployments</strong>: Manage the desired state of Pods, ensuring the correct number of replicas are running and automatically handling updates and rollbacks.</li><li><strong>Services</strong>: Provide stable networking endpoints, enabling communication between the GRAFT modules.</li><li><strong>ConfigMaps and Secrets</strong>: Store configuration data and sensitive information like API keys, ensuring secure and consistent configurations across the system.</li><li><strong>Persistent Volumes (PVs) and Persistent Volume Claims (PVCs)</strong>: Manage storage resources for stateful components like Neo4j and Redis, ensuring data persistence across reboots and redeployments.</li></ul><p>Once the GRAFT modules are containerized and their resources defined in Kubernetes, we can focus on automating operations with Operators and implementing event-driven scaling.</p><h4>Automating Operations with Kubernetes Operators</h4><p>Managing GRAFT manually can be complex, especially as the system scales. To streamline this process, we leverage Kubernetes Operators. Operators extend the Kubernetes API to manage the entire lifecycle of GRAFT, automating tasks like deployment, updates, monitoring, and scaling.<strong> </strong>We need a custom Kubernetes Operator, to manage the desired state of each GRAFT module, monitor the health of the system, and handles operational tasks with minimal manual intervention.</p><ul><li><strong>Deployment</strong>: Automates the deployment of each GRAFT module, ensuring that predefined configurations and dependencies are applied.</li><li><strong>Configuration Management</strong>: Ensures consistency in configurations across modules by centralizing them using ConfigMaps and Secrets.</li><li><strong>Updates and Upgrades</strong>: Minimizes downtime by handling automated updates to the system.</li><li><strong>Monitoring and Logging</strong>: Integrates with monitoring tools like Prometheus to capture key performance metrics, while logs from each module are forwarded to a centralized logging service.</li><li><strong>Self-Healing and Error Recovery</strong>: Detects and resolves common issues automatically, such as restarting failed Pods and rebalancing workloads.</li><li><strong>Resource Optimization</strong>: Dynamically adjusts resource allocation based on real-time metrics, ensuring optimal performance without wasteful over-provisioning.</li></ul><h4><strong>Enhancing Scalability with KEDA</strong></h4><p>Scaling GRAFT efficiently is critical to managing its operational complexity, especially under varying workloads. KEDA enhances GRAFT’s scalability by providing event-driven autoscaling, allowing the system to scale based on custom metrics such as message queue length or database load.</p><ul><li><strong>Custom KEDA Scalers</strong>: Monitor custom metrics emitted by the GRAFT modules, such as Redis queue length, LLM response times, and Neo4j query loads. Based on these metrics, KEDA dynamically adjusts the number of running Pods.</li><li><strong>Horizontal Pod Autoscaler (HPA)</strong>: KEDA works in conjunction with HPA to automatically scale the Pods up or down based on workload demand. This ensures that GRAFT can handle spikes in workload efficiently without over-provisioning resources.</li></ul><p>By integrating KEDA, GRAFT becomes a dynamic, self-scaling system that adjusts resource allocation in real-time, ensuring cost-efficiency and robust performance.</p><h4>Operator and KEDA Integration: Architecture Overview</h4><p>Bringing everything together, the architecture of GRAFT in a Kubernetes environment leverages Operators and KEDA to manage the lifecycle of each GRAFT component. This section provides a breakdown of how each component is deployed, managed, and scaled dynamically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYs6uLH1cg6Mb5QR3SmgbQ.png" /></figure><p><strong>Orchestrator Operator</strong></p><ul><li>Function: Manages the Orchestrator component of the GRAFT system .</li><li>Deployment: Managed by its custom Operator, ensuring that the correct number of instances are running based on real-time demand.</li><li>Scaling: KEDA scales the Orchestrator Pods based on queue length and task processing times, ensuring timely orchestration.</li></ul><p><strong>Thought Generator Operator</strong></p><ul><li>Function: Manages the Thought Generator component of the GRAFT system.</li><li>Deployment: Managed by its Operator, ensuring it interacts efficiently with LLM APIs.</li><li>Scaling: KEDA adjusts the number of Thought Generator Pods based on the rate of thought generation requests.</li></ul><p><strong>Thought Evaluator Operator</strong></p><ul><li>Function: Manages the Thought Evaluator component of the GRAFT system.</li><li>Deployment: Managed by its custom Operator.</li><li>Scaling: KEDA scales the Thought Evaluator based on evaluation task queue length and computational load.</li></ul><p><strong>Solution Validator Operator</strong></p><ul><li>Function: Manages the Solution Validator component of the GRAFT system.</li><li>Deployment: Managed by its Operator, ensuring consistency in solution validation.</li><li>Scaling: KEDA dynamically scales Solution Validator Pods based on the number of solutions requiring validation.</li></ul><p><strong>Redis Operator</strong></p><ul><li>Function: Manages Redis infrastructure of the GRAFT system.</li><li>Deployment: Deployed as a StatefulSet with PVCs for storage, managed by its custom Redis Operator.</li><li>Scaling: KEDA scales Redis Pods based on custom metrics like queue length and memory usage.</li></ul><p><strong>Neo4j Operator</strong></p><ul><li><strong>Function</strong>: Manages the Neo4j infrastructure of the GRAFT system.</li><li><strong>Deployment</strong>: Deployed as a StatefulSet with associated PVCs, managed by the Neo4j Operator.</li><li><strong>Scaling</strong>: KEDA adjusts the number of Neo4j Pods based on query load and database size.</li></ul><p>This Kubernetes-based architecture not only simplifies the operational complexity of the graph based GRAFT system but also ensures that it remains scalable, resilient, and cost-efficient, making it a robust solution for advanced LLM inferencing.</p><h4>Monitoring and Metrics with Prometheus</h4><p>To ensure the GRAFT system is operating optimally, Prometheus is used to collect and monitor custom metrics from the GRAFT modules. These metrics are also used by KEDA for autoscaling decisions. Monitoring these metrics allows the system to adjust resource allocation dynamically, providing insights into performance bottlenecks and helping maintain operational efficiency.</p><ul><li>Queue Length: For Redis task queues.</li><li>Response Times: For LLM interactions.</li><li>Resource Usage: Compute and memory consumption of each module.</li><li>Database Load: Neo4j query performance metrics.</li></ul><p>With the foundational concepts in place, it’s time to move from theory to practice. Let’s dive into the implementation details and explore how to build the GRAFT Operator, the core component responsible for automating the deployment, scaling, and management of GRAFT within Kubernetes.</p><h4>Show me the code: Building the GRAFT Operator</h4><p>To automate the deployment and management of GRAFT, we need to implement the <strong>GRAFT Thought Operator.</strong> This Operator is responsible for maintaining the desired state of each GRAFT module — Orchestrator, Thought Generator, Thought Evaluator, and others — ensuring smooth operations and scaling within the Kubernetes environment. Below, we break down how to build this Operator step-by-step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVcp-s87g1z95R2E7JQ5UA.png" /></figure><ol><li><strong>Define the Custom Resource (CRD) : </strong>The first step is defining the Custom Resource Definition (CRD) for the GRAFT components. This CRD specifies the custom resources that the Operator will manage. For instance, here’s how we might define a CRD for Neo4j, which is used to store the GRAFT reasoning graph:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81928f1aefeb61bce3158c24278643f9/href">https://medium.com/media/81928f1aefeb61bce3158c24278643f9/href</a></iframe><p><strong>2. Develop L4 Controller</strong>: Code the controller using the Kubernetes Operator Framework (Golang is commonly used). The controller ensures that the observed state matches the desired state, taking corrective actions as necessary. Here is a sample corresponding controller file for neo4j CRD</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45426b5d00392bdf0f5d1df398004324/href">https://medium.com/media/45426b5d00392bdf0f5d1df398004324/href</a></iframe><p><strong>3. Deploy the Operator</strong>: Deploy the operator to the Kubernetes cluster and instantiate the custom resources. The operator then automatically creates the GRAFT environment as defined in the CRDs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63rV8J5Q4VBNlGI4Zx8oLw.png" /></figure><p>Now that we’ve explored how the GRAFT Thought Operator is built, it’s time to get it up and running.</p><h4>Installing and Deploying GRAFT Operator</h4><p><strong>Prerequisites</strong>:</p><ul><li>Server<strong>:</strong> Canonical Ubuntu 22.04 LTS or higher</li><li>Clients<strong>:</strong> <a href="https://neo4j.com/download/">Neo4J Desktop</a> , <a href="https://redis.io/insight/">Redis Insights</a></li></ul><p><strong>Steps to Install the Core Components on the Server</strong></p><ol><li>Clone the Git Repository:</li></ol><pre>git clone https://github.com/asheeshgoja/grapt<br>cd graft/</pre><p>2. Create the Credential Files:</p><pre>sudo apt-get install make<br>cd make<br>make -f 00-Makefile_creds</pre><p>3. Specify the Required Credentials:</p><p>In /graph-of-thought/creds folder you fill see three files</p><ul><li>aws — This is for AWS Bedrock , use AccessKey and Secret.</li><li>openai — This is for OpenAI, use the OpenAI Key.</li><li>neo4j — This is for the neo4j db uid/psw</li></ul><p>4. Install, configure and verify Docker Runtime: (Skip if already installed)</p><pre>make -f 01-Makefile_docker<br>docker images</pre><p>5. Install and verify minikube</p><pre>make -f 02-Makefile_minikube<br>minikube version</pre><p>7. Install and verify Golang and kubectl : (Skip if already installed)</p><pre>make -f 03-Makefile_golang<br>make -f 04-Makefile_kubectl<br><br>source ~/.bashrc<br>go version<br>k version</pre><p>8. Start Minikube, build GRAFT operator and core components images, and then run the Graph of Thoughts K8s Operator. Then verify that got-webserver and graph-of-thought images are build and deployed.</p><pre>make -f 05-Makefile_got-operator<br>source ~/.bashrc<br><br>docker images<br>REPOSITORY                                TAG        IMAGE ID       CREATED          SIZE<br>graft-dashboard                           latest     6b5f3bc4763f   9 minutes ago    1.15GB<br>graft-core                                latest     7289210dfdad   10 minutes ago   1.13GB<br>redis                                     latest     590b81f2fea1   5 weeks ago      117MB<br>registry.k8s.io/kube-apiserver            v1.30.0    c42f13656d0b   4 months ago     117MB<br>registry.k8s.io/coredns/coredns           v1.11.1    cbb01a7bd410   12 months ago    59.8MB<br>registry.k8s.io/pause                     3.9        e6f181688397   23 months ago    744kB<br>neo4j                                     3.5.12     dd6c46d544a5   3 years ago      367MB<br></pre><p>Also verify that the GRAFT operator is running:</p><pre>ss -tulnp | grep 8080<br>tcp   LISTEN 0      4096                 *:8080             *:*    users:((&quot;main&quot;,pid=&lt;&gt;,fd=3))</pre><p>9. Start the GRAFT Pods and Services. Verify the pods and services are up and running.</p><pre>make -f 06-Makefile_start-got-services<br><br>k get po<br>NAME                                            READY   STATUS    RESTARTS        AGE<br>graft-orchestrator-pod-5ff849b954-sp4bw         1/1     Running   0               3m30s<br>graft-solution-validator-pod-bbb745bc7-wz7bv    1/1     Running   0               3m30s<br>graft-thought-bus-pod-54c88848d7-q95rr          1/1     Running   0               4m54s<br>graft-thought-evaluator-pod-f46944d84-cwgpt     1/1     Running   0               3m30s<br>graft-thought-evaluator-pod-f46944d84-fpt7p     1/1     Running   0               3m29s<br>graft-thought-generator-pod-67cc8b4f88-8758j    1/1     Running   0               3m30s<br>graft-thought-generator-pod-67cc8b4f88-h6mbf    1/1     Running   0               3m30s<br>graft-thought-generator-pod-67cc8b4f88-qzmtr    1/1     Running   0               3m30s<br>graft-thought-graph-pod-577d75ff6b-2vtx5        1/1     Running   0               4m54s<br>graft-web-and-api-server-pod-569bb47497-xltpv   1/1     Running   3 (4m33s ago)   4m54s<br><br>k get svc<br>graft-web-server            NodePort    10.98.54.122     &lt;none&gt;        8000:30018/TCP                                 4m49s<br>kubernetes                  ClusterIP   10.96.0.1        &lt;none&gt;        443/TCP                                        8m38s<br>neo4j-graphdb-nodeportsvc   NodePort    10.97.243.116    &lt;none&gt;        7474:30014/TCP,7473:30015/TCP,7687:30016/TCP   4m49s<br>neo4j-graphdb-service       ClusterIP   10.110.130.185   &lt;none&gt;        30011/TCP,30012/TCP,30013/TCP                  4m49s<br>redis-pubsub-nodeportsvc    NodePort    10.103.113.67    &lt;none&gt;        6379:30008/TCP                                 4m49s<br>redis-pubsub-service        ClusterIP   10.108.110.166   &lt;none&gt;        30007/TCP                                      4m49s</pre><p>10. Open and Forward Ports:</p><pre>cd ./graph-of-thought/build<br>. 07_forward_ports.sh</pre><p>You will see this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNVFyg7ATFv7ynP9vMf7Sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aG3phHohH9uI8VFN1jf-oA.png" /></figure><p>9. Open the <a href="http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/#/pod?namespace=default">Kubernetes dashboard</a>. If all the services installed correctly, you will see this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0zA3km8rt91yE0NuEk1Mw.png" /></figure><h4>Demo Time</h4><p>1. <strong>Graph of Thoughts UI :</strong> Open the <a href="http://localhost:30018/demo.html">Graft Dashboard</a>. Click the “Solve Problem” button. You wil see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3irwnI3-7eeXJIXe8eleg.png" /></figure><p><strong>2. Check the Thought Graph: </strong>Open Neo4J Desktop and connect to the <em>neo4j-graphdb-service </em>at bolt://localhost:7687. Set the UID/PSW as specified in step 3 of the installation. In Neo4J, run the query</p><pre>MATCH(t:Thought) RETURN t</pre><p>You will see this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJMfb0ZfrquSyqOD7uHMBg.png" /></figure><p><strong>3. Thought Logs:</strong> Open the Redis Insights UI and the create a database connnection to <em>127.0.0.1:30008. </em>Open this connection and the add a subscription to the ToT logs channels</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3K-qZB7SqU-Aez3GwWxEQQ.png" /></figure><h4>Conclusion</h4><p>In this three-part series, we explored the core principles, software architecture, and platform engineering needed to bring the GRAFT to life. In <strong>P</strong><a href="https://medium.com/p/92551b5969e9/"><strong>art 1</strong></a>, we introduced the limitations of traditional LLMs in handling complex reasoning tasks and showed how GRAFT, with its graph-based reasoning, addresses these challenges.</p><p>In <a href="https://medium.com/p/f0b5db5a7aea/"><strong>Part 2</strong></a>, we shifted focus to the software engineering patterns required to build a modular and scalable GRAFT system. By applying techniques like modularization, containerization, and parallelization, we outlined a robust software architecture that supports the dynamic reasoning capabilities of GRAFT while managing computational complexity and resource constraints.</p><p>Finally, in <strong>Part 3</strong>, we dove into the platform engineering aspects of deploying GRAFT at scale using Kubernetes. We demonstrated how to leverage containerization, Kubernetes Operators, and KEDA for dynamic resource scaling, automating operational tasks, and optimizing performance, all while reducing costs. This cohesive strategy ensures that GRAFT is not just theoretically powerful but also practical for real-world deployment.</p><p>By integrating advanced AI concepts with modern software and platform engineering practices, GRAFT offers a scalable and efficient solution for solving complex, multi-step reasoning tasks with LLMs. Whether you’re designing better Gen AI systems or deploying large-scale inferencing frameworks, GRAFT provides a blueprint for pushing the boundaries of what LLMs can achieve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7753ec521831" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GRAFT: Graph-Augmented Framework of Thought — Part 2]]></title>
            <link>https://medium.com/@asheesh.goja/graft-graph-augmented-framework-of-thought-part-2-f0b5db5a7aea?source=rss-8b819656b4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0b5db5a7aea</guid>
            <dc:creator><![CDATA[Asheesh Goja]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 18:43:27 GMT</pubDate>
            <atom:updated>2025-07-23T18:46:48.845Z</atom:updated>
            <content:encoded><![CDATA[<h3>GRAFT: Graph-Augmented Framework of Thought — Part 2</h3><h4>Software Engineering</h4><h3>Introduction</h3><p>Welcome to Part 2 of our series on the Graph-Augmented Framework of Thought (GRAFT). In <a href="https://medium.com/p/92551b5969e9/">Part 1</a>, we explored the theoretical foundations of integrating graph-based reasoning into the enhanced ToT framework to address the limitations of LLMs in complex reasoning tasks. Now, we move from theory to practice, tackling challenges like computational complexity and operational costs. This installment covers system design, software patterns, and practical steps for building and deploying a scalable GRAFT system. (<a href="https://github.com/asheeshgoja/graft"><em>Source Code</em></a>)</p><h4>GRAFT Challenges</h4><p>Implementing GRAFT faces key challenges in computational complexity, resource constraints, and costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AsJmx_hAQTMZzntTPREtA.png" /></figure><ul><li><strong>Computational Complexity</strong>: GRAFT’s graph-based approach, while effective, results in high time and space complexities. As the graph grows with more nodes and edges, exploring potential solution paths can become exponentially slower, and storing large graph structures with associated metadata strains memory resources, particularly in large-scale tasks.</li><li><strong>Resource Constraints</strong>: Running LLMs locally requires substantial GPU memory and compute power, which may not be available on standard hardware. When using external LLM APIs, rate limits and throttling reduce the system’s ability to handle continuous or large-scale reasoning tasks, as API call caps hinder performance during heavy workloads.</li><li><strong>Cost Considerations</strong>: Frequent API calls in GRAFT’s iterative reasoning process can quickly escalate costs, making it expensive for large-scale or complex tasks. Running LLMs locally requires significant upfront investments in high-performance GPUs, alongside ongoing energy and maintenance costs, making scaling the system even more costly.</li></ul><p>Careful software design is needed to address these challenges, utilizing appropriate patterns to optimize performance and cost-efficiency.</p><h4>Software Patterns</h4><p>Implementing GRAFT requires strategies to manage computational complexity, resource constraints, and costs. Key software design patterns optimize time, space, throughput, and latency. Here’s a breakdown of patterns for each challenge. Let’s explore some key patterns in each category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewy6YRMY3pzgK1h7NwMW6g.png" /></figure><p><strong>Managing Time Complexity:</strong></p><ul><li><em>Functional Decomposition</em>: Break GRAFT into smaller tasks for efficiency.</li><li><em>Divide and Conquer</em>: Solve independent tasks simultaneously to save time.</li><li><em>Early Termination</em>: Stop non-promising paths early to avoid wasted computation.</li><li><em>Parallelize Search</em>: Use parallel computing to explore graph branches faster.</li></ul><p><strong>Managing Space Complexity:</strong></p><ul><li><em>Memoization</em>: Cache results to avoid redundant calculations.</li><li><em>Lazy Initialization</em>: Delay object creation to reduce memory use.</li><li><em>Distributed Cache</em>: Use distributed storage to relieve memory pressure on nodes.</li></ul><p><strong>Managing Throughput Limits:</strong></p><ul><li><em>Exponential Backoff</em>: Gradually increase retry times during high demand to avoid overload.</li><li><em>Rate Limiting</em>: Control the number of API requests within a set period.</li><li><em>Cache to Reduce Calls</em>: Use caching to minimize repeated API calls.</li></ul><p><strong>Managing Latency:</strong></p><ul><li><em>Event-Driven Parallelism</em>: Process tasks asynchronously to reduce wait times.</li><li><em>Scatter-Gather</em>: Parallelize tasks across multiple nodes and collect results.</li><li><em>Load Balancing</em>: Evenly distribute tasks to prevent overloading nodes.</li></ul><p><strong>Reducing Operational Costs:</strong></p><ul><li><em>Horizontal Scaling</em>: Add nodes as demand grows to efficiently manage resources.</li><li><em>Batch Prompting</em>: Group multiple requests into one to reduce API call volume.</li><li><em>Containerization</em>: Use containers for consistent deployment and scaling of GRAFT components.</li></ul><h4>Patterns To Practice</h4><p>With the key software patterns in mind, let’s explore how to apply them in practice to build a scalable GRAFT system. Here’s a step-by-step guide:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29vI2_e2MpmKePe8rEHQoQ.png" /></figure><ul><li><strong>Modularize</strong>: Break GRAFT into decoupled modules like the Orchestrator, Thought Generator, and Redis Thought Bus. Each module is self-contained, allowing independent development and optimization.</li><li><strong>Externalize</strong>: Offload state management and message queues to external systems like Neo4j for graph storage and Redis for caching, keeping GRAFT lightweight and stateless.</li><li><strong>Containerize</strong>: Package each GRAFT component into Docker containers for consistency, easy scaling, and seamless deployment in different environments.</li><li><strong>Parallelize</strong>: Use Kubernetes to distribute workloads across nodes, enabling concurrent processing of thought generation and evaluation tasks for efficient large-scale operations.</li></ul><p>Next, we’ll dive into GRAFT’s architecture, exploring how these components interact to solve complex reasoning tasks.</p><h4>Applying Patterns to Build GRAFT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vm-9fTWvzkyJlLIIS7KGNA.png" /></figure><h4><strong>Orchestrator</strong></h4><ol><li><strong>Modularization</strong></li></ol><ul><li>Thought Scheduler: Manages the scheduling of thought generation, evaluation, and solution validation as events in a FIFO queue, controlling task distribution.</li><li>Tree Search Control: Implements tree traversal algorithms like BFS, DFS, and A* to guide the exploration of solution paths.</li><li>Backtracker and Lookahead Simulator: Evaluates and prunes less-promising branches while simulating alternative paths to enhance solution discovery.</li><li>Thought Ranker: Ranks and sorts partial solutions to determine the most viable paths.</li><li>Thought Graph Builder: Interfaces with Neo4j to update and query the evolving reasoning graph as new thoughts and relationships are created.</li></ul><p><strong>2. Externalization</strong></p><ul><li>State Management: Offloads reasoning state to Neo4j, where the graph structure is maintained externally, enabling efficient querying and visualization.</li><li>Messaging: Uses Redis as a message bus for communication between modules, ensuring asynchronous task distribution across components.</li><li>Logging: External database stores logs of solution paths, facilitating traceability and analysis.</li></ul><p><strong>3. Parallelization</strong></p><ul><li>Task Distribution: The Thought Scheduler offloads tasks to worker nodes in parallel via Redis, enabling simultaneous generation and evaluation of thoughts.</li><li>Backtracking and Lookahead: Parallel processing of multiple solution paths accelerates the discovery of optimal solutions by pruning unpromising paths earlier.</li></ul><p><strong>4. Patterns Implemented</strong></p><ul><li>Divide and Conquer: Tree search algorithms split the problem into smaller sub-problems that are processed concurrently.</li><li>Parallelize Search: Exploration of thought paths occurs in parallel across multiple worker nodes.</li><li>Early Termination: Unproductive branches are pruned early to optimize resource usage.</li><li>State Externalization: Offloading the reasoning graph to Neo4j minimizes memory consumption and allows scalable graph queries.</li></ul><h4>Thought Generator</h4><ol><li><strong>Modularization</strong></li></ol><ul><li>Prompter: Takes input from the Orchestrator and prepares it for submission to the LLM, ensuring proper formatting of the prompt.</li><li>LLM Module: Abstracts the interaction with either an API or a local LLM model, ensuring a flexible and scalable architecture.</li><li>Parser: Processes the output generated by the LLM, extracting potential thoughts and solutions.</li><li>De-Duplicator: Identifies and removes duplicate thoughts to streamline the reasoning process and avoid redundant paths.</li></ul><p><strong>2. Externalization</strong></p><ul><li>Message Passing: Utilizes Redis for task communication between the Thought Generator and other components, ensuring decoupled, stateless interactions.</li><li>LLM Caching: External caches store previously generated thoughts, reducing API call overhead by reusing results when possible.</li></ul><p><strong>3. Parallelization</strong></p><ul><li>Task Queuing: Thought generation tasks are enqueued in Redis, allowing worker nodes to process thought generation concurrently.</li><li>Concurrent Thought Generation: Multiple thought generation jobs are executed simultaneously across worker nodes to explore diverse solution paths in parallel, speeding up the process of idea generation.</li></ul><p><strong>4. Patterns Implemented</strong></p><ul><li>Functional Decomposition: Breaking the thought generation process into modular tasks (prompting, parsing, deduplication) ensures each sub-task is optimized independently.</li><li>Exponential Backoff: Retries for LLM API requests are managed to prevent overwhelming the system during high demand periods.</li><li>Memoization: Caching LLM results ensures previously generated thoughts are reused, reducing redundant computations.</li><li>Containerization: Dockerized components simplify deployment and scaling across multiple environments.</li></ul><h4>Thought Evaluator</h4><ol><li><strong>Modularization</strong></li></ol><ul><li>Prompter: Wraps each thought generated by the Thought Generator with an evaluation prompt for the LLM to classify the quality of the partial solution.</li><li>LLM Module: Encapsulates the LLM API call or local LLM processing, sending prompts for thought evaluation.</li><li>Parser: Extracts and processes the evaluation scores from the LLM’s responses.</li><li>Classification Values Mapper: Maps the LLM output to a numeric score that ranks the quality of each thought based on predefined criteria.</li></ul><p><strong>2. Externalization</strong></p><ul><li>State Tracking: Evaluation results are stored externally in a database, allowing persistent and scalable management of thought evaluations.</li><li>Message Passing: Uses Redis to queue thought evaluation tasks and communicate results back to the Orchestrator.</li></ul><p><strong>3. Parallelization</strong></p><ul><li>Concurrent Evaluations: Thought evaluations are processed in parallel across multiple worker nodes, using Redis for asynchronous task distribution.</li><li>Batch Evaluation: Multiple thoughts can be grouped and evaluated in parallel, allowing the system to scale effectively even under heavy load.</li></ul><p><strong>4. Patterns Implemented</strong></p><ul><li>Batch Prompting: Grouping thoughts together for evaluation reduces the number of API calls, improving efficiency.</li><li>Retry with Jitter: Introduces randomness in retries to prevent spikes in demand, ensuring smooth operation under high load.</li><li>Competing Consumers: Multiple workers process evaluation tasks concurrently, improving throughput and reducing latency.</li></ul><p>Now that we’ve explored the inner workings of the GRAFT system architecture and its event flow, it’s time to bring these concepts to life through code samples.</p><h3>Show me the code</h3><h4><strong>Orchestrator Module</strong></h4><p>The Orchestrator coordinates the entire GRAFT process, managing interactions between components like the Thought Generator, Thought Evaluator, and graph traversal algorithms. It oversees thought generation, evaluation, and graph updates, pruning non-viable paths to solve complex reasoning tasks efficiently.</p><p><strong>Key Operations</strong></p><ul><li><strong>Initialization<br></strong>This method sets up the Orchestrator with key components such as traversal algorithms (DFS, BFS, A*, MCTS), the LLM, prompt formatter, and task settings. It also initializes Redis connections for caching and communication, along with the Thought Generator and Thought Evaluator.</li></ul><pre>class Orchestrator:<br>    def __init__(self, traversal_algo, llm, prompt_formatter, depth, evaluate_sample, host, port, taskModelSpecs, breadth=3):<br>        self.traversal_algo = traversal_algo(self)<br>        self.llm = llm<br>        redis_conn = redis.StrictRedis(host=host, port=port, db=0)<br>        self.thoughtGenerator = ThoughtGenerator(redis_conn, taskModelSpecs, self.llm)<br>        self.thoughtEvaluator = ThoughtEvaluator(redis_conn, taskModelSpecs, self.llm)<br>        self.graph = Neo4jReasoningGraph()</pre><ul><li><strong>Solution Finding<br></strong>This method is responsible for initiating the search for a solution to a given problem. It starts with an empty list of partial solutions and initializes the graph structure. The traversal algorithm is then called to explore the problem space and find a solution.</li></ul><pre>def find_solution(self, problem):<br>    partialSolutions = [&#39;&#39;]<br>    self.graph.createProblemNode(problem)<br>    return self.traversal_algo.traverse(problem, partialSolutions)</pre><ul><li><strong>Thought Expansion and Graph Updating<br></strong>These methods updates the graph by adding new nodes (thoughts) along with their evaluation scores. This method integrates newly generated thoughts into the graph structure, allowing for a more informed search process.</li></ul><pre>def expand_thought_graph(self, evals, partialSolutions):<br>        self.graph.addValLabelsToGraphNodes(list(set(zip(evals, partialSolutions))), self.llm.answerThreshold())<br><br>def find_potential_solution_nodes(self, evals, partialSolutions):<br>    answer_threshold =  self.llm.answerThreshold()<br>    for value, thought  in list( set(zip(evals, partialSolutions))):<br>        prop_arr =  [s.strip() for s in thought.split(&#39;\n&#39;) if s]<br>        composite_key =  &quot;&lt;-&gt;&quot;.join(prop_arr)<br>        node = self.graph.addValueProperty(self.graph.salted_hash(composite_key),value)<br>        if (value &gt;= answer_threshold):<br>            if node:<br>                node.add_label(&quot;Answer&quot;)<br>                    self.graph.graph.push(node)</pre><h4><strong>ThoughtGenerator Module</strong></h4><p>This module creates new potential solutions, or “thoughts,” based on the current problem state. It uses Redis queues for distributed task execution, ensuring scalability. The module generates thoughts by enqueuing tasks via ThoughtGeneratorTask.generate_proposals_task, which are processed asynchronously.</p><p><strong>Key Operations</strong></p><ul><li><strong>Thought Generation<br></strong>This method is responsible for creating new potential solutions (thoughts) based on the current state of the problem.</li></ul><pre>def generate(self,  problem, partialSolutions): <br>        jobs = []<br>        # Enqueue tasks and store job objects<br>        for partialSolution in partialSolutions:<br>            job = self.proposals_q.enqueue(ThoughtGeneratorTask.generate, problem, partialSolution, self.taskModelSpecs.Proposal, self.llm )<br>            jobs.append(job)<br>        results = []<br>        for job in jobs:<br>            while not job.is_finished:<br>                time.sleep(0.1)<br>            results.append(job.result)<br>        flattened_res = list(itertools.chain(*results))<br>        return flattened_res</pre><ul><li><strong>Task Enqueueing:</strong> For each partial solution , a task is enqueued to generate new thoughts using the generate method of the ThoughtGeneratorTask class. This method is executed asynchronously, allowing multiple thoughts to be generated in parallel.</li><li><strong>Async Task Execution<br></strong>The ThoughtGeneratorTask class handles the actual generation of thoughts. It defines methods for generating thought proposals using different models (e.g., GPT-4, Claude).</li></ul><pre>class ThoughtGeneratorTask:<br>    @staticmethod<br>    def generate(problem,partialSolutions, model_type, llm):<br>        prompt_formatter = ThoughtGeneratorTask._get_model_and_formatter( model_type)<br>        propose_prompt = prompt_formatter.propose_prompt_wrap(problem, partialSolutions)<br>        response = llm.generate(propose_prompt, n=1)<br>        proposals = prompt_formatter.propose_prompt_unwrap(response)<br>        ThoughtGeneratorTask.graph.appendProposalsToGraph(partialSolutions, proposals)<br>        return [partialSolutions + _ + &#39;\n&#39; for _ in proposals]</pre><ul><li><strong>ThoughtGeneratorWorker Management<br></strong>The ThoughtGeneratorWorker class runs a worker process that listens for tasks in the Redis queue. This setup enables distributed processing, where multiple workers can be deployed to handle thought generation tasks concurrently. The worker listens to the proposals_q queue for incoming tasks. Multiple workers can be launched to process tasks in parallel, improving the scalability and responsiveness of the system.</li></ul><pre>class ThoughtGeneratorWorker:<br>  def run(redis_host, redis_port):<br>      listen = [ThoughtGeneratorTask.getProposalsQueueName()]<br>      redis_url = f&#39;redis://{redis_host}:{redis_port}&#39;<br>      conn = redis.from_url(https://medium.com/redis_url)<br>      with Connection(conn):<br>          worker = Worker(list(map(Queue, listen)))<br>          worker.work()</pre><h4><strong>ThoughtEvaluator Module</strong></h4><p>The ThoughtEvaluator assesses the quality and potential of generated thoughts, identifying promising paths and pruning less viable ones. It uses Redis queues for distributed evaluation tasks, enabling scalable handling of complex reasoning. The core method, evaluate, takes an input problem and partial solutions, enqueues tasks in Redis, and processes results asynchronously.</p><p><strong>Key Operations</strong></p><ul><li><strong>Thought Evaluation</strong><br>This method evaluates the generated thoughts to determine their potential effectiveness. The ThoughtEvaluator assigns scores to each partial solution, guiding the Orchestrator on which paths to prioritize.</li><li><strong>Task Enqueueing and Result Collection</strong><br>Each partial solution is enqueued for evaluation using the ValueTask.get_value method, allowing concurrent task processing. Results are collected asynchronously, improving efficiency.</li><li><strong>Caching</strong><br>Local caching prevents redundant evaluations of duplicate thoughts, optimizing the process.</li><li><strong>Async Task Execution</strong><br>The ValueTask class handles evaluation by formatting prompts, sending them to the LLM for self-evaluation, and processing the responses for the ThoughtEvaluator.</li></ul><pre>class ValueTask:<br>    @staticmethod<br>    def get_value(problem, partialSolutions , taskModelSpecs, llm):<br>        prompt_formatter = ValueTask._get_model_and_formatter( taskModelSpecs.Value)<br>        value_prompt, is_final_answer = prompt_formatter.value_prompt_wrap(problem, partialSolutions)<br>        if is_final_answer == True:<br>            return ValueTask.validate_solution(problem, partialSolutions, value_prompt, taskModelSpecs.FinalAnswer, llm)<br>        else:<br>            if (ValueTask.cache_value and value_prompt in prompt_formatter.value_cache):<br>                return prompt_formatter.value_cache[value_prompt]<br>            completion = llm.generate(value_prompt, n=1)           <br>       <br>            value_outputs = prompt_formatter.value_outputs_split(completion)            <br>            value = prompt_formatter.value_outputs_unwrap(problem, partialSolutions, value_outputs)<br>            if ValueTask.cache_value:<br>                prompt_formatter.value_cache[value_prompt] = value<br>            return (partialSolutions, value)</pre><h4>Graph Traversal Algorithms</h4><p>Graph traversal algorithms play a crucial role in navigating the graph structure to explore potential solutions effectively. These algorithms help in determining which paths to explore, backtrack, or prune, ensuring that the reasoning process is both thorough and efficient. Below, we outline the key graph traversal algorithms — Breadth-First Search (BFS), Depth-First Search (DFS), A*, and Monte Carlo Tree Search (MCTS) — each of which offers distinct advantages depending on the nature of the problem being solved.</p><p><strong>Breadth-First Search (BFS)<br></strong>BFS explores all nodes at the current depth level before moving to the next, ensuring the shortest or shallowest solution is found first. It’s complete and optimal for finding solutions in unweighted graphs but can be memory-intensive, especially in wide graphs. In GRAFT, BFS is ideal when it’s crucial to explore all possible solutions at a given depth before proceeding. Here is a code snippet of implemeting BFS using Recursion:</p><pre>class BFS(GraphTraversalAlgo):<br>    def __init__(self,orchestrator):<br>        super().__init__( orchestrator)<br>def traverse(self, problem, partialSolutions, traversal_step=0):<br>        if traversal_step &gt;= self.orchestrator.depth:<br>            return partialSolutions<br>        # generation<br>        new_partialSolutions = self.orchestrator.generate_thoughts( problem, partialSolutions) <br>        partialSolutionIndices = list(range(len(new_partialSolutions)))<br>        # evaluation<br>        evals = self.orchestrator.evaluate_thoughts(problem, new_partialSolutions)<br>        self.orchestrator.expand_though_graph(evals, new_partialSolutions)<br>        # prune thoughts<br>        promotedPartialSolutionIndices = sorted(partialSolutionIndices, key=lambda x: evals[x], reverse=True)[:self.orchestrator.breadth]<br>        promotedPartialSolutions = self.orchestrator.prune_thoughts(problem, new_partialSolutions,promotedPartialSolutionIndices, evals )<br>        #log<br>        self.orchestrator.log_thoughts(promotedPartialSolutions, new_partialSolutions, evals)<br>        return self.traverse(problem, promotedPartialSolutions, traversal_step=traversal_step + 1)</pre><p><strong>Depth-First Search (DFS)</strong></p><p>DFS explores as far down a branch as possible before backtracking, making it suitable for deep problem spaces. It uses less memory than BFS but risks getting stuck on single paths in deep or infinite graphs. In GRAFT, DFS is ideal for exploring extensive reasoning paths when the solution is likely to be found deeper in the graph. HEre is code snippet of DFS using Recursion:</p><pre>class DFS(GraphTraversalAlgo):<br>    def __init__(self,orchestrator):<br>        super().__init__( orchestrator)<br>        <br>    def traverse(self, problem, partialSolutions, traversal_step=0):<br>        if traversal_step &gt;= self.orchestrator.depth:<br>            return partialSolutions<br>        all_solutions = []<br>        for partialSolution in partialSolutions:<br>            # generation<br>            new_partialSolutions = self.orchestrator.generate_thoughts( problem, partialSolutions) <br>            partialSolutionIndices = list(range(len(new_partialSolutions)))<br>            # evaluation<br>            evals = self.orchestrator.evaluate_thoughts(problem, new_partialSolutions)<br>            self.orchestrator.expand_though_graph(evals, new_partialSolutions)<br>            # prune thoughts<br>            promotedPartialSolutionIndices = sorted(partialSolutionIndices, key=lambda x: evals[x], reverse=True)[:1]  # Depth-first takes one best option<br>            promotedPartialSolutions = self.orchestrator.prune_thoughts(problem, new_partialSolutions,promotedPartialSolutionIndices, evals )<br>            # log<br>            self.orchestrator.log_thoughts(promotedPartialSolutions, new_partialSolutions, evals)<br>            # recursive call for next level<br>            result = self.traverse(problem, promotedPartialSolutions, traversal_step=traversal_step + 1)<br>            all_solutions.extend(result)<br>        return all_solutions</pre><p><strong>A* Search</strong></p><p>A* is a heuristic-based search algorithm that combines BFS and DFS, using a cost function to guide the search towards the goal. It is both optimal and complete when the heuristic is admissible, meaning it doesn’t overestimate costs. A* is ideal in scenarios where a good heuristic efficiently directs the search toward promising solutions.</p><pre>class AStar(GraphTraversalAlgo):<br>    def __init__(self,orchestrator):<br>        super().__init__( orchestrator)<br><br>def traverse(self, problem, partialSolutions, traversal_step=0):<br>        open_list = []<br>        for ps in partialSolutions:<br>            heapq.heappush(open_list, (0, ps))  # Start with zero cost<br>        while open_list:<br>            cost, current_solution = heapq.heappop(open_list)<br>            if traversal_step &gt;= self.orchestrator.depth:<br>                return [current_solution]<br>            # generation<br>            new_partialSolutions = self.orchestrator.generate_thoughts( problem, [current_solution]) <br>            partialSolutionIndices = list(range(len(new_partialSolutions)))<br>            # evaluation<br>            evals = self.orchestrator.evaluate_thoughts(problem, new_partialSolutions)<br>            self.orchestrator.expand_though_graph(evals, new_partialSolutions)            <br>            # calculate costs<br>            for i in partialSolutionIndices:<br>                heuristic = self.calculate_heuristic(new_partialSolutions[i])<br>                total_cost = cost + evals[i] + heuristic<br>                heapq.heappush(open_list, (total_cost, new_partialSolutions[i]))<br>            # prune thoughts<br>            promotedPartialSolutionIndices = sorted(partialSolutionIndices, key=lambda x: evals[x], reverse=True)[:self.orchestrator.breadth]<br>            promotedPartialSolutions = self.orchestrator.prune_thoughts(problem, new_partialSolutions,promotedPartialSolutionIndices, evals )<br>            # log<br>            self.orchestrator.log_thoughts(promotedPartialSolutions, new_partialSolutions, evals)           <br>            traversal_step += 1</pre><p><strong>Monte Carlo Tree Search (MCTS)<br></strong>Monte Carlo Tree Search (MCTS) is a heuristic algorithm that uses random sampling to explore large and complex search spaces, often used in decision-making problems like games. It balances exploration of new paths with exploiting known promising ones, adapting to various problem structures. MCTS is highly scalable, as it can be tuned by adjusting the number of simulations or balancing exploration and exploitation. In GRAFT, MCTS is useful for navigating vast search spaces where exhaustive exploration isn’t feasible, and random sampling helps focus on high-value areas.</p><pre>class MCTS(GraphTraversalAlgo):<br>    def __init__(self,orchestrator):<br>        super().__init__( orchestrator)     <br>      <br>def traverse(self, problem, partialSolutions):<br>        root = MCTSNode(state=MCTSState(problem, &#39;&#39;, self.orchestrator.breadth))<br>        <br>        for _ in range(self.orchestrator.depth):<br>            node = self.selection(root)<br>            if not node.is_fully_expanded():<br>                node = self.expansion(node)<br>            reward = self.simulation(node.state)<br>            self.backpropagation(node, reward)<br>            self.orchestrator.log_thoughts([node.state.partial_solution], [node.value], [node.visits])<br>            <br>        return self.best_solution(root)<br>    def selection(self, node):<br>        while node.children:<br>            node = node.best_child()<br>        return node<br>    def expansion(self, node):<br>        new_partialSolutions = self.orchestrator.generate_thoughts( node.state.problem, [node.state.partial_solution]) <br>        <br>        for solution in new_partialSolutions:<br>            new_state = MCTSState(node.state.problem, solution, self.orchestrator.breadth)<br>            child_node = MCTSNode(state=new_state, parent=node)<br>            node.children.append(child_node)<br>        return node.children[-1]<br>    def simulation(self, state):<br>        new_partialSolutions = self.orchestrator.generate_thoughts( state.problem, [state.partial_solution]) <br>        evals = self.orchestrator.evaluate_thoughts(state.problem, new_partialSolutions)<br>        self.orchestrator.expand_though_graph(evals, new_partialSolutions)        <br>        return max(evals)<br>    def backpropagation(self, node, reward):<br>        while node:<br>            node.visits += 1<br>            node.value += reward<br>            node = node.parent<br>    def best_solution(self, root):<br>        return max(root.children, key=lambda child: child.visits).state.partial_solution<br><br>class MCTSState:<br>    def __init__(self, problem, partial_solution, breadth):<br>        self.problem = problem<br>        self.partial_solution = partial_solution<br>        self.breadth = breadth<br><br>class MCTSNode:<br>    def __init__(self, state, parent=None):<br>        self.state = state<br>        self.parent = parent<br>        self.children = []<br>        self.visits = 0<br>        self.value = 0<br>    def is_fully_expanded(self):<br>        return len(self.children) == self.state.breadth<br>    def best_child(self, c_param=1.4):<br>        choices_weights = []<br>        for child in self.children:<br>            if child.visits &gt; 0:<br>                exploitation = child.value / child.visits<br>                exploration = c_param * math.sqrt((2 * math.log(self.visits) / child.visits))<br>                choices_weights.append(exploitation + exploration)<br>            else:<br>                # Assign a high value to ensure unvisited nodes are selected<br>                choices_weights.append(float(&#39;inf&#39;))<br>        <br>        return self.children[choices_weights.index(max(choices_weights))]</pre><h4><strong>Solution Validation Module</strong></h4><p>This module validates potential solutions generated by the reasoning process, ensuring each meets the correctness criteria before acceptance. It uses Redis for task queuing and distributed processing, enabling efficient, parallel validation at scale.</p><p><strong>Key Operations</strong></p><ul><li><strong>SolutionValidatorTask</strong><br>The SolutionValidatorTask class defines validation tasks, selecting the appropriate LLM (e.g., GPT-4, Claude) and prompt formatter. It generates completions from the LLM, processes outputs, and checks if the solution meets the problem’s requirements. The SolutionValidatorWorker listens for tasks in the Redis queue, allowing distributed workers to validate solutions concurrently for improved scalability.</li></ul><pre>class SolutionValidatorTask:<br>    <br>    @staticmethod<br>    def validate(problem, partialSolutions, prompt, model_type, llm):<br>        formatter = SolutionValidatorTask._get_model_and_formatter(model_type)<br>        completion = llm.generate(prompt, n=1)<br>        value_outputs = formatter.value_outputs_split(completion)   <br>        value = formatter.value_outputs_unwrap(problem, partialSolutions, value_outputs)<br>        return partialSolutions, value<br><br>class SolutionValidatorWorker:<br>    def run(redis_host, redis_port):<br>        listen = [SolutionValidatorTask.getValuesQueueName()]<br>        redis_url = f&#39;redis://{redis_host}:{redis_port}&#39;<br>        conn = redis.from_url(https://medium.com/redis_url)<br>        with Connection(conn):<br>            worker = Worker(list(map(Queue, listen)))<br>            worker.work()</pre><h4><strong>Neo4jReasoningGraph Module</strong></h4><p>To effectively manage and persist the complex relationships between thoughts, the Orchestrator class relies on the Neo4jReasoningGraph to externalize and handle the state of the reasoning graph. This class designed to externalize and manage the state of the reasoning graph used in the GRAFT framework. This externalization of the reasoning state allows for better scalability, persistence, and analysis of the decision-making process.</p><p><strong>Key Operations</strong></p><ul><li><strong>AppendProposalsToGraph<br></strong>The appendProposalsToGraph method adds new thought proposals to the graph by linking them to existing parent nodes, creating a coherent decision-making structure. It identifies the parent node using a hashed key and appends new child nodes. To avoid duplicates, it checks for existing nodes with the same key before adding new ones.</li></ul><pre>def appendProposalsToGraph(self, parentProposal, proposals):<br>    if self.rootNode == &#39;&#39;:<br>        m = NodeMatcher(self.graph)<br>        node = m.match(&quot;Thought&quot;, root=&quot;true&quot;).first()<br>        self.rootNode = node<br><br>    prop_arr = [s.strip() for s in parentProposal.split(&#39;\n&#39;) if s]<br>    if len(prop_arr) == 0:<br>        parentProposal = &#39;&#39;<br>    else:<br>        parentProposal = &quot;&lt;-&gt;&quot;.join(prop_arr)<br>    parent_hashed_key = self.salted_hash(parentProposal)<br>    parentNode = self.getNode(parent_hashed_key)<br>    if not parentNode:<br>        parentNode = self.rootNode<br>    for proposal in proposals:<br>        proposal = proposal.strip()<br>        if proposal:<br>            prop_arr.append(proposal)<br>            composite_key = &quot;&lt;-&gt;&quot;.join(prop_arr)<br>            prop_arr.remove(proposal)<br>            hashed_key = self.salted_hash(composite_key)<br>            childNode = self.getNode(hashed_key)<br>            if not childNode:<br>                self.createChildNode(parentNode, thought=proposal, parentThought=parentProposal, dict_key=hashed_key)<br>            else:<br>                print(f&quot;duplicate node eliminated: {composite_key}&quot;)</pre><h4>Part 3 — Operationalizing GRAFT using Kubernetes</h4><p>With the architecture and event flow of GRAFT now thoroughly examined, and having seen how to code the core modules, it’s clear that managing such a complex system manually poses significant challenges. As the system scales to handle more demanding thought graphs, efficient orchestration becomes crucial.</p><p>In <a href="https://medium.com/p/7753ec521831">Part 3</a>, we will delve into the platform engineering aspect of deploying the GRAFT framework using Kubernetes. We’ll focus on how Kubernetes and its ecosystem can manage and optimize the GRAFT system efficiently, addressing operational complexities and leveraging features like containerization, Kubernetes Operators, and Kubernetes Event-Driven Autoscaling (KEDA). These tools will help automate and streamline deployment, configuration management, scaling, and monitoring, ensuring the GRAFT system remains robust, scalable, and cost-effective as it handles dynamic workloads effortlessly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0b5db5a7aea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GRAFT: Graph-Augmented Framework of Thought — Part 1]]></title>
            <link>https://medium.com/@asheesh.goja/graft-graph-augmented-framework-of-thought-part-1-92551b5969e9?source=rss-8b819656b4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/92551b5969e9</guid>
            <dc:creator><![CDATA[Asheesh Goja]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 18:42:38 GMT</pubDate>
            <atom:updated>2025-07-23T18:46:31.636Z</atom:updated>
            <content:encoded><![CDATA[<h3>GRAFT: Graph-Augmented Framework of Thought — Part 1</h3><h4>Prompt Engineering</h4><h3>Introduction</h3><p>As LLMs have revolutionized artificial intelligence, their impressive capabilities in areas like language understanding and generation have been matched by shortcomings in complex reasoning. This 3-part blog series, introduces the Graph-Augmented Framework of Thought (GRAFT), an innovative approach that augments LLM prompting with graph-based reasoning to enable them to tackle multi-step problems more effectively. We’ll explore this new paradigm from three key engineering perspectives: prompt engineering, software engineering, and platform engineering with Kubernetes. (<a href="https://github.com/asheeshgoja/graft"><em>Source Code</em></a>)</p><p>In Part 1, we dive into the limitations of current autoregressive LLMs when it comes to long-range reasoning, and explore how advanced <strong>prompt engineering</strong> strategies like Chain-of-Thought and Tree of Thoughts attempt to overcome these challenges. We then introduce GRAFT and explain how it builds upon these techniques, using a graph structure to flexibly explore, combine and refine potential solution paths. We will examine the prompt engineering aspects of this approach, detailing how to effectively create, evaluate, and refine the prompts that guide the reasoning process.</p><p><a href="https://medium.com/p/f0b5db5a7aea">Part 2</a> shifts focus to the <strong>software engineering</strong> patterns needed to implement GRAFT in a modular, parallelizable, and scalable manner. We break down core components like the Orchestrator, Thought Generator, and Solution Validator, and show how externalizing state to graph databases, caches and queuing systems enables the efficient distribution and processing of complex reasoning workloads. Code examples demonstrate the practical aspects of architecting and implementing the key modules, and integrating with tools like Neo4j and Redis.</p><p>Finally, in <a href="https://medium.com/p/7753ec521831/">Part 3</a> we tackle the <strong>platform engineering</strong> challenges of deploying GRAFT on Kubernetes to minimize operational complexity and maximize performance. We explore how containerizing local LLMs and GRAFT components, automating management with Kubernetes Operators, and dynamically scaling with KEDA allows the framework to robustly handle the demands of advanced reasoning tasks in production environments. A step-by-step guide walks through installing and running an example GRAFT implementation, illustrating the platform engineering principles in action.</p><p>By the end of this series, you will gain a well-rounded understanding of GRAFT from the perspectives of prompt engineering, software design, and infrastructure management. The included reference code and deployment instructions aim to provide hands-on experience in augmenting LLMs to solve complex real-world problems using this approach.</p><p>So let’s dive in and see how GRAFT can expand the boundaries of what LLMs can do! In Part 1, we’ll first examine the prompt engineering strategies that set the stage for graph-based reasoning.</p><h4>The Problem with Autoregressive LLMs and the Promise of Prompt Engineering</h4><p>The autoregressive architecture of LLMs is a double-edged sword. While it enables high-quality language generation by leveraging the context of preceding tokens, it also imposes a strict linearity that hinders complex reasoning tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghv-eIqtv_wQqrE6r8UQOg.png" /></figure><p>The LLM autoregressive inference process begins with tokenization, where the input prompt is converted into a sequence of tokens that the model can process. This tokenized input is then passed through the model in a single forward pass during the <strong>prefill</strong> stage, generating an initial output token. The core of the process lies in the <strong>decode</strong> stage, where the model enters an autoregressive loop. In each iteration, the model takes the previously generated tokens (including the initial input and all subsequently generated tokens) and uses this context to predict the next token in the sequence. This new token is then appended to the existing sequence, and the process repeats. The model continues this token-by-token generation, with each new token influencing the prediction of the next, until it reaches a stopping condition such as generating an end-of-sequence token or hitting a predefined maximum length. This autoregressive approach allows the model to maintain coherence and context throughout the generation process, as each new token is produced with consideration of all previous tokens.</p><p>In problem-solving scenarios that demand the ability to backtrack, reassess, and revise earlier decisions, this autoregressive nature of LLMs falls short. Once a token is generated, the model cannot revisit it, leading to a cascading effect where a single error can propagate through the entire sequence, resulting in increasingly incoherent outputs. This limitation is particularly detrimental in tasks requiring long-range reasoning, where the ability to refine earlier steps is crucial for accurate and coherent results. The linear, one-step-at-a-time approach of autoregressive models constrains their ability to perform exploratory reasoning, considering multiple potential solutions before converging on the optimal one.</p><p><strong>Dual-process theory</strong> in human cognition offers a lens to understand these limitations. It posits two distinct thinking systems: System 1, which is fast, automatic, and relies on heuristics and pattern recognition; and System 2, which is slow, deliberate, and employed for tasks requiring deep reasoning and planning. LLMs, due to their autoregressive nature, primarily align with System 1 thinking. They excel at generating fluent text and providing quick, intuitive responses, but struggle with tasks demanding System 2 thinking, such as solving complex puzzles or making decisions involving trade-offs across a sequence of actions.</p><p>However, advanced prompting strategies offer a promising avenue to bridge this gap and enable LLMs to tackle more complex reasoning tasks. Techniques like Chain-of-Thought (CoT) and Tree of Thoughts (ToT) aim to structure the reasoning process in a way that encourages deeper exploration of possible solutions.</p><p><strong>Advanced Prompt Engineering Strategies<br></strong>To bridge the gap between LLMs’ strengths and the demands of System 2 tasks, advanced prompting strategies like Chain-of-Thought (CoT) and Tree of Thoughts (ToT) have been developed. These strategies aim to structure the reasoning process in a way that encourages deeper exploration of possible solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDhYg4ZT19YVLcLXcc7LWQ.png" /></figure><ul><li><strong>Chain-of-Thought (CoT)</strong>: CoT involves breaking down a problem into a sequence of reasoning steps, guiding the model through a structured thought process. This approach helps mitigate the limitations of the autoregressive architecture by imposing a more deliberate structure on the generation process.</li><li><strong>CoT-Self Consistency (CoT-SC): </strong>This strategy further refines CoT approach by employing an ensemble method that considers multiple independent chains to resolve ambiguities.</li><li><strong>Tree of Thoughts (ToT)</strong>: ToT extends the CoT approach by organizing thoughts into a hierarchical tree structure. Each branch of the tree represents a different reasoning path, allowing the model to explore multiple potential solutions simultaneously. This approach introduces the possibility of backtracking and revising earlier decisions, addressing some of the limitations of traditional LLMs.</li></ul><p><strong>Limitations of ToT<br></strong>While ToT improves upon LLM prompting strategies, it has some limitations. The primary drawback is its rigid hierarchical structure. Each branch of the tree is independent, preventing easy interaction or influence between thoughts on different branches. This can constrain the model’s ability to effectively explore the full problem space, especially when cross-pollination of ideas or merging insights from different paths is required.<br>Moreover, the tree structure is still inherently sequential, with each thought dependent on the previous one in its branch. There is limited flexibility to revisit and revise earlier thoughts once a branch is chosen, potentially leading to suboptimal solutions in complex reasoning tasks where the optimal solution may lie at the intersection of multiple reasoning paths.</p><h4>GRAFT: Augmenting ToT with Graph-Based Reasoning</h4><p>To overcome the limitations of ToT, GRAFT (Graph-Augmented Framework of Thought), enhances the ToT strategy by incorporating graph-based reasoning. GRAFT transforms the rigid hierarchical tree structure of ToT into a more flexible, interconnected graph. This transformation allows for greater exploration, recombination, and refinement of thoughts across different paths, enabling a more dynamic and robust problem-solving process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJ4SsW88eY7izHdDEDpt6A.png" /></figure><p>In GRAFT, each node in the graph represents a thought or partial solution, and edges between nodes represent possible transitions or relationships between these thoughts. Unlike the fixed branches of a tree, the graph structure in GRAFT allows for connections between any nodes, enabling the model to explore multiple reasoning paths simultaneously and merge insights from different directions. This flexibility is particularly beneficial in tasks that require non-linear reasoning, cross-referencing of ideas, or integration of disparate insights.</p><h4>The Architecture and Operation of GRAFT</h4><p>By integrating graph-based reasoning into the ToT strategy, GRAFT overcomes many of the limitations associated with hierarchical and sequential problem-solving methods. Let’s see how GRAFT’s architecture enables a more dynamic and flexible reasoning process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_nsTm2urF4ULAuNUd6U3ZA.jpeg" /></figure><p><strong>Core components</strong></p><ol><li><strong>Thought Generator: </strong>The Thought Generator is the engine that drives the expansion of the reasoning graph. Starting from an initial state or root node, it generates new thoughts or partial solutions that represent possible next steps in the reasoning process. These thoughts are added as new nodes in the graph, effectively expanding the search space. The Thought Generator leverages techniques from generative modeling to produce diverse and contextually relevant thoughts, ensuring that the model explores a wide range of possibilities.</li><li><strong>Thought Evaluator: </strong>Once new thoughts are generated, the Thought Evaluator steps in to assess their potential. Using the underlying LLM, the Thought Evaluator wraps each partial solution in a prompt and evaluates it based on its likelihood to contribute to the final goal. This evaluation is critical in determining the direction of the search process, as thoughts are classified into categories. The Thought Evaluator’s assessments guide the exploration of the graph, helping to focus computational resources on the most promising paths.</li><li><strong>Solution Validator: </strong>The Solution Validator is responsible for verifying the correctness of complete solution paths within the graph. Once a path from the root node to a leaf node is identified as a potential solution, the Solution Validator checks it against the problem’s requirements. This validation process ensures that the final output meets the desired criteria, serving as a final safeguard before the solution is accepted. Techniques from verifiable computing can enhance this component, providing robust and reliable validation.</li><li><strong>Orchestrator: </strong>The Orchestrator serves as the central controller that manages the overall reasoning process. It coordinates the actions of the Thought Generator, Thought Evaluator, and Solution Validator, making strategic decisions about which paths to explore, which nodes to expand, and which branches to prune. The Orchestrator leverages advanced graph traversal algorithms such as Depth-First Search (DFS), Breadth-First Search (BFS), A*, and Monte Carlo Tree Search (MCTS) to efficiently navigate the graph, optimizing the search trajectory based on feedback from the Thought Evaluator.</li><li><strong>Graph Search Algorithms: </strong>The underlying structure of GRAFT is a graph, which allows for complex interconnections between nodes (thoughts). Various graph search algorithms are employed to traverse this structure. These algorithms, which include DFS, BFS, A*, and MCTS, determine how the graph is explored and which nodes are prioritized for expansion. The choice of algorithm can be tailored to the specific characteristics of the problem being solved, providing flexibility and adaptability in the reasoning process.</li></ol><p>To better understand how GRAFT works in practice, it’s helpful to examine its application to a specific problem. The framework’s ability to break down complex reasoning tasks into structured, manageable steps makes it an ideal solution for problems that require multi-step calculations and decision-making. One such example is the classic <a href="https://en.wikipedia.org/wiki/24_(puzzle)">Game of 24</a> puzzle, where the objective is to manipulate four given numbers using arithmetic operations to reach a total sum of 24.</p><h4>Solving the Game of 24</h4><p>Let’s see how the GRAFT framework solves the “Game of 24” using the core components. The challenge is to arrange four numbers, a, b, c, d, with arithmetic operations to get 24. The GRAFT approach systematically breaks down the problem into manageable steps, applying its components to explore various solution paths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FWil1d6x-Tishs020i0Sg.png" /></figure><ol><li><strong>Thought Generator:</strong> The process starts with a root node that holds the four numbers: a, b, c, d. The Thought Generator<strong> </strong>creates new thought branches by applying basic arithmetic operations between these numbers. For example, it might generate expressions like a + b or a * b and then proceed with the remaining numbers c and d. These operations create partial solutions, represented as new nodes in the graph, expanding the search space.</li><li><strong>Thought Evaluator:</strong> Assesses each generated expression to determine its potential for solving the problem. For example, if the expression (a + b) results in a value far from 24, the evaluator might categorize this path as &quot;Impossible.&quot; Alternatively, if it sees potential in combining c and d with the partial result, it marks the path as &quot;Likely.&quot; This evaluation helps focus the search on promising nodes.</li><li><strong>Orchestrator</strong>: Manages the overall exploration of the graph. It receives input from the Thought Evaluator and decides which nodes to further expand and which to prune. For instance, if an expression like (a + b) + c is evaluated as promising, the Orchestrator will direct the Thought Generator to explore further operations with d. On the other hand, unpromising paths, such as expressions yielding values too large or too small, are pruned to reduce complexity.</li><li><strong>Graph Search Algorithms</strong> : Control how the graph is traversed. Using algorithms like DFS, A* or Monte Carlo Tree Search (MCTS), the Orchestrator ensures that the most promising paths are explored first. This optimization allows GRAFT to efficiently home in on solutions, like (a + b) + (c + d) = 24, without getting stuck in unfruitful paths.</li><li><strong>Solution Validator:</strong> Once a potential solution path is found, such as (a + b) + (c + d) = 24, the Solution Validator steps in to check the correctness. It verifies that all four numbers a, b, c, d have been used exactly once and that the final result equals 24. If the solution is valid, the process concludes, and the correct expression is returned.</li></ol><p>By integrating these five components, GRAFT not only solves the Game of 24 but can also handle a wide array of complex reasoning tasks such as</p><ul><li>Mathematical Problem Solving</li><li>Creative Writing</li><li>Logical Reasoning</li><li>Text Summarization</li><li>Question Answering</li></ul><p>Now let’s explore the specific technical advantages that this innovative framework brings to the table.</p><ol><li><strong>Parallel Exploration</strong>: By representing the reasoning process as a graph, GRAFT allows for the simultaneous evaluation of multiple solution paths. This parallelism significantly improves the efficiency of the reasoning process, as it enables the model to explore a broader range of possibilities without being constrained by a linear or hierarchical structure.</li><li><strong>Backtracking and Lookahead</strong>: GRAFT’s graph-based structure enhances the model’s ability to backtrack and use lookahead techniques, which are crucial for navigating complex reasoning tasks. The graph structure allows the model to revisit and revise earlier decisions, explore alternative paths, and merge insights from different branches. This capability mimics advanced human problem-solving strategies, where the ability to reconsider previous steps and anticipate future challenges is essential for finding optimal solutions.</li><li><strong>Enhanced Scalability</strong>: GRAFT’s combination of graph structures and parallel processing capabilities makes it highly scalable. The framework can efficiently handle large and complex problem spaces by distributing the computation across multiple nodes and connections. This scalability makes GRAFT adaptable to a wide range of scenarios, from simple tasks to complex, multi-step reasoning challenges.</li><li><strong>Improved Accuracy</strong>: The systematic evaluation and refinement of partial solutions through graph traversal algorithms reduce the likelihood of errors and improve the accuracy of the final solution. GRAFT’s iterative feedback loop helps fine-tune the reasoning process, ensuring more precise outcomes. The framework’s ability to integrate insights from different branches of the graph further enhances its accuracy, as it allows the model to consider a wider range of possibilities before converging on a final solution.</li><li><strong>Adaptability</strong>: GRAFT’s adaptability is another significant advantage. The framework can be tailored to various problem types by integrating different graph search algorithms, such as BFS, DFS, A*, or MCTS. This adaptability makes GRAFT a versatile tool for a wide range of applications, from simple tasks like text generation to complex, multi-step reasoning challenges that require sophisticated problem-solving strategies.</li></ol><p>We’ve covered a lot of theoretical ground discussing GRAFT and its approach to complex reasoning. But now, let’s shift gears and see how it actually performs in a real-world scenario.</p><h4>Demo Time</h4><p>In this demo, we’ll see how GRAFT tackles a classic game of 24, showcasing its ability to navigate the problem space, generate and evaluate solution paths, and arrive at the correct answer.</p><ol><li>Run this <a href="https://gist.github.com/asheeshgoja/6dce3d0febe8ee132e502ce8a6302392">docker-compose</a> file</li></ol><pre>wget https://gist.githubusercontent.com/asheeshgoja/6dce3d0febe8ee132e502ce8a6302392/raw/b228f7bf8fe10c8bde972ff79b04176295d2530c/graft-demo-docker-compose.yaml<br>docker-compose -f graft-demo-docker-compose.yaml up</pre><p>This will pull and start three containers — graft-core, thought-bus and thought-db</p><pre>docker ps<br>72c1a2bd5e9c   asheeshgoja/graft-core:latest     &quot;python -u /graft/te…&quot;   48 seconds ago       Up 47 seconds                 5000/tcp                                                                                         graft-core<br>4bb6272690dc   redis/redis-stack-server:latest   &quot;/entrypoint.sh&quot;         About a minute ago   Up About a minute (healthy)   0.0.0.0:6379-&gt;6379/tcp, :::6379-&gt;6379/tcp                                                        thought-bus<br>588a84ebc679   neo4j:5.23.0                      &quot;tini -g -- /startup…&quot;   About a minute ago   Up About a minute (healthy)   0.0.0.0:7474-&gt;7474/tcp, :::7474-&gt;7474/tcp, 7473/tcp, 0.0.0.0:7687-&gt;7687/tcp, :::7687-&gt;7687/tcp   thought-db</pre><p>2. Run the graft-test.py.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47aab34c6a5263785760af810abeb973/href">https://medium.com/media/47aab34c6a5263785760af810abeb973/href</a></iframe><pre>python3 graft-test.py &quot;1 1 11 11&quot;</pre><p>This will ask the GRAFT runtime to arrange the “1 1 11 11” using the four arithmetic operators (+, -, x , / ) to obtain 24, by using each number only once .</p><p>3. Wait for graft to find the solution. You will see this</p><pre>Sent problem &#39;1 1 11 11&#39; , to GRAFT for a solution<br><br>1 + 1 = 2 (left: 2 11 11)  <br>2 + 11 = 13 (left: 11 13)<br>11 + 13 = 24 (left: 24)<br> ((1 + 1) + 11) + 11 = 24</pre><p>You will also be able to see realtime DAGs and logs of partial solution paths using the <a href="https://neo4j.com/download/">Neo4J Desktop</a> , <a href="https://redis.io/insight/">Redis Insights</a> by connecting to following ports</p><pre>Neo4J<br>neo4j@bolt://localhost:7687<br><br>Redis<br>127.0.0.1:6379</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GqXA-HZKePKgRzAM2MsMA.gif" /></figure><p>If this demo sparks your interest, stay tuned for Part 2, where I’ll guide you step-by-step through building and deploying the GRAFT framework, including setting up key components, implementing the modules, and using it to tackle complex problems.</p><h4>Part 2: Implementing GRAFT</h4><p>In the <a href="https://medium.com/p/f0b5db5a7aea/">second part</a> of this series, we will transition from theory to practice by guiding you through the steps to build, install, and run the code for the GRAFT framework. This hands-on section will provide detailed instructions on setting up the required components, implementing the key modules, and deploying the system in a scalable and efficient manner.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92551b5969e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bits, FLOPS, and Watts: A Systems-Level Perspective of Scaling LLMs — Part 2]]></title>
            <link>https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-2-ce397041dec2?source=rss-8b819656b4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce397041dec2</guid>
            <dc:creator><![CDATA[Asheesh Goja]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 20:08:08 GMT</pubDate>
            <atom:updated>2026-03-17T18:28:02.587Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bits, FLOPS, and Watts: A Systems-Level Perspective of Scaling LLMs — Part 2</h3><h4>The Walls of Silicon</h4><h3>Introduction</h3><p>In <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-1-34ef63d95b6c"><strong>Part 1</strong></a>, we explored the algorithmic foundations driving LLM scaling; now, we shift our focus to the silicon that underpins it. This brings us to the <strong>“</strong>Walls of Silicon<strong>”</strong> — the fundamental physical constraints that define the performance and scalability of GPU-accelerated compute: the Memory Wall, Power Wall, and Interconnect Wall. These walls arise at the intersection of Transformer algorithmic complexity and silicon physics, reshaping the calculus of bits, FLOPS, and watts that drives LLM performance.<br><em>(</em><a href="https://github.com/asheeshgoja/bits-flops-and-watts/raw/main/Bits,%20FLOPS,%20and%20Watts_%20A%20Systems-Level%20Perspective%20of%20Scaling%20LLMs.pdf"><em>PDF version the paper</em></a><em>)</em></p><p>To understand why these barriers inevitably arise, we first need to examine how GPUs operate at a fundamental level. By grasping the intricacies of GPU architecture and execution flows, we can pinpoint precisely where LLM workloads stress hardware resources and how that pressure eventually hits the three Scaling Walls. Let’s begin by exploring the internal architecture of a modern NVIDIA GPU.</p><h3>The GPU Architecture</h3><p>NVIDIA GPUs are built around <a href="https://developer.nvidia.com/blog/nvidia-hopper-architecture-in-depth/#h100_sm_key_feature_summary"><strong>Streaming Multiprocessors (SMs)</strong></a>, each housing a diverse set of computational units and on-chip caches. These SMs are the backbone of parallel processing, with specialized units handling different aspects of the workload:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ayws1Kp_SmLobMAvDKcmAA.png" /></figure><ul><li><strong>CUDA Cores</strong> execute general-purpose arithmetic and memory operations, such as addition, multiplication, and data movement. These cores are highly pipelined to support a massive number of concurrent, small-scale computations.</li><li><strong>Tensor Cores</strong> specialize in matrix multiply-accumulate (MMA) operations, crucial for deep learning workloads. By fusing multiplication and addition into a single cycle, they significantly boost throughput, particularly for reduced-precision formats like FP16 and BF16.</li><li><strong>Special Function Units (SFUs)</strong> accelerate transcendental functions, including trigonometric and exponential calculations, making them vital for activation functions and other mathematical transformations in neural networks.</li><li><strong>LD/ST (Load/Store) Units</strong> manage memory operations, transferring data between the SMs and the GPU’s memory hierarchy. These units fetch data from either the low-latency on-chip caches (L1, shared memory) or the high-capacity but higher-latency global memory, typically High Bandwidth Memory (HBM).</li></ul><p>Each SM also includes <strong>local register files</strong> to store temporary variables for active threads, along with a <strong>fast L1 cache and shared memory region</strong> for efficient intra-thread block communication. All SMs share a larger <strong>L2 cache</strong>, which serves as an intermediary between the compute units and the global HBM. This multi-tiered <a href="#7840">memory hierarchy</a> — spanning registers, caches, and HBM — ensures that data remains as close to the compute units as possible, reducing global memory latency and enabling massive parallel throughput.</p><h4>GPU Execution Flow</h4><p>A GPU executes workloads using thousands of concurrent threads, organized hierarchically into <strong>warps, thread blocks, and grids</strong> to maximize parallelism.</p><ul><li><strong>Warp</strong>: The fundamental execution unit in CUDA, consisting of 32 threads. Each SM can run 2048 threads simultaneously, grouping them into multiple warps.</li><li><strong>Thread Block</strong>: A collection of threads, grouped as warps, that execute together on a single SM. All threads in a block have access to the same shared memory and can synchronize with each other.</li><li><strong>Grid</strong>: A higher-level grouping of multiple thread blocks distributed across the GPU’s many SMs, working together to complete execution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6fziXnl7PvU_DlUVJJvZQ.png" /></figure><p>At a high level, a CUDA program launches <strong>kernels</strong> (parallel functions) that execute across a grid of thread blocks. All threads in a grid execute the same kernel. This follows the Single-Instruction, Multiple-Thread (<a href="https://en.wikipedia.org/wiki/Single_instruction,_multiple_threads"><strong>SIMT</strong></a>) paradigm, where all threads within a warp execute the same instruction but operate on different data elements. SIMT extends <a href="https://en.wikipedia.org/wiki/Single_instruction,_multiple_data">SIMD</a> (Flynn’s Taxonomy) by reducing instruction-fetch overhead, enabling efficient execution across thousands of threads.</p><p><strong>Warp Scheduler<br></strong>To keep GPU arithmetic units busy and hide memory latency, the warp scheduler on each SM interleaves instructions from different warps each clock cycle. The scheduler can seamlessly switch between concurrent warps from any block within any kernel without incurring any overhead. If a warp stalls due to an instruction that can’t execute immediately, the scheduler switches to a ready warp, one whose next instruction has all required data available. This efficient warp-switching helps mask instruction latency when enough warps are available on the SM. When multiple warps are ready, the SM uses a scheduling policy to select which warp’s instruction to fetch next. This concurrency model is one of the key reasons GPUs excel at matrix and tensor workloads as thousands of lightweight threads can be orchestrated to deliver immense throughput.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhw_ngH004rqNwVAg6VHcQ.png" /><figcaption><a href="https://www.3dgep.com/cuda-thread-execution-model/">Source</a></figcaption></figure><p>However, managing this parallelism is not without its challenges. When threads within the same warp diverge due to conditional statements, the warp must serialize different execution paths. This phenomenon, called “<a href="https://class.ece.iastate.edu/tyagi/cpre581/papers/HPCA14WarpDivergence.pdf"><strong>warp divergence</strong></a>,” leads to underutilization of SM cores. Consequently, memory access patterns and branching structures become important design considerations for high-performance kernels.</p><p>Once a kernel completes, results are written back to global memory (HBM or system memory via PCIe/NVLink), where they can be accessed by subsequent kernels or by the CPU. The GPU’s memory subsystem, including the register files, shared memory, L1 cache, L2 cache, and HBM, is carefully designed to keep data movement efficient, but this is exactly where some of the fundamental constraints of scaling, particularly with <a href="#dae1">memory bandwidth</a> and capacity show up.</p><h4>Transformers and Tensor Cores</h4><p><a href="https://medium.com/@asheesh.goja/34ef63d95b6c#6c46">Transformer</a>s are ideally suited to exploit the <strong>Tensor Core</strong> units in NVIDIA GPUs. Transformers rely heavily on matrix multiplications to compute attention, feed-forward transformations, and gradient updates during backpropagation. Each <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#3fba">multi-head attention layer</a> involves large matrix multiplications of the input embedding matrix with query, key, and value weight matrices. Similarly, <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#acec">FFNs</a> perform matrix multiplications interspersed with non-linear activations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MmLzHLKabl13r-9q.png" /><figcaption><a href="https://developer.nvidia.com/blog/programming-tensor-cores-cuda-9/#what_are_tensor_cores">Source</a></figcaption></figure><p>Since Tensor Cores can deliver up to an 8x <a href="https://docs.nvidia.com/deeplearning/performance/mixed-precision-training/index.html">speedup</a> for half-precision FP16 matrix operations compared to standard FP32 operations, they have become vital for both training and inference at scale. However, to maximize throughput on Tensor Cores, data dimensions must align with certain constraints. Tensor Cores achieve optimal performance when operations align with specific memory <a href="https://docs.nvidia.com/deeplearning/performance/dl-performance-getting-started/index.html">boundaries</a>: multiples of 4 for TF32, 8 for FP16, and 16 for INT8 (16-byte memory alignment). Similarly, batch dimensions also need to be properly tuned. When these conditions are met, Tensor Cores train models much faster. For instance, the backward pass can reuse the same matrix multiplication logic to compute gradients, taking advantage of reduced-precision formats that preserve enough numerical fidelity for stable training while significantly improving performance and reducing memory traffic.</p><h4>Under the hood — A WMMA Kernel</h4><p>To illustrate Tensor Core operations at the warp level, let’s examine a simple CUDA kernel that performs a warp-level matrix multiply-accumulate (<a href="https://docs.nvidia.com/cuda/parallel-thread-execution/#warp-level-matrix-instructions-wmma">WMMA</a>) using low level <a href="https://docs.nvidia.com/cuda/parallel-thread-execution/#warp-level-matrix-instructions-wmma">PTX ISA</a>. <br>(Use this <a href="https://gist.github.com/asheeshgoja/d1059e4f2ac9a3e31818de335af0ca3e">test code</a> and instructions to compile and run <a href="https://gist.github.com/asheeshgoja/0a444fc56a18a2311eed13dab93c9fdc">this kernel</a> on an NVIDIA A10 GPU.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ae43dda3426c9deb448ca39662eafef/href">https://medium.com/media/1ae43dda3426c9deb448ca39662eafef/href</a></iframe><p>The kernel starts with thread selection using (<em>mov.u32, setp.lt.u32</em>) to ensure single-warp execution of 32 threads. That is followed by register allocation for matrix fragments using mixed-precision formats: FP16 for input matrices <strong>A/B</strong>, FP32 for accumulator <strong>C</strong> and output <strong>D</strong>. The SM’s register file (RF) allocation uses .<strong><em>reg</em></strong> directives to set up <em>f16</em>x<em>2</em> and <em>f32</em> register arrays, enabling efficient data access patterns for the Tensor Core operations. The core data movement occurs through<strong> <em>wmma.load</em></strong> operations, transferring 16x16 matrix data from global memory to specialized registers in the required format (row/column-major) and precision, utilizing the <a href="#7840">GPU’s memory hierarchy</a> through L1/L2 caches.</p><p>The key Tensor Core computation is performed via the <strong><em>wmma.mma.sync</em></strong> instruction, which executes the matrix multiply-accumulate operation (<strong>D = A×B + C</strong>) on 16x16 matrices, called <strong>tiles</strong>. This operation leverages the hardware’s ability to perform fused multiply-add (FMA) operations in a single cycle across the warp’s 32 threads. The SIMD execution model ensures all threads in the warp execute the same instruction but operate on different data elements, while the warp scheduler manages instruction interleaving to hide memory latency. Finally, <strong><em>wmma.store.d.sync</em></strong> writes the computed results back to global memory through the cache hierarchy, completing the matrix multiplication sequence. All operations maintain warp-wide synchronization through <strong><em>.sync</em></strong> barriers, ensuring coordinated execution across the 32 threads of the warp.</p><p>The entire operation sequence aligns with specific memory boundaries (16-byte alignment for FP16 operations) and leverages the SM’s computational units: LD/ST units handle memory transactions, Tensor Cores perform the core MMA operations, and the warp scheduler manages execution flow. This hardware-software coordination enables efficient parallel processing of matrix operations, making it particularly suitable for Transformer’s GEMM-heavy (General Matrix to Matrix Multiplication) structure of attention and feed-forward layers, where aligned 16x16x16 tiles maximize Tensor Core utilization, accelerating both inference and training.</p><p>While the WMMA kernel exemplifies the remarkable engineering that enables efficient matrix operations on modern GPUs, it also provides a window into the fundamental challenges of scaling LLMs to even greater sizes. The careful orchestration required at the hardware level, from warp-level execution to memory alignment and specialized compute units, shows a delicate balance between computational power and physical constraints. As we push towards trillion-parameter LLMs, these constraints begin to manifest not as mere engineering hurdles, but as major barriers that define the boundaries of what’s possible with current technology.</p><h3><strong>Walls of Silicon</strong></h3><p>These barriers emerge from the fundamental physics of semiconductor technology and the underlying computer architecture, manifesting as three interconnected walls that constrain our ability to scale LLMs:</p><ol><li><a href="#5137"><strong>Memory Wall</strong></a></li><li><a href="#4c8e"><strong>Power Wall</strong></a></li><li><a href="#3f37"><strong>Interconnect Wall</strong></a></li></ol><p>Each wall represents a different facet of the same underlying challenge: the physical limits of silicon-based computing. By examining these constraints and their interplay, we can better understand both their immediate impact on model scaling and their implications for the future of AI hardware architecture. These walls arise from inherent physical and engineering constraints. They impose significant limits on how many GPUs can be scaled out, how large on-chip memory can be, how much power a data center can provide, and how efficiently data can be moved and processed across devices.</p><p>In the following sections, we will go deeper into each of these barriers, explore their root causes, and discuss strategies used to address or mitigate them. Understanding these challenges is essential for advancing research and deployment of LLMs, where increasing model size no longer guarantees proportional performance improvements.</p><h3>The Memory Wall</h3><p>Understanding the intricacies of GPU architecture, its reliance on parallel <a href="#ee91">SMs</a>, layered memory hierarchies, and high-bandwidth operations, highlights how performance hinges on efficient data movement. GPUs thrive on feeding their computational cores with a steady stream of data from memory, yet as LLMs scale to trillions of parameters, this demand outpaces the capacity of GPU’s memory systems. This challenge manifests as the “Memory Wall” — a widening gap between computational capability and memory performance. This fundamental problem presents itself in three critical ways. First, the movement of data between memory elements and processing units introduces significant latency overhead. Second, data movement through memory hierarchies is severely constrained by bandwidth limitations. Finally, and perhaps most critically, the energy cost of data movement is immense. In fact, transferring data between computing units and off-chip memory can consume nearly 100 to 200 times more power than the floating-point computations themselves. We will explore this energy cost in greater detail in the <a href="#4c8e"><strong>Power Wall</strong></a> section.</p><p>At the root of this challenge lies the <strong>Von Neumann architecture</strong>, the foundational model upon which modern computing systems are built. By examining this architecture, we can pinpoint the structural bottlenecks in data movement and understand the limitations GPUs encounter in meeting the escalating demands of LLMs.</p><h4><strong>The Von Neumann Architecture</strong></h4><p>Computing systems, such as GPUs, are fundamentally influenced by the Von Neumann architecture, which logically separates compute and memory elements. In this model, a processor— equipped with high-speed registers, arithmetic logic units (ALUs), and control units — fetches instructions and data from a main memory, typically implemented using <a href="#f04e">DRAM</a>. This memory stores both program code and the data the program operates on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSZxC1ekQ1vyX66WCcj1WA.png" /></figure><p>These components work together to enable efficient execution of instructions. At the core, the <strong>processor</strong> consists of arithmetic logic units (ALUs), registers, and control logic, handling computations and instruction execution. Supporting this, <strong>main memory (</strong>DRAM<strong>)</strong> serves as high-capacity storage for both instructions and data, though it operates at a slower speed compared to the processor. To facilitate communication, <strong>buses</strong> act as shared pathways, transmitting data and control signals between the processor, memory, and I/O devices. <strong>I/O devices</strong> serve as the interface between the system and external data sources or end users, ensuring interaction with the outside world. This entire system operates in a continuous <strong>fetch-decode-execute cycle</strong>, where the processor retrieves an instruction from memory, deciphers it, and executes it before moving to the next.</p><p>While GPUs adhere to these core Von Neumann principles, they optimize for parallel computation through specialized hardware. Unlike CPUs, which are primarily optimized for low-latency execution on fewer threads, GPUs contain multiple <a href="#ee91">SMs</a>, which collectively house thousands of ALUs capable of simultaneous operations. They implement <a href="#d145">SIMT</a> execution models, enabling massive parallelism. This parallel execution is further supported by a hierarchical memory structure consisting of HBM, shared memory, caches, and registers. This intricate memory hierarchy is essential for feeding the thousands of processing cores and operates synergistically with the SIMT execution model and its underlying warp scheduling mechanisms to maximize bandwidth, manage data efficiently, and crucially, hiding the latency inherent in accessing main memory. However, this technique of “hiding the latency” itself becomes a problem for workloads with <a href="#e696">low arithmetic intensity</a>, as we will see in subsequent sections.</p><p>While fetch-decode-execute cycle forms the foundation of computation, a persistent challenge arises due to the growing performance gap between processor clock rates and memory speeds, often resulting in stalls when the processor waits for data retrieval.</p><h4><strong>The Von Neumann Bottleneck</strong></h4><p>This performance mismatch between on-chip processor elements and comparatively slow off-chip main memory leads to the Von Neumann Bottleneck. While processor speeds and transistor densities have increased exponentially over the decades, improvements in main memory (DRAM) latency and bandwidth have been relatively modest. This disparity means that even highly efficient GPUs often spend a significant portion of their time waiting idly for data to arrive from memory, wasting cycles and reducing overall throughput. This “Von Neumann Bottleneck” is particularly pronounced for LLMs, which require rapid, large-scale data movement to and from memory during both training and inference.</p><p>The bottleneck arises from the trade-off between data transfer rates and energy efficiency — the interplay between <strong>bits</strong> per second (bps) and <strong>watts</strong> per bit. From an electrical engineering standpoint, data movement is constrained by signal propagation physics, where energy use scales with frequency and distance due to capacitance, resistance, impedance, and inductance. As data moves across longer paths, especially to off-chip DRAM , it must traverse chip boundaries, package pins, and board traces, increasing energy costs and exacerbating both latency and thermal constraints. Accelerators like GPUs demand ever-higher memory bandwidth but must operate within strict power envelopes, creating a fundamental bottleneck: increasing data throughput drives up energy consumption. Simply put, the faster we move <strong>bits</strong>, the more <strong>watts</strong> we burn.</p><h4><strong>Memory Hierarchies</strong></h4><p>To mitigate these effects, GPUs employ a multi-level memory hierarchy designed to minimize the performance penalty of accessing off-chip DRAM. This hierarchy typically consists of:</p><ul><li><strong>L0 and L1 caches</strong> — Small, fast <a href="#e76f">SRAM</a> caches located near compute units, supplying operands at near-processor speeds (~1–10 cycles).</li><li><strong>L2 cache</strong> — A larger, on-chip SRAM cache that buffers intermediate results shared among multiple execution units.</li><li><strong>High Bandwidth Memory (HBM)</strong> — Off-chip DRAM stacks serving as the primary high-capacity memory for the GPU.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-tepmolyCAgTZwKuSPCAA.png" /></figure><p>To illustrate this hierarchy in practice, let’s examine the NVIDIA<strong> </strong><a href="https://developer.nvidia.com/blog/nvidia-hopper-architecture-in-depth/">H100</a>:</p><ul><li><strong>256 KB Register File (RF) per SM</strong> — The fastest on-chip SRAM for immediate computations.</li><li><strong>L0 Instruction Cache</strong> — Private to SM quadrants for quick instruction fetch.</li><li><strong>256KB L1 Cache per Streaming Multiprocessor (SM)</strong> — Provides low-latency memory for frequently accessed data.</li><li><strong>50MB L2 Cache</strong> — A large, <a href="https://developer.nvidia.com/blog/nvidia-hopper-architecture-in-depth/#h100_l2_cache">partitioned-crossbar</a> cache that minimizes HBM3 accesses by sharing data across <a href="#ee91">SMs</a>.</li><li><strong>HBM3 Memory (up to 80GB)</strong> — The primary high-capacity VRAM, responsible for handling large datasets efficiently.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaJDZieutwyFM3Nz8Mb87Q.png" /></figure><p>This hierarchical structure improves enhances memory efficiency, ensuring high-speed access to critical data while reducing reliance on slower, off-chip memory.</p><h4>Revisiting the PTX Kernel Example</h4><p>Now let’s deep dive into how this GPU hierarchical memory structures help mitigate the Von Neumann Bottleneck by revisiting the <a href="#e0b2">WMMA kernel example</a> from the previous section. The <a href="https://gist.github.com/asheeshgoja/0a444fc56a18a2311eed13dab93c9fdc">kernel</a> begins by loading pointers for matrices A, B, C, and D into registers using<em> </em><strong><em>ld.param.u64</em></strong>. If bandwidth falls short during these loads, the pipeline stalls, and the Tensor Cores sit idle. Next, the kernel performs <strong><em>wmma.mma.sync</em></strong>, a fused multiply-accumulate operation that leverages specialized Tensor Cores for parallel half-precision inputs and single-precision accumulators. While these cores can significantly increase throughput, their potential goes underutilized whenever data fails to arrive on time, exacerbating the Von Neumann Bottleneck.</p><p>GPU’s mitigate this bottleneck by layering multiple tiers of memory. At the smallest scale, registers (<em>%A_reg to %D_reg</em>) provide near-instant access to critical data operands. Separately, an <strong>L0</strong> instruction cache provides rapid access to fetched instructions, ensuring a steady instruction stream for the SM. The <strong>L1</strong> cache brings frequently used operands closer to each SM, while a sizable <strong>L2</strong> cache, spanning tens of megabytes, reduces the need for repeated fetches from <strong>HBM</strong>. Although HBM3 provides large storage capacity, its higher latency still poses a challenge. To address this, instructions like <strong><em>wmma.load</em></strong> are designed to leverage this caching hierarchy to ensure that Tensor Cores remain consistently fed, minimizing idle cycles. This interplay of memory hierarchy and advanced compute capabilities helps manage the Von Neumann Bottleneck, particularly for matrix-intensive operations.</p><h4>SRAM vs. DRAM: Latency vs. Capacity</h4><p>At the core of modern memory hierarchies are Static Random Access Memory (<strong>SRAM</strong>) and Dynamic Random Access Memory (<strong>DRAM</strong>), two fundamental memory technologies that each balance speed and capacity in different ways. SRAM is optimized for extremely low latency and serves as the foundation of on-chip processor caches, such as L1 and L2, which sit closest to compute units. DRAM, in contrast, operates off-chip and offers higher capacity but at slower access speeds, thus forming a hierarchical structure in which each memory level is carefully positioned to balance latency, bandwidth, and storage capacity. To understand why SRAM achieves such low latency, it is important to first examine its architecture in detail.</p><h4><strong>SRAM Architecture</strong></h4><p>SRAM uses a 6-transistor (6T) design, in which two cross-coupled inverters form a stable latch to store a single <strong>bit</strong> (0 or 1), and two additional transistors act as access gates for read and write operations. The cross-coupled inverters ensure bistability, meaning that once a bit is written, it remains in that state until explicitly changed. This sharply contrasts with DRAM, which stores bits in capacitors that discharge over milliseconds, causing state decay and requiring periodic <a href="#998d">refreshes</a> to maintain data integrity. The access transistors, controlled by the word line (<strong>WL</strong>), connect the storage nodes to the bit-lines (<strong>BL</strong> and <strong>B̅L̅</strong>), facilitating faster read and write operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9WP7hNZOV5A4jwvdc9wYA.png" /></figure><p>During a write operation, the bit-lines are driven to complementary values ( BL = VDD, B̅L̅ = 0 for writing a ‘<strong>binary 1</strong>’) before enabling the word line. This forces the corresponding values into the storage nodes, overriding the previous state. For a read operation, both bit-lines are precharged to VDD​, and then the word line is activated, allowing the stored value to slightly perturb one of the bit-lines, which is then detected by a sense amplifier. Sense amplifiers also improve SRAM power efficiency by reducing bitline voltage swings, facilitating lower supply voltages, accelerating read operations, and mitigating leakage current.</p><p>Because it does not rely on capacitors, SRAM does not require the periodic refresh cycles that DRAM or HBM necessitate, which in turn enables faster access times and lowers idle power consumption. Its latch-based mechanism removes the delay associated with the charge-based read and write operations found in DRAM, allowing data retrieval in as few as 1–10 clock cycles. The near-instantaneous transistor switching enabled by this architecture makes SRAM ideal for L1 and L2 caches, where supplying data at near-core speeds is essential. At a fundamental level, SRAM’s low latency is achieved through its latch-based architecture and rapid transistor switching, and its operation is managed by precise timing control driven by external clock signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWW0xgb4zq0jN0A5Wqagkw.png" /><figcaption><a href="https://www.ardent-tool.com/memory/pdf/sramop.pdf">Source</a></figcaption></figure><p>These signals include the clock (<strong>CLK</strong>) for synchronization, the address (<strong>ADDR</strong>) for selecting specific storage locations, and signals such as Chip Select (<strong>CS</strong>), Write Enable (<strong>WE</strong>), and Output Enable (<strong>OE</strong>) that determine when the SRAM is active, when data can be written, and when data can be read. Data flows through dedicated data input/output (<strong>DQ</strong>) pins during these read and write operations. When performing a read, the address is registered on the rising edge of the clock, and valid data arrives at the output pins after the specified access time, which can sometimes be as short as a single processor cycle. Similarly, write operations follow a clock-synchronized sequence, although different implementations optimize how dead cycles between read and write operations are handled.</p><p>Despite its speed, SRAM’s 6-transistor design reduces storage density and increases cost per bit, which limits on-chip cache sizes to megabytes. Larger capacity memory resources thus turn to DRAM, such as off-chip HBM, which offers the density required by LLMs at the expense of higher latency. Even though small SRAM caches can mitigate some of DRAM’s latency, understanding the intricacies of DRAM architecture is crucial for recognizing the remaining bottlenecks.</p><h4><strong>DRAM Architecture</strong></h4><p>Dynamic Random-Access Memory (DRAM) is built on a 1T1C (1 Transistor, 1 Capacitor) memory cell architecture. Each cell consists of a capacitor, which stores charge representing a <strong>bit</strong> (0 or 1), and a transistor that acts as an access gate. These cells are organized in a grid-like array of <strong>wordlines</strong> (rows) and <strong>bitlines</strong> (columns) to enable read and write operations through the activation of specific intersections.</p><p>When a wordline is activated, the transistor connects the capacitor to the bitline, allowing data transfer. A charged capacitor represents<strong> binary 1, </strong>while a discharged capacitor signifies<strong> binary 0</strong>. However, reading data depletes the capacitor’s charge due to charge sharing with the bitline, requiring immediate restoration via a <strong>sense amplifier</strong> to maintain data integrity. Furthermore, capacitors leak charge over time, necessitating periodic <strong>refresh cycles</strong> to prevent data loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAO74Ixryddwqg-ian9fOg.png" /></figure><p>To achieve high-density storage within a compact form factor, DRAM capacitors employ extreme aspect ratios<strong> (~100:1)</strong>, increasing surface area to maintain capacitance (~6 fF) as DRAM cells shrink. This structural optimization enables DRAM to balance <strong>s</strong>peed, cost, and density, making it faster than NAND but more cost-effective than SRAM. The Row Address Strobe (<strong>RAS</strong>) and Column Address Strobe (<strong>CAS</strong>) signals facilitate efficient memory access, though the need for periodic refreshing introduces latency. Despite this limitation, DRAM remains the dominant choice for main memory in GPUs due to its ability to deliver an optimal mix of performance and scalability.</p><p><strong>DRAM Refresh </strong><br>The inherent physics of DRAM’s capacitor-based cells require constant attention to prevent data loss. It stems from the inherent leakage of charge in capacitor-based memory cells. Without periodic reinforcement, the charge in each cell would decay below detectable thresholds within 64 ms at room temperature, leading to data loss. At higher temperatures (above 85°C), leakage accelerates, requiring refresh intervals as short as 32 ms to maintain data reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_yVq9TqqjGRGKb1oy67Jw.png" /></figure><p>The refresh process involves activating a specific row via the <strong>RAS signal</strong>, precharging bitlines to a mid-level voltage (e.g., 0.5V). The capacitors’ charge interacts with the bitlines, and the <strong>sense amplifier</strong> detects voltage changes to determine if the cell stores a 0 or 1. The sense amplifier then reinforces these values, restoring the capacitors to their original states.</p><p><strong>DRAM Density<br></strong>As DRAM density increases, two key factors drive up power demands. First, smaller capacitors exhibit faster charge leakage, requiring more frequent refresh intervals. Second, with increased density, the total time spent on refresh operations increases, due to more rows that must be refreshed, leading to longer periods where memory banks are active and consuming power.</p><p>Moreover, higher cell density amplifies electrical interference (<strong>crosstalk</strong>) and susceptibility to power supply noise, increasing the risk of data corruption. During refresh operations, DRAM temporarily blocks access to memory banks for the duration of the <strong>tRFC</strong> (Refresh Cycle Time). This forces the memory controller to queue incoming read and write requests, increasing latency and potentially reducing system performance. The impact is particularly pronounced in high-density DRAM modules, where frequent refresh cycles substantially degrade bandwidth and response times.</p><p>To mitigate these performance bottlenecks, modern memory controllers utilize strategies such as distributed refresh and intelligent scheduling, minimizing the impact of refresh cycles. However, despite these optimizations, refresh cycles remain a contributor to power consumption, especially in GPUs. Additionally, memory access operations, including reads, also contribute to dynamic power consumption within the DRAM, adding to the overall power budget. Consequently, a portion of the GPU’s power budget is allocated to managing DRAM state through refresh operations, rather than solely for computations. This issue is exacerbated in memory-intensive workloads like LLMs, where frequent refresh cycles interfere with low-latency memory access, ultimately limiting efficiency.</p><p><strong>Implications on DRAM scaling<br></strong>The physical limitations of shrinking DRAM cells, such as increased refresh rates and higher power consumption, have far-reaching consequences for DRAM scaling. Although computational capabilities have experienced exponential growth, advancements in DRAM bandwidth have not kept pace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*KEENib9tX0oWnn6261Iy5g.png" /></figure><p>This disparity is highlighted by the fact that even if compute logic can achieve a staggering<strong> 60,000-fold</strong> improvement in performance, memory bandwidth may have only increased by a factor of <strong>100</strong> over the same time frame. Furthermore, the energy cost of moving data significantly outweighs that of performing computations. Accessing data from off-chip DRAM can consume 100 to 200 times more energy compared to executing a single floating-point operation.</p><h4><strong>High Bandwidth Memory (HBM)</strong></h4><p>High Bandwidth Memory (HBM) addresses this growing disparity between compute performance and memory bandwidth. HBM’s advanced 3D die stacking and ultra-wide data buses provide a significant upgrade over traditional DRAM, enabling faster data transfer and mitigating memory bottlenecks that impede system performance. HBM can be likened to a high-speed, multi-lane superhighway for data, in contrast to the congested, narrow lanes of traditional DRAM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7jHUb-gMQmZnE_aMDiFIA.png" /><figcaption><a href="https://www.rambus.com/blogs/hbm3-everything-you-need-to-know/">Source</a></figcaption></figure><p>By vertically stacking multiple DRAM layers (8 or more) and interconnecting them using Through-Silicon Vias (TSVs), HBM achieves a 1024-bit wide data bus per stack, which is 16 times wider than DDR5 DRAM’s 64-bit bus, enabling up to 1.2 TB/s bandwidth (HBM3E) per stack. This increased bus width substantially accelerates data transfer between the processor and memory. Moreover, HBM is co-packaged with the GPU on an interposer, significantly reducing the physical distance between memory and processor to mere millimeters, compared to the few centimeter gap in DRAM (DDR in DIMM) memory. This close proximity results in lower latency and reduced energy consumption per bit transferred (<strong>pJ/bit</strong>), making HBM more power-efficient despite its high data throughput. By offering a high-bandwidth, low-latency, and energy-efficient memory solution, HBM prioritizes bandwidth over capacity, thereby helping to alleviate the Von Neumann bottleneck.</p><h3>Transformers and the Memory Wall</h3><p>After this deep technical exploration of the Memory Wall, one cannot but wonder and ask this crucial question: <strong><em>Are current GPU architectures inherently suited for the evolving computational complexity of scaling Transformer-based LLMs?</em></strong></p><p>The answer lies in understanding the interplay of <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#c050">Transformer’s algorithmic complexity</a> and the underlying <a href="#ee91">GPU architecture</a>. GPUs historically were designed for graphics workloads, which are highly parallel and uniform in their arithmetic intensity (a measure of the amount of computation performed per unit of data accessed from memory). Tasks like pixel processing and vertex shading involve performing the same operations on large datasets in parallel, making them both arithmetic-heavy and predictable. In contrast, Transformer-based LLMs exhibit a very different computational profile. While they rely on dense operations such as matrix multiplications, they also incorporate sparse computations like sparse attention and <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#e531">MoE</a>, along with numerous nonlinear kernels such as Softmax, GELU, and Layer Normalization. These operations create data-dependent execution paths and irregular memory access patterns, leading to suboptimal scaling efficiency and underutilization of available computational throughput (FLOPS).</p><p>Despite innovations such as HBM and hierarchical caches, GPUs are still constrained by the von Neumann architecture’s fundamental separation of compute and memory units. This physical divide forces constant data movement between memory and processing elements, where each transfer consumes significantly more energy (<strong>pJ/bit</strong>) than the actual computation (FLOPS). Transformers exacerbate this issue through dynamic, data-dependent attention mechanisms that produce irregular memory access patterns. As discussed in <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-1-34ef63d95b6c"><strong>Part 1</strong></a>, inference, in particular the decoding phase, further amplifies these problems. Unlike the parallel training process, decoding is inherently sequential and memory-bound, making it less efficient. Self-attention exhibits quadratic scaling with sequence length at <em>O(n²⋅d)</em>, thus rapidly increasing memory and compute requirements. Although optimizations such as the <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#377c">KV cache</a> can reduce per-token complexity from quadratic<em> O(n²)</em> to linear <em>O(n),</em> they introduce substantial memory overhead for long sequences and CoT based <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#660d">reasoning models</a>, making large-scale inference increasingly challenging.</p><p>Frequent cache misses force GPUs to access off-chip memory, but it is the higher off-chip latency that amplifies the problem, causing excessive stalls as data is repeatedly fetched. This bottleneck results in significant energy costs, as data traverses chip boundaries, interposers, and circuit board traces. The repeated transfers not only degrade cache utilization and overwhelm hardware prefetching mechanisms but also trigger even more off-chip operations, creating a self-perpetuating cycle of inefficiency. While methods such as <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#377c">MQA, GQA, and MLA</a> can mitigate some of these inefficiencies, the memory burden posed by Transformers remains a significant challenge to both scalability and performance.</p><p>With these challenges in mind, the next key factor to examine is <strong>arithmetic intensity</strong> — and how it contributes to underutilizing the GPU’s compute cores in Transformer workloads.</p><h4>Arithmetic Intensity and Underutilization of Compute Cores</h4><p>Arithmetic intensity, measured in (OPs/byte) or (FLOPs/byte), represents the ratio of floating-point computations to memory operations. It is quite useful in maximizing GPU performance for Transformer models. Models with high arithmetic intensity perform more computation per unit of data transfer, allowing better utilization of compute resources. However, LLMs often experience phases of low arithmetic intensity, especially during token-by-token <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#5159">decoding</a>. They alternate between compute-heavy operations, such as matrix multiplications for <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#acec">FFN</a>s or attention mechanisms, and memory-intensive operations, such as retrieving token embeddings or reading and writing <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#377c">KV caches</a>. When memory bandwidth fails to keep pace with data demands, memory transfers become a bottleneck, leading to underutilization of the GPU’s available FLOPS. To analyze and mitigate this issue, the Berkeley Roofline Model offers a valuable framework for understanding performance limitations.</p><p><strong>Berkeley Roofline Model<br></strong>This model visually maps achievable performance (FLOPS) against arithmetic intensity, where FLOPs per byte fetched from the memory hierarchy are plotted along the x-axis (FLOPs/byte). It helps determine whether a workload is constrained by memory bandwidth or compute capability. The model creates a characteristic “roof” shape. The slanted line on the left represents the memory bandwidth limit or the <strong>bandwidth roof</strong>. This limit shows that at low arithmetic intensity, performance is bottlenecked by how quickly data can be fetched from memory. The horizontal line at the top signifies the <strong>peak compute roof</strong>, representing the theoretical maximum computational performance of the given hardware. The actual roofline, and thus the realistic achievable performance, is the lower bound of these two limits at any given arithmetic intensity, visually forming the “roof”.</p><blockquote>Transformer-based LLMs often fall within the memory-bound region, particularly during token-by-token inference, meaning their performance is constrained by the speed at which data moves from memory rather than by raw compute power.</blockquote><p>By analyzing where different layers or phases of a model lie on this chart, researchers and engineers can determine whether the workload is memory-bound or compute-bound and apply optimizations accordingly. This understanding guides optimization efforts. For layers identified as memory-bound, prioritizing techniques to reduce memory transfers is key. Examples include model quantization or data layout optimizations to improve cache usage. For compute-bound layers, improving mathematical efficiency becomes more critical, which might involve using more efficient algorithms or optimized kernel implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QUVAh7TqO2S7zW_g7kz3g.png" /><figcaption><a href="https://github.com/hahnyuan/LLM-Viewer">Source</a></figcaption></figure><p><strong>Practical Example: Llama-2–70b on H100 SXM5<br></strong>This roofline chart for Llama‑2–70B’s decode stage on an H100 SXM shows a workload that is predominantly memory‐bound, as indicated by the performance curve adhering to the “bandwidth slope” rather than approaching the horizontal “peak compute” line. In token‐by‐token inference, large model weights must be repeatedly fetched from memory with minimal reuse, creating a low arithmetic intensity that limits achievable FLOPS. Although the theoretical peak for FP16 Tensor Core operations on the <a href="https://developer.nvidia.com/blog/nvidia-hopper-architecture-in-depth/#h100_sm_architecture">H100 SXM</a> (with sparsity) can reach nearly <em>1.979 × 10¹⁵ FLOPS</em>, single‐batch decode sustains around <em>1.1 × 10¹⁵ FLOPS</em>, corresponding to ~55% of that nominal peak. This figure should not be viewed as unusually low, because real‐world LLM workloads rarely approach 100% of a GPU’s maximum advertised performance. This significant gap between the achievable performance and the theoretical maximum is a direct consequence of the <strong>memory wall</strong>. As the decode stage spends a disproportionate amount of time waiting for data to be fetched rather than performing computations, the immense computational horsepower of the H100 SXM remains partially untapped. Consequently, the roofline visualization not only confirms the memory-bound nature of the Llama-2–70b decode stage but also highlights the magnitude of the memory bottleneck in limiting the utilization of the H100 SXM peak compute potential.</p><p>Memory access patterns are only one part of the challenge. The computational patterns within transformers introduce another layer of complexity, because they heavily rely on specialized mathematical operations that, while still leveraging linear algebra, push the demands beyond the core linear algebra workloads GPUs were originally designed to accelerate. This places additional strain on traditional GPU architectures, necessitating new hardware strategies that better align with the unique demands of transformer-based LLMs.</p><h4>Non-Linear and Irregular Operations</h4><p>Transformers rely on nonlinear operations such as softmax, GeLU, and layer normalization, which are crucial for stabilizing training and learning expressive representations. Unlike large matrix multiplications, which GPUs handle efficiently due to their inherent parallelism and optimized data access patterns, these nonlinear functions introduce unique optimization challenges. They often involve branching computations and operations like conditional checks, exponentials, and normalizations. These introduce more complex control flow within threads and can lead to reduced peak efficiency on SIMT architectures compared to the maximum throughput achievable with perfectly regular and predictable operations like matrix multiplications.</p><p><strong>Softmax Example</strong><br>Softmax computation involves calculating exponentials for every element in an input vector, normalizing probabilities by summing these values, and addressing floating-point overflow or underflow through techniques like Max-Shift or Log-Sum-Exp (LSE). Since the exponential function amplifies differences in input values, threads within a warp may encounter vastly different numerical ranges, leading to potential overflow, underflow, or denormal numbers. Managing these exceptional cases introduces <a href="https://class.ece.iastate.edu/tyagi/cpre581/papers/HPCA14WarpDivergence.pdf">warp divergence</a>, where some threads proceed with normal execution while others handle slower exception cases or denormal operations. Unlike matrix multiplication, where threads operate in uniform lockstep, this divergence degrades GPU performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OhXiU0omvDzE2NgL5ncDg.png" /></figure><p>Additionally, computing the sum Σ exp(…) requires communication across threads, typically handled by parallel reduction algorithms. These reductions involve operations such as intra-warp shuffles and inter-warp communication through shared or global memory, introducing latency and synchronization points where threads may idle, further exacerbating performance bottlenecks. Furthermore, softmax computation exhibits relatively low arithmetic intensity compared to operations like large matrix multiplications (GEMMs). It requires reading the input vector, accessing intermediate values such as the maximum and summed exponentials, and writing the output vector, leading to frequent memory accesses. Consequently, the ratio of computation (exponentials, summations, and divisions) to memory operations is significantly lower than in GEMMs, often causing softmax performance to be constrained by memory bandwidth rather than compute capability, resulting in compute units frequently sitting idle while awaiting data. Optimizing softmax thus demands careful attention to minimizing thread divergence and memory latency, posing a distinctly different set of challenges compared to optimizing large-scale matrix multiplication kernels.</p><p><strong>Divergence in Nonlinear Kernels<br></strong>As explained in the <a href="#d145">GPU architecture section</a>, thousands of threads are organized into warps, thread blocks, and grids, with each warp executing the same instruction in lockstep. This structure excels in dense matrix multiplications because identical operations can be repeatedly applied to contiguous chunks of data, allowing the warp scheduler to hide memory latencies by interleaving instructions from different warps and smoothly saturating compute resources.</p><p>Nonlinear kernels, including <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#acec">FFN</a> activation functions (ReLU, GeLU, sigmoid, tanh), normalization layers (RMSNorm, <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#4c3f">LayerNorm</a>), introduce greater control flow and memory irregularities. When some threads within the same warp encounter exponentials or conditional logic while others do not, the warp must serialize the divergent paths, leading to underutilization of the <a href="#ee91">SMs</a>. Essentially, the warp executes each branch of the divergent code path sequentially, forcing threads that do not take a particular branch to remain idle while others execute it. This serialization disrupts what could ideally be parallel execution.</p><p><strong>Memory Access Patterns and Reductions<br></strong>Additionally, these kernels often exhibit uncoalesced or strided memory accesses when computing normalization statistics or partial sums in activation layers, further increasing pressure on the memory subsystem and caches. For instance, LayerNorm’s mean and variance calculations involve reductions across the feature dimension. However, the combination of parallel processing and reduction operations, particularly given common data layouts in memory, can result in misaligned memory accesses, increasing memory pressure and reducing cache efficiency due to inefficient coalescing.</p><p>Similarly, partial sums or reductions in activation layers may not follow perfectly contiguous memory access patterns, unlike dense matrix multiplications, particularly if the data layout is not optimized for such operations. Uncoalesced or strided accesses often result in cache misses, as memory accesses fail to align with cache lines, lowering cache hit rates and necessitating more frequent accesses to slower off-chip DRAM. Although GPUs offer extremely high bandwidth and can schedule warps from any thread block to hide memory latencies, the inherent variance in elementwise operations, dynamic range checks, and branching significantly reduces effective throughput.</p><p>This interplay of divergence, irregular access patterns, and the computational overhead of transcendental functions contributes to bottlenecks in both training and inference. Tensor Cores can deliver enormous speedups for matrix operations by exploiting half-precision or TF32 formats, but they offer less benefit to nonlinear kernels that do not align with the specialized numeric pipelines. The performance gap grows when sequences become longer or require more complex attention mechanisms, compounding the dataflow disruptions in every pass of forward and backward propagation. Although these nonlinear operations remain essential for stable training and expressive power, their unpredictable data dependencies and branching logic create a mismatch with GPU execution flow, and they often require specialized kernel optimizations or algorithmic restructuring to mitigate the underutilization they can cause.</p><h4>Sparsity and Data-Dependent Patterns</h4><p>Sparsity and data-dependent patterns in Transformer-based LLMs introduce a set of challenges that go well beyond the usual concerns of dense matrix-matrix multiplication. Traditional Transformer layers already stress GPU memory bandwidth and computational throughput, but newer techniques like sparse attention, <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#e531">mixture-of-experts</a> layers, and selective token routing exacerbate these bottlenecks by introducing inherently irregular dataflows. Rather than operating on neatly packed tensors, these operations frequently perform dynamic indexing, gather/scatter data movement, and conditional computation that cannot be easily “vectorized” or coalesced. The result is a departure from the dense, straightforward access patterns that GPUs were originally optimized to handle.</p><p>From an architectural standpoint, GPUs rely on a <a href="#7840">hierarchical memory system</a> to hide memory latency and keep hundreds of threads running concurrently. Sparse operations undermine this design by triggering random or highly irregular access patterns, which break the assumptions of spatial and temporal locality that caches and memory coalescers depend on. When threads in a warp request data scattered across memory, the hardware struggles to batch and combine these loads, resulting in multiple smaller transactions instead of a single large coalesced one. This non-coalesced access lowers effective bandwidth and increases the frequency of cache misses, which in turn stalls the <a href="#ee91">SMs</a>. Over time, these stalls accumulate into larger latency penalties, further slowing down the pipeline.</p><p>Complicating matters, the GPU’s <a href="#d145">warp-based </a>execution model assumes that all threads in a warp will follow a similar execution path. Sparse operations, however, typically involve conditional branches and partial computations. Some tokens may be routed to different experts in an <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#e531">MoE</a> layer or attend to different subsets of tokens in a sparse attention mechanism. Such data-dependent branching can cause warp divergence, where subsets of threads in the same warp are forced to idle while others carry out different operations. Divergence also complicates the use of shared memory for caching intermediate results, since different threads within the same block may be fetching data from disjoint memory regions. Meanwhile, partial synchronization points can arise when only a subset of threads must wait for certain sparse kernels to complete before proceeding. Since GPUs rely on massive parallelism and deep pipelining, these synchronization stalls disrupt execution, reducing overall throughput. The impact extends beyond idle threads within a warp; entire warps or blocks may also remain idle, waiting for others to synchronize. This further diminishes the concurrency that GPUs depend on for efficiency.</p><p>These factors collectively prevent GPUs from reaching their theoretical FLOPS and bandwidth ceilings when executing sparse, data-dependent Transformer workloads. The result is lower occupancy, fewer active warps per <a href="#ee91">SM</a>, and higher latency, as hardware resources frequently stall on memory or synchronization. GPUs like the H100 mitigate some inefficiencies with <strong>structured sparsity</strong>, accelerating statically pruned weights. However, they struggle with dynamic sparsity in advanced LLMs, where sparse attention and <a href="https://medium.com/@asheesh.goja/34ef63d95b6c#e531">MoE</a> introduce irregular memory access and warp divergence. Unlike structured sparsity, which optimizes pre-defined weight pruning, these patterns are algorithmically driven and unpredictable, making static optimizations insufficient. As a result, tighter integration between algorithm design and hardware architecture to explicitly address dynamic sparsity is needed. While sparsity and data-dependent execution are effective for managing large context windows and parameter counts, they also exacerbate the “Memory Wall,” underscoring the fundamental mismatch between general-purpose GPU architectures and the irregular execution flows of modern Transformer variants.</p><p>So far, we’ve explored how the interplay between Transformer architecture and the Memory Wall creates bottlenecks within a <strong>single GPU</strong>. However, as LLMs continue to grow, they far exceed the capacity of any single accelerator, necessitating a shift towards multi-GPU scale-out architectures. Distributing the workload across multiple GPUs helps circumvent the limitations of individual devices, but it doesn’t eliminate bottlenecks — it merely shifts them to a new frontier: the <strong>Interconnect Wall</strong>. The bandwidth and latency challenges we’ve discussed now grow rapidly, as hundreds or even thousands of interconnected GPUs must work in unison. In the next section, we’ll delve into the intricacies of this Interconnect Wall and its profound impact on the scalability of ever-larger LLMs.</p><h3>The Interconnect Wall</h3><p>Scaling LLMs to meet growing compute and memory demands initially relied on a <strong>scale-up</strong> approach. This strategy involved enhancing individual accelerator chips by increasing core counts, memory, and bandwidth. Additionally, multiple accelerators were interconnected within the same server to boost overall compute and memory capacity. The original Transformer model from <a href="https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf">Vaswani et al. (2017)</a> exemplifies this early approach: it was trained on a single machine with just 8 NVIDIA P100 GPUs, with each training step taking approximately 0.4 seconds for base models. These models required only 100,000 steps or 12 hours of total training time.</p><p>However, as LLMs have grown exponentially in size, the scale-up approach has become inadequate, necessitating a shift to <strong>scale-out</strong> architectures. Instead of relying on a single multi-GPU server, modern training runs are distributed across massive clusters of accelerators. This shift is exemplified by Grok 3, which was trained on the <a href="https://nvidianews.nvidia.com/news/spectrum-x-ethernet-networking-xai-colossus">Colossus</a> supercomputer, utilizing 200,000 NVIDIA H100 GPUs. Grok 3’s training spanned 80 days and consumed an estimated 200 million GPU-hours. The contrast is striking: once, 8 P100 GPUs could train a model in under 12 hours, whereas today, 200,000 H100 GPUs, each delivering 105 times the FP16 FLOPS of a P100, train for over two months. This massive scale highlights the current paradigm in LLM training, where advancements hinge not just on model architecture improvements but on the ability to orchestrate compute across large-scale distributed systems.</p><p>While scale-out architectures have unlocked unprecedented model sizes and capabilities, they have introduced the “<strong>Interconnect Wall</strong>” as a critical bottleneck. Unlike single-machine training where data exchange is minimal, large-scale clusters must coordinate massive parameter and gradient exchanges. Inefficiencies in interconnect bandwidth and synchronization can lead to extreme slowdowns, with some collective operations consuming up to <a href="https://sc23.supercomputing.org/proceedings/tech_poster/poster_files/rpost174s3-file3.pdf">90%</a> of training time. This makes hardware-software co-design essential, balancing computation with data movement to ensure scalability.</p><h4>Limits of Scaling-up a Single GPU</h4><p>A scale-up approach that integrates more compute cores, larger on-die SRAM, and specialized compute units into a single package eventually encounters fundamental manufacturing limits. One of the primary constraints is the <strong>reticle size</strong> in semiconductor fabrication, which is governed by the capabilities of photolithography.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mnAoRH_sFC80Gkme5A8Zg.png" /></figure><p>The size of the reticle in semiconductor manufacturing plays a crucial role in determining chip capabilities. This reticle serves as a template during <strong>photolithography</strong>, the process used to imprint intricate circuit patterns onto silicon wafers. However, the constraints of optical physics and semiconductor fabrication impose strict limits on its dimensions. For a given process-node and photolithography equipment, there is a maximum reticle size that can be effectively utilized. This restriction directly impacts chip design by capping the total area available for transistors. Since transistors are the fundamental building blocks of computation, a limit on their number directly restricts the computational capacity that can be achieved on a single integrated circuit. Therefore, the reticle size becomes a primary constraint, acting as a bottleneck that restricts the potential processing power of individual chips by limiting transistor density.</p><h4>Addressing Single Chip Scale-Up Limitations : Advanced Packaging</h4><p>Advanced packaging techniques, such as chiplet-based Multi-Chip Modules (MCMs), address these scaling limitations of single package monolithic chip designs by disaggregating Systems-on-Chips (<strong>SoCs</strong>) into smaller, specialized <strong>chiplets</strong>. These chiplets are interconnected within a single package, allowing MCMs to overcome the fabrication constraints of single-die architectures. Among advanced packaging techniques, <strong>2.5D</strong> architectures, such as TSMC’s <a href="https://3dfabric.tsmc.com/english/dedicatedFoundry/technology/cowos.htm"><strong>CoWoS</strong></a> (Chip-on-Wafer-on-Substrate), enable high-bandwidth, low-latency interconnects by placing chiplets on an intermediary substrate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMK38kehPOU_TVpQ3jR25Q.png" /><figcaption>Source: TSMC <strong>CoWoS</strong> Architecture</figcaption></figure><p>CoWoS relies on several key components working in concert. The <strong>interposer</strong> serves as the foundation offering a dense connectivity layer where chiplets are arranged. <strong>TSVs</strong> acting as microscopic conduits enable signal transmission through the silicon, facilitating dense interconnectivity. Redistribution Layers (<strong>RDLs</strong>), layered atop the interposer and chiplets, form intricate wiring networks that fan out and route signals from TSVs across the interposer. The attachment of chiplets to the interposer is achieved using <strong>microbumps</strong>, fine-pitch connectors that establish high-bandwidth links between chiplets and the interposer. Finally, the <strong>substrate</strong> provides the mechanical foundation for the entire package, supporting the interposer and chiplets while also routing power and signals to the system’s motherboard. This integration is critical for workloads such as LLM inference, where substantial computational power and memory bandwidth are essential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1BrkFBtTcZYNHrJFePHexQ.png" /><figcaption><a href="https://3dfabric.tsmc.com/english/dedicatedFoundry/technology/cowos.htm"><strong>CoWos-L</strong> Source: TSMC</a></figcaption></figure><p>CoWoS is available in three main variants: CoWoS-S, CoWoS-R, and CoWoS-L. The <strong>CoWoS-L</strong> variant, in particular, has significantly expanded the capabilities of 2.5D packaging. By utilizing RDL interposers with Local Silicon Interconnect (<strong>LSI</strong>) bridges, CoWoS-L extends the package size to span up to multiple reticle limits, pushing performance boundaries while introducing new thermal design challenges. CoWoS also enhances design flexibility by enabling modular integration of chiplets from different suppliers. This capability allows GPU manufacturers, such as NVIDIA, to integrate high-bandwidth memory (HBM) from SK Hynix or Micron, creating optimized single-package solutions that leverage best-in-class components.</p><h4><strong>Industry Example: Scaling-up </strong>NVIDIA<strong> Blackwell GPU</strong></h4><p>Blackwell GPU exemplifies the cutting edge of semiconductor manufacturing, leveraging <strong>2.5D</strong> packaging with <strong>CoWoS-L</strong> to push the boundaries of GPU design. To overcome the reticle size limitation in extreme ultraviolet (<strong>EUV</strong>) lithography, Blackwell splits its GPU logic across two reticle-sized dies, interconnected using <strong>NV-HBI</strong> — a high-speed interconnect delivering ~10 TB/s of bandwidth. This architecture effectively combines two dies into a single GPU, increasing compute density while circumventing the physical constraints imposed by monolithic chip scaling.</p><p>As explained earlier, a major challenge in single GPU scaling is the <strong>reticle size limit</strong> of extreme ultraviolet (<strong>EUV</strong>) lithography. The Blackwell chip is fabricated using <a href="https://www.tsmc.com/english/dedicatedFoundry/technology/logic/l_5nm">TSMC’s 4NP</a> process-node that utilizes ASML’s <a href="https://www.asml.com/en/products/euv-lithography-systems/twinscan-nxe3400c">EUV</a> machine with a Numerical Aperture of <strong>0.33 NA</strong>. In EUV lithography, this 0.33 NA specification limits the exposure field to <strong>858 mm²</strong> (26 mm x 33 mm). This restriction stems from the 4x reduction optics employed in 0.33 NA EUV systems, where the standardized mask size of 104 mm x 132 mm translates to a maximum exposure field of 26 mm x 33 mm. The fundamental constraints imposed by 0.33 NA projection optics prevent further scaling of the field size, as any increase would degrade image fidelity due to optical aberrations. These limitations directly affect process efficiency, lithographic accuracy, and overall manufacturability.</p><p>To meet its performance targets requiring approximately 208 billion transistors, which far exceeded what could fit on a single die within the 858 mm² reticle limit, NVIDIA split the chip into two co-packaged dies of about 429 mm² each. This design approach effectively doubled the available transistor budget and improved manufacturing yields. Unlike previous NVIDIA GPUs that utilized <strong>CoWoS-S,</strong> Blackwell required the more advanced <strong>CoWoS-L</strong> packaging due to its finer “bump pitch” — the spacing between micro-bumps connecting the chip to the substrate. This reduced bump pitch significantly increased the density of contact pads, a critical factor in enabling Blackwell’s high-performance features, such as the <strong>NV-HBI 10TB/s</strong> die-to-die interconnect for rapid data transfer between chiplets. However, it also introduced a new bottleneck at the interconnect between the two dies. To operate as a unified processor, data must now communicate via NVIDIA’s NV-HBI.</p><p>While NV-HBI is an advanced interconnect, fundamental laws of physics and engineering constraints prevent communication between two separate pieces of silicon from matching the speed and efficiency of a monolithic die. Several factors contribute to this limitation: the increased physical distance signals must travel, the overhead imposed by the NV-HBI protocol and its physical transceivers for off-chip signaling, and the added complexity of maintaining cache coherency across dies. Consequently, even with cutting-edge NV-HBI, the computational throughput of this dual-die architecture remains inherently constrained, representing a theoretical performance ceiling compared to a single-chip implementation.</p><h4>Challenges of Advanced Packaging</h4><p>Advanced packaging designs promise significant performance gains but also bring formidable engineering challenges.</p><p><strong>Thermal Management<br></strong>Dies stacked vertically face challenges dissipating heat from upper layers. CoWoS-L technology, as implemented in NVIDIA’s Blackwell GPUs, amplifies this thermal management dilemma. CoWoS technology, when used to integrate vertical HBM stacks and logic dies with dense TSV interconnects, already presents significant heat concentration challenges. CoWoS-L further intensifies this issue with its significantly smaller bump pitch, which, while enhancing interconnect speeds and power efficiency, results in even greater heat density. Furthermore, the smaller size of the micro-bumps in CoWoS-L makes them inherently more vulnerable to thermal stress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbB1gFq9a2saC7NLQ3yWQw.png" /><figcaption><a href="https://semiengineering.com/knowledge_centers/memory/volatile-memory/dynamic-random-access-memory/high-bandwidth-memory/">Source</a></figcaption></figure><p><strong>Mechanical Reliability<br></strong> Disparities in the coefficients of thermal expansion (<strong>CTE</strong>) between silicon chiplets, the interposer, and the organic substrate becomes increasingly problematic under thermal fluctuations. During operational thermal cycles, these CTE mismatches induce differential expansion and contraction, concentrating mechanical stresses at critical interconnection points. Solder joints, TSV-based connections, and micro-bump arrays, all vital for electrical and mechanical integrity, become focal points for these stresses. Repeated thermal cycling then risks solder joint fatigue, interposer cracking, and degradation of micro-bump interconnections, posing a constant threat to the package’s structural integrity and long-term operational reliability.</p><p><strong>Signal Integrity and Crosstalk<br></strong>Achieving multi-terabit-per-second communication in chiplet systems immediately confronts limitations in signal integrity within densely packed wiring. The sheer demand for bandwidth necessitates extremely high-density interconnects, inherently leading to timing skew and electromagnetic interference. Close proximity of signal lines, essential for these speeds, inevitably fosters crosstalk, where signals bleed from one line to another, corrupting data. Simultaneously, variations in electrical path lengths and impedance mismatches across these dense interconnects create timing skew, causing signals to arrive out of sync and potentially leading to data errors. These signal integrity issues are not minor disturbances; they are core obstacles manifesting as degraded signal quality, increased error rates, and ultimately, restrictions on the attainable communication bandwidth between chiplets.</p><p><strong>Power Delivery Network (PDN)<br></strong>Powering chiplet assemblies introduces significant complexities arising from the diverse power requirements of individual chiplets. Each chiplet, performing specialized functions, may demand distinct power levels, creating a heterogeneous power landscape within the package. This diversity amplifies the sensitivity of these high-performance systems to noise propagation. Noise originating in one area of the Power Delivery Network — whether from switching activities or fluctuating current demands — has the potential to cascade throughout the entire package. This ripple effect across interconnected power planes can disrupt the performance of other chiplets, making the management of noise and the provision of stable power a formidable challenge in ensuring reliable chiplet operation.</p><p><strong>Cost and Yield<br></strong> Fabricating large interposers and implementing fine-pitch micro-bumping, processes essential for high-performance chiplets, are inherently complex and expensive. Wafer thinning, also frequently employed, introduces additional process steps and yield risks. These sophisticated manufacturing requirements translate directly into escalating production costs. Furthermore, maintaining acceptable yield rates in these intricate processes presents a persistent challenge. Process variations, equipment calibration issues, and the sheer complexity of handling large, thin wafers all contribute to potential yield losses, making cost control and yield optimization critical, yet inherently difficult, aspects of chiplet manufacturing viability.</p><p>As LLMs surpass the trillion-parameter mark, even the most advanced scale-up architectures struggle to keep pace. Training such LLMs demand terabytes of memory to store parameters, activations, gradients, and optimizer states. For instance, a trillion-parameter model using a stateful optimizer like Adam requires nearly 16 TiB of GPU memory at 16-bit precision. These extreme memory requirements, coupled with skyrocketing computational demands, render scale-up solutions impractical. Consequently, the industry shifted toward scale-out architectures to sustain LLM growth.</p><h4>Scale-Out Architectures</h4><p>Scale-out architectures solve this challenge by distributing the workload across horizontally scaled GPU clusters. This approach not only makes trillion-parameter LLMs feasible, but also provides the flexibility to expand hardware resources as new, larger models emerge. To optimize performance across large GPU clusters, several complementary parallelization strategies efficiently distribute data and computation.</p><p>Data Parallelism splits the training dataset among GPUs, allowing each to process mini-batches independently while synchronizing updates — ideal for distributed training without modifying the model. Model Parallelism divides the model itself across GPUs, enabling the training of massive architectures that exceed single-device memory limits. Pipeline Parallelism partitions the model into sequential stages, assigning each stage to a different GPU to overlap computation and communication, improving throughput. Tensor Parallelism further optimizes efficiency by distributing large matrix operations across multiple GPUs, reducing memory bottlenecks in large-scale LLMs.</p><p>Achieving efficient scale-out parallelization requires low-latency, high-bandwidth communication both within a node and across a GPU cluster. Different solutions cater to these two levels: <strong>intra-node</strong> interconnects like NVLink, and NVSwitch facilitate high-speed communication between GPUs within a server-node (such as <a href="https://www.nvidia.com/en-us/data-center/hgx/">HG B200</a>) or a SuperPOD (such as <a href="https://nvdam.widen.net/s/wwnsxrhm2w/blackwell-datasheet-3384703">GB200 NVL72</a>), while <strong>inter-node</strong> networking technologies such as Ethernet, RoCE, and InfiniBand enable scaling across multiple servers. Let’s examine these technologies and how they evolved to address the growing demands of large-scale LLM training.</p><h4>Intra-Node GPU Communication</h4><p><strong>PCI Express (PCIe) </strong><br>Initially, PCI Express (PCIe) connected GPUs to the system’s root complex, providing offload capabilities at generations like PCIe 4.0 (~32 GB/s for x16) and 5.0 (~64 GB/s for x16). While sufficient for early GPU computing, PCIe’s point-to-point interconnect design and relatively high latency made it a bottleneck in multi-GPU deep learning, as data repeatedly traversed the CPU or chipset.</p><p><strong>NVLink</strong><br>To address PCIe’s limitations, NVIDIA developed NVLink, offering direct, point-to-point GPU-to-GPU connections for large data transfers. NVLink was designed as a dedicated, high-bandwidth, low-latency interconnect specifically engineered to address the intra-node communication bottleneck. Unlike PCIe, which is a general-purpose bus, NVLink is a point-to-point, direct connection between GPUs. This direct connection, leveraging advanced signaling and streamlined protocols, allows NVLink to deliver significantly higher bi-directional bandwidth and lower latency compared to PCIe for GPU-to-GPU data exchange. NVLink effectively bypasses the PCIe bus for critical GPU-to-GPU communication, creating a fast efficient pathway for data sharing and synchronization within a single server-node/SuperPOD. Often, GPUs incorporating NVLink are packaged in <strong>SXM (Server PCI Express Module)</strong> form factors, which provide the necessary power and cooling for these high-performance components and facilitate dense GPU deployments in server environments.</p><p><strong>NVSwitch </strong><br>As systems grew to eight GPUs or more, wiring a full NVLink mesh became complex. NVSwitch acts as a high-radix, non-blocking crossbar switch designed to aggregate multiple NVLink connections. It essentially creates a centralized hub that allows every GPU within a node to communicate with every other GPU via NVLink, through the NVSwitch fabric. This allows for the creation of highly interconnected intra-node GPU systems, significantly expanding the number of GPUs that can efficiently communicate at NVLink speeds within a server-node/SuperPOD. NVSwitch enables the construction of powerful single-node “GPU servers” with a large count of interconnected GPUs, facilitating larger local model partitions and minimizing reliance on slower inter-node communication for certain aspects of training. By managing and optimizing the communication paths between GPUs within a node, NVSwitch further enhances the efficiency and scalability of intra-node parallelism, building upon the foundation laid by NVLink. In products like NVIDIA DGX servers, multiple NVSwitches efficiently interconnect all GPUs, removing in-node bottlenecks for large-scale distributed training.</p><h4>Inter-Node Networking</h4><p><strong>Ethernet (TCP/IP) </strong><br>For multi-node clusters, early setups used <strong>Ethernet</strong> running <strong>TCP/IP</strong>. The traditional TCP/IP stack, designed for general-purpose networking, introduces significant CPU overhead for data processing and transmission. This CPU involvement in every network operation increases latency and reduces the effective bandwidth available for application-level communication, especially when scaling to a large number of nodes requiring frequent inter-node data exchange. This overhead significantly impacts all-reduce-intensive workloads, making standard Ethernet less optimal for large-scale LLM training.</p><p><strong>RoCE (RDMA over Converged Ethernet)</strong><br>To mitigate TCP/IP overhead, HPC practitioners turned to <strong>RDMA</strong> (Remote Direct Memory Access), allowing direct reads and writes to remote memory buffers without extensive CPU involvement. RoCE (RDMA over Converged Ethernet) encapsulates RDMA within Ethernet frames, reducing latency and boosting throughput. While RoCE helps Ethernet-based clusters close some of the performance gap with specialized interconnects, ultra-high bandwidth needs still often push adopters toward purpose-built networking solutions.</p><p><strong>InfiniBand</strong><br>For the most demanding distributed LLM training scenarios, where absolute performance and scalability are paramount, InfiniBand has emerged as the leading interconnect technology. InfiniBand is a purpose-built networking standard designed from the ground up for high-performance computing and distributed environments. It incorporates RDMA in its hardware and protocol design, offering native RDMA support without relying on encapsulation like RoCE. This native RDMA implementation, combined with optimized hardware and protocols, allows InfiniBand to consistently deliver superior bandwidth and lower latency compared to Ethernet-based solutions, including RoCE. InfiniBand also includes advanced features like sophisticated congestion management and Quality of Service (QoS) mechanisms to ensure reliable and predictable performance even at massive scale.</p><p><strong>NCCL and CUDA-Aware Networking<br></strong>Irrespective of the underlying interconnect technology realizing the full potential of these hardware advancements necessitates a sophisticated software layer. Hardware performance is unlocked through software like NCCL (NVIDIA Collective Communications Library), which implements optimized all-reduce, broadcast, and other collective primitives. NCCL automatically detects and exploits whichever interconnect is present — NVLink, NVSwitch, RoCE, or InfiniBand — while CUDA-Aware Networking integrates these transfers directly with the GPU’s memory space. Together, they minimize CPU intervention and ensure near-peak interconnect utilization in deep learning frameworks like PyTorch and TensorFlow.</p><p><strong>HPC Topologies for Large-Scale GPU Clusters</strong><br>As these GPU clusters expand to encompass hundreds or even thousands of nodes, tasked with exchanging multi-terabyte-per-second data streams, the arrangement of these interconnects — the network topology — becomes equally critical. Standard, simpler network layouts often falter under such immense traffic demands. To address these challenges and ensure efficient, scalable communication in large GPU clusters for demanding workloads like LLM training, specialized <strong>HPC network topologies</strong> are essential. Topologies such as <strong>Fat-Tree, Dragonfly, and Torus </strong>are specifically designed to overcome these limitations and are crucial for maintaining performance in large-scale distributed LLM training. These topologies address the challenges of massive scale by strategically reducing network diameter, providing multiple redundant paths, and more effectively balancing traffic loads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DDxS_8b9m9C2CWDJ.png" /></figure><p>By minimizing the <strong>network diameter</strong>, which is the maximum number of network hops between any two nodes, HPC topologies directly reduce communication latency. Instead of relying on a single, potentially congested route between nodes, HPC networks are characterized by <strong>multiple redundant paths</strong>. This redundancy is vital for workloads that involve heavy all-to-all or many-to-many communication patterns, as is common in data-parallel and model-parallel LLM training. These parallel paths help to avoid the creation of congestion hotspots, ensuring more consistent and predictable network performance across the cluster.</p><p>These topologies also deliver <strong>scalability </strong>and<strong> fault tolerance</strong>. The architecture of <strong>Fat-Tree</strong> designs, for instance, allows for incremental expansion by adding switch tiers, making it relatively straightforward to scale the network as the cluster grows in size. <strong>Dragonfly</strong> and <strong>Torus</strong> layouts employ a combination of local and global connectivity to efficiently link thousands of endpoints. This hierarchical and structured approach enables these topologies to meet the massive bandwidth requirements of modern LLMs without a drastic degradation in performance as the node count increases. This scalability is essential for accommodating the ever-growing size and complexity of LLMs. If one path experiences congestion or even fails entirely, the network can seamlessly reroute traffic through alternative paths. This inherent fault tolerance is critical for maintaining high cluster throughput and ensuring the stability of long-running training jobs, protecting against disruptions caused by transient network issues.</p><p>Despite advancements in high-bandwidth, low-latency interconnects and sophisticated network topologies, scaling massive LLMs reveals fundamental limits in scale-out architectures. As clusters grow to hundreds or thousands of nodes, the assumption of linear scalability breaks down. Communication overhead quickly saturates interconnects, creating a critical bottleneck — inter-accelerator communication constraints, known as the <strong>“Interconnect Wall”.</strong></p><h4>Scale-Out Limitations: Emergence of the Interconnect Wall</h4><p>As distributed training scales from a handful of accelerators to hundreds or thousands, communication overhead becomes a formidable barrier. This “Interconnect Wall” arises when the cost of coordinating data and synchronizing computations outweighs the benefits of parallelization. In smaller clusters (2–8 accelerators), high-speed links effectively mask latency and bandwidth limitations; however, as the cluster’s <strong>world size</strong> (number of interconnected devices) grows, even minor inefficiencies — such as suboptimal routing or insufficient bisection bandwidth — can stall the entire job.</p><p>Although raw bandwidth is critical, factors like round-trip latency, contention, and fault tolerance also shape the Interconnect Wall. For collective operations such as all-reduce or all-gather, a single saturated link or a slight increase in latency can cause cluster-wide ripple effects, drastically reducing training throughput. These underlying bottlenecks expose the fundamental limits of scale-out architectures, highlighting a complex interplay of communication overhead, memory constraints, and system-level inefficiencies that collectively impede large-scale distributed LLM training.</p><h4><strong>Parallelization Strategies and The Interconnect Wall</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UJweD7VBMJ9ohPfS.png" /><figcaption><a href="https://uvadlc-notebooks.readthedocs.io/en/latest/tutorial_notebooks/scaling/JAX/tensor_parallel_simple.html">Source</a></figcaption></figure><p><strong>Data Parallelism: Distributing the Dataset<br></strong>Data Parallelism partitions the training dataset into distinct subsets, assigning each subset to a separate GPU. Each GPU processes mini-batches independently using a full replica of the model, ensuring consistency through periodic synchronization of model updates. This approach effectively utilizes multiple GPUs without requiring model modifications, making it a widely used strategy for distributed training. However, it depends on an <a href="https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/collectives.html"><strong>all-reduce</strong></a> operation to aggregate gradients across GPUs.</p><p>In large-scale deployments, all-reduce operations can consume over 90% of each training step, creating a significant bottleneck. To optimize memory usage, techniques like ZeRO and <a href="https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/#how-fsdp-works">FSDP</a> shard model states across GPUs, reducing per-device memory requirements. However, this optimization introduces additional communication overhead, as parameters, gradients, and optimizer states must be frequently exchanged to maintain consistency.</p><p>While data parallelism ensures logical consistency, frequent cluster-wide communication can slow down training, especially when substantial gradient updates require high-bandwidth networks. Since all-reduce is central to data parallelism, inefficiencies, whether due to limited bandwidth, network congestion, or synchronization overhead , can significantly impact performance. As cluster sizes grow, all-reduce overhead often becomes the dominant factor in per-step runtime, limiting scalability.</p><p><strong>Tensor Parallelism: Distributing Matrix Operations<br></strong>Tensor Parallelism focuses on distributing a model’s weight matrices across multiple devices. By splitting large matrix operations across GPUs, this method enables efficient parallel computation of the dominant workloads in LLMs. Particularly useful for large LLMs that exceed the memory limits of a single device, tensor parallelism helps balance both computational and memory demands.</p><p>Tensor parallelism partitions each layer’s parameters among multiple GPUs, reducing local memory usage but introducing significant communication of intermediate activations. Each micro-batch forward or backward pass now generates partial results that must be broadcast or gathered. If a layer is split across four GPUs, every forward pass can involve multiple parallel matrix multiplications interspersed with data exchanges. Tensor parallelism is frequently combined with data parallelism, forming a hybrid scheme that can improve GPU utilization. Yet this approach intensifies demands on the interconnect, requiring fast and reliable data exchanges to keep partial activations synchronized.</p><p><strong>Pipeline Parallelism: Overlapping Computation<br></strong>Pipeline Parallelism introduces a staged execution model by dividing the LLM into sequential stages, each assigned to a different GPU. This approach enables overlapping computation and communication, improving throughput. While one GPU processes a given stage, another GPU can begin processing the next mini-batch, reducing idle time and mitigating memory bottlenecks.</p><p>In practice, a network’s layers are divided into pipeline stages, and each stage resides on a specific GPU or group of GPUs. Micro-batches flow through the pipeline, and GPUs must wait for data from preceding stages. While pipeline parallelism can reduce memory usage (fewer layers per device), it also introduces pipeline bubbles and stage-to-stage communication overhead. GPUs must wait for output from the preceding stage, which can lower overall throughput if the network introduces extra delays.</p><p><strong>Sequence parallelism</strong> <br>Sequence parallelism focuses on partitioning long input sequences among multiple GPUs. Though it alleviates memory demands for attention, distributing the sequences requires frequent exchange of partial attention maps. When combined with tensor parallelism, network traffic increases substantially in both the depth (layers) and width (sequence length) dimensions. This multidimensional partitioning further reveals bandwidth and latency constraints in the interconnect.</p><p><strong>Expert Parallelism<br></strong>Expert Parallelism (<a href="https://docs.nvidia.com/nemo-framework/user-guide/24.09/nemotoolkit/features/parallelisms.html#expert-parallelism">EP</a>) is a specialized form of model parallelism tailored for Mixture of Experts (<a href="https://medium.com/@asheesh.goja/34ef63d95b6c#e531">MoE</a>) models, where only the expert layers are distributed across multiple GPUs, while the rest of the model remains unchanged. This approach enables efficient scaling by leveraging all-to-all redistribution of tokens or activations, offering flexibility but introducing frequent data transfers that can strain bandwidth.</p><p>A key advantage of MoE is its ability to increase the model’s parameter count without a proportional rise in computation. However, routing tokens to specific experts often necessitates large-scale all-to-all operations, which become costly when tokens within a batch are assigned to different experts on separate GPUs. Each micro-batch step incurs expensive cross-node data shuffles, further compounded by load imbalance, where certain experts become “hotspots,” receiving an excessive number of tokens, leading to increased communication and compute overhead on specific GPUs.</p><p>To mitigate these challenges, strategies such as Switch Transformer, which restricts each token to a single expert, and dynamic load balancing techniques help reduce congestion. However, efficient scaling ultimately depends on high-performance networking, ensuring that distributed systems can avoid bottlenecks and sustain optimal throughput.</p><h4><strong>Checkpointing, Fault Tolerance, and Concurrency Overheads</strong></h4><p>Beyond communication overheads, another key challenge in distributed LLM training is ensuring resilience against failures and optimizing memory usage. As workloads scale across thousands of nodes, maintaining fault tolerance and managing stateful execution become increasingly complex. Checkpointing, Fault Tolerance, and Concurrency Overheads play a crucial role in addressing these challenges, enabling efficient recovery from failures, optimizing memory utilization, and balancing computational loads to sustain high-performance training.</p><p><strong>Checkpoint Overheads <br></strong>As model sizes grow, checkpoint data can range from tens to hundreds of gigabytes per snapshot. Writing these checkpoints to a distributed file system or object store can saturate network links. Full checkpoints demand simultaneous writes from all GPUs, intensifying overall cluster traffic and risking performance collapse if the storage or network layers are not carefully orchestrated. Layer-wise or asynchronous checkpoint attempt to stagger the write load, but background traffic can still contend with real-time gradient synchronization, compounding the Interconnect Wall.</p><p><strong>Fault Tolerance and Blast Radius</strong> <br>At large scale, the probability of node or link failure within a multi-day or multi-week training job becomes significant. Failures can force partial restarts, re-partitions, or slow re-synchronizations that temporarily overload the network. Topologies like a torus or mesh can see entire segments of the network impacted by a single node failure. Even well-connected fat-tree networks experience performance dips if specialized congestion control or resilience mechanisms are not in place.</p><p><strong>Orchestration Spikes</strong> <br>When a fault occurs or a reconfiguration is triggered (e.g., resizing job resources to match load or forcibly replacing defective nodes), orchestration frameworks (SLURM, Kubernetes, or HPC schedulers) initiate data movement in bulk. This can produce “<strong>network storms,</strong>” where nodes exchange large volumes of model state or re-shard the training data, further exposing the cluster to potential slowdowns if not meticulously managed.</p><h4><strong>Memory Management Pressures</strong></h4><p>As LLMs continue to scale, the need for efficient memory allocation becomes paramount. Techniques like activation checkpointing and optimizer state sharding aim to reduce per-GPU memory footprint, but they come with their own trade-offs, particularly in terms of recomputation and communication overheads.</p><p><strong>Activation Checkpointing and Recomputation</strong> <br>LLMs frequently exceed available device memory when processing large batch sizes and extended sequence lengths. Activation checkpointing addresses this by selectively storing only a subset of activations in memory and recomputing the remaining activations on-demand. This approach effectively reduces peak memory usage, allowing larger models to fit onto fewer GPUs. However, this memory-saving benefit comes with a trade-off: significant computational overhead due to additional forward passes needed during recomputation. Specifically, the backward pass latency increases due to these recomputation steps, leading to higher FLOPS and increased utilization of on-chip computation and memory bandwidth.</p><p><strong>Sharding Optimizer States</strong> <br>Techniques like ZeRO or <a href="https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/#how-fsdp-works">FSDP</a> remove redundant storage of optimizer states by distributing them across multiple GPUs. While this approach successfully cuts per-device memory usage, it relies on low-latency, high-bandwidth communication to synchronize shards during backpropagation. Hardware features such as RDMA, NVLink can help, but at massive scale, inter-node connections still risk saturation. These memory management optimizations therefore offer a trade-off: they enable larger models to train, but they also intensify the very communication overheads that define the Interconnect Wall.</p><p>Despite sophisticated model parallelization strategies, advanced high-bandwidth interconnect hardware, and complex HPC network topologies, communication overhead remains a significant barrier to large-scale distributed LLM training. Whether GPUs are connected via high-speed NVLinks, NVSwitches or InfiniBand fabrics, once clusters grow to hundreds or thousands of accelerators, the cost of synchronizing gradients, sharding model states, and handling inevitable failures can overshadow gains in compute throughput. This is the essence of the Interconnect Wall: as we push larger models across more nodes, the time spent moving data increasingly limits overall performance.</p><p>Yet, as LLMs continue to grow in complexity and scale, the demand for greater computational throughput and memory bandwidth pushes against a more fundamental barrier — one that extends beyond latency or interconnect constraints. At its core, this challenge is not just about <strong>bits</strong> and <strong>FLOPS</strong> but also about energy consumption — the critical limit of <strong>watts</strong>. This constraint, known as the “<strong>Power Wall</strong>”, imposes a fundamental ceiling on performance scaling.</p><h3>The Power Wall</h3><p>The “<strong>power wall</strong>” represents a fundamental constraint in modern computing, significantly impacting the scalability of LLMs. This barrier arises from an increasingly difficult trade-off: the relentless demand for higher computational throughput, increased memory density, and greater bandwidth to support massive LLM workloads clashes directly with the rising power consumption and heat dissipation required to maintain operational stability. As GPUs scale to incorporate ever-larger transistor counts and denser memory architectures, their power consumption grows non-linearly, governed by fundamental semiconductor physics. In dense compute environments, this scaling issue becomes especially critical, as heat dissipation transitions from a design challenge to an absolute limiting factor. At a certain point, the heat generated — directly proportional to power consumption — can no longer be efficiently removed, imposing a hard thermal constraint. Beyond this threshold, even the most advanced cooling solutions become inadequate. When these limits are reached, thermal throttling mechanisms automatically activate, lowering clock frequencies and even deactivating cores, ultimately capping real-world performance. This creates the power wall, a fundamental barrier that prevents further scaling based solely on increasing computational and memory density. Consequently, the power wall is not just an energy consumption issue but, more crucially, a thermal management challenge that dictates the practical power delivery limits of computing devices.</p><p>The impact of the power wall is a widening gap between theoretical and practical compute capacity. While latest GPUs may boast over 1000+ TFLOPS (FP16/BF16) of theoretical performance, power constraints typically restrict sustained workloads to just 60–80% of this potential. This efficiency drop-off creates a significant bottleneck in real-world LLM training and inference, where sustained high compute throughput is essential. To fully understand this limitation, we must examine the fundamental physics of CMOS technology, which underpins modern processors and ultimately dictates the power-performance trade-offs shaping computing today.</p><h4>CMOS Technology</h4><p>Complementary Metal-Oxide-Semiconductor (CMOS) technology integrates pairs of p-type and n-type metal-oxide-semiconductor field-effect transistors (MOSFETs) to implement high-density logic functions efficiently. These complementary transistor pairs allow for push-pull circuit configurations where power is primarily consumed during switching operations. Ideally, static power consumption is very low; this historic advantage stems from the complementary nature of PMOS and NMOS transistors. In CMOS logic gates, paired PMOS and NMOS transistors are arranged so that when one conducts, the other remains off. This design ensures that no direct conductive path exists between the supply voltage (Vdd) and ground (Vss) under steady-state conditions, minimizing continuous power loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-iTsW_9B3jQU4I_P.png" /></figure><p>Unlike older bipolar junction transistors (BJTs) that consume power even when idle, CMOS transistors dissipate energy only during switching events, making them highly efficient. This enables CMOS gates to achieve remarkably low energy dissipation — measured in femtojoules per gate evaluation — while operating at picosecond speeds, facilitating high-speed computing. Coupled with exceptional density, CMOS technology allows for the fabrication of billion-transistor chips that maintain reliability. Additionally, its cost-effectiveness supports the production of complex chips at scale, highlighting an unmatched combination of performance, efficiency, density, and affordability.</p><p>This fundamental advantage has enabled the integration of billions of transistors on a single die, driving the advanced compute capabilities essential for modern GPUs. It also fueled the initial scaling benefits predicted by Moore’s Law. However, these gains came with significant power management challenges. As transistor densities increased, the semiconductor industry relied on another key principle to control power consumption, known as <strong>Dennard scaling</strong>. However, this approach eventually broke down, leading to the power wall predicament we face today.</p><h4>Dennard Scaling</h4><p>Historically, Dennard scaling (also known as MOSFET scaling) offered an elegant solution to the power problem. First described by Robert H. Dennard in 1974, this principle stated that as transistors shrank in size, their power density would remain constant. Specifically, reducing transistor dimensions by a factor of <strong>1/k</strong> would permit voltage and current scaling by the same factor, allowing clock frequencies to increase by a factor of <strong>k</strong> for roughly the same power draw per unit area.</p><p>This remarkable property meant that smaller transistors could operate faster while consuming proportionally less power individually, keeping the overall power density unchanged. In practical terms, this allowed chip designers to pack more transistors into the same die area and run them at higher frequencies without encountering thermal issues. This virtuous cycle drove processor performance improvements for decades, with each new process-node delivering substantial gains in both performance and energy efficiency. However, these benefits have waned significantly since the mid-2000s when process-nodes dropped below 90nm. Voltage no longer scales down seamlessly with transistor size due to quantum tunneling effects and subthreshold leakage. While the ideal threshold voltage (Vt) should scale with transistor dimensions, maintaining a minimum threshold voltage became necessary to prevent excessive leakage, creating a “<strong>voltage wall</strong>” around 1V.</p><p>Additionally, leakage currents rise sharply as transistors shrink, introducing significant static power consumption that wasn’t accounted for in the original Dennard scaling model. This means boosting clock frequencies further escalates both dynamic and static power consumption in a superlinear fashion. Even though transistor counts continue to grow according to Moore’s Law (doubling roughly every 18–24 months), processor performance today is bounded less by raw transistor availability and more by power delivery and thermal dissipation limits. This shift marks the era of <strong><em>post-Dennard scaling</em></strong>, where increasing transistor density no longer directly translates to proportional performance gains.</p><h4>The Switching Power Equation</h4><p>The switching power equation provides a mathematical foundation for understanding the link between performance and power consumption (P) in CMOS chips:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SnPUov95MkxdAkzbohJi6w.png" /></figure><p>Where Q is the activity factor, C represents the load capacitance, V the operating voltage, and f the frequency of switching. This equation reveals that performance gains, often pursued through higher clock frequencies (f) and sometimes higher voltages (V) to drive transistors faster, directly and significantly increase power demands. The squared term for voltage (V²) emphasizes the dramatic impact of voltage scaling on power. This relationship creates a critical dynamic: as GPUs are pushed for higher performance in LLM workloads, they inevitably face thermal throttling when heat dissipation exceeds the system’s safe limits, especially under compute intensive workloads like LLM training. Modern GPUs typically operate very close to their thermal limits, with junction temperatures often reaching 85–95°C during sustained workloads, leaving minimal thermal headroom for performance optimization. Additionally, capacitance C is sum of gate capacitances, diffusion capacitances, and interconnect (wire) capacitance. As transistors continue to shrink, wire capacitance doesn’t scale down as effectively as the others. As a result, it becomes a larger fraction of the total capacitance, which in turn has a significant impact on both power consumption and signal delay.</p><p>Moreover, the era of post-Dennard scaling highlights a concerning discrepancy between gains in transistor density and corresponding improvements in power efficiency. With each new semiconductor process node, transistors shrink by a scaling factor S (reducing linear dimensions by 1/S and increasing density by S²), theoretically enabling performance scaling towards S³ via higher density and frequency. However, the foundational principle of Dennard scaling — constant power density — ceased to hold primarily because supply voltage (Vdd) could no longer be scaled down proportionally with transistor dimensions. Attempting to do so resulted in unacceptable increases in static leakage current as threshold voltages (Vt) approached physical limits, making static power a dominant factor in modern GPUs. While transistor switching speeds improved, this inability to aggressively reduce voltage negated much of the expected power benefit for dynamic switching. Additionally, factors influencing dynamic power, such as switched capacitance (C), scaled imperfectly — often simplified to roughly 1/S for gate capacitance but with interconnect capacitance scaling less favorably. Consequently, this combination of rising static power dominance and less-than-ideal dynamic power scaling means that overall power efficiency improvements now significantly lag behind the gains achieved purely through increased transistor density.</p><p>This discrepancy leads to a situation where power efficiency improvements lag behind performance gains. Instead of the full theoretical potential, power efficiency improves by roughly 40% per generation, according to estimations and empirical observations, further highlighting the growing power wall challenge. This efficiency gap explains why modern GPUs with billions of transistors still struggle with power density challenges despite advanced manufacturing processes.</p><p><strong>Pollack’s rule<br></strong>The scaling effects of power and performance manifest directly in single-core computational capability. Pollack’s rule, formulated by Intel’s Fred Pollack, describes how scalar performance scales with the square root of transistor resource allocation, whereas power consumption can grow at an even faster rate. Mathematically, when using r transistor resources, scalar performance only rises to: Perf(r) = √r, while power consumption increases much more aggressively as <strong>P = Perfᵅ</strong>, where <strong>α</strong> is empirically observed to be approximately 1.75 for modern processors. This means power increases nearly quadratically with targeted performance improvements. The power can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmOgmp-997ob7aSX87P6zw.png" /></figure><p>With α = 1.75, this becomes P ∝ r⁰․⁸⁷⁵, demonstrating how quickly power requirements escalate with increased transistor resources. For example, doubling the transistor count (r → 2r) only improves performance by about 41% (√2 ≈ 1.41), but increases power consumption by approximately 84% (2⁰.⁸⁷⁵ ≈ 1.84).</p><p>This disproportionate relationship between resource allocation and performance gains explains why simply adding more transistors to processors yields diminishing returns, pushing the industry toward specialized architectures and heterogeneous compute solutions that allocate transistor resources more efficiently based on workload characteristics. The implications of Pollack’s rule become even more significant when considered alongside another major challenge in semiconductor scaling: the phenomenon known as dark silicon.</p><h4>Dark Silicon and the Voltage Scaling Barrier</h4><p>As transistor geometries shrank below the 65nm node, static leakage currents in nominally “off” transistors became a substantial component of total power consumption. While quantum tunneling through thin gate oxides contributes, the dominant factor is often subthreshold leakage, which increases exponentially as the transistor’s threshold voltage (Vt) is lowered to enable faster switching and lower operating voltages. Process engineers face a critical trade-off: a lower Vt enhances performance but drastically increases this leakage. Consequently, maintaining acceptable static power imposes a practical minimum Vt floor, exacerbated by quantum effects and other short-channel behaviors at advanced process-nodes.</p><p>Reliable high-frequency operation requires a supply voltage (Vdd) sufficiently above this Vt threshold to ensure transistors switch quickly enough. Attempting to operate below the Vdd required for a target frequency results primarily in timing failures and functional errors, rather than directly causing an exponential increase in leakage. Therefore, the practical Vt floor dictates a corresponding minimum Vdd floor needed to achieve high performance goals (historically in the ~0.7–1.0V range for many planar MOSFETs, though the exact value varies depending on transistor types like FinFETs or GAAFETs ).</p><p>This inability to continue scaling voltage aggressively alongside feature size marks the breakdown of traditional Dennard scaling, meaning that power density (<strong>watt</strong>/mm²) no longer scales favorably with smaller transistors. While rooted in fundamental physics, this barrier presents immense ongoing engineering challenges, tackled by innovations like High-K Metal Gate stacks, FinFETs, and emerging Gate-All-Around (GAA) structures designed to improve electrostatic control and mitigate leakage.</p><p>The direct architectural consequence is that we can integrate far more transistors than we can afford to power and cool simultaneously at peak performance. This leads inevitably to designs where significant portions of the chip must be selectively power-gated (“<a href="https://www.bsg.ai/papers/taylor_dark_silicon_horsemen_dac_2012.pdf"><strong>dark silicon</strong></a>”), operated dynamically at reduced voltage and frequency states (“<strong>dim silicon</strong>” via DVFS), or functionality must be implemented using specialized hardware accelerators (like the Tensor Cores) which execute specific tasks far more energy-efficiently than general-purpose cores.</p><h4>Thermal Design Power (TDP) Constraints</h4><p>Managing “dark” and “dim” silicon is fundamentally tied to thermal constraints. While total chip power may be capped, the trend of packing more transistors into smaller areas significantly increases power density, making heat dissipation a central challenge in chip design and sustained performance. This thermal limitation is formally captured by the concept of Thermal Design Power (TDP), which represents the maximum amount of heat a chip is expected to generate under typical high-load conditions. TDP, in turn, defines the cooling requirements and plays a crucial role in shaping both the achievable performance and the architecture of modern processors and accelerators. Unlike transient power spikes, which may briefly exceed TDP during burst workloads, TDP sets a ceiling on sustained power draw — exceeding it over time risks overheating, thermal damage, and long-term reliability issues. The relationship between temperature rise above ambient (ΔT) and TDP follows the basic heat transfer equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYuATYPZsrqwwehMctPrfw.png" /></figure><p>where <strong>Tmax</strong> is the maximum temperature rise, <strong>Rconv</strong> is the heatsink thermal convection resistance, <strong>k</strong> incorporates many-core design properties and <strong>A</strong> is the chip area. This relationship reveals why power density becomes increasingly problematic as chips shrink or become more densely packed with transistors. When chip area (A) decreases, the temperature rise increases proportionally if TDP remains constant. Conversely, maintaining the same temperature requires reducing TDP as chip area shrinks, directly limiting performance.</p><h4>CoWoS Packaging and Thermal Challenges</h4><p>Balancing thermal design power (TDP) constraints is deeply intertwined with advanced packaging strategies that enhance memory bandwidth and interconnect density. As <a href="#8783">discussed earlier</a>, CoWoS packaging offers significant performance advantages through high-density integration, but this same density introduces formidable thermal management challenges, exacerbating power wall constraints.</p><p><a href="#92b6">Several factors</a> contribute to the complexity of thermal regulation in CoWoS packaging. Vertical HBM stacks create localized hotspots with high thermal resistance paths to heat sink, while densely packed TSVs can contribute to localized heating by concentrating power delivery and disrupting lateral heat spreading paths within the silicon. The silicon interposer further impedes heat dissipation, and the RDLs add additional thermal barriers. Compounding these issues, differences in the thermal expansion coefficients of various materials introduce mechanical stress under temperature fluctuations, raising reliability concerns. While this architecture mitigates traditional photolithographic reticle size limitations, it also increases power density, amplifying thermal challenges and complicating heat management.</p><p><strong>Industry Example: </strong>NVIDIA<strong>’s Blackwell — </strong>The impact of CoWoS-L packaging is evident in NVIDIA’s Blackwell GPUs (B100 and B200), which utilize this technology to achieve 10 TB/s interconnect speeds through carefully positioned LSI bridges. However, thermal expansion mismatches between GPU chiplets, bridges, the RDL interposer, and the motherboard substrate can lead to warping and operational failures under stress. To address these challenges, NVIDIA redesigned the top metal layers and bump structures, improving yield and reliability. This example underscores the delicate balance between maximizing compute density and managing the thermal and mechanical complexities inherent in CoWoS-L packaging.</p><h4>Thermal-Induced HBM Slowdown</h4><p>HBM performance also suffers significantly under heat because charge stored in its DRAM’s tiny capacitors leaks away faster at higher temperatures, requiring more frequent <a href="#50c7">refresh cycles</a>. As GPUs operate at high utilization and generate intense heat, the nearby HBM becomes more vulnerable to thermal degradation and must refresh more often to prevent data corruption. Each refresh operation removes memory from availability and consumes extra power, creating a feedback loop in which the temperature of the HBM continues to climb, prompting even more refreshes. At smaller process-nodes (&lt; 7nm) where leakage and <a href="https://people.inf.ethz.ch/omutlu/pub/HBM_RowHammer_dsn-disrupt23-talk.pdf">rowhammer</a> vulnerabilities become more pronounced, and with CoWoS packaging placing HBM in close proximity to hot GPU logic, managing heat dissipation grows increasingly complex. System architects must therefore consider thermal throttling, larger buffering mechanisms, and other design adjustments to ensure reliability and maintain memory throughput. This highlights how thermal density and power constraints are tightly intertwined across both GPU compute and HBM subsystems.</p><h4>Thermal Limits and Power Throttling in GPUs</h4><p>When GPUs operate under sustained high computational loads, typical during LLM training or inference, the physical limitations of silicon become evident through the complex interplay between switching power consumption and the thermal management required for cooling. Dynamic (switching) power consumption occurs as transistors change states during computation. As billions of transistors rapidly switch states under intense workloads, power consumption quickly approaches the GPU’s TDP, typically up to 700W for an NVIDIA H100 (SXM) and up to 1KW for an B200.</p><p>To manage these power constraints, GPUs employ sophisticated techniques such as Dynamic Voltage and Frequency Scaling (DVFS). DVFS dynamically reduces the voltage and frequency of the <a href="#ee91">SMs</a> as the GPU approaches its maximum cooling capacity or TDP limit. Lowering voltage and frequency decreases the transistor switching speed, which directly impacts computational performance. As a result, GPUs experience a reduction in clock frequency, thereby lowering overall performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*u_SqdgrIOXIO6vYp" /><figcaption><a href="https://www.thonking.ai/i/142508107/marketing-vs-real-performance">Source</a></figcaption></figure><p>This power throttling mechanism creates a discrepancy between advertised theoretical performance and actual sustained performance. GPU manufacturers often highlight peak theoretical performance metrics based on maximum achievable clock frequencies. However, under realistic workloads, such peak frequencies cannot be sustained due to thermal and power constraints. Empirical data shows that GPUs running intensive matrix multiplication workloads often operate at lower clock speeds than advertised. For instance, while the NVIDIA H100 (SXM) has a theoretical TF32 Tensor Core performance (with sparsity) of 989 TFLOPS, achieving this requires sustaining a boost clock speed of 1.830 GHz. However, under sustained heavy loads like LLM workloads, TDP limits often prevent GPUs from consistently maintaining peak boost clocks. This throttling reduces sustained FLOPS below advertised peak theoretical levels. Consequently, the actual energy efficiency (<strong>FLOPS/watt</strong>) achieved differs from simple peak-based calculations, especially since peak theoretical efficiency often occurs below maximum power limits, not at the thermal ceiling.</p><h4>Data Movement: The Hidden Power Sink</h4><p>While power throttling mechanisms like DVFS mitigate thermal constraints, they do not address another often-overlooked challenge, the energy cost of data movement. As LLMs push the boundaries of computational demand, this cost becomes a critical bottleneck. The gap between the energy required for computation and data transport is several orders of magnitude wide, and this gap continues to widen. While GPUs excel at executing arithmetic operations with remarkable energy efficiency, the energy required to fetch data from memory is significantly higher. For example, the B100 (SXM) achieves an impressive <strong>5 TFLOPS/watt</strong> for sparse FP16/BF16 operations, translating to just <strong>0.2 pJ/FLOP</strong>. In contrast, fetching data from HBM consumes around <strong>6–10 pJ/bit</strong>. Even with on-chip <a href="#7840">L0-L2 cache</a> hierarchies designed to mitigate these costs, accessing them still incurs significant energy overhead. Instruction cache access alone can consume up to a third of a processor’s instruction energy, while data cache access, though beneficial, restricts potential energy savings to just three to four times compared to an ideal system with no memory access overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9Wn224t2u_rmMWKoVEF2Q.png" /><figcaption><a href="https://berkeley-deep-learning.github.io/cs294-dl-f16/slides/DL_HW_Berkeley_0916.pdf">Source</a></figcaption></figure><p>All of this ties back to a deceptively simple principle often expressed in the equation: <strong>P = Eₒₚ × OPS, </strong>where <strong>P</strong> is power, <strong>Eₒₚ</strong>​ is energy per operation, and <strong>OPS</strong> represents the operations per second. In the context of LLMs, where we often push trillions of operations per inference or training pass, this relationship becomes a central challenge. Even if each multiply-accumulate (MAC) or fused multiply-add (FMA) is highly efficient on its own, the sheer number of operations multiplies overall power consumption. And when each of those operations triggers data retrieval from caches, HBM, or even more remote memory layers, the effective <strong>Eₒₚ</strong>​ balloon thanks to these heavier data-transfer costs. As a result, simply adding more GPU cores or increasing clock speeds won’t effectively boost OPS without also driving up power consumption (P). Instead, any real gains must come from reducing <strong>Eₒₚ</strong>​ at every step, especially the hidden cost of moving data.</p><p>In essence, the power equation forces a balancing act: to keep OPS high without blowing past TDP, engineers must relentlessly shrink <strong>Eₒₚ</strong>, both for the arithmetic itself and for every step of the memory journey that feeds those operations. This tight linkage between computation and data transport underscores why advanced packaging techniques like CoWoS or chiplet-based approaches only partially alleviate the problem. They may shorten some interconnect distances and improve heat dissipation, but fundamentally you still have to move vast volumes of data across the chip boundary and through on-die caches. Consequently, tackling data movement inefficiencies remains a top priority. Novel architectures that bring compute closer to memory, domain-specific accelerators that minimize off-chip accesses, and software optimizations that restructure models or batching strategies to boost data locality are all crucial.</p><h3>Conclusion</h3><p>In this dynamic interplay of bits, FLOPS, and watts, we glimpse not just the future of LLMs, but the fundamental nature of artificial intelligence itself, currently bound to the silicon that gives it form and the thermodynamic principles that shape its evolution. This reality challenges us to rethink how intelligence is realized within computational substrates. Nature, through billions of years of evolution, has optimized biological intelligence to operate at milliwatt-scale power budgets with remarkable efficiency. In contrast, silicon-based intelligence remains orders of magnitude less efficient, a gap highlighted by the growing energy demands of ever-scaling LLMs. As detailed in this two-part series, the pursuit of larger and more capable LLMs — driven by neural scaling laws — now collides with “Walls of Silicon”: limitations imposed by memory capacity, power consumption, and interconnect bandwidth. These constraints, rooted in CMOS density limits, thermal envelopes, and the finite speed of causality, underscore the need for a holistic approach that balances computational throughput, memory bandwidth, and energy efficiency.</p><p>Within existing architectures, hardware-aware algorithmic advancements like FlashAttention-3 and sparse attention mechanisms are already improving LLM performance. Meanwhile, alternative model architectures, such as state-space models (SSMs) and diffusion-based LLMs, explore different computational patterns that may present alternative hardware efficiency profiles compared to Transformers, though they still demand significant compute and energy resources and require their own hardware-specific optimizations. Adding further complexity, sophisticated reasoning models such as DeepSeek-R1 and OpenAI’s o1/o3 have increased computational demands during inference, not just during training. Despite innovations like DeepSeek’s MLA and MTP, such models rely on generating intermediate, non-deterministic representations — often called “thinking tokens” — before arriving at the output token. This multi-step CoT reasoning process demands significantly larger KV caches, more computational power, and higher memory bandwidth, ultimately resulting in increased latency and reduced efficiency in parallelization and batching. Furthermore, recent advancements in Agentic AI, often requiring numerous inference calls per task, are driving inference-time computational demands at an unprecedented pace, shifting focus from peak training throughput to inference latency, cost-per-query, and energy efficiency.</p><p>As these demands grow exponentially, they push the limits of current semiconductor technologies and energy infrastructures, making it increasingly vital to move beyond traditional von Neumann architectures. To meet these demands, the next generation of compute architectures is emerging — featuring tailored instruction set architectures (ISAs), dataflow-centric execution models, and memory hierarchies, each designed to maximize the efficiency required by modern LLM workloads. Realizing this ambitious future will require deep and sustained collaboration between hardware engineers and AI researchers to pioneer entirely new computing paradigms. This collaboration becomes even more critical with the rise of multimodal and embodied LLMs, which integrate vision, language, and other modalities into unified networks, placing extreme demands on memory systems and interconnect designs, which must efficiently support cross-modal attention and data flow.</p><p>Looking further, radical innovations in photonic computing, reversible logic, and biologically inspired neuromorphic systems offer intriguing opportunities to break through the walls of silicon-based hardware. Ultimately, the future of LLM scaling lies not in forcing tomorrow’s models onto yesterday’s hardware but in co-designing algorithms and computing substrates that work in harmony with — rather than against — the fundamental physics of information processing.</p><p><strong>Upcoming</strong><br>In the next installment of this series, we will explore one of the most promising frontiers in hardware-software co-design: ASIC-based Domain-Specific Architectures (DSAs). Unlike general-purpose accelerators, DSAs address computational challenges at their core rather than working around them. By redesigning computation at every level — from dataflow execution and optimized memory locality to specialized pipeline processing and deterministic execution — DSAs offer a path beyond the constraints of conventional computer architectures. In doing so, they unlock new dimensions of LLM scaling — balancing computational throughput, memory bandwidth and energy efficiency — and bring us closer to realizing the full potential of Artificial General Intelligence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce397041dec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bits, FLOPS, and Watts: A Systems-Level Perspective of Scaling LLMs — Part 1]]></title>
            <link>https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-1-34ef63d95b6c?source=rss-8b819656b4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/34ef63d95b6c</guid>
            <dc:creator><![CDATA[Asheesh Goja]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 20:06:46 GMT</pubDate>
            <atom:updated>2026-03-20T19:10:27.356Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bits, FLOPS, and Watts: A Systems-Level Perspective of Scaling LLMs — Part 1</h3><h4>The Laws of Scaling</h4><h3>Introduction</h3><p>Scaling Large Language Models (LLMs) goes beyond simply increasing parameter counts. It emerges from a complex interplay of hardware, software, and algorithmic optimizations. These deep neural networks operate in high-dimensional vector spaces with complex loss landscapes and scaling power laws, where learning unfolds along intricate manifolds that often defy human intuition. Yet their existence is tethered to silicon and electricity — bound by thermodynamics, semiconductor physics, and the finite resources of our four-dimensional world. Ultimately, the mathematics of LLMs is bound by the very physics of silicon.<br><em>(</em><a href="https://github.com/asheeshgoja/bits-flops-and-watts/raw/main/Bits,%20FLOPS,%20and%20Watts_%20A%20Systems-Level%20Perspective%20of%20Scaling%20LLMs.pdf"><em>PDF version the paper</em></a><em>)</em></p><p>To understand their evolution, we must trace the journey of neural architectures from simple single-layer perceptrons to today’s trillion-parameter Transformers. At every stage, algorithmic breakthroughs and hardware advancements have propelled each other forward. As transistor scaling, memory bandwidth, and parallelism improved, each wave of innovation pushed the boundaries of what neural networks could achieve, reinforcing the deep synergy between software and silicon. Today’s relentless drive to build ever-larger LLMs stands upon that same foundation, revealing that the future of LLM scaling depends not on software or hardware alone, but on their careful co-design, emphasizing the need for a systems-level perspective on scaling.</p><p>Adopting such a perspective, the triad of Bits, FLOPS, and Watts provides a systems-level lens to understand the scaling dynamics of LLMs. Information capacity, measured in <strong>bits</strong>, is determined by parameter count, weight precision, model architecture, and data entropy, all of which collectively define a model’s representational power. Computational throughput, measured in <strong>FLOPS</strong>, directly influences both training and inference speed, shaping the model’s efficiency and responsiveness. And <strong>watts</strong> measure energy consumption, highlighting the growing power costs and associated economic implications of scaling up LLMs. Each bit, woven in LLMs vast network of weights, biases and activations, demands energy to store and process, unfolding into a cascade of FLOPS orchestrated by increasingly complex and power-hungry hardware. At the same time, the silent but absolute arbiter of watts sets the ultimate boundary for this computational symphony, reminding us that unlimited scaling remains tethered to the thermodynamic constraints of our physical universe. That limit is not arbitrary. Landauer’s principle, a cornerstone of information theory, states that erasing even a single bit of information carries an irreducible energy cost. While we are orders of magnitude above this limit, it highlights the intimate connection between information, computation, and thermodynamics. As models scale to trillions of parameters, each bit processed accumulates a thermodynamic debt that must be repaid through heat dissipation. Absent rigorous hardware software co-design and efficient energy management, the trillion-parameter LLM era risks sliding into thermodynamic insolvency.</p><p>This challenge underscores the interplay between information capacity, computational throughput, and energy consumption. Optimizing these three dimensions in tandem is crucial. It spurs the development of novel architectures, new algorithms, and hardware innovations that cater to all three resource demands holistically. This two-part series takes a deep dive into these challenges from both software and hardware standpoints.</p><h4>Part 1 Preview:<strong> The Laws of Scaling</strong></h4><p>We will begin <a href="#a1ba">part 1</a> by tracing the evolution of LLMs, highlighting the critical role of software and hardware co-design in shaping deep neural networks. From there, we develop an intuitive understanding of neural scaling laws and their relationships with model performance, compute, data, model size, and the emergence of intelligence. We will also examine how these scaling laws extend to inference-time compute in models like o1/o3 and DeepSeek-R1, and how they relate to advanced reasoning capabilities such as Chain-of-Thought (CoT). Throughout this exploration, we introduce pivotal theoretical concepts such as irreducible entropy, the efficient-compute frontier, emergent abilities, and the manifold hypothesis. These concepts will illuminate both the extraordinary potential and the fundamental limitations of LLMs.</p><p>Next, we conduct a thorough analysis of the <strong>Transformer</strong> architecture, uncovering its theoretical underpinnings and the mechanisms by which it generates language with unreasonable effectiveness. We explore why Transformers serve as the backbone of LLMs and how its design choices influence scalability, especially the significant demands placed on the underlying compute infrastructure by Transformers inherent algorithmic complexity. We will focus on topics such as the arithmetic intensity of self-attention, the space complexity of the KV cache, the overhead of non-linear operations, and the role of sparsity in attention. This exploration will reveal how this complexity necessitates increasing amounts of memory (bits), computational throughput (FLOPS), and, most critically, leads to the unsustainable cost of power (watts) required to train and run today’s trillion-parameter LLMs.</p><p>By the conclusion of <a href="#a1ba">part 1</a>, we establish a central tension at the heart of LLM advancement: while neural scaling laws push us inexorably toward ever-larger models in our quest for Artificial General Intelligence (AGI), the algorithmic complexity of Transformers creates physical bottlenecks that cannot be overcome through software optimization alone. This comprehensive framework sets the stage for <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-2-ce397041dec2">Part 2</a>, where we will analyze the critical triad of bits, FLOPS, and watts from a systems-level perspective, exploring potential pathways forward in addressing these challenges.</p><h4><strong>Part 2 Preview: The Walls of Silicon</strong></h4><p>In <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-2-ce397041dec2">Part 2</a>, we explore how the fundamental interplay between bits, FLOPS, and watts erects three critical barriers in GPU-based accelerated computing: the <strong>Memory Wall, Power Wall, and Interconnect Wall</strong>. These barriers aren’t merely engineering challenges, they represent fundamental physical principles governing semiconductor technology and information processing. At their core, these walls arise because information in physical form requires space (memory), energy (power), and efficient pathways (interconnects) — all finite resources constrained by transistor density, heat dissipation limits, and the speed of light. In silicon-based computers operating at the nanometer scale, electrons simultaneously serve as both carriers of information and energy, embodying bits and watts within a single quantum entity.</p><p>Our exploration begins with an examination of how modern GPUs operate, focusing on execution flow, tensor cores, and warp schedulers. We’ll analyze a kernel performing WMMA (warp matrix multiply-accumulate) operation using low-level <a href="https://medium.com/@asheesh.goja/ce397041dec2#e0b2">PTX ISA</a>, revealing how the “<strong>Memory Wall</strong>” naturally emerges from the classical Von Neumann architecture. This wall represents the growing disparity between computational capability and memory performance — a gap that widens as processing power increases. To understand this challenge more deeply, we’ll examine hierarchical memory structures, from on-chip SRAM to off-chip HBM, and use frameworks like the Berkeley Roofline Model to demonstrate how this bottleneck becomes particularly pronounced in Transformer-based LLMs, preventing GPUs from achieving their theoretical compute throughput.</p><p>As we push against memory limitations, the typical response is to scale up individual GPUs with more compute and memory. However, this approach eventually hits insurmountable limits due to photolithographic reticle size constraints and the complexities of advanced multi-chip module packaging techniques like CoWoS. These physical constraints force a shift toward scale-out architectures with massive GPU clusters. This transition, however, introduces our second major barrier: the <strong>Interconnect Wall</strong>. Coordinating computations and exchanging data across thousands of interconnected GPUs creates new bottlenecks, as LLM parallelization strategies demand extreme bandwidth and low latency. We’ll examine how these requirements push interconnect technologies like NVLink and InfiniBand to their physical limits, further constraining our ability to scale efficiently.</p><p>The third constraint, the<strong> Power Wall</strong>, not only drives power consumption toward <strong>gigawatt</strong> levels in future GPU clusters but also prevents individual GPUs from hitting their theoretical peak in high-intensity LLM workloads. By examining the physics of CMOS technology and mathematical relationship between clock frequency, voltage, and power consumption, we discover why performance gains inevitably lead to large increases in power draw. Because a significant portion of that power turns into heat, TDP (Thermal Design Power) becomes an unyielding limit, prompting solutions like Dynamic Voltage and Frequency Scaling (DVFS) to prevent overheating at the cost of peak GPU performance. Beyond raw FLOPS, we’ll also explore why data movement can consume orders of magnitude more energy than the computations themselves, creating a persistent efficiency bottleneck despite extraordinary GPU power.</p><p>By the end of <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-2-ce397041dec2">Part 2</a>, it will be clear that these three “Walls of Silicon” fundamentally constrain our ambitions to scale LLMs. The path forward demands more than just optimizing our existing GPU hardware — it calls for truly novel compute architectures, new memory technologies, advanced interconnects, or alternative computing paradigms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vOagmiR_4jVD3iJ-T8qXMQ.png" /><figcaption>Synthetic Sentience within Silicon Walls</figcaption></figure><h3>Part 1</h3><h4><strong>Early Neural Architectures - From Perceptrons to LSTMs</strong></h4><p>The journey of neural network development began with the simplest form: single-layer perceptrons, designed for basic classification tasks. These early models, while conceptually groundbreaking, quickly encountered limitations, particularly their inability to solve non-linear problems. A notable example was their failure to learn the XOR function, a fundamental logical operation. This limitation, among others, contributed to a period of reduced research activity known as the first “<a href="https://seantrott.substack.com/i/140563576/the-first-ai-winter">AI Winter</a>.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5bpImHF7YJ5wKX7ueCYIYA.png" /></figure><p>The field experienced a resurgence with the development of Multilayer Perceptrons (MLPs) and the introduction of the backpropagation algorithm. Backpropagation, a method for calculating gradients of the loss function with respect to network weights, enabled the training of these deeper networks. However, progress was hampered by the limited processing capabilities of CPUs in the 1990s. These computational constraints restricted both the size and complexity of networks that could be practically trained and deployed. Despite these hardware limitations, the combination of multi-layer architectures and gradient-based optimization through backpropagation demonstrated the vast potential of neural networks and laid crucial theoretical foundations for future advancements.</p><p>A profound transformation occurred with the advent of General Purpose GPU (GPGPU) computing. <a href="https://medium.com/p/ce397041dec2#ee91">GPUs</a>, originally designed for graphics processing, possess a highly parallel architecture that proved to be exceptionally well-suited for the matrix and vector operations that dominate neural network training. This hardware advancement enabled the practical implementation of Convolutional Neural Networks (CNNs). <a href="https://en.wikipedia.org/wiki/AlexNet">AlexNet’s</a> groundbreaking performance in the 2012 ImageNet competition, served as a powerful demonstration of the capabilities of CNNs when combined with GPU acceleration.</p><p>In parallel, sequential data processing advanced through Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM) architectures, with LSTM’s gating mechanisms providing a solution to significantly mitigate vanishing gradient issues ( shrinking of gradients during training, constraining model’s ability to capture long-range dependencies). However, processing very long sequences remained a challenge due to memory constraints and the difficulty of preserving information over many time steps. Also the inherently sequential processing nature of RNNs and LSTMs did not align well with the parallel processing capabilities of modern GPUs, leading to inefficiencies in training and inference.</p><p>Throughout these developments, it became evident that advancements in algorithms were inherently tied to hardware capabilities. Each theoretical breakthrough demanded corresponding improvements in processing power, memory capacity, and specialized hardware optimized for the linear algebra computations at the core of neural networks — all while balancing memory throughput, floating-point operations, and power constraints.</p><h4><strong>The Transformer Revolution</strong></h4><p>The introduction of the <a href="#6c46">Transformer</a> architecture in 2017 marked a pivotal shift in natural language processing and beyond. Its core innovation was the replacement of recurrent processing with <a href="#b8b6">self-attention</a>, a mechanism that allows models to process all tokens in a sequence concurrently. This enabled parallel computation, aligning seamlessly with the Single Instruction, Multiple Thread (<a href="https://medium.com/@asheesh.goja/ce397041dec2#d145">SIMT</a>) architecture of GPUs, leading to dramatic speedups in training. By eliminating the hidden state bottleneck of RNNs, Transformers unlocked scalability to hundreds of layers and billions of parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yd67yF3RAmz2Uj1N5eU3Q.png" /></figure><p>While parallelization increased computational throughput and improved FLOPS efficiency, it also introduced significant memory demands as model sizes grew. To address this, specialized hardware blocks such as tensor cores were developed to optimize the mixed-precision matrix multiplications at the heart of Transformer computations, illustrating the co-evolution of hardware and software to accommodate ever-growing model complexity.</p><p>LLMs have demonstrated that increasing the number of layers and parameters can lead to significant improvements in performance, where performance refers to a model’s ability to effectively complete its intended tasks. This scaling has allowed models to tackle problems once deemed too complex for neural networks. However, this raises a fundamental question: <em>how exactly does performance improve as models scale?</em> Understanding the relationship between model size and its effectiveness is crucial, and this is where scaling laws come into play.</p><h3>The Laws of Scale</h3><p>Scaling laws provide a framework for understanding how model size, dataset size, and computational budget collectively influence overall performance. LLMs have consistently followed a “bigger is better” trend, where increasing these factors leads to measurable improvements. These neural scaling laws have proven remarkably predictive across architectures and tasks, not only mapping out how performance improves but also revealing the points where gains may start to plateau. By examining the mathematics behind these laws, we can see how they unify seemingly unrelated concepts such as test loss, irreducible entropy in natural data, and the interplay between model, dataset, and compute size into a cohesive understanding of LLM scaling behavior.</p><p><strong>Power Laws<br></strong>In the early days of deep learning, researchers made a crucial observation. When they plotted test loss, which measures the error between a model’s predictions and actual values, against dataset size or model size on logarithmic scales, the data points formed remarkably straight lines. This linear trend on a log-log plot is a hallmark of an inverse power-law relationship, which can be mathematically expressed as: <strong>y = k ⋅ x⁻ⁿ</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2XK3gbw9y-QJFbbU" /></figure><p>Here, <strong><em>x</em></strong> can represent the model size (<strong><em>N</em></strong>), the dataset size (<strong><em>D</em></strong>), or the total compute used (<strong>C</strong>). <strong><em>y</em></strong> typically represents the validation or test cross-entropy loss, a key metric for evaluating the performance of LLMs. The negative power exponent (-<strong><em>n</em></strong>) is of particular interest, as it quantifies the rate at which the loss decreases as <em>N</em>, <em>D</em>, or <em>C</em> increases.</p><p>The practical significance of this power-law relationship is immense. Researchers can fit this equation to the results of relatively small-scale, and therefore less expensive, experiments. They can then use the fitted equation to extrapolate and predict the performance of much larger, more expensive runs.</p><blockquote>This predictive capability is not only scientifically illuminating but also economically advantageous. It allows research teams to forecast performance gains, manage financial risks associated with large-scale training runs, and allocate resources effectively, ensuring the right proportion of data tokens to model parameters.</blockquote><h4>Cross-Entropy Loss</h4><p>When training LLMs, a fundamental question arises: <em>how do different aspects of performance improve as we scale up the models?</em> Cross-entropy loss serves as one of our primary metrics for measuring this improvement. It evaluates how accurately a model can predict the next token in a text sequence by comparing the model’s predicted probability distribution to the actual distribution of the next token. During training, when the model generates a probability distribution over its entire vocabulary, cross-entropy quantifies the discrepancy between this predicted distribution and the true distribution of the next token.</p><p>The cross-entropy loss for a single prediction is calculated as <strong>−log(<em>p</em>)</strong>, where <strong><em>p</em></strong> represents the probability the model assigned to the correct next token. The use of the negative logarithm imposes steep penalties on predictions that are far off, meaning the loss decreases towards zero as the model becomes more confident and accurate in its predictions. However, the inherent ambiguity and variability of natural language mean that even massive models cannot achieve a perfect cross-entropy score of 0.0 on typical text datasets. This is because, for any given context, there are often multiple plausible continuations.</p><p>This fundamental limitation indicates that while scaling laws demonstrate consistent reductions in cross-entropy as we increase computational resources, training data, and model parameters, there exists a minimum threshold that cannot be crossed through additional training. The characteristics and exact value of this threshold are directly related to the concept of irreducible entropy, which we will explore next.</p><h4>The Role of Irreducible Entropy</h4><p>Even with virtually unlimited parameters, vast datasets, and boundless computational resources, LLMs cannot reduce the cross-entropy loss to zero on natural language. This inherent limitation is tied to what researchers call the irreducible entropy of the data. Natural text, as well as other modalities like images and audio, often exhibits multiple equally valid continuations or encodings. Language is replete with synonyms, colloquialisms, and stylistic flourishes that make the concept of “the single correct next word” inherently ambiguous.</p><p>One way to see irreducible entropy is to look at where the loss curves “bend.” In an idealized scenario, if the data were fully deterministic, the loss trend might continue straight toward zero. In reality, these curves eventually flatten, revealing a nonzero lower bound. While early scaling experiments by OpenAI found no obvious leveling off for large-scale language data, subsequent research from DeepMind suggested that there may be at least a small curving in the scaling plots, indicating a nonzero asymptote.</p><p>The precise value of language’s irreducible entropy remains an active area of research. Theoretical work suggests it might be around <strong>1.69 nats or 2.44 bits </strong>(equivalent to an average cross-entropy loss of 1.69 on a dataset), but conclusively determining this value would necessitate experiments even larger than current capabilities allow.</p><blockquote>Understanding irreducible entropy is crucial because it establishes the<strong> ultimate performance ceiling</strong> that LLM can achieve. Beyond this ceiling, additional scaling will not yield further improvements in terms of cross-entropy loss.</blockquote><h4>The Efficient-Compute Frontier</h4><p>When we plot model performance (such as cross-entropy loss or error rate) against computational resources on logarithmic scales, we often observe multiple descending lines. Each line typically represents a distinct model architecture or a specific set of parameters. These lines illustrate how increasing the computational budget allocated for training tends to reduce the cross-entropy loss or error rate for models of a given size. However, each line eventually plateaus, reflecting the diminishing returns that occur as we continue to invest more compute into training a model of a fixed size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JaJ2y39Z0RLTOuR_NtY6g.png" /><figcaption><a href="https://arxiv.org/pdf/2203.15556">Source</a></figcaption></figure><p>By examining multiple such curves, each representing a different model size, we can identify what’s known as the <strong>efficient-compute frontier. </strong>This frontier represents the outer boundary connecting the most efficient points across all the curves. These are the points that achieve the minimum error for any given computational budget. When aiming for a specific performance target, the goal is to identify the point on this frontier that reaches the target with the least amount of computational resources.</p><p>The power of this frontier lies in its ability to inform resource allocation decisions. If we under-invest in data relative to model size, or vice versa, we will find ourselves operating “inside” the frontier, effectively wasting computational resources.</p><blockquote>The frontier thus provides a generalized answer to a crucial question in LLM development: <strong>should we train a very large model for a smaller number of steps, or a smaller model for a larger number of steps?</strong> The optimal answer depends on where we aim to land along the efficient-compute boundary.</blockquote><h4>Kaplan Scaling Laws</h4><p>In a seminal <a href="https://arxiv.org/abs/2001.08361">2020 paper</a> titled “Scaling Laws for Neural Language Models,” researchers at OpenAI, led by Jared Kaplan, made a groundbreaking observation. They found that the error of a language model, as measured by cross-entropy loss, follows a power-law relationship with respect to three key factors: model size (<em>N</em>), dataset size (<em>D</em>), and the amount of training compute (C) measured in PF-days (PF-day = 10¹⁵ × 24 × 3600 = 8.64 ×10¹⁹ FLOP). The simplest form of their empirical result can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RthbfZ6_o-baIDEZTunl6g.png" /></figure><p>Here <em>αN</em>​, <em>αD</em>​, and <em>αC</em>​ are exponents that quantify the sensitivity of model loss to changes in model size, dataset size, and compute resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YnvFMoo6EERmncVU" /></figure><p>When these relationships are visualized on logarithmic scales, they manifest as straight lines, with each exponent determining the slope of the corresponding line. A striking finding from the Kaplan team’s experiments was the strong sensitivity of loss to model size (N). Based on these findings, they concluded that if one had to choose a single dimension to scale within a fixed compute budget, increasing the model size would be the most effective strategy for enhancing performance.</p><p>This “bigger is better” philosophy quickly shaped AI research landscape. In the same year, OpenAI scaled from models in the billions of parameters to GPT-3 with 175 billion parameters. The remarkable alignment between the theoretical predictions of the scaling laws and the real-world performance of GPT-3 fueled the notion that these laws are robust and that continuing to scale up model size is a straightforward path to pushing the boundaries of AI capabilities.</p><h4>Chinchilla Scaling Laws</h4><p>While the original Kaplan laws emphasized increasing model size, a later study by <a href="https://arxiv.org/pdf/2203.15556">Hoffmann et al</a>. (nicknamed <strong>Chinchilla</strong>) found that training data quantity is just as critical. They proposed revised scaling laws, described by the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*KQbYaeldT2BbKGBVTLjCwg.png" /></figure><p>where <strong><em>L(N, D) </em></strong>represents<strong><em> </em></strong>the cross-entropy loss as a function of model size <strong><em>(N) </em></strong>and dataset size <strong><em>(D)</em></strong>. The term<strong><em> E </em></strong>is the irreducible loss, representing the inherent entropy of the data. Constants <strong><em>A</em></strong> and <strong><em>B</em></strong> capture the contributions of model size and dataset size, while <strong><em>α</em></strong> and <strong><em>β</em></strong> serve as scaling exponents, quantifying the sensitivity of the loss to variations in <strong><em>N</em></strong> and <strong><em>D</em></strong>, respectively.</p><p>This equation highlights a key insight: for sufficiently large models and efficient training, the optimal strategy is to scale both the model and the data together. They discovered that to minimize loss for a given compute budget, parameter count (<strong><em>N</em></strong>) and dataset size (<strong><em>D</em></strong>) should be scaled in tandem. If either is neglected, you leave performance “on the table.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rh4R3JFmq5Cpyiy1cysp4g.png" /></figure><p>The irreducible term (<strong><em>E</em></strong>) in the Chinchilla equation defines a fundamental limit on language modeling performance, tied directly to irreducible entropy. It implies that beyond a certain point, simply adding more parameters or data won’t yield further loss improvements. While increasing model or dataset size can significantly reduce loss (represented by the power-law term), the irreducible term establishes a finite lower bound on achievable loss.</p><p>Chinchilla’s main contribution was identifying the “<strong>compute at parity</strong>” sweet spot: the optimal balance between model size and training data volume that maximizes the return on each FLOP. Over-investing in parameters without sufficient data leads to inefficiency, as the model cannot fully utilize its capacity. Conversely, a small model cannot fully exploit a large dataset, resulting in diminishing returns.</p><p>This perspective doesn’t invalidate Kaplan’s findings but refines them. It demonstrates that the optimal scaling exponent depends on the training regime. Larger models not only require more compute but also proportionally more data to reach their full potential.</p><h4>Beyond Train-Time Compute: Test-Time Compute Scaling</h4><p>Foundational work such as the Kaplan and Chinchilla scaling laws guides us on how to balance model size and data to maximize performance during pre-training. However, the conversation is no longer restricted to pre-training alone. An emerging paradigm, often called <em>test-time</em> or <em>inference-time</em> compute scaling, has begun to reframe the way we think about model capacity and performance. A 2024 paper by <a href="https://arxiv.org/html/2408.03314v1">Snell et al.</a> proposes that strategically allocating computational resources during inference can significantly boost LLMs performance, sometimes even surpassing the gains achieved by simply scaling up pre-training.</p><p>The core idea is to adopt a “<strong>compute-optimal</strong>” approach during inference, dynamically adjusting the amount of computational effort based on the complexity of each prompt. Imagine a model that can decide, for each query it receives, how much “thinking time” it needs. This strategy can outperform simpler methods, like “best-of-N” sampling (where a model generates N responses and picks the best one), and can even rival or exceed the performance of models that are significantly larger in terms of pre-training parameters, depending on the query’s nature and the available inference budget. While this work doesn’t present a single, closed-form law like those of Kaplan or Chinchilla, it establishes a conceptual framework for scaling computation intelligently during inference.</p><p>Formally, if <strong>𝑦* (𝑞)</strong> denotes the correct answer for a query <strong><em>q</em></strong> and <strong><em>θ</em></strong> represents a particular search policy (method plus hyperparameters), then the compute-optimal scaling strategy <strong><em>𝜃₍𝑞,𝑦₎* (𝑞)* (𝑁)</em></strong><em>,</em> aims to satisfy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BeXleA52_pFemk3wpmvMpg.png" /></figure><p>where <strong><em>N</em></strong> is the fixed test-time compute budget. In practice, each query <strong><em>q</em></strong> has a difficulty that can be estimated (e.g., via pass rates or an internal difficulty scorer). One can then adaptively select how best to spend the test-time budget <strong><em>N</em></strong>. For easier queries, few or no refinements may be necessary. For more challenging queries, the strategy might spawn multiple solution paths or iteratively refine a single path until it converges on a plausible solution.</p><p>Test-time compute scaling often falls into two broad categories:</p><ul><li><strong>Verifiers</strong>, which involve searching over partial solutions, generate and evaluate multiple solution paths using dedicated models or heuristics to select the best option. Methods range from simple Best-of-N sampling with outcome reward models (ORMs) to more complex approaches like beam search and Monte Carlo Tree Search (MCTS) that use process reward models (PRMs) to score and prune intermediate reasoning steps.</li><li><strong>Revisions</strong>, or iteratively improving the model’s output distribution, focus on refining a single solution through techniques like self-reflection, token re-ranking, and targeted rewriting of problematic sections. The model iteratively improves its output by identifying and correcting errors or suboptimal paths.</li></ul><p>The theoretical frameworks for test-time compute scaling have moved from research into industry implementations, with OpenAI’s “o1” and DeepSeek-R1 serving as prime examples of different approaches to deploying these concepts at scale.</p><h4><strong>OpenAI’s “o1/o3”</strong></h4><p>o1 showcases test-time compute capabilities through its dynamic, step-by-step reasoning approach. While the model isn’t fully open-sourced, its problem-solving methodology, particularly in mathematics, clearly demonstrates this systematic reasoning process. The model’s effectiveness increases with the number of permitted reasoning steps, suggesting a sophisticated internal mechanism. Early analysis indicates that o1 employs something akin to self-verification or chain-of-thought refinement, iteratively developing and critiquing partial solutions before synthesizing a final, coherent answer. This capability is further evidenced by o3’s impressive 87.5% score on the <a href="https://arcprize.org/blog/oai-o3-pub-breakthrough">ARC-AGI benchmark</a>, marking a significant leap forward in AI’s ability to tackle novel and unfamiliar challenges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jPfCeUqYFCpEHKaC" /><figcaption><a href="https://openai.com/index/learning-to-reason-with-llms/">Source</a></figcaption></figure><p>Researchers have proposed that o1 likely employs a hybrid approach: generating multiple solution paths for complex questions while streamlining the process for simpler ones. This adaptive strategy aligns with the compute-optimal approach that different problems warrant different amounts of test-time computational resources.</p><h4>DeepSeek-R1</h4><p><a href="https://arxiv.org/pdf/2501.12948"><strong>DeepSeek-R1</strong></a><strong> </strong>takes a novel approach by applying reinforcement learning (RL) directly to improve reasoning capabilities without relying heavily on external verification or supervised fine-tuning (SFT). While DeepSeek researchers initially explored PRMs and MCTS, they found these approaches had significant limitations. PRMs struggled with defining and scoring intermediate reasoning steps and risked reward hacking, while MCTS became impractical due to the vast token-level search space and challenges in training fine-grained value models. Instead, through pure RL training with simple rule-based rewards for accuracy and format, the model naturally learned to leverage extended test-time computation by generating longer chains-of-thought (CoT) and incorporating self-verification behaviors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hP7p9NqFxHgqlUimCMVG4g.png" /><figcaption><a href="https://arxiv.org/pdf/2501.12948">Source</a></figcaption></figure><p>The average response length increases significantly during RL training, reaching thousands of tokens as the model learns to break down complex problems and verify its own reasoning. What makes this particularly remarkable is the emergence of sophisticated behaviors during test-time computation. The model spontaneously develops reflection capabilities — revisiting and reevaluating its previous steps — and explores alternative problem-solving approaches without explicit programming.</p><blockquote>These <strong>emergent behaviors</strong> arise purely from the model’s interaction with the reinforcement learning environment, where increased <strong>test-time compute</strong> leads to more sophisticated reasoning.</blockquote><h4>Emergent Abilities</h4><p>The scaling laws discussed above describe how LLMs steadily reduce cross-entropy loss or other error metrics with increasing data, model size, and compute. However, a fascinating and somewhat mysterious aspect of LLM behavior is the emergence of qualitatively new abilities as models scale up. These are often referred to as “<a href="https://openreview.net/pdf?id=yzkSU5zdwD">emergent abilities</a>”. An ability is emergent if it is not present in smaller models but suddenly appear in larger ones. These abilities include multi-step reasoning (e.g., chain-of-thought), instruction following, arithmetic problem-solving, improved truthfulness in answers, enhanced semantic understanding, and the ability to handle diverse knowledge tasks across multiple languages and domains. These capabilities often appear abruptly and were either entirely absent or only rudimentary in smaller models.</p><p>What is particularly intriguing about these emergent abilities is that they do not map neatly onto the smooth, predictable power-law declines in cross-entropy loss described by the scaling laws. Instead, they seem to manifest somewhat abruptly, suggesting the existence of thresholds or phase transitions in model capabilities as a function of scale.</p><blockquote>However, while Scaling laws reliably predict <strong>quantitative improvements</strong>, such as reduced test loss with increased compute, they do not guarantee specific <strong>qualitative changes</strong> in model behavior. While larger models become more robust and expressive, emergent capabilities remain unpredictable, making it unclear how scaling translates into intelligence or complex reasoning abilities.</blockquote><p>These emergent behaviors are still connected to the training regime. A model that is trained in a balanced manner, with appropriate scaling of both data and parameters, is more likely to exhibit these emergent capabilities than a model that is trained in an unbalanced way.</p><h4>The Manifold Hypothesis</h4><p>Why do these empirical power laws arise so consistently across different models and datasets? One compelling explanation invokes the <a href="https://deepai.org/machine-learning-glossary-and-terms/manifold-hypothesis"><strong>manifold hypothesis</strong></a>, a concept that has gained traction in the field of deep learning. This hypothesis posits that natural data, such as text, images, and audio, tends to lie on a lower-dimensional manifold embedded within a much higher-dimensional space. For instance, consider a dataset of 28x28 pixel grayscale images. Each image can be represented as a point in a 784-dimensional space (28 * 28 = 784). However, real-world images do not uniformly fill this entire 784-dimensional space. Instead, they tend to cluster along a manifold with a much lower intrinsic dimensionality. This is because natural images share common structures and patterns, and not all possible combinations of pixel values correspond to meaningful images.</p><p>Deep neural networks learn to approximate the geometry of this manifold. As model size (N) or dataset size (D) grows, the network can represent the manifold with finer resolution, thereby reducing error. Simple geometric arguments suggest that the average distance between data points on a manifold of dimension (d) scales as <strong>𝐷⁻¹⸍ᵈ</strong>. Cross-entropy loss, which effectively squares these distance errors, can scale as <strong>𝐷⁻⁴⸍ᵈ</strong>. This insight helps explain why feeding LLMs ever more data yields a predictable drop in loss, even in extremely high-dimensional settings. For text, estimating the intrinsic dimension is difficult. Early attempts suggest a very high dimension (d≈100), which complicates perfect fits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*khBzO6trt49x8Py48N39IQ.png" /></figure><p>However, despite some alignment with real-world experiments, no closed-form “unified theory” of neural scaling has been universally validated. The manifold hypothesis provides a powerful heuristic for understanding why larger datasets and models generally lead to improved performance. It suggests that we can conceptualize the process of scaling as learning increasingly refined approximations of a complex, high-dimensional manifold. However, this learning process is still fundamentally bounded by the irreducible entropy inherent in the language data.</p><p>Having established how scaling laws dictate the balance among model performance, size, data, and compute, we now turn to the blueprint that has made such ambitious scaling feasible. At the heart of LLMs lies the <strong>Transformer Architecture</strong>, a design whose self-attention mechanism not only unlocks parallelized training but also overcomes the long-range dependency issues that held back its sequential predecessors. By examining how Transformers process language we can see exactly why this architecture forms the backbone of today’s LLMs.</p><h3>The Transformer Architecture</h3><p>The introduction of the Transformer architecture in “<a href="https://arxiv.org/pdf/1706.03762v7">Attention Is All You Need</a>” revolutionized natural language processing (NLP). While previous approaches like RNNs and LSTMs processed text sequentially, limiting their scalability on modern GPUs, Transformers introduced a groundbreaking parallel processing approach through self-attention. This mechanism allows the model to simultaneously analyze relationships between all tokens in a sequence, significantly improving both training efficiency and contextual understanding.</p><p>Despite the proliferation of different model sizes and training objectives, the core Transformer architecture has maintained its elegant simplicity through three key stages. In the input embedding stage, data from various modalities (text, images, audio) is converted into high-dimensional vector representations. These embeddings then pass through transformer blocks, where multi-headed self-attention and feed-forward layers iteratively refine them by capturing complex patterns and relationships. Finally, the output processing stage maps these refined embeddings into the desired predictions.</p><p>This versatile architecture comes in three main variants, each specialized for different tasks:</p><ul><li>Encoder-only models like BERT and RoBERTa excel at classification tasks by generating fixed-size representations of input data.</li><li>Encoder-decoder models like T5, BART, and mT5 power machine translation by using separate components to process source and target languages.</li><li>Decoder-only models like GPT, LLaMA, and Claude focus on text generation, making them the primary choice for LLMs.</li></ul><p>For building modern LLMs, the decoder-only variant has emerged as the dominant architecture. Its ability to generate coherent text from input prompts, combined with the Transformer’s inherent parallel processing capabilities, makes it particularly well-suited for training efficient and powerful language models on GPU hardware. Let’s examine the core building blocks of this architecture:</p><h4>Input Embedding</h4><p>The foundation of Transformer processing lies in token embeddings, which convert raw inputs, such as words, into dense numerical vectors within a high-dimensional space. Think of this space as a complex semantic map, where each dimension represents a distinct aspect of meaning. By placing tokens at specific coordinates within this map, the embeddings capture subtle relationships between different pieces of information. This mathematical representation allows neural networks to grasp the nuances of language, as words with similar meanings naturally cluster together in the embedding space.</p><p>The specific technique for creating these embeddings varies depending on the type of input being processed, whether it’s text, images, or other forms of data. Text is broken into subword tokens using methods like Byte Pair Encoding (BPE), which are then converted to vectors. Images are divided into patches that are flattened and projected into embeddings. Audio is first transformed into spectrograms, which can then be processed similarly to images by splitting them into patches. Once this conversion is complete, a single batch of input can contain token embeddings derived from text, images, audio, or any other modality, all ready to be consumed by the Transformer blocks.</p><h4>Positional Encoding</h4><p>While the core self-attention mechanism within transformer blocks treats inputs as unordered sets of embeddings, language requires a precise understanding of word order to convey meaning. Without maintaining sequential position information for each token, the model would lose crucial context and grammatical structure. To address this, various positional encoding strategies have been developed. Early approaches focused on absolute positions, such as learned positional embeddings (unique vectors trained for each position up to a maximum length) and fixed sinusoidal encodings (deterministic vectors based on varying frequencies). In these absolute methods, the positional vectors are typically added directly to the token embeddings before the first transformer block, maintaining the embedding dimensionality.</p><p>However, many modern approaches emphasize relative positioning to better capture pairwise relationships and improve generalization. Relative Positional Encoding (RPE) encompasses techniques that encode the distance or relationship between tokens, often by modifying attention scores directly or using specific relative embeddings within the attention calculation itself. Furthermore, Rotary Positional Encoding (RoPE), injects relative positional information in a unique way by applying position-dependent rotations to the query and key vectors before the attention computation. These diverse mechanisms are crucial for enabling Transformers to effectively process sequence data.</p><p>While text-based applications typically use one-dimensional embeddings to capture linear sequence order, image processing often employs two-dimensional position embeddings to represent both height and width coordinates. This positional encoding mechanism elegantly bridges the gap between naturally ordered data and the set-based nature of self-attention, enabling the model to effectively process sequential, grid-based, or higher-dimensional structured inputs.</p><h4>The Self-Attention Operation</h4><p>After embedding the tokens and adding positional information, we arrive at the heart of the Transformer, the attention mechanism. This ingenious system allows tokens to interact and share information with each other, creating a rich understanding of context. The process works by transforming each token’s embedding (a row in the input matrix X) into three distinct, learned representations using separate weight matrices:</p><ul><li><strong>Queries (Q)</strong>: Generated by multiplying the input X by a learned weight matrix WQ. Think of this as a token formulating a question about what information it needs from others.</li><li><strong>Keys (K)</strong>: Generated by multiplying X by a different learned weight matrix WK. This acts like a label or descriptor for the token, indicating the kind of information it holds, making it discoverable by relevant queries.</li><li><strong>Values (V)</strong>: Generated by multiplying X by a third learned weight matrix WV. This contains the actual information or features of the token that will be shared.</li></ul><p>Think of this as a sophisticated communication system. Each token uses its query to determine which other tokens it wants to gather information from, while its key helps determine which tokens will seek information from it. When a token’s query aligns strongly with another token’s key, it receives more of that token’s value, the actual information being shared. Through these learned projections (WQ, WK, WV), the model creates dynamic pathways for information to flow between tokens, allowing them to build a nuanced understanding of their relationships within the sequence. This attention-based approach is what gives Transformers their remarkable ability to process language with such sophistication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*2a-Ajhxh1c36NNqkIi5-xg.png" /><figcaption><a href="https://arxiv.org/pdf/1706.03762v7">Source</a></figcaption></figure><h4>Scaled Dot Product Attention</h4><p>Scaled dot-product attention is the mathematical realization of this process. It computes an attention matrix by taking the dot product of the queries and keys, resulting in scores for every pair of tokens. This matrix has dimensions <strong>T×T </strong>for a sequence of length <strong>T</strong> in self-attention. To stabilize training, the scores are divided by <strong>√dₖ</strong>, where <strong>dₖ</strong> is the dimension of the key vectors and <strong>Kᵀ</strong> is the transpose of the key vector <strong>K</strong>. Finally, a softmax function normalizes each row in the attention matrix, converting the raw dot products into a set of weights that sum to 1. These weights determine how much each token “pays attention” to every other token, and the weighted sum of the value vectors (<strong>V</strong>) gives each token a refined representation based on context. Mathematically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*As62Fhidl63cazSq7vm2_A.png" /></figure><h4>Multi-Headed Attention (MHA)</h4><p>While a single attention operation suffices to compute context-dependent representations, Transformers extend the concept with multiple heads. Rather than using one set of<strong> Q, K</strong>, and <strong>V</strong> projections, the embedding dimension is partitioned across several heads, and each head performs its own attention calculation on a subset of the dimension. This parallel processing enhances the model’s ability to learn diverse relationships and focus on different aspects of the sequence simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*1kC9WhHfDWLD1HMXFSBAvg.png" /><figcaption><a href="https://arxiv.org/pdf/1706.03762v7">Source</a></figcaption></figure><p>After each head computes its own weighted combination of the value vectors, the outputs of all heads are concatenated and passed through a linear projection that restores the dimension back to the original size. By operating across multiple subspaces, multi-head attention can capture varied token relationships that a single head might miss.</p><h4>Masked Multi-Headed Self-Attention</h4><p>While MHA captures global context, decoder-only Transformers must ensure that each position in the sequence only attends to itself and the tokens before it. This requirement is critical for autoregressive language generation, where a token should not “peek” at future positions. To impose this constraint, masked multi-headed self-attention introduces a causal mask <strong>𝑀 ∈ ℝⁿ×ⁿ (</strong>a matrix with n rows and n columns) applied to the attention weights to disallow attention to future positions (causality). This is implemented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vm_BurSKw2qrFpQzwcNp8Q.png" /></figure><p>After forming the [T,T]-sized attention matrix by multiplying the queries (Q) with the transposed keys (<strong>Kᵀ)</strong>, all entries corresponding to “future” tokens are masked out by setting them to negative infinity (or a very large negative constant) before the softmax operation. In other words, token <strong>𝑡ᵢ​</strong> does not attend to positions <strong>𝑗ᵢ</strong> where <strong>j &gt; i</strong> . Once the softmax is applied, those masked entries become effectively zero, ensuring each token can only gather information from itself and preceding tokens.</p><h4><strong>Key-Value (KV) Cache</strong></h4><p>MHA excels at capturing token dependencies, but its computational demands, especially during inference, have driven algorithmic innovations like the <strong>Key-Value (KV) cache</strong>. During text inference, recomputing K and V vectors for previously processed tokens at each step is inefficient. Instead, these vectors are stored in a KV cache, enabling reuse and significantly accelerating inference. However, as sequence length increases, the KV cache grows linearly, creating a memory bottleneck that impacts long-context LLMs. This memory bottleneck is precisely what the following MHA variants aim to address.</p><h4><strong>Multi-Query Attention (MQA)</strong></h4><p>MQA tackles this memory bottleneck by implementing a shared communication system. Rather than each attention head maintaining separate<strong> K a</strong>nd <strong>V</strong> vectors, MQA uses a single set shared across all heads. While each head retains its unique Query, they all attend over this common Key-Value space. This reduces the <strong>KV cache</strong> size and accelerates inference, particularly for long sequences and larger batch sizes. However, this efficiency comes at a cost, the shared Keys and Values limit the model’s ability to capture diverse relationships and nuanced information. MQA can also introduce instability during fine-tuning, especially with longer sequences.</p><h4><strong>Grouped-Query Attention (GQA)</strong></h4><p>GQA emerges as a middle ground between MHA and MQA. Instead of either complete independence (MHA) or total sharing (MQA) of KV pairs, GQA organizes attention heads into groups that share Keys and Values within each group. The number of groups (G) becomes a important hyperparameter. When G equals the number of heads, GQA functions like MHA and when G is 1, it behaves like MQA. Setting G to an intermediate value (typically 4 to 8) achieves an optimal balance between generation quality and inference speed. This approach has been widely adopted in models like the Llama 3 series and Mistral 7B models.</p><h4><strong>Multi-Head Latent Attention (MLA)</strong></h4><p>MLA as implemented in DeepSeek models, takes a novel approach to Key-Value (KV) cache reduction through <strong>Low-rank Key-Value Joint Compression</strong>. For each token, MLA first projects the Keys and Values into a lower-dimensional latent space using a down-projection matrix shared across all attention heads. During inference, these compressed representations are reconstructed using up-projection matrices unique to each head, enabling each head to operate on individualized reconstructed Key and Value vectors. This strategy achieves a 57x reduction in KV cache size — from 4MB per token to just 70KB — while preserving or even improving model quality compared to traditional MHA or GQA.</p><p>Unlike MQA, where all heads share identical KV matrices (sacrificing specialization), or GQA, which shares KV matrices across subsets of heads, MLA maintains head-specific expressiveness by learning head-specific up-projection matrices. The compressed latent cache is thus shared, but its reconstruction into per-head Key and Value representations allows nuanced specialization. Crucially, DeepSeek optimizes the compute path: through clever linear algebra, they absorb the head-specific projection matrices into the query and output paths, meaning that these transformations are only computed once and do not add runtime overhead during inference.</p><p>MLA fundamentally rethinks the Transformer’s KV cache bottleneck. By learning how to efficiently compress and reconstruct attention information, it breaks the typical scaling dependency between KV cache size and the number of attention heads. This innovation enables DeepSeek R1 to scale to 100,000-token contexts using a manageable memory footprint, generating tokens 6x faster than standard Transformers, and redefines what is computationally feasible for high-context, high-performance LLMs.</p><h4>Feed-Forward Network (FFN)</h4><p>The feed-forward network (FFN) that follows the self-attention module serves a distinct but complementary purpose in processing token embeddings. While self-attention captures relationships between tokens across the sequence, the FFN operates on each token independently, focusing on enriching individual token representations.</p><p>In a typical decoder-only Transformer block, the FFN first projects each token’s embedding into a higher-dimensional space, usually four times larger than the input. This expansion creates room for the network to learn more nuanced features. The expanded representation then passes through a non-linear activation function, such as GeLU, ReLU or SwiGLU, which introduces non-linear transformations. A second linear projection then compresses the representation back to its original dimensionality, maintaining consistency in the token embeddings that flow between Transformer blocks. This architectural choice of expanding and then contracting the representation, with non-linearity in between, achieves an elegant balance between computational efficiency and expressiveness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQnmCIo3-_vdUwIAanGnMA.png" /></figure><p>The synergy between attention and feed-forward layers creates a powerful processing pipeline: attention mechanisms discover how tokens relate to and influence each other, while FFNs deeply transform individual token representations to capture richer meanings. This relationship modeling in attention layers and individual token processing in FFNs forms the backbone of the Transformer’s effectiveness.</p><h4>Layer Normalization (Norm)</h4><p>Layer Normalization stabilizes neural network activations, reducing internal covariate shift and accelerating convergence. Without normalization, the distribution of activations can shift dynamically across layers, making it harder for the network to learn effectively. In a decoder-only Transformer, LayerNorm computes the mean and variance along the embedding dimension of each token vector, rather than across a batch, ensuring stable normalization independent of batch size. Mathematically, LayerNorm is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgGdBkSKGJrntdHTftCsCA.png" /></figure><p>where <strong>μ and σ</strong> are the mean and standard deviation along the embedding dimension, <strong>ϵ</strong> is a small constant for numerical stability, and <strong>γ and β </strong>are learnable parameters that apply an affine transformation. The affine transformation ensures that the normalized output can still capture meaningful variations in the data, rather than simply standardizing it to zero mean and unit variance. RMSNorm is another popular alternative.</p><h4>Residual Connections (Add)</h4><p>Residual connections help mitigate vanishing and exploding gradients by providing a “shortcut” for gradient flow. After the self-attention or feed-forward sub-layer transforms the token vectors, the original input is <strong>added</strong> to that transformed output: <strong>Output=Input+Layer(Input).<br></strong>Because residual connections preserve the dimensionality of their input, they integrate seamlessly with the self-attention and feed-forward modules within the Transformer block. They provide a “shortcut” for the gradient to flow back through the network during backpropagation. This helps to stabilize training and improve the overall performance of Transformer models.</p><h4>Putting It All Together: The Decoder-Only Transformer Block</h4><p>With these elements defined, we can now assemble the complete decoder-only Transformer block, the fundamental unit upon which these powerful LLMs are built. These blocks are stacked sequentially (<strong>Nx</strong>), creating a deep network capable of learning complex language representations. Each block processes the input it receives and passes its transformed output to the next block in the stack, preserving the dimensionality of the token embeddings throughout the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kG6tpBslnRA1APPAVGo7Qg.png" /></figure><p>Each Transformer block consists of two primary processing stages:</p><ol><li><strong>Masked Multi-Headed Self-Attention:</strong> This stage is the heart of the Transformer’s ability to capture contextual relationships.</li><li><strong>Feed-Forward Network:</strong> Following the attention stage, each token’s representation is independently processed by a FFN.</li></ol><p>These two core stages are supported by two crucial mechanisms — <strong>Add &amp; Norm</strong>:</p><ul><li><strong>Layer Normalization (Norm):</strong> Layer normalization, whether applied before (Pre-LN) or after (Post-LN) each stage (of attention and FFNs), helps stabilize activation distributions.</li><li><strong>Residual Connections (Add):</strong> After each stage, the original input to that stage is added to its output.</li></ul><p>The output of a single Transformer block is a set of transformed token embeddings, which serves as the input to the next block in the sequence. Following the final block, a concluding linear layer — often called the ‘output projection layer’ or ‘language modeling head’ — processes the representations for all token positions. This layer maps each token’s high-dimensional embedding to logits (raw, unnormalized scores), with one logit score per word in the model’s vocabulary. While logits are generated for every position, during typical text generation, it’s the logits corresponding to the last token of the input sequence that are converted via a softmax function into a probability distribution. This distribution is then used to predict or sample the single most likely next token to extend the sequence.</p><p>This modular design, with its repeating blocks of self-attention, feed-forward networks, layer normalization, and residual connections, is key to the Transformer’s success. Having established the fundamental structure and functionality of the decoder-only Transformer block, let’s now see how a powerful architectural innovation allows us to scale these models even further: the Mixture of Experts (MoE) approach, which introduces sparsity to enhance capacity while maintaining efficiency.</p><h4>Mixture of Experts</h4><p>Mixture of Experts (<a href="https://substack.com/home/post/p-148217245">MoE</a>) is a powerful technique for scaling Transformer models. It modifies the standard Transformer by substituting the FFN with a collection of “expert” FFNs, each specializing in a different aspect of the data. A “router,” or gating network, intelligently directs each input token to one or a few of these experts. This routing is dynamic, based on learned scores that are typically normalized using a softmax function.</p><p>The core advantage of MoE lies in its <strong>sparsity </strong>as<strong> </strong>only a subset of experts is activated for each token. This contrasts sharply with <strong>dense</strong> FFNs, where all neurons are involved. For instance, models like GPT, LLaMA, and Claude use dense architectures where all parameters are active for every input. On the other hand, MoE models such as Mixtral 8x7B and DeepSeek-R1 activate only a subset of their total parameters for each input. Sparsity enables MoE models to significantly increase their capacity (number of parameters) without a proportional surge in computational demands during inference. To maintain efficiency, most MoE models employ sparse gating, selecting only the top-k experts (usually top-1 or top-2) for each token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cXmiPmMJN9vv-8Ueu795Q.png" /></figure><p>Load-balancing mechanisms, like auxiliary losses and capacity factors, ensure that all experts are used effectively and prevent the router from simply favoring a few popular experts. Although MoE can increase the memory footprint as all experts need to be loaded, it offers a way to enhance the Transformer’s representational power without a linear increase in computational cost.</p><h3>The Scaling Bottlenecks of Transformers</h3><p>While the Transformer architecture, particularly its self-attention mechanism, offers significant advantages in parallel processing and capturing long-range dependencies, scaling these models to billions or trillions of parameters presents substantial computational and memory challenges. These challenges stem from the inherent complexity of the Transformer’s components and their interactions with modern compute hardware.</p><h4><strong>Quadratic Complexity of Self-Attention</strong></h4><p>A significant bottleneck arises from the self-attention mechanism itself. Its computational cost scales quadratically with the sequence length (<em>n</em>). Specifically, the <a href="https://www.interdb.jp/dl/part04/ch15/sec03.html">time complexity</a> of multi-headed attention is <strong><em>O(n²⋅d + n⋅d²)</em></strong>, where <em>d</em> is the embedding dimension. The <strong><em>n²⋅d</em></strong> term comes from calculating the attention scores between all pairs of tokens, while the <strong><em>n⋅d²</em></strong> term accounts for the linear projections of tokens into queries, keys, and values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D49nb5W-yBxZtAHHpqyXuQ.png" /></figure><p>Similarly, while the space complexity is <strong><em>O(n² + n⋅d)</em></strong> , from storing the full attention matrix, modern implementations use optimizations like FlashAttention. These techniques cleverly avoid materializing the entire <em>n x n </em>matrix, mitigating the quadratic memory bottleneck and achieving practical memory usage closer to linear O(n⋅d) scaling with sequence length. Nonetheless, the computational complexity remains quadratic O(n²⋅d) . This means that doubling the sequence length, even if memory scaling is managed, still roughly quadruples the computational load required for self-attention, posing a major obstacle for processing very long sequences.</p><h4><strong>Arithmetic Intensity of Self-Attention</strong></h4><p>The performance of Transformer models is influenced not only by the quadratic cost of self-attention but also by low arithmetic intensity, particularly during inference. Arithmetic intensity refers to the ratio of compute operations (like matrix multiplications in MHA and FFN) to memory accesses, like reading Q, K, V vectors or loading parameters from GPU memory.</p><p>GPUs, given their graphics lineage, are designed for <a href="https://medium.com/p/ce397041dec2#e696">high arithmetic intensity</a>, where workloads maximize computational throughput relative to memory accesses. They achieve peak efficiency when computations involve dense matrix operations, as seen in training workloads where large tensor multiplications dominate. During training, the ability to process entire sequences in parallel, especially within the self-attention mechanism, helps maintain high arithmetic intensity. However, this dynamic shifts during inference, which consists of two stages: <strong>Prefill</strong> and <strong>Decoding</strong>.</p><ul><li><strong>Prefill:</strong> In this stage, the model ingests the prompt tokens in parallel, efficiently leveraging high arithmetic intensity to rapidly populate the key and value vectors<strong> (KV) cache</strong>. The KV cache serves as the state for the model within the attention operation, reducing redundant computation in later steps. Since no tokens are being generated at this point, computations primarily involve tensor multiplications and memory writes to populate the cache, making this phase well-suited for <strong>high arithmetic intensity</strong> GPU acceleration.</li><li><strong>Decoding:</strong> In the decoding phase, the model uses the previously stored KV cache to sample and generate the next token. Unlike Prefill, which is highly parallel, decoding is inherently sequential — each new token depends on the previously generated tokens, limiting parallelism and shifting the computation towards <strong>low arithmetic intensity</strong>. The KV cache mitigates some inefficiency by avoiding redundant recomputation, but decoding remains memory-bound, as each new token retrieval involves fetching and updating intermediate representations (such as Q, K, and V vectors). Since most inference time is spent in decoding for text generation, this stage significantly impacts scalability.</li></ul><h4><strong>Space Complexity of the KV Cache</strong></h4><p>While decoding is predominantly memory-bound due to limited parallelism and repeated memory accesses, the <a href="#377c">KV cache</a> offers a partial solution by reusing previously computed Key (K) and Value (V) vectors for already-processed tokens. This optimization directly addresses the growing computational burden imposed by the quadratic cost of self-attention, since caching reduces the cost per new token from quadratic <strong>O(n²) </strong>to line<strong>ar O(n)</strong>. At the same time, the transition from high arithmetic intensity (as seen in training and prefill) to the more memory-intensive decoding stage naturally benefits from the KV cache’s ability to avoid redundant computations.</p><p>However, the efficiency gains come at a steep memory cost, the total KV cache size expands with sequence length, model depth, number of attention heads, hidden dimension, and batch size. <strong>Batch</strong> is a collection of input sequences processed simultaneously during training or inference, enhancing efficiency by enabling parallel processing of multiple inputs. For large models and long sequences, this rapidly becomes the dominant memory bottleneck. For instance, in a 175B parameter GPT-3 model, a batch size of 64 with a 4096-token sequence can push the KV cache to require approximately 1208 GB of GPU memory, more than triple the memory needed to store the model’s weights. Such massive memory requirements limit the number of concurrent requests and pose a significant scalability challenge. As explained in the<a href="#377c"> earlier sections</a>, algorithmic advances like MQA, GQA and MLA seek to strike a balance between mitigating the quadratic complexity of self-attention and the space complexity of KV cache.</p><h4><strong>Dynamic Memory Access Patterns</strong></h4><p>Unlike the predictable data access in convolutional networks, self-attention involves data-dependent memory accesses where the locations to be accessed are determined by the input sequence itself. This unpredictability hinders the effectiveness of <a href="https://people.cs.pitt.edu/~debashis/papers/ISCA2019.pdf">hardware prefetchers</a>, leading to increased cache misses and cache pollution. Also, the often scattered and non-contiguous nature of these memory accesses results in inefficient utilization of memory bandwidth, which is optimized for transferring large, contiguous blocks of data. These dynamic and irregular memory access patterns are a bottleneck, limiting the performance and scalability of Transformers, especially during inference.</p><h4><strong>Overhead of Non-Linear Operations</strong></h4><p>Non-linear operations such as Softmax, GeLU, and LayerNorm are critical to Transformer models but introduce significant computational overhead on GPUs. Unlike the highly optimizable matrix multiplications in linear layers, these element-wise operations often involve expensive reductions (e.g., for Softmax and LayerNorm) and multiple kernel launches, creating synchronization points that restrict parallelism. Their fine-grained nature disrupts the fusion of operations essential for GPU performance, resulting in excessive data movement, reduced occupancy, and underutilized compute resources, bottlenecks that worsen as LLMs scale.</p><p>Moreover, the complex, input-dependent nature of these non-linearities complicates optimization and makes them difficult to fuse with other operations. Reduction steps across sequence or embedding dimensions add synchronization overheads, and Softmax in particular (with its exponentiation, summation, and division) can dominate the execution time of the attention mechanism for longer sequences. While solutions like NVIDIA’s specialized <a href="https://developer.nvidia.com/blog/accelerating-transformers-with-nvidia-cudnn-9/">cuDNN</a> kernels and TensorFlow’s <a href="https://openxla.org/xla/tf2xla">XLA</a> compiler offer partial optimizations, the inherent complexity and data dependencies of these operations continue to limit their effectiveness, posing a persistent challenge in the efficient scaling and deployment of Transformer models.</p><h4><strong>Sparsity</strong></h4><p>Sparsity in Transformer attention poses optimization challenges due to its unstructured, dynamic nature. Unlike predictable sparsity patterns, the non-zero elements in the attention matrix shift with each input, reflecting the quadratic cost of self-attention. Growing sequence lengths exacerbate memory and compute demands for storing Key-Value (KV) pairs, even if many are ultimately unused. Standard sparse matrix libraries offer limited assistance because the dynamic sparsity prevents pre-computation, leading to runtime adaptation overhead. Indexing and load-balancing for scattered non-zero elements introduce further challenges, potentially limiting hardware acceleration. While sparse models aim to retain relevant tokens over long contexts, aggressive pruning can lead to loss of crucial information, impacting memory optimizations and model performance.</p><p>As these demands evolve, we must move beyond traditional von Neumann architectures and embrace specialized AI accelerators that seamlessly integrate software innovations. Future systems will require carefully tailored instruction set architectures (ISAs), dataflow architectures, and efficient memory hierarchies to handle increasingly complex tasks. Effective model parallelism will hinge on interconnect fabrics designed to minimize bottlenecks, enabling large-scale data transfers without compromising performance. Realizing this vision calls for close collaboration between hardware engineers and ML researchers to drive novel computing paradigms.</p><h3>Conclusion</h3><p>From single-layer perceptrons to today’s trillion-parameter Transformers, every leap in capability has been driven by the synergy of hardware and software, shaped by empirically observed scaling laws. These laws — governing model size, data volume, and compute — reveal power-law trends in performance gains while also exposing the irreducible entropy that limits achievable performance. Yet the emergence of unexpected abilities at certain scale thresholds suggests we’re still uncovering the deeper connections between scale and intelligence.</p><p>At the heart of this evolution, the Transformer architecture’s self-attention and feed-forward blocks have demonstrated remarkable efficiency — yet at extreme scales, they demand immense memory and power. The key to future advancements lies not in algorithmic improvements or hardware innovations alone, but in their thoughtful co-design. <strong>Bits, FLOPS,</strong> and <strong>watts</strong> must be treated as interdependent dimensions of a single scaling challenge, requiring optimizations that cut across all three.</p><p>In <a href="https://medium.com/@asheesh.goja/bits-flops-and-watts-a-systems-level-perspective-of-scaling-llms-part-2-ce397041dec2"><strong>Part 2</strong></a>, we will explore these hardware challenges in-depth, tracing the path from algorithmic complexity to silicon constraints. By examining GPU architectures, interconnect bottlenecks, and the underlying CMOS physics, we will see how future progress hinges not just on building larger models, but on a thoughtful and innovative co-design of hardware and software to drive the next leap in LLM capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34ef63d95b6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Architect’s Guide to the AIoT]]></title>
            <link>https://medium.com/@asheesh.goja/the-architects-guide-to-the-aiot-c55cccd04acb?source=rss-8b819656b4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c55cccd04acb</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[iiot]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[edge-ai]]></category>
            <category><![CDATA[argo-workflows]]></category>
            <dc:creator><![CDATA[Asheesh Goja]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 02:43:50 GMT</pubDate>
            <atom:updated>2024-04-09T02:47:05.336Z</atom:updated>
            <content:encoded><![CDATA[<p>Cloud computing, artificial intelligence, and internet-connected devices are the ineliminable technological pillars of contemporary digital society. However, a greater untapped potential, that can usher in the next generation of digital transformations and innovations, lies latent at the convergence of these technologies.</p><p>The combined power of AI and IoT collectively referred to as the Artificial Intelligence of Things or AIoT, promises to unlock unrealized customer value in a broad swath of industry verticals such as edge analytics, autonomous vehicles, personalized fitness, remote healthcare, precision agriculture, smart retail, predictive maintenance, and industrial automation.</p><p>In principle, combining AI with IoT seems to be the obvious logical progression in the evolution of these technologies. In practice though, building an AIoT solution is fraught with seemingly insurmountable architectural and engineering challenges. In a three-part series, I will discuss such challenges in sufficient detail and address them by proposing an overarching architectural framework. This series will give you the adequate architectural context and perspective needed to build an industrial-grade scalable and robust AIoT application. Here is the series breakdown:</p><p>Part 1: <a href="https://techblog.cisco.com/blog/architects-guide-to-aiot-1">AIoT Architecture</a> — In this section, you will get a thorough grounding in the AIoT problem space, understand the inherent challenges and investigate emergent behaviors. I will present a set of effective solution patterns that can address such challenges, along with a comprehensive reference architecture. The reference architecture will serve as a cognitive map in the hitherto uncharted territory of AIoT architectures. It will assist you in pairing AIoT problem scenarios with applicable solution patterns and viable technology stacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uCqOYBWuqXp7TeqK" /></figure><p>Part 2: <a href="https://techblog.cisco.com/blog/architects-guide-to-aiot-2">AIoT Infrastructure</a> — Here using the reference architecture you will see how to establish an edge infrastructure for an AIoT application. The infrastructure is built using various CNCF open-source projects from the Kubernetes ecosystem such as K3S, Argo, Longhorn, and Strimzi. You will see how to configure and install these projects on a cluster of AI acceleration equipped single-board computers such as NVIDIA® Jetson Nano™ and Google Coral Edge TPU™.</p><p>Part 3: <a href="https://techblog.cisco.com/blog/architects-guide-to-aiot-3">AIoT Design</a> — In the concluding part, you will see how to design and build an AIoT application that simulates an industrial predictive maintenance scenario. In this scenario, analog sensors monitor an induction motor by sensing its power utilization, vibration, sound, and temperature, and this data is then processed by an AIoT application. This application powered by a TPU accelerator applies a logistic regression model to predict and prevent motor breakdown. You will see how ML pipelines measure drift, re-train and re-deploy the model. Using various design artifacts such as event diagrams and deployment topology models you will get an in-depth view of the systems design. You will find ample code and configuration samples in C++, Go, Python and YAML. These samples will show you how to configure, code, build (ARM64 compatible), containerize (distroless), deploy and orchestrate AIoT modules and services as MLOps pipelines across various heterogeneous infrastructure tiers. This section also includes IoT device firmware code along with circuit schematics.</p><p>Read the complete series on <a href="https://outshift.cisco.com/blog/author/asheesh-goja">Cisco Tech Blog.</a></p><p><a href="https://github.com/asheeshgoja/architects-guide-2-aiot">Source Code on Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c55cccd04acb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expert Systems — The Why, What, and How]]></title>
            <link>https://medium.com/@asheesh.goja/expert-systems-the-why-what-and-how-24f3c785a41d?source=rss-8b819656b4a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/24f3c785a41d</guid>
            <category><![CDATA[artificalintelligence]]></category>
            <category><![CDATA[rules-engine]]></category>
            <dc:creator><![CDATA[Asheesh Goja]]></dc:creator>
            <pubDate>Fri, 03 Jun 2022 20:28:35 GMT</pubDate>
            <atom:updated>2022-06-06T18:11:09.677Z</atom:updated>
            <content:encoded><![CDATA[<h3>Expert System — A quick introduction</h3><h3>Background</h3><p>In 1997, <a href="http://en.wikipedia.org/wiki/Deep_Blue_(chess_computer)"><strong>Deep Blue</strong></a> defeats chess grandmaster Gary Kasparov and in 2011 <a href="http://en.wikipedia.org/wiki/Watson_(artificial_intelligence_software)"><strong>Watson</strong></a> defeats Jeopardy champions, Ken Jennings and Brad Rutter. The reigning champion of Go, the world&#39;s most classic challenging game, is an AI program named AlphaGo. Deep Blue demonstrated solving extremely complex but logically well-bounded problems like chess. Watson on the other hand solved the problem of meaning behind natural languages, which inherently is unbounded. Both AlphaGo and Watson are indicative of the great strides made in the field of Artificial Intelligence. While significant progress has been made in the <a href="http://en.wikipedia.org/wiki/AI-complete">AI-complete</a> fields like natural language processing, self-decision making, and open domain question answering, it may take a while for such fields to become useful for mainstream commercial applications. One AI discipline that has matured and found applicability in diverse domains like internal medicine, accounting, finance, organic chemistry, etc. is <strong>Expert Systems</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*nkDw_g57jxA5OP7v.GIF" /></figure><h3>What is an Expert System?</h3><p>An expert system is a computer system that emulates, or acts in all respects, with the decision-making capabilities of a human expert. An expert system is functionally equivalent to a human expert in a specific problem domain of reasonable complexity. The equivalence is qualified in terms of its capability to:</p><ul><li>Reason over representations of human knowledge</li><li>Solve the problem by heuristic or approximation techniques</li><li>Explain and justify the solution based on known facts</li></ul><h3>Why do we need one?</h3><p>So why do we need to create an Expert System if a human expert can solve the same problem? Well here are a few reasons :</p><ul><li>Low cost of expertise</li><li>Response without cognitive bias or logical fallacies</li><li>24/7 availability with high reliability</li><li>Clone the expert</li><li>Use in hazardous environments</li><li>Ability to explain the reasoning without attitude.</li><li>I will delve into theoretical concepts later, but for now, let’s get started with programming as an expert.</li></ul><h3>How do we build one?</h3><p><a href="https://sourceforge.net/projects/clipsrules/files/CLIPS/6.40/">Download </a>and install CLIPS. <em>(CLIPS is an open-source framework for programming expert systems, it was developed by NASA-Johnson Space Center).</em></p><h4>Windows</h4><p>Open CLIPSWin.exe. from the Window, the menu opens the facts and agenda windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*ahi-ygvdTxavELzw.GIF" /></figure><h4>macOS</h4><p>Open Clips-IDE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lB1HSmeOUXI8x7s4_OR5YA.png" /></figure><p>You are now all set to program an expert system.</p><h3>Writing “Hello world” in CLIPS</h3><p>In the CLIPS programming window write the following code (or just copy/paste it) and hit enter.</p><pre>(defrule start-up<br>=&gt;<br>(printout t &quot;Hello indecisive homo sapien. The ‘wise one’ is here to help!&quot; crlf ))</pre><p>A “Hello indecisive…” message will show up on the window. Let us take a closer look at what just happened.</p><h4>Heuristic knowledge as Rules</h4><p>A rule captures a set of actions to perform in response to certain stimuli. The stimuli come from the information in the working memory of an expert system. This information is called facts. Coming back to the “Hello world” app. The first thing you did was define a rule using the “defrule” construct and named it “start-up”. This instructs the expert system to create a rule. A rule consists of two parts</p><ul><li>Left hand side (LHS) or antecedent</li><li>Right hand side (RHS) or consequent</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*NnUTqO9KYJqFJ4yz.GIF" /></figure><p>The antecedents of a rule are a collection of “conditional elements” (CEs). When all CEs are satisfied (evaluate to true) actions in the RHS of the rule are executed. Since our “start-up” rule has no conditions it executes (or fires) immediately after you issue the (run) command. The “run” command instructs the expert system engine to fire all rules whose LHS or antecedents are true (or have no antecedents).</p><h4>Rules with antecedents</h4><p>Now let us modify the rule and add a condition (antecedent or LHS). Say you want to print “Hello indecisive…” only when there exists a fact with a specific name in it. In order to do that we modify the rule and add an antecedent or LHS to it. The antecedent is a fact represented by symbols “name asheesh goja” . I will explain facts and symbols in more detail later, but for now modify the rule by typing the following text and hit enter.</p><pre>(defrule start-up<br>(name asheesh goja) <br>=&gt;<br>(printout t &quot;Hello indecisive homo sapien. The &#39;wise one&#39; is here to help!&quot; crlf))</pre><p>This time there is no response from the system. It is because this rule will fire only when a fact “(name asheesh goja)” exists in its working memory or facts list.</p><p>To add this fact type the following code and hit enter</p><pre>(assert (name asheesh goja))</pre><p>Notice two things happen after you issue this command</p><ul><li>An entry shows up in the agenda window: “start-up: f-1”</li><li>And another one in the facts windows: “f-1 (name asheesh goja)”.<br>(Note: You will also see a fact “f0 (initial-fact)”, this ‘a priori’ fact is created by the CLIPS engine</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*2WKYgrKUXawYotkt.GIF" /></figure><p>Creating (or “asserting” in experts system parlance) a fact triggers the “start-up” rule, as the rule’s antecedents are now true. So when you run the engine it fires the rule. Type (run) and hit enter to see the “Hello indecisive…” shows up.</p><p>Ok now let us step back to take a peek under the hood.</p><h3>Anatomy of an expert system</h3><p>An expert system consists of the following components:</p><ul><li>Explanation facility — Provides the reasoning behind a certain conclusion.</li><li>Knowledge acquisition facility — Provides a means for capturing and storing knowledge elicited from a human expert(s) into a knowledge base.</li><li>Knowledge base– Stores this knowledge in form of rules.</li><li>Working memory–Database of facts used by the rules.</li><li>Inference engine– Decides which rule to fire and in what priority.</li><li>Agenda — A prioritized list of rules whose conditions are satisfied by facts.</li><li>Pattern matcher– Compares rules and facts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/0*_pIirABcBDQBQrJw.gif" /></figure><h3>Execution of an expert system</h3><p>The core facility in an expert system is its inference engine. The inference engine follows this cycle</p><ul><li><strong>Pattern matcher</strong> uses an algorithm like Rete to create a list of rules whose antecedents (or LHS) match (or are satisfied) with the facts in the working memory.</li><li>The <strong>agenda</strong> determines the order in which the rule fire from this list.</li><li>The <strong>conflict resolver</strong> selects the rule with the highest priority from the agenda.</li><li>The <strong>action executor</strong> executes the consequent (or RHS) of the selected rule and also removes this rule from the agenda.</li><li>The <strong>pattern matcher</strong> kicks in again and updates the agenda with rules whose antecedents match and also removes the rules whose don’t.</li></ul><p>This cycle continues until there are no rules left on the agenda. A particular rule fires only once its LHS is satisfied. This important feature of expert systems is called <strong>Refraction</strong>. It ensures that the expert system doesn’t get caught in trivial loops.</p><p>Now that we know how an expert system works; the next thing is to find out how human expertise is converted into a format for expert systems to reason over. This is called Knowledge Engineering.</p><h3>Knowledge Engineering</h3><p>Knowledge engineering is the process of eliciting the domain knowledge from a human expert and then structuring, formalizing, and integrating it into the knowledge base of an expert system. Domain knowledge is the logic or heuristic used by a human to arrive at a particular solution. Unlike an algorithm where you are guaranteed to get an exact solution in a finite amount of time, expert systems only guarantee the most reasonable solution in a finite time. Depending on the level of a human expert’s understanding of the causal connections of a system, a knowledge engineer can program an expert system using heuristic/empirical or structural/behavioral knowledge. The former is called <strong>shallow knowledge</strong> and the latter <strong>deep knowledge</strong>. This knowledge is expressed as a collection of rules called the knowledge base. Now let us see how domain knowledge is represented as rules.</p><p><strong>Knowledge Representation</strong></p><p>Computer programs consist of data structures and algorithms while expert systems consist of knowledge and inference. Knowledge is part of a hierarchy called the knowledge pyramid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*5h5CvhW-9TKYkRkM.gif" /></figure><p>Representing knowledge so that valid inference can be made from it is called knowledge representation. Before we represent knowledge we first need to define:</p><ul><li>What is knowledge?</li><li>How is knowledge acquired?</li><li>How do we know what we know?</li><li>A study of such questions is called epistemology.</li></ul><h4>Epistemology</h4><p>Epistemology is the study of the nature, structure, and origins of knowledge. Categories of epistemology are:</p><ul><li>A priori — This is universally true knowledge.</li><li>A posteriori — This is knowledge acquired from senses and can be invalidated on basis of new knowledge</li><li>Procedural — This is the knowledge of how to do something.</li><li>Declarative — This is the knowledge that something is true or false.</li><li>Tacit — This is unconscious knowledge.</li></ul><p>Epistemic categories are represented in expert systems as productions.</p><h4>Productions</h4><p>Productions consist of two parts: A precondition (an IF) and a post condition (a THEN). If the production’s precondition is verified as true based on the current state of the system, then the production is triggered. You saw one such production called rules in the “Heuristic knowledge as Rules” section. Additional techniques used to define productions are:</p><ul><li>Semantic nets</li><li>Frames</li><li>Logic</li></ul><h4>Logic</h4><p>Logic is the study of making valid inferences. It has two primary branches:</p><ul><li>Informal Logic — Here the meaning of the statement is used to make valid inferences. Semantics is of the essence.</li><li>Formal Logic — Here the form of statement is used to make valid inferences. The syntax is of the essence.</li></ul><h4>Formal Logic</h4><p>Expert systems need to make inferences without knowing the meaning of words, hence they use formal logic. The most fundamental formal logic is based on syllogism. Consider the following statements</p><ol><li>all programmers are smart.</li><li>asheesh is a programmer.</li><li>therefore asheesh is smart.</li></ol><p>Using the law of syllogism, the 3rd statement was inferred from the hypothesis of the 1st statement and the conclusion of the 2nd. This syllogism is represented in an expert system as a rule that takes the form</p><ol><li>IF all programmers are smart AND</li><li>asheesh is as programmer</li><li>THEN asheesh is smart</li></ol><h4>Methods of inference or reasoning</h4><p>The key to knowledge representation is to separate the actual meaning of words from the reasoning process itself. What may appear as reasoning may be knowledge. Once that is accomplished then inferences can be represented as mathematical rules that change one set of symbols to another. Various methods of making inferences are:</p><ul><li>Deduction — a premise, a conclusion, and a rule that the former implies the latter</li><li>Induction — the inference is from the specific case to the general</li><li>Intuition — no proven theory</li><li>Heuristics — rules of thumb based on experience</li><li>Generate and test — trial and error</li><li>Abduction — reasoning back from a true condition to the premises that may have caused the condition</li><li>Default — the absence of specific knowledge</li><li>Autoepistemic — self-knowledge</li><li>Nonmonotonic — previous knowledge</li><li>Analogy — inferring conclusions based on similarities with other situations<br>The process of grouping multiple inferences that connect a problem with a solution is called chaining.</li></ul><h4>Chaining</h4><p>A chain that is traversed from a problem to its solution is called a forward chain. A chain traversed from a hypothesis back to the facts that support the hypothesis is a backward chain. Consider the following rules chain</p><ul><li>IF A then B</li><li>IF B then C</li><li>IF C then D</li></ul><p>If fact A is asserted then the inference engine matches the facts against the antecedents resulting in the assertion of intermediate facts B and C. This in turn leads to conclusion D. This is forward chaining.</p><p>In backward chaining, if fact (or hypothesis) D is asserted then the inference engine matches the facts against the consequents. Thus C and B now become sub-goals or intermediate hypotheses that must be satisfied to satisfy hypothesis D. The evidence as fact A ends the backward chain of sub-goals hence validating D. If no A is found then hypothesis D is unsupported. The chain now becomes</p><ul><li>IF D then C</li><li>IF C then B</li><li>IF B then A</li></ul><p>We will use this technique to create a backward chaining algorithm in part-2 of this article. For now, let&#39;s see how these concepts apply to our “Hello world” program.</p><h4>Knowledge representation in CLIPS</h4><p>In the “Hello world“ app the “start-up” rule has an antecedent (or LHS) expressed as a set of three symbols “name asheesh goja”. This rule creates the causal connection between the precondition (LHS) and the conclusion (RHS/antecedent). The CLIPS engine doesn’t know the meaning of these symbols. All it does is to see if a fact (a set of symbols in the working memory) matches the LHS of the rule. So when you entered the symbol “name asheesh goja” in the facts list, it resulted in a complete pattern match (between LHS and fact), hence activation of “start-up” rule. This in turn triggers the rule’s consequent, hence executing the command in its RHS viz. “(printout t “Hello indecisive homo sapien. The ‘wise one’ is here to help!”))”. Additional constructs used by a knowledge engineer to represent domain expertise are:</p><ul><li>Ordered Facts</li><li>Unordered Facts</li><li>Rules</li></ul><p>Let me explain them in more detail.</p><h4>Ordered Facts</h4><p>The fact “(name asheesh goja)” is an example of an ordered fact. The first field of an ordered fact specifies a “relation” that applied to the remaining fields in the ordered fact. Ordered facts don’t have an associated fact template. The ones that have are unordered facts.</p><h4>Unordered facts</h4><p>These are structured fact representations created using the “deftemplate” construct. We can use this construct to create a new fact called “homo-sapien” and add name and age attributes/slots to it. Type or copy/paste the following code blocks in CLIPS ( hit enter after you type them)</p><pre>(deftemplate homo-sapien<br> (multislot name (type SYMBOL) (default none) )<br> (slot age (type INTEGER) (default 0) ))</pre><p>I issued a (clear) command to remove any existing facts and rules. You can constraint attributes of an unordered fact with the following restrictions:</p><ul><li>type</li><li>default</li><li>cardinality</li><li>range</li><li>allowed-[symbols, strings, lexemes, floats, numbers, instance-names, values].</li></ul><h4>Rules</h4><p>Rules in CLIPS are created using the “defrule” construct. Let us rewrite the “start-up” rule to use the unordered fact created above. Type or copy/paste the following code in CLIPS and press enter</p><pre>(defrule start-up<br> (homo-sapien (age 37) (name asheesh goja)) <br> =&gt;<br> (printout t “Hello indecisive homo sapien. The ‘wise one’ is here to help!”))</pre><p>Notice that in the LHS of this rule the order of the fact’s slots doesn’t matter. I specified the age before the name. This is the reason why such facts are called unordered facts.</p><p>Now that you know the fundamental constructs required to create the knowledge base and working memory, let us see how to create a non-trivial program using some more advanced concepts. CLIPS allows you to control the pattern matching (matching facts with LHS) using</p><ul><li>Literal constraints</li><li>Variable constraints</li><li>Conditional Elements (CE)</li></ul><h4>Literal constraints</h4><p>The “start-up” rule’s LHS is constrained by the literals 37 and “asheesh goja”. This means that this rule will fire only when facts match these constraints. To see that add the following facts (one at a time, followed by pressing the enter key)</p><pre>(assert (homo-sapien (name huan goja) (age 38)))<br>(assert (homo-sapien (name thomas goja) (age 41)))</pre><p>Notice that no activations show up in the agenda window. This means that none of these facts match the LHS of the “start-up” rule; the reason being the literal constraint. Now add a fact that matches the constraints</p><pre>(assert (homo-sapien (name asheesh goja) (age 37)))</pre><p>You will now see three facts in the facts window and the following activation in the agenda window:</p><pre>0 start-up: f-3</pre><p>This means that the rule “start-up” LHS matches the fact “f-3”. The fact “f-3” corresponds to “(name (value asheesh goja) (age 37))”</p><h4>Variable constraints</h4><p>What if you want to constrain age attributes within a range of values. Say you want the rule to fire the rule only when the age of a person is more than 30 but less than 40. Additionally, you want to print out the name of the person(s) that fall in this age category. For that, you need variable constraints.</p><p>Modify the “start-up” rule’s LHS and add the following variable constraints. Type this code and press enter</p><pre>(defrule start-up<br> (homo-sapien (age ?a&amp;:(&gt; ?a 30)&amp;:(&lt; ?a 40)) (name $?n) ) <br> =&gt;<br> (printout t “Hello indecisive homo sapien named “ ?n “. The ‘wise one’ is here to help!” crlf))</pre><p>Notice two activations show up in the agenda window:</p><pre>“0 start-up: f-3”.<br>“0 start-up: f-1”.</pre><p>The syntax may take some time to get used to, but it perfectly complements the functional programming style of CLIPS. CLIPS uses the prefix notation as opposed to the infix which is common in procedural languages like C++, .net, Java, etc. Read this article for more information on such notations.</p><p>Now let us take a closer look at LHS to see its individual elements along with the variable constraints</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*tDQOnHnAdvF8VIoV.GIF" /></figure><p>This is how you read it in plain English:</p><p><em>Any homo sapien (homo-sapien) whose (age) stored in variable named ‘a’ (?a) and (&amp;) constrained by (:) a value greater that 30 (&gt; ?a 30) and (&amp;) constrained by (:) a value less that 40 (&lt; ?a 40) and (name) stored in multi-field variable named ’n’ ($?n)</em></p><p>In addition to the ‘&amp;’ connective constraint CLIPS supports:</p><ul><li>~ (not connective)</li><li>| (or connective)</li></ul><h4>And conditional element (CE)</h4><p>We looked at controlling the pattern matching using variable constraints within a fact, but what if we want to express relations between groups of facts. Say we want to trigger the “start-up” rule with a constrained “homo -sapien” fact and only if he/she is a millionaire. To do that we add another condition in the LHS of the rule and constraint it with the value stored in a variable ?n. Type this rule in CLIPS</p><pre>(defrule start-up<br> (and (homo-sapien (age ?a&amp;:(&gt; ?a 30)&amp;:(&lt; ?a 40)) (name $?n) ) <br> (millionaire $?n)) <br> =&gt;<br> (printout t “Hello indecisive millionaire homo sapien named “ ?n “. The ‘wise one’ is here to help!” crlf))</pre><p>The rule will fire when the following facts exist:<br><em>Any homo-sapien whose age is within 30–40 and whose name stored in variable ?n matches any millionaire whose name is the name stored in variable ?n.</em></p><p>Notice after you write this modified rule the agenda window becomes empty. Now enter a “millionaire” fact</p><pre>(assert (millionaire asheesh goja))</pre><p>The agenda now shows:</p><pre>“0 start-up: f-3,f-4”.</pre><p>The conditional element used in this rule was “and”. Using it is optional as it is assumed by default. So you can rewrite the rule and omit “and” CE.</p><pre>(defrule start-up<br> (homo-sapien (age ?a&amp;:(&gt; ?a 30)&amp;:(&lt; ?a 40)) (name $?n) ) <br> (millionaire $?n) <br> =&gt;<br> (printout t “Hello indecisive millionaire homo sapien named “ ?n “. The ‘wise one’ is here to help!” crlf))</pre><h4>Or conditional Element</h4><p>Say you want to trigger this rule with either of the conditions: homo-sapien or millionaire. This is done using the “or” CE</p><pre>(defrule start-up<br> (or (homo-sapien (age ?a&amp;:(&gt; ?a 30)&amp;:(&lt; ?a 40)) (name $?n) ) <br> (millionaire $?n)) <br>=&gt;<br> (printout t “Hello indecisive millionaire homo sapien named “ ?n “. The ‘wise one’ is here to help!” crlf))</pre><p>The rule will now fire only when the following facts exist:<br><em>Any homo-sapien whose age is within 30–40 and whose name is stored in variable $?n, OR any millionaire whose name is stored in variable $?n.</em></p><p>Notice three activations show up in the agenda window:</p><pre>“0 start-up: f-4”.<br>“0 start-up: f-3”.<br>“0 start-up: f-1”.</pre><p>This means that this rule will fire three times.</p><p>Enter (run) and see the following:</p><pre>Hello indecisive millionaire homo sapien named (asheesh goja). The ‘wise one’ is here to help!<br>Hello indecisive millionaire homo sapien named (asheesh goja). The ‘wise one’ is here to help!<br>Hello indecisive millionaire homo sapien named (huan goja). The ‘wise one’ is here to help!</pre><h4>Additional CEs supported in CLIPS are</h4><ul><li>not</li><li>exists</li><li>test</li><li>forall</li><li>logical</li></ul><h4>Limitations of Expert Systems</h4><p>While expert systems provide consistent answers for repetitive decisions and can process large quantities of information; it is important to know their limitations though. Here are a few:</p><ul><li>Expert systems work best in a narrow domain of reasonable complexity. Generalizing them for a broader domain is usually counterproductive.</li><li>An expert system cannot completely replace human common sense.</li><li>It is not always possible for a human expert to explain how he/she reasons. This can make developing an expert system completely unfeasible.</li><li>Expert systems don’t guarantee the quality of their rules. Garbage in = Garbage out.</li><li>Given the ease of adding new rules, a novice knowledge engineer can easily add rules that conflict with existing rules, potentially compromising the accuracy/reliability of the expert system.</li></ul><h3>Conclusion</h3><p>This post gives you the theoretical concepts required to build an application using an Expert System. You can see how to design and code Expert systems based Artifical Advisor in CLIPS from my <a href="https://www.codeproject.com/Articles/179378/Man-Marriage-and-Machine-Adventures-in-Artificial">past posts on Code Project</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24f3c785a41d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>