<?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 AISHWARYA P.S.V.S on Medium]]></title>
        <description><![CDATA[Stories by AISHWARYA P.S.V.S on Medium]]></description>
        <link>https://medium.com/@psvsaishwarya?source=rss-53307ac94e90------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RDgrK1XRbYJh1CTbqo82QA.jpeg</url>
            <title>Stories by AISHWARYA P.S.V.S on Medium</title>
            <link>https://medium.com/@psvsaishwarya?source=rss-53307ac94e90------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:04:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@psvsaishwarya/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[Who Verifies the Verifier?]]></title>
            <link>https://medium.com/@psvsaishwarya/who-verifies-the-verifier-bb77e8eea1b7?source=rss-53307ac94e90------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb77e8eea1b7</guid>
            <category><![CDATA[lms]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[qlora-fine-tuning]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[jevs]]></category>
            <dc:creator><![CDATA[AISHWARYA P.S.V.S]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 19:31:23 GMT</pubDate>
            <atom:updated>2026-10-02T19:31:23.594Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a Verifier-Guided RAG + SLM Learning Loop with QLoRA and Jev</h4><p>Most Retrieval-Augmented Generation systems end with a familiar architecture:</p><pre>User Question<br>     │<br>     ▼<br>Retriever<br>     │<br>     ▼<br>Relevant Context<br>     │<br>     ▼<br>LLM / SLM<br>     │<br>     ▼<br>Answer</pre><p>But I wanted to explore what happens <strong>after</strong> that.</p><p>What if the retriever finds the correct evidence, but the model still interprets it incorrectly?</p><p>What if a Small Language Model drops an important condition such as:</p><pre>only if</pre><p>or:</p><pre>unless</pre><p>What if we add a verifier?</p><p>And then an even more interesting question appears:</p><blockquote><strong><em>What if the verifier is also wrong?</em></strong></blockquote><p>That question became the most important part of this experiment.</p><p>I built an end-to-end system combining:</p><ul><li>ContractNLI</li><li>Qwen2.5–0.5B-Instruct</li><li>teacher-generated supervision</li><li>human ground-truth labels</li><li>Jev</li><li>QLoRA</li><li>Retrieval-Augmented Generation</li><li>claim-level verification</li><li>deterministic routing</li><li>held-out benchmarking</li><li>hard-example mining</li></ul><p>The objective was not to claim state-of-the-art performance.</p><p>The goal was to understand whether verification could become part of the <strong>training, inference, evaluation, and future learning loop</strong> of a small language model.</p><h3>The Core Problem</h3><p>Small Language Models are increasingly attractive because they can be:</p><ul><li>cheaper to run</li><li>easier to deploy locally</li><li>faster for constrained workloads</li><li>easier to fine-tune</li><li>practical on limited hardware</li></ul><p>But smaller models can also be less reliable.</p><p>A particularly dangerous class of errors happens when retrieval works correctly, but generation does not preserve the meaning of the retrieved evidence.</p><p>Consider this evidence:</p><pre>Opened headphones can be returned only if they are defective.</pre><p>Now imagine the model responds:</p><pre>Yes, you can return opened headphones.</pre><p>At first glance, this sounds reasonable.</p><p>But the model dropped the critical phrase:</p><pre>only if they are defective</pre><p>That tiny omission completely changes the policy.</p><p>The problem is therefore not always:</p><pre>Retriever failed</pre><p>Sometimes the problem is:</p><pre>Retriever succeeded<br>        │<br>        ▼<br>Correct evidence reached the model<br>        │<br>        ▼<br>Model interpreted it incorrectly</pre><p>This kind of failure matters in areas such as:</p><ul><li>contracts</li><li>finance</li><li>enterprise policy</li><li>compliance</li><li>legal workflows</li><li>customer support</li><li>healthcare systems</li></ul><p>So I wanted another layer between <strong>generation</strong> and the <strong>final answer</strong>.</p><p>That layer became Jev.</p><h3>Why I Chose Jev</h3><p>One of my design principles was to separate:</p><pre>Generation<br>    from<br>Judgment</pre><p>The student SLM is responsible for generating language.</p><p>Jev is responsible for making a focused decision.</p><p>Conceptually:</p><pre>┌───────────────────┐<br>        │ Retrieved Evidence│<br>        └─────────┬─────────┘<br>                  │<br>                  ▼<br>        ┌───────────────────┐<br>        │ Generated Claim   │<br>        └─────────┬─────────┘<br>                  │<br>                  ▼<br>        ┌───────────────────┐<br>        │        Jev        │<br>        └─────────┬─────────┘<br>                  │<br>       ┌──────────┼───────────┐<br>       │          │           │<br>       ▼          ▼           ▼<br> SUPPORTED   CONTRADICTED  INSUFFICIENT<br>       │          │           │<br>       ▼          ▼           ▼<br>    RETURN     ESCALATE   RETRIEVE MORE</pre><p>This produces a useful separation of responsibilities:</p><pre>SLM<br> │<br> └──► Generate</pre><pre>Jev<br> │<br> └──► Judge</pre><pre>Router<br> │<br> └──► Act</pre><p>The verifier is therefore not responsible for writing another long answer.</p><p>Its output becomes a machine-actionable decision.</p><h3>Where Jev Fits in the Architecture</h3><p>I used Jev in <strong>two different stages</strong>.</p><h3>Training-time verification</h3><pre>Teacher Prediction<br>        │<br>        ▼<br>Compare With Human Label<br>        │<br>        ▼<br>Jev Independently Checks<br>Original Context + Claim<br>        │<br>        ▼<br>Validated Training Example</pre><h3>Inference-time verification</h3><pre>Student Answer<br>      │<br>      ▼<br>Split Into Claims<br>      │<br>      ▼<br>Jev Checks Each Claim<br>Against Retrieved Evidence<br>      │<br>      ▼<br>Routing Decision</pre><p>This distinction is important.</p><p>Jev is:</p><pre>NOT the teacher<br>NOT the human label<br>NOT automatically ground truth</pre><p>It is an independent decision component.</p><p>That became extremely important later when I benchmarked the system.</p><h3>Full Architecture</h3><p>The system evolved into three connected loops:</p><ol><li>Training</li><li>Production</li><li>Improvement</li></ol><h3>End-to-End Architecture</h3><pre>TRAINING LOOP</pre><pre>              ┌────────────────────┐<br>              │    ContractNLI     │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │ Context + Claim    │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │    Teacher LLM     │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │ Verdict + Rationale│<br>              │ + Grounded Answer  │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │ Compare With Human │<br>              │ Ground-Truth Label │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │  Jev Verification  │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │ Validated Examples │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │       QLoRA        │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │   Student SLM v1   │<br>              └──────────┬─────────┘<br></pre><pre>                   PRODUCTION LOOP</pre><pre>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │   User Question    │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │   RAG Retrieval    │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │ Relevant Evidence  │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │ Student SLM Draft  │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │  Split Into Claims │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │ Jev Claim Checks   │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │ Aggregate Routing  │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │ Grounded Response  │<br>              └──────────┬─────────┘<br></pre><pre>                  IMPROVEMENT LOOP</pre><pre>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │   Failure Logs     │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │ Failure Validation │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │ Trusted Hard Cases │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │      QLoRA v2      │<br>              └──────────┬─────────┘<br>                         │<br>                         ▼<br>              ┌────────────────────┐<br>              │   Student SLM v2   │<br>              └────────────────────┘</pre><h3>Step 1: Starting With ContractNLI</h3><p>I used ContractNLI because its examples naturally contain the kind of reasoning I wanted to test.</p><p>Each example contains:</p><pre>Contract Context<br>      +<br>Claim<br>      +<br>Human Label</pre><p>The classification labels are:</p><pre>SUPPORTED<br>CONTRADICTED<br>INSUFFICIENT</pre><p>For example:</p><pre>Contract:<br>The agreement may be terminated with 30 days written notice.</pre><pre>Claim:<br>The agreement can be terminated without notice.</pre><p>Ground truth:</p><pre>CONTRADICTED</pre><p>The dataset contains many examples involving:</p><ul><li>conditions</li><li>obligations</li><li>exceptions</li><li>missing evidence</li><li>contradictions</li></ul><p>Exactly the sort of cases where a small model may incorrectly infer more than the evidence actually says.</p><h3>Step 2: The First Important Failure — Label Leakage</h3><p>One of the most useful lessons came from a mistake in my first implementation.</p><p>Initially, the human label accidentally appeared inside the teacher prompt.</p><p>That produced responses such as:</p><pre>The human label states SUPPORTED...</pre><p>The outputs looked reasonable.</p><p>But scientifically, this was wrong.</p><p>The teacher already knew the answer.</p><p>This is <strong>label leakage</strong>.</p><p>So I changed the architecture.</p><p>The teacher now sees only:</p><pre>Context<br>   +<br>Claim</pre><p>The human label remains hidden.</p><p>The teacher is required to independently generate:</p><pre>Verdict:<br>Rationale:<br>Grounded response:</pre><p>The flow changed from:</p><pre>Human Label<br>     │<br>     ▼<br>Teacher Sees Answer<br>     │<br>     ▼<br>Writes Explanation</pre><p>to:</p><pre>Context + Claim<br>      │<br>      ▼<br>Teacher Predicts Independently<br>      │<br>      ▼<br>Prediction Generated<br>      │<br>      ▼<br>Human Label Revealed<br>Only For Evaluation</pre><p>This was a crucial correction.</p><h3>Step 3: Teacher-Generated Supervision</h3><p>The teacher produces structured outputs such as:</p><pre>Verdict: SUPPORTED</pre><pre>Rationale:<br>The contract explicitly states that the recipient receives<br>no rights to the confidential information.</pre><pre>Grounded response:<br>The agreement grants the recipient no rights to the<br>confidential information.</pre><p>This response becomes potential supervision for the student.</p><p>This is not logit-based distillation.</p><p>The experiment uses something closer to:</p><pre>Teacher Response Generation<br>          │<br>          ▼<br>Validated Sequence Targets<br>          │<br>          ▼<br>Supervised QLoRA Fine-Tuning</pre><p>So the student learns from:</p><ul><li>verdict format</li><li>rationale structure</li><li>grounded responses</li></ul><h3>Step 4: Why Teacher Outputs Needed Verification</h3><p>Synthetic supervision can contain errors.</p><p>If the teacher generates the wrong answer and I train the student on it, the error simply moves from one model to another.</p><p>So I added multiple signals.</p><pre>Context + Claim<br>                     /          \<br>                    /            \<br>                   ▼              ▼<br>          ┌──────────────┐ ┌──────────────┐<br>          │   Teacher    │ │     Jev      │<br>          └──────┬───────┘ └──────┬───────┘<br>                 │                │<br>                 ▼                ▼<br>          Teacher Verdict     Jev Verdict<br>                 \                /<br>                  \              /<br>                   ▼            ▼<br>                  Human Ground Truth</pre><p>I now had three pieces of information:</p><pre>1. Human Label<br>2. Teacher Verdict<br>3. Jev Verdict</pre><p>The goal was to prevent obviously unreliable examples from entering the student training set.</p><h3>Step 5: What Happened on the First 20 Examples?</h3><p>I ran an initial smoke test on 20 examples.</p><p>The result:</p><pre>Generated: 20</pre><pre>Accepted:  10<br>Rejected:  10</pre><p>A frequent failure looked like:</p><pre>Teacher: SUPPORTED<br>Human:   INSUFFICIENT</pre><p>The tiny teacher tended to infer support even when the contract did not explicitly establish the claim.</p><p>That was already an interesting observation.</p><p>It reinforced one important principle:</p><blockquote><strong><em>Synthetic data should not automatically be trusted.</em></strong></blockquote><h3>Step 6: QLoRA Distillation</h3><p>For the student, I used:</p><pre>Qwen/Qwen2.5-0.5B-Instruct</pre><p>The setup was:</p><pre>Base Model<br>   │<br>   ▼<br>4-bit Quantization<br>   │<br>   +<br>   │<br>LoRA Adapters<br>   │<br>   +<br>   │<br>Validated Training Data<br>   │<br>   ▼<br>QLoRA Training</pre><p>The smoke-test training used:</p><pre>10 validated examples<br>3 epochs<br>9 optimization steps</pre><p>The resulting adapter was saved as:</p><pre>artifacts/student-qlora-v1</pre><p>The reported final training loss was approximately:</p><pre>2.19</pre><p>This result did <strong>not</strong> prove that the student had become generally better.</p><p>Ten examples are far too few for that.</p><p>At this point, the goal was simply:</p><pre>Can the full pipeline train successfully?</pre><p>The answer was yes.</p><h3>Step 7: Connecting the Student to RAG</h3><p>The student was then placed inside a RAG pipeline.</p><pre>User Question<br>      │<br>      ▼<br>┌──────────────────┐<br>│    Retriever     │<br>└────────┬─────────┘<br>         │<br>         ▼<br>┌──────────────────┐<br>│ Relevant Evidence│<br>└────────┬─────────┘<br>         │<br>         ▼<br>┌──────────────────┐<br>│ Distilled SLM v1 │<br>└────────┬─────────┘<br>         │<br>         ▼<br>┌──────────────────┐<br>│   Draft Answer   │<br>└──────────────────┘</pre><p>This is where the experiment became much more interesting.</p><h3>The Headphones Example</h3><p>I tested the system with:</p><pre>Question:<br>Can I return opened headphones?</pre><p>The retriever returned:</p><pre>Opened headphones can be returned only if they are defective.</pre><p>So retrieval had succeeded.</p><p>But the SLM produced an answer effectively saying:</p><pre>Yes, you can return opened headphones.</pre><p>It also suggested that there was no specific condition.</p><p>But the evidence clearly said:</p><pre>only if they are defective</pre><p>The model had removed the condition.</p><p>This created a very useful diagnosis:</p><pre>Retriever<br>    │<br>    ▼<br>Correct Evidence<br>    │<br>    │ ✅<br>    ▼<br>Student SLM<br>    │<br>    ▼<br>Condition Dropped<br>    │<br>    │ ❌<br>    ▼<br>Incorrect Interpretation</pre><p>The problem was not retrieval.</p><p>It was generation.</p><h3>Step 8: Jev Caught the Hallucination</h3><p>Rather than returning the entire draft directly to the user, I split it into individual claims.</p><pre>Student Draft<br>                      │<br>          ┌───────────┼───────────┐<br>          │           │           │<br>          ▼           ▼           ▼<br>       Claim 1     Claim 2     Claim 3<br>          │           │           │<br>          ▼           ▼           ▼<br>         Jev         Jev         Jev</pre><p>For the claim:</p><pre>Yes, you can return opened headphones.</pre><p>Jev returned:</p><pre>CONTRADICTED</pre><p>Other generated claims were classified as:</p><pre>CONTRADICTED</pre><p>or:</p><pre>INSUFFICIENT</pre><p>So in this concrete example:</p><blockquote><strong><em>Jev successfully caught the SLM’s unsupported interpretation.</em></strong></blockquote><p>The complete failure-detection flow looked like this:</p><pre>┌─────────────────────────────────────────┐<br>│ Evidence                                │<br>│                                         │<br>│ &quot;Opened headphones can be returned     │<br>│  only if they are defective.&quot;          │<br>└───────────────────┬─────────────────────┘<br>                    │<br>                    ▼<br>          ┌──────────────────┐<br>          │ Student SLM      │<br>          └────────┬─────────┘<br>                   │<br>                   ▼<br>┌─────────────────────────────────────────┐<br>│ Generated Claim                         │<br>│                                         │<br>│ &quot;Yes, you can return opened headphones.&quot;│<br>└───────────────────┬─────────────────────┘<br>                    │<br>                    ▼<br>             ┌─────────────┐<br>             │     Jev     │<br>             └──────┬──────┘<br>                    │<br>                    ▼<br>             CONTRADICTED<br>                    │<br>                    ▼<br>                ESCALATE<br>                    │<br>                    ▼<br>┌─────────────────────────────────────────┐<br>│ Grounded Response                       │<br>│                                         │<br>│ Opened headphones can be returned       │<br>│ only if they are defective.             │<br>└─────────────────────────────────────────┘</pre><p>This was one of the strongest moments in the project.</p><p>The SLM made a semantic error.</p><p>Jev caught it.</p><p>And the bad draft was not returned as the final answer.</p><h3>Step 9: Claim-Level Routing</h3><p>The verifier itself is not the final product.</p><p>Its decisions need to affect application behavior.</p><p>The basic router became:</p><pre>Jev Verdict<br>                        │<br>        ┌───────────────┼────────────────┐<br>        │               │                │<br>        ▼               ▼                ▼<br>   SUPPORTED       CONTRADICTED      INSUFFICIENT<br>        │               │                │<br>        ▼               ▼                ▼<br>     RETURN          ESCALATE        RETRIEVE MORE</pre><p>This is one of the reasons I found the verifier useful.</p><p>Its result could directly control normal application code.</p><h3>Step 10: Why Aggregation Was Necessary</h3><p>Initially, every claim produced an independent action.</p><p>For example:</p><pre>Claim 1 → ESCALATE<br>Claim 2 → ESCALATE<br>Claim 3 → RETRIEVE<br>Claim 4 → ESCALATE<br>Claim 5 → RETRIEVE</pre><p>That was useful for debugging.</p><p>But it was not a good user experience.</p><p>So I added an aggregate routing rule:</p><pre>ESCALATE<br>   &gt;<br>RETRIEVE<br>   &gt;<br>RETURN</pre><p>Conceptually:</p><pre>Claim-Level Decisions</pre><pre>       ESCALATE<br>       ESCALATE<br>       RETRIEVE<br>       ESCALATE<br>       RETRIEVE<br>           │<br>           ▼<br>   ┌──────────────────┐<br>   │ Aggregate Router │<br>   └────────┬─────────┘<br>            │<br>            ▼<br>         ESCALATE<br>            │<br>            ▼<br>   One Final Grounded<br>        Response</pre><p>For the headphones example:</p><pre>RETURN:    0<br>RETRIEVE:  1<br>ESCALATE:  5</pre><p>The final answer became:</p><pre>Based on the retrieved evidence:<br>Opened headphones can be returned only if they are defective.</pre><h3>At This Point, the System Looked Successful</h3><p>I had a nice story:</p><pre>Correct Evidence<br>      │<br>      ▼<br>SLM Drops Condition<br>      │<br>      ▼<br>Jev Detects Contradiction<br>      │<br>      ▼<br>Router Blocks Draft<br>      │<br>      ▼<br>Grounded Answer Returned</pre><p>It would have been easy to stop here and say:</p><blockquote><em>“Adding a verifier solved the hallucination problem.”</em></blockquote><p>But one successful example does not prove that.</p><p>So I benchmarked the system.</p><p>That changed the story.</p><h3>Step 11: Held-Out Evaluation</h3><p>I created another 20 ContractNLI examples that did not overlap with the original smoke-test rows.</p><p>Then I compared:</p><pre>┌──────────────────────────────┐<br>│        Held-Out Data         │<br>└──────────────┬───────────────┘<br>               │<br>     ┌─────────┼──────────┐<br>     │         │          │<br>     ▼         ▼          ▼<br> Base SLM   SLM v1   SLM v1 + Jev</pre><p>A future experiment will also include:</p><pre>Hard-example-trained SLM v2</pre><h3>Benchmark Results</h3><p>The results were:</p><p>SystemAccuracyMacro-F1Base SLM20%0.148Distilled SLM v120%0.142</p><p>This result immediately showed:</p><blockquote><strong><em>The first QLoRA run did not improve held-out classification accuracy.</em></strong></blockquote><p>That is not surprising.</p><p>The student had only 10 validated training examples.</p><p>The fine-tuning run was a smoke test.</p><p>But the important point is that I now had <strong>measured evidence</strong>.</p><h3>Step 12: Evaluating the Jev Gate</h3><p>The Jev-gated version produced:</p><pre>Total Examples: 20</pre><pre>Returned:        6<br>Escalated:      14</pre><pre>Coverage:       30%</pre><p>Of the six predictions the system allowed through:</p><pre>Correct Returned:   2<br>Incorrect Returned: 4</pre><p>Therefore:</p><pre>Accepted Accuracy:<br>33.3%</pre><pre>False Acceptance Rate:<br>66.7%</pre><p>Visualizing that:</p><pre>20 Held-Out Cases<br>                        │<br>                        ▼<br>              ┌─────────────────┐<br>              │ SLM + Jev Gate  │<br>              └────────┬────────┘<br>                       │<br>          ┌────────────┴────────────┐<br>          │                         │<br>          ▼                         ▼<br>     6 Returned                14 Escalated<br>          │<br>      ┌───┴────┐<br>      │        │<br>      ▼        ▼<br>   2 Correct  4 Wrong</pre><p>That changed my interpretation of the architecture.</p><h3>Who Verifies the Verifier?</h3><p>Originally, I assumed:</p><pre>Student Prediction<br>      +<br>Jev Prediction<br>      │<br>      ▼<br>Both Agree<br>      │<br>      ▼<br>Probably Safe</pre><p>The benchmark showed that this assumption was too strong.</p><p>Sometimes:</p><pre>Student<br>   │<br>   └──► Wrong</pre><pre>Jev<br>   │<br>   └──► Same Wrong Decision</pre><p>The two systems could agree and still be wrong.</p><p>That became the central lesson of the project.</p><p>A simplistic architecture is:</p><pre>Generator<br>    │<br>    ▼<br>Verifier<br>    │<br>    ▼<br>Truth</pre><p>A more realistic architecture is:</p><pre>Generator<br>    │<br>    ▼<br>Verifier<br>    │<br>    ▼<br>Verifier Evaluation<br>    │<br>    ▼<br>Calibration<br>    │<br>    ▼<br>Routing Policy<br>    │<br>    ▼<br>Final Action</pre><p>A verifier is another model component.</p><p>It also needs:</p><ul><li>benchmarking</li><li>calibration</li><li>monitoring</li><li>error analysis</li><li>stress testing</li></ul><h3>Did Jev Help?</h3><p>Yes.</p><p>But the answer is more nuanced than:</p><pre>Jev = always correct</pre><p>Jev helped in four important ways.</p><h3>1. It caught a real hallucination</h3><p>The headphones example clearly showed a case where the SLM dropped a critical condition and Jev marked the resulting claim as contradicted.</p><h3>2. It exposed uncertainty</h3><p>On the held-out benchmark:</p><pre>70% of examples were escalated</pre><p>instead of being blindly returned.</p><p>That itself is useful information.</p><h3>3. It provided structured actions</h3><pre>SUPPORTED<br>→ RETURN</pre><pre>CONTRADICTED<br>→ ESCALATE</pre><pre>INSUFFICIENT<br>→ RETRIEVE MORE</pre><h3>4. It made the pipeline observable</h3><p>Without a verifier:</p><pre>Model<br>  │<br>  ▼<br>Answer<br>  │<br>  ▼<br>User</pre><p>With a verifier:</p><pre>Model<br>  │<br>  ▼<br>Claim<br>  │<br>  ▼<br>Verifier<br>  │<br>  ▼<br>Decision<br>  │<br>  ▼<br>Router<br>  │<br>  ▼<br>Logs + Metrics<br>  │<br>  ▼<br>Final Response</pre><p>That gives the system measurable internal behavior.</p><h3>Why I Did Not Immediately Train SLM v2</h3><p>My original idea was:</p><pre>SLM v1<br>  │<br>  ▼<br>Jev Finds Failure<br>  │<br>  ▼<br>Save Failure<br>  │<br>  ▼<br>QLoRA<br>  │<br>  ▼<br>SLM v2</pre><p>But the benchmark revealed a risk.</p><p>If the verifier itself can be wrong:</p><pre>Incorrect Jev Decision<br>        │<br>        ▼<br>Incorrect Hard Example<br>        │<br>        ▼<br>QLoRA<br>        │<br>        ▼<br>Student Learns<br>Incorrect Behavior</pre><p>That would turn verification errors into training errors.</p><p>So the improvement loop needs another validation step.</p><h3>A Safer Hard-Example Loop</h3><p>The updated design is:</p><pre>Student Failure<br>                       │<br>                       ▼<br>                 Jev Signal<br>                       │<br>                       ▼<br>             ┌─────────────────┐<br>             │ Validate Failure│<br>             └────────┬────────┘<br>                      │<br>         ┌────────────┼────────────┐<br>         │            │            │<br>         ▼            ▼            ▼<br>    Human Label   Trusted LLM   Rule Check<br>         │            │            │<br>         └────────────┼────────────┘<br>                      │<br>                      ▼<br>              Corrected Target<br>                      │<br>                      ▼<br>              Trusted Hard Example<br>                      │<br>                      ▼<br>                  QLoRA v2</pre><p>This is a much safer self-improvement mechanism.</p><h3>Error Taxonomy</h3><p>Not every failure should become a training example.</p><p>So I want to classify failures into categories such as:</p><pre>Dropped Condition<br>Missed Negation<br>Incorrect Exception<br>Unsupported Assumption<br>Wrong Entity<br>Wrong Date<br>Wrong Amount<br>Retrieval Failure<br>Verifier Disagreement</pre><p>Why?</p><p>Because different problems require different fixes.</p><p>For example:</p><pre>Retrieval Failed<br>      │<br>      ▼<br>Better Chunking<br>Better Embeddings<br>Query Rewriting<br>Reranking</pre><p>But:</p><pre>Correct Evidence Retrieved<br>          +<br>Student Dropped &quot;only if&quot;<br>          │<br>          ▼<br>Good Fine-Tuning Candidate</pre><p>This distinction matters.</p><h3>Condition Preservation</h3><p>The headphones example highlighted a particularly important family of expressions:</p><pre>only if<br>unless<br>except<br>provided that<br>subject to<br>within 30 days<br>not permitted unless</pre><p>These words often carry more meaning than the rest of the sentence.</p><p>For example:</p><pre>Refund allowed only if defective.</pre><p>is very different from:</p><pre>Refund allowed.</pre><p>So one metric I want to add is:</p><blockquote><strong><em>Condition Preservation Accuracy</em></strong></blockquote><p>Example test cases:</p><pre>Refund allowed only if defective.</pre><pre>Cancellation allowed unless processing has started.</pre><pre>Access permitted except for external contractors.</pre><pre>Disclosure permitted provided that written approval exists.</pre><p>This kind of metric may be particularly useful for enterprise and policy applications.</p><h3>Adaptive Retrieval</h3><p>Verification can also improve retrieval.</p><p>Instead of:</p><pre>Retrieve Top-3<br>     │<br>     ▼<br>Generate<br>     │<br>     ▼<br>INSUFFICIENT<br>     │<br>     ▼<br>Stop</pre><p>the system can do:</p><pre>Retrieve Top-3<br>     │<br>     ▼<br>Generate<br>     │<br>     ▼<br>Jev: INSUFFICIENT<br>     │<br>     ▼<br>Retrieve More<br>     │<br>     ▼<br>Top-8<br>     │<br>     ▼<br>Rerank<br>     │<br>     ▼<br>Generate Again</pre><p>Now verification becomes part of an active control loop.</p><h3>Query Decomposition</h3><p>Complex questions can also be decomposed.</p><pre>Complex Question<br>                    │<br>                    ▼<br>            ┌──────────────┐<br>            │  Decomposer  │<br>            └──────┬───────┘<br>                   │<br>      ┌────────────┼────────────┐<br>      │            │            │<br>      ▼            ▼            ▼<br>Sub-question 1 Sub-question 2 Sub-question 3<br>      │            │            │<br>      ▼            ▼            ▼<br>   Retrieve      Retrieve      Retrieve<br>      │            │            │<br>      └────────────┼────────────┘<br>                   │<br>                   ▼<br>             Merge Evidence<br>                   │<br>                   ▼<br>                Generate</pre><p>This can improve evidence coverage before the student even begins generation.</p><h3>Structured Student Output</h3><p>Another improvement would be to make the student produce structured results.</p><p>Instead of:</p><pre>Opened headphones can be returned...</pre><p>the student could return:</p><pre>{<br>  &quot;verdict&quot;: &quot;INSUFFICIENT&quot;,<br>  &quot;conditions&quot;: [<br>    &quot;Return is allowed only if defective&quot;<br>  ],<br>  &quot;answer&quot;: &quot;Opened headphones can be returned only if they are defective.&quot;<br>}</pre><p>Then I can evaluate independently:</p><pre>Verdict Accuracy</pre><pre>Condition Preservation</pre><pre>Final Answer Groundedness</pre><h3>Confidence Calibration</h3><p>A verifier confidence score should not automatically be interpreted as:</p><pre>Probability that this answer is correct</pre><p>Instead, confidence needs calibration.</p><p>For example:</p><pre>0.9–1.0 confidence<br>      │<br>      ▼<br>How often actually correct?</pre><pre>0.8–0.9 confidence<br>      │<br>      ▼<br>How often actually correct?</pre><pre>0.7–0.8 confidence<br>      │<br>      ▼<br>How often actually correct?</pre><p>Possible methods include:</p><pre>Reliability Diagrams</pre><pre>Expected Calibration Error</pre><pre>Platt Scaling</pre><pre>Isotonic Regression</pre><p>Only then should confidence thresholds control important production decisions.</p><h3>Multi-Verifier Architecture</h3><p>Another possible extension is to avoid trusting one verifier.</p><pre>Claim<br>                           │<br>             ┌─────────────┼─────────────┐<br>             │             │             │<br>             ▼             ▼             ▼<br>            Jev        NLI Model     Rule Engine<br>             │             │             │<br>             └─────────────┼─────────────┘<br>                           │<br>                           ▼<br>                  Decision Aggregator<br>                           │<br>                  ┌────────┴─────────┐<br>                  │                  │<br>                  ▼                  ▼<br>               RETURN            ESCALATE</pre><p>For example:</p><pre>Jev:<br>SUPPORTED</pre><pre>NLI:<br>CONTRADICTED</pre><pre>Result:<br>ESCALATE</pre><p>The idea is not to stack models endlessly.</p><p>The goal is to see whether independent verification signals can meaningfully reduce false acceptance.</p><h3>Future SLM v2</h3><p>Once I have trustworthy hard examples, the next training stage becomes:</p><pre>Clean Validated Data<br>                   │<br>                   │<br>                   +<br>                   │<br>           Trusted Hard Cases<br>                   │<br>                   ▼<br>             Mixed Dataset<br>                   │<br>                   ▼<br>                 QLoRA<br>                   │<br>                   ▼<br>              Student v2</pre><p>Then I can run the full comparison:</p><pre>Held-Out Dataset<br>       │<br>       ├──► Base SLM<br>       │<br>       ├──► Distilled SLM v1<br>       │<br>       ├──► Distilled SLM v1 + Jev<br>       │<br>       └──► Hard-Example SLM v2</pre><p>Metrics should include:</p><pre>Accuracy</pre><pre>Macro-F1</pre><pre>Precision</pre><pre>Recall</pre><pre>Coverage</pre><pre>Escalation Rate</pre><pre>False Acceptance Rate</pre><pre>Condition Preservation</pre><pre>Latency</pre><pre>Verifier Agreement</pre><p>Only then can I make a stronger claim about model improvement.</p><h3>Champion vs Challenger</h3><p>A production system should not automatically deploy the newest adapter.</p><p>Instead:</p><pre>┌─────────────────┐<br>│ Student SLM v1  │<br>│    Champion     │<br>└────────┬────────┘<br>         │<br>         │ compare<br>         │<br>┌────────▼────────┐<br>│ Student SLM v2  │<br>│   Challenger    │<br>└─────────────────┘</pre><p>Promote v2 only if:</p><pre>Accuracy improves<br>        AND</pre><pre>False acceptance decreases<br>        AND</pre><pre>Latency stays acceptable</pre><p>Otherwise:</p><pre>Keep v1</pre><p>Training completion is not the same thing as production readiness.</p><h3>How Is This Different From Typical Jev + RAG Work?</h3><p>A common Jev + RAG architecture looks like:</p><pre>Query<br>  │<br>  ▼<br>Retriever<br>  │<br>  ▼<br>Many Chunks<br>  │<br>  ▼<br>Jev Reranking / Filtering<br>  │<br>  ▼<br>Best Chunks<br>  │<br>  ▼<br>LLM<br>  │<br>  ▼<br>Answer</pre><p>That is a useful use case.</p><p>Jev can also be used for:</p><pre>Classification</pre><pre>Routing</pre><pre>Relevance Scoring</pre><pre>Citation Checking</pre><pre>Document Filtering</pre><pre>Structured Decisions</pre><p>My experiment explores a broader lifecycle.</p><pre>TRAINING<br>                        │<br>                        ▼<br>Human Ground Truth<br>        │<br>        ▼<br>Teacher<br>        │<br>        ▼<br>Jev Validation<br>        │<br>        ▼<br>QLoRA Student<br>        │<br>        │<br>        ▼</pre><pre>                    PRODUCTION<br>                        │<br>                        ▼<br>RAG<br> │<br> ▼<br>Student Generation<br> │<br> ▼<br>Claim-Level Jev Verification<br> │<br> ▼<br>Routing<br> │<br> ▼<br>Grounded Response<br> │<br> │<br> ▼</pre><pre>                    EVALUATION<br>                        │<br>                        ▼<br>Held-Out Benchmark<br> │<br> ▼<br>Verifier Failure Analysis<br> │<br> ▼<br>Trusted Hard Examples<br> │<br> ▼<br>Future SLM v2</pre><p>The differentiator is not simply:</p><pre>&quot;I used Jev.&quot;</pre><p>It is the integration of:</p><pre>Distillation<br>      +<br>Verification<br>      +<br>RAG<br>      +<br>Routing<br>      +<br>Benchmarking<br>      +<br>Failure Analysis<br>      +<br>Future Retraining</pre><p>into one experiment.</p><h3>What Surprised Me Most</h3><p>I initially expected the main result to be:</p><blockquote><strong><em>Jev caught an SLM hallucination.</em></strong></blockquote><p>And it did.</p><p>But the more interesting result was:</p><blockquote><strong><em>Jev itself could not simply be treated as ground truth.</em></strong></blockquote><p>That changed the design.</p><p>My first mental model was:</p><pre>SLM Makes Mistake<br>      │<br>      ▼<br>Verifier Catches Mistake<br>      │<br>      ▼<br>Problem Solved</pre><p>The architecture I ended up with is:</p><pre>SLM Makes Mistake<br>      │<br>      ▼<br>Verifier Judges It<br>      │<br>      ▼<br>Measure Verifier<br>      │<br>      ▼<br>Calibrate<br>      │<br>      ▼<br>Route Carefully<br>      │<br>      ▼<br>Validate Failures<br>      │<br>      ▼<br>Create Trusted Training Data<br>      │<br>      ▼<br>Retrain</pre><p>That is a much more realistic engineering loop.</p><h3>What This Experiment Does Not Prove</h3><p>With such a small initial experiment, I do not claim that:</p><pre>The distilled model is generally better.</pre><pre>Jev is always correct.</pre><pre>Ten examples are enough for meaningful fine-tuning.</pre><pre>The system is already self-improving.</pre><pre>The current architecture is optimal.</pre><p>The held-out benchmark actually showed that:</p><pre>Base Accuracy:<br>20%</pre><pre>Distilled v1 Accuracy:<br>20%</pre><p>So v1 did <strong>not</strong> outperform the base model.</p><p>That is part of the result.</p><h3>What the Experiment Does Demonstrate</h3><p>The project successfully connects:</p><pre>Human Ground Truth<br>        │<br>        ▼<br>Teacher Generation<br>        │<br>        ▼<br>Training-Time Verification<br>        │<br>        ▼<br>QLoRA<br>        │<br>        ▼<br>Student SLM<br>        │<br>        ▼<br>RAG<br>        │<br>        ▼<br>Claim-Level Verification<br>        │<br>        ▼<br>Routing<br>        │<br>        ▼<br>Held-Out Benchmarking<br>        │<br>        ▼<br>Failure Analysis</pre><p>into one functioning experimental pipeline.</p><p>More importantly, the benchmark exposed weaknesses that a demo-only project would have hidden.</p><h3>Final Takeaway</h3><p>I started the project with this question:</p><blockquote><strong><em>Can a verifier make a Small Language Model more reliable?</em></strong></blockquote><p>The experiment led me to a more interesting question:</p><blockquote><strong><em>How do we know when the verifier itself is reliable enough to trust?</em></strong></blockquote><p>The solution is probably not one magical model.</p><p>It is a system built around:</p><pre>Generation<br>    +<br>Verification<br>    +<br>Measurement<br>    +<br>Calibration<br>    +<br>Routing<br>    +<br>Feedback</pre><p>The direction is not simply:</p><pre>Train a better model.</pre><p>It is:</p><pre>Build a system<br>      │<br>      ▼<br>Detect where the model is weak<br>      │<br>      ▼<br>Measure the weakness<br>      │<br>      ▼<br>Route unsafe cases<br>      │<br>      ▼<br>Validate failures<br>      │<br>      ▼<br>Turn trustworthy failures<br>into better training data</pre><p>That is the direction I want to continue exploring.</p><p>Not a perfect model.</p><p>A system that learns where it is weak.</p><h3>Final System Vision</h3><pre>┌──────────────┐<br>                     │    DATA      │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │   TEACHER    │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │ GROUND TRUTH │<br>                     │  VALIDATION  │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │     JEV      │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │ CLEAN DATA   │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │    QLoRA     │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │ STUDENT SLM  │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │     RAG      │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │    DRAFT     │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │ CLAIM SPLIT  │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │     JEV      │<br>                     │ VERIFICATION │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │   ROUTING    │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │ FINAL ANSWER │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │ FAILURE LOG  │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │ VALIDATE HARD│<br>                     │   EXAMPLES   │<br>                     └──────┬───────┘<br>                            │<br>                            ▼<br>                     ┌──────────────┐<br>                     │   QLoRA v2   │<br>                     └──────────────┘</pre><blockquote><strong><em>A verifier should not merely catch failures. A well-designed system should measure the verifier, learn from trustworthy failures, and gradually convert those failures into better training data.</em></strong></blockquote><h3>References</h3><ol><li><strong>ContractNLI: A Dataset for Document-Level Natural Language Inference for Contracts</strong><br>Koreeda, Y., Manning, C. D.<br><a href="https://aclanthology.org/2021.findings-emnlp.164/">https://aclanthology.org/2021.findings-emnlp.164/</a></li><li><strong>QLoRA: Efficient Finetuning of Quantized LLMs</strong><br>Dettmers, T. et al.<br><a href="https://arxiv.org/abs/2305.14314">https://arxiv.org/abs/2305.14314</a></li><li><strong>Qwen2.5 Technical Report</strong><br>Qwen Team.<br><a href="https://arxiv.org/abs/2412.15115">https://arxiv.org/abs/2412.15115</a></li><li><strong>TypeSafe AI — Jev</strong><br>Official Jev overview and structured decision workflow.<br><a href="https://www.typesafeai.org/jev">https://www.typesafeai.org/jev</a></li><li><strong>Spring AI + TypeSafe Jev for Modular RAG</strong><br>Example of Jev used for RAG filtering and reranking.<br><a href="https://spring.io/blog/2026/10/02/spring-ai-modular-rag-typesafe-jev/">https://spring.io/blog/2026/10/02/spring-ai-modular-rag-typesafe-jev/</a></li><li><strong>PEFT: Parameter-Efficient Fine-Tuning</strong><br>Hugging Face documentation.<br><a href="https://huggingface.co/docs/peft/">https://huggingface.co/docs/peft/</a></li></ol><h3>Project Repository</h3><p>The complete implementation for this experiment is available on GitHub:</p><p><strong>JevRagSlmImprovement</strong><br><a href="https://github.com/aishwaryatesting/JevRagSlmImprovement">https://github.com/aishwaryatesting/JevRagSlmImprovement</a></p><p>My Linkeldn Profile: <a href="https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/?isSelfProfile=true">https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/?isSelfProfile=true</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb77e8eea1b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tool Calling Is Easy. Finishing the Task Is Hard.]]></title>
            <link>https://medium.com/@psvsaishwarya/tool-calling-is-easy-finishing-the-task-is-hard-7b8f920fac98?source=rss-53307ac94e90------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b8f920fac98</guid>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[AISHWARYA P.S.V.S]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 12:05:31 GMT</pubDate>
            <atom:updated>2026-09-13T12:05:31.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*je36ey_UL2Rybnhs7guvfQ.png" /></figure><p><em>What GPT-6 Astra reveals about reasoning, harnesses, and reliable AI agents.</em></p><p>AI agents can now search the web, read files, run code, query databases, and call APIs.</p><p>That sounds impressive. But tool calling is becoming common.</p><p>The harder question is this:</p><blockquote><em>Can an AI system complete a real task reliably when the task changes, tools fail, and evidence arrives slowly?</em></blockquote><p>This is where GPT-6 Astra becomes interesting.</p><p>Its value is not simply that it can use tools. Many modern models can do that. The more interesting question is how a model handles a long workflow: deciding what to do next, preserving requirements, interpreting failures, and knowing when it has enough evidence to say the work is complete.</p><p>OpenAI describes GPT-6 Astra as a model for difficult end-to-end work across reasoning, coding, browsing, computer use, research, and professional workflows. <a href="https://openai.com/index/gpt-6-astra/">OpenAI’s GPT-6 Astra launch post</a></p><h3>A tool call is not task completion</h3><p>Imagine asking an AI assistant:</p><blockquote><em>“Fix the failing tests in this Python project. Do not change the public API. Run the test suite and explain the fix.”</em></blockquote><p>A simple agent can follow a basic loop:</p><pre>Read files<br>→ Find a possible bug<br>→ Edit code<br>→ Run tests<br>→ Return an answer</pre><p>But real tasks rarely follow a perfect straight line.</p><p>The test command might fail because a dependency is missing. The first code change might break another test. The user may add a requirement after the assistant has started work:</p><blockquote><em>“This function is used by another service. Backward compatibility is critical.”</em></blockquote><p>At that point, writing code is not the central challenge.</p><p>The system needs to decide whether its earlier plan still applies. It needs to know whether a test result belongs to the current version of the task. It needs to avoid saying “the tests passed” before tests have actually finished.</p><p>Tool calling gives a model actions.</p><p>It does not automatically give it good judgment.</p><h3>Why GPT-6 Astra matters</h3><p>Many models can request a tool call. The difference appears in the quality of decisions made across a longer workflow.</p><p>OpenAI documents several Astra capabilities that are useful for agent workflows.</p><h3>Asynchronous tool calling</h3><p>Some tools return immediately. Others take time.</p><p>Reading a file may take milliseconds. Running a test suite, generating a report, or executing a data pipeline may take much longer.</p><p>Astra supports asynchronous tool calling. While an application executes a tool, Astra can continue with independent reasoning or other actions. The application still executes the tool and manages the pending operation. <a href="https://developers.openai.com/api/docs/guides/latest-model">OpenAI’s GPT-6 Astra developer guide</a></p><p>A workflow might look like this:</p><pre>Astra requests a test run<br>→ The application starts the test job<br>→ Astra reviews related code or documentation<br>→ The test result returns<br>→ Astra interprets the result<br>→ Astra decides whether the task is complete</pre><p>This is useful because some work is independent.</p><p>But it also creates a responsibility: the system must distinguish between work that can continue and work that depends on an unfinished result.</p><p>An assistant can draft an explanation while tests run. It should not claim the tests passed until the test result arrives.</p><h3>Mid-turn steering</h3><p>Users often clarify or revise a request while work is underway.</p><p>For example:</p><blockquote><em>“Fix the performance problem, but do not add a new database dependency.”</em></blockquote><p>Astra supports mid-turn steering, allowing additional user instructions to be incorporated while work continues through a WebSocket-based workflow. <a href="https://developers.openai.com/api/docs/guides/latest-model">OpenAI’s GPT-6 Astra developer guide</a></p><p>This matters because a changed requirement may invalidate earlier decisions.</p><p>A model may need to revise:</p><ul><li>Its implementation plan.</li><li>A proposed code change.</li><li>The tests it intends to run.</li><li>The criteria for considering the task complete.</li></ul><p>The ability to receive a correction is useful. The harder problem is using that correction correctly.</p><h3>Adjustable reasoning effort</h3><p>Not every step in a workflow needs the same amount of reasoning.</p><p>A simple formatting change may need only a quick response. Diagnosing a subtle production failure may require deeper analysis.</p><p>OpenAI documents that Astra’s reasoning effort can be changed during a conversation while preserving cached context. <a href="https://developers.openai.com/api/docs/guides/latest-model">OpenAI’s GPT-6 Astra developer guide</a></p><p>Conceptually, this allows a workflow like:</p><pre>Routine request<br>→ lower reasoning effort</pre><pre>Unexpected failure<br>→ higher reasoning effort</pre><pre>Simple follow-up<br>→ lower reasoning effort again</pre><p>This turns reasoning into a resource that can be managed according to task difficulty.</p><h3>The missing layer: the harness</h3><p>A model does not directly become an agent merely because it can request tools.</p><p>It needs a harness.</p><p>An agent harness is the application layer around the model. It supplies context, defines tools, executes permitted actions, tracks state, handles errors, and checks results.</p><pre>User request<br>      ↓<br>Harness prepares context and tools<br>      ↓<br>GPT-6 Astra chooses the next action<br>      ↓<br>Harness executes the action<br>      ↓<br>Tool result returns to Astra<br>      ↓<br>Astra continues or finishes</pre><p>The model and the harness have different jobs.</p><p>JobModelHarnessUnderstand the user’s goalYesProvides relevant contextDecide what action may helpYesDefines what actions existRequest a test runYesStarts the test runnerApply permissionsNoYesTrack pending workCan reason about itStores operational stateInterpret test outputYesReturns accurate outputVerify completionCan assess evidenceEnforces required checks</p><p>A model might say:</p><blockquote><em>“The bug is fixed.”</em></blockquote><p>But a harness can require evidence before the task is marked complete:</p><ul><li>Was the file actually updated?</li><li>Did the requested test run?</li><li>Did the command exit successfully?</li><li>Does the result correspond to the latest requirement?</li></ul><p>The harness does not make the model intelligent. It makes the workflow observable and controllable.</p><blockquote><strong><em>Suggested diagram caption:</em></strong><em> A model requests actions; the harness controls execution, tracks state, and verifies the evidence before completion.</em></blockquote><h3>What “finishing” really means</h3><p>A generated answer and a completed task are not the same thing.</p><p>Consider three statements:</p><ol><li>“I wrote a fix.”</li><li>“I applied the fix.”</li><li>“I applied the fix, ran the relevant tests, and the tests passed.”</li></ol><p>Each statement requires stronger evidence.</p><p>A trustworthy agent should match its claim to the evidence it has.</p><p>For example, a successful test run supports this statement:</p><blockquote><em>“The specified tests passed.”</em></blockquote><p>It does not support this statement:</p><blockquote><em>“The software has no bugs.”</em></blockquote><p>Likewise, creating a report file proves that a file exists. It does not prove the report’s conclusions are correct.</p><p>The goal is not perfection. The goal is to make the system honest about what it knows and what it verified.</p><h3>The difference between features and quality</h3><p>Many modern AI models can call tools.</p><p>Two models might have access to exactly the same tools:</p><pre>read_file<br>edit_file<br>run_tests<br>search_docs</pre><p>Yet they can still perform very differently.</p><p>One model might inspect irrelevant files, misinterpret an error, ignore a constraint, or stop too early.</p><p>Another might identify relevant information, preserve the user’s requirement, adjust when new evidence appears, and wait for verification before reporting success.</p><p>The tool list is not the full story.</p><p>The quality of decisions across the workflow matters.</p><p>OpenAI reports that Astra is stronger at long-task coherence, instruction following, incorporating new requirements, and complex tool-assisted work. These are OpenAI’s published claims and evaluation results, not an independent result from this article. <a href="https://openai.com/index/gpt-6-astra/">OpenAI’s GPT-6 Astra launch post</a></p><h3>How to evaluate an AI agent</h3><p>The right question is not:</p><blockquote><em>“Does this model have tool calling?”</em></blockquote><p>A better question is:</p><blockquote><em>“Can this model complete my workflow accurately and with evidence?”</em></blockquote><p>A useful evaluation can measure:</p><ul><li>Did the task succeed?</li><li>Did the agent preserve important constraints?</li><li>Did it interpret tool errors correctly?</li><li>Did it wait for verification before claiming completion?</li><li>How often did it need human intervention?</li><li>How long did it take?</li><li>What did it cost per successful task?</li></ul><p>For a coding workflow, a practical evaluation might include a set of small bugs with known tests and requirements.</p><p>Keep the task set, tools, execution limits, and harness constant. Then compare model behavior.</p><p>This does not prove that one model is universally best. It provides evidence for the work that matters to your application.</p><h3>The practical lesson</h3><p>Tool calling is easy to demonstrate.</p><p>Task completion is harder.</p><p>A capable model needs to reason across changing requirements, incomplete information, and real execution results. A capable harness needs to provide useful context, controlled actions, operational state, and verification.</p><p>GPT-6 Astra is interesting because its documented features support this type of workflow: asynchronous tools, mid-turn steering, and adjustable reasoning effort.</p><p>But features alone are not the outcome.</p><p>The outcome is whether the complete system can do useful work, recover from failure, respect constraints, and accurately report what happened.</p><p>That is the standard AI agents should be judged by.</p><h3>References</h3><ol><li><a href="https://openai.com/index/gpt-6-astra/">GPT-6 Astra: A New Generation of Intelligence — OpenAI</a></li><li><a href="https://developers.openai.com/api/docs/guides/latest-model">Using GPT-6 Astra — OpenAI Developer Guide</a></li><li><a href="https://developers.openai.com/api/docs/models/gpt-6-astra">GPT-6 Astra Model Specifications — OpenAI</a></li></ol><p>My Linkeldn url:<a href="https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/">https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b8f920fac98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How a Causal Looped Transformer Thinks With RAG: A PyTorch Experiment]]></title>
            <link>https://medium.com/@psvsaishwarya/how-a-causal-looped-transformer-thinks-with-rag-a-pytorch-experiment-ead6516122c3?source=rss-53307ac94e90------2</link>
            <guid isPermaLink="false">https://medium.com/p/ead6516122c3</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[looped-transformer]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[AISHWARYA P.S.V.S]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 13:14:27 GMT</pubDate>
            <atom:updated>2026-09-08T13:33:16.954Z</atom:updated>
            <content:encoded><![CDATA[<p>Most Transformer tutorials explain self-attention, embeddings, and next-token prediction. I wanted to understand a different question:</p><blockquote><em>What happens when the same causal Transformer block is reused multiple times instead of stacking many different layers?</em></blockquote><p>That idea is called a <strong>looped Transformer</strong>.</p><p>This project is inspired by <a href="https://arxiv.org/abs/2311.12424"><em>Looped Transformers are Better at Learning Learning Algorithms</em></a>. I am not reproducing the paper’s full experiments. I built a small educational PyTorch implementation to understand causal attention, shared weights, autoregressive generation, and RAG.</p><p>Project code: <a href="https://github.com/aishwaryatesting/looped-causal-rag-demo">looped-causal-rag-demo</a></p><h3>The basic idea</h3><p>A standard deep Transformer uses different parameters at each layer.</p><pre>Input → Block 1 → Block 2 → Block 3 → Output<br>         W1        W2        W3</pre><p>A looped Transformer creates one block and applies it repeatedly.</p><pre>Input → Shared Block → Shared Block → Shared Block → Output<br>          Wshared       Wshared       Wshared</pre><p>The weights remain the same, but the hidden state changes at every loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*828MQROxt8CXY-as8I6OuQ.png" /></figure><pre>state = torch.zeros_like(embeddings)</pre><pre>for _ in range(self.n_loops):<br>    state = self.shared_block(state + embeddings)</pre><p>Here:</p><pre>embeddings = fixed token and position information<br>state      = changing internal hidden state</pre><p>The first iteration starts from zeros:</p><pre>Loop 1: shared_block(zeros + embeddings)</pre><p>The second and third iterations use the previous hidden state:</p><pre>Loop 2: shared_block(state from loop 1 + embeddings)<br>Loop 3: shared_block(state from loop 2 + embeddings)</pre><p>This is the key point: the model reuses the same learned block, but it does not receive the same hidden state twice.</p><h3>Causal Transformer versus looped Transformer</h3><p>“Causal” and “looped” describe different parts of an architecture.</p><p>Causal TransformerLooped TransformerControls what a token may attend toControls how computation is repeatedCan see earlier tokens but not future tokensReuses one Transformer block multiple timesUsed for next-token generationUsed for repeated hidden-state refinementUses a causal maskUses shared weights across loops</p><pre>Causal = Where may attention look?<br>Looped = How many times is the same block applied?</pre><p>My model combines both ideas:</p><pre>Causal attention<br>+ shared block reused for loops<br>= causal looped Transformer</pre><h3>How causal attention prevents cheating</h3><p>For text generation, a model must predict the next token without seeing the future answer.</p><p>For example:</p><pre>Input: “loop”<br>Goal: predict the next character</pre><p>When processing the final o, the model can look at previous characters such as l, o, and o. It cannot look at the future character it is supposed to predict.</p><p>In PyTorch, I enforce this using a causal mask:</p><pre>future_mask = torch.triu(<br>    torch.ones(T, T, dtype=torch.bool, device=x.device),<br>    diagonal=1,<br>)</pre><pre>scores = scores.masked_fill(future_mask, float(&quot;-inf&quot;))</pre><p>torch.triu(..., diagonal=1) creates a mask above the diagonal. Those positions represent future tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRsPrPoVaWEJ1UzB2gn1MQ.png" /></figure><p>After softmax, attention scores with -inf become probability zero.</p><p>This is the core idea behind GPT-style next-token generation. The original Transformer introduced self-attention, while causal masking makes self-attention work for left-to-right generation. <a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a></p><h3>What d_model and block_size mean</h3><p>Two numbers confused me when I started:</p><pre>d_model = 32<br>block_size = 256</pre><p>They are not the same.</p><pre>d_model    = width of each token’s internal representation<br>block_size = maximum number of tokens that fit in the context window</pre><p>For example, if a RAG prompt contains 180 character tokens:</p><pre>Input IDs:       [1, 180]<br>Embeddings:      [1, 180, 32]<br>Hidden state:    [1, 180, 32]<br>Output logits:   [1, 180, vocabulary size]</pre><p>block_size=256 means the 180-token prompt fits in context.</p><p>d_model=32 means every token is represented internally by 32 learned numbers.</p><pre>&quot;a&quot;<br> ↓<br>token ID 4<br> ↓<br>[0.18, -0.42, 0.07, ..., 0.91]<br> └──────── 32 values ────────┘</pre><p>These values are learned. They do not have fixed human-readable meanings individually. Together, they form the model’s representation of that token.</p><h3>Multi-head causal attention</h3><p>The model creates queries, keys, and values with:</p><pre>self.qkv = nn.Linear(d_model, 3 * d_model)</pre><p>This produces three vectors from each token representation:</p><pre>Q = query: what information am I looking for?<br>K = key: what information do I contain?<br>V = value: what information should I send?</pre><p>Attention scores are calculated using:</p><pre>scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_size)</pre><p>Then the causal mask removes future positions.</p><pre>attention_weights = F.softmax(scores, dim=-1)<br>head_outputs = attention_weights @ v</pre><p>The values are combined according to attention probabilities.</p><pre>high attention probability → take more information from that token<br>low attention probability  → take less information from that token</pre><p>Multi-head attention lets different heads learn different relationships. One head may focus on nearby characters, while another may learn longer patterns.</p><h3>How next-token training works</h3><p>The model receives token IDs and produces vocabulary scores.</p><pre>Input IDs: [batch, sequence length]<br>Logits:    [batch, sequence length, vocabulary size]</pre><p>For example:</p><pre>[2, 8, 50]</pre><p>means:</p><pre>2 sequences<br>8 positions per sequence<br>50 possible next-token scores at every position</pre><p>To train next-token prediction, I shift the input by one position.</p><pre>Input:   [7, 8, 9, 10]<br>Target:     [8, 9, 10]</pre><p>The model should learn:</p><pre>7 → 8<br>8 → 9<br>9 → 10</pre><p>For my character-level language-model version, it learns the same next-token rule using characters instead of artificial numbers.</p><p>The loss in my code is:</p><pre>loss = F.cross_entropy(<br>    prediction_logits.reshape(-1, vocab_size),<br>    targets.reshape(-1),<br>)</pre><p>Cross-entropy compares the model’s predicted vocabulary scores with the correct next-token IDs. <a href="https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html">PyTorch cross-entropy documentation</a></p><p>Then training updates the learned weights:</p><pre>optimizer.zero_grad()<br>loss.backward()<br>optimizer.step()</pre><pre>zero_grad() → clear previous gradients<br>backward()  → calculate how weights affected the loss<br>step()      → update weights to reduce future loss</pre><p>In my small experiment, training loss decreased approximately from:</p><pre>3.73 → 2.80</pre><p>That showed the learning pipeline was working. It does not mean this tiny model became a strong language model.</p><h3>Autoregressive generation</h3><p>A causal language model generates one token at a time.</p><pre>Prompt<br>→ predict next token<br>→ append it<br>→ predict the next token again<br>→ repeat</pre><p>My generation function is:</p><pre>@torch.no_grad()<br>def generate(model, token_ids, max_new_tokens):<br>    model.eval()</pre><pre>    for _ in range(max_new_tokens):<br>        context = token_ids[:, -model.block_size:]<br>        logits = model(context)</pre><pre>        next_token_logits = logits[:, -1, :]<br>        next_token = next_token_logits.argmax(dim=-1, keepdim=True)</pre><pre>        token_ids = torch.cat((token_ids, next_token), dim=1)</pre><pre>    return token_ids</pre><p>@torch.no_grad() means gradients are not calculated during generation. The model is predicting, not learning. This saves memory and computation. <a href="https://pytorch.org/docs/stable/generated/torch.no_grad.html">PyTorch </a><a href="https://pytorch.org/docs/stable/generated/torch.no_grad.html">no_grad documentation</a></p><p>This line selects the final token position:</p><pre>next_token_logits = logits[:, -1, :]</pre><p>If logits has shape:</p><pre>[batch, sequence length, vocabulary size]</pre><p>then:</p><pre>:  → every sequence in the batch<br>-1 → final token position<br>:  → every vocabulary score</pre><p>The model uses the final position because it has access to all earlier tokens allowed by causal attention.</p><p>Then:</p><pre>next_token = next_token_logits.argmax(dim=-1, keepdim=True)</pre><p>chooses the vocabulary ID with the highest score.</p><p>Finally:</p><pre>token_ids = torch.cat((token_ids, next_token), dim=1)</pre><p>appends the prediction to the prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3yesnIhEcHtXcqH281pUg.png" /></figure><p>max_new_tokens=30 means the model can append at most 30 new character tokens. It does not mean 30 Transformer loops.</p><pre>n_loops = 3           → shared block runs three times per prediction<br>max_new_tokens = 30   → generation predicts up to 30 new tokens</pre><h3>What happens with hundreds of loops?</h3><p>My tutorial model uses:</p><pre>n_loops = 3</pre><p>So gradients flow through all three loops.</p><p>The looped Transformer paper studies much longer loop counts. If a shared block is repeated hundreds of times, backpropagating through every loop may require too much memory and create unstable gradient paths.</p><p>One technique is to run early loops without gradient tracking and preserve gradients only in the final loop window.</p><pre>with torch.no_grad():<br>    for _ in range(330):<br>        state = shared_block(state + embeddings)</pre><pre>for _ in range(20):<br>    state = shared_block(state + embeddings)</pre><pre>loss.backward()</pre><p>Conceptually:</p><pre>First 330 loops<br>→ hidden state is refined<br>→ no gradient history is saved</pre><pre>Last 20 loops<br>→ hidden state is refined<br>→ gradients are saved<br>→ backpropagation uses this final window</pre><p>This does not completely solve vanishing gradients. It reduces the length of the backpropagation path and lowers memory use. Residual connections and LayerNorm also help stabilize repeated computation.</p><h3>Do more loops cause overfitting?</h3><p>Not automatically.</p><pre>More training steps can cause overfitting.<br>More model parameters can increase overfitting risk.<br>More loop iterations are repeated computation using the same parameters.</pre><p>Because a looped Transformer shares one block’s weights, increasing n_loops does not add a new set of parameters like adding separate layers would. This can make it more parameter-efficient.</p><p>However, many loops can still create practical problems:</p><pre>- longer computation time<br>- higher activation-memory cost during training<br>- unstable or vanishing/exploding gradients over long loop paths<br>- learning a task-specific iterative pattern that may not generalize</pre><p>So looping is not a guaranteed cure for overfitting. It trades extra unique parameters for repeated computation.</p><h3>Adding RAG</h3><p>A looped Transformer can repeatedly refine information already in its input. But it cannot retrieve information that was never provided.</p><p>That is why RAG is useful.</p><pre>Question<br>→ retrieve relevant documents<br>→ add them to the prompt<br>→ tokenize prompt<br>→ causal looped Transformer<br>→ generate continuation<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2nUqw0VdjkpSh0vOxf9NA.png" /></figure><p>My first retriever is intentionally simple. It finds documents using matching words:</p><pre>score = len(query_words &amp; words(document))</pre><p>For the question:</p><pre>How does a looped Transformer reuse a block?</pre><p>it retrieves documents containing words such as:</p><pre>looped<br>transformer<br>block</pre><p>Then it builds a RAG prompt:</p><pre>Context:<br>- A looped Transformer reuses one shared Transformer block over multiple loops.<br>- A causal Transformer can attend to earlier tokens but cannot attend to future tokens.</pre><pre>Question: How does a looped Transformer reuse a block?<br>Answer:</pre><p>The prompt is converted into token IDs and sent into the model.</p><p>RAG combines generation with retrieved external evidence. <a href="https://arxiv.org/abs/2005.11401">Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks</a></p><h3>Context length is important in RAG</h3><p>The retrieved prompt must fit inside the model’s context window.</p><pre>RAG prompt length ≤ block_size</pre><p>If a prompt contains 180 tokens but:</p><pre>block_size = 32</pre><p>the model cannot use all retrieved evidence. Earlier context will be lost.</p><p>For this reason, I increased my demonstration model to:</p><pre>block_size = 256</pre><p>Real RAG systems must carefully choose:</p><pre>chunk size<br>number of retrieved documents<br>context-window size</pre><p>More retrieved text is not always better if it pushes important information outside the context window.</p><h3>What worked and what did not</h3><p>The project runs end-to-end:</p><pre>Text<br>→ token IDs<br>→ embeddings<br>→ causal attention<br>→ shared Transformer loops<br>→ next-token prediction<br>→ cross-entropy loss<br>→ gradients<br>→ retrieval<br>→ RAG prompt<br>→ generation</pre><p>However, the generated text is still weak and repetitive.</p><p>That is expected because my model is intentionally tiny:</p><pre>- character-level tokenizer<br>- d_model = 32<br>- three loops<br>- small repeated training corpus<br>- 200 training steps<br>- keyword retrieval instead of semantic retrieval</pre><p>This project demonstrates the architecture, not a production-ready RAG assistant.</p><p>A stronger version would use:</p><pre>- a pretrained tokenizer<br>- a pretrained causal language model<br>- embedding/vector retrieval<br>- real documents<br>- larger context windows<br>- much more training data</pre><h3>Final takeaway</h3><p>This project helped me separate three ideas that are often confused:</p><pre>Causal attention<br>→ controls which tokens can be seen</pre><pre>Looped computation<br>→ reuses the same Transformer block repeatedly</pre><pre>RAG<br>→ retrieves external knowledge before generation</pre><p>A looped Transformer does not automatically produce better language generation. RAG does not solve training issues such as vanishing gradients.</p><p>But combining them creates a useful educational architecture:</p><pre>retrieve knowledge<br>→ add context<br>→ repeatedly refine hidden state<br>→ predict the next token<br>→ generate an answer</pre><p>The main value of this project was not the quality of the final toy output. It was understanding every step of the pipeline through code.</p><h3>References</h3><ol><li><a href="https://arxiv.org/abs/2311.12424">Looped Transformers are Better at Learning Learning Algorithms</a></li><li><a href="https://github.com/Leiay/looped_transformer">Official Looped Transformer repository</a></li><li><a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a></li><li><a href="https://arxiv.org/abs/2005.11401">Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks</a></li><li><a href="https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html">PyTorch cross-entropy documentation</a></li><li><a href="https://pytorch.org/docs/stable/generated/torch.no_grad.html">PyTorch </a><a href="https://pytorch.org/docs/stable/generated/torch.no_grad.html">torch.no_grad documentation</a></li></ol><p>and also my linkeldn link:<a href="https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/">https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ead6516122c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Happens Inside torch.sum()? From PyTorch to CUDA Warp Reduction]]></title>
            <link>https://medium.com/@psvsaishwarya/what-happens-inside-torch-sum-from-pytorch-to-cuda-warp-reduction-fce185916ce7?source=rss-53307ac94e90------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce185916ce7</guid>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[AISHWARYA P.S.V.S]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 17:09:33 GMT</pubDate>
            <atom:updated>2026-09-03T17:09:33.462Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What one simple PyTorch operation taught me about CUDA threads, groups of 32, shared memory, Triton, JAX, and the kernels behind modern AI systems.</em></p><p>My journey started with a familiar line of PyTorch:</p><pre>result = torch.sum(x)</pre><p>PyTorch makes the operation look simple, as it should. But I wanted to understand the work hidden underneath that line.</p><p>If x contains 67,108,864 floating-point values, how can a massively parallel GPU turn all of them into one result?</p><p>When I began reading GPU code, I recognized words such as blocks, warps, shared memory, synchronization, shuffles, tiling, and fusion. However, I could not see how those ideas formed one system.</p><p>Following a single sum from PyTorch down toward CUDA finally connected them.</p><p>The mathematical operation is straightforward:</p><pre>sum(x) = x[0] + x[1] + ... + x[n-1]</pre><p>The arithmetic is elementary. The execution is not.</p><p>Millions of independent values must eventually become one value. The GPU cannot simply allow millions of threads to update the same memory location without creating contention.</p><p>My central question became:</p><blockquote><em>At this stage of the computation, who owns the partial result, and what is the least expensive way to move it to the next stage?</em></blockquote><h3>My original mental model was incomplete</h3><p>I initially imagined GPU performance like this:</p><pre>More data → launch more threads → finish sooner</pre><p>That model explains how independent work begins. However, a reduction contains an additional dependency: all the separate results must eventually be combined.</p><p>A tempting CUDA kernel might allow every thread to perform an atomic addition into one output:</p><pre>__global__ void atomic_sum(<br>    const float* input,<br>    float* result,<br>    size_t n<br>) {<br>    size_t i =<br>        blockIdx.x * blockDim.x + threadIdx.x;</pre><pre>    if (i &lt; n) {<br>        atomicAdd(result, input[i]);<br>    }<br>}</pre><p>This can produce the correct answer, but it sends every participating thread toward the same destination.</p><p>The work is parallel, but the destination becomes a bottleneck.</p><p>Instead, I wanted the communication to narrow gradually:</p><pre>private work inside each thread<br>        ↓<br>cooperation inside each warp<br>        ↓<br>cooperation inside each block<br>        ↓<br>partial results in global memory<br>        ↓<br>another reduction pass<br>        ↓<br>one final value</pre><p>The guiding principle is:</p><blockquote><em>Combine as much data as possible nearby before moving the result farther away.</em></blockquote><h3>Step 1: Give every thread a private accumulator</h3><p>Each CUDA thread begins with its own sum:</p><pre>float local = 0.0f;</pre><p>local belongs to one thread. Other threads do not directly read or update it.</p><p>The compiler will normally store a variable like this in a register. Registers are private to each thread and provide very fast access.</p><p>A grid-stride loop allows a fixed number of GPU threads to process an arbitrarily large input:</p><pre>const size_t start =<br>    static_cast&lt;size_t&gt;(blockIdx.x) *<br>    blockDim.x * 2 +<br>    threadIdx.x;</pre><pre>const size_t stride =<br>    static_cast&lt;size_t&gt;(blockDim.x) *<br>    2 *<br>    gridDim.x;</pre><pre>for (size_t i = start; i &lt; n; i += stride) {<br>    local += input[i];</pre><pre>    if (i + blockDim.x &lt; n) {<br>        local += input[i + blockDim.x];<br>    }<br>}</pre><p>Suppose a block contains 256 threads.</p><p>Each thread attempts to load two values, so one block initially covers:</p><pre>256 threads × 2 values = 512 values</pre><p>Adjacent threads read adjacent memory locations. This produces a GPU-friendly memory-access pattern.</p><p>The bounds check protects the kernel when the array size is not an exact multiple of the tile size:</p><pre>if (i + blockDim.x &lt; n)</pre><p>The grid-stride loop also explains why the number of blocks can be capped. After processing its first pair of values, a thread advances by the width of the entire grid and processes another pair.</p><p>At the end of this stage, millions of input values have become one private partial sum per thread.</p><p>The input reading is parallel, but the thread results still need to be combined.</p><h3>Step 2: Warp reduction turns 32 thread sums into one</h3><p>On NVIDIA GPUs, threads execute in groups called warps.</p><p>A warp contains 32 threads. The positions inside a warp are called lanes, numbered from 0 to 31.</p><pre>Warp<br>├── lane 0<br>├── lane 1<br>├── lane 2<br>├── ...<br>└── lane 31</pre><p>If all 32 lanes hold private partial sums, we need to combine those 32 values.</p><p>The following helper performs a warp-level tree reduction:</p><pre>__device__ __forceinline__<br>float warp_sum(float value) {<br>    for (<br>        int offset = warpSize / 2;<br>        offset &gt; 0;<br>        offset /= 2<br>    ) {<br>        value += __shfl_down_sync(<br>            0xffffffff,<br>            value,<br>            offset<br>        );<br>    }</pre><pre>    return value;<br>}</pre><p>Because warpSize is 32, the offset values are:</p><pre>16 → 8 → 4 → 2 → 1</pre><h3>What happens when offset = 16?</h3><p>Lane 0 receives the value from lane 16.</p><p>Lane 1 receives the value from lane 17.</p><p>Lane 2 receives the value from lane 18.</p><p>This continues until lane 15 receives the value from lane 31.</p><pre>Lane 0  += Lane 16<br>Lane 1  += Lane 17<br>Lane 2  += Lane 18<br>...<br>Lane 15 += Lane 31</pre><p>The lower 16 lanes now contain sums representing two original lane values.</p><h3>What happens when offset = 8?</h3><p>Lane 0 receives lane 8’s updated value.</p><p>Because lane 8 already represents two original values, lane 0 now represents four values.</p><p>The reduction continues:</p><pre>32 partial sums<br>      ↓ offset 16<br>16 useful sums<br>      ↓ offset 8<br>8 useful sums<br>      ↓ offset 4<br>4 useful sums<br>      ↓ offset 2<br>2 useful sums<br>      ↓ offset 1<br>1 complete warp sum</pre><p>After five rounds, lane 0 contains the sum of all 32 original lane values.</p><h3>Why access another thread’s value?</h3><p>Normally, a thread’s register values are private.</p><p>However, the purpose of a reduction is to combine values. At some point, threads must communicate.</p><p>The instruction:</p><pre>__shfl_down_sync(<br>    0xffffffff,<br>    value,<br>    offset<br>)</pre><p>allows a thread to obtain a register value from another participating lane in the same warp.</p><p>This avoids repeatedly writing the values to shared memory, synchronizing, and reading them back.</p><p>The mask:</p><pre>0xffffffff</pre><p>contains 32 set bits and indicates that all 32 lanes participate.</p><p>This full mask is valid in this educational kernel because the block size is a multiple of 32 and every thread reaches the shuffle instruction.</p><p>For kernels with partial or divergent warp participation, the mask must be constructed more carefully.</p><h3>Step 3: Cross the boundary between warps</h3><p>A block containing 256 threads has:</p><pre>256 / 32 = 8 warps</pre><p>After the first warp reduction, the block contains eight useful results — one result in lane 0 of each warp.</p><p>A shuffle operation can exchange values only inside one warp. It cannot directly move a value from one warp to another.</p><p>Therefore, the eight warps need a block-visible meeting place.</p><p>That meeting place is shared memory:</p><pre>extern __shared__ float warp_sums[];</pre><p>Shared memory is visible to all threads in the same block.</p><p>Each thread calculates its lane and warp number:</p><pre>const unsigned lane = threadIdx.x &amp; 31;<br>const unsigned warp = threadIdx.x &gt;&gt; 5;</pre><p>For a warp size of 32, these bit operations are equivalent to:</p><pre>lane = threadIdx.x % 32;<br>warp = threadIdx.x / 32;</pre><p>Examples:</p><pre>threadIdx.x = 0<br>lane = 0<br>warp = 0</pre><pre>threadIdx.x = 31<br>lane = 31<br>warp = 0</pre><pre>threadIdx.x = 32<br>lane = 0<br>warp = 1</pre><pre>threadIdx.x = 63<br>lane = 31<br>warp = 1</pre><p>Only lane 0 of every warp owns the completed warp sum:</p><pre>if (lane == 0) {<br>    warp_sums[warp] = local;<br>}</pre><p>For a 256-thread block, shared memory now contains eight results instead of 256 individual values.</p><p>Before any thread reads those results, the block must synchronize:</p><pre>__syncthreads();</pre><p>Without this barrier, the first warp might try to read a shared-memory entry before another warp has written it.</p><h3>Step 4: Let the first warp finish the block reduction</h3><p>The first eight threads load the eight warp sums from shared memory.</p><p>The remaining lanes receive zero, which is the identity value for addition:</p><pre>const unsigned number_of_warps =<br>    (blockDim.x + 31) / 32;</pre><pre>local =<br>    threadIdx.x &lt; number_of_warps<br>        ? warp_sums[lane]<br>        : 0.0f;</pre><p>Only the first warp performs the final reduction:</p><pre>if (warp == 0) {<br>    local = warp_sum(local);</pre><pre>    if (lane == 0) {<br>        partials[blockIdx.x] = local;<br>    }<br>}</pre><p>The same warp_sum helper now combines eight real warp sums and 24 zeros.</p><p>Lane 0 finally writes one result for the entire block.</p><p>This is where shared memory began to make sense to me.</p><p>Shared memory is not automatically the place where every value should live.</p><p>In this kernel:</p><pre>Registers<br>→ hold private thread accumulators</pre><pre>Warp shuffle<br>→ combines values inside groups of 32 threads</pre><pre>Shared memory<br>→ connects different warps inside one block</pre><pre>Global memory<br>→ stores one partial result per block</pre><p>Every memory location has a specific purpose.</p><h3>Step 5: One kernel launch is not the complete reduction</h3><p>Suppose the first kernel pass launches 4,096 blocks.</p><p>Each block writes one partial sum, so the first pass produces:</p><pre>4,096 partial sums</pre><p>That is much smaller than 67 million values, but it is still not one final answer.</p><p>The host repeatedly launches the reduction kernel:</p><pre>while (current_n &gt; 1) {<br>    int blocks = static_cast&lt;int&gt;(<br>        std::min&lt;size_t&gt;(<br>            (<br>                current_n +<br>                threads * 2 -<br>                1<br>            ) /<br>            (threads * 2),<br>            4096<br>        )<br>    );</pre><pre>    reduce_partials&lt;&lt;&lt;<br>        blocks,<br>        threads,<br>        ((threads + 31) / 32) *<br>            sizeof(float)<br>    &gt;&gt;&gt;(<br>        current_input,<br>        current_output,<br>        current_n<br>    );</pre><pre>    current_n = blocks;<br>    current_input = current_output;<br>    current_output =<br>        current_output == a ? b : a;<br>}</pre><p>The block-count expression performs ceiling division.</p><p>With 256 threads and two initial loads per thread, each block initially covers 512 values:</p><pre>blocks = ceil(current_n / 512)</pre><p>The cap of 4,096 blocks is a performance-tuning choice. It is not a fixed CUDA rule.</p><p>Correctness is maintained because the grid-stride loop allows the existing threads to process additional input values.</p><p>The two temporary buffers, a and b, alternate roles:</p><pre>Original input<br>      ↓<br>Buffer A<br>      ↓<br>Buffer B<br>      ↓<br>Buffer A<br>      ↓<br>Final scalar</pre><p>For the default input size of 2²⁶, the reduction passes can look like:</p><pre>67,108,864 values<br>        ↓<br>4,096 block partials<br>        ↓<br>8 block partials<br>        ↓<br>1 final result</pre><p>The arithmetic remains simple throughout.</p><p>The engineering work is deciding how ownership narrows from millions of values to one.</p><h3>Why use 67,108,864 values?</h3><p>The number comes from:</p><pre>1ull &lt;&lt; 26</pre><p>Shifting the number 1 left by 26 binary positions calculates:</p><pre>2²⁶ = 67,108,864</pre><p>Each value is a 32-bit float occupying four bytes.</p><p>Therefore, the input size is:</p><pre>67,108,864 × 4 bytes<br>= 268,435,456 bytes<br>= 256 MiB</pre><p>This is large enough to make GPU memory movement meaningful while still fitting comfortably into the memory of many modern GPUs.</p><p>It is a benchmark default, not a CUDA requirement. The program can accept other input sizes through its command-line arguments.</p><h3>A smaller example that made the algorithm understandable</h3><p>The 67-million-element benchmark was difficult to visualize, so I considered a smaller example:</p><pre>256 values<br>64 threads per block<br>2 values loaded by each thread</pre><p>One block initially covers:</p><pre>64 threads × 2 values = 128 values</pre><p>Therefore, two blocks cover all 256 values:</p><pre>Block 0 → values 1–128<br>Block 1 → values 129–256</pre><p>The block results are:</p><pre>Block 0 partial = 8,256<br>Block 1 partial = 24,640</pre><p>The next pass combines them:</p><pre>8,256 + 24,640 = 32,896</pre><p>This matches the expected result:</p><pre>1 + 2 + ... + 256 = 32,896</pre><p>The small example contains exactly the same ownership hierarchy as the large one. It simply makes every transition easier to see.</p><h3>How this helps me understand PyTorch</h3><p>The educational CUDA kernel in this article should not be treated as the exact source code used internally by every version of PyTorch.</p><p>PyTorch may select different implementations depending on:</p><ul><li>Tensor shape</li><li>Data type</li><li>Memory layout</li><li>GPU architecture</li><li>PyTorch version</li><li>CUDA version</li></ul><p>The value of the exercise is the execution model it reveals.</p><p>When I write:</p><pre>import torch</pre><pre>x = torch.randn(<br>    67_108_864,<br>    device=&quot;cuda&quot;<br>)</pre><pre>result = torch.sum(x)</pre><p>I can now picture the hidden journey:</p><pre>PyTorch tensor on the GPU<br>        ↓<br>Threads read different elements<br>        ↓<br>Each thread creates a private partial sum<br>        ↓<br>Each warp reduces 32 thread sums<br>        ↓<br>Shared memory connects warps in a block<br>        ↓<br>Each block writes one partial result<br>        ↓<br>Additional work reduces the block results<br>        ↓<br>PyTorch returns one tensor value</pre><p>Understanding this hierarchy explains why reductions can be expensive. The GPU must read a large amount of data and gradually combine it.</p><p>It also explains why GPU benchmarking requires synchronization. CUDA operations are normally asynchronous, so measuring ordinary CPU time around a PyTorch operation may not measure the actual GPU execution correctly.</p><h3>How this relates to torch.compile</h3><p>Consider the following PyTorch function:</p><pre>@torch.compile<br>def score(x):<br>    return torch.sum(<br>        torch.relu(x) * x<br>    )</pre><p>Without fusion, an implementation might perform several stages:</p><pre>Read x<br>→ calculate ReLU<br>→ write temporary result<br>→ read temporary result<br>→ multiply by x<br>→ write another temporary<br>→ read temporary<br>→ perform reduction</pre><p>A compiler may be able to combine compatible work:</p><pre>Read x<br>→ calculate ReLU and multiplication locally<br>→ reduce values<br>→ write final output</pre><p>This can reduce:</p><ul><li>Kernel-launch overhead</li><li>Temporary tensor creation</li><li>Global-memory reads</li><li>Global-memory writes</li></ul><p>CUDA teaches us what the costs are.</p><p>PyTorch provides productive high-level operations.</p><p>torch.compile and related compiler technologies attempt to organize those operations more efficiently.</p><h3>Triton changes which decisions I write down</h3><p>After understanding the CUDA version, the same idea can be expressed in Triton:</p><pre>@triton.jit<br>def partial_sum_kernel(<br>    input_ptr,<br>    output_ptr,<br>    n_elements: tl.constexpr,<br>    BLOCK_SIZE: tl.constexpr,<br>):<br>    pid = tl.program_id(axis=0)</pre><pre>    offsets = (<br>        pid * BLOCK_SIZE +<br>        tl.arange(0, BLOCK_SIZE)<br>    )</pre><pre>    mask = offsets &lt; n_elements</pre><pre>    values = tl.load(<br>        input_ptr + offsets,<br>        mask=mask,<br>        other=0.0,<br>    )</pre><pre>    partial = tl.sum(<br>        values,<br>        axis=0<br>    )</pre><pre>    tl.store(<br>        output_ptr + pid,<br>        partial<br>    )</pre><p>In CUDA, I describe the work of individual threads.</p><p>In Triton, I describe a tile of values.</p><p>pid selects a Triton program instance. tl.arange creates positions inside its tile. The mask protects the unfinished final tile, and tl.sum reduces the loaded values.</p><p>I still make important decisions:</p><ul><li>BLOCK_SIZE</li><li>The launch grid</li><li>The number of warps</li><li>Memory-access patterns</li><li>Tile ownership</li></ul><p>However, I no longer write every shuffle operation, shared-memory handoff, and synchronization barrier manually.</p><p>Triton’s compiler maps the blocked program onto GPU execution.</p><h3>JAX moves attention toward the mathematical operation</h3><p>The JAX version can be written as:</p><pre>import jax<br>import jax.numpy as jnp</pre><pre>@jax.jit<br>def reduce_sum(x):<br>    return jnp.sum(x)</pre><p>There is no thread index, tile size, shuffle instruction, shared-memory array, or explicit kernel pass in the source code.</p><p>The physical reduction has not disappeared.</p><p>Responsibility for organizing it has moved into the compiler stack.</p><p>This becomes especially useful for a neighboring operation:</p><pre>@jax.jit<br>def squared_sum(x):<br>    return jnp.sum(x * x)</pre><p>When compatible operations are fused, the implementation may avoid materializing the complete x * x temporary array in global memory.</p><p>My shorthand is:</p><pre>CUDA<br>→ I describe worker-level cooperation</pre><pre>Triton<br>→ I describe tile-level work</pre><pre>JAX<br>→ I describe the mathematical transformation</pre><p>This is not a ranking.</p><p>Higher-level code is not automatically slower, and handwritten CUDA is not automatically faster.</p><p>Each level changes which decisions I control and which decisions I ask a compiler or library to make.</p><h3>Why one sum matters beyond torch.sum()</h3><p>Reduction appears inside many operations used by machine-learning systems:</p><ul><li>Softmax needs maximum and sum reductions.</li><li>RMSNorm reduces squared activations.</li><li>Layer normalization computes means and variances.</li><li>Attention combines values and normalizes scores.</li><li>Loss functions aggregate per-element contributions.</li><li>Gradient calculations accumulate partial results.</li></ul><p>For example, softmax conceptually contains two important reductions:</p><pre>maximum = torch.max(<br>    x,<br>    dim=-1,<br>    keepdim=True<br>).values</pre><pre>exponentials = torch.exp(<br>    x - maximum<br>)</pre><pre>denominator = torch.sum(<br>    exponentials,<br>    dim=-1,<br>    keepdim=True<br>)</pre><pre>output = exponentials / denominator</pre><p>Both the maximum and denominator calculations are reductions.</p><p>The implementation may be more sophisticated and fused, but the same questions remain:</p><ul><li>What does one thread own?</li><li>Which values should remain in registers?</li><li>When must lanes exchange values?</li><li>When must warps communicate through shared memory?</li><li>When is a global-memory write necessary?</li><li>Can adjacent operations be fused?</li></ul><h3>How this connects to vLLM</h3><p>Inference systems such as vLLM repeatedly execute operations involving:</p><ul><li>Attention</li><li>Normalization</li><li>Sampling</li><li>Quantization</li><li>Tensor transformations</li><li>Reduction and aggregation</li></ul><p>A simple sum is not the final destination.</p><p>It is a small laboratory for understanding the communication patterns used by much larger inference workloads.</p><p>Knowing warp reduction does not mean we must manually rewrite every PyTorch operation in CUDA. It gives us a mental model for understanding why optimized kernels, Triton, compilation, and fusion matter.</p><h3>What should be measured before claiming performance?</h3><p>I intentionally avoid inventing benchmark numbers.</p><p>A responsible CUDA, Triton, JAX, or PyTorch comparison should use:</p><ol><li>The same physical GPU.</li><li>Equivalent inputs.</li><li>The same data type.</li><li>Warm-up runs.</li><li>Proper GPU synchronization.</li><li>Multiple timing samples.</li><li>A median rather than one lucky result.</li><li>Several input sizes.</li><li>A higher-precision correctness reference.</li><li>Recorded framework, compiler, CUDA, driver, and GPU versions.</li></ol><p>The performance ranking can change with the input size and hardware.</p><p>The central claim of this article is not that one programming system always wins.</p><p>The claim is that all of them must eventually solve the same ownership and communication problem.</p><h3>What I learned</h3><p>I started with the belief that GPU programming was mainly about creating parallel work.</p><p>I ended with a different mental model:</p><blockquote><em>Parallel work is only the beginning. A fast kernel also needs a plan for ownership, locality, and communication.</em></blockquote><p>In the CUDA reduction, that plan is visible:</p><pre>Global input<br>      ↓<br>Private register sums<br>      ↓<br>Warp shuffle reductions<br>      ↓<br>Shared warp sums<br>      ↓<br>Block partials in global memory<br>      ↓<br>Additional kernel passes<br>      ↓<br>One scalar</pre><p>Triton preserves the tiled structure while hiding much of the lane-level choreography.</p><p>JAX preserves the mathematical intent while asking the compiler to choose even more of the execution strategy.</p><p>PyTorch gives us the productive interface from which many developers begin:</p><pre>result = torch.sum(x)</pre><p>The sentence I now carry into other GPU problems is:</p><blockquote><em>First decide where the data should live. Then decide who needs to communicate. Only then decide how many threads to launch.</em></blockquote><h3>References</h3><ul><li><a href="https://docs.nvidia.com/cuda/cuda-programming-guide/pdf/cuda-programming-guide.pdf">NVIDIA CUDA C++ Programming Guide: Warp Shuffle Functions</a></li><li><a href="https://docs.nvidia.com/cuda/cuda-programming-guide/02-basics/writing-cuda-kernels.html">NVIDIA CUDA Programming Guide: Writing SIMT Kernels</a></li><li><a href="https://docs.pytorch.org/docs/stable/generated/torch.sum.html">PyTorch documentation: </a><a href="https://docs.pytorch.org/docs/stable/generated/torch.sum.html">torch.sum</a></li><li><a href="https://docs.pytorch.org/docs/stable/generated/torch.compile.html">PyTorch documentation: </a><a href="https://docs.pytorch.org/docs/stable/generated/torch.compile.html">torch.compile</a></li><li><a href="https://triton-lang.org/main/programming-guide/chapter-1/introduction.html">Triton Programming Guide</a></li><li><a href="https://docs.jax.dev/en/latest/201/jit.html">JAX documentation: Just-in-time compilation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce185916ce7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Maintainable RAG Application Using SOLID Principles]]></title>
            <link>https://medium.com/@psvsaishwarya/building-a-maintainable-rag-application-using-solid-principles-32a7a816a6b0?source=rss-53307ac94e90------2</link>
            <guid isPermaLink="false">https://medium.com/p/32a7a816a6b0</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[AISHWARYA P.S.V.S]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 12:25:47 GMT</pubDate>
            <atom:updated>2026-08-30T12:25:47.450Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern RAG applications are often created as one large script:</p><pre>Load documents<br>→ Create embeddings<br>→ Retrieve documents<br>→ Rerank results<br>→ Call the LLM<br>→ Evaluate the answer</pre><p>This approach may work for a demo, but it becomes difficult to test, maintain, and extend.</p><p>In this article, we will design a small RAG application using SOLID principles. The complete application is available on GitHub:</p><p><a href="https://github.com/aishwaryatesting/solidprinciples_best/blob/main/app.py">View the complete application on GitHub</a></p><h3>What is RAG?</h3><p>Retrieval-Augmented Generation combines document retrieval with language-model generation.</p><pre>User question<br>    ↓<br>Retrieve relevant documents<br>    ↓<br>Rerank the documents<br>    ↓<br>Send the best context to the LLM<br>    ↓<br>Generate an answer</pre><p>The retriever finds possible evidence. The re-ranker improves the order of that evidence. The generator creates the final response.</p><h3>The problem with a monolithic RAG application</h3><p>A basic implementation may look like this:</p><pre>class RAGBot:<br>    def answer(self, question):<br>        documents = retrieve_documents(question)<br>        documents = rerank_documents(question, documents)<br>        prompt = build_prompt(question, documents)<br>        answer = call_llm(prompt)<br>        return evaluate(answer)</pre><p>This class is responsible for retrieval, reranking, prompt construction, generation, and evaluation.</p><p>This creates several problems:</p><ul><li>It is difficult to test each part separately.</li><li>Changing the vector database can affect the entire application.</li><li>Replacing the LLM requires modifying the main logic.</li><li>There is no clear contract between components.</li><li>Retrieval and generation become tightly coupled.</li></ul><p>SOLID principles help us create a cleaner design.</p><h3>Applying SOLID to RAG</h3><p>The application separates the system into these components:</p><pre>Retriever<br>Reranker<br>Generator<br>Evaluator<br>Workflow</pre><p>Each component has a specific responsibility.</p><h3>Single Responsibility Principle</h3><p>The Single Responsibility Principle says that a class should have one main reason to change.</p><p>In our application:</p><pre>class KeywordRetriever:<br>    def retrieve(self, query, k=5):<br>        ...</pre><p>The retriever only searches for relevant documents.</p><pre>class TermReranker:<br>    def rerank(self, query, documents):<br>        ...</pre><p>The reranker only changes the document order.</p><pre>class GroundedGenerator:<br>    def stream(self, query, documents):<br>        ...</pre><p>The generator only creates the answer.</p><pre>class SimpleEvaluator:<br>    def evaluate(self, answer, documents):<br>        ...</pre><p>The evaluator only checks whether the answer is supported by retrieved evidence.</p><p>This makes the application easier to understand and test.</p><h3>Open/Closed Principle</h3><p>The Open/Closed Principle says that software should be open for extension but closed for modification.</p><p>The workflow depends on a retriever interface:</p><pre>class Retriever(Protocol):<br>    def retrieve(self, query: str, k: int = 5):<br>        ...</pre><p>We can add new implementations:</p><pre>KeywordRetriever<br>BM25Retriever<br>DenseRetriever<br>HybridRetriever</pre><p>The main workflow does not need to be rewritten.</p><p>In a production application, the simple keyword retriever could be replaced with a LangChain retriever or a vector database such as Qdrant, Chroma, or Pinecone.</p><h3>Liskov Substitution Principle</h3><p>The Liskov Substitution Principle says that different implementations should be interchangeable when they follow the same contract.</p><p>Every retriever should:</p><pre>Receive a query<br>Receive a value of k<br>Return a list of documents</pre><p>This allows the workflow to use different retrievers safely:</p><pre>documents = self.retriever.retrieve(question, k=5)</pre><p>The workflow does not need to know whether the documents came from BM25, vector search, or hybrid search.</p><h3>Interface Segregation Principle</h3><p>The Interface Segregation Principle says that components should not be forced to depend on methods they do not use.</p><p>Instead of creating one large interface:</p><pre>class AIComponent:<br>    def embed(self): ...<br>    def retrieve(self): ...<br>    def rerank(self): ...<br>    def generate(self): ...<br>    def evaluate(self): ...</pre><p>we use smaller interfaces:</p><pre>class Retriever(Protocol):<br>    def retrieve(self, query, k):<br>        ...<br></pre><pre>class Reranker(Protocol):<br>    def rerank(self, query, documents):<br>        ...<br></pre><pre>class Generator(Protocol):<br>    def stream(self, query, documents):<br>        ...<br></pre><pre>class Evaluator(Protocol):<br>    def evaluate(self, answer, documents):<br>        ...</pre><p>A reranker only needs to rerank. It does not need to generate answers or create embeddings.</p><h3>Dependency Inversion Principle</h3><p>The Dependency Inversion Principle says that high-level logic should depend on abstractions rather than specific tools.</p><p>The workflow receives its dependencies through the constructor:</p><pre>class RAGWorkflow:<br>    def __init__(<br>        self,<br>        retriever,<br>        reranker,<br>        generator,<br>        evaluator<br>    ):<br>        self.retriever = retriever<br>        self.reranker = reranker<br>        self.generator = generator<br>        self.evaluator = evaluator</pre><p>We can configure it like this:</p><pre>workflow = RAGWorkflow(<br>    retriever=KeywordRetriever(documents),<br>    reranker=TermReranker(),<br>    generator=GroundedGenerator(config),<br>    evaluator=SimpleEvaluator()<br>)</pre><p>Later, we can replace the components:</p><pre>workflow = RAGWorkflow(<br>    retriever=HybridRetriever(),<br>    reranker=ColBERTReranker(),<br>    generator=LocalLLMGenerator(config),<br>    evaluator=RagasEvaluator()<br>)</pre><p>The orchestration logic remains the same.</p><h3>Why use @dataclass(frozen=True)?</h3><p>The application defines a document using:</p><pre>@dataclass(frozen=True)<br>class Document:<br>    id: str<br>    text: str<br>    metadata: dict[str, str]</pre><p>@dataclass automatically creates useful methods such as:</p><pre>__init__()<br>__repr__()<br>__eq__()</pre><p>It allows us to create a document clearly:</p><pre>document = Document(<br>    id=&quot;refund&quot;,<br>    text=&quot;Annual subscriptions can be refunded within 30 days.&quot;,<br>    metadata={&quot;title&quot;: &quot;Refund Policy&quot;}<br>)</pre><p>frozen=True prevents reassignment of the document fields:</p><pre>document.text = &quot;New text&quot;  # Raises an error</pre><p>This is useful because retrieved documents should not accidentally be modified during the RAG workflow.</p><h3>Generators for streaming answers</h3><p>The generator uses yield:</p><pre>def stream(self, query, documents):<br>    answer = &quot;Annual subscriptions can be refunded within 30 days.&quot;</pre><pre>    for token in answer.split():<br>        yield token</pre><p>The answer is produced one token at a time:</p><pre>for token in workflow.stream(question):<br>    print(token, end=&quot; &quot;, flush=True)</pre><p>This is useful for LLM applications because users do not have to wait for the complete answer.</p><p>The flow is:</p><pre>Generate token<br>→ yield token<br>→ display token<br>→ generate next token</pre><h3>Decorators for measuring latency</h3><p>The application also uses a timing decorator:</p><pre>@timed<br>def retrieve_and_rank(self, question):<br>    candidates = self.retriever.retrieve(question)<br>    return self.reranker.rerank(question, candidates)</pre><p>The decorator measures how long retrieval and reranking take.</p><pre>def timed(func):<br>    @wraps(func)<br>    def wrapper(*args, **kwargs):<br>        started = time.perf_counter()<br>        result = func(*args, **kwargs)<br>        elapsed = time.perf_counter() - started<br>        return result, elapsed * 1000</pre><pre>    return wrapper</pre><p>This helps us measure latency before the first generated token.</p><h3>Temperature and generation</h3><p>Temperature controls randomness during LLM generation.</p><pre>Temperature 0.0 → deterministic output<br>Temperature 0.2 → focused factual answer<br>Temperature 0.8 → more creative answer</pre><p>For factual RAG answers, a low temperature is usually preferable:</p><pre>GenerationConfig(<br>    temperature=0.2,<br>    max_tokens=120<br>)</pre><p>Temperature affects generation. It does not improve retrieval or reranking.</p><h3>Evaluation</h3><p>The application checks whether the answer is grounded in retrieved evidence:</p><pre>grounded = bool(documents) and documents[0].text in answer</pre><p>A production system could use more advanced metrics:</p><pre>Recall@K<br>MRR<br>NDCG<br>Faithfulness<br>Answer relevance<br>Citation correctness<br>Time to first token<br>Tokens per second</pre><p>A correct RAG system should answer not only fluently, but also with evidence.</p><h3>Final architecture</h3><pre>Question<br>   ↓<br>Retriever<br>   ↓<br>Reranker<br>   ↓<br>Generator<br>   ↓<br>Evaluator<br>   ↓<br>Grounded answer</pre><p>SOLID principles make each stage independent and replaceable.</p><pre>Retriever  → finds evidence<br>Reranker   → improves ordering<br>Generator  → creates response<br>Evaluator  → checks correctness<br>Workflow   → coordinates the process</pre><h3>Conclusion</h3><p>SOLID principles do not make the language model more intelligent. They make the system around the model easier to maintain, test, replace, and evaluate.</p><p>The complete working example is available here:</p><p><a href="https://github.com/aishwaryatesting/solidprinciples_best/blob/main/app.py">GitHub repository: SOLID RAG Application</a></p><p>My linkeldn:<a href="https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/">https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32a7a816a6b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude, Codex, Hermes, Pi, OpenHands, and OpenCode]]></title>
            <link>https://medium.com/@psvsaishwarya/claude-codex-hermes-pi-openhands-and-opencode-0892d19a0cf0?source=rss-53307ac94e90------2</link>
            <guid isPermaLink="false">https://medium.com/p/0892d19a0cf0</guid>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[agentic-harness]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[AISHWARYA P.S.V.S]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 13:40:42 GMT</pubDate>
            <atom:updated>2026-08-19T13:40:42.930Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Practical Comparison of AI Agent Harnesses</h3><p>This article compares how several popular agent systems approach those components.</p><p>The comparison should not be viewed as a competition with one universal winner.</p><p>Different harnesses optimize for different environments:</p><ul><li>Coding</li><li>Personal assistance</li><li>Research</li><li>Terminal workflows</li><li>Repository automation</li><li>Sandboxed software development</li><li>Tool-driven enterprise operations</li></ul><p>The right choice depends on the task, security requirements, memory model, and level of customization required.</p><h3>Claude Code</h3><p>Claude Code is a coding-oriented agent harness designed to work with repositories, terminals, files, tools, and project instructions.</p><p>Common customization components include:</p><ul><li>CLAUDE.md</li><li>Skills</li><li>Subagents</li><li>MCP servers</li><li>Hooks</li><li>Plugins</li><li>Permission controls</li></ul><p>A typical workflow may look like:</p><pre>Read CLAUDE.md<br>     │<br>     ▼<br>Inspect repository<br>     │<br>     ▼<br>Use skills and tools<br>     │<br>     ▼<br>Modify files<br>     │<br>     ▼<br>Run validation</pre><h3>Strengths</h3><p>Claude Code is useful when a project requires:</p><ul><li>Repository-aware coding</li><li>Reusable skills</li><li>Tool integrations</li><li>Subagent delegation</li><li>Automated hooks</li><li>Interactive development</li></ul><h3>Example configuration</h3><pre>CLAUDE.md<br>  → project rules</pre><pre>SKILL.md<br>  → code-review workflow</pre><pre>MCP<br>  → external database or documentation</pre><pre>Hook<br>  → run tests after edits</pre><h3>Important design principle</h3><p>A project instruction file should explain the repository.</p><p>A skill should explain a repeatable task.</p><p>A hook should enforce a deterministic rule.</p><h3>Codex</h3><p>Codex-style coding harnesses commonly use repository instructions such as AGENTS.md.</p><p>The file may describe:</p><ul><li>Project architecture</li><li>Coding conventions</li><li>Testing commands</li><li>Directory-specific rules</li><li>Validation requirements</li><li>Safe operating boundaries</li></ul><p>A repository may contain instructions at different levels:</p><pre>Global instructions<br>       │<br>       ▼<br>Repository instructions<br>       │<br>       ▼<br>Directory instructions<br>       │<br>       ▼<br>File-specific context</pre><p>The agent should use the most relevant instructions for the current file and task.</p><h3>Strengths</h3><p>Codex-style workflows are useful for:</p><ul><li>Repository changes</li><li>Controlled shell execution</li><li>Code analysis</li><li>Testing</li><li>Reviewable diffs</li><li>Structured development tasks</li></ul><h3>Typical workflow</h3><pre>Understand task<br>     │<br>     ▼<br>Inspect instructions<br>     │<br>     ▼<br>Search codebase<br>     │<br>     ▼<br>Plan change<br>     │<br>     ▼<br>Edit files<br>     │<br>     ▼<br>Run tests<br>     │<br>     ▼<br>Review diff</pre><p>The important concept is that the agent should not modify files blindly. It should first understand the local project rules and validate the result afterward.</p><h3>Hermes</h3><p>Hermes is designed around a more persistent personal-agent model.</p><p>Common concepts include:</p><ul><li>SOUL.md</li><li>USER.md</li><li>MEMORY.md</li><li>SKILL.md</li><li>Profiles</li><li>Layered memory</li><li>Session search</li><li>SQLite FTS5</li><li>Context compression</li><li>Prompt caching</li><li>Long-running interactions</li></ul><p>A simplified Hermes-style memory model is:</p><pre>Identity<br>   │<br>   ▼<br>User Preferences<br>   │<br>   ▼<br>Long-Term Memory<br>   │<br>   ▼<br>Current Session<br>   │<br>   ▼<br>Current Task</pre><h3>SOUL.md</h3><p>Defines identity and behavioral preferences.</p><pre>Be honest about uncertainty.<br>Prefer concise answers.<br>Do not claim that an action succeeded without validation.<br>Ask before external side effects.</pre><h3>USER.md</h3><p>Stores stable user preferences.</p><pre>The user prefers:<br>- Practical examples<br>- Clear diagrams<br>- Python code<br>- Minimal repetition</pre><h3>MEMORY.md</h3><p>Stores selected durable facts.</p><pre>The project uses PostgreSQL.<br>Authentication uses JWT.<br>Deployment occurs through GitHub Actions.</pre><h3>Layered memory</h3><p>A layered memory system may separate:</p><pre>Short-term context<br>Session history<br>Task checkpoints<br>Project memory<br>User preferences<br>Long-term facts</pre><p>This is preferable to placing every past interaction into one massive prompt.</p><h3>Context compression</h3><p>Long-running agents eventually need to compact old context.</p><p>A typical strategy is:</p><pre>Protect system rules<br>Protect recent task state<br>Summarize older reasoning<br>Remove duplicate tool output<br>Preserve important decisions and evidence</pre><p>Hermes-like systems are especially interesting for studying persistent identity, memory, and context management.</p><h3>Pi</h3><p>Pi is a lightweight, terminal-oriented coding-agent environment.</p><p>Possible customization components include:</p><ul><li>AGENTS.md</li><li>CLAUDE.md</li><li>.pi/SYSTEM.md</li><li>Skills</li><li>Extensions</li><li>Sessions</li><li>Compaction</li><li>Project-level configuration</li></ul><p>Pi-style systems are useful when developers want a smaller and more composable environment.</p><h3>Strengths</h3><p>Pi can be useful for:</p><ul><li>Terminal-based development</li><li>Lightweight workflows</li><li>Custom extensions</li><li>Session control</li><li>Local project instructions</li><li>Developer experimentation</li></ul><h3>Compaction</h3><p>Long sessions can be compacted by:</p><ul><li>Preserving recent context</li><li>Summarizing older messages</li><li>Removing repetitive tool output</li><li>Keeping active files and decisions</li><li>Retaining unresolved errors</li></ul><p>A compaction result might look like:</p><pre>{<br>  &quot;goal&quot;: &quot;Fix token expiration bug&quot;,<br>  &quot;files_changed&quot;: [<br>    &quot;src/auth.py&quot;,<br>    &quot;tests/test_auth.py&quot;<br>  ],<br>  &quot;decisions&quot;: [<br>    &quot;Use UTC timestamps&quot;<br>  ],<br>  &quot;current_failure&quot;: &quot;Expired token returns HTTP 500&quot;,<br>  &quot;next_action&quot;: &quot;Normalize exception handling&quot;<br>}</pre><p>Pi does not automatically provide the same isolation as a full sandbox. Safe execution still depends on operating-system permissions, tool configuration, and the environment in which it runs.</p><h3>OpenHands</h3><p>OpenHands is designed for software-engineering tasks and controlled execution.</p><p>Common concepts include:</p><ul><li>Sandboxed runtimes</li><li>Repository operations</li><li>Shell tools</li><li>Browser tools</li><li>Event streams</li><li>Security analysis</li><li>Confirmation policies</li><li>Tool execution</li></ul><p>A typical OpenHands workflow may look like:</p><pre>Task<br> │<br> ▼<br>Agent observes repository<br> │<br> ▼<br>Agent proposes action<br> │<br> ▼<br>Runtime executes action<br> │<br> ▼<br>Result returns as event<br> │<br> ▼<br>Agent continues or revises</pre><h3>Strengths</h3><p>OpenHands is useful when the workflow requires:</p><ul><li>Multiple tool interactions</li><li>Repository modification</li><li>Terminal execution</li><li>Testing</li><li>Isolated environments</li><li>Long-running software tasks</li></ul><h3>Security model</h3><p>A sandbox helps reduce the impact of unsafe commands, but it does not replace:</p><ul><li>Permission controls</li><li>Secret management</li><li>Network restrictions</li><li>Human approval</li><li>Output validation</li><li>Prompt-injection defenses</li></ul><p>A security analyzer may identify suspicious actions, but the execution environment must still enforce the final boundary.</p><h3>OpenCode</h3><p>OpenCode is a configurable agent environment with tools, agents, instructions, MCP integrations, and permission policies.</p><p>A useful permission model is:</p><pre>Allow → run automatically<br>Ask   → request approval<br>Deny  → block the action</pre><p>Example:</p><pre>{<br>  &quot;read_file&quot;: &quot;allow&quot;,<br>  &quot;write_file&quot;: &quot;allow&quot;,<br>  &quot;network_request&quot;: &quot;ask&quot;,<br>  &quot;production_deploy&quot;: &quot;ask&quot;,<br>  &quot;delete_database&quot;: &quot;deny&quot;<br>}</pre><h3>Strengths</h3><p>OpenCode-style configuration is useful for:</p><ul><li>Fine-grained permissions</li><li>Tool control</li><li>Project-level customization</li><li>Multiple agents</li><li>MCP integrations</li><li>Explicit action policies</li></ul><p>The main advantage of granular permissions is that security rules do not need to depend entirely on model behavior.</p><h3>Comparison by Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Te-e87vA0PwBfZ7QpT_qVw.png" /></figure><h3>Same Concepts, Different Names</h3><p>Different tools may use different terminology for similar concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJQVecJdUOmZL74uKF0Qxw.png" /></figure><h3>How to Choose a Harness</h3><p>Choose based on the task rather than popularity.</p><h3>Choose a coding-focused harness when you need:</h3><ul><li>Repository search</li><li>File editing</li><li>Shell tools</li><li>Test execution</li><li>Git workflows</li><li>Code review</li><li>Subagents</li></ul><h3>Choose a persistent personal harness when you need:</h3><ul><li>User preferences</li><li>Long-term memory</li><li>Identity</li><li>Session search</li><li>Personal workflows</li><li>Continuous interaction</li></ul><h3>Choose a sandbox-oriented harness when you need:</h3><ul><li>Autonomous code execution</li><li>Browser automation</li><li>Untrusted repositories</li><li>Isolated runtimes</li><li>Controlled terminals</li></ul><h3>Choose a highly configurable harness when you need:</h3><ul><li>Custom permissions</li><li>MCP integrations</li><li>Pluggable tools</li><li>Multiple agent types</li><li>Organization-specific workflows</li></ul><h3>What All Harnesses Need</h3><p>Regardless of product, a reliable harness should provide:</p><pre>Instructions<br>    +<br>Context management<br>    +<br>Tools<br>    +<br>Permissions<br>    +<br>Memory<br>    +<br>Validation<br>    +<br>Observability</pre><p>Without instructions, the agent lacks project-specific behavior.</p><p>Without context management, the agent becomes overwhelmed.</p><p>Without permissions, the agent may overreach.</p><p>Without validation, the system cannot distinguish success from plausible output.</p><p>Without observability, developers cannot diagnose failures.</p><h3>Final Comparison</h3><p>he tools differ in their emphasis:</p><pre>Claude Code → skills, tools, hooks, and coding workflows<br>Codex       → repository-aware coding and controlled execution<br>Hermes      → identity, memory, and long-running interaction<br>Pi          → lightweight terminal customization<br>OpenHands   → sandboxed autonomous software engineering<br>OpenCode    → configurable tools and permissions</pre><p>These are not completely separate categories.</p><p>A production system may combine ideas from several of them:</p><pre>Claude-style skills<br>+ Codex-style repository instructions<br>+ Hermes-style memory<br>+ Pi-style extensions<br>+ OpenHands-style sandboxing<br>+ OpenCode-style permissions</pre><p>The important lesson is not to copy one tool’s file structure blindly.</p><p>Instead, design the harness around the task:</p><ul><li>What must the agent know?</li><li>What may it access?</li><li>What may it change?</li><li>What must be validated?</li><li>What should be remembered?</li><li>What should be forgotten?</li><li>When should a human approve the action?</li></ul><blockquote><em>The best AI harness is not the one with the most features. It is the one whose instructions, tools, memory, permissions, and validation match the work it must perform.</em></blockquote><h3>References and Further Reading</h3><ul><li><a href="https://docs.anthropic.com/en/docs/claude-code">Claude Code Documentation</a></li><li><a href="https://developers.openai.com/codex/">OpenAI Codex Documentation</a></li><li><a href="https://github.com/NousResearch/hermes-agent">Hermes Agent Repository</a></li><li><a href="https://github.com/badlogic/pi-mono">Pi Coding Agent Repository</a></li><li><a href="https://docs.all-hands.dev/">OpenHands Documentation</a></li><li><a href="https://opencode.ai/docs/">OpenCode Documentation</a></li><li><a href="https://modelcontextprotocol.io/">Model Context Protocol</a></li><li><a href="https://medium.com/%40maclarensg_50191/how-hermes-agent-solves-the-context-window-problem-and-what-every-agent-builder-should-borrow-bf90071f4757">How Hermes Agent Solves the Context Window Problem</a></li><li><a href="https://gyliu513.medium.com/hermes-agent-under-the-hood-stable-prompts-dynamic-capabilities-and-layered-memory-84f06aaa11e1">Hermes Agent Under the Hood</a></li><li><a href="https://medium.com/%40rosgluk/hermes-agent-skill-authoring-skill-md-structure-and-best-practices-32a59d09189b">Hermes Agent Skill Authoring</a></li></ul><p>The explanations, examples, and comparison tables are an original synthesis. No source wording or diagram has been reproduced directly.</p><p>My Linkeldn url:<a href="https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/">https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0892d19a0cf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4: The Inference Engine]]></title>
            <link>https://medium.com/@psvsaishwarya/part-4-the-inference-engine-604d918e22ce?source=rss-53307ac94e90------2</link>
            <guid isPermaLink="false">https://medium.com/p/604d918e22ce</guid>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[agentic-harness]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <dc:creator><![CDATA[AISHWARYA P.S.V.S]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 12:49:56 GMT</pubDate>
            <atom:updated>2026-08-13T12:49:56.887Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Prefill to Decode: How AI Agents Actually Run</h3><p>In the previous parts, we discussed how an agent retrieves context, shares information between subagents, and executes tools safely.</p><p>Now we need to understand what happens after the harness sends the final context to the language model.</p><p>The model does not process a request as one single operation. Inference usually has two major phases:</p><ol><li>Prefill</li><li>Decode</li></ol><p>Understanding these phases helps explain:</p><ul><li>Why long prompts increase time to first token</li><li>Why long answers increase total latency</li><li>How KV-cache works</li><li>Why prompt caching is useful</li><li>How GPU utilization affects performance</li><li>Where FlashAttention helps</li><li>Why speculative decoding mainly improves generation speed</li><li>How harness engineering improves inference efficiency</li></ul><h3>What Is Inference?</h3><p>Inference is the process of using a trained model to generate an output for a new input.</p><p>A simplified flow is:</p><pre>User Request<br>     │<br>     ▼<br>Tokenization<br>     │<br>     ▼<br>Prompt Tokens<br>     │<br>     ▼<br>Model Inference<br>     │<br>     ▼<br>Generated Tokens<br>     │<br>     ▼<br>Final Response</pre><p>For example:</p><pre>User text:<br>&quot;Find the authentication bug&quot;</pre><pre>Tokens:<br>[Find, the, authentication, bug]</pre><p>The model does not directly process words as humans understand them. It processes token IDs and converts them into numerical representations.</p><h3>Tokenization</h3><p>Tokenization converts text into smaller units called tokens.</p><p>A token may represent:</p><ul><li>A complete word</li><li>Part of a word</li><li>Punctuation</li><li>Whitespace</li><li>A programming symbol</li><li>A code fragment</li></ul><p>For example:</p><pre>&quot;authentication&quot;</pre><p>might be represented as one token or several subword tokens, depending on the tokenizer.</p><p>Source code can require many tokens because it contains:</p><ul><li>Indentation</li><li>Brackets</li><li>Operators</li><li>Variable names</li><li>File paths</li><li>Repeated syntax</li><li>Long identifiers</li></ul><p>A context containing 20,000 words does not necessarily equal 20,000 tokens.</p><p>The actual cost depends on the tokenizer and the content.</p><h3>The Complete Agent Inference Flow</h3><p>A coding agent may send a request containing:</p><pre>System instructions<br>+ Project rules<br>+ User request<br>+ Conversation summary<br>+ Retrieved source files<br>+ Tool definitions<br>+ Previous test results<br>+ Handoff information</pre><p>The model processes this context as follows:</p><pre>┌─────────────────────────────┐<br>│ System and project rules    │<br>├─────────────────────────────┤<br>│ User request                │<br>├─────────────────────────────┤<br>│ Retrieved evidence          │<br>├─────────────────────────────┤<br>│ Tool definitions            │<br>├─────────────────────────────┤<br>│ Current task state          │<br>└──────────────┬──────────────┘<br>               ▼<br>          Tokenization<br>               │<br>               ▼<br>             Prefill<br>               │<br>               ▼<br>           KV-cache<br>               │<br>               ▼<br>             Decode<br>               │<br>               ▼<br>        Tool call or response</pre><h3>Phase 1: Prefill</h3><h3>What Is Prefill?</h3><p>Prefill is the phase in which the model processes the input prompt before generating the first output token.</p><p>If the prompt contains 20,000 tokens, the model processes those tokens during prefill.</p><pre>Input tokens:<br>[1, 2, 3, 4, 5, ..., 20,000]<br>                │<br>                ▼<br>             Prefill<br>                │<br>                ▼<br>       Internal attention state</pre><p>During prefill, the model creates internal representations for the entire input sequence.</p><p>This is why a longer prompt usually increases:</p><ul><li>Time to first token</li><li>GPU memory usage</li><li>Prompt-processing cost</li><li>Initial request latency</li></ul><h3>Prefill and Context Length</h3><p>Suppose the harness sends:</p><pre>2,000 tokens</pre><p>The prefill phase is usually much shorter than when it sends:</p><pre>20,000 tokens</pre><p>A larger context means more information must be processed before the model can start responding.</p><p>Example:</p><pre>Input context: 2,000 tokens<br>Prefill latency: 300 ms</pre><pre>Input context: 20,000 tokens<br>Prefill latency: 2,500 ms</pre><p>The exact relationship depends on:</p><ul><li>Model architecture</li><li>GPU</li><li>Batch size</li><li>Sequence length</li><li>Attention implementation</li><li>Quantization</li><li>Memory bandwidth</li><li>Server scheduling</li></ul><h3>What Is TTFT?</h3><p>TTFT means Time to First Token.</p><p>It measures the time between receiving a request and producing the first generated token.</p><pre>TTFT =<br>queue latency<br>+ request preparation<br>+ tokenization<br>+ prefill<br>+ scheduling overhead<br>+ first decode step</pre><p>A useful approximation is:</p><pre>TTFT ≈ Queue latency + Prefill latency + First-token overhead</pre><p>Example:</p><pre>Queue latency:       100 ms<br>Tokenization:         50 ms<br>Prefill:            2,500 ms<br>First-token work:     350 ms<br>──────────────────────────────<br>TTFT:              3,000 ms</pre><p>If TTFT is high, the user waits a long time before seeing any response.</p><h3>Phase 2: Decode</h3><h3>What Is Decode?</h3><p>Decode is the autoregressive generation phase.</p><p>The model generates one token, then uses that token to generate the next token.</p><pre>Prompt → Token 1 → Token 2 → Token 3 → Token 4</pre><p>The process is sequential:</p><pre>Generate token 1<br>       │<br>       ▼<br>Use token 1 to generate token 2<br>       │<br>       ▼<br>Use token 2 to generate token 3<br>       │<br>       ▼<br>Continue until stopping</pre><p>This is different from prefill, where the model processes many input tokens in parallel.</p><h3>Why Decode Is Sequential</h3><p>At each step, the model must determine the probability of the next token based on all previous tokens.</p><p>For example:</p><pre>The authentication function returns the</pre><p>The model may predict:</p><pre>payload</pre><p>After generating payload, it predicts the next token.</p><p>This dependency makes decode harder to parallelize than prefill.</p><h3>Decode Latency</h3><p>If the model produces 50 tokens per second and must generate 500 tokens:</p><pre>Decode time =<br>500 tokens ÷ 50 tokens per second<br>= 10 seconds</pre><p>Total response time is approximately:</p><pre>End-to-end latency =<br>queue latency<br>+ prefill latency<br>+ decode latency<br>+ tool latency<br>+ network overhead</pre><p>Example:</p><pre>Queue latency:      100 ms<br>Prefill latency:  2,500 ms<br>Decode latency:   5,000 ms<br>Tool latency:       800 ms<br>────────────────────────────<br>E2E latency:      8,400 ms</pre><h3>Prefill Versus Decode</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkOrFwSA_Ay4hLqnG4BHRw.png" /></figure><p>If TTFT is high, investigate prefill and queueing.</p><p>If output generation is slow, investigate decode performance.</p><h3>The KV-Cache</h3><h3>What Is the KV-Cache?</h3><p>During attention, the model creates key and value representations for tokens.</p><p>These are stored in a key-value cache, commonly called the KV-cache.</p><p>Without a KV-cache, the model would repeatedly recompute previous tokens during every decode step.</p><pre>Without KV-cache:<br>Step 1 → process previous context<br>Step 2 → process previous context again<br>Step 3 → process previous context again</pre><p>With a KV-cache:</p><pre>Prefill → store key/value states<br>Decode  → reuse previous key/value states</pre><pre>Prompt<br>  │<br>  ▼<br>Prefill<br>  │<br>  ▼<br>┌────────────────┐<br>│ KV-cache       │<br>│ Previous state │<br>└───────┬────────┘<br>        ▼<br>Decode uses cached state</pre><h3>Why KV-Cache Matters</h3><p>The KV-cache can improve decode speed, but it consumes GPU memory.</p><p>Its memory usage depends on:</p><ul><li>Number of layers</li><li>Number of attention heads</li><li>Head dimension</li><li>Sequence length</li><li>Batch size</li><li>Data type</li><li>Number of active requests</li></ul><p>A simplified relationship is:</p><pre>KV-cache memory ∝<br>number of tokens<br>× number of layers<br>× attention dimensions<br>× bytes per value</pre><p>Longer contexts require larger KV-caches.</p><p>This creates a trade-off:</p><pre>More context<br>    ↓<br>More KV-cache memory<br>    ↓<br>Fewer concurrent requests<br>    ↓<br>Higher queue latency</pre><h3>KV-Cache in Multi-Agent Systems</h3><p>Each active agent session may require its own KV-cache.</p><pre>Agent 1 → KV-cache 1<br>Agent 2 → KV-cache 2<br>Agent 3 → KV-cache 3</pre><p>If Agent 1 finishes, its cache can usually be released or evicted.</p><p>However, durable information should first be saved as:</p><ul><li>A structured handoff</li><li>A task checkpoint</li><li>A summary</li><li>A database record</li><li>A file-state record</li></ul><pre>Agent 1 KV-cache<br>       │<br>       ├── release after completion<br>       │<br>       └── preserve important state externally</pre><p>Releasing a KV-cache does not mean losing the task if the important state was persisted.</p><h3>Prompt Caching</h3><h3>What Is Prompt Caching?</h3><p>Many agent requests contain a stable prefix.</p><p>For example:</p><pre>System instructions<br>+ tool definitions<br>+ project rules<br>+ repository conventions</pre><p>That prefix may be repeated across many requests.</p><p>Prompt caching allows the system to reuse processing for a stable part of the prompt.</p><pre>Request 1:<br>Stable prefix + User task A</pre><pre>Request 2:<br>Stable prefix + User task B</pre><pre>Request 3:<br>Stable prefix + User task C</pre><p>Instead of processing the stable prefix from the beginning every time, the model-serving system may reuse cached internal state, depending on the provider and serving architecture.</p><h3>Good Candidates for Prompt Caching</h3><p>Prompt caching is useful for:</p><ul><li>Stable system instructions</li><li>Long tool definitions</li><li>Repository rules</li><li>Large static documentation</li><li>Shared project context</li><li>Agent identity</li><li>Repeated policy text</li></ul><p>Dynamic information should generally be placed after the stable prefix:</p><pre>Stable prefix<br>     │<br>     ▼<br>Cached instructions and tools<br>     │<br>     ▼<br>Dynamic user request<br>Dynamic retrieval results<br>Dynamic tool output</pre><p>This can improve:</p><ul><li>TTFT</li><li>Prompt-processing cost</li><li>Throughput</li><li>Resource utilization</li></ul><p>The exact caching behavior depends on the model provider and API.</p><h3>FlashAttention</h3><h3>What Is FlashAttention?</h3><p>FlashAttention is an optimized attention implementation designed to reduce inefficient memory movement on GPUs.</p><p>Traditional attention may require materializing a large attention matrix in GPU memory.</p><p>FlashAttention uses techniques such as:</p><ul><li>Tiling</li><li>On-chip memory reuse</li><li>Fused operations</li><li>Reduced intermediate memory writes</li></ul><pre>Traditional attention:<br>Read → compute → write large matrix → read again</pre><pre>FlashAttention:<br>Read tiles → compute locally → write fewer intermediates</pre><p>This improves the efficiency of attention computation.</p><h3>What FlashAttention Improves</h3><p>FlashAttention can improve:</p><ul><li>Attention throughput</li><li>GPU memory efficiency</li><li>Prefill performance</li><li>Long-sequence processing</li><li>Training and inference efficiency</li></ul><p>It is especially relevant when the input context is large.</p><h3>What FlashAttention Does Not Do</h3><p>FlashAttention does not:</p><ul><li>Remove tokens from the prompt</li><li>Summarize conversation history</li><li>Select relevant documents</li><li>Prevent prompt injection</li><li>Replace retrieval</li><li>Automatically reduce logical context length</li><li>Guarantee lower total latency in every workload</li></ul><p>The distinction is important:</p><pre>Context compression:<br>Fewer logical tokens</pre><pre>FlashAttention:<br>More efficient processing of the same attention operation</pre><p>A harness may use both:</p><pre>Retrieve fewer tokens<br>     +<br>Process them more efficiently</pre><h3>Quantization</h3><h3>What Is Quantization?</h3><p>Quantization represents model weights or activations using lower numerical precision.</p><p>Common formats include:</p><ul><li>FP32</li><li>FP16</li><li>BF16</li><li>INT8</li><li>INT4</li></ul><pre>FP16 → lower memory than FP32<br>INT8 → lower memory than FP16<br>INT4 → lower memory than INT8</pre><p>Quantization can reduce:</p><ul><li>Model memory</li><li>Memory bandwidth</li><li>Inference cost</li><li>Hardware requirements</li></ul><h3>Quantization Trade-offs</h3><p>Quantization may affect:</p><ul><li>Accuracy</li><li>Reasoning quality</li><li>Tool-call reliability</li><li>Code generation</li><li>Long-context behavior</li><li>Numerical stability</li></ul><p>A lower-precision model is not automatically better.</p><p>It should be evaluated on the actual workload.</p><pre>Performance gain<br>        versus<br>Quality loss</pre><p>Useful evaluation tasks include:</p><ul><li>Code repair</li><li>Retrieval-grounded answers</li><li>Tool selection</li><li>Structured JSON generation</li><li>Long-context question answering</li><li>Security classification</li></ul><h3>Speculative Decoding</h3><h3>What Is Speculative Decoding?</h3><p>Speculative decoding uses two models:</p><ul><li>A smaller draft model</li><li>A larger target model</li></ul><p>The draft model quickly proposes several tokens.</p><p>The target model verifies those tokens.</p><pre>Prompt<br>  │<br>  ▼<br>Draft Model<br>  │<br>  ├── proposes token 1<br>  ├── proposes token 2<br>  ├── proposes token 3<br>  └── proposes token 4<br>          │<br>          ▼<br>Target Model verifies proposal<br>          │<br>          ▼<br>Accepted tokens are emitted</pre><p>If many draft tokens are accepted, the target model can generate output faster.</p><h3>When Speculative Decoding Helps</h3><p>It is useful when:</p><ul><li>The draft model is much faster</li><li>The draft and target models produce similar continuations</li><li>The output is long enough to benefit</li><li>Verification is efficient</li><li>The workload is decode-bound</li></ul><p>It may be less useful when:</p><ul><li>The draft model is poor</li><li>Many proposed tokens are rejected</li><li>The output is very short</li><li>The workload is dominated by prefill</li><li>Tool calls interrupt generation frequently</li></ul><h3>What Speculative Decoding Does Not Improve</h3><p>Speculative decoding primarily improves decode speed.</p><p>It does not directly solve:</p><ul><li>Excessively long prompts</li><li>Poor retrieval</li><li>High prefill latency</li><li>Large tool definitions</li><li>Context-window overflow</li><li>Prompt poisoning</li><li>Incorrect handoffs</li></ul><p>Therefore:</p><pre>Long prompt problem → context optimization<br>Slow generation problem → speculative decoding</pre><h3>Sliding-Window Attention</h3><h3>What Is Sliding-Window Attention?</h3><p>Sliding-window attention limits the amount of context each token attends to.</p><p>Instead of attending to every previous token, a token attends mainly to a nearby window.</p><pre>Full attention:</pre><pre>Token 1 ↔ Token 2 ↔ Token 3 ↔ ... ↔ Token 10000</pre><pre>Sliding window:</pre><pre>Token 5000 attends mainly to:<br>Token 4900 ... Token 5100</pre><p>This can reduce the cost of very long sequences.</p><h3>Benefits</h3><p>Sliding-window attention may provide:</p><ul><li>Lower memory usage</li><li>Lower attention computation</li><li>Better scalability for long sequences</li><li>More predictable resource usage</li></ul><h3>Risks</h3><p>Important information may be far outside the local window.</p><p>For example:</p><pre>A security rule appears at token 100.<br>The agent acts at token 20,000.</pre><p>If the model cannot access the earlier rule, it may make an incorrect decision.</p><p>Sliding-window attention should therefore be combined with:</p><ul><li>Summaries</li><li>Retrieval</li><li>Important-fact pinning</li><li>Global tokens</li><li>Structured state</li><li>Checkpoints</li></ul><p>It also depends on the model architecture. It is not something an external harness can safely enable for every model.</p><h3>Continuous Batching</h3><h3>What Is Batching?</h3><p>Batching processes multiple requests together.</p><pre>Request A<br>Request B<br>Request C<br>        │<br>        ▼<br>     GPU batch</pre><p>Batching improves hardware utilization, but agent requests have different lengths and completion times.</p><p>Traditional static batching may leave GPU capacity unused.</p><p>Continuous batching allows new requests to join while other requests are still decoding.</p><pre>Time ───────────────────────────────&gt;</pre><pre>Request A: [prefill────][decode────────]<br>Request B:       [prefill──][decode───]<br>Request C:              [prefill─][decode────]<br>Request D:                       [prefill][decode]</pre><p>This can improve:</p><ul><li>Throughput</li><li>GPU utilization</li><li>Concurrent request handling</li></ul><p>However, batching can also increase queue latency if the scheduler is poorly configured.</p><h3>GPU Utilization</h3><p>GPU utilization indicates how busy the GPU is, but it must be interpreted carefully.</p><p>High utilization can mean:</p><ul><li>The GPU is being used efficiently</li><li>The workload is compute-heavy</li><li>The system is near capacity</li><li>Requests are waiting for resources</li><li>Latency may increase under load</li></ul><p>For example:</p><pre>GPU utilization: 95%<br>TTFT: 3 seconds<br>Queue latency: 100 ms<br>Prefill latency: 2.5 seconds<br>Input: 20,000 tokens</pre><p>This may indicate that the GPU is busy processing a very large prompt, but it does not automatically prove the system is efficient.</p><p>Efficiency must be evaluated together with:</p><ul><li>Throughput</li><li>Latency</li><li>Cost</li><li>Quality</li><li>Error rate</li><li>Memory usage</li><li>Queue behavior</li></ul><h3>Agent Inference Metrics</h3><h3>Request Rate</h3><p>Number of requests received per second or minute.</p><pre>request rate = incoming requests / time</pre><p>Useful for capacity planning.</p><h3>Error Rate</h3><p>Percentage of failed requests.</p><pre>error rate =<br>failed requests<br>────────────────<br>total requests</pre><p>Track errors by category:</p><ul><li>Model errors</li><li>Tool errors</li><li>Timeout errors</li><li>Permission errors</li><li>Validation errors</li><li>Context overflow errors</li></ul><h3>TTFT</h3><p>Measures how quickly the first token appears.</p><p>High TTFT may indicate:</p><ul><li>Long input context</li><li>High queue latency</li><li>Slow tokenization</li><li>Poor prefill performance</li><li>Cache misses</li><li>GPU contention</li></ul><h3>Prefill Latency</h3><p>Measures prompt processing time.</p><p>It is primarily affected by:</p><ul><li>Input token count</li><li>Model size</li><li>Attention implementation</li><li>Batch size</li><li>GPU hardware</li><li>Prompt-cache hit rate</li></ul><h3>Decode Latency</h3><p>Measures the time spent generating output tokens.</p><p>It is primarily affected by:</p><ul><li>Output token count</li><li>Model size</li><li>KV-cache access</li><li>GPU memory bandwidth</li><li>Quantization</li><li>Speculative decoding</li></ul><h3>Output Tokens per Second</h3><pre>output tokens per second =<br>generated tokens / decode time</pre><p>This is useful for measuring generation speed.</p><h3>Inter-Token Latency</h3><p>Measures the time between generated tokens.</p><p>Low inter-token latency generally produces smoother streaming responses.</p><h3>End-to-End Latency</h3><p>Measures the complete request:</p><pre>E2E latency =<br>queue<br>+ retrieval<br>+ prefill<br>+ tool calls<br>+ decode<br>+ validation<br>+ network</pre><h3>KV-Cache Usage</h3><p>Track:</p><ul><li>Active cache memory</li><li>Cache hit rate</li><li>Cache eviction</li><li>Maximum sequence length</li><li>Number of concurrent sessions</li></ul><h3>Cost per Request</h3><p>A useful production metric is:</p><pre>cost per request =<br>input token cost<br>+ output token cost<br>+ retrieval cost<br>+ tool cost<br>+ infrastructure cost</pre><h3>Diagnosing Performance</h3><p>A harness should separate latency into components.</p><pre>Total latency<br> ├── Queue latency<br> ├── Retrieval latency<br> ├── Context assembly<br> ├── Prefill latency<br> ├── Decode latency<br> ├── Tool latency<br> ├── Validation latency<br> └── Network latency</pre><p>Example:</p><pre>TTFT:              3.0 s<br>Queue:             0.1 s<br>Retrieval:         0.2 s<br>Context assembly:  0.1 s<br>Prefill:           2.3 s<br>First decode:      0.3 s</pre><p>The largest component is prefill.</p><p>Possible improvements:</p><ul><li>Reduce irrelevant context</li><li>Cache stable prefixes</li><li>Improve retrieval filtering</li><li>Reduce tool-definition size</li><li>Use efficient attention kernels</li><li>Increase GPU memory bandwidth</li><li>Improve batching</li><li>Use a smaller model for routing or summarization</li></ul><h3>Prefill and Decode Verification</h3><p>A harness can verify that inference behaves as expected by recording structured traces.</p><p>Example:</p><pre>{<br>  &quot;request_id&quot;: &quot;req-1001&quot;,<br>  &quot;input_tokens&quot;: 12000,<br>  &quot;output_tokens&quot;: 850,<br>  &quot;queue_ms&quot;: 85,<br>  &quot;retrieval_ms&quot;: 120,<br>  &quot;prefill_ms&quot;: 1400,<br>  &quot;decode_ms&quot;: 4200,<br>  &quot;ttft_ms&quot;: 1600,<br>  &quot;e2e_ms&quot;: 5920,<br>  &quot;gpu_utilization&quot;: 84,<br>  &quot;kv_cache_mb&quot;: 9200,<br>  &quot;cache_hit&quot;: true<br>}</pre><p>The system can then calculate:</p><pre>decode tokens/sec =<br>850 ÷ 4.2<br>≈ 202 tokens/sec</pre><p>This is more useful than looking only at total latency.</p><h3>Harness Engineering and Inference</h3><p>Harness engineering affects inference performance through context and orchestration decisions.</p><p>The harness can:</p><ul><li>Select fewer but better documents</li><li>Keep stable prompt prefixes cacheable</li><li>Remove duplicate tool outputs</li><li>Limit unnecessary tool calls</li><li>Route simple requests to smaller models</li><li>Parallelize independent retrieval calls</li><li>Compress old history</li><li>Use structured handoffs</li><li>Set output-token limits</li><li>Stop when validation succeeds</li><li>Retry only transient failures</li><li>Record phase-level metrics</li></ul><pre>Better Harness<br>      │<br>      ├── Smaller context<br>      ├── Fewer tool calls<br>      ├── Better cache reuse<br>      ├── Less duplicate work<br>      └── Better scheduling<br>              │<br>              ▼<br>        Faster and cheaper inference</pre><p>The model may remain unchanged while the system becomes significantly faster.</p><h3>Practical Optimization Strategy</h3><p>Use this order when improving an agent system.</p><h3>Step 1: Measure</h3><p>Capture:</p><ul><li>Input tokens</li><li>Output tokens</li><li>TTFT</li><li>Queue latency</li><li>Prefill latency</li><li>Decode latency</li><li>Retrieval latency</li><li>Tool latency</li><li>GPU utilization</li><li>KV-cache usage</li></ul><h3>Step 2: Find the dominant cost</h3><pre>If queue is high:<br>    improve scheduling or capacity</pre><pre>If retrieval is high:<br>    optimize indexes and parallelize search</pre><pre>If prefill is high:<br>    reduce context and use caching</pre><pre>If decode is high:<br>    reduce output length, quantize, or use speculative decoding</pre><pre>If tool latency is high:<br>    optimize tools or run independent calls concurrently</pre><h3>Step 3: Apply the correct optimization</h3><p>Do not use quantization to solve a retrieval problem.</p><p>Do not use FlashAttention to solve excessive context selection.</p><p>Do not use speculative decoding to solve high queue latency.</p><p>Match the optimization to the bottleneck.</p><h3>Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnQQO7ZFR4pxDSypy6Xa5A.png" /></figure><h3>Final Principle</h3><p>Inference is not one single operation.</p><pre>Prefill processes the context.<br>KV-cache stores reusable attention state.<br>Decode generates the response.</pre><p>A reliable and efficient agent system optimizes each phase differently:</p><pre>Prefill optimization:<br>Context selection<br>Prompt caching<br>FlashAttention<br>Efficient batching</pre><pre>Decode optimization:<br>Quantization<br>KV-cache management<br>Speculative decoding<br>Output control</pre><pre>Harness optimization:<br>Retrieval<br>Tool design<br>Handoffs<br>Routing<br>Validation</pre><p>The central lesson is:</p><blockquote><em>Faster AI agents are created by matching each optimization to the correct stage of the inference pipeline.</em></blockquote><h3>References and Further Reading</h3><ul><li><a href="https://arxiv.org/abs/2205.14135">FlashAttention: Fast and Memory-Efficient Exact Attention</a></li><li><a href="https://arxiv.org/abs/2211.17192">Fast Inference from Transformers via Speculative Decoding</a></li><li><a href="https://arxiv.org/abs/2307.08691">FlashAttention-2</a></li><li><a href="https://docs.vllm.ai/">vLLM Documentation</a></li><li><a href="https://nvidia.github.io/TensorRT-LLM/">NVIDIA TensorRT-LLM Documentation</a></li><li><a href="https://huggingface.co/docs/transformers/">Hugging Face Transformers Documentation</a></li><li><a href="https://medium.com/harness-engineering/the-agent-loop-is-the-new-os-c4db8876bc58">The Agent Loop Is the New OS</a></li><li><a href="https://medium.com/%40maclarensg_50191/how-hermes-agent-solves-the-context-window-problem-and-what-every-agent-builder-should-borrow-bf90071f4757">How Hermes Agent Solves the Context Window Problem</a></li><li><a href="https://gyliu513.medium.com/hermes-agent-under-the-hood-stable-prompts-dynamic-capabilities-and-layered-memory-84f06aaa11e1">Hermes Agent Under the Hood</a></li></ul><p>The explanations, examples, calculations, and diagrams in this article are an original synthesis of these technical concepts. No source text or diagram has been reproduced directly.</p><h3>Coming Next</h3><h3>Part 5: Harness Optimization</h3><p>In Part 5, we will examine how to improve an AI agent’s speed, cost, reliability, and quality without changing the underlying language model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=604d918e22ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your AI Agent Does Not Know Your Whole Codebase]]></title>
            <link>https://medium.com/@psvsaishwarya/your-ai-agent-does-not-know-your-whole-codebase-7ade607daa8c?source=rss-53307ac94e90------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ade607daa8c</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[agent-harness]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <dc:creator><![CDATA[AISHWARYA P.S.V.S]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 11:38:56 GMT</pubDate>
            <atom:updated>2026-08-13T11:38:56.735Z</atom:updated>
            <content:encoded><![CDATA[<p>An AI agent is not automatically aware of an entire repository, company database, documentation system, or cloud environment.</p><p>It only reasons over the context supplied during a particular model call.</p><p>That context may include:</p><ul><li>The user’s request</li><li>System instructions</li><li>Project rules</li><li>Relevant source files</li><li>Retrieved documents</li><li>Database records</li><li>Previous tool results</li><li>Agent memory</li><li>Validation results</li><li>Information passed by another agent</li></ul><p>This leads to a fundamental principle:</p><blockquote><em>An agent’s answer is limited by the quality, relevance, freshness, and trustworthiness of the context it receives.</em></blockquote><p>A model may have strong reasoning ability, but it cannot reliably use information that was never provided to it.</p><h3>What Is a Harness?</h3><p>A production AI agent usually operates inside a software control layer called an agent harness.</p><p>The model generates decisions, but the harness manages the surrounding system.</p><pre>User Request<br>     │<br>     ▼<br>┌─────────────────────┐<br>│ Agent Harness        │<br>│                     │<br>│ • Retrieve context  │<br>│ • Select tools      │<br>│ • Apply policies    │<br>│ • Manage memory     │<br>│ • Run actions       │<br>│ • Validate results  │<br>└──────────┬──────────┘<br>           ▼<br>     Language Model<br>           │<br>           ▼<br>    Answer or Action</pre><p>A harness may be responsible for:</p><ul><li>Searching a codebase</li><li>Querying databases</li><li>Calling external tools</li><li>Selecting relevant documents</li><li>Managing token budgets</li><li>Starting subagents</li><li>Running code in a sandbox</li><li>Blocking unsafe actions</li><li>Validating generated changes</li><li>Recording traces and metrics</li></ul><p>The model is the reasoning component. The harness is the operating environment around it.</p><h3>Context Engineering</h3><p>Prompt engineering focuses mainly on how instructions are written.</p><p>Context engineering focuses on how the complete working context is designed, retrieved, filtered, ordered, compressed, and delivered to the model.</p><p>A useful abstraction is:</p><pre>Final Context =<br>Instructions<br>+ User Request<br>+ Relevant Evidence<br>+ Tool Capabilities<br>+ Memory<br>+ Current State<br>+ Validation Rules</pre><p>The context should not be treated as an unlimited information bucket. It is a limited working memory.</p><p>If the context contains too little information, the agent may hallucinate or make incorrect assumptions.</p><p>If it contains too much information, the agent may:</p><ul><li>Miss important facts</li><li>Spend more time processing tokens</li><li>Increase inference cost</li><li>Produce less focused answers</li><li>Confuse old and new information</li><li>Follow irrelevant instructions</li><li>Exceed the model’s context window</li></ul><p>Therefore, the goal is not to provide maximum context.</p><p>The goal is to provide sufficient, relevant, trustworthy context.</p><h3>The Context Assembly Pipeline</h3><p>A production harness commonly builds context in stages.</p><pre>User Question<br>      │<br>      ▼<br>Query Understanding<br>      │<br>      ▼<br>Candidate Retrieval<br>      │<br>      ▼<br>Filtering and Ranking<br>      │<br>      ▼<br>Deduplication<br>      │<br>      ▼<br>Context Budgeting<br>      │<br>      ▼<br>Prompt Construction<br>      │<br>      ▼<br>Model Inference</pre><p>Each stage solves a different problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vbwEfFRjuCp4jki5PpRpTg.png" /></figure><p>This pipeline is why retrieval is more than simply “searching a database.”</p><h3>AST Parsing</h3><h3>What Is an AST?</h3><p>An Abstract Syntax Tree represents source code as a structured tree.</p><p>For example:</p><pre>def validate_token(token):<br>    payload = decode_token(token)</pre><pre>    if payload.is_expired():<br>        raise AuthenticationError()</pre><pre>    return payload</pre><p>A simplified AST representation could be:</p><pre>Function: validate_token<br> ├── Parameter: token<br> ├── Call: decode_token(token)<br> ├── Condition: payload.is_expired()<br> ├── Exception: AuthenticationError<br> └── Return: payload</pre><p>Instead of treating the source file as plain text, an AST exposes its structural meaning.</p><p>AST parsing can identify:</p><ul><li>Functions</li><li>Classes</li><li>Methods</li><li>Imports</li><li>Variables</li><li>Parameters</li><li>Conditions</li><li>Return statements</li><li>Exceptions</li><li>Decorators</li><li>Inheritance</li><li>Function calls</li><li>Definitions</li><li>Test cases</li><li>Syntax errors</li></ul><h3>Why AST Retrieval Is Useful</h3><p>Suppose the user asks:</p><blockquote><em>Where is authentication validated?</em></blockquote><p>A keyword search might return every file containing the words authentication or token.</p><p>An AST-based system can locate:</p><pre>validate_token()<br> ├── decode_token()<br> ├── expiration check<br> └── AuthenticationError</pre><p>AST retrieval is deterministic. It does not depend on semantic similarity or the wording used in the query.</p><p>It is especially useful for:</p><ul><li>Code navigation</li><li>Refactoring</li><li>Dependency analysis</li><li>Finding callers of a function</li><li>Locating class definitions</li><li>Identifying test coverage</li><li>Detecting syntax problems</li><li>Understanding imports</li><li>Building code summaries</li></ul><h3>AST Indexing</h3><p>A code intelligence system can create an index such as:</p><pre>{<br>  &quot;symbol&quot;: &quot;validate_token&quot;,<br>  &quot;type&quot;: &quot;function&quot;,<br>  &quot;file&quot;: &quot;src/auth.py&quot;,<br>  &quot;line&quot;: 12,<br>  &quot;parameters&quot;: [&quot;token&quot;],<br>  &quot;calls&quot;: [&quot;decode_token&quot;],<br>  &quot;called_by&quot;: [&quot;login_request&quot;],<br>  &quot;tests&quot;: [&quot;test_validate_token&quot;]<br>}</pre><p>The harness can then answer structural questions without sending the entire repository to the model.</p><h3>Graph Retrieval</h3><h3>What Is a Graph?</h3><p>A graph represents entities and relationships.</p><pre>User<br> │<br> ├── owns ──&gt; Account<br> │              │<br> │              └── uses ──&gt; PaymentMethod<br> │<br> └── created ──&gt; Transaction</pre><p>A graph contains:</p><ul><li>Nodes or vertices</li><li>Edges or relationships</li><li>Properties</li><li>Labels</li><li>Directions</li><li>Paths</li></ul><p>A codebase can also be represented as a graph:</p><pre>login()<br>   │ calls<br>   ▼<br>validate_token()<br>   │ calls<br>   ▼<br>decode_token()</pre><h3>The Graph Question</h3><p>Vector search asks:</p><blockquote><em>Which documents are semantically similar to this query?</em></blockquote><p>Graph retrieval asks:</p><blockquote><em>What is connected to this entity, and through which relationships?</em></blockquote><p>This makes graph retrieval useful for:</p><ul><li>Dependency analysis</li><li>Call graphs</li><li>Impact analysis</li><li>Service relationships</li><li>Fraud detection</li><li>Recommendation systems</li><li>Knowledge graphs</li><li>Supply-chain analysis</li><li>Identity and access analysis</li><li>Root-cause investigation</li></ul><h3>Example</h3><p>Question:</p><blockquote><em>If </em><em>decode_token() changes, which services may be affected?</em></blockquote><p>A graph traversal can follow:</p><pre>decode_token()<br>   ▲<br>   │ called_by<br>validate_token()<br>   ▲<br>   │ called_by<br>login()<br>   ▲<br>   │ used_by<br>AuthService</pre><p>The result is based on known relationships rather than textual similarity.</p><h3>Graph Databases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30naJyUsJh9HuEl2Qgfyvg.png" /></figure><p>Azure Cosmos DB for Apache Gremlin stores and traverses graph data using the Gremlin query language. <a href="https://learn.microsoft.com/en-us/azure/cosmos-db/gremlin/overview">Azure Cosmos DB for Apache Gremlin</a></p><h3>Vector Retrieval</h3><h3>What Is an Embedding?</h3><p>An embedding converts text, code, an image, or another object into a numerical vector.</p><pre>&quot;How is authentication validated?&quot;<br>              │<br>              ▼<br>[0.12, -0.44, 0.81, 0.09, ...]</pre><p>A document is also converted into a vector:</p><pre>&quot;JWT validation occurs in validate_token()&quot;<br>              │<br>              ▼<br>[0.10, -0.40, 0.79, 0.11, ...]</pre><p>The retrieval system compares these vectors.</p><p>Common similarity measures include:</p><ul><li>Cosine similarity</li><li>Dot product</li><li>Euclidean distance</li></ul><p>Cosine similarity measures the angle between two vectors:</p><pre>cosine similarity =<br>(query · document)<br>──────────────────────<br>||query|| × ||document||</pre><p>Vector retrieval is useful when the query and document use different words but express a related meaning.</p><p>Example:</p><pre>Query: &quot;How do users sign in?&quot;<br>Document: &quot;The authentication middleware validates credentials.&quot;</pre><p>The words are different, but the concepts may be semantically related.</p><h3>Vector Indexing</h3><p>For a small dataset, the system can compare the query vector against every document vector.</p><p>This is called a flat or exact search.</p><p>For a large dataset, approximate nearest-neighbor indexes are used:</p><ul><li>HNSW</li><li>IVFFlat</li><li>IVF-PQ</li><li>Product quantization</li><li>GPU vector indexes</li></ul><p>These indexes trade a small amount of recall for much faster search.</p><h3>Vectorless RAG</h3><h3>What Is Vectorless RAG?</h3><p>Vectorless RAG retrieves information without embeddings.</p><p>It can use:</p><ul><li>BM25</li><li>Elasticsearch</li><li>OpenSearch</li><li>PostgreSQL full-text search</li><li>SQLite FTS5</li><li>SQL filters</li><li>AST parsing</li><li>Graph traversal</li><li>Metadata indexes</li><li>Regular expressions</li><li>Exact identifiers</li></ul><pre>Question<br>   │<br>   ▼<br>Keyword + SQL + AST + Graph Retrieval<br>   │<br>   ▼<br>Evidence<br>   │<br>   ▼<br>Language Model</pre><p>Vectorless retrieval is especially useful for:</p><ul><li>Error messages</li><li>Function names</li><li>Account IDs</li><li>Product codes</li><li>Legal clauses</li><li>Ticket numbers</li><li>Configuration keys</li><li>Version numbers</li><li>Exact technical terms</li></ul><p>For example, if the user searches for:</p><pre>ERR_CONNECTION_RESET</pre><p>An exact lexical search may be more reliable than semantic vector search.</p><h3>BM25</h3><p>BM25 is a ranking algorithm, not a database.</p><p>It ranks documents using:</p><ul><li>Term frequency</li><li>Inverse document frequency</li><li>Document length</li><li>Query-term relevance</li></ul><p>A simplified form is:</p><pre>BM25(D, Q) =<br>Σ IDF(term) ×<br>      term frequency adjustment<br>      document length normalization</pre><p>BM25 gives more importance to terms that:</p><ul><li>Appear in the query</li><li>Appear frequently in a relevant document</li><li>Are rare across the whole collection</li></ul><p>It also prevents a very long document from receiving an unfair advantage simply because it contains the query term many times.</p><p>Elasticsearch uses BM25 as its default similarity algorithm. Its k1 parameter controls term-frequency saturation, while b controls document-length normalization. <a href="https://www.elastic.co/docs/reference/elasticsearch/index-settings/similarity">Elasticsearch similarity documentation</a></p><h3>Full-Text Search Systems</h3><h3>Elasticsearch and OpenSearch</h3><p>These systems are designed for large-scale search.</p><p>They commonly provide:</p><ul><li>Inverted indexes</li><li>BM25 ranking</li><li>Tokenization</li><li>Stemming</li><li>Filtering</li><li>Faceting</li><li>Distributed shards</li><li>Replicas</li><li>Hybrid keyword and vector search</li></ul><p>A simplified inverted index looks like this:</p><pre>&quot;authentication&quot; → document_1, document_7, document_12<br>&quot;token&quot;          → document_1, document_3, document_7<br>&quot;middleware&quot;     → document_2, document_7</pre><p>Instead of scanning every document, the search engine directly finds documents containing the terms.</p><h3>PostgreSQL Full-Text Search</h3><p>PostgreSQL full-text search is useful when application data already lives in PostgreSQL.</p><p>It supports:</p><ul><li>tsvector</li><li>tsquery</li><li>Ranking</li><li>Stemming</li><li>GIN indexes</li><li>Filtering with SQL</li><li>Transactions and relational joins</li></ul><p>This is useful for applications that need both:</p><pre>Business filters + full-text retrieval</pre><p>For example:</p><pre>SELECT id, title<br>FROM documents<br>WHERE tenant_id = 42<br>  AND search_vector @@ plainto_tsquery(&#39;authentication middleware&#39;);</pre><h3>SQLite FTS5</h3><p>SQLite FTS5 is useful for:</p><ul><li>Local agent memory</li><li>Desktop applications</li><li>Embedded tools</li><li>Offline systems</li><li>Session search</li><li>Small repositories</li></ul><p>It provides full-text indexing without requiring a separate search server.</p><p><a href="https://www.postgresql.org/docs/current/textsearch.html">PostgreSQL full-text search</a><br><a href="https://www.sqlite.org/fts5.html">SQLite FTS5</a></p><h3>Hybrid Retrieval</h3><p>The strongest retrieval systems often combine multiple approaches.</p><pre>User Query<br>                        │<br>        ┌───────────────┼────────────────┐<br>        ▼               ▼                ▼<br>   BM25 Search     Vector Search     Graph Search<br>        │               │                │<br>        ▼               ▼                ▼<br>   Exact matches   Semantic matches   Relationships<br>        └───────────────┼────────────────┘<br>                        ▼<br>                 Reranking Layer<br>                        │<br>                        ▼<br>                   Final Evidence</pre><p>Example:</p><pre>User question:<br>&quot;Which services depend on the expired-token validation logic?&quot;</pre><p>Possible retrieval plan:</p><ol><li>AST search finds validate_token().</li><li>Graph traversal finds callers of validate_token().</li><li>BM25 finds documentation containing “expired token”.</li><li>Vector search finds semantically related security documents.</li><li>Metadata filters restrict results to the current repository and branch.</li><li>A reranker combines the results.</li><li>The final evidence is sent to the model.</li></ol><h3>Retrieval Selection Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*UKcT-DinTHOrgwzprWjPdw.png" /></figure><h3>Retrieval Quality</h3><p>A retrieval system should be measured independently from the final answer.</p><h3>Recall@K</h3><p>Recall@K measures whether the relevant evidence appears in the first K results.</p><pre>Recall@K =<br>relevant retrieved documents<br>─────────────────────────────<br>all relevant documents</pre><h3>Precision@K</h3><p>Precision@K measures how many of the first K results are relevant.</p><pre>Precision@K =<br>relevant retrieved documents<br>─────────────────────────────<br>K retrieved documents</pre><h3>Mean Reciprocal Rank</h3><p>MRR rewards systems that place the first relevant result near the top.</p><pre>MRR = average(1 / rank of first relevant result)</pre><h3>nDCG</h3><p>nDCG is useful when documents have different relevance levels.</p><p>For example:</p><pre>Highly relevant      = 3<br>Partially relevant   = 2<br>Weakly relevant      = 1<br>Irrelevant           = 0</pre><p>Retrieval quality affects answer quality. If the correct evidence is never retrieved, the model cannot reliably cite it.</p><h3>Context Selection</h3><p>Retrieval produces candidates. Context selection decides what is actually sent to the model.</p><p>A selection policy may consider:</p><ul><li>Retrieval score</li><li>Source trust</li><li>Recency</li><li>User permissions</li><li>File type</li><li>Token cost</li><li>Duplication</li><li>Task relevance</li><li>Evidence completeness</li></ul><p>A practical scoring model could be:</p><pre>Final Score =<br>0.35 × lexical score<br>+ 0.30 × semantic score<br>+ 0.20 × graph relevance<br>+ 0.10 × source trust<br>+ 0.05 × recency</pre><p>This is only an example. Production weights should be learned or tuned using evaluation data.</p><p>The harness should also preserve provenance:</p><pre>{<br>  &quot;source&quot;: &quot;src/auth.py&quot;,<br>  &quot;line_start&quot;: 12,<br>  &quot;line_end&quot;: 20,<br>  &quot;retrieval_method&quot;: &quot;AST&quot;,<br>  &quot;confidence&quot;: 0.98,<br>  &quot;trust_level&quot;: &quot;repository&quot;<br>}</pre><p>Provenance helps the agent:</p><ul><li>Cite evidence</li><li>Detect conflicts</li><li>Avoid unsupported claims</li><li>Explain why information was selected</li><li>Debug retrieval failures</li></ul><h3>The Central Principle</h3><pre>AST       → code structure<br>Graph     → relationships<br>BM25      → exact words<br>Vectors   → semantic similarity<br>SQL       → structured filters<br>Metadata  → access and scope<br>Reranking → final relevance</pre><p>A reliable AI harness does not ask one retrieval method to solve every problem.</p><p>It routes each question to the retrieval method that best matches the information need.</p><blockquote><em>Good agents do not simply receive more context. They receive the right context, from the right source, in the right format, at the right time.</em></blockquote><h3>References and Further Reading</h3><p>The following sources were consulted for technical background and conceptual comparison. The explanations, examples, architecture, and diagrams in this article are my own synthesis.</p><h3>Official Documentation</h3><ul><li><a href="https://docs.aws.amazon.com/neptune/">Amazon Neptune Documentation</a></li><li><a href="https://docs.tigergraph.com/tigergraph-server/current/intro/internal-architecture">TigerGraph Architecture</a></li><li><a href="https://graphdb.ontotext.com/documentation/10.7/">GraphDB Documentation</a></li><li><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/gremlin/overview">Azure Cosmos DB for Apache Gremlin</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/index-modules-similarity.html">Elasticsearch Similarity and BM25</a></li><li><a href="https://www.postgresql.org/docs/current/textsearch.html">PostgreSQL Full-Text Search</a></li><li><a href="https://www.sqlite.org/fts5.html">SQLite FTS5 Extension</a></li></ul><h3>Related Medium Articles</h3><ul><li><a href="https://medium.com/%40usmaanrifkhan/building-the-control-layer-for-ai-agents-harness-engineering-explained-0198ed4742c8">Building the Control Layer for AI Agents: Harness Engineering Explained</a></li><li><a href="https://milvusio.medium.com/harness-engineering-the-execution-layer-ai-agents-actually-need-c3896359917d">Harness Engineering: The Execution Layer AI Agents Actually Need</a></li><li><a href="https://medium.com/%40randhir.jassal/context-engineering-for-enterprise-ai-part-1-context-management-why-rag-alone-isnt-enough-603fa92204e4">Context Engineering for Enterprise AI: Why RAG Alone Isn’t Enough</a></li><li><a href="https://medium.com/%40abhishekchatterjee/the-anatomy-of-an-agent-harness-b173e154096b">The Anatomy of an Agent Harness</a></li><li><a href="https://medium.com/data-from-the-trenches/the-3-layers-of-agent-building-db45b52178ec">The 3 Layers of Agent Building</a></li></ul><p>These articles discuss related ideas such as context engineering, hybrid retrieval, agent loops, and harness architecture. They were used as references and inspiration, not as text or diagram templates.</p><p>This is the foundation for the next part of the series, where we will examine how multiple agents exchange context through structured handoffs. Part 2: The Multi-Agent Context Pipeline also my</p><p>Linkeldn path: <a href="https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/">https://www.linkedin.com/in/aishwarya-p-s-v-s-5a07a41ab/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ade607daa8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>