Back to Creators
ACAvi Chawla

Avi Chawla

@_avichawla
AIEnglishMid-Tier (30K–200K)

Shares data science, ML, LLM, and RAG tutorials while covering practical AI tools and agent infrastructure.

Daily tutorials and insights on DS, ML, LLMs, and RAGs • Co-founder @dailydoseofds_ • IIT Varanasi • ex-AI Engineer @ MastercardAI

Share on X
Followers
81.0K
Typical Views
18.2K34 posts · 30d
Bookmark %
1.6%
Authority
—unknown
30d Breakout Hits
9since 2026-11-22
Reach RatioTypical Views / FollowersMid-Tier (30K–200K)
Typical views ≈ 22% of followers·▲ Peer Median 8%2.8×
0%▲100%

7d follower delta is accumulating (tracked since 2026-11-22); 7d net growth appears after multi-day follower snapshots are recorded.

Shipped Products · EarlyLore Portfolio

2 products
View on EarlyLore

Daily Dose of Data Science

dailydoseofds.com
Official

Master Full-Stack AI Engineering From First Principles to Production

117K visits/mo

3-Day Follower Growth

Select a ★ growth spike to view that day’s trigger post and interactions

Follower trendGrowth spike
81.3K80.9K80.5K11-2581.0K+511-2211-2411-25
2026-11-25+5 / day
Total: 81.0K
Notable Post & Bio Update

No single breakout post linked on this date.

Notable InteractionsPublic interactions

No tracked creator interactions recorded on this date.

Content Format Mix

Original 0%Thread 0%Quote 100%Reply 0%
Top & Breakout Posts
Sorted by outlier multiplier & heat
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

10 MCP, AI Agents, and RAG projects for AI Engineers (with code):

780K7.4K(0.9%)3.2K39160
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

Another insane Jev use case!

Traditional database filters need precise, predefined conditions. But many questions are semantic:

- Is this article mainly about software engineering? - Which topic best describes it? - How technically deep does it appear?

These usually require moving rows into application code, invoking a model, parsing its output, and writing the result back.

pg-jev is an open-source Postgres extension that exposes Jev through SQL functions.

- jev() works inside WHERE - jev_prob() returns a probability - jev_choice() selects a label - jev_score() ranks rows across ordered levels.

It needs no vector column or embedding index.

Under the hood, pg-jev batches rows, sends them to Jev, and returns typed answers that SQL can filter, sort, group, and combine with exact predicates.

The recording below runs it against real Hacker News stories stored in Postgres.

It first shows the rows, then asks Jev to find software-engineering stories, classify them by topic, and rank them by technical depth. The final query reports requests, tokens, cost, and cache hits from the database session.

GitHub repo: t.co/6OD0nRMgfH

(don't forget to star it ⭐)

Postgres keeps the data and controls the query, while Jev handles the part SQL cannot express as a deterministic condition.

If you want to understand what Jev is doing under the hood, I also wrote a hands-on guide to building a Jev-style model with open models, entirely locally.

Read it below.

302K4.5K(1.5%)3.2K397137
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

RAG vs. Jev + RAG, clearly explained!

In a standard RAG setup, documents are split into chunks, converted into embeddings, and stored in a vector DB.

When a query arrives, the system embeds it and retrieves the top-k chunks with the closest vectors.

Many production setups add a reranker after retrieval.

The reranker compares the query with each retrieved passage, improves their ordering, and keeps the highest-scoring results.

Those passages are then placed in the context window, and the LLM generates an answer from them.

The problem is that ranking and answerability are different questions.

A passage can be more relevant than the other candidates while still containing weak, incomplete, or merely adjacent evidence.

The LLM receives it anyway and may produce a plausible answer from context that never supported one.

Jev + RAG keeps the retrieval stage as is but changes what happens before generation.

Instead of using a conventional reranker at this stage, Jev can judge every retrieved candidate against a typed question such as:

"Does this passage help answer the query?"

The query becomes the shared state, while the retrieved passages become individual candidates. Jev evaluates them together and returns a probability for each one.

Application code then applies a threshold.

↳ Candidates above the threshold continue to the LLM. ↳ Candidates below it are removed from the context window.

The same Jev request can also judge whether the remaining evidence is sufficient to answer the query.

If answerability falls below the threshold, the application can skip the LLM and return "not in the documents."

Jev does not replace the embedding model, vector database, or generation model. Retrieval still sets the cap because Jev cannot recover a passage that never entered the candidate set.

The diagram below depicts the complete flow.

- RAG retrieves a broad candidate set. - Jev reranks and gates those candidates. - The LLM generates an answer.

If you want to dive deeper, I have also written a hands-on guide showing how to build a Jev-style model with open models, entirely locally.

Read it below.

178K2.7K(1.5%)2.0K30492
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followersHarnessRouter
typical 18.2K

Insane Grok @bot upgrade!

Finally, you can connect Grok Bot to different agent harnesses and run tasks through their native runtimes.

Devs just open-sourced HarnessRouter, the infrastructure layer that lets Grok Bot run tasks across:

- Codex - Hermes - Claude Code - DeepSeek Harness - System One, powered by Jev - Pi, and 20 more

GitHub repo: t.co/4y6zJShd2W

(don’t forget to star it ⭐)

With HarnessRouter, each external specialist gets to use its own harness, model, tools, skills, and agent loop while Grok coordinates the project from one conversation.

I tested this by asking Grok Bot to turn a support-ticket CSV into an interactive dashboard.

Grok Bot assigned the analysis to DeepSeek Harness with Claude Sonnet 5.5, passed the output to Codex with GPT-5.5, and checked the finished dashboard in its browser.

This differs from simply creating more Bots. These workers are not additional Grok Bots, and Grok Bot itself does not switch harnesses.

Instead, it remains the coordinator while the delegated tasks run inside separate HarnessRouter sessions with the harness of your choice.

So for another task, you can use Claude Code, Hermes, Pi, etc., without requiring a separate integration for task execution, sessions, streaming, and generated files.

HarnessRouter standardizes all those operations through the Unified Harness Protocol (UHP).

UHP handles sessions, streaming, files, cancellation, and failures through the same interface, regardless of which harness runs the task.

I shared the GitHub repo above.

And if you want to dive deeper into Grok Bot, I wrote about it in full in a masterclass, including the shared computer, memory, skills, routines, and the macOS setup.

Read it below.

138K3.0K(2.2%)1.3K106183
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

Another big breakthrough after Jev!

Jev answers a fixed question over a fixed input, so a live chat requires re-reading the full transcript on every update.

Devs just built Sage2, which pairs an extraction model and a decision model on the same live stream.

Usually, in a live conversation, the details and the decisions keep changing.

New details show up gradually, and several questions stay open the whole time.

- The extraction stage turns each new message into structured fields in 150 ms, each tied to the exact source span it came from. Those fields then become decision options.

- The decision model scores them as text streams in, and returns typed answers with probabilities, so the full loop from raw text to action runs in about 200 ms.

This gives a fully reactive automation over a live chat, with no re-reading of the transcript.

Sage2 is built by @levantolabs, the team that shipped the first decision model, before Jev.

The video below depicts the model live in action on a broadband support chat, and I worked with the team to put this together.

More details below.

Software can now understand human language and act on it, in real time.

Introducing Sage2 - Extract: natural language in, structured data out. 166x cheaper than Opus 5.5, beats @Cloudflare's Clairic - Decide: the first decision model with streaming. 3x faster, because it reads the context as it grows.

Sage2 is a new primitive for developers. Get 20M tokens free 👇

Also available on @near_ai and, for agents, via @mpp with @Stripe cards and @Tempo stables.

133K2.3K(1.7%)1.5K12224
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

Big win for local LLM inference!

This new inference engine runs LLMs 4x faster than llama.cpp:

I ran Qwen3.5 9B on a base M5 MacBook Pro with three engines:

- llama.cpp: 22.0 tokens/s - MLX: 25.1 tokens/s - uzu: 92.1 tokens/s

The video below shows all three runs side by side.

The first two numbers don't mean llama.cpp or MLX are badly built. But both are sitting right under a hard limit of local decoding.

When an LLM generates text, every new token needs one full pass through the model, and that pass reads all of the model's weights from memory.

A base M5 reads memory at about 153 GB/s. A 4-bit 9B model weighs about 5.2 GB.

So at one token per pass, the ceiling is roughly 153 ÷ 5.2 ≈ 29 tokens/s, however fast the GPU computes.

uzu gets past that ceiling by producing several tokens per pass instead of one:

↳ A small drafter (DFlash) proposes candidates for the next 16 positions at once.

↳ A tiny adapter (Weaver, 56.7M params) picks among them left to right, so the guesses form coherent text, and keeps a few alternative branches as a tree.

↳ The 9B model checks the whole tree in a single pass and keeps the longest path it agrees with. The main model still decides every token that ends up in the output.

GitHub repo: t.co/TKikR80qEA

(don't forget to star it 🌟)

In my run, each pass of the 9B model produced 7.5 tokens on average. Ordinary decoding produces exactly 1.

The weights and kernels are designed around this too. uzu ships its own 4-bit checkpoints, and on M5 chips it runs the verification step on the GPU's int8 matrix path.

uzu is an open-source inference engine by Mirai Labs, written in Rust with Metal kernels. It has Swift, Python, TypeScript and Rust bindings, so the same engine runs inside a Mac or iOS app.

I shared the GitHub repo above.

If you want to dive deeper, my co-founder wrote a detailed breakdown of why local inference is memory-bound and how uzu's speculative decoding gets past it.

Read it below.

129K2.6K(2.0%)1.7K180121
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followersBeacon
typical 18.2K

Top 12 agentic use cases for Jev:

(bookmark this)

Jev handles semantic decisions that ordinary code cannot express reliably. It returns typed answers and probabilities, while code continues to cover the workflow.

Here are 12 practical use cases for Jev:

1. Browser next action

> Convert the current DOM state into a bounded action such as click, type, or stop. Code executes only valid operation-target pairs. There are already several open-source Jev web agents.

2. Context compaction

> Decide which events from a long agent trace should remain. The selected text stays verbatim instead of being replaced with a generated summary.

3. Skill and context loading

> Compare the current user turn against the available skills. Load only the instructions needed for that turn instead of filling the context window with every skill.

4. Typed tool-call compilation

> Map a natural-language request to a function and fill its typed arguments. Each argument is evaluated separately before code allows execution.

5. Citation verification

> Check whether a quoted passage exists and whether the surrounding evidence supports the claim. The output can be supported, unsupported, or contradicted.

6. Extraction verification

> Run a cheap extractor first, then use Jev to verify questionable fields. Clean records stay on the fast path while uncertain ones reach a reasoning model.

7. Agent trace evaluation

> Turn raw trajectories into queryable labels such as progress and repetition. This avoids asking another LLM to write a full review of every run.

8. Semantic regression tests

> Replay a trace suite against a new agent build. Semantic checks can then pass or block prompt, model, tool, and policy changes in CI.

9. Jevgrep code search

> Search a codebase by what the code does rather than its exact words. Jev scores candidate snippets and returns the most relevant code first.

10. Entity alignment

> Compare two candidate records and decide whether to merge, review, or keep them separate. Candidate generation remains deterministic while Jev handles semantic identity.

11. Retrieval reranking

> Let embeddings retrieve a broad candidate set, then use Jev to reorder passages by relevance. The generation model receives the most useful evidence first.

12. Memory promotion gate

> Capture a completed agent trace, then judge whether its corrections contain a reusable lesson. Trace-backed lessons can be promoted while task-specific noise is discarded.

If you want to see the final pattern in practice, it is already implemented in the Beacon open-source project.

Beacon captures full sessions across Claude Code, Codex, Cursor, OpenCode, and 20+ agent harnesses, and then Jev identifies which workflows and corrections are worth learning from, so that a lesson discovered by one agent can become available to the others.

GitHub repo: github.com/Asymptote-Labs/agent-beacon

(don’t forget to star it ⭐)

If you want to dive deeper, I also wrote about a similar mechanism in a hands-on guide. It covers building a Jev-style decision path with open models, entirely locally.

Read it below.

引用帖 @_avichawla: x.com/i/article/2101408350391136256

130K2.0K(1.5%)1.3K17749
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

NVIDIA released a new looped transformer:

Instead of stacking more layers, it runs the same layers multiple times so a 4B model can think like a 9B one.

Here's how it works:

In a standard transformer, every token passes through a stack of decoder blocks once, and each block has its own weights.

So if you want a deeper model, you add more blocks, and the parameter count grows with the depth.

NVIDIA's Dory1.0-4B decouples the two by reusing a chunk of its layers.

The model is split into three parts:

> An input block of 8 blocks runs once and turns the tokens into a hidden state x.

> A recurrent block of 20 shared blocks runs k times, where k can be anywhere from 1 to 4.

> An output block of 8 blocks runs once on the final state, followed by the LM head.

Before every pass through the recurrent block, x is added back to the current state and the sum is L2-normalized.

This keeps the original token representation in view on every pass, instead of each pass only seeing what the previous one produced.

Both models in the diagram below store 36 blocks of weights.

The standard transformer applies each block once, while Dory applies 36 blocks at k=1, 56 at k=2, and 96 at k=4, i.e., 72, 112, and 192 physical layers from the same checkpoint.

The extra depth is actually helpful on reasoning and agentic tasks:

> SWE-bench Verified:

- at 1 loop → 50.3 - at 2 loops → 59.5 - at 4 loops → 61.8

> 12-benchmark average:

- at 1 loop → 35.17 - at 2 loops → 39.67 - at 4 loops → 40.60 - and with 2 or more loops, it beats Qwen3.5-9B, Gemma 4 12B, and Gemma 4 26B-A4B.

More loops implies more compute per token, but the 4-loop model also writes 1.3x to 2.5x fewer output tokens on agentic tasks.

So 2 loops end up costing only 1.03x to 1.25x the compute of 1 loop end to end, which is why NVIDIA recommends 2 as the default.

By default, Dory keeps a separate KV cache for every loop, so at 4 loops the recurrent layers store 4x the cache.

To avoid this, it can keep only the cache from the last loop, which uses the same KV memory as a normal model with only a small change in accuracy.

One thing to note here is that looping helps the model reason over what it already knows, but it does not add knowledge.

For instance, on tasks like AA-Omniscience, accuracy stays at 10.0 whether you run 1 loop or 4, and on knowledge-heavy tasks like GPQA, Dory still trails Qwen3.5-4B.

Here's the paper: t.co/pdrqhdCHpZ

That said, how much memory looping costs comes down to how the KV cache is handled, so I wrote a full breakdown of how KV caching works.

It covers what gets cached during prefill, how the cache grows during decoding, and why it becomes the main memory bottleneck at long context.

Read it below.

111K1.7K(1.6%)1.8K22163
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

Skills 2.0 is here!

(8x fewer tokens and 2x faster)

We package repeated workflows as skills all the time, but the agent still re-reads the skill and decides every step on every run, which costs tokens and time.

Devs just open-sourced Swamp, where your coding agent turns a repeated skill into a workflow that it builds once and runs again and again.

You describe the task once, and the agent breaks it into reusable behaviors connected in a workflow.

Every behavior has typed inputs and outputs, and plain code decides which step runs next. Swamp then gives you:

- model calls only on steps that need judgment - secrets pulled from vaults and redacted from output - versioned data from every run that you can query later - a full record of what happened on each run

Here's the repo: t.co/GtaNpqAngp

(don't forget to star it ⭐ )

Swamp plugs into the coding agent you already use, like:

- Claude Code - Codex - Cursor - OpenCode - And 5 more agent harnesses

In Swamp, the model is a step in the workflow, not the thing deciding what happens next.

The model steps still reason like any LLM call.

However, in this case, code owns the loop, so the agent doesn't spend tokens rediscovering the same process every time.

Here's an official result, where they turned a code-review skill into a Swamp workflow:

- Skill in Codex: about 4.6M tokens, 23 agents, 12.8 minutes - Swamp workflow: about 506K tokens, 3 agents, 6.6 minutes

That is ~8x fewer tokens in about half the time, and most of the savings came from replacing the coordinator agent with plain code.

You can keep using skills while you prototype. Once a task starts repeating, ask your agent to turn it into a Swamp workflow.

This helps answer practical questions such as:

- Which steps actually need a model? - What exactly happened on last week's run? - Can a cheaper model handle the one step that needs judgment?

Once it's built, you can run the workflow from your agent, the CLI, a schedule, or an API, with every run recorded.

So you are no longer paying a model to figure out the same workflow on every run.

Instead, you spend tokens only on the steps where the model's judgment adds something.

The animation below shows how Swamp differs from Skills, and I worked with the team to put this together.

If you want to understand the coordination layer that Swamp replaces with code, I wrote a full breakdown of how Claude Code splits work across subagents and agent teams.

It covers when a single subagent is enough, when you need a team of agents that coordinate with each other, and what that coordination costs in context and tokens.

Read it below.

76.1K1.3K(1.7%)87593107
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followersBeacon
typical 18.2K

Another insane way to use Jev:

Jev makes it dramatically cheaper to identify which corrections and trajectories from an agent run are reusable across agents.

And finally, someone open-sourced a self-improving memory layer that can put that signal to work across agent harnesses:

- Claude Code - Codex - Cursor - OpenCode - Hermes, and 20+ more

Beacon by @asymptotelabs continuously captures agent sessions across harnesses and stores their traces in a shared index.

I used it with Jev to build a live cross-agent memory workflow.

Beacon captures each run as it happens across all harnesses on my machine. Then Jev evaluates whether the trace contains a reusable engineering lesson, and the approved lesson becomes available to the next agent.

GitHub repo: t.co/7n0b9guyQI

(don't forget to star it ⭐)

Preserving an agent run and learning from it are two different problems.

Most traces contain file reads, failed commands, routine exploration, and implementation details that only apply to one task.

Passing the complete transcript to another agent adds context without identifying what matters.

In this workflow, one agent never receives another agent's raw transcript. It receives only the specific engineering lesson produced from the evaluated trace.

A correction made in one agent can then prevent the same mistake when another agent encounters a similar problem.

The recording shows the complete workflow I built.

If you want to dive deeper into Jev, I also wrote a hands-on guide to building this Jev-style decision path with open models, entirely locally.

Read it below.

72.0K1.3K(1.8%)6697224
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

RAG vs. Graph RAG vs. Agentic RAG, clearly explained!

Standard RAG embeds documents into vectors and retrieves the most similar chunks via similarity search. For direct factual lookups, this works well.

But it breaks down when a query needs to connect facts spread across multiple documents. Similarity search retrieves individual chunks, not the relationships between them.

Graph RAG adds a knowledge graph layer on top.

→ During indexing, an LLM extracts entities and relationships from the documents.

→ During retrieval, the system traverses these connections instead of relying on embedding similarity alone.

This is what enables multi-hop queries.

Say a vector DB stores three facts about internal services:

↳ "The checkout service uses payments API." ↳ "The payments API runs on cluster-3." ↳ "Cluster-3 is scheduled for maintenance on Friday."

Someone asks: "Will the checkout service be affected by Friday's maintenance?"

Vector search can likely retrieve facts 1 and 3 because the query mentions "checkout service" and "Friday maintenance."

But it will miss fact 2, which connects the payments API to cluster-3.

That middle fact sits too far from the query in embedding space. It mentions neither "checkout" nor "maintenance," so it never makes it into the retrieved context.

A knowledge graph connects these as linked entities, and graph traversal finds the full path in one query.

Agentic RAG takes a different approach entirely.

Instead of a fixed retrieval pipeline, an LLM agent decides at query time which tools to invoke, which sources to query, and in what order.

Check the visual below to understand the three architectures thoroughly.

One thing to note here is that these three aren't levels of sophistication that you need to graduate through.

Instead, they solve different query types.

↳ Single-hop factual lookups → standard RAG ↳ Multi-hop relationship queries → Graph RAG ↳ Dynamic multi-source tasks with tool use → Agentic RAG

Once the right architecture is in place, the next leverage point is efficiency.

Most RAG architectures rely heavily on vector search, and that layer can be made 32x more memory-efficient using binary quantization.

I covered the full implementation in the article below.

👉 Over to you: Which RAG architecture are you running in production?

68.1K879(1.3%)5969044
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followersHarnessRouter
typical 18.2K

System 1 vs. System 2 Agent Harnesses, clearly explained:

(bookmark this)

There are two different ways to put AI inside an application.

A System 1 harness asks the model to make a bounded judgment.

The app provides a request and relevant state. The model selects a constrained result such as a category, score, route, or extracted field.

Code checks confidence and policy before executing the result or escalating the case.

The model does not own the workflow. It selects from choices supplied by code.

This works well for intent classification, model routing, risk gates, reranking, and other high-volume decisions where the possible outputs are known in advance.

Jev is designed for this System 1 role to make fast, bounded judgments while application code controls the workflow.

A System 2 harness handles work whose path cannot be specified upfront.

The LLM receives a goal, constraints, and current state. It plans the next step, while a guarded router controls which tools it can invoke.

Tool results return to the harness, which updates state and verifies progress. Each cycle can end in a final action, a question for the user, or another plan.

The LLM helps drive the workflow, but it should not have authority. Tool permissions, budgets, stop conditions, and final execution remain in application code.

This pattern is useful for coding, research, incident investigation, and other tasks involving several dependent actions.

So this is not primarily a small-model versus large-model distinction but rather a difference in control flow.

Most production apps need both: System 1 for fast, bounded judgments and System 2 for ambiguous or multi-step work.

The next engineering problem is running both patterns without maintaining a separate execution layer for every harness.

And the solution to this is now actually open-source and implemented in HarnessRouter.

It provides the infrastructure layer between an application and the harnesses that execute its work.

- Its System One base can run Jev and other decision models that select finite actions using typed outputs and confidence gates.

- Its agent-harness bases support runtimes such as Codex, Claude Code, and Hermes, which can plan, call tools, manage files, and complete open-ended tasks.

GitHub repo: github.com/HarnessRouter/harnessrouter

(don't forget to star it ⭐)

HarnessRouter does not make these systems reason identically. Instead, it only standardizes the infrastructure surrounding their execution.

Through the Unified Harness Protocol, an application gets one contract for starting tasks, streaming progress, continuing sessions, exchanging files, cancelling work, and reporting structured failures.

This lets an application select the appropriate harness without rebuilding its task lifecycle around every runtime.

If you want to dive deeper, Akshay wrote a detailed article explaining how HarnessRouter and the Unified Harness Protocol provide this infrastructure layer.

It covers why model routing is not harness routing, how tasks and sessions work across runtimes, the local setup, and a complete API call.

Read it below.

引用帖 @akshay_pachaar: x.com/i/article/2100874380012056576

57.4K650(1.1%)4346232
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

Turn any open LLM into a Jev-style model:

Researchers just open-sourced AnyJev, a Python library that extracts typed choices, yes/no judgments, scores, and probabilities from causal LLMs.

Beyond its raw baseline, AnyJev offers three levels depending on how much labeled data and calibration you need:

- L0 requires no labels. It rotates the answer options to reduce position bias, but its probabilities remain uncalibrated.

- L1 uses 100-500 labeled examples per question to calibrate those probabilities through temperature scaling. It improves confidence estimates without changing the answer ranking.

- L2 uses 100-300 labels to fit a closed-form head on an intermediate hidden state. It leaves model weights untouched and can stop inference before the full forward pass completes.

The main constraint is model access. AnyJev requires access to logits or hidden states, so it is built for open models. L2 heads are also specific to a model and question.

It is compatible with several open causal LLMs.

Repo: github.com/nokia-applied-research/AnyJev

(don't forget to star it ⭐ )

If you want to dive deeper, I also wrote about a similar mechanism in a hands-on guide. It covers building a Jev-style decision path with open models, entirely locally.

Read it below.

引用帖 @_avichawla: x.com/i/article/2101408350391136256

56.4K780(1.4%)5279320
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

Prompt, context, harness & loop engineering, clearly explained!

An agent is a while loop with four layers of engineering wrapped around it:

- Prompt engineering - Context engineering - Harness engineering - Loop engineering

Each one wraps the last, and the model sits in the middle, so none of them compete with the others. Instead, they just zoom one level further out.

> Prompt engineering:

This defines the input the model sees on one call, often composed of a role, instructions, examples, and an output format.

The techniques here alter the internal computation and reasoning the model goes through due to the wording it sees:

- Chain-of-thought makes it work in steps before answering - Few-shot examples define the format and the edge cases - A JSON schema or XML tags make the output parseable by code - Self-consistency samples a few chains and takes the majority

> Context engineering:

It's everything the model sees on a turn, not just the prompt. That includes the query, retrieved docs, memory, prior turns, and tool outputs from earlier steps.

The window is finite and fills up fast, so the engineering work is to rank inputs and cut everything that isn't pulling weight.

You do this by:

- Retrieving only the chunks relevant to the query, then reranking them - Keeping key facts out of the middle, where accuracy drops - Summarizing old turns, evict stale outputs, push big blobs to files

> Harness engineering:

It's the code around the model that defines the tools, parses the calls, retries on failure, and can route work to sub-agents so one handles retrieval and another handles code.

A verifier then grades the result by running tests, validating a schema, etc.

Prompt and context involve getting one call right. The harness involves everything that has to happen around that call for it to run in a real system.

> Loop engineering:

In the usual setup, you manage the outer loop, i.e, you write a prompt, read the turns the agent runs, write the next prompt, and repeat, while catching failures.

This layer hands that job to the agent itself. It kicks off on a schedule or an event, and runs many turns with no prompt in between.

A loop inherently doesn't know when it's finished. An agent can report that it's done and halt while the tests still fail. So the stop can't be the agent's word, but rather it has to be a real signal, like:

- A turn and token cap to stop stuck runs - A no-progress detector to catch repeated calls - A completion check to verify the goal with a separate model or a deterministic test

By this layer, you're operating on the whole run, so the engineering moves from writing each prompt to setting the goal and the stop conditions up front and letting it run.

A longer run also makes the cost of the layers underneath it grow.

When a tool returns a 50K-token response and nothing removes it, the model reads it again on every later call. Over a loop of twenty steps, one response turns into hundreds of thousands of tokens.

I wrote a full breakdown of where an agent's tokens actually go and how a harness keeps context flat, using TrueForge, an open-source harness that turns an LLM into a working agent.

GitHub repo: t.co/ZjePhhfKIh

(don't forget to star it ⭐ )

It covers offloading large tool outputs to files, subagents for context isolation, Code Mode for multi-tool joins, and compaction.

It also has a benchmark of three harnesses on the same 14 tasks, where TrueForge reached the same answers on about 40% of the tokens Claude Managed Agents used.

You can read my full article below.

50.5K980(1.9%)73514274
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

Why temperature 0 isn't deterministic in LLM inference?

(a popular technical LLM interview question)

At temperature 0, inference engines usually switch to greedy decoding directly. At every step, they pick the highest-logit token, so the same prompt should give the same output every time.

In practice, it doesn't.

Thinking Machines actually tested this by sending "Tell me about Richard Feynman" to Qwen3-235B 1,000 times at temperature 0 and got 80 unique completions.

While picking the biggest logit is a perfectly deterministic step...

...the variation actually comes from computing the logits themselves. If those numbers come out slightly different, argmax can pick a different token.

Let's understand how the logits can slightly change at times.

1) The order of addition changes the result:

GPUs store numbers with limited precision. fp16 keeps only 11 significant bits, and between 1024 and 2048, that leaves no room for anything after the decimal point. So 1024.4 gets rounded back to 1024.

Now consider 1024 + 0.4 + 0.4 in two orders.

Left to right, 1024 + 0.4 rounds back to 1024, and adding 0.4 again rounds back to 1024. The answer is 1024.

If the small numbers go first, 0.4 + 0.4 gives 0.8, and 1024 + 0.8 rounds up to 1025. The answer is 1025.

An LLM performs billions of such additions in every forward pass, so if their order changes, the logits change slightly too.

2) What causes the order to change?

The popular reason is that parallel GPU threads finish in an unpredictable order.

But that isn't the main reason, since the kernels in a typical forward pass compute each sum in a fixed order.

So the same matrix multiplication on the same inputs, at the same batch size, gives bit-for-bit identical results every time.

3) The real reason is the other requests on the server:

An inference server groups requests from many users into a batch and runs them together.

The kernels decide how to split their work based on the batch size.

- With a large batch, every GPU core is busy, so each core computes its sum in one go.

- With a small batch, many cores would sit idle, so the kernel cuts each long sum into chunks, spreads them across cores, and combines the partial results at the end.

A different split leads to a different order of addition, and the batch size depends on how many other people are using the server at that moment.

4) How this tiny difference changes the entire answer:

Consider two runs of the same prompt:

In a batch of 8, say the logits come out as: - "Queens" = 12.3417 - "New" = 12.3415

In this case, argmax picks "Queens".

In a batch of 32, the rounding works out slightly differently, giving: - "Queens" = 12.3414 - "New" = 12.3416

In this case, argmax picks "New".

The output only flips at such near ties. And every token after that is generated from a different prefix.

In the above test by Thinking Machines, all 1,000 runs matched for the first 102 tokens. At token 103, 992 runs wrote "Queens, New York" while 8 wrote "New York City".

5) The solution:

This isn't a big problem per se, but to make it genuinely deterministic, every kernel should split its work the same way regardless of batch size (for attention, that means a fixed chunk size), even if it leaves some cores idle.

Thinking Machine tested this with batch-invariant kernels, where all 1,000 runs were identical. But this impacted speed.

On Qwen3-8B, default vLLM took 26s for 1,000 requests, while the deterministic version took 55s, and 42s after an improved attention kernel.

The visual below depicts what we discussed.

That said, batching isn't the only thing that changes how these sums get split.

A cache hit does too, since some attention kernels process cached tokens separately from new ones, and Thinking Machines had to handle this case explicitly.

I recently covered the four caches in LLM serving in an article, with code for each.

Read it below.

49.4K838(1.7%)75910141
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

RAG vs. Vectorless RAG, clearly explained!

In a standard RAG setup, documents are split into chunks, embedded, and stored in a vector DB. The query gets embedded too, and the top-k closest chunks go to the LLM.

The problem is that similarity and relevance answer different questions.

For instance, five annual reports from one company can likely follow the same template every year, and only the numbers can change.

So a FY2022 question can lie just as close to an FY2025 chunk, and the LLM might answer from the wrong year.

Cross-references introduce another problem. If a chunk mentions "see Appendix G" but looks nothing like the table in Appendix G, that table will never make it to the top-k.

Vectorless RAG drops the embedding model and the vector DB, and replaces similarity search with LLM reasoning instead.

The preprocessing step parses each document's layout into a ToC tree index. Every node holds a section title, its page range, and a short summary, and the whole tree fits in the LLM's context.

At query time, the LLM gets the query along with the tree. It reads the section titles and summaries and picks the few sections most likely to hold the answer.

For example, for a question about debt, it might pick the "Financial Summary" section and also "Appendix G", because its summary says the debt details are there.

The system then pulls those full sections and checks whether the evidence is enough.

↳ If it is, the LLM answers from the full sections, with page citations. ↳ If not, it goes back to the tree and opens more nodes.

The LLM also sees the chat history. So if you ask about assets and then follow up with "what about liabilities?", it goes back to the same report.

The trade-off is that every query now runs LLM calls over the tree.

Top-k vector search will be cheaper in that same run (although not guaranteed to be as accurate), and the tree only helps when documents have real structure.

So the two suit different data:

↳ Use a tree for long, structured documents like filings, contracts, and manuals. ↳ Stick with a vector DB for lots of short, unrelated text.

The diagram below depicts both flows.

If you want to dive deeper, I have also written a full breakdown of MIT's Recursive Language Models.

It covers why LLMs get worse as context grows and how RLMs let the model split a long document and work through it piece by piece.

Read it below.

47.5K752(1.6%)6418452
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

This is the ChatGPT moment for Voice AI.

A ten-second sample can show that a synthetic voice sounds natural. But it tells little about whether that voice can stay coherent across an entire conversation.

Real callers ask follow-up questions, change their requirements, and interrupt before the agent finishes speaking. The voice must respond quickly without resetting its tone and pacing after every turn.

This creates two memory problems.

- The LLM needs to remember what the caller said. - The speech model needs to retain how the agent has been speaking.

A transcript handles the first problem, but not the second. It preserves the words, not their delivery or how much of the previous response the caller actually heard.

Deepgram's Flux TTS handles this by maintaining acoustic state inside a persistent streaming session. Each response begins with the speech history from earlier turns, and the first audio arrives in under 200 ms.

Flux also handles interruptions through playback tracking. The application sends the point where playback stopped, and the API reports which words the caller heard.

That gives the LLM an accurate conversation history for its next response.

In a blind listening evaluation across roughly 14,400 paired comparisons, Flux's best voice recorded a 73.4% naturalness win rate. Cartesia Sonic 3.5 recorded 72.0%.

Build with Flux TTS here: t.co/CT2TXyjZ1Y

I recorded a conversation with a car dealership agent about hybrid and electric cars. I changed my requirements and asked follow-up questions to hear how the voice behaved across the full exchange.

The recording is below, and I worked with the Deepgram team on this post to put it together.

42.8K997(2.3%)6737319
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

A tricky LLM interview question:

You're serving a reasoning model on vLLM, and long traces keep pushing it out of GPU memory.

You add KV cache compression and evict 90% of the cached tokens.

VRAM usage doesn't move, and the GPU still runs out of memory.

Why?

(answer below)

Evicting 90% of the KV cache can free close to zero bytes on a paged server.

During decoding, every new token appends its key and value vectors at every layer. vLLM holds all of them until the request finishes.

For reasoning models with long chains of thought, this cache is the main memory cost.

A Qwen3-32B with 4-bit weights on a 24GB GPU needs KV for every token of a 32K-token trace, and it hits OOM around 24K tokens.

Attention over long contexts is sparse, so you can keep the high-importance tokens and drop the rest with little accuracy loss.

That reduces the number of cached tokens but it doesn't necessarily reduce allocated memory.

vLLM manages the cache with PagedAttention. It splits GPU memory into fixed physical blocks of 16 token slots each.

The allocator reclaims a block only when all 16 slots are empty.

Importance-based eviction keeps tokens scattered across the full sequence, so the retained tokens are spread over nearly every block.

Evict 14K of 16K tokens across 1,000 blocks, and almost every block still holds at least one token.

So the allocator reclaims close to nothing.

You could write new tokens into the empty slots. If token 16,001 goes into the slot token 40 held, the block now reads positions 38, 16,001, 41.

The cache is no longer in position order. Attention still gives the correct result, but each slot now needs a stored position index, and every kernel has to read it.

An in-order layout doesn't need that metadata.

So the cache shrinks 90% logically and 0% physically. Many compression papers miss this because they benchmark on pre-allocated contiguous tensors instead of a paged server.

The second problem is the eviction signal.

Most eviction methods rank tokens by their attention scores.

FlashAttention never materializes those scores. It computes attention tile by tile in on-chip SRAM and discards each score tile after use, which is where its speed comes from.

To get the scores, you have to fall back to eager attention and build the full score matrix in HBM, which removes the speedup FlashAttention provides.

NVIDIA's TriAttention handles both problems.

It ranks tokens without attention scores. It uses the geometry of the query and key vectors before RoPE is applied, where they form stable clusters.

Every 128 decoded tokens, it runs a compaction pass. Retained tokens move forward to fill the evicted slots, so trailing blocks empty out completely and return to the allocator, and the cache stays in position order.

On long reasoning traces, it matches full-attention accuracy with 2.5x faster decoding and 10.7x less KV memory.

For KV cache compression on a real server, the metric to track is blocks freed, not tokens evicted.

NVIDIA's write-up: t.co/ZwXv7VezVu

I also wrote a first-principles breakdown of the KV cache. It covers why the model caches keys and values, why the cache grows with every token, and how generation speed compares with and without caching.

Read it below.

41.8K856(2.1%)6678947
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

I have been fine-tuning LLMs for over 3 years now.

Here are 5 LLM fine-tuning techniques, explained with visuals:

Traditional fine‑tuning is impractical for LLMs (billions of params; 100s of GB).

Since this kind of compute isn't accessible to everyone, parameter-efficient fine-tuning techniques (PEFT) were built.

Before we go into details of each technique, here's some background that will help you better understand these techniques:

LLM weights are matrices of numbers adjusted during fine-tuning.

Most PEFT techniques involve finding a lower-rank adaptation of these matrices, a smaller-dimensional matrix that can still represent the information stored in the original.

Now with a basic understanding of the rank of a matrix, we're in a good position to understand the different fine-tuning techniques.

(refer to the image below for a visual explanation of each technique)

1) LoRA

- Add two low-rank trainable matrices, A and B, alongside the weight matrices. - Instead of fine-tuning W, adjust the updates in these low-rank matrices.

Even for the largest LLMs, LoRA matrices take up a few MBs of memory.

2) LoRA-FA

While LoRA significantly decreases the total trainable parameters, it requires substantial activation memory to update the low-rank weights.

LoRA-FA (FA stands for Frozen-A) freezes matrix A and only updates matrix B.

3) VeRA

- In LoRA, low-rank matrices A and B are unique for each layer. - In VeRA, A and B are frozen, random, and shared across all layers. - Instead, it learns layer-specific scaling VECTORS (b and d) instead.

4) Delta-LoRA

- It tunes the matrix W as well, but not in the traditional way. - Here, the difference (or delta) between the product of matrices A and B in two consecutive training steps is added to W.

5) LoRA+

- In LoRA, both matrices A and B are updated with the same learning rate. - Authors of LoRA+ found that setting a higher learning rate for matrix B results in better convergence. ____ Find me → @_avichawla Every day, I share tutorials and insights on DS, ML, LLMs, and RAGs.

42.4K1.1K(2.7%)83513026
View on X
ACAvi Chawla
Avi Chawla@_avichawlaAI81.0K followers
typical 18.2K

A good technical LLM interview question:

You replace a dense feed-forward layer with a top-2 MoE.

The profiler confirms that the MoE executes fewer FLOPs per token.

However, end-to-end inference latency has increased instead of decreasing.

Why did this happen?

(answer below)

A standard Transformer applies the same feed-forward network to every token in a layer.

An MoE layer replaces that network with multiple experts. Each expert is a feed-forward network with its own weights.

A router reads each token's hidden-state vector, scores the available experts, and selects the top two. It also produces a routing weight for each selection.

Only those selected experts process the token. The model therefore contains many expert weights while executing only a small subset for each token.

The serving system must move activations when the selected experts are stored on different GPUs.

The visual follows a batch that begins on GPU 0.

The router returns two expert IDs and two routing weights per token. One selected path is shown for each example token to keep the diagram readable.

Token T1 selects E1 on GPU 0. Its activation remains in local GPU memory, where E1 processes it.

T2 selects E4 on GPU 1 in the same server. GPU 0 transfers the activation through NVLink, a high-bandwidth GPU-to-GPU connection. NVSwitch connects several GPUs through this fabric.

T3 selects E7 on GPU 2 in another server. Its activation crosses the cluster network through InfiniBand or Ethernet.

To be clear, the system transfers activation vectors, which are the numerical representations produced for a token by the preceding Transformer operations.

Each destination GPU runs its expert and returns the output to GPU 0.

GPU 0 multiplies both selected expert outputs by their routing weights, adds them together, and restores the original token order.

Different tokens can select different expert pairs. Across a batch, those assignments may involve every GPU storing experts.

Each GPU may therefore send activations to several GPUs while receiving activations for its own experts. This exchange is called all-to-all communication.

And there are several ways to optimize this.

For instance, keeping frequently selected experts within the same server reduces remote traffic.

Balanced routing prevents one GPU from delaying the layer.

Communication overlap allows local expert computation to continue while remote activations move.

In this setup, sparse routing reduces expert FLOPs, but token dispatch and network communication erase part of that saving.

If you want to dive deeper, I recently covered MoE inference engineering, including routing, expert placement, token dispatch, load balancing, communication overlap, memory, quantization, and offloading.

Read my article below.

引用帖 @_avichawla: x.com/i/article/2100852768403861504

39.5K498(1.3%)4636620
View on X

Similar Creators

Explore AI →