<?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 ashwin g on Medium]]></title>
        <description><![CDATA[Stories by ashwin g on Medium]]></description>
        <link>https://medium.com/@ashwingadam?source=rss-40f4d57ba9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fzJlwbwKa2r72xM-.</url>
            <title>Stories by ashwin g on Medium</title>
            <link>https://medium.com/@ashwingadam?source=rss-40f4d57ba9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 01:07:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashwingadam/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[From Agent Loops to DAGs]]></title>
            <link>https://medium.com/@ashwingadam/from-agent-loops-to-dags-understanding-the-session-8-architecture-14c56a7d694e?source=rss-40f4d57ba9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/14c56a7d694e</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[ashwin g]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 05:18:14 GMT</pubDate>
            <atom:updated>2026-06-22T05:19:17.480Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding the Architecture</h3><p>In earlier agent architectures, the mental model was simple: the model thinks, chooses the next tool, runs the tool, observes the result, and repeats. This loop-based approach works, but it becomes hard to debug, expensive in tokens, and inefficient for tasks that naturally split into independent subtasks.</p><p>Session 8 introduces a different way of thinking about agent orchestration.</p><p>Instead of keeping the model inside a repeated decision loop, Session 8 moves toward a DAG-based architecture. The model writes the workflow, and the executor runs it.</p><p>A DAG, or Directed Acyclic Graph, is simply a flowchart where work moves forward. Each box in the flowchart is a node, and each arrow is a dependency. A node can only run when the nodes it depends on are complete.</p><p>This shift sounds small, but it changes how we reason about agents, debugging, cost, recovery, and execution.</p><h3>The Core Idea</h3><p>In Session 8, every task is represented as a graph.</p><p>The user query first goes to a Planner. The Planner does not directly solve the problem. Instead, it creates a JSON plan describing which skills should run and how their outputs should flow.</p><p>For example, if the user asks:</p><blockquote><em>Find the populations of London, Paris, and Berlin, and tell me which two are closest in size.</em></blockquote><p>The Planner may create a DAG like this:</p><pre>User Query<br>   ↓<br>Planner<br>   ↓<br> ┌──────────────┬──────────────┬──────────────┐<br> ↓              ↓              ↓<br>Researcher      Researcher      Researcher<br>London          Paris           Berlin<br> └──────────────┴──────────────┴──────────────┘<br>                ↓<br>              Coder<br>             /     \<br>            ↓       ↓<br>      Formatter   SandboxExecutor<br>            ↓<br>      Final Answer</pre><p>The three Researcher nodes can run in parallel because they do not depend on each other. The Coder waits until all three researchers finish. The Formatter creates the user-facing answer, while the SandboxExecutor verifies the generated Python code.</p><p>This is the main architectural change:</p><pre>Session 7: Model decides the next step inside a loop.<br>Session 8: Model writes a graph, and the Executor runs the graph.</pre><h3>What Is a Skill?</h3><p>A skill in Session 8 is intentionally simple.</p><p>It consists of:</p><ol><li>A prompt file</li><li>A list of allowed MCP tools</li><li>A temperature setting</li></ol><p>There is no separate Python class for each skill. There is no unique code path for Planner, Researcher, Coder, Formatter, or Critic.</p><p>Every skill runs through the same dispatcher and the same gateway client. What makes one skill different from another is mostly its prompt and tool permissions.</p><p>For example:</p><ul><li>The Planner prompt asks the model to emit graph nodes as JSON.</li><li>The Researcher prompt asks the model to search or fetch information.</li><li>The Coder prompt asks the model to produce code and a summary.</li><li>The Formatter prompt asks the model to produce the final user-facing response.</li><li>The Critic prompt asks the model to judge another node’s output.</li></ul><p>This design keeps the system easy to extend. Adding a new skill is mostly a YAML edit plus a new prompt file.</p><h3>The Orchestrator and Executor</h3><p>The Orchestrator is responsible for running the DAG.</p><p>Its loop is conceptually simple:</p><pre>while there are incomplete nodes:<br>    find nodes whose dependencies are complete<br>    run all ready nodes concurrently<br>    after each node completes:<br>        add any new nodes it emitted<br>        save the graph and node state to disk</pre><p>A node is “ready” when all its predecessor nodes are complete or skipped.</p><p>For example, after the Planner finishes, the three city Researcher nodes become ready. Since they are independent, the Executor can run them concurrently using asyncio.gather.</p><p>The Coder is not ready yet because it depends on all three Researcher outputs. Once all researchers finish, the Coder becomes ready.</p><p>This is the benefit of the DAG model: execution is driven by dependencies, not by a repeated agent loop.</p><h3>Memory in Session 8</h3><p>One common question is: if every node runs separately, why does the system not read memory again and again?</p><p>The answer is that Session 8 separates long-term memory from current-run state.</p><p>Memory is read once at the beginning of the session. The orchestrator calls memory.read(query) and retrieves relevant memory hits using FAISS. Those memory hits are inserted into every skill prompt as a MEMORY HITS block.</p><p>So each skill can see relevant memory, but the system does not need to hit memory repeatedly for every node.</p><p>This matters because most information created during a run does not belong in long-term memory. For example, if a London Researcher finds the population of London, that output should flow to the Coder through the DAG edge. It should not be written to long-term memory.</p><p>The distinction is important:</p><pre>Memory = useful long-term knowledge across runs<br>DAG edges = current task outputs passed between nodes<br>Persistence = saved graph and node state for resume/debugging</pre><p>Session 8 reads memory once, then lets node outputs move through the graph.</p><h3>Parallel Fan-Out and the Barrier</h3><p>One of the clearest benefits of Session 8 is parallel execution.</p><p>In the population query, the three Researcher nodes ran concurrently:</p><pre>Researcher London: 40.5 seconds<br>Researcher Paris: 36.9 seconds<br>Researcher Berlin: 32.4 seconds</pre><p>If these ran sequentially, the total research time would be roughly:</p><pre>40.5 + 36.9 + 32.4 = 109.8 seconds</pre><p>But because they ran in parallel, the cost of that layer was close to the slowest branch:</p><pre>max(40.5, 36.9, 32.4) = 40.5 seconds</pre><p>The Coder cannot start until all three Researchers finish. This waiting point is the barrier.</p><p>In simple terms:</p><blockquote><em>If three people are collecting information at the same time, the next step starts when the slowest person returns.</em></blockquote><p>This is why optimizing the slowest branch matters more than optimizing the average branch. If London is the slowest Researcher, improving Paris does not significantly reduce wall-clock time. Improving London does.</p><h3>Token Cost Improvements</h3><p>Session 8 is also cheaper in terms of token usage.</p><p>In Session 7, the loop repeatedly resent cumulative history to Perception and Decision. By later iterations, each call carried previous memory hits, previous action results, and goal-list state. This caused the input token bill to grow quickly.</p><p>In the population query, Session 7 used around 54,000 input tokens.</p><p>Session 8 used around 17,000 input tokens.</p><p>Why?</p><p>Because each node receives only the context it needs.</p><p>The London Researcher receives the user query and the London sub-question. The Paris Researcher receives the user query and the Paris sub-question. The Coder receives the three Researcher outputs. The Formatter receives the Coder output.</p><p>No node receives unnecessary history.</p><p>This is one of the biggest practical benefits of DAG-based orchestration:</p><blockquote><em>The graph controls context flow.<br>Each node gets scoped input instead of the entire conversation history.</em></blockquote><h3>Trust and Verify: Formatter and SandboxExecutor</h3><p>The population DAG ends with a diamond shape.</p><p>The Coder has two children:</p><pre>Coder<br> ├── Formatter<br> └── SandboxExecutor</pre><p>The Coder outputs a JSON object containing two fields:</p><pre>{<br>  &quot;code&quot;: &quot;Python code that computes the answer&quot;,<br>  &quot;summary&quot;: &quot;Natural-language explanation of the result&quot;<br>}</pre><p>The Formatter reads the summary and creates the final user-facing answer.</p><p>The SandboxExecutor reads the code field and runs the Python code in an isolated subprocess. It captures stdout, stderr, exit code, and any files written to a temporary directory.</p><p>This is where Session 8 becomes more than a DAG of LLM calls. It becomes a DAG of LLM calls plus real execution.</p><p>The Formatter trusts the LLM summary. The SandboxExecutor verifies the code.</p><p>In the population query, this gave a more precise answer. Instead of saying “approximately 1.6 million,” the system could verify the exact difference as 1,640,000.</p><p>However, the sandbox has an important limitation. It is a usability boundary, not a security boundary. It has a timeout, output caps, a temporary working directory, and scrubbed environment variables, but it does not fully isolate the network, filesystem, or process privileges.</p><p>In simple terms:</p><blockquote><em>The sandbox catches mistakes, not attacks.</em></blockquote><p>It is useful for student code and normal verification. It is not suitable for running hostile untrusted code in production.</p><h3>The Critic Loop</h3><p>Session 8 also introduces a Critic mechanism.</p><p>The Critic is an LLM that reads another LLM’s output and returns:</p><pre>{<br>  &quot;verdict&quot;: &quot;pass&quot;,<br>  &quot;rationale&quot;: &quot;...&quot;<br>}</pre><p>or:</p><pre>{<br>  &quot;verdict&quot;: &quot;fail&quot;,<br>  &quot;rationale&quot;: &quot;...&quot;<br>}</pre><p>The skill catalogue can mark a skill with critic: true. For example, the Distiller skill can be configured this way.</p><p>When the orchestrator sees a Distiller output feeding into another node, it automatically inserts a Critic in between:</p><pre>Distiller → Critic → Next Node</pre><p>If the Critic says pass, the next node continues.</p><p>If the Critic says fail, the successor node is skipped and a recovery Planner is queued with the failure rationale.</p><p>This is useful, but it has a limitation: the Critic is still an LLM.</p><p>It works well for review tasks such as fluency, tone, coherence, and checking whether fields are present in attached source material. But it is not reliable for exact checks like syllable counting, arithmetic, regex validation, or strict schema matching unless it has tools.</p><p>A haiku test exposed this limitation. The system asked for a strict 4–6–4 syllable haiku. The generated poem did not satisfy the constraint, but the Critic still returned pass.</p><p>The architecture worked. The Critic ran, returned a verdict, and the Executor followed it. The problem was the Critic policy, not the graph mechanism.</p><p>The fix is to give the Critic tools.</p><p>For example:</p><ul><li>syllable counter</li><li>JSON schema validator</li><li>regex matcher</li><li>arithmetic calculator</li></ul><p>The important lesson is:</p><pre>Mechanism problem → fix orchestrator wiring<br>Policy problem → fix prompt or give the skill tools</pre><h3>Recovery Classification</h3><p>Another important Session 8 improvement is failure classification.</p><p>Initially, every node failure triggered a recovery Planner. That sounded reasonable, but it caused a serious problem.</p><p>If a Researcher failed because of a temporary 503 gateway error, the orchestrator queued a recovery Planner. But if the gateway was still unavailable, the recovery Planner also failed. That failure triggered another recovery Planner. The system entered a useless loop, growing the graph and burning tokens until a max-node cap stopped it.</p><p>The fix was to classify failures into three types:</p><p>Failure typeMeaningActiontransientGateway/network issue like 503, 502, timeoutSurface error, do not re-planvalidation_errorBad JSON or schema validation issueSurface error, fix prompt/schemaupstream_failureReal workflow failureQueue one recovery Planner</p><p>This prevents the system from using planning to solve problems that planning cannot solve.</p><p>In simple words:</p><blockquote><em>Do not re-plan because the internet is down.<br>Do not re-plan because the Planner emitted malformed JSON.<br>Re-plan when the workflow itself produced a bad intermediate result.</em></blockquote><h3>Persistence and Resume</h3><p>Session 8 saves every graph modification and every node state to disk.</p><p>A session directory looks like this:</p><pre>state/sessions/&lt;session_id&gt;/<br>  query.txt<br>  graph.json<br>  nodes/<br>    n_001.json<br>    n_002.json<br>    n_003.json</pre><p>query.txt stores the original user query.<br>graph.json stores the NetworkX DAG as JSON.<br>Each file under nodes/ stores one node’s state.</p><p>All writes are atomic. The implementation writes to a temporary file first and then swaps it into place using os.replace. That means there should be no half-written graph file if the process is killed during a write.</p><p>Resume is straightforward:</p><pre>flow.py --resume s8-0be05ca6</pre><p>The system reads the graph, resets any node marked running back to pending, and continues from the next ready node.</p><p>Completed nodes are not rerun.</p><p>However, resume works at the node boundary, not the tool-call boundary. If a Researcher was killed three tool calls into its loop, the whole Researcher node is rerun from the beginning.</p><p>This is a known deferral. A later version can persist partial messages inside the node state and resume from the next tool call.</p><h3>The V8 Gateway Upgrade</h3><p>Session 8 also uses the V8 gateway.</p><p>The V7 gateway remains available on port 8107. V8 runs on port 8108.</p><p>V8 is not mainly an algorithmic change. It is an observability and routing upgrade.</p><p>The key additions are:</p><h3>Agent and session tagging</h3><p>Each /v1/chat call can include:</p><pre>{<br>  &quot;agent&quot;: &quot;researcher&quot;,<br>  &quot;session&quot;: &quot;s8-0be05ca6&quot;<br>}</pre><p>This means every gateway call can be traced to a specific skill and session.</p><h3>Cost by agent</h3><p>The /v1/cost/by_agent endpoint shows token usage grouped by skill.</p><p>This makes it easy to see where the token spend went:</p><pre>planner<br>researcher<br>coder<br>formatter</pre><p>In Session 7, this was not possible because the loop did not name its sub-steps.</p><h3>Agent routing YAML</h3><p>The agent_routing.yaml file maps skill names to providers.</p><p>If researcher is pinned to a provider, the gateway sends researcher calls directly there without asking the router. This saves router-classification latency and token cost.</p><p>The trade-off is that pinning gives up some failover flexibility.</p><h3>Retry on 5xx</h3><p>V8 retries temporary 502 and 503 provider errors with exponential backoff before surfacing the failure.</p><p>This is important because temporary gateway noise should not become an agent recovery problem.</p><h3>Worked Queries</h3><p>Session 8 was tested with different query types.</p><h3>1. Hello query</h3><pre>Say hello.</pre><p>This produces the smallest possible DAG:</p><pre>Planner → Formatter</pre><p>No research, no coding, no distillation.</p><h3>2. Claude Shannon Wikipedia query</h3><pre>Fetch Claude Shannon&#39;s Wikipedia page and extract birth date, death date, and three contributions.</pre><p>This creates a sequential DAG:</p><pre>Planner → Researcher → Distiller → Critic → Formatter</pre><p>The benefit here is not speed. The query is naturally sequential. The benefit is the clear trace.</p><h3>3. Three city populations</h3><p>This is the parallel fan-out case:</p><pre>Planner → three Researchers → Coder → Formatter/SandboxExecutor</pre><p>This showed major improvements in both wall-clock time and token usage.</p><h3>4. Graceful failure</h3><pre>Read /nonexistent/path.txt and tell me what&#39;s in it.</pre><p>The Planner recognized that the request could not be satisfied and emitted:</p><pre>Planner → Formatter</pre><p>No tool was dispatched unnecessarily.</p><h3>5. Resumable execution</h3><p>A query about Lagos, Cairo, and Kinshasa was killed mid-run and resumed.</p><p>The graph persisted enough state to avoid rerunning completed nodes. Only the running Researcher was reset to pending and rerun.</p><p>This proves that Session 8’s graph state is durable and inspectable.</p><h3>Honest Design Choices</h3><p>Session 8 makes several deliberate simplifications.</p><p>First, the SandboxExecutor is not a production-grade security sandbox.</p><p>Second, resume does not yet work inside a tool-use loop.</p><p>Third, the Critic is generic and needs tools for precise verification.</p><p>Fourth, skills are YAML entries plus prompt files, not rich Python subclasses. This keeps the system simple, but special skills like SandboxExecutor need dispatcher special-casing.</p><p>Fifth, agent_routing.yaml is read at gateway startup and is not hot-reloaded. Changing routing requires a restart.</p><p>These are not accidental flaws. They are clear boundaries chosen for a teaching-grade implementation.</p><h3>Areas of Improvement</h3><p>Session 8 creates a strong foundation, but several areas can be improved.</p><h3>1. Browser-grounded research</h3><p>The Researcher currently relies on web_search and fetch_url. A future version can use a headless browser that can click, scroll, and read rendered pages.</p><h3>2. Resumable tool-use loops</h3><p>Instead of restarting a whole Researcher node after a crash, the system can persist partial messages and resume from the next tool call.</p><h3>3. Tool-grounded Critic</h3><p>The Critic should use tools for exact checks such as syllable counting, JSON schema validation, regex matching, and arithmetic.</p><h3>4. Stronger sandbox security</h3><p>A production sandbox should add stronger isolation, such as containers, restricted users, network blocking, filesystem controls, CPU/memory limits, and seccomp-style restrictions.</p><h3>5. Richer skill abstraction</h3><p>If more skills need special execution behavior, the system should move beyond YAML-only skill definitions and introduce a cleaner skill abstraction.</p><h3>6. Better retrieval</h3><p>Memory retrieval can be improved with hybrid retrieval: dense search, sparse keyword search, and reranking.</p><h3>Final Thoughts</h3><p>Session 8 is not just a performance improvement. It is a change in how we think about agent systems.</p><p>The old loop-based model is easy to start with, but hard to inspect as tasks become more complex. The DAG model gives us a clearer artifact: a graph of named nodes, each with one job, each with saved state, cost visibility, and dependency-aware execution.</p><p>The biggest lesson is this:</p><blockquote><em>Good agent architecture is not only about getting the right answer.<br>It is about creating a workflow that is faster, cheaper, inspectable, recoverable, and easier to trust.</em></blockquote><p>Session 8 moves the system in that direction.</p><p>It turns the agent trace from a long diary of repeated thoughts into a workflow diagram that engineers can reason about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14c56a7d694e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Monolithic Agents to Cognitive Architectures: Building Smarter AI Systems with Memory…]]></title>
            <link>https://medium.com/@ashwingadam/from-monolithic-agents-to-cognitive-architectures-building-smarter-ai-systems-with-memory-988f938456f6?source=rss-40f4d57ba9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/988f938456f6</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[ashwin g]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 17:18:59 GMT</pubDate>
            <atom:updated>2026-06-04T17:18:59.901Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Monolithic Agents to Cognitive Architectures: Building Smarter AI Systems with Memory, Perception, Decision, and Action</h3><p>Modern AI agents are no longer simple chatbots that answer questions in a single LLM call. As tasks become more complex, agents must remember information, decompose goals, interact with tools, and reason across multiple iterations.</p><p>One of the biggest challenges in agent engineering is scalability.</p><p>An agent that works perfectly for a simple question often begins to fail when asked to handle multiple objectives simultaneously.</p><p>Consider the following request:</p><p>“Remind me to wish John on his birthday next week and also book a table for 2 near his office at 7 PM.”</p><p>For a traditional single-loop agent, this seemingly simple request creates several problems:</p><ul><li>Multiple goals</li><li>Missing information</li><li>Ambiguous dates</li><li>Dependency on previously stored knowledge</li></ul><p>The result is often forgotten tasks, merged objectives, or endless reasoning loops.</p><p>This is exactly the problem that Session 6’s Agentic Architecture attempts to solve.</p><p><strong>Why Traditional Agent Loops Eventually Break</strong></p><p>In previous architectures, a single agent was responsible for:</p><ul><li>Understanding the request</li><li>Planning actions</li><li>Calling tools</li><li>Validating outputs</li><li>Managing memory</li></ul><p>Everything happened inside one large reasoning loop.</p><p>While functional, this design creates a bottleneck:</p><ul><li>Prompts become larger</li><li>State becomes difficult to manage</li><li>New features increase complexity exponentially</li><li>Reliability decreases as task complexity grows</li></ul><p>The core insight of Session 6 is simple:</p><blockquote><em>A loop becomes an architecture when responsibilities are separated into specialized roles.</em></blockquote><p>Instead of one agent doing everything, the system introduces four cognitive roles.</p><h3>The Four Cognitive Roles</h3><p>The architecture divides intelligence into four independent responsibilities:</p><h3>1. Memory</h3><p>Memory acts as the system’s knowledge layer.</p><p>It stores:</p><ul><li>Facts</li><li>User preferences</li><li>Tool outcomes</li><li>Temporary scratchpad information</li></ul><p>Examples:</p><ul><li>“John’s office is in HSR Layout.”</li><li>“User prefers morning meetings.”</li><li>Previous tool execution results.</li></ul><p>Unlike many agent systems, Memory is consulted at the beginning of every iteration, ensuring the agent starts by asking:</p><blockquote><em>“What do I already know?”</em></blockquote><p>This dramatically reduces redundant reasoning and tool usage.</p><h3>2. Perception</h3><p>Perception acts as the orchestrator.</p><p>Its responsibilities include:</p><ul><li>Understanding the user’s request</li><li>Breaking complex queries into goals</li><li>Tracking completion status</li><li>Deciding whether additional context is needed</li></ul><p>For example:</p><p>User Request:</p><blockquote><em>Remind me to wish John on his birthday and book dinner near his office.</em></blockquote><p>Perception decomposes this into:</p><p>Goal 1:</p><ul><li>Find John’s birthday</li></ul><p>Goal 2:</p><ul><li>Create reminder</li></ul><p>Goal 3:</p><ul><li>Find John’s office location</li></ul><p>Goal 4:</p><ul><li>Book restaurant</li></ul><p>Instead of solving everything at once, the system works through one bounded goal at a time.</p><p>This dramatically improves reliability.</p><h3>3. Decision</h3><p>Decision is the reasoning engine.</p><p>Its job is intentionally narrow:</p><p>Given one goal, decide:</p><ul><li>Can I answer directly?</li><li>Do I need a tool?</li></ul><p>Decision has only two valid outputs:</p><h3>Output 1: Answer</h3><pre>DecisionOutput(<br>    answer=&quot;John&#39;s birthday is May 15th&quot;<br>)</pre><h3>Output 2: Tool Call</h3><pre>DecisionOutput(<br>    tool_call=ToolCall(<br>        name=&quot;fetch_calendar&quot;,<br>        arguments={...}<br>    )<br>)</pre><p>It never performs multiple actions simultaneously.</p><p>One goal.<br>One decision.</p><p>This constraint significantly reduces hallucinations and planning errors.</p><h3>4. Action</h3><p>Action is the execution layer.</p><p>Unlike Perception and Decision, it contains no LLM reasoning.</p><p>Its responsibilities are:</p><ul><li>Execute MCP tools</li><li>Return results</li><li>Store large outputs as artifacts</li><li>Record outcomes in memory</li></ul><p>Because Action contains no intelligence, it becomes highly deterministic and easy to debug.</p><h3>The Hidden Hero: Artifacts</h3><p>One of the most elegant ideas in this architecture is the Artifact Store.</p><p>Imagine a tool retrieves a 100 KB web page.</p><p>Without artifacts:</p><ul><li>The entire page enters memory</li><li>Context windows explode</li><li>Costs increase</li><li>Performance degrades</li></ul><p>Instead:</p><ol><li>Store large content separately</li><li>Generate an artifact handle</li></ol><pre>art:09ffab...</pre><ol><li>Save only the reference in memory</li></ol><p>Memory stores:</p><pre>{<br>  &quot;artifact_id&quot;: &quot;art:09ffab...&quot;<br>}</pre><p>Actual bytes remain outside the reasoning context.</p><p>Only when needed does Perception attach the artifact to the Decision process.</p><p>This design keeps reasoning lightweight while still supporting large documents and web content.</p><h3>The Control Flow</h3><p>The execution sequence is remarkably clean.</p><pre>User Query<br>     |<br>     v<br>  Memory<br>     |<br>     v<br> Perception<br>     |<br>     v<br> Decision<br>     |<br>     v<br> Action<br>     |<br>     v<br> Update Memory<br>     |<br>     v<br> Repeat</pre><p>The cycle continues until all goals are marked complete.</p><p>A critical difference from earlier architectures:</p><p>Perception reevaluates the goal list every iteration.</p><p>There is no separate verification layer anymore.</p><p>Verification becomes a natural outcome of Perception observing history and determining whether a goal has been satisfied.</p><h3>Why Typed Contracts Matter</h3><p>Every interaction between components uses Pydantic models.</p><p>Examples include:</p><pre>MemoryItem<br>Goal<br>Observation<br>ToolCall<br>DecisionOutput<br>Artifact</pre><p>This creates strong boundaries:</p><pre>Memory -&gt; Observation<br>Observation -&gt; DecisionOutput<br>DecisionOutput -&gt; ToolCall</pre><p>Benefits include:</p><ul><li>Validation</li><li>Structured outputs</li><li>Reduced parsing errors</li><li>Better debugging</li><li>Easier future expansion</li></ul><p>Instead of exchanging unstructured text, components exchange typed objects.</p><h3>Memory-First Architecture</h3><p>One particularly clever design choice is:</p><blockquote><em>The LLM works harder during writes so that reads become cheaper later.</em></blockquote><p>When the user says:</p><blockquote><em>“John’s birthday is May 15th.”</em></blockquote><p>The write operation performs classification:</p><pre>{<br>  &quot;kind&quot;: &quot;fact&quot;,<br>  &quot;entity&quot;: &quot;John&quot;,<br>  &quot;attribute&quot;: &quot;birthday&quot;,<br>  &quot;value&quot;: &quot;2026-05-15&quot;<br>}</pre><p>Future retrieval becomes simple keyword matching rather than another expensive LLM call.</p><p>This design shifts cost from retrieval time to storage time and makes the system more scalable.</p><h3>Why This Architecture Matters</h3><p>The real significance of Session 6 is not the implementation itself.</p><p>It creates the foundation for future evolution.</p><p>Session 6 introduces:</p><ul><li>Memory</li><li>Perception</li><li>Decision</li><li>Action</li></ul><p>Session 7 expands Memory into a multi-layer retrieval system.</p><p>Session 8 replaces the loop with a DAG-based execution model.</p><p>Future sessions evolve Perception into a dedicated Planner Agent.</p><p>Yet the vocabulary remains the same.</p><p>The architecture changes.</p><p>The cognitive roles survive.</p><h3>Final Thoughts</h3><p>The biggest lesson from this architecture is that intelligence scales through separation of concerns.</p><p>Instead of building larger prompts and larger loops, we build specialized cognitive modules:</p><ul><li>Memory remembers.</li><li>Perception understands.</li><li>Decision reasons.</li><li>Action executes.</li></ul><p>Together they create a system that is more reliable, easier to debug, and far more scalable than a monolithic agent loop.</p><p>As agentic systems evolve toward multi-agent orchestration, DAG execution, long-term memory, and autonomous planning, architectures like this provide the foundation for building production-grade AI agents rather than experimental prototypes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=988f938456f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Autonomous Stock Analyst Agent Inside a Chrome Extension using Gemini]]></title>
            <link>https://medium.com/@ashwingadam/building-an-autonomous-stock-analyst-agent-inside-a-chrome-extension-using-gemini-7ff3bb978c12?source=rss-40f4d57ba9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ff3bb978c12</guid>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[ashwin g]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 18:13:00 GMT</pubDate>
            <atom:updated>2026-04-24T18:13:00.481Z</atom:updated>
            <content:encoded><![CDATA[<p><em>*How I built a 100% client-side AI agent that scrapes financials, reads the news, and gives actionable stock recommendations right in your browser.*</em></p><p>— -</p><p>If you’ve ever tried to do fundamental analysis on a stock, you know the drill: you have one tab open for the latest news, another for sector outlooks, and a third for a financial screener like Screener.in or Yahoo Finance.</p><p>Synthesizing all this data takes time and mental energy. But what if you could have an autonomous AI agent sit right inside your browser, gather all this data for you, reason through it, and hand you a final verdict?</p><p>That’s exactly what I built: a <strong>**100% client-side Chrome Extension**</strong> powered by Google’s <strong>**Gemini API**</strong> and <strong>**Function Calling**</strong>.</p><p>Here’s a deep dive into how I built it, the architecture, and the custom tools the agent uses.</p><p><strong>## The Architecture: Why 100% Client-Side?</strong></p><p>When building AI agents, the standard approach is to build a heavy Python backend (using frameworks like LangChain or AutoGen) and have the frontend communicate with it via API calls.</p><p>For this project, I wanted to see if I could push the limits of modern browser capabilities. Could a Chrome Extension Service Worker act as the entire agentic loop?</p><p><strong>**The answer is yes.**</strong> By utilizing Chrome’s `host_permissions` to bypass CORS and directly interacting with the Gemini REST API, the extension runs entirely in the background script (`background.js`). No Python. No backend hosting. No server costs.</p><p><strong>## Empowering the Agent with Tools</strong></p><p>An LLM on its own only knows what it was trained on. To make it a live stock analyst, I had to give it tools to see the current world. I equipped the Gemini agent with three distinct tools using Function Calling:</p><p><strong>### 1. `get_company_news`</strong></p><p>Stock prices move on news. This tool calls <strong>**SerpApi’s Google News engine**</strong> to fetch the top 5 most recent headlines for a given company.</p><p><strong>### 2. `get_sector_info`</strong></p><p>A company might be doing great, but if the macroeconomic sector is crashing, the stock will suffer. This tool performs a targeted SerpApi search to gather macroeconomic data and sector performance outlooks.</p><p><strong>### 3. `get_screener_financials`</strong></p><p>This is where the real fundamental analysis happens. I built a custom scraper that fetches the target company’s page from <strong>**Screener.in**</strong>.</p><p>Because Chrome Extension Service Workers don’t have access to the DOM (meaning no `DOMParser`), I couldn’t use standard HTML parsing. Instead, I wrote lightweight Regex patterns directly in the background script to extract key financial ratios (like P/E, ROCE, Debt-to-Equity) and the company’s Pros/Cons list directly from the raw HTML payload.</p><p><strong>## The “Reasoning Chain” UI</strong></p><p>One of the most fascinating parts of working with AI agents is watching them “think.”</p><p>Instead of just showing the user a loading spinner and then spitting out a final “Buy” or “Sell,” I built a terminal-like <strong>**Reasoning Chain**</strong> UI in the extension popup.</p><p>As the background Service Worker runs its `while` loop (sending context to Gemini, receiving a tool call, executing the tool, and sending the result back), it streams its status to the popup via Chrome’s messaging API.</p><p>The user gets to see:</p><p>- `[TOOL CALL]` <em>*Function get_company_news called for ‘Tata Motors’*</em></p><p>- `[TOOL RESULT]` <em>*Raw news headlines returned…*</em></p><p>- `[AGENT THOUGHT]` <em>*The news looks positive, but I need to check the financials before making a decision…*</em></p><p>- `[FINAL RECOMMENDATION]` <em>*A detailed markdown analysis ending in a definitive BUY, SELL, or HOLD.*</em></p><p>Watching the agent realize it needs more information, call a tool, ingest the data, and form an opinion is incredibly satisfying to watch.</p><p><strong>## Technical Hurdles &amp; Workarounds</strong></p><p>Building an agent entirely in a Service Worker came with some unique challenges:</p><p>1. <strong>**Parallel Tool Calling**</strong>: Newer Gemini models (like `gemini-1.5-pro` and `3.1`) are smart enough to request <em>*multiple*</em> tools at the exact same time to save latency. I had to upgrade my agent loop to process an array of `functionCall` objects concurrently and pass back an array of `functionResponse` objects in a single turn.</p><p>2. <strong>**CORS Restrictions**</strong>: Fetching raw HTML from Screener.in or JSON from SerpApi would normally throw Cross-Origin Resource Sharing (CORS) errors in a browser. By adding `https://*.screener.in/*` and `https://*.serpapi.com/*` to the `host_permissions` in `manifest.json`, the Chrome extension is granted elevated privileges to fetch this data seamlessly.</p><p><strong>## Conclusion</strong></p><p>Building this extension proved that you don’t necessarily need a complex backend infrastructure to deploy autonomous AI agents. Modern browser extensions combined with the Gemini API’s native function calling capabilities are more than enough to create incredibly powerful, localized AI assistants.</p><p>The next time I’m looking at a stock, instead of opening five different tabs, I just click the extension icon, enter the ticker, and let the agent do the heavy lifting.</p><p>— -</p><p><em>*If you are interested in building something similar, check out the Google Gemini API documentation on Function Calling and the Chrome Extension Manifest V3 guides!*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ff3bb978c12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Query Batching for LLM Inference Optimization (with Code Examples)]]></title>
            <link>https://medium.com/@ashwingadam/query-batching-for-llm-inference-optimization-with-code-examples-e842e2cab530?source=rss-40f4d57ba9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e842e2cab530</guid>
            <dc:creator><![CDATA[ashwin g]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 17:52:44 GMT</pubDate>
            <atom:updated>2025-12-31T17:52:44.796Z</atom:updated>
            <content:encoded><![CDATA[<p>Large Language Models (LLMs) are extremely powerful — but <strong>inference is expensive</strong>.<br> One of the <strong>most impactful optimizations</strong> for serving LLMs at scale is <strong>query batching</strong>.</p><p>This blog explains <strong>query batching from scratch using only code</strong>, moving from naive inference to production-grade batching.</p><h3><strong>No Query Batching (Baseline — Worst Case)</strong></h3><p>Each request is processed independently.</p><pre>from transformers import AutoTokenizer, AutoModelForCausalLM<br>import torch<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;gpt2&quot;)<br>model = AutoModelForCausalLM.from_pretrained(&quot;gpt2&quot;).cuda()<br><br>def infer(prompt):<br>    inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br>    outputs = model.generate(**inputs, max_new_tokens=50)<br>    return tokenizer.decode(outputs[0])<br><br># Sequential inference (❌)<br>infer(&quot;Explain transformers&quot;)<br>infer(&quot;Explain query batching&quot;)<br>infer(&quot;Explain attention mechanism&quot;)</pre><h4>Problems</h4><ul><li>GPU is mostly idle</li><li>Very low throughput</li><li>Not scalable</li></ul><h3><strong>Static Query Batching (Simple but Inefficient)</strong></h3><p>Multiple prompts are batched together in one forward pass.</p><pre>prompts = [<br>    &quot;Explain transformers&quot;,<br>    &quot;Explain query batching&quot;,<br>    &quot;Explain attention mechanism in detail&quot;<br>]<br><br>inputs = tokenizer(<br>    prompts,<br>    return_tensors=&quot;pt&quot;,<br>    padding=True  # Pads to longest prompt<br>).to(&quot;cuda&quot;)<br><br>outputs = model.generate(**inputs, max_new_tokens=50)<br><br>for i, out in enumerate(outputs):<br>    print(tokenizer.decode(out))</pre><h4><strong>Issues</strong></h4><ul><li>Padding wastes GPU compute</li><li>All requests wait for the slowest one</li><li>Not suitable for real-time APIs</li></ul><h3>Dynamic Query Batching (Request-Level)</h3><p>Requests are collected for a short time window and processed together.</p><pre>import asyncio<br>import time<br><br>request_queue = []<br><br>MAX_BATCH_SIZE = 4<br>MAX_WAIT_MS = 10<br><br>async def submit(prompt):<br>    future = asyncio.Future()<br>    request_queue.append((prompt, future))<br>    return await future<br><br>async def batch_worker():<br>    while True:<br>        if not request_queue:<br>            await asyncio.sleep(0.001)<br>            continue<br><br>        start = time.time()<br><br>        while (<br>            len(request_queue) &lt; MAX_BATCH_SIZE and<br>            (time.time() - start) * 1000 &lt; MAX_WAIT_MS<br>        ):<br>            await asyncio.sleep(0.001)<br><br>        batch = request_queue[:MAX_BATCH_SIZE]<br>        del request_queue[:MAX_BATCH_SIZE]<br><br>        prompts = [p for p, _ in batch]<br>        futures = [f for _, f in batch]<br><br>        inputs = tokenizer(prompts, padding=True, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br>        outputs = model.generate(**inputs, max_new_tokens=50)<br><br>        for f, out in zip(futures, outputs):<br>            f.set_result(tokenizer.decode(out))<br><br>asyncio.create_task(batch_worker())</pre><h4><strong>Improvements</strong></h4><ul><li>Better GPU utilization</li><li>Lower per-request cost</li></ul><h4><strong>Still a Problem</strong></h4><ul><li>Padding still exists</li><li>Entire batch blocks until generation completes</li></ul><h3>Token-Level Query Batching (Correct LLM Approach)</h3><p>Modern LLM servers batch <strong>tokens</strong>, not requests.</p><pre>class Request:<br>    def __init__(self, prompt):<br>        self.input_ids = tokenizer(prompt, return_tensors=&quot;pt&quot;).input_ids.to(&quot;cuda&quot;)<br>        self.generated = []<br>        self.past_key_values = None<br>        self.finished = False<br><br>active_requests = []<br><br>def add_request(prompt):<br>    active_requests.append(Request(prompt))<br><br>def generate_one_token():<br>    input_ids = []<br>    past_kvs = []<br><br>    for r in active_requests:<br>        if r.past_key_values is None:<br>            input_ids.append(r.input_ids)<br>        else:<br>            input_ids.append(<br>                torch.tensor([[r.generated[-1]]], device=&quot;cuda&quot;)<br>            )<br>        past_kvs.append(r.past_key_values)<br><br>    input_ids = torch.cat(input_ids, dim=0)<br><br>    outputs = model(<br>        input_ids,<br>        past_key_values=past_kvs,<br>        use_cache=True<br>    )<br><br>    next_tokens = torch.argmax(outputs.logits[:, -1, :], dim=-1)<br><br>    for i, r in enumerate(active_requests):<br>        token = next_tokens[i].item()<br>        r.generated.append(token)<br>        r.past_key_values = outputs.past_key_values<br><br>        if token == tokenizer.eos_token_id or len(r.generated) &gt; 50:<br>            r.finished = True<br><br>    active_requests[:] = [r for r in active_requests if not r.finished]</pre><pre>add_request(&quot;Explain transformers&quot;)<br>add_request(&quot;Explain query batching&quot;)<br><br>while active_requests:<br>    generate_one_token()</pre><h4>Why this works</h4><ul><li>No padding</li><li>Requests can join and leave dynamically</li><li>Maximum GPU utilization</li></ul><h3>Chunked Prefill (Handling Long Prompts)</h3><p>Long prompts are processed in chunks to avoid memory spikes.</p><pre>def chunked_prefill(request, chunk_size=512):<br>    tokens = request.input_ids[0]<br>    for i in range(0, len(tokens), chunk_size):<br>        chunk = tokens[i:i+chunk_size].unsqueeze(0)<br>        outputs = model(<br>            chunk,<br>            past_key_values=request.past_key_values,<br>            use_cache=True<br>        )<br>        request.past_key_values = outputs.past_key_values</pre><h3>Production-Ready Query Batching (vLLM)</h3><p>In real systems, batching is handled automatically.</p><pre>from openai import OpenAI<br><br>client = OpenAI(<br>    base_url=&quot;http://localhost:8000/v1&quot;,<br>    api_key=&quot;dummy&quot;<br>)<br><br>client.chat.completions.create(<br>    model=&quot;mistralai/Mistral-7B-Instruct&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain query batching&quot;}],<br>    max_tokens=100<br>)</pre><h4>vLLM internally:</h4><ul><li>Performs token-level batching</li><li>Manages KV cache efficiently</li><li>Dynamically schedules GPU execution</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e842e2cab530" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling LLM Inference: From Single Prompt to Millions of Users]]></title>
            <link>https://medium.com/@ashwingadam/scaling-llm-inference-from-single-prompt-to-millions-of-users-17f1ca57b049?source=rss-40f4d57ba9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/17f1ca57b049</guid>
            <dc:creator><![CDATA[ashwin g]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 09:14:20 GMT</pubDate>
            <atom:updated>2025-12-31T09:14:20.744Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Large Language Models (LLMs) have demonstrated remarkable capabilities across tasks such as text generation, summarization, code assistance, and reasoning. However, <strong>building or fine-tuning an LLM is only half the challenge</strong>. The real test begins when these models are deployed to serve real users at scale.</p><p><strong>Inference scalability</strong> — the ability to serve thousands or millions of requests efficiently, cost-effectively, and reliably — has become one of the most critical engineering problems in modern AI systems.</p><p><strong>What Is LLM Inference?</strong></p><p>Inference is the process where a trained LLM:</p><ol><li>Accepts an input prompt</li><li>Tokenizes it</li><li>Iteratively predicts the next token</li><li>Streams or returns the generated output</li></ol><p><strong>Why Scaling LLM Inference Is Hard</strong></p><ol><li>Autoregressive Token Generation</li><li>KV Cache Explosion</li><li>Variable-Length Requests</li><li>Latency vs Throughput Trade-off</li></ol><p><strong>Key Techniques for Scaling LLM Inference</strong></p><ol><li><strong>Continuous (Dynamic) Batching</strong></li></ol><p>Instead of waiting for a fixed batch:</p><ul><li>Requests are added dynamically</li><li>Tokens are scheduled per step</li><li>Improves GPU utilization dramatically</li></ul><p><strong>2. KV Cache Optimization</strong></p><p><strong>Paged KV Cache</strong>:</p><ul><li>Stores KV blocks in non-contiguous memory</li><li>Avoids fragmentation</li><li>Allows memory reuse across requests</li></ul><p><strong>KV Cache Offloading</strong>:</p><ul><li>Move inactive KV blocks to CPU or NVMe</li><li>Trade slight latency for higher concurrency</li></ul><p><strong>3. Quantization</strong></p><p>Inference-friendly precision formats:</p><ul><li>FP16 / BF16</li><li>INT8</li><li>4-bit NF4 (QLoRA-style)</li></ul><p><strong>4. Flash Attention</strong></p><p>Optimized attention computation that:</p><ul><li>Reduces memory reads/writes</li><li>Improves cache locality</li><li>Speeds up both prefill and decode phases</li></ul><p><strong>5. Speculative Decoding</strong></p><p>Use a <strong>smaller draft model</strong> to propose tokens:</p><ul><li>Larger model verifies in parallel</li><li>Accepted tokens skip decoding steps</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f1ca57b049" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Small Language Model (SLM) from Scratch: A Complete Guide]]></title>
            <link>https://medium.com/@ashwingadam/building-a-small-language-model-slm-from-scratch-a-complete-guide-95f9c000b713?source=rss-40f4d57ba9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/95f9c000b713</guid>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[ashwin g]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 03:49:47 GMT</pubDate>
            <atom:updated>2025-10-13T03:49:47.661Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this comprehensive guide, we’ll walk through building a Small Language Model (SLM) with approximately 50–60 million parameters from scratch. Unlike massive models like GPT-4, our SLM is designed to be trainable on consumer hardware while still generating creative and coherent text.</p><p>We’ll use the TinyStories dataset — a collection of simple stories that a 3–4 year old could understand — to train our model to generate creative narratives.</p><h3><strong>Architecture Overview:</strong></h3><p>Our SLM is based on the Transformer architecture with the following specifications:</p><ul><li><strong>Parameter Count</strong>: ~50–60 million parameters</li><li><strong>Layers</strong>: 6 transformer blocks</li><li><strong>Attention Heads</strong>: 6 heads per layer</li><li><strong>Embedding Dimension</strong>: 384</li><li><strong>Context Window</strong>: 128 tokens</li><li><strong>Vocabulary Size</strong>: 50,257 tokens (GPT-2 tokenizer)</li></ul><h3><strong>Step 1: Dataset Preparation</strong></h3><h4>The TinyStories Dataset</h4><p>We use the TinyStories dataset from HuggingFace, which contains synthetic short stories generated by GPT-3.5 and GPT-4. These stories use simple vocabulary that young children understand, making it perfect for training a small model.</p><pre>from datasets import load_dataset<br>ds = load_dataset(&quot;roneneldan/TinyStories&quot;)</pre><p><strong>Why TinyStories?</strong></p><ul><li>Simple vocabulary reduces complexity</li><li>Consistent story structure helps the model learn patterns</li><li>Large enough dataset for effective training</li><li>Generated by advanced models, ensuring quality</li></ul><h3>Step 2: Tokenization</h3><h4>Converting Text to Numbers</h4><p>Language models don’t understand text directly — they work with numbers. Tokenization converts text into numerical tokens.</p><pre>import tiktoken<br>enc = tiktoken.get_encoding(&quot;gpt2&quot;)</pre><p><strong>The Process:</strong></p><ol><li><strong>Text Input</strong>: “Once upon a time”</li><li><strong>Tokenization</strong>: [7454, 2402, 257, 640]</li><li><strong>Storage</strong>: Saved in binary files (train.bin, validation.bin)</li></ol><p><strong>Why Binary Storage?</strong></p><ul><li>Efficient disk storage</li><li>Fast loading during training</li><li>Memory-mapped files prevent RAM overflow</li><li>Handles datasets larger than available RAM</li></ul><p><strong>Token IDs Format</strong></p><p>We use uint16 data type because GPT-2&#39;s vocabulary (50,257 tokens) fits within 16 bits (max 65,536).</p><h3>Step 3: Creating Training Batches</h3><h4>Input-Output Pairs</h4><p>The model learns by predicting the next token. For each input sequence, we create a target sequence shifted by one position:</p><p><strong>Example:</strong></p><pre>Input:  [Once, upon, a, time, there]<br>Target: [upon, a, time, there, was]</pre><p>The model learns: given “Once upon a time”, predict “there”</p><p><strong>Batch Configuration</strong></p><ul><li><strong>Batch Size</strong>: 32 sequences processed together</li><li><strong>Block Size</strong>: 128 tokens per sequence</li><li><strong>Gradient Accumulation</strong>: 32 steps (effective batch size: 1024)</li></ul><p>This configuration balances memory usage with training stability.</p><h3><strong>Step 4: Model Architecture</strong></h3><h4>The Transformer Components</h4><h4><strong>1. Token and Position Embeddings</strong></h4><pre>wte = nn.Embedding(vocab_size, n_embd)  # Token embeddings<br>wpe = nn.Embedding(block_size, n_embd)  # Position embeddings</pre><ul><li><strong>Token Embedding</strong>: Converts each token ID to a 384-dimensional vector</li><li><strong>Position Embedding</strong>: Adds positional information (token’s location in sequence)</li><li><strong>Combined embedding</strong> = Token + Position</li></ul><p><strong>2. Causal Self-Attention</strong></p><p>The heart of the transformer. It allows each token to “attend” to previous tokens.</p><p><strong>Key Features:</strong></p><ul><li><strong>Multi-Head Attention</strong>: 6 parallel attention mechanisms</li><li><strong>Causal Masking</strong>: Prevents looking at future tokens</li><li><strong>Scaled Dot-Product</strong>: Computes attention scores</li></ul><p><strong>How It Works:</strong></p><ol><li>Split input into Query (Q), Key (K), Value (V) matrices</li><li>Compute attention scores: Q × K^T / √d</li><li>Apply causal mask (future tokens = -∞)</li><li>Softmax to get attention weights</li><li>Multiply by Values to get output</li></ol><p><strong>Flash Attention</strong>: Uses PyTorch’s optimized scaled_dot_product_attention when available for faster computation.</p><p>3. <strong>Feed-Forward Network (MLP)</strong></p><pre>class MLP:<br>    fc1: Linear(384 → 1536)  # Expand 4x<br>    gelu: GELU activation<br>    fc2: Linear(1536 → 384)  # Project back<br>    dropout: Regularization</pre><p>The MLP processes each token independently after attention, expanding to 4x the embedding dimension then projecting back.</p><h4>4. Layer Normalization</h4><p>Applied before each sub-layer (pre-norm architecture):</p><ul><li>Normalizes activations across the embedding dimension</li><li>Stabilizes training</li><li>Uses learnable scale and bias parameters</li></ul><p>5. <strong>Residual Connections</strong></p><pre>x = x + self.attn(self.ln1(x))  # Attention residual<br>x = x + self.mlp(self.ln2(x))   # MLP residual</pre><p>Residual connections help gradients flow during backpropagation, enabling deeper networks.</p><p><strong>The Complete Block</strong></p><p>Each of the 6 transformer blocks follows this pattern:</p><pre>Input → LayerNorm → Self-Attention → Add → LayerNorm → MLP → Add → Output</pre><p><strong>Weight Tying</strong></p><p>The input token embedding and output projection share weights:</p><pre>self.transformer.wte.weight = self.lm_head.weight</pre><p>This reduces parameters and often improves performance.</p><h3>Step 5: Training Configuration</h3><h4>Optimizer: AdamW</h4><pre>AdamW(lr=1e-4, betas=(0.9, 0.95), weight_decay=0.1)</pre><p><strong>Why AdamW?</strong></p><ul><li>Adaptive learning rates per parameter</li><li>Decoupled weight decay for better regularization</li><li>Beta2=0.95 for better long-term dependencies</li><li>eps=1e-9 for numerical stability</li></ul><h3>Learning Rate Schedule</h3><p>We use a two-phase schedule:</p><p><strong>1. Warmup Phase (1,000 steps)</strong></p><ul><li>Gradually increase learning rate from 0 to 1e-4</li><li>Prevents unstable training at initialization</li><li>Allows model to “settle” before full-speed training</li></ul><p><strong>2. Cosine Annealing (19,000 steps)</strong></p><ul><li>Smoothly decrease learning rate to 5e-5</li><li>Follows cosine curve</li><li>Helps model converge to better minima</li></ul><p><strong>Mixed Precision Training</strong></p><pre>dtype = &#39;bfloat16&#39; or &#39;float16&#39;</pre><h4><strong>Benefits:</strong></h4><ul><li>2x faster training</li><li>50% memory reduction</li><li>Maintains model quality with GradScaler</li><li>Automatic loss scaling prevents underflow</li></ul><h4>Gradient Accumulation</h4><p>With accumulation steps = 32:</p><ul><li>Process 32 batches before updating weights</li><li>Effective batch size = 32 × 32 = 1,024</li><li>Enables large batch training on limited memory</li></ul><h4>Gradient Clipping</h4><pre>clip_grad_norm_(parameters, max_norm=0.5)</pre><p>Prevents exploding gradients by capping the gradient norm, ensuring stable training.</p><h3>Step 6: Training Loop</h3><h4>The Training Process</h4><pre>for epoch in range(20,000):<br>    # Forward pass with mixed precision<br>    with autocast():<br>        logits, loss = model(X, y)<br>        loss = loss / gradient_accumulation_steps<br>    <br>    # Backward pass with gradient scaling<br>    scaler.scale(loss).backward()<br>    <br>    # Update weights every 32 steps<br>    if (epoch + 1) % gradient_accumulation_steps == 0:<br>        clip_grad_norm_(model.parameters(), 0.5)<br>        scaler.step(optimizer)<br>        scaler.update()<br>        optimizer.zero_grad()<br>        scheduler.step()</pre><h3>Evaluation Strategy</h3><p>Every 500 iterations:</p><ol><li>Switch to evaluation mode</li><li>Calculate loss on train and validation sets</li><li>Save model if validation loss improves</li><li>Track learning rate</li></ol><p><strong>Why This Matters:</strong></p><ul><li>Prevents overfitting (validation loss monitoring)</li><li>Saves best model, not just the latest</li><li>Helps diagnose training issues</li></ul><h3>Step 7: Loss Function</h3><h4>Cross-Entropy Loss</h4><p>The model uses cross-entropy loss to compare predicted token probabilities with actual next tokens:</p><pre>loss = CrossEntropy(predicted_distribution, actual_token)</pre><p><strong>Interpretation:</strong></p><ul><li>Lower loss = Better predictions</li><li>Measures how “surprised” the model is by the actual next token</li><li>Gradient drives the model to assign higher probability to correct tokens</li></ul><h3>Step 8: Text Generation</h3><h4>Autoregressive Generation</h4><p>The model generates text one token at a time:</p><pre>def generate(idx, max_new_tokens, temperature=1.0, top_k=None):<br>    for _ in range(max_new_tokens):<br>        # Get predictions for next token<br>        logits = model(idx)<br>        <br>        # Apply temperature (controls randomness)<br>        logits = logits / temperature<br>        <br>        # Optional: Keep only top-k tokens<br>        if top_k:<br>            filter_to_top_k(logits, k)<br>        <br>        # Sample from probability distribution<br>        next_token = sample(softmax(logits))<br>        <br>        # Append to sequence<br>        idx = concat(idx, next_token)</pre><h3>Generation Parameters</h3><p><strong>Temperature</strong>: Controls randomness</p><ul><li>Low (0.1–0.5): Conservative, repetitive</li><li>Medium (0.7–1.0): Balanced creativity</li><li>High (1.5–2.0): Wild, unpredictable</li></ul><p><strong>Top-k Sampling</strong>:</p><ul><li>Considers only the k most likely next tokens</li><li>Prevents sampling from low-probability tokens</li><li>Typical values: 40–50</li></ul><h3>Step 9: Results &amp; Performance</h3><h4>Model Size Calculation</h4><pre>Embedding Layers:<br>- Token embeddings: 50,257 × 384 = 19.3M<br>- Position embeddings: 128 × 384 = 49K<br><br>Transformer Blocks (6 layers):<br>- Attention weights: 384 × 1152 × 6 = 2.65M per layer<br>- MLP weights: 384 × 1536 × 2 × 6 = 7.08M per layer<br>- Total per block: ~9.73M<br>- Total blocks: 58.4M<br><br>Layer norms &amp; output: ~0.3M<br><br>Total: ~58 million parameters</pre><h3>Example Outputs</h3><p><strong>Prompt</strong>: “Once upon a time there was a pumpkin.”</p><p><strong>Generated Story</strong>: The model can generate coherent continuations like:</p><ul><li>Character introductions</li><li>Simple plot developments</li><li>Age-appropriate language</li><li>Story conclusions</li></ul><h3>Training Metrics</h3><p>Typical training progression:</p><ul><li>Initial loss: ~4.5</li><li>After 5,000 steps: ~2.5</li><li>After 15,000 steps: ~1.8</li><li>Final validation loss: ~1.6–1.7</li></ul><h3>Key Takeaways</h3><h3>What Makes This SLM Special?</h3><ol><li><strong>Size</strong>: 58M parameters (vs billions in large models)</li><li><strong>Trainable</strong>: Can train on single GPU in hours</li><li><strong>Effective</strong>: Generates coherent stories despite small size</li><li><strong>Educational</strong>: Perfect for understanding transformers</li></ol><h3>Design Decisions Explained</h3><p><strong>Why 6 layers?</strong></p><ul><li>Balance between capacity and trainability</li><li>Sufficient depth for pattern learning</li><li>Manageable computational requirements</li></ul><p><strong>Why 384 embedding dimension?</strong></p><ul><li>Divisible by 6 heads (64 per head)</li><li>Sweet spot for 50M parameter budget</li><li>Proven effective in similar models</li></ul><p><strong>Why 128 context window?</strong></p><ul><li>Captures sentence-level context</li><li>Fits in memory efficiently</li><li>Adequate for short story generation</li></ul><h3>Limitations</h3><ul><li>Short context (128 tokens) limits long-form coherence</li><li>Simple vocabulary from TinyStories dataset</li><li>May struggle with complex reasoning</li><li>Limited world knowledge</li></ul><h3>Potential Improvements</h3><ol><li><strong>Larger Context</strong>: Increase to 256 or 512 tokens</li><li><strong>More Layers</strong>: 8–12 layers for better capacity</li><li><strong>Better Dataset</strong>: Mix TinyStories with other sources</li><li><strong>Architecture</strong>: Try Rotary embeddings (RoPE)</li><li><strong>Training</strong>: Longer training with more data</li></ol><h3>Conclusion</h3><p>Building a Small Language Model from scratch demystifies how modern AI systems work. With just 58 million parameters, our model learns to generate creative stories, demonstrating that effective language models don’t always need billions of parameters.</p><p>This project showcases:</p><ul><li>Transformer architecture fundamentals</li><li>Efficient training techniques</li><li>Practical deep learning implementation</li><li>Path to understanding larger models</li></ul><p>The complete code provides a foundation for experimentation — try different architectures, datasets, or generation strategies to see how they affect performance!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95f9c000b713" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Positional Embedding in LLM]]></title>
            <link>https://medium.com/@ashwingadam/positional-embedding-in-llm-37a934861d6b?source=rss-40f4d57ba9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/37a934861d6b</guid>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[ashwin g]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 11:13:08 GMT</pubDate>
            <atom:updated>2025-06-30T11:13:08.239Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>What Is Positional Embedding and Why Do LLMs Need It?</strong></h4><p>When humans read a sentence, we understand the meaning based on the order of the words. For example:</p><blockquote><em>“Dog bites man” is very different from “Man bites dog.”</em></blockquote><p>Even though the words are the same, the <em>order</em> changes the meaning. Large Language Models like GPT or BERT must also understand word order to make sense of sentences.</p><p>But here’s the problem…</p><p>Transformers (the neural network architecture used in LLMs) look at all words <em>at once</em>. They don’t naturally know which word came first, second, or last. That’s where <strong>positional embedding</strong> comes in — it acts like a GPS or time-stamp for each word, telling the model where in the sentence each word is.</p><h4><strong>Imagine a Puzzle</strong></h4><p>Let’s say you get a puzzle without any picture on the box. Just 10 pieces. How do you know where each piece goes?</p><p>You don’t.</p><p>Now imagine someone numbers the pieces from 1 to 10 — suddenly you can arrange them in the right order. That’s <em>exactly</em> what positional embedding does for words in a sentence. It gives each word a <em>numbered clue</em> to tell the model where it belongs.</p><h4>How Does It Work Technically</h4><p>Every word is first converted into a vector (a list of numbers) — this is called <strong>word embedding</strong>. Then, we <strong>add or concatenate positional embeddings</strong> — extra numbers that encode the position of the word.</p><p>These position numbers can be:</p><ul><li><strong>Fixed</strong>, like sinusoids (waves), which help the model learn relative positions (used in models like the original Transformer paper).</li><li><strong>Learned</strong>, like trainable weights, which adapt as the model trains (used in models like BERT and GPT).</li></ul><p>So the model doesn’t just know what the word is — it knows <em>where</em> it is.</p><h4>Why Does This Matter in LLMs?</h4><p>LLMs deal with long texts, conversations, documents. If they don’t understand sequence, they can mix up who said what, or lose the context of a story.</p><p>Without positional embedding:</p><ul><li>The model might think “I love pizza” is the same as “Pizza loves I”.</li></ul><p>With positional embedding:</p><ul><li>It knows the subject, verb, and object are in the right place — and it keeps that understanding across <em>hundreds or thousands</em> of tokens.</li></ul><h4>Final Thoughts</h4><p>Positional embeddings are like invisible threads that stitch together the meaning in sentences. They let AI models understand grammar, structure, and flow — turning raw text into meaningful language.</p><p>Without them, even the most powerful model would be like a robot reading a scrambled recipe — all the ingredients, none of the order.</p><p>Without them, even the most powerful model would be like a robot reading a scrambled recipe — all the ingredients, none of the order.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37a934861d6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>