<?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 Nandana Dileep on Medium]]></title>
        <description><![CDATA[Stories by Nandana Dileep on Medium]]></description>
        <link>https://medium.com/@nandanadileep29?source=rss-b36c4376690b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vPsoxpJDiqH4LLYq</url>
            <title>Stories by Nandana Dileep on Medium</title>
            <link>https://medium.com/@nandanadileep29?source=rss-b36c4376690b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:29:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nandanadileep29/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[What I Saw from Profiling vLLM on an NVIDIA A100]]></title>
            <link>https://medium.com/@nandanadileep29/what-i-saw-from-profiling-vllm-on-an-nvidia-a100-eb69a9c7da74?source=rss-b36c4376690b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb69a9c7da74</guid>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[throughput]]></category>
            <dc:creator><![CDATA[Nandana Dileep]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 13:14:22 GMT</pubDate>
            <atom:updated>2026-11-07T13:14:22.996Z</atom:updated>
            <content:encoded><![CDATA[<h3>An experiment with KV caching, attention overhead, and small speed improvements.</h3><h3>The question I started with</h3><p>While learning how vLLM schedules requests, I became interested in the tradeoffs behind cache reuse:</p><blockquote><em>When does reusing cached work reduce latency, and when does the overhead outweigh the savings?</em></blockquote><p>KV caching saves attention information from tokens the model has already processed. Prefix caching lets requests reuse that information when their prompts begin with the same tokens.</p><p>I wanted to understand where that reuse pays off, where it adds overhead, and what determines the boundary between the two. I started experimenting to measure those tradeoffs.</p><h3>First, a few simple definitions</h3><p>I measured three main things:</p><ul><li><strong>Throughput:</strong> how many output tokens the server produces per second.</li><li><strong>Time to first token:</strong> how long a request waits before receiving its first output token.</li><li><strong>Total latency:</strong> how long the complete request takes.</li></ul><p>I also measured p95 latency, the time within which 95% of requests finish. It helps show what slower requests experience.</p><p>Concurrency means the number of requests the client keeps active at once.</p><h3>More cache reuse brought extra costs</h3><p>My early experiments changed how cached KV data was reused and managed.</p><p>Some changes reused more tokens. But the NVIDIA benchmarks did not establish a throughput improvement from those cache policies. Partial-prefix reuse also increased first-token latency in the tested workloads.</p><p>Reusing cached work has its own costs. The server may need to:</p><ul><li>Look up matching entries.</li><li>Update cache information.</li><li>Copy data into a usable location.</li><li>Manage blocks as requests arrive and finish.</li></ul><p>Those costs can consume the time saved by avoiding computation. That led me to profile the system: measure where it was spending time.</p><h3>Profiling exposed another source of overhead</h3><p>The profiles showed query and output tensor copies inside a FlashAttention-2 attention path used for single-query work, including decoding.</p><p>These were attention-layout copies, separate from copying KV-cache blocks.</p><p>This path rearranges query heads into groups before running attention. That arrangement is intended to help computation, but rearranging tensors can also require copies.</p><p>I tested a guarded routing change for eligible single-query calls. The guard keeps an explicit “no future tokens” window setting, selecting an existing alternative FA2 path instead of the grouping path. The model’s query heads still share KV heads. Direct native attention checks showed the CPU-recorded clone count falling from two to zero for the tested call.</p><p>The next question was whether this would improve complete request performance.</p><h3>I tested beyond the original setup</h3><p>Earlier controlled tests used synthetic prompts and eager execution. To broaden the evaluation, I added:</p><ul><li>CUDA graphs enabled.</li><li>HTTP serving.</li><li>Human-written prompts from WildChat.</li><li>An additional model family.</li></ul><h4>Models and workloads</h4><p>For this final benchmark, all experimental cache policies were disabled; native prefix caching and chunked prefill remained enabled. This isolates the attention-routing change from the earlier cache experiments.</p><p>Requests used local HTTP, with the client and server on the same machine. Timings included HTTP streaming and detokenization, but excluded tokenization, model loading, compilation, and warmup. These measurements are not internet-facing application latency.</p><p>The prompts were English and mostly short. KV memory was ample, and no preemptions occurred, so these results do not establish benefits under memory pressure or predominantly long-prompt traffic.</p><p>The models were:</p><ul><li><strong>Qwen3–0.6B:</strong> 0.6 billion parameters.</li><li><strong>Qwen3–1.7B:</strong> 1.7 billion parameters.</li><li><strong>SmolLM3–3B:</strong> 3 billion parameters.</li></ul><p>Each model used the same 96 selected human prompts, rendered with its own chat template. I tested concurrency three and sixteen, with fixed output lengths of 32 and 128 tokens.</p><p>Each comparison used six paired repeats. Stock and optimized servers ran separately, with their order alternating across repeats.</p><p>The complete timed study included 36 fresh servers, 13,824 requests, and 1,105,920 generated tokens.</p><p>This was a controlled workload using real prompts. It was not a replay of production traffic: output lengths were forced, and requests followed a fixed concurrency limit.</p><h3>Correctness checks set an important boundary</h3><p>Before accepting speed results, I checked numerical results and generated outputs.</p><p>All three models passed the checks in batch-invariant FA2 mode with CUDA graphs enabled. Batch-invariant mode is intended to keep model results consistent when requests are batched differently.</p><p>In that mode:</p><ul><li>Across all three models, all 96 checked pairs of full API log-probability vectors matched in value.</li><li>Across all three models, all 24 checked natural-response pairs produced identical token sequences.</li><li>Every timed output sequence matched across variants and repeats.</li></ul><p>The default BF16 comparisons exceeded my declared numerical-equivalence limits, so I excluded those modes from timing.</p><p>This does not establish that their answers were worse. Different generated text is not an accuracy score. It means I could not claim numerical equivalence under the checks I had defined.</p><p>The performance results below therefore apply to the validated batch-invariant configuration.</p><h3>The speedup depended on concurrency</h3><h4>At concurrency three</h4><p>The throughput improvement was small and repeatable:</p><ul><li><strong>Qwen3–0.6B:</strong> about 2.9–3.2%.</li><li><strong>Qwen3–1.7B:</strong> about 1.8–2.0%.</li><li><strong>SmolLM3–3B:</strong> about 1.8–2.0%.</li></ul><p>Across these low-concurrency settings, p95 total latency fell by approximately 1.5–2.8%.</p><h4>At concurrency sixteen</h4><p>The benefit largely disappeared. Most throughput comparisons did not establish an improvement.</p><p>SmolLM3 with 128-token outputs showed a small, repeatable throughput regression of approximately 0.63%.</p><p>Qwen3–0.6B with 128-token outputs also showed approximately 0.76% worse p95 total latency.</p><p>Time to first token also showed no consistent improvement across the study.</p><p>The result was useful, but clearly conditional.</p><p>Attention routing with CUDA graphs and human prompts. Reported improvements are median paired changes across six repeats; error bars show 95% bootstrap intervals. Intervals crossing zero do not establish a consistent improvement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oye5faCgQE4J8jiuYnVm7Q.png" /></figure><h3>The routing change affected more than copies</h3><p>Further source inspection clarified an important part of the experiment.</p><p>The routing change also affects automatic split-KV execution in the frozen FA2 implementation. Split-KV divides attention work across portions of the cached keys and values. Changing that choice can affect parallelism and floating-point reduction order.</p><p>Batch-invariant mode already forces a single split in the pinned backend. That helps explain why execution mode matters to this experiment.</p><p>The study measured a routing change with several connected effects. It did not isolate every part of the speed difference as a pure copying cost.</p><h3>What I can conclude</h3><p>The strongest conclusion is:</p><p>A guarded attention-routing change improved throughput by roughly 1.8–3.2% at low concurrency in the tested batch-invariant FA2 configuration. The benefit mostly disappeared at higher concurrency.</p><p>The experiments also changed how I think about optimization:</p><ul><li>Saving computation is useful only after accounting for the cost of reuse.</li><li>Removing copies can change other execution choices.</li><li>A speed improvement needs numerical and output checks.</li><li>Neutral results and regressions help define where an optimization is useful.</li></ul><p>I also found closely related prior work, including a 2024 output-buffer workaround and an output-stride proposal addressing the same decode path. This study does not establish a new attention algorithm.</p><h3>What I would investigate next</h3><p>A useful next experiment would try to reduce layout copies while preserving the grouped attention and split-KV choices. That would help separate the cost of moving data from the benefit of the existing computation path.</p><p>I would also expand task-level quality evaluation, workloads, and hardware coverage before making a broader deployment claim.</p><p>For now, the value of this experiment is a measured boundary: a small optimization helped in a specific setting, and broader testing showed where that benefit stopped.</p><h3>Code, scope, and attribution</h3><p><strong>Code and results:</strong> <a href="https://github.com/ver-labs/vllm-exp">vLLM experiment repository</a></p><p><strong>Scope:</strong> Frozen vLLM v0.31.0 baseline, NVIDIA A100 PCIe 40GB allocation, BF16 batch-invariant FlashAttention-2, CUDA graphs enabled, and the declared controlled workloads.</p><p><strong>Dataset attribution:</strong> This study uses information from WildChat, available under the ODC Attribution License.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb69a9c7da74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[13 Performance Experiments on One Reranker: The Limits of Faster GPU Code]]></title>
            <link>https://medium.com/@nandanadileep29/13-performance-experiments-on-one-reranker-the-limits-of-faster-gpu-code-94670171711f?source=rss-b36c4376690b------2</link>
            <guid isPermaLink="false">https://medium.com/p/94670171711f</guid>
            <category><![CDATA[mlx]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[triton]]></category>
            <dc:creator><![CDATA[Nandana Dileep]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 17:59:25 GMT</pubDate>
            <atom:updated>2026-10-11T17:59:25.843Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Benchmarking compilation, custom kernels, batching, and serving</em></p><p>To see how inference optimization works in practice, I took a pretrained reranker and tried to make it faster. Across 13 experiments on an <strong>Apple GPU</strong> and an <strong>NVIDIA L40S</strong>, the work compared PyTorch and MLX, tested compilation and custom GPU kernels, and measured Python and Rust serving. The question was which changes improved document scoring and whether those gains held up for complete HTTP requests.</p><p>I used <strong>cross-encoder/ms-marco-MiniLM-L6-v2</strong>, a pretrained reranker with about <strong>22.7 million parameters</strong>. A reranker takes a query and a set of candidate documents, scores each query–document pair, and orders the documents by relevance.</p><p>I kept the model weights unchanged throughout. The experiments focused on execution: frameworks, compilation, custom kernels, batching, and serving. I ran the Apple experiments on my <strong>MacBook’s M5 GPU</strong> and the NVIDIA experiments on an <strong>L40S in a remote cluster</strong>. Each optimization was compared against a baseline on the same device.</p><p>I measured performance at three levels: individual GPU operations, complete document scoring, and complete HTTP requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lK2ZLuGeH1xE4JaALFPPHw.png" /></figure><p>These levels fit inside each other:</p><p>HTTP request → complete document scoring → model execution → individual GPU operations.</p><p>A change could help at one level without producing a measurable improvement at the next. Keeping those measurements separate helped me understand what an optimization had achieved.</p><h3>How I measured improvements</h3><p>The primary scoring workload used <strong>100 documents per query, a pair batch size of 16, and a maximum combined query–document length of 512 tokens</strong>. The implementation comparisons used FP32. Model batches, documents per request, and concurrent requests are three different settings; I changed them separately.</p><p>Candidates came from fixed <strong>BM25 retrieval results</strong> on <strong>SciFact and NFCorpus</strong> development data. I did not inject positive documents into the candidate lists. Primary timing used 16 predetermined queries, while secondary sweeps used four. The accuracy audit was larger: 485 queries at each of 10, 50, and 100 candidates, totaling 77,600 query–document pair occurrences per implementation.</p><p>I checked numerical agreement and ranking behavior before accepting timing results. All 11 implementation audits passed the declared checks. There were no top-1 or top-10 membership changes, although some nearly tied documents changed order. Passing these checks means the differences stayed within the declared limits; the outputs were not always identical.</p><p>For primary direct scoring, I collected 18 paired repetitions across six Apple sessions and 15 across five NVIDIA sessions. The reported performance intervals use independently started sessions, rather than treating every document as an independent trial. They are exploratory 95% intervals, without correction for the many comparisons in the study.</p><p>I also set a practical rule before collecting headline results: the lower interval bound had to exceed a <strong>5% improvement</strong> to qualify as a practical win. A small measurable difference could therefore pass the statistical comparison without changing my implementation choice.</p><h3>Experiment 1: PyTorch versus MLX on Apple M5</h3><p>I started by measuring complete document scoring with <strong>stock PyTorch and MLX</strong>. I also measured complete HTTP requests using a Python coordinator at concurrency one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQU8Rejfj5iX2tlfWOGj9A.png" /></figure><p><em>Apple M5; 100 documents per query; batch size 16; maximum 512 tokens; warm execution.</em></p><p>Direct scoring excludes HTTP handling and sorting. The HTTP measurements include those stages, plus queueing and returning the response. I did not isolate sorting or HTTP overhead as individual benchmarks.</p><p>The two columns came from separate benchmark runs with different execution patterns. Their absolute throughput values cannot be subtracted to estimate HTTP overhead. The higher HTTP throughput does not mean HTTP accelerated inference. The supported comparison is between frameworks within each measurement setting.</p><p>PyTorch outperformed MLX in both settings for this model on my M5. One relevant implementation detail was attention: MiniLM has a head dimension of 32, which the installed MLX version’s fused full-attention kernel did not support. Runtime checks and dispatch evidence showed the mathematical fallback. This result describes the implementations I measured, rather than a general advantage for every PyTorch workload.</p><h3>Experiment 2: Compiling PyTorch</h3><p>Next, I tried torch.compile while keeping the model weights and primary workload fixed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKXoYJTPTMjgT4ivRYHzQQ.png" /></figure><p>The percentage estimates come from paired comparisons within repetitions. They differ from dividing the separately calculated throughput medians in the table.</p><p>Compilation passed the accuracy checks on both devices. On Apple, it was a practical improvement for warm direct scoring. On NVIDIA, the improvement was smaller and did not clear the predefined practical threshold. <strong>The frozen selection rule therefore retained stock PyTorch as the practical NVIDIA baseline, even though compiled PyTorch had the fastest measured primary scoring throughput.</strong></p><p>The stock baseline already used <a href="https://docs.pytorch.org/docs/2.14/generated/torch.nn.functional.scaled_dot_product_attention.html"><strong><em>PyTorch’s SDPA</em></strong></a> attention implementation. On NVIDIA, profiling recorded memory-efficient SDPA; on Apple, it recorded native MPS SDPA math. I did not treat using the SDPA API as proof of FlashAttention.</p><h3>Experiment 3: Compiling MLX</h3><p>I also tested MLX compilation on Apple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njJkjc-_LcSVhQA97cbRXQ.png" /></figure><p>The paired improvement was <strong>25.3%</strong>, with a 95% interval of <strong>13.9%–37.9%</strong>. Compiled MLX passed the accuracy checks and was selected as the best measured MLX configuration under the frozen rule.</p><p>That gain did not make it the fastest framework in the study: compiled PyTorch remained faster on the primary Apple workload.</p><h3>Experiment 4: A custom Metal kernel</h3><p>For the Apple kernel experiment, I fused <strong>residual addition and LayerNorm</strong>. The residual addition combines a layer’s output with its input; LayerNorm normalizes the resulting values. A fused kernel can perform both in one GPU operation, reducing intermediate work and dispatches.</p><p>I adapted the kernel to the pretrained model’s hidden size of 384 and its LayerNorm settings, then checked synthetic inputs and real model activations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFfEf7WrvyNBvM8QTYYYqQ.png" /></figure><p>All three operation comparisons supported an improvement. These Apple timings include dispatch and synchronization; the paired ratios are calculated separately from the displayed medians.</p><p>Then I put the kernel inside the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ckzTA_4FRwp0EREFTY1KUQ.png" /></figure><p>Neither custom-versus-native model comparison established a scoring improvement. The MLX/custom-Metal paired ratio was <strong>0.909 [0.799, 1.015]</strong>; the compiled-MLX/compiled-Metal ratio was <strong>0.966 [0.821, 1.187]</strong>. Both intervals included parity.</p><p>This was the clearest example of why I needed more than an operation benchmark. <strong>The kernel became faster in isolation, but I could not establish that it made complete document scoring faster.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uSjvomB4iuqw-qdQBwHFWw.png" /></figure><h3>Experiment 5: A custom CUDA kernel</h3><p>On NVIDIA, I implemented the same <strong>residual-plus-LayerNorm intervention in CUDA</strong> and compared it against both stock PyTorch and an explicit matched graph. The explicit graph agreed exactly with stock scores, which helped check the implementation comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQmUif6SC5DOctguBrGCfA.png" /></figure><p>The custom CUDA implementation passed the accuracy checks, but offered little improvement over normal PyTorch and was about 2.9% slower than compiled PyTorch. Its isolated kernel helped only at the largest tested input size. Combining it with full-model compilation was unsupported because the compiler could not trace the external CUDA call.</p><h3>Experiment 6: A custom Triton kernel</h3><p>I wrote the same fused operation in <strong>Triton</strong> and ran it on the NVIDIA L40S.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNTTRn4HFVHQWSZSTLUOPQ.png" /></figure><p>Triton passed the accuracy checks, but it did not beat compiled stock PyTorch. The paired compiled/Triton ratio was <strong>0.975 [0.972, 0.978]</strong>. Isolated operation results also varied with shape and did not establish a consistent improvement.</p><p>Profiling helped put the intervention in context. In one selected-query CUDA profile, all 13 LayerNorm kernels accounted for roughly <strong>1.9% of summed leaf GPU-kernel time</strong>. Twelve residual normalizations were eligible for fusion; the embedding normalization was not. Residual-addition time was outside that 1.9%, so the figure is not an upper bound on the fusion opportunity.</p><p>Tokenization dominated that query’s synchronized stage breakdown. This was a selected-query diagnostic, rather than a fraction measured over every query or HTTP request. It showed why optimizing one model operation could have limited reach, without establishing the cause of every timing difference.</p><h3>Experiment 7: Increasing the pair batch size</h3><p>I swept batch sizes <strong>1, 8, 16, 32, and 64</strong> at 100 documents per query and the 512-token cap.</p><p>Here are representative stock and compiled PyTorch results from the secondary scoring sweep:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DgRaaG_Cwn1oA209PCfEZw.png" /></figure><p><em>These are four-query diagnostic sweeps, separate from the primary timing collection. Secondary batch sizes did not receive the complete primary accuracy audit.</em></p><p>On NVIDIA, batch size one was costly. Larger batches increased throughput, with gains becoming smaller toward the upper end of the sweep.</p><p>Apple’s results were non-monotonic: batch size one sometimes exceeded larger batches. Dynamic padding and framework execution change with batch size, and I did not establish a causal explanation. I retained the frozen primary batch size of 16 rather than claiming it was globally optimal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSVtF5NJxKnXT4NTCk9jHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rD0oozJ37dBihCbqmZbDg.png" /></figure><h3>Experiment 8: Changing the documents per request</h3><p>A pair batch is the amount processed in one model batch. A request can contain more documents than that, requiring multiple batches. I tested requests containing <strong>10, 50, and 100 documents</strong>.</p><p>These Apple results use the Python coordinator at concurrency one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Clhfqc16kyHGzQ4wgvlNqA.png" /></figure><p>More documents meant more work per request and fewer completed requests per second. That is why a requests-per-second number needs its document count next to it. A service processing 100-document requests is doing a different amount of work from one processing 10-document requests.</p><p>This sweep also made the framework difference visible in latency: PyTorch was faster at all three request sizes in this setup.</p><h3>Experiment 9: Shortening the token limit</h3><p>I tested maximum lengths of <strong>128, 256, and 512 tokens</strong>. Shorter inputs reduced computation, but also removed information from documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fk1U4jQKEe5BPoC6yI4t_A.png" /></figure><p><em>Secondary four-query scoring sweeps; 100 documents per query and batch size 16. These are diagnostic comparisons, not fully accuracy-qualified replacements for the primary workload.</em></p><p>The speed difference was substantial, especially on Apple. But the untruncated median input lengths in the K100 timing fixture were 383 tokens for SciFact and 358.5 for NFCorpus. A 128-token cap truncated almost every pair.</p><p>On a separate 16-query context-quality diagnostic, the L128-minus-L512 nDCG@10 difference was <strong>−0.0165</strong>, with an interval of <strong>[−0.0700, 0.0178]</strong>. MRR@10 differed by <strong>−0.0365 [−0.1927, 0.0835]</strong>. At 256 tokens, the nDCG difference was <strong>+0.0017 [−0.0053, 0.0111]</strong>.</p><p>Those broad intervals did not establish application-equivalent quality. I kept 512 tokens for primary comparisons. Shorter context can be a useful tradeoff, but changing the task input needs a quality decision alongside the timing result.</p><h3>Experiment 10: Python versus Rust serving</h3><p>I compared <strong>Python and Rust HTTP</strong> coordinators using the <strong>same Python inference worker</strong>. Rust handled coordination; it did not replace the model implementation. Request validation, sorting, response contents, and timeouts were matched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uREJLKc7ATb9hFjmgFFvRw.png" /></figure><p><em>Apple loopback HTTP, concurrency one, batch size 16, maximum 512 tokens.</em></p><p>Across the full document-count/concurrency matrix, Rust’s PyTorch comparisons favored Rust in six of nine exploratory intervals. The estimated gains were about 2–4%, and none cleared the practical 5% criterion. MLX coordinator differences were mostly inconclusive, with one point favoring Python.</p><p>P50 and throughput can move differently: slower requests affect total elapsed time even when the median request becomes slightly faster. These measurements did not establish a universal language advantage or justify switching coordinators solely for throughput.</p><h3>Experiment 11: Increasing concurrency</h3><p>I tested <strong>1, 4, and 8 simultaneous requests</strong>. The service used one inference worker and did not batch documents across requests.</p><p>For 100-document requests with the Python coordinator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zDTIBFXsSF4eZ-xEu77uw.png" /></figure><p>Throughput barely changed while latency rose. At concurrency four, Python/PyTorch’s median queue wait was about <strong>2,240 ms</strong>, compared with about <strong>755 ms</strong> of processing time. Requests were mostly waiting for the serialized worker.</p><p>This is a result about this service architecture. It does not establish how multiple workers or cross-request batching would behave. The client also used closed-loop load: a new request followed a completed one within each concurrency slot. I did not test open-loop overload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BS4egp20vI9pWHaVnMWI5A.png" /></figure><h3>Experiment 12: Did compilation help HTTP serving?</h3><p>After finding direct-scoring gains, I measured compiled backends behind HTTP. Each follow-up started new matched baseline workers. I compared within those families rather than borrowing baseline measurements from the earlier coordinator study.</p><p>For 100 documents per request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5zXRYDFUMA6rmFTg6acCg.png" /></figure><p>Compiled PyTorch’s direct-scoring improvement did not produce a practical HTTP gain. Concurrency one and four were inconclusive; concurrency eight showed a small exploratory effect below the practical threshold.</p><p>Compiled MLX improved its own HTTP baseline. Concurrency one and eight cleared the practical criterion; concurrency four’s lower bound did not. Even after compilation, MLX remained slower than PyTorch in the matched service measurements.</p><p>I could observe that the PyTorch gain did not carry through, but I did not establish one cause for the discrepancy. The direct and HTTP execution patterns differ, so these results cannot be used to assign an exact fraction to HTTP overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBZFUOcRvbimzJP76Gvn_A.png" /></figure><h3>Experiment 13: Startup cost and amortization</h3><p>Warm throughput leaves out the cost of reaching that state. I measured first scoring with fresh software-cache directories:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEpXbP5ZE9sUkrUeo6s4-A.png" /></figure><p>These were single ordered startup pairs. Fresh software caches do not clear all system shader or driver caches, and GPU driver cache state was unknown. The results illustrate overhead; they do not provide startup confidence intervals or fully cold-start estimates.</p><p>Using the observed model-setup-plus-first-score difference and median paired warm saving gave illustrative amortization estimates of about <strong>41 K100 queries on Apple</strong>and <strong>11,287 on NVIDIA</strong>. They are not production break-even predictions, and the Apple direct-scoring estimate does not imply an HTTP break-even point.</p><p>Startup mattered more when the warm improvement was small. It belongs alongside throughput when choosing an implementation for a short-lived process.</p><h3>What I would use after these experiments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whgrPGcde8s8jnCCLHzU3g.png" /></figure><p>The custom-kernel work was useful for learning. It required checking real activations, matching numerical behavior, profiling the model, and comparing against an existing optimized implementation. But a faster isolated operation was insufficient evidence for changing the complete inference path.</p><p>Compilation was the clearest successful intervention for Apple direct scoring. The serving experiments added another requirement: measure the complete request before claiming an application improvement.</p><h3>What this study does not establish</h3><p>This is one pretrained model on two hardware environments. It does not establish that the model’s size caused the results, that custom kernels are generally ineffective, or that one framework is universally faster.</p><p>The HTTP study used local loopback requests on Apple. NVIDIA HTTP, HTTPS/TLS overhead, mixed precision, open-loop overload, distributed serving, and cross-request batching were not measured. Each HTTP repetition contained 16 requests, so the highest-concurrency runs had only two waves; their P99 values cannot characterize production tails.</p><p>The timing fixtures were deliberately small enough to repeat. Secondary batch and context sweeps were diagnostic and did not receive the complete primary accuracy audit. The retrieval metrics describe these development candidates; training overlap is unknown, so this is not a leaderboard evaluation of the model.</p><p>Other machine activity was visible, exclusive isolation and fixed GPU clocks were not established, and Apple temperature/clock measurements were unavailable. Memory snapshots were process RSS measurements, not total-system peak memory.</p><p>Across the accepted HTTP runs, <strong>12,288 responses passed score and ranking validation, with no measured failures or timeouts</strong>. That supports correctness for the tested protocol; it does not establish behavior under production load.</p><h3>Closing thought</h3><p>I started this project to understand what the different performance tools let me do. By the end, I had a better way to decide whether a change was useful: check that it preserves the intended output, repeat the measurement, and time the amount of work the application needs to complete.</p><p>Some changes helped. Some made one operation faster without establishing a model improvement. Others showed small differences that did not justify adding complexity. Measuring all three levels made those distinctions visible.</p><p>or lets just say in this setup pytorch worked the best after all.</p><p><em>repository link — </em><a href="https://github.com/ver-labs/tiny-reranker"><em>https://github.com/ver-labs/tiny-reranker</em></a></p><p>The custom-kernel work was useful for learning. It required checking real activations, matching numerical behavior, profiling the model, and comparing against an existing optimized implementation. But a faster isolated operation was insufficient evidence for changing the complete inference path.<br>Compilation was the clearest successful intervention for Apple direct scoring. The serving experiments added another requirement: measure the complete request before claiming an application improvement.<br>What this study does not establish<br>This is one pretrained model on two hardware environments. It does not establish that the model’s size caused the results, that custom kernels are generally ineffective, or that one framework is universally faster.<br>The HTTP study used local loopback requests on Apple. NVIDIA HTTP, HTTPS/TLS overhead, mixed precision, open-loop overload, distributed serving, and cross-request batching were not measured. Each HTTP repetition contained 16 requests, so the highest-concurrency runs had only two waves; their P99 values cannot characterize production tails.<br>The timing fixtures were deliberately small enough to repeat. Secondary batch and context sweeps were diagnostic and did not receive the complete primary accuracy audit. The retrieval metrics describe these development candidates; training overlap is unknown, so this is not a leaderboard evaluation of the model.<br>Other machine activity was visible, exclusive isolation and fixed GPU clocks were not established, and Apple temperature/clock measurements were unavailable. Memory snapshots were process RSS measurements, not total-system peak memory.<br>Across the accepted HTTP runs, 12,288 responses passed score and ranking validation, with no measured failures or timeouts. That supports correctness for the tested protocol; it does not establish behavior under production load.<br>Closing thought<br>I started this project to understand what the different performance tools let me do. By the end, I had a better way to decide whether a change was useful: check that it preserves the intended output, repeat the measurement, and time the amount of work the application needs to complete.<br>Some changes helped. Some made one operation faster without establishing a model improvement. Others showed small differences that did not justify adding complexity. Measuring all three levels made those distinctions visible.<br>Results and reproduction<br>The detailed report, measured tables, and frozen protocol contain the full comparisons, accuracy checks, implementation details, and reproduction instructions. The figures above are developed from the saved E18 results.<br>The 13 sections group comparisons from the E18 study; they are not 13 independently preregistered studies. This article covers E18-small-v1, collected on October 10–11, 2026, using pinned model revision 233902d25c440f23af6f7d6e94d2946bac0bee0a.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94670171711f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside LLM Memory: OpenAI’s Dreaming V3 vs Anthropic’s userMemories]]></title>
            <link>https://medium.com/@nandanadileep29/inside-llm-memory-openais-dreaming-v3-vs-anthropic-s-usermemories-c2bd66134d43?source=rss-b36c4376690b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2bd66134d43</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Nandana Dileep]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 13:44:06 GMT</pubDate>
            <atom:updated>2026-06-22T13:44:06.713Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A Technical Comparison of State Architectures in two Modern LLM Systems</em></p><p>AI memory is no longer a research term. Every major AI provider has now engineered state management systems to make stateless LLMs behave as if they remember you. Many of you might have noticed that the way Claude injects what it knows about you and the way ChatGPT uses that same knowledge feel fundamentally different. (I found Claude weird, for the record.) That makes sense. OpenAI and Anthropic appear to have made fundamentally different architectural bets on how persistent memory should work. They change the security profile, token efficiency, and trust boundary of the entire system.</p><p>Every memory system built on top of an LLM is solving the same problem: how do you make a stateless function behave as if it has history? The answer is always the same. You inject context into the prompt. The difference is what you inject, when, and who decides.</p><h3><strong>ChatGPT’s Memory Evolution: From Notepad to Dreaming V3</strong></h3><h4><strong>April 2024: Saved Memories (V1)</strong></h4><p>The first version was essentially a notepad. You told it what to remember, it saved a line item. “Remember I’m a bird.” “Remember I prefer worms.” Explicit, manual, and brittle.</p><p>The problems were obvious. I remember manually deleting stale memories that had long stopped being relevant. This version also required strong cues to trigger a memory write. The model had to detect an explicit instruction. Anything subtle got dropped.</p><h4><strong>April 2025: Dreaming V0</strong></h4><p>This is where it gets architecturally interesting. OpenAI added a background process that could reference broader chat history beyond just the saved memories list. It no longer required explicit user instruction to write a memory.</p><p>But V0 was a layer on top of V1, not a replacement. Two systems running simultaneously, which created inconsistencies. Sometimes memory came from the notepad, sometimes from the background synthesis, and the model couldn’t always tell which was more authoritative. OpenAI’s own retrospective framing positions V0 as never sufficient as a standalone system.</p><h4><strong>June 2026: Dreaming V3</strong></h4><p>OpenAI’s own June 4 2026 blog post names this system “<a href="https://openai.com/index/chatgpt-memory-dreaming/">Dreaming V3</a>” and describes it as their most capable memory architecture yet. It becomes the new default foundation, with saved memories still available as a fallback. A background process learns from many conversations and synthesizes memory state continuously, capturing context that arises naturally rather than waiting for an explicit instruction.</p><p><a href="https://www.tenable.com/blog/hackedgpt-novel-ai-vulnerabilities-open-the-door-for-private-data-leakage">Tenable Research</a> documented this while investigating ChatGPT vulnerabilities in November 2025. They say the synthesized memory state is maintained in a separate data layer and injected into the system prompt at inference time. Every new conversation starts with a context window that already contains what the system has synthesized about you. Memory now self-updates as time passes.</p><p>What remains undocumented is the exact mechanism by which synthesis runs, how frequently it triggers, and whether additional retrieval layers operate underneath. The observed behavior suggests synthesized summaries rather than per-conversation retrieval, but OpenAI has not confirmed the internal architecture in detail.</p><p>This introduces a compression tradeoff. Whatever the synthesis process decides isn’t worth retaining gets dropped from the active memory state. Whether it’s recoverable in a future synthesis pass is unknown.</p><p>The trust boundary argument is where things get structurally important. In traditional software, trust boundaries are enforced by external systems: authentication layers, validation schemas, something outside the data that checks it before it moves between zones. Based on what’s publicly known, this appears to collapse in Dreaming V3. The model decides what to write, the model is exposed to conversation content that could be malicious, and the model later reads and acts on that memory. Neither OpenAI nor external researchers have documented a validation layer sitting between synthesis and injection. That absence is notable, though it is absence of evidence, not confirmed absence of a control.</p><h3><strong>Claude’s Memory Architecture</strong></h3><p>Unlike OpenAI, Anthropic has not published a detailed technical breakdown of their memory system. No named architecture, no eval numbers, no public blog post explaining the internals. Most of what’s known comes from reverse engineering, security disclosures, and leaked system prompts.</p><h4><strong>How It Works</strong></h4><p>Based on reverse engineering and security research, Claude’s memory appears to operate through a userMemories block injected directly into the system prompt at the start of every conversation. Not a retrieval step. Not a database query. A flat block of synthesized text that arrives before you&#39;ve said anything.</p><p>The approach appears conservative and extractive by design: pulling recognizable facts and patterns from recent conversations rather than synthesizing broadly across your entire archive. The synthesis cadence and exact scope have not been publicly confirmed by Anthropic.</p><p>No publicly documented conflict resolution mechanism comparable to OpenAI’s has been identified for Claude. Dreaming V3 explicitly addresses staleness, rewriting memories as circumstances change.</p><h4><strong>The Injection Point and What It Shares With ChatGPT</strong></h4><p>Both systems surface memory as privileged context presented before the user’s current message. For ChatGPT, Tenable Research documented this as system prompt injection at inference time. For Claude, security researchers have observed the same pattern via the userMemories block. Both models treat this content as higher trust than anything in the user turn.</p><p>Where they diverge is in apparent attack surface. ChatGPT’s background synthesis sweeps broadly across conversation history, meaning a payload buried in a document you processed weeks ago could plausibly surface in persistent memory on a future synthesis pass. Claude’s sweep appears narrower: recent conversations, conservative extraction. Harder to get a payload in, but not impossible.</p><p>But narrower is not safe. The moment something lands in userMemories it carries the same elevated authority as anything else in the system prompt. Narrower attack window, same consequence.</p><p>At a high level, both systems solve the same problem: how do you make a stateless model behave as if it remembers the user? The answer in both cases is synthesized memory injected into privileged prompt context. The difference lies in how that memory is created, updated, and maintained over time.</p><p>OpenAI’s Dreaming V3 appears to treat memory as a continuously evolving state. New conversations are synthesized into an existing memory representation, stale information is rewritten, and memory adapts as circumstances change. The emphasis is on keeping the memory state current, even if that means repeatedly modifying what was previously stored.</p><p>Claude’s userMemories system appears to take a more conservative approach. Public observations suggest a narrower synthesis scope and a stronger focus on extracting stable facts and patterns from recent interactions. While Anthropic has not documented the underlying architecture, the resulting behavior feels less like a continuously rewritten memory state and more like a curated profile of user information.</p><p>Both systems appear to favor synthesized summary injection over per-conversation retrieval, which keeps injected context leaner than raw chunk retrieval would. But the compression is lossy and opaque. What got dropped from synthesis is invisible to your application. You pay a context cost on every conversation for a memory block you didn’t author and can’t fully inspect.</p><p>Neither architecture exposes typed, timestamped, or attributable memory writes to the applications built on top of them. No public documentation from either company describes an external validation layer between synthesis and injection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*AxXEpowbilg7xZX0-O5Law.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2bd66134d43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[vLLM-Inspired LLM Serving Engine on Apple Silicon with MLX]]></title>
            <link>https://medium.com/@nandanadileep29/building-a-vllm-inspired-llm-serving-engine-on-apple-silicon-with-mlx-65b0576ebd05?source=rss-b36c4376690b------2</link>
            <guid isPermaLink="false">https://medium.com/p/65b0576ebd05</guid>
            <category><![CDATA[cpu-utilization]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[vllm-serving]]></category>
            <dc:creator><![CDATA[Nandana Dileep]]></dc:creator>
            <pubDate>Sun, 10 May 2026 11:07:18 GMT</pubDate>
            <atom:updated>2026-05-27T06:52:16.036Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Recreating core ideas behind vLLM on Apple Silicon using MLX while benchmarking the system against real vLLM serving.</em></p><p>This project explores the core systems ideas behind modern LLM serving engines such as vLLM through a lightweight MLX-based implementation built on Apple Silicon. The server implements <strong><em>continuous batching, paged KV-cache abstractions, prefix-aware KV reuse, and chunked prefilling</em></strong> to study how inference systems optimize throughput and memory efficiency under concurrent workloads. The implementation is benchmarked against both a CPU-only llama.cpp baseline and real vLLM deployments to analyze scaling behavior, latency tradeoffs, and hardware bottlenecks during concurrent inference serving.</p><h4>What vLLM Actually Does</h4><p>vLLM’s performance comes from three core ideas:</p><p><strong><em>Continuous batching: </em></strong>Instead of waiting for an entire batch to finish before starting the next one, requests are admitted and retired individually during generation. New requests can join while others are still decoding, keeping the GPU continuously busy.</p><p><strong><em>PagedAttention: </em></strong>KV cache is stored in fixed-size physical blocks, similar to virtual memory pages. Logical token positions map to physical blocks through a block table, reducing fragmentation and allowing memory to be allocated dynamically as sequences grow. In vLLM, the attention kernel reads directly from these block mappings without reconstructing a dense KV tensor.</p><p><strong><em>Prefix caching: </em></strong>If multiple requests share a common prefix, such as a system prompt, vLLM reuses previously computed KV states instead of recomputing the entire prefix for every request. Only the unique suffix needs additional processing.</p><blockquote>PagedAttention is implemented using fused CUDA kernels that directly operate on paged KV memory layouts. That is the component that cannot be reproduced efficiently on Apple Silicon without equivalent Metal kernels.</blockquote><h4>The Stack (which mimics vLLM)</h4><pre>Continuous Batching      → Requests join and leave the running batch <br>                           mid-generation, no waiting for others to finish<br>KV Management            → KV memory stored in fixed-size blocks and <br>                           allocated dynamically as sequences grow<br>Prefix Caching           → Shared prompt prefixes computed once and <br>                           reused across matching requests<br>Dynamic KV Allocation    → Sequences receive KV blocks on demand, <br>                           with eviction/preemption when memory is exhausted<br>Chunked Prefill          → Long prompts processed incrementally while <br>                           preserving accumulated KV cache state<br>Streaming Inference      → Tokens sent to the client as they generate, <br>                           (OpenAI-compatible)<br>KV Paging Experiment     → KV physically stored in pages, reassembled <br>                           into a dense tensor before each attention call</pre><h4>How Each Component Is Implemented</h4><p><strong><em>Continuous batching: </em></strong>The scheduler was built around mlx_lm’s BatchGenerator, which processes decoding one step at a time across active requests. New requests can join the batch while existing ones are still generating, allowing the system to keep the GPU continuously occupied under concurrent workloads.</p><p>One interesting observation from benchmarking was that continuous batching is not a free optimization. At low concurrency, the scheduling overhead actually reduced throughput compared to simpler wave-based generation. The benefits only became visible once concurrency increased enough to keep decoding slots consistently occupied.</p><p><strong><em>Paged KV management: </em></strong>A custom paged KV memory manager was implemented using fixed-size KV blocks, per-sequence block tables, and dynamic allocation during generation. This reproduced the scheduler-side behavior of PagedAttention, including fragmentation tracking and memory preemption.</p><p>An experimental gather-based KV path was later added to store KV tensors physically in paged layouts, effectively “paged allocation + gather, dense SDPA.” However, unlike real vLLM, attention still operated on reconstructed dense tensors rather than reading directly from paged memory through fused kernels. Building both versions made it clear that the real performance advantage of PagedAttention comes from the attention kernel itself, not just the block-table abstraction.</p><p><strong><em>Prefix caching: </em></strong>Prefix caching was implemented using a radix-tree KV cache with block-aligned sharing. Requests with common prompt prefixes reused previously computed KV states instead of recomputing them from scratch.</p><p>One subtle detail was that caching only occurred at fixed token boundaries, matching how real paged KV systems treat blocks as the fundamental unit of sharing.</p><p><strong><em>Chunked prefill: </em></strong>Chunked prefill was implemented by processing long prompts incrementally while carrying KV cache state across chunks. This allowed large prompts to be interleaved with active decoding workloads instead of monopolizing the scheduler during a single long prefill phase.</p><p><em>Full implementation details are available in the </em><a href="https://github.com/nandanadileep/vllm-like-llm-serving.git"><em>GitHub</em></a><em> repository.</em></p><p>With the core scheduling and KV-management components implemented, the next step was understanding how closely the system behaved compared to baseline inference and production vLLM serving.</p><h4>Benchmarking Against vLLM</h4><p>The implementation was benchmarked against:</p><ul><li>a CPU-only llama.cpp setup,</li><li>and production vLLM running Llama-3.2–1B-Instruct FP16 on a Colab T4 GPU.</li></ul><p>All systems were tested using the same prompts and concurrency levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivvOj1jXw-3M-d5KIzB-Ag.png" /></figure><blockquote>One important detail is that the latency measurements are not identical quantities. Local TTFT was measured internally from request arrival to first-token generation inside the scheduler, while the vLLM measurements include full end-to-end latency through an ngrok tunnel. Because of this, the absolute latency numbers should not be treated as a strict head-to-head comparison.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ca3gZTw2PYzvqkxyst0zbw.png" /><figcaption><em>Throughput scaling across CPU inference, the MLX-based near-vLLM stack, and production vLLM under increasing concurrency.</em></figcaption></figure><p>The latency trends told the same story. vLLM’s P50 latency remained nearly flat under increasing concurrency, while the local implementation degraded significantly once memory bandwidth became saturated. The scheduler itself continued behaving correctly under load, but the underlying hardware and kernel efficiency eventually became the limiting factors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnMdD0GbiRpqHJIZ68TyFg.png" /><figcaption>P50 latency under increasing concurrency. The MLX-based near-vLLM stack begins degrading once memory bandwidth becomes saturated, while vLLM maintains more stable latency under load.</figcaption></figure><p>The three systems showed very different scaling behavior under load.</p><p>The CPU-only llama.cpp baseline improved throughput gradually with concurrency, but latency remained extremely high because requests were effectively competing for limited compute resources without modern serving optimizations.</p><p>The MLX-based near-vLLM stack scaled significantly better, peaking around concurrency 4 before degrading as memory bandwidth became saturated on the M1 Air.</p><p>vLLM on the T4 GPU continued scaling much more consistently at higher concurrency levels due to fused attention kernels, significantly higher memory bandwidth, and production-grade GPU scheduling.</p><h4>Where the Hard Part Actually Is</h4><p>The benchmark results also made it clear where the largest remaining gap with production vLLM still exists.</p><p>The fused PagedAttention kernel is the one major component that was not implemented in this project, and it is also the part that matters most for high-throughput inference at scale.</p><p>While the scheduler and KV paging logic can be reproduced at the Python level, real PagedAttention requires the attention kernel itself to read directly from paged KV memory without reconstructing dense tensors during every decode step. That requires custom GPU kernels rather than scheduler-side abstractions alone.</p><p>In this implementation, paged KV tensors were reconstructed into dense views using mx.take before attention execution. The structure was correct, but the additional re-materialization overhead remained. Real vLLM avoids this cost entirely through fused CUDA kernels, while newer Apple Silicon efforts such as vllm-metal implement equivalent behavior using Metal kernels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftMyWMfIGVTDKxPymM5rBA.png" /><figcaption>Unsurprisingly, during testing the same model still produced different outputs across both servers for identical prompts. LLMs being LLMs, small differences in runtime execution and decoding behavior can still lead to divergent generations.</figcaption></figure><blockquote>While this project does not implement fused Metal attention kernels, the serving stack is fully usable for local MLX-based LLM inference experiments on Apple Silicon. The repository can be used as a lightweight playground for exploring continuous batching, KV-cache management, prefix caching, and scheduling behavior without requiring CUDA or custom GPU kernels.</blockquote><blockquote>Code, benchmark scripts, and experiment configurations are available in the <a href="https://github.com/nandanadileep/vllm-like-llm-serving">GitHub</a> repository.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65b0576ebd05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding Multi-Agent Orchestration in LangChain]]></title>
            <link>https://medium.com/@nandanadileep29/decoding-multi-agent-orchestration-in-langchain-ad6b46ed1058?source=rss-b36c4376690b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad6b46ed1058</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Nandana Dileep]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 18:56:33 GMT</pubDate>
            <atom:updated>2026-04-22T18:56:33.686Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Most multi-agent systems don’t fail because the models are weak.<br>They fail because the agents cannot reliably talk to each other.</em></p><p>Once you move from a single agent to multiple agents, you are no longer just prompting a model. You are designing a system. Messages have to be passed, state has to be shared, and every component needs to agree on what data looks like.<br>This is where most systems break.<br>LangChain approaches this problem not by making agents smarter, but by making communication stricter. To understand how multi-agent orchestration actually works, you need to look at the problems it is trying to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hh4eCEy-9zXElCE-CcEuA.png" /><figcaption>The Starry Night, Painting by Vincent van Gogh</figcaption></figure><h3><strong>Orchestration Patterns</strong></h3><p>Agents can be coordinated in a few common ways. In <strong>hierarchical</strong> orchestration, a supervisor breaks the goal into pieces and delegates each to a specialist. In <strong>sequential</strong> pipelines, agents hand off to each other one step at a time. In <strong>ensemble</strong>, multiple agents tackle the same problem independently and their outputs are compared. In <strong>shared state</strong>, all agents read from and write to a common context rather than calling each other directly.</p><p><strong><em>Patterns in LangChain,</em></strong></p><p>Hierarchical is the primary pattern. Each agent is a self-contained unit that can be plugged into a larger graph as a node. A supervisor routes between specialists, each unaware of the others. This keeps agents independently testable and the system easy to extend.<br>Shared state is not a pattern you choose, it is the default. All agents communicate through a single central state object carrying the full conversation history. Nothing passes values around explicitly. This makes the system inspectable at every step and eliminates hidden data flows.<br>Sequential is built into every agent’s internal loop. The model runs, tools execute, the model runs again, in that fixed order until there is nothing left to do. Reasoning has dependencies, and keeping the order explicit makes bugs easy to find.<br>Ensemble is only partially there. Tool calls issued by the model do run in parallel, which is ensemble at a small scale. But full ensemble, multiple agents producing independent answers that get reconciled, is not built in. Aggregation strategies are too application-specific, so the framework leaves that decision to the developer.</p><h3>Communication Layer Problems</h3><p>Once you have multiple agents, a new set of problems appears. How does one agent hand something off to another? What form does that handoff take? And what happens when one agent’s output does not quite match what the next agent expects?</p><p><em>The serialization problem</em></p><p>When agents communicate, anything they share has to cross a boundary. It gets saved, passed along, or sent as a message. Because of that, it must be in a format that can be written down and read back later.<br>LangChain uses structured message objects. Each message has a clear type and format, and the entire interaction is just a list of these messages. There is no hidden memory sharing. If something cannot be serialized, it cannot move between agents.</p><pre>{<br> &quot;type&quot;: &quot;ai&quot;,<br> &quot;id&quot;: &quot;msg-abc123&quot;,<br> &quot;content&quot;: &quot;The capital of France is Paris.&quot;,<br> &quot;tool_calls&quot;: [],<br> &quot;name&quot;: &quot;researcher-agent&quot;<br>}</pre><p><em>The structured communication problem</em></p><p>Plain text is too ambiguous for agents. If one agent sends a sentence and another needs specific fields, something has to extract and validate that data.<br>LangChain enforces structured output. Agents produce data that follows a predefined schema, and the system validates it before passing it forward. This removes guesswork and makes communication reliable.</p><pre><br>John’s application was approved yesterday and everything looks good<br><br>this will be converted to:<br>{<br> &quot;name&quot;: &quot;John&quot;,<br> &quot;date&quot;: &quot;2026–04–22&quot;,<br> &quot;status&quot;: &quot;approved&quot;<br>}</pre><h3>State and Context Problems</h3><p><em>The context transfer problem<br></em>Context is everything that has happened so far, not just the last message. Passing this between agents is difficult because it grows over time and models have limits.<br>LangChain treats the message list as the single source of truth. Every agent reads from the same shared history. The system may control how much each agent sees, but the format remains consistent. There is no translation between agents.</p><h3>Interface Problems</h3><p><em>The impedance mismatch problem<br></em>Agents often expect different data formats. One agent’s output may not match another agent’s input.<br>LangChain forces every agent to define its input and output schemas in advance. These schemas are checked and merged before the system runs. If they do not align, the system fails early instead of breaking during execution.</p><h3>Execution Problems</h3><p><em>Conflict Resolution<br></em>Multi-agent systems do not fail in one single way. Conflicts show up in different forms depending on where they happen, and each type is handled differently.</p><p>When multiple tools or agents try to update the same piece of <strong>state</strong> at the same time, the system applies strict rules. Some fields are appended to, like message history. Others follow a last-writer-wins approach, such as timestamps. Numeric values are accumulated, and nested structures are merged. If two updates are fundamentally incompatible, the system does not guess. It raises an error.</p><p>Conflicts can also happen earlier, at the <strong>decision stage.</strong> If the model generates parallel tool calls that would interfere with each other, the system catches this before execution. Instead of proceeding, it sends an error back into the conversation and asks the model to try again. The model is expected to self-correct.</p><p>Not all conflicts are treated as errors. When two agents or tools disagree on a <strong>fact</strong>, the system does not attempt to resolve it. Both results are stored in the shared message history, and the model sees them together. The responsibility of choosing what to trust is pushed back to the model.</p><p>There is a stricter boundary when it comes to <strong>output quality. </strong>If a model produces something that does not match the expected schema, it is rejected. The validation error is fed back, and the model must regenerate its response. This repeats a few times. If it still fails, the system stops. There is no partial acceptance.</p><p>Some conflicts are not allowed to reach execution at all. If schemas cannot be aligned or components expect incompatible data shapes, the system fails during setup. It does not attempt to resolve these issues at runtime.</p><p>Multi-agent systems are not just about adding more agents.<br>They are about designing how those agents communicate.<br>Most failure points come down to one thing: unclear contracts.<br>What data is passed, in what format, and who validates it.<br>I started exploring agent architectures to understand how real systems are built, and realized the hard part is not the model but everything around it. LangChain makes that painfully clear.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad6b46ed1058" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Beautiful Memory Architecture Inside LlamaIndex]]></title>
            <link>https://medium.com/@nandanadileep29/the-beautiful-memory-architecture-hidden-inside-llamaindex-eef91e01bc2c?source=rss-b36c4376690b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eef91e01bc2c</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llamaindex]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[context]]></category>
            <dc:creator><![CDATA[Nandana Dileep]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 18:06:39 GMT</pubDate>
            <atom:updated>2026-04-20T18:23:07.358Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A complete breakdown of all memory strategies and where the gaps are</em></p><blockquote>This article is about LlamaIndex OSS, the open source framework, not LlamaParse, their document parsing platform.</blockquote><p>You have a conversational agent. Around turn fifteen, it starts forgetting things. Around turn thirty, it contradicts itself. The instinct is to bump the context window from 16K to 128K. It helps for a while. Then the same degradation sets in, just later, at four times the compute cost.</p><p>The real problem was never window size. It was treating the context window as infinite scratch paper. There is a four-tier memory architecture sitting inside LlamaIndex that most developers never deliberately use: short-term, long-term, episodic, and procedural. Each tier has a job. Each one breaks in a specific way when ignored.</p><h3><strong>Short-Term Memory: The Active Queue</strong></h3><p>The failure mode here is subtle. A 128K context window is not 128K of reliable recall. Pretraining data is overwhelmingly short documents, so the model has learned, at the weight level, to weight early tokens more heavily. Modern LLMs also use Rotary Position Embeddings, where attention between two tokens decays as their relative distance increases. Recent tokens accumulate more attention mass by geometry, not by choice. The result, documented as “lost in the middle,” is that information buried in the center of a long context gets attended to far less than what’s at the start or end.</p><p>LlamaIndex’s approach is a FIFO queue with a hard token budget, 70% reserved for raw conversation history and 30% allocated to long-term memory blocks. When the queue fills past a flush threshold, the oldest messages waterfall down into long-term storage. Hard constraints and instructions go at the start of context to benefit from primacy bias. Retrieved episodic content goes immediately before the current message to benefit from recency bias.</p><p>The gap is importance scoring. Evicting by age sounds reasonable until a user correction from turn three flushes before a filler “sounds good” from turn forty. Any fixed heuristic fails on edge cases. LLM-based scoring would work but adds latency on every message. LlamaIndex leaves this unsolved, which means in a long conversation, the messages most worth keeping are exactly the ones most likely to disappear.</p><h3><strong>Long-Term Memory: The Vector Layer</strong></h3><p>The failure mode is that embeddings are lossy compression in ways that destroy meaning without warning. Negations are the clearest example. “Do not contact before 9am” and “contact before 9am” have surprisingly similar embeddings in many models. The word “not” does not reliably push a vector to a different region of the space. When rolling summarization compresses “do NOT send reminders before 9am,” it often produces “user has preferences about reminder timing” or worse, “user prefers morning reminders.” The negation is gone. The summary looks complete and readable. The constraint has been reversed.</p><p>LlamaIndex deals with this using a layered chunking and retrieval pipeline. For chunking, it supports strategies ranging from simple fixed-size splitting to topic boundary detection, where chunks end at actual semantic transitions rather than arbitrary token counts. The most precise approach indexes individual sentences for matching but stores surrounding sentences alongside each one, so the model reads context rather than just the matching fragment. On top of chunking, LlamaIndex implements HyDE: rather than embedding the query directly, it asks the model to write a hypothetical answer first and embeds that. A hypothetical answer already lives in the same part of the embedding space as real document content, closing the gap between how users write queries and how documents are written. The catch is that HyDE fails silently when the model’s hypothesis is wrong, it retrieves from a coherent but incorrect neighborhood, with high similarity scores and no signal that anything went wrong. A cross-encoder reranker paired with HyDE gives a second opinion that is far less vulnerable to a bad initial hypothesis.</p><p>The gap is structured extraction. LlamaIndex extracts facts from conversation before archiving them, which is better than storing raw text. But natural language facts are still lossy. A later extraction pass might rephrase a constraint. A summarization step might drop the negation entirely. A truly robust system needs typed schemas — where the NOT is a boolean field, the time is a structured value, and the constraint is a record that cannot be accidentally rephrased away. Without that, you are still trusting language to preserve meaning, which is exactly the failure mode you were trying to escape.</p><h3><strong>Episodic Memory: Conversation History Across Sessions</strong></h3><p>The failure mode is treating an append-only log as mutable state. Raw conversation history is a log: each entry is immutable, contradictions accumulate without resolution, and the model must reconstruct state on every inference call by reading all past turns and figuring out what is still current. This works for short histories. At scale, contradictions pile up and the model attends to both the original statement and its correction with roughly equal weight, producing unpredictable output.</p><p>LlamaIndex handles this with two complementary strategies. The first embeds flushed conversation turns for semantic retrieval, so when a new session starts, past exchanges relevant to the current topic get pulled back into context. This is how an agent can remember a project you worked on three weeks ago without carrying three weeks of raw history in every window. The second runs an extraction pass before archiving, pulling out discrete facts and updating them when new information contradicts old, pushing the system toward maintaining state rather than just accumulating log entries. What neither strategy handles automatically is tool result bloat. When a tool call returns two thousand tokens of raw JSON, that payload gets archived verbatim. By turn twenty in a tool-heavy agent, raw results can dominate the token budget.</p><p>The gap is the decision log pattern. LlamaIndex’s extraction strategies treat all information with roughly equal priority. But not all information ages the same way. A hard constraint like “under no circumstances contact clients on weekends” should be as fresh on turn two hundred as it was on turn two. The naive solution is to never flush these messages, but without a separate store you have no way to distinguish them from ordinary history. An importance classifier could tag them, but then you need the classifier to be reliable enough that a missed tag doesn’t silently drop a hard constraint. LlamaIndex does not implement this. You need a dedicated never-summarized store injected at the highest priority on every turn, and the logic to populate it is entirely yours to build.</p><h3><strong>Procedural Memory: How the Agent Knows How to Behave</strong></h3><p>The failure mode is invisible regression. You fine-tune for customer support tone and formatting. The model’s instruction-following on edge cases degrades by 12%. Your eval set covers customer support tasks. You ship the regression and never know it happened. Fine-tuning on any task degrades performance on adjacent tasks that share weight regions. This is not a risk. It is a statistical certainty.</p><p>LlamaIndex handles the in-context side with a static memory block: text that is always injected at a fixed position with a fixed priority, never evicted, never summarized. It is the right place for standing instructions and persona definitions. For weight-level adaptation, LlamaIndex defers entirely to external tooling. You train a LoRA adapter using something like HuggingFace PEFT or Unsloth and plug it in through the LLM integration layer. The framework has evaluation utilities for fine-tuned embedding models, but nothing for evaluating regressions in the LLM itself after fine-tuning.</p><p>The gap is a capability regression suite. Fine-tuning degrades adjacent capabilities in ways that are invisible unless you measure them. The problem is that “adjacent” is hard to define in advance, you discover which capabilities were affected after you ship, not before. A proper regression suite needs broad coverage across instruction following, refusal behavior, output formats, and tasks that share weight regions with your fine-tune objective. Without it, you are deploying blind.</p><p>There is now a map.</p><p>Short-term for what the model is actively working with.</p><p>Long-term for what needs to survive beyond a single session.</p><p>Episodic for what happened and when.</p><p>Procedural for how the agent is supposed to behave.</p><p>LlamaIndex builds the infrastructure for all four cleanly and deliberately. The gaps it leaves are not oversights, they are the boundary where the framework ends and your system begins. That part is for the users to build. That is also the interesting part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cp_myIPwKYZdNRsRhwDXfA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eef91e01bc2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Checklist to Prevent all the Agent Failure Modes.]]></title>
            <link>https://medium.com/@nandanadileep29/checklist-to-prevent-all-the-agent-failure-modes-f4dfdc7597e1?source=rss-b36c4376690b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4dfdc7597e1</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[guardrail]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nandana Dileep]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 05:02:27 GMT</pubDate>
            <atom:updated>2026-04-08T05:03:27.460Z</atom:updated>
            <content:encoded><![CDATA[<p><em>When your agent says it’s done, how do you know it actually is?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*snE0PuXS2ypp2hnmFhCUEg.jpeg" /><figcaption><em>René Magritte, The Philosopher’s Lamp, 1936. © Succession René Magritte / ADAGP, Paris</em></figcaption></figure><h4><strong>Hallucination Cascade</strong></h4><p><em>Did the agent lie about what it knew?</em></p><p>An agent fabricates a fact (eg: claims a tool returned data that it never actually called), then uses that fabrication as the basis for subsequent decisions. Each downstream action compounds the error, creating a chain reaction where wrong conclusions are built on false premises. The agent’s confidence remains high because it has no feedback signal that the initial assertion was unfounded.</p><blockquote>Every factual assertion the agent makes during reasoning must be traceable to a tool call and its result. Implement a verification layer that, before any action is taken on a claim, confirms a corresponding tool_use + tool_result pair exists in the trace. Claims with no tool backing should be flagged and blocked from influencing downstream decisions.</blockquote><h4><strong>Observability Black Hole</strong></h4><p><em>Did the agent fail to see what happened?</em></p><p>An agent performs an action (calls a tool, sends data, modifies state) but cannot observe whether the action succeeded or failed. The agent has no feedback loop no response, error message, or verification query so it proceeds based on assumption. It declares success without confirmation, or worse, repeats the same failed action multiple times because it has no signal that it’s failing.</p><blockquote>Pair every write tool with a mandatory verification tool call before the agent is allowed to proceed. Define explicit completion criteria for every task at the start of execution, and require the agent to check each criterion against tool results before it is allowed to give a final response.</blockquote><h4>Infinite Reasoning Loops</h4><p><em>Did the agent get stuck going nowhere?</em></p><p>An agent cycles through the same reasoning pattern, decision, or action repeatedly without progress or variation. It retries the same failed tool call identically, re-reads the same documentation looking for missed detail, or oscillates between two contradictory conclusions. Token count grows linearly while the agent makes no forward progress toward the goal.</p><blockquote>Implement loop detection at the executor level, not in the agent’s reasoning, the agent will not recognize it is stuck. Hash the last N action sequences at each step; if the same hash recurs within a sliding window, halt execution automatically and surface the loop to the user. Set hard token budgets and distinct tool call ceilings per task. The agent should never be given the option to continue indefinitely. For oscillation between contradictory conclusions specifically, introduce a forced commitment rule, after two visits to the same decision point with no new tool evidence, the agent must either call a new tool to break the tie or escalate to the user rather than re-reasoning over the same data.</blockquote><h4><strong>Tool Misuse / Boundary Violations</strong></h4><p><em>Did the agent act correctly?</em></p><p>An agent calls tools in the wrong order, with the wrong scope, or outside their intended boundaries. It may invoke a destructive tool (DELETE, OVERWRITE, SEND) when a read-only one was appropriate, pass unvalidated output from one tool directly as input to another, or call tools in a dependency order that violates the system’s assumptions.</p><p>For example, updating a record before confirming it exists, or sending a notification before the underlying action has committed.</p><blockquote>Define preconditions for every mutating tool and enforce them at the tool layer, not in the agent’s reasoning. Similarly, enforce strict input/output schemas at tool boundaries. Output from Tool A should be validated against Tool B’s expected input before the agent is permitted to pass it through.</blockquote><h4><strong>Goal Misalignment / Task Drift</strong></h4><p><em>Did the agent decide to solve the right problem?</em></p><p>An agent begins with the correct objective but gradually optimizes for a proxy goal instead, one that is easier to satisfy but not what was actually asked. It may complete all its tool calls without error, produce a confident final response, and still have solved the wrong problem. The drift is rarely sudden. It accumulates across steps as the agent reframes the task to fit the tools available, the data it found, or the path of least resistance. By the end, the trace looks healthy but the output is misaligned with the original intent.</p><blockquote>At task initialization, decompose the instruction into explicit sub-goals and store them as a checklist external to the agent’s context window. At each major decision point, evaluate the agent’s current trajectory against this checklist, not against its most recent reasoning, which may have drifted. Before the agent is permitted to emit a final response, require it to map its output to each sub-goal explicitly. Any sub-goal with no corresponding output should block completion and return the agent to the task, not allow it to declare success.</blockquote><h4><strong>Context Window Corruption / Memory Poisoning</strong></h4><p><em>Was the agent reasoning over bad input?</em></p><p>An agent’s decisions are only as good as the context it is reasoning over. As a long-running agent accumulates tool results, intermediate outputs, and conversation turns, its context window fills with information of varying reliability. Stale data sits alongside fresh data with no timestamp. A failed tool result that was never resolved remains in context and gets treated as valid. An early incorrect assumption, never corrected, gets re-read and reinforced with each new reasoning step. The agent isn’t hallucinating, it is faithfully reasoning over corrupted input.</p><blockquote>Treat context as a cache, not a source of truth. Every critical value the agent reads early, resource status, user data, config etc should have an expiry window. If more than N steps have passed since a fetch, re-fetch before acting on it. When a tool call returns an error or null, invalidate that result immediately, it should never enter reasoning as a valid observation. In multi-entity tasks, separate retrieved data by the entity it belongs to so data fetched for one resource cannot bleed into decisions about another. And any value the agent has re-read 2 or more times without a fresh tool call should trigger a forced re-verification before action.</blockquote><h4><strong>Premature Termination / False Completion</strong></h4><p><em>Did the agent actually finish the problem?</em></p><p>An agent declares the task complete before it actually is. It returns a confident final response, stops issuing tool calls, and hands control back to the user, but the goal has only been partially satisfied. This isn’t the agent lying about what it did. It genuinely believes it is done. The failure is in how it evaluates completion: it mistakes the absence of obvious next steps for the presence of a finished result, or it hits a soft signal (a successful tool call, a non-error response) and interprets that as task closure.</p><blockquote>Define completion criteria before the agent starts, not after it stops. At task initialization, decompose the instruction into explicit sub-goals and store them as a checklist external to the agent’s reasoning, not inside the context window where they can be quietly dropped. Pair every mutating action with a mandatory verification call: a GET after a CREATE, a test run after a code change, a read-back after a write. Before the agent emits a final response, require it to map its output to each sub-goal. Any sub-goal with no corresponding tool result blocks completion.</blockquote><h4><strong>Cascading Permission / Trust Escalation</strong></h4><p><em>Did the agent stay within the authority?</em></p><p>An agent begins with a defined scope of access and authority. Over the course of execution, it quietly expands that scope, not through explicit grants, but through inference. It reads a successful tool response as implicit permission to do more. It inherits credentials passed through one tool and uses them in another context they were never intended for.</p><blockquote>At the start of every task, declare an explicit permission manifest: which tools the agent may call, which resources it may read or write, and which domains it may cross into. This manifest should be enforced at the executor level, tool calls outside the manifest are rejected regardless of how the agent justified them. Credentials and identifiers extracted from tool results should not be automatically reusable in other tool calls.</blockquote><h4><strong>Instruction Injection / Prompt Hijacking</strong></h4><p><em>Did the external content take control?</em></p><p>An agent reads external content as part of its task: a webpage, a document, a database record, an email, and that content contains text designed to look like instructions. Its goal shifts without the user’s knowledge.</p><blockquote>The agent must operate with a hard architectural separation between its instruction context (system prompt, user input) and its data context (tool results, fetched documents, retrieved records). Content in the data context should never be parsed for instructions. Implement an input sanitization layer that strips or escapes instruction-like patterns from all external content before it enters the agent’s reasoning context.</blockquote><p>Agents fail quietly. They don’t crash with a stack trace, they produce confident output, clean traces, and completed tool calls, and still deliver the wrong result. None of the nine failure modes here require the agent to be broken. They require only that the agent has no mechanism to catch itself. The debugging order in this article starts with what the agent claimed to know, works outward to what it did, and ends with what it was allowed to do. Each layer assumes the ones above it have been cleared. The guardrails follow the same logic, they are not patches on individual failures, they are structural properties that make an entire class of failures impossible rather than merely unlikely. Build the checks in before the agent runs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4dfdc7597e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Takeaways from Leaked Claude Code Repo]]></title>
            <link>https://medium.com/@nandanadileep29/my-takeaways-from-leaked-claude-code-repo-3ec2f42b7545?source=rss-b36c4376690b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ec2f42b7545</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[anthropic-claude-code]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <dc:creator><![CDATA[Nandana Dileep]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 10:31:31 GMT</pubDate>
            <atom:updated>2026-04-02T11:10:54.807Z</atom:updated>
            <content:encoded><![CDATA[<p>I went through the leaked codebase to understand how this AI system is actually built.</p><p><strong>The .npmignore that appears to have shaken the community</strong></p><p>On March 31, 2026, a researcher noticed something odd inside a routine update to Anthropic’s Claude Code on npm. A 59.8 MB debug file that wasn’t supposed to be there, and inside it, the entire source code. 512,000 lines of TypeScript. 1,900 files. Every engineering decision Anthropic had made, sitting in plain sight.</p><p>The Claude Code runtime appears to use Bun, which generates sourcemap debug files by default. When publishing to npm, the sourcemap files were not excluded, effectively one missing line (*.map) in .npmignore which appears to have exposed everything.</p><p>Even though most coverage treated this as a scandal, I am going to look into the internal decisions and design patterns that make this AI system work.</p><p><strong>The 5 Layer Architecture</strong></p><p><strong>Layer 1 Entrypoints</strong><br>Claude Code can be accessed in multiple ways — through the terminal, VS Code, browser, desktop apps, or programmatically via an SDK. These are essentially different entry points into the same system. The code for these interfaces lives in src/entrypoints/, and they all eventually hand off control to a shared execution engine (e.g., launchRepl()).</p><p><strong>Layer 2 REPL, Hooks, and State</strong><br>At the core is a REPL (Read–Eval–Print Loop), which powers the interactive session. The CLI bootstraps through a large orchestration file (main.tsx), which parses input, initializes the environment, and starts the loop.</p><p>A hook system allows specific parts of the execution flow to be intercepted or modified, while shared state maintains context across the session.</p><p><strong>Layer 3 QueryEngine (Conversation Core)</strong><br>Each conversation is managed by its own QueryEngine. It maintains a single, centralized list of messages representing the entire conversation.</p><p>All new inputs go through a controlled interface (submitMessage()), and no other part of the system modifies this message list directly. This enforces a reliable “single source of truth” for the conversation state.</p><p><strong>Layer 4 Tools (Execution Layer)</strong><br>The system uses a collection of tools to perform real actions — such as running shell commands, reading and editing files, searching code, or spawning sub-agents.</p><p>This tool-based design is what allows the system to go beyond simple text generation and handle real engineering workflows.</p><p><strong>Layer 5 Services (Underlying Infrastructure)</strong><br>Beneath everything are supporting services like authentication, API communication, memory management, analytics, and integrations (e.g., language servers).</p><p>These components provide the necessary infrastructure but remain abstracted away from the higher-level logic.</p><blockquote>This architecture cleanly separates <strong>interfaces, execution, conversation state, capabilities, and infrastructure</strong>, which is why the system scales across multiple environments while staying consistent.</blockquote><p><strong>The Query Loop</strong></p><p>At the core is a simple loop that runs every time a message is sent:</p><p><strong>build prompt → call model → stream response</strong></p><p>If the model decides it needs a tool (read files, run commands, etc.), the system executes it, adds the result back into the conversation, and repeats the loop. This continues until the model decides it’s done.</p><p>This forms a <strong>think → act → observe loop (ReAct)</strong>, which is what turns it into an agent rather than just a chatbot.</p><p>The system uses async function*, so responses stream token by token as they’re generated.</p><p>This means no waiting for full responses, no callback complexity, and easy interruption.</p><p><strong>Context Management: Compaction</strong></p><p>To handle context limits, the system uses multiple strategies:</p><ul><li><strong>microCompact</strong> → trims large outputs per step</li><li><strong>apiMicrocompact</strong> → server-side trimming</li><li><strong>autoCompact</strong> → summarizes when context gets too large</li><li><strong>sessionMemoryCompact</strong> → smarter, memory-based compaction</li><li><strong>compact</strong> → manual full compression</li></ul><p>Instead of one solution, it uses <strong>layered compaction</strong> to stay within limits.</p><p>Compaction sometimes failed repeatedly, leading to thousands of wasted retries per session.</p><blockquote>The code comments tell the story directly: Around 1300 sessions were making up to 3000+ retries each, resulting in around 250,000 wasted API calls per day globally.</blockquote><p>Fix: after 3 consecutive failures, it stops trying. A simple <strong>circuit breaker</strong> that prevents runaway API usage.</p><p><strong>Memory Architecture (My Favorite Part)</strong></p><p><strong>How Claude “Dreams” to Remember</strong></p><p>Claude doesn’t store everything in real time. Instead, it uses a background system called <strong>autoDream</strong> to periodically process and organize memory.</p><p>autoDream runs only when certain conditions are met: enough time has passed (24 hours), enough activity has occurred (5+ sessions), and no other autoDream process is running. This gating ensures expensive operations only run when necessary.</p><p>When triggered, autoDream launches a separate background agent. This isn’t just a function call, it’s an independent Claude session that runs silently while the user continues working. It’s also restricted to read-only bash commands (ls, grep, cat), it can explore the system, but cannot modify it directly.</p><blockquote>AutoDream is not officially released yet. It is technically available. you just have to find it. Run /memory in any Claude Code session and look for the Auto-dream toggle. If it shows up, you can enable it right now.</blockquote><p><strong>The 4-Phase Memory Cycle</strong></p><p>The process follows a structured cycle:</p><ul><li><strong>Orient</strong> → scan existing memory and understand current state</li><li><strong>Gather</strong> → identify new or relevant information from recent activity</li><li><strong>Consolidate</strong> → merge updates, remove outdated or conflicting data</li><li><strong>Prune</strong> → keep memory compact, maintain a small index</li></ul><p>When it finishes, a quiet “Improved memory” note appears in the transcript showing which files were updated.</p><p><strong>Memory as a Hint, Not Truth</strong></p><p>Memory is treated as a hint, not a source of truth. The system explicitly verifies stored information against the actual codebase before trusting it. If a memory contradicts reality, it gets deleted, not preserved.</p><p><strong>Filesystem as State</strong></p><p>Instead of a traditional database, the system uses the filesystem itself. Memory is stored as files, with timestamps tracking when consolidation last happened, and a lock file preventing simultaneous runs. If a process crashes, the system detects a stale lock and safely recovers.</p><blockquote>This design avoids storing everything blindly. It batches, filters, and maintains memory over time, keeping it useful, compact, and reliable.</blockquote><p><strong>From Reactive to Proactive (Anthropic Roadmap)</strong></p><p>One of the more interesting signals in the codebase is a system referred to as <strong>KAIROS</strong>, which appears to be gated behind feature flags and not exposed to users.</p><p>While details are limited, it suggests a shift in direction.</p><p>Today, the system is reactive, it responds when you ask.</p><p>KAIROS hints at something different: a system that can run in the background, observe changes, and act within predefined boundaries without constant prompting.</p><p>Instead of repeatedly issuing commands, the user defines intent — and the system takes care of execution.</p><blockquote>It’s a move from “tools you use” to “systems that work for you.”</blockquote><p><strong>Anti-Distillation: Defensive Design</strong></p><p>In claude.ts, there appears to be a flag related to anti-distillation. When enabled, additional tool definitions may be injected into the system prompt.</p><p>One possible interpretation is that this makes it harder to infer real tool usage patterns purely from API traces.</p><blockquote>The system isn’t just designed to use tools — it’s designed to make that usage harder to replicate externally.</blockquote><p><strong>Prompt Caching: Where the Cost Actually Drops</strong></p><p>Every API call has a cost, but not every part of the prompt needs to be reprocessed each time.</p><p>The system is designed to <strong>separate what changes from what doesn’t</strong>.</p><ul><li>The <strong>stable parts</strong> (system prompt, tools, core instructions) stay identical</li><li>The <strong>variable part</strong> (latest message) is the only thing that changes</li></ul><p>Because of this, the stable portion gets <strong>cached</strong>, and only the new input is processed fresh.</p><p>What leaked was the <strong>source code around the model</strong>, not the model itself.</p><p>The exposure includes the scaffolding, how the system structures prompts, manages tools, and orchestrates agents. But the core components that make the model intelligent are absent.</p><p>The model weights, training data, and underlying research are not part of runtime code. They are never bundled into client-side artifacts like .map files.</p><blockquote>This wasn’t a model leak. It was a systems leak.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*xQfxJL8gpPNAAnmE7KwlAw.png" /><figcaption>this is a fun part</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ec2f42b7545" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to Prompt, RAG, or Fine-Tune]]></title>
            <link>https://medium.com/@nandanadileep29/when-to-prompt-rag-or-fine-tune-efdb4ba67a84?source=rss-b36c4376690b------2</link>
            <guid isPermaLink="false">https://medium.com/p/efdb4ba67a84</guid>
            <category><![CDATA[decision-making]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Nandana Dileep]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 17:33:05 GMT</pubDate>
            <atom:updated>2026-03-30T17:43:00.994Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Sounds basic but most people still get wrong in practice.</em></p><p>Every time you start a new LLM-powered project, you face the same fork in the road: do I prompt it, build a retrieval pipeline around it, or fine-tune a model? Pick wrong and you either waste weeks (or tokens hehe) over engineering something that a good system prompt could’ve handled, or you ship a brittle prompt-hack that falls apart the moment inputs get messy.</p><p>I am going to walk you through one project per approach; what the problem was, why I picked that approach, and what would’ve gone wrong if I’d picked differently.</p><p><strong>Prompt Engineering: AI Code Review Bot</strong></p><p>I built a GitHub App that automatically reviews pull requests. When someone opens or updates a PR, the bot grabs the diff, sends it to Llama3–8B via Groq, and posts a structured review comment right on the PR flagging bugs, security risks, and code quality issues.</p><p>I didn’t fine-tune anything. I didn’t build a vector store of past code reviews. I wrote a prompt.</p><p>Why? Because the model already knew how to read code and reason about it. Llama3–8B has seen enough code during pretraining that it can spot a missing null check or an exposed API key without me teaching it what those are. The gap wasn’t knowledge or behavior, it was direction. The model needed to know: what is the diff, what should you look for, and how should you structure the output.</p><p>That’s the core of prompt engineering, you’re not adding new capability to the model. You’re steering capability it already has. In my case, the prompt set the role (you’re a senior code reviewer), defined the scope (focus on bugs, security, readability), injected the context (the actual PR diff), and specified the output structure.</p><p>If I had gone the RAG route, I’d have been building a retrieval pipeline for no reason, the model didn’t need external knowledge to review a diff sitting right in the prompt. If I had fine-tuned, I’d have spent days curating code review examples and training a model to do something it could already do out of the box with the right instructions.</p><p><a href="https://github.com/nandanadileep/ai-code-review-bot"><em>Here’s the full project</em></a></p><p><strong>RAG: Chatting With Your Documents (Without LangChain)</strong></p><p>Next project, different problem. I built a document chat system from scratch, no LangChain, or any other framework. Upload your docs, ask questions in natural language, get answers grounded in the actual content. The stack: sliding window chunking, FAISS for vector search, and a React frontend.</p><p>This time, prompting alone wouldn’t cut it. Not because the model lacked the ability to answer questions, it’s great at that. The problem was that the model had never seen my documents. You can’t stuff a 200-page PDF into a prompt and call it a day. Context windows have limits, and even if they didn’t, throwing an entire document at a model and hoping it finds the right paragraph is wasteful and unreliable.</p><p>I deliberately skipped LangChain because I wanted to understand every layer of the RAG pipeline myself. When you hide behind abstractions, you lose the ability to debug, optimize, and explain what’s actually happening.</p><p>So the answer was retrieval. When a user asks a question, the system first searches for the most relevant chunks using vector similarity (FAISS), then feeds only those chunks into the prompt alongside the question. The model’s job isn’t to know the answer from training, it’s to synthesize an answer from the retrieved context.</p><p>This is what RAG solves: the model has the skill (reading comprehension, summarization, reasoning) but lacks the knowledge (your specific documents). Instead of baking that knowledge into the model through fine-tuning, which would be expensive, brittle, and outdated the moment the documents change, you retrieve it at inference time.</p><p><a href="https://github.com/nandanadileep/RAGS-without-lang-chain"><em>Here’s the full project</em></a></p><p><strong>Fine-Tuning: Teaching a Model to Play Chess</strong></p><p>Last one completely different problem. I fine-tuned Gemma3 on chess notation to predict valid moves and understand board states.</p><p>If you were gonna try prompting your way through this one, tell an LLM “given the moves e4 e5 Nf3 Nc6, predict the next move.” It might give you something plausible. It might also give you an illegal move and sound confident about it. LLMs don’t understand chess (at least smaller models like the one I am using<em>) </em>, they’ve seen chess games in their training but they haven’t <em>learned</em> the structure of the game. They’re pattern-matching on text, not reasoning about board state.</p><p>RAG doesn’t help either. There’s no document to retrieve. You’re not asking “what does Wikipedia say about the Sicilian Defense”, you’re asking the model to internalize the rules and patterns of chess deeply enough to predict what comes next in a sequence of algebraic notation. That’s not a knowledge retrieval problem. That’s a behavior problem.</p><p>So I fine-tuned. I trained Gemma3 on chess game data, sequences of moves with the task of predicting the next valid move. After training, the model didn’t need instructions or retrieved context. It had internalized the patterns of chess notation well enough to produce legal, strategically reasonable moves on its own.</p><p>This is the clearest signal for fine-tuning: when you need the model to develop a capability it fundamentally doesn’t have. Not knowledge it can look up. Not instructions you can write. An actual new behavior baked into the weights.</p><p>The tradeoff is real though. Fine-tuning costs compute, requires good training data, and the moment your target behavior changes, you retrain. I used LoRA (which freezes the base model and only trains a small set of adapter weights) to keep it manageable. But even with parameter-efficient methods, it’s still the heaviest tool in the box. That’s why it comes last in the decision tree, not first.</p><p><a href="https://github.com/nandanadileep/Chess-Gemma3-Finetuning"><em>Here’s the full projec</em><strong><em>t</em></strong></a></p><p>The tradeoffs show up quickly in production. Prompting is cheapest and fastest, but brittle when inputs shift. RAG adds latency and token cost due to retrieval and longer context, and it fails when the right chunks aren’t found. Fine-tuning reduces prompt complexity at inference, but costs upfront in data and training, and can overfit if your data is narrow. Each fails differently: prompts break silently, RAG misses context, fine-tuned models fail confidently. So the real decision isn’t just what works, it’s what fails in a way you can tolerate.</p><p><strong>So next time you start an LLM project, ask three questions in order:</strong></p><p>Does the model already know how to do this? → <strong>Prompt it.</strong></p><p>Does it know how but lacks specific knowledge? → <strong>RAG.</strong></p><p>Does it need to consistently behave differently than its base personality? → <strong>Fine-tune.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKRbEKYY7xjAWNhSrxJhYA.png" /></figure><p>In reality, you’ll probably use all three. These aren’t mutually exclusive. Production systems layer them, a fine-tuned base model, a RAG pipeline for live knowledge, and a well-crafted prompt holding it all together. The framework isn’t about picking one forever. It’s about knowing the <em>minimum</em> viable approach and layering up only when you need to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efdb4ba67a84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swapped Every Part of nanoGPT With Modern Alternatives. (Some Made It Worse)]]></title>
            <link>https://medium.com/@nandanadileep29/i-rebuilt-a-tiny-gpt-into-a-mini-deepseek-one-component-at-a-time-718d3e04cfb6?source=rss-b36c4376690b------2</link>
            <guid isPermaLink="false">https://medium.com/p/718d3e04cfb6</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Nandana Dileep]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 16:52:53 GMT</pubDate>
            <atom:updated>2026-03-25T19:38:37.428Z</atom:updated>
            <content:encoded><![CDATA[<h3>What happens when you swap in every modern LLM trick, piece by piece, and measure the results?</h3><p>So what actually makes modern LLMs better?</p><p>Not the vibes. Not the benchmarks. The actual mechanisms — the architectural choices that separate GPT-2 from LLaMA 3 from DeepSeek V3. I wanted to see each one, not just read about it in a paper.</p><p>So I took Andrej Karpathy’s nanoGPT, a beautifully minimal ~300-line GPT implementation and decided to work on it. One component at a time. Measuring loss after every cut.</p><p>By the end, I had built what I’m calling nanoLLaMA: a tiny model that stacks every quality-improving architecture trick from the last three years into a single, readable codebase. And I have the receipts.</p><p><strong>nanoGPT</strong></p><p>Karpathy’s nanoGPT is a thing of beauty. It’s a clean GPT-2 implementation you can read in an afternoon. Transformer blocks with LayerNorm, GELU activations, learned positional embeddings, standard multi-head attention.</p><p>I set up a fixed benchmark: a 4-layer, 4-head, 128-dimensional model trained on Shakespeare character-level data for 2000 iterations. Small enough to run on CPU in minutes. Same seed every time. Val loss = pure next-token cross-entropy.</p><p><strong>Baseline val loss: 1.6645</strong></p><p>Everything is measured against this.</p><p><strong>Cut 1: RMSNorm — The Easy Win</strong></p><p>LayerNorm computes a mean and variance, then re-centers and rescales. RMSNorm throws away the mean-centering and just divides by the root-mean-square. That’s it.</p><pre>class RMSNorm(nn.Module):<br>    def forward(self, x):<br>        rms = x.pow(2).mean(-1, keepdim=True).add(1e-6).rsqrt()<br>        return x * rms * self.weight</pre><p><strong>Result: 1.6589 (−0.006)<br></strong>Marginal improvement. The real gain is efficiency, fewer operations per forward pass.</p><p><strong>Cut 2: SwiGLU — Where Things Get Interesting</strong></p><p>The standard MLP in a transformer is: Linear → GELU → Linear. Two projections. SwiGLU uses three projections:</p><pre>gate = Linear(x)<br>up = Linear(x)<br>output = down(SiLU(gate) * up)</pre><p>The gate acts like a learned filter. Instead of just activating neurons, you’re learning which neurons even matter for a given input. The result is a more expressive MLP with the same parameter budget.<br>One gotcha: hidden dim. The standard MLP uses 4 × d_model. To keep params roughly equal with three projections, SwiGLU uses ⅔ × 4 × d_model. (And you need to round to a hardware-friendly multiple — I used 64, not 256, or you accidentally inflate params by 30%.)<br><strong>Result: 1.5897 (−0.075 from baseline)</strong></p><p><strong>Cut 3: RoPE — Giving the Model a Sense of Time</strong></p><p>Learned positional embeddings (like nanoGPT uses) have a problem: they memorize positions during training. Positions outside the training context length are a mystery.</p><p>Rotary Position Embeddings (RoPE) encode position geometrically, by rotating query and key vectors in 2D subspaces. The rotation angle is a function of position. Crucially, the relative angle between position 3 and position 7 is the same whether you’re near the start or deep into a long document.</p><pre>def apply_rotary_emb(x, cos, sin):<br>    return x * cos + rotate_half(x) * sin</pre><p>No extra parameters. No positional embedding table. Just a mathematical property baked into how Q and K interact.<br><strong>Result: 1.5641 (−0.100 from baseline)<br></strong>The largest single-component improvement. RoPE earns its spot in every modern architecture.</p><p><strong>Cut 4: Grouped Query Attention — Cheaper Inference</strong></p><p>Standard multi-head attention (MHA) has N query heads and N key-value heads. At inference, you cache all of them. For a 70B model, that KV cache can be tens of gigabytes.</p><p>GQA splits the difference: fewer KV heads, full Q heads. A group of query heads share one KV pair.</p><pre># Each KV head serves 2 query heads<br><br>n_head = 4 (query heads)<br>n_kv_head = 2 (key-value heads)</pre><p>Before attention, you expand K and V with repeat_interleave.<br><strong>Result: 1.6863 (+0.022)<br></strong>Slightly worse accuracy — each query head has less unique key/value information. But: 2× smaller KV cache. At 70B scale with long contexts, this is worth every point.</p><p><strong>Cut 5: Multi-Head Latent Attention — DeepSeek’s Secret Weapon</strong></p><p>GQA reduces KV heads. MLA does something more radical: it compresses K and V into a single low-dimensional latent vector.</p><pre>c_KV = kv_down(x)          # compress: [d] → [r], r &lt;&lt; d<br>K    = k_up(kv_norm(c_KV))<br>V    = v_up(kv_norm(c_KV))</pre><p>At inference, you only cache c_KV — not full K and V. Then you reconstruct K, V on the fly. DeepSeek V2/V3 uses this to get an 8× KV cache reduction vs standard MHA.</p><p><strong>Result: 1.8067 (+0.142)</strong></p><p>Worse than baseline on this tiny model, at this tiny scale. MLA’s compression ratio is aggressive for 128-dimensional embeddings — the bottleneck squeezes too hard. At scale (where kv_lora_rank is large relative to the compression benefit), it shines. This is an important lesson: <strong>not every technique works at every scale.</strong></p><p><strong>Cut 6: Mixture of Experts — Conditional Computation</strong></p><p>Dense LLMs activate every parameter for every token. MoE changes this: you have N independent MLPs (“experts”), and a router selects only the top-K for each token.</p><pre>router_logits = self.router(x)  # [B, T, n_experts]<br>topk_weights, topk_idx = router_logits.topk(top_k)</pre><p>With 4 experts and top-2 routing: every token uses 2 MLPs, but you have 4 to choose from. The model can specialize — different experts for syntax, semantics, rare words, common phrases. There’s a catch: experts can collapse. The router might learn to always pick the same 2 experts and ignore the rest.</p><p>The fix is an auxiliary load-balancing loss:</p><pre>L_aux =α × E × Σ(f_i × p_i)</pre><p>Where f_i is the fraction of tokens routed to expert i, and p_i is the average routing probability. This penalizes imbalance.</p><p><strong>Result: 1.6321 (−0.032 from baseline)</strong></p><p>Better than baseline with effectively the same compute per token. At scale, MoE lets you have a 400B parameter model with 40B active parameters. That’s the DeepSeek formula.</p><p><strong>Cut 7: Multi-Token Prediction — Denser Training Signal</strong></p><p>Standard language model training: predict the next token. MTP: predict the next N tokens simultaneously.</p><pre>for i, head in enumerate(self.mtp_heads):<br>    offset = i + 2  # predict t+2, t+3, ...<br>    aux_logits = head(x[:, :-offset])<br>    aux_loss += cross_entropy(aux_logits, targets[:, offset-1:])</pre><p>Same forward pass. Same inference (MTP heads are only active during training). But each training step is richer — the model must be consistent about multiple future positions, not just the immediate next token. Meta uses this in their latest research.</p><p><strong>Result: 1.6353 (−0.029 from baseline)</strong></p><p>The gain seems small in 2000 iterations. But at longer training runs,MTP is reported to accelerate convergence significantly. The model learns more from each token it sees.</p><p><strong>The Finale: All of It Together</strong></p><p>Stack them all: RMSNorm + SwiGLU + RoPE + MoE (4 experts, top-2) + MTP (4 heads).</p><pre><br>norm_type = ‘rmsnorm’<br>mlp_type = ‘swiglu’<br>pos_type = ‘rope’<br>n_experts = 4<br>moe_top_k = 2<br>mtp_depth = 4<br>mtp_loss_coeff = 0.3</pre><p><strong>Result: 1.5259 (−0.139 from baseline)<br></strong>And more importantly — it converges faster. The nanoLLaMA stack reached baseline’s final val loss (1.6645) by around step 500, while the baseline doesn’t get there until step 1500–2000.</p><p><strong>What I Learned</strong></p><p><strong>The quality winners:</strong> RoPE &gt; SwiGLU &gt; MoE &gt; MTP &gt; RMSNorm. If you only add one thing, add RoPE.</p><p><strong>The efficiency winners:</strong> GQA and MLA trade a little quality for massive KV cache savings. At scale, this trade is often worth it — the difference between a model that fits in GPU memory and one that doesn’t.</p><p><strong>MLA’s lesson:</strong> Low-rank compression only works when the compression ratio is reasonable. On a 128-dim toy model, you’re bottlenecking too aggressively. The idea is sound; the scale matters.</p><p><strong>A caveat on “synergy”:</strong> The combined improvement (0.139) is less than RoPE (0.100) + SwiGLU (0.075) alone (0.175). So these components aren’t magically amplifying each other — there’s overlap in what they improve. That said, the combined stack still outperforms any individual component, and the convergence speed improvement is real.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5_R6sNbnAt-Cr1B-v9es2w.png" /></figure><p>The full code is on GitHub <a href="https://github.com/nandanadileep/nanoLLaMA.git">here</a>. Every component is toggled by a single config flag. Every benchmark is reproducible. Fork it, break it, improve it.</p><p>Karpathy gave us the clearest possible baseline. This is what happens when you modernize it, one cut at a time.</p><p><em>Thanks for reading. If you found this useful, the code is all open — go run your own experiments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=718d3e04cfb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>