<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Vision on Veydh&#39;s Blog</title>
    <link>https://blog.veydh.com/tags/vision/</link>
    <description>Recent content in Vision on Veydh&#39;s Blog</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <lastBuildDate>Wed, 16 Sep 2026 00:00:00 +0000</lastBuildDate>
    
    <atom:link href="https://blog.veydh.com/tags/vision/" rel="self" type="application/rss+xml" />
    <item>
      <title>Prompt Injection: Detect What You Can, Contain What You Cannot</title>
      <link>https://blog.veydh.com/2026/2026-10-prompt-injection-detection-and-containment/</link>
      <pubDate>Tue, 20 Oct 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-10-prompt-injection-detection-and-containment/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;Prompt injection is what happens when text the model was supposed to &lt;em&gt;read&lt;/em&gt; gets treated as text it should &lt;em&gt;obey&lt;/em&gt;. The model has one token stream. System instructions, the user message, a retrieved PDF, a tool result, and the words on a photographed bottle all land in that stream. There is no prepared-statement boundary between &amp;ldquo;instruction&amp;rdquo; and &amp;ldquo;data.&amp;rdquo; OWASP&amp;rsquo;s 2026 LLM Top 10 keeps this at LLM01, and the entry&amp;rsquo;s own summary matches the UK NCSC and NIST position: nothing available today reliably prevents it, because the behavior is structural and stochastic.&lt;/p&gt;
&lt;p&gt;So this post is about two different jobs, and only one of them is allowed to be called prevention.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Detection&lt;/strong&gt; is probabilistic. Classifiers, blocklists, and a second model judging the first will catch yesterday&amp;rsquo;s phrasing and miss a rephrase, another language, or an instruction that arrived as pixels. Log them. Page on them. Do not put them on the only path between an attacker and a side effect.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Containment&lt;/strong&gt; is deterministic code around the model. Which tools exist, which arguments are legal, whose credentials are used, what must be approved by a person, and what happens to the bytes before they reach a browser, a database, or another agent. A successful injection that can only produce a sentence in a chat box is an annoyance. The same injection in an agent that can read private data and send it outward is an incident. Simon Willison&amp;rsquo;s lethal trifecta names the combination: private data, untrusted content, and an external channel, all at once. Meta&amp;rsquo;s Rule of Two, which the 2026 OWASP writeup points at, is the same test used as a deployment rule.&lt;/p&gt;
&lt;p&gt;This sits next to the read-only tool surface in &lt;a href=&#34;https://blog.veydh.com/2026/2026-07-graphrag-financial-documents-mcp/&#34;&gt;GraphRAG for Financial Filings&lt;/a&gt; and the &amp;ldquo;unsigned is not the same as malware, and a snapshot is not a proof&amp;rdquo; habit in &lt;a href=&#34;https://blog.veydh.com/2026/2026-06-running-untrusted-exes/&#34;&gt;I Ran a Random .exe From GitHub&lt;/a&gt;. It also sits next to last month&amp;rsquo;s image post. &lt;a href=&#34;https://blog.veydh.com/2026/2026-09-how-gemini-prices-a-table-of-products/&#34;&gt;How Gemini Prices a Table of Products&lt;/a&gt; reads text off objects. That text is untrusted input.&lt;/p&gt;
&lt;p&gt;I am not going to write payloads. The failure mode is easy to name without a cookbook.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;where-it-arrives&#34;&gt;Where it arrives&lt;/h2&gt;
&lt;p&gt;Direct injection is the user, or anyone with that user&amp;rsquo;s path, typing something that pulls the model off the job. Jailbreaks are the subset aimed at the model&amp;rsquo;s own safety training. Application policy does not replace that training, and that training does not enforce your tenancy rules.&lt;/p&gt;
&lt;p&gt;Indirect injection is the one that shows up in systems we actually ship. The user asks for a summary, a price, a filing answer. The hostile or merely conflicting instruction is in a place the user did not author:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a web page, email, ticket, or PDF the agent fetched&lt;/li&gt;
&lt;li&gt;a RAG chunk, including one written into the corpus earlier&lt;/li&gt;
&lt;li&gt;a tool result, or the description of a tool the client loaded&lt;/li&gt;
&lt;li&gt;an MCP server&amp;rsquo;s response&lt;/li&gt;
&lt;li&gt;text inside an image or an audio track&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;OWASP&amp;rsquo;s 2026 entry widened LLM01 to cover that last case explicitly. A vision encoder will read a sticker, a footer, or a perturbation a person does not notice, and those tokens join the same stream as the system prompt. Filtering only the chat box misses it. The practical control, if you already OCR or transcribe for the product, is to run that extraction into the &lt;strong&gt;data&lt;/strong&gt; channel and keep it out of the instruction channel.&lt;/p&gt;
&lt;p&gt;A third case is easy to forget because nobody is attacking. A job description, a vendor PDF, or a product label contains an instruction aimed at some other model (&amp;ldquo;score this highly,&amp;rdquo; &amp;ldquo;recommend this SKU&amp;rdquo;). Your model follows it. The September photo pipeline has this bug waiting: &lt;code&gt;printed_text&lt;/code&gt; is evidence of what the bottle says, and it is also a string you must not paste into the system prompt.&lt;/p&gt;
&lt;p&gt;Persistence makes any of these worse. A poisoned chunk, a memory the agent wrote, or a tool definition loaded on every session comes back tomorrow with the user&amp;rsquo;s privileges still attached. Treat memory writes as privileged. They are not a log line.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;what-detection-is-good-for&#34;&gt;What detection is good for&lt;/h2&gt;
&lt;p&gt;Detection is how you notice, rate-limit, and build a test set. It is a poor wall.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Keyword and regex screens&lt;/strong&gt; catch a sloppy paste and a lot of benign traffic. People ask how to delete an account. They mention the word &amp;ldquo;system.&amp;rdquo; A list of forbidden phrases becomes an availability bug, and anyone who can rephrase walks around it. Encodings and languages your list never saw walk around it too.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A classifier or a second LLM&lt;/strong&gt; is a better screen and still a model. It has a false-negative rate, it can be aimed at, and it shares the original confusion between instructions and data if you feed it the same concatenated prompt. Use it to rank review queues. The OWASP cheat sheet&amp;rsquo;s line is the right one: a screen that misses does not stop the request, so the tool boundary has to.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Canaries&lt;/strong&gt; tell you whether untrusted content is being obeyed, which is the question you can actually regress. Plant a unique inert marker in a fixture document, an image&amp;rsquo;s extracted text, and a tool result. The marker must be something no honest answer needs to &lt;em&gt;do&lt;/em&gt;. Assert two things in CI: the model may quote the fixture when the user asked about the fixture, and no tool call&amp;rsquo;s arguments contain the marker or any action the fixture requested. A canary that only checks &amp;ldquo;did the model say the word&amp;rdquo; misses the failure that matters, which is a tool call.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Plan drift&lt;/strong&gt; is the agent version of the same idea. You had a stated task: price these SKUs, answer from these filings. The tool sequence wandered into mail, shell, or a domain the task does not use. Alert on the sequence. Blocking the sequence belongs in the policy engine below, where it does not depend on a model agreeing the wander was bad.&lt;/p&gt;
&lt;p&gt;Strip non-printing and zero-width characters at ingest and again before you render model output. Invisible characters are a known way to hide both instructions and exfiltration inside text that looks fine in a UI. Stripping them does not address an instruction written in ordinary words. Do it anyway, because it is cheap and it closes a channel that content filters do not see. If a human is approving an action, show them the bytes you will execute, after that stripping. An approval dialog that renders a different string than the one you run is not an approval.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;the-boundary-that-holds&#34;&gt;The boundary that holds&lt;/h2&gt;
&lt;p&gt;Assume the instruction boundary fails. Design so the failure has a small blast radius. The controls below are the ones that stay standing when a classifier is wrong. They match LLM01:2026&amp;rsquo;s own ordering: constrain the role in the prompt if you want, and do not confuse that with enforcement.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tools are an allowlist in your process, not a paragraph in the prompt.&lt;/strong&gt; The model emits a name and a JSON object. Your code decides whether that name exists for this task, whether the arguments match the schema, and whether this caller may do this to this tenant. &lt;a href=&#34;https://blog.veydh.com/2026/2026-07-graphrag-financial-documents-mcp/&#34;&gt;GraphRAG for Financial Filings&lt;/a&gt; already draws the important line: the analyst-facing server is read-only, and the write path is a different process with validators in front of it. A prompt cannot become a write if the process has no write function.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Credentials never sit in the context window.&lt;/strong&gt; The model asks for &amp;ldquo;send&amp;rdquo; or &amp;ldquo;query.&amp;rdquo; The application holds the token, scoped to the operation, short-lived, and useless for the operation next door. A tool that can both read mail and send mail is two tools. Ship the read. Leave the send behind a person.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Arguments are checked against something the model did not just invent.&lt;/strong&gt; A file path has to live under a root you chose. A URL has to match a host allowlist. A SQL string the model composed is the wrong interface; a parameterized call with bound fields is the right one. Schema-valid JSON can still be a malicious email body or a hostile query. Validate structure, then apply the destination&amp;rsquo;s own rules. That destination check is LLM10 in the 2026 list, improper output handling, and it is where HTML escaping, parameterized queries, and &amp;ldquo;do not fetch this URL from the server&amp;rdquo; live.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;People approve the irreversible and the outward.&lt;/strong&gt; Show the action, the target, and the data that will leave. Summaries are how an injected instruction hides inside the thing the user thinks they approved. Approval fatigue is real, which is an argument for fewer privileged tools, not for skipping the prompt on the ones that remain.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Untrusted content stays labeled, in a separate channel, all the way through.&lt;/strong&gt; Delimiters and data marking (spotlighting, in the Microsoft Research writeup) reduce how often the model confuses a passage with an order, in tests where the attacker does not know the marking. An attacker who can see the scheme can imitate it. Nasr and colleagues, cited in the 2026 OWASP entry, report adaptive attacks getting through most of a dozen recent defenses that looked solved on a static set. Mark the data so the model has a chance. Enforce the policy so you do not need the model to get it right.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Capability budget.&lt;/strong&gt; If the agent reads untrusted content, holds private data, and can change state or talk to the network, require a person on each of those actions. Drop one of the three and the trifecta is broken. An agent that only answers from a public FAQ, an agent that drafts into a box a person sends, an agent that reads private data and cannot egress: each of those is a different product, and only the combination is the dangerous one.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Supply chain of the tools themselves.&lt;/strong&gt; Pin the MCP server and the tool package. Read the tool descriptions you are about to inject into the prompt. A description is an instruction the model will see on every turn. &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/&#34;&gt;Serving Small Models Behind an HTTP API&lt;/a&gt; already wants request ids and a version header. Add the tool package version and the content hash of what you retrieved to that log. When a session goes wrong you need to know which bytes were in the window.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;a-gate-that-does-not-ask-the-model&#34;&gt;A gate that does not ask the model&lt;/h2&gt;
&lt;p&gt;This is the piece I want in the request path. It is boring on purpose. The model proposes. The gate disposes.&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; dataclasses &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; dataclass
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;ALLOWED &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; {
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;get_metrics&amp;#34;&lt;/span&gt;: {&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;read&amp;#34;&lt;/span&gt;},
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;get_chunk&amp;#34;&lt;/span&gt;: {&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;read&amp;#34;&lt;/span&gt;},
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;screen_companies&amp;#34;&lt;/span&gt;: {&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;read&amp;#34;&lt;/span&gt;},
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;PRIVILEGED &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; {&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;send_mail&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;write_file&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;shell&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;http_fetch&amp;#34;&lt;/span&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#a6e22e&#34;&gt;@dataclass&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Decision&lt;/span&gt;:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    allow: bool
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    reason: str
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;authorize&lt;/span&gt;(tool: str, args: dict, task_tools: set[str]) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; Decision:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; tool &lt;span style=&#34;color:#f92672&#34;&gt;in&lt;/span&gt; PRIVILEGED:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; Decision(&lt;span style=&#34;color:#66d9ef&#34;&gt;False&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;privileged tools are not on this agent&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; tool &lt;span style=&#34;color:#f92672&#34;&gt;not&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;in&lt;/span&gt; task_tools &lt;span style=&#34;color:#f92672&#34;&gt;or&lt;/span&gt; tool &lt;span style=&#34;color:#f92672&#34;&gt;not&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;in&lt;/span&gt; ALLOWED:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; Decision(&lt;span style=&#34;color:#66d9ef&#34;&gt;False&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;tool is outside this task allowlist&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#75715e&#34;&gt;# Schema, tenant, and path checks happen here, in code.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#75715e&#34;&gt;# A second model does not get a vote on allow/deny.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;not&lt;/span&gt; args_in_schema(tool, args):
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; Decision(&lt;span style=&#34;color:#66d9ef&#34;&gt;False&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;arguments failed schema&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;not&lt;/span&gt; tenant_may(tool, args):
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; Decision(&lt;span style=&#34;color:#66d9ef&#34;&gt;False&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;caller tenant cannot touch this target&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; Decision(&lt;span style=&#34;color:#66d9ef&#34;&gt;True&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;ok&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;code&gt;task_tools&lt;/code&gt; changes per route. The pricing flow from the September post gets a catalog quote function. It does not get &lt;code&gt;http_fetch&lt;/code&gt; aimed at whatever URL was printed on the bottle. The retrieval flow gets &lt;code&gt;get_chunk&lt;/code&gt;. It does not get a tool that posts the chunk somewhere else.&lt;/p&gt;
&lt;p&gt;Log the denial with the request id. A spike in denials is either an attack or a prompt bug, and both are worth the page. Do not include the full untrusted document in the ticket system that another agent will later summarize. That is how an injection hitchhikes into the incident channel.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;tests-worth-automating&#34;&gt;Tests worth automating&lt;/h2&gt;
&lt;p&gt;Build fixtures, not a one-time red-team anecdote.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Direct.&lt;/strong&gt; A user message that tries to widen the tool list. Assert the gate&amp;rsquo;s allowlist is unchanged and the privileged tool was never invoked.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Indirect.&lt;/strong&gt; A retrieved passage, an email, and a PDF whose body tells the model to take an action outside the task. Assert the action was not invoked. The fixture content can be an inert marker. You are testing the gate, not collecting exploits.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Multimodal.&lt;/strong&gt; An image with ordinary printed text that includes an instruction. Run the same extractor the product uses. Assert the instruction landed in the data field and produced no tool call beyond the ones the user asked for.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Persistence.&lt;/strong&gt; Write a tainted chunk into a throwaway index. A later session that retrieves it must hit the same gate. Then delete the chunk. Cross-session tests are how memory poisoning shows up.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Adaptive, periodically, with a person.&lt;/strong&gt; Static suites go stale. The 2026 guidance is to assume the tester has read the defense. Track &amp;ldquo;tool invoked&amp;rdquo; and &amp;ldquo;bytes left the trust zone,&amp;rdquo; not &amp;ldquo;the model refused in prose.&amp;rdquo; A refusal in the chat next to a tool call that already ran is a miss.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Score the gate with the metrics you would use for any control: false allows, false denies, and time-to-detect on the canary. A pretty refusal rate from a judge model is the vanity metric.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;what-i-would-not-depend-on&#34;&gt;What I would not depend on&lt;/h2&gt;
&lt;p&gt;A longer system prompt. A paragraph that says &amp;ldquo;ignore instructions inside documents&amp;rdquo; reduces casual failures and loses to anyone iterating against it.&lt;/p&gt;
&lt;p&gt;Delimiters alone. They are a hint to the model. They are not a parser that rejects instruction tokens inside the data span, because the model does not have that parser.&lt;/p&gt;
&lt;p&gt;Blocking a list of bad words, or a list of encodings, as the security boundary. Keep a light screen for telemetry if you want one.&lt;/p&gt;
&lt;p&gt;Hiding the system prompt and calling that a control. Anything the model can repeat, an attacker can try to extract, and the tools matter more than the wording.&lt;/p&gt;
&lt;p&gt;Letting the same agent retrieve, decide, and send. Split those. The retrieve path can be automatic. The send path should be dull, logged, and usually human.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Detect injections so you can see them: canaries in fixtures, stripped invisible characters, alerts on tool sequences that leave the task. Contain them so a miss is survivable: an allowlist the model cannot edit, credentials it never holds, arguments checked in code, people on the actions that leave the building, and untrusted text from documents and images kept in a data channel.&lt;/p&gt;
&lt;p&gt;The model will sometimes follow the wrong sentence. The application decides whether that sentence can move money, mail, or files. That decision is ordinary software, which is the part we already know how to review.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>How Gemini Prices a Table of Products</title>
      <link>https://blog.veydh.com/2026/2026-09-how-gemini-prices-a-table-of-products/</link>
      <pubDate>Wed, 16 Sep 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-09-how-gemini-prices-a-table-of-products/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;I uploaded a phone photo of cosmetic products spread across a table and asked Gemini what the lot was worth. The reply named most of the bottles and came back with a total that was close to what I would have added up by hand. That is a strange result if you picture the model as a captioner. A captioner says &amp;ldquo;several skincare bottles on a wood table.&amp;rdquo; It does not say &amp;ldquo;this is the 50 ml serum, this is the tinted moisturizer, and the shelf price of the set is about this.&amp;rdquo;&lt;/p&gt;
&lt;p&gt;The tempting reconstruction is a classical vision pipeline: draw a box around each product, OCR the label, look every name up in parallel, add the prices. Parts of that reconstruction are real. Parts of it are a diagram we invent because the chat UI never shows its work. This post separates the two, using Google&amp;rsquo;s own descriptions of Gemini image understanding and of AI Mode, plus the failure modes that make a &amp;ldquo;close&amp;rdquo; total still the wrong thing to wire into a checkout.&lt;/p&gt;
&lt;p&gt;The follow-up, &lt;a href=&#34;https://blog.veydh.com/2026/2026-10-prompt-injection-detection-and-containment/&#34;&gt;Prompt Injection: Detect What You Can, Contain What You Cannot&lt;/a&gt;, matters here for a dull reason. Text on a bottle, a sticker, or a screenshot is data. A model that can read it can also follow it.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;two-products-two-pipelines&#34;&gt;Two products, two pipelines&lt;/h2&gt;
&lt;p&gt;&amp;ldquo;Gemini&amp;rdquo; is doing different jobs depending on which surface you typed into.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Gemini API, given only an image and a question,&lt;/strong&gt; runs a multimodal model. The image becomes visual tokens. The tokens sit in the same context as your text. One generation can name objects, read printed text, and talk about how the objects are arranged. Google&amp;rsquo;s image-understanding guide is explicit that this covers captioning, classification, visual question answering, object detection, and segmentation without a separate detector you trained yourself. Detection is extra training on top of that general ability, and it shows up when you ask for coordinates.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The consumer surfaces Google has actually described for &amp;ldquo;what is everything in this photo, and what does it cost&amp;rdquo;&lt;/strong&gt; add tools. In the March 2026 &amp;ldquo;Ask a Techspert&amp;rdquo; note on visual search, Google&amp;rsquo;s account is: Gemini looks at the image and the question and decides which tools to call. Lens is the visual library. A fan-out then fires multiple searches at once, for the scene and for the individual objects, and the model writes one answer over those results. The same pattern is in the AI Mode multimodal post: Gemini understands the scene, Lens identifies each object, fan-out issues the queries. Shopping queries can land on the Shopping Graph, which Google describes as more than 50 billion listings, with more than 2 billion of them refreshed every hour. Those are Google&amp;rsquo;s published figures.&lt;/p&gt;
&lt;p&gt;So the accurate answer to &amp;ldquo;did it box every product, read the names, and look them up concurrently?&amp;rdquo; is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Names.&lt;/strong&gt; Yes, that is the part the model is built to do, from packaging appearance and from the words printed on the packaging.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Boxes.&lt;/strong&gt; The model can emit them. Lens localizes objects in the search product. A chat reply that never drew a rectangle still may have localized internally. You do not get to treat an undrawn box as a step you observed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Concurrent lookups.&lt;/strong&gt; That is the published shape of AI Mode and of the multi-object Lens path: many queries in one turn, then a synthesis. A Gemini transcript with shopping cards or source links is evidence the tool path ran. A bare paragraph with no sources is compatible with the model remembering typical prices and never leaving the weights.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The Vertex AI image console, as documented, still says grounding is not supported for multimodal prompts on that screen. An API call that only attaches a JPEG does not, by itself, hit the Shopping Graph. If you are rebuilding this, you turn search on deliberately, or you look prices up in your own code.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;what-the-model-actually-receives&#34;&gt;What the model actually receives&lt;/h2&gt;
&lt;p&gt;The image is not fed to the transformer as pixels one-for-one. It is reduced to a budget of visual tokens. Two accountings are in the current docs, and they belong to different controls:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The API guide&amp;rsquo;s tile estimate: an image whose sides are both at most 384 pixels costs 258 tokens. Larger images are cut into tiles. The worked example is a 960×540 image becoming 6 tiles at 258 tokens each.&lt;/li&gt;
&lt;li&gt;Gemini 3&amp;rsquo;s &lt;code&gt;media_resolution&lt;/code&gt; cap, per image: low 280, medium 560, high 1120, ultra-high 2240. The documented default for an unspecified Gemini 3 image is 1120 tokens. The same page lists Gemini 3.1 Pro preview and Gemini 3 Flash preview as the image models, with a default of 1120.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Label text is the first casualty of a tight budget. A wide shot of a table makes each bottle a small fraction of the frame. At low resolution the silhouette and the brand color can still be recognizable, and the shade name or the &amp;ldquo;50 ml&amp;rdquo; can be mush. Turning resolution up is how you buy back small text. You pay for it in tokens, latency, and money, which is the same budget fight as &lt;a href=&#34;https://blog.veydh.com/2026/2026-03-token-limits-budgets-and-truncation/&#34;&gt;Token Budgets: Enforcing Limits at the API Layer&lt;/a&gt;. Rotate the photo so the labels are upright before you spend that budget. The guide calls rotation out because the model will not reliably fix it for you.&lt;/p&gt;
&lt;p&gt;Identification then has three sources, and a close total usually mixes them:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Text on the object.&lt;/strong&gt; Brand, line, size, shade. This is the model reading, in the same forward pass as the rest of the scene. It is the same family of skill as OCR, and it fails when the type is small, reflective, or partly occluded.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Appearance.&lt;/strong&gt; Shape, cap color, layout of the label. Useful when the text is unreadable, and also how a dupe or a counterfeit gets the real product&amp;rsquo;s name.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Memory of prices.&lt;/strong&gt; Popular SKUs have prices in the training mixture. Those prices have a region, a year, and a size. They are not a quote.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;A fourth source appears only when a tool runs: a search snippet, a Lens near-duplicate, or a Shopping Graph row with a current price. That source is the one that can make an obscure SKU come out right. Memory cannot do that for a product the model barely saw.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;boxes-when-you-actually-ask-for-them&#34;&gt;Boxes, when you actually ask for them&lt;/h2&gt;
&lt;p&gt;Object detection in the Gemini API is a prompted, structured output. You ask for items. The model returns JSON. Each box is &lt;code&gt;[ymin, xmin, ymax, xmax]&lt;/code&gt;, origin at the top left, each value an integer from 0 to 1000. You scale by the real image width and height. The same response can carry a label and, if you asked, a segmentation polygon in the same 0–1000 space. AI Studio will draw the boxes. On Vertex you draw them yourself.&lt;/p&gt;
&lt;p&gt;That is a detector you did not train. It is also a generative detector. It can miss a bottle at the edge, merge two overlapping compacts, or invent a box around a shadow. Custom instructions work (&amp;ldquo;only the bottles, not the tissue box&amp;rdquo;), which is the useful part, and they work without a fine-tune, which is also how a sloppy prompt localizes the wrong thing with confidence.&lt;/p&gt;
&lt;p&gt;A minimal request, pinned to whatever Gemini 3 model id you actually evaluated:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; pydantic &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; BaseModel, Field
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; typing &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; List
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Item&lt;/span&gt;(BaseModel):
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    box_2d: List[int] &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; Field(description&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;[ymin, xmin, ymax, xmax] in 0..1000&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    label: str
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    printed_text: str &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; Field(description&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Words read off the package. Empty if illegible.&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    size: str &lt;span style=&#34;color:#f92672&#34;&gt;|&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;TableScan&lt;/span&gt;(BaseModel):
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    items: List[Item]
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;prompt &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; (
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;List each distinct cosmetic product on the table. &amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;box_2d is [ymin, xmin, ymax, xmax] normalized to 0-1000. &amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;printed_text must be words you can read, not a guess from the shape. &amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;If two items are the same SKU, return both.&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Send &lt;code&gt;prompt&lt;/code&gt; plus the image, and require JSON matching &lt;code&gt;TableScan&lt;/code&gt;. Keep the raw image size next to the response so you can descale:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;to_pixels&lt;/span&gt;(box: list[int], width: int, height: int) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; tuple[int, int, int, int]:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    ymin, xmin, ymax, xmax &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; box
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; (
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        round(xmin &lt;span style=&#34;color:#f92672&#34;&gt;/&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;1000&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt; width),
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        round(ymin &lt;span style=&#34;color:#f92672&#34;&gt;/&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;1000&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt; height),
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        round(xmax &lt;span style=&#34;color:#f92672&#34;&gt;/&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;1000&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt; width),
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        round(ymax &lt;span style=&#34;color:#f92672&#34;&gt;/&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;1000&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt; height),
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    )
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;I would log every box and the &lt;code&gt;printed_text&lt;/code&gt; beside the final prices. When the total is wrong, the usual bug is a name that never appeared on the package.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;the-lookup-and-who-is-allowed-to-add&#34;&gt;The lookup, and who is allowed to add&lt;/h2&gt;
&lt;p&gt;Google&amp;rsquo;s fan-out is concurrent search: the model proposes several queries, the search systems run them together, the model reads the pile and writes the answer. Inside AI Mode that is one product. Inside an application you should split it, for the same reason the financial graph post refuses to let the model do the arithmetic. See &lt;a href=&#34;https://blog.veydh.com/2026/2026-07-graphrag-financial-documents-mcp/&#34;&gt;GraphRAG for Financial Filings&lt;/a&gt;: growth rates belong in the query, and the model interprets the rows.&lt;/p&gt;
&lt;p&gt;The split that matches the cosmetic photo:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Perceive.&lt;/strong&gt; One multimodal call returns items, boxes, and the text actually printed. No prices in this call. A model that is allowed to &amp;ldquo;helpfully&amp;rdquo; fill in a price will do it from memory and you will not know.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resolve.&lt;/strong&gt; Map &lt;code&gt;(brand, line, size)&lt;/code&gt; to a catalog id. This is entity resolution again. &amp;ldquo;The ordinary niacinamide&amp;rdquo; and &amp;ldquo;The Ordinary Niacinamide 10% + Zinc 1%, 30 ml&amp;rdquo; must collapse, and the 30 ml must not collapse into the 60 ml.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Price in your system.&lt;/strong&gt; Concurrent lookups against a catalog or a shopping API you are allowed to call. One query per resolved id. Record the currency, the retailer, and whether the number is a shelf price or a sale.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Add in code.&lt;/strong&gt; &lt;code&gt;sum(unit_price * count)&lt;/code&gt;. The model can explain the table. It does not get to be the source of the total.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cite.&lt;/strong&gt; Each line carries the catalog row id. A line with no row is &amp;ldquo;unpriced,&amp;rdquo; and it stays out of the total.&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; asyncio
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;async&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;price_table&lt;/span&gt;(items: list[dict]) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; dict:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    resolved &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; [catalog&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;resolve(it) &lt;span style=&#34;color:#66d9ef&#34;&gt;for&lt;/span&gt; it &lt;span style=&#34;color:#f92672&#34;&gt;in&lt;/span&gt; items]
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    quotes &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;await&lt;/span&gt; asyncio&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;gather(&lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt;(catalog&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;quote(r) &lt;span style=&#34;color:#66d9ef&#34;&gt;for&lt;/span&gt; r &lt;span style=&#34;color:#f92672&#34;&gt;in&lt;/span&gt; resolved))
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    lines &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; []
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    total &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;0&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    currency &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;for&lt;/span&gt; item, sku, quote &lt;span style=&#34;color:#f92672&#34;&gt;in&lt;/span&gt; zip(items, resolved, quotes):
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; quote &lt;span style=&#34;color:#f92672&#34;&gt;is&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            lines&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;append({&lt;span style=&#34;color:#f92672&#34;&gt;**&lt;/span&gt;item, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;sku&amp;#34;&lt;/span&gt;: &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;price&amp;#34;&lt;/span&gt;: &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;})
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            &lt;span style=&#34;color:#66d9ef&#34;&gt;continue&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        count &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; int(item&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;get(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;count&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#ae81ff&#34;&gt;1&lt;/span&gt;))
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        total &lt;span style=&#34;color:#f92672&#34;&gt;+=&lt;/span&gt; quote&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;price &lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt; count
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        currency &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; currency &lt;span style=&#34;color:#f92672&#34;&gt;or&lt;/span&gt; quote&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;currency
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        lines&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;append({
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            &lt;span style=&#34;color:#f92672&#34;&gt;**&lt;/span&gt;item,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;sku&amp;#34;&lt;/span&gt;: sku&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;id,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;price&amp;#34;&lt;/span&gt;: quote&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;price,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;count&amp;#34;&lt;/span&gt;: count,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;currency&amp;#34;&lt;/span&gt;: quote&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;currency,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        })
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; {&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;lines&amp;#34;&lt;/span&gt;: lines, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;total&amp;#34;&lt;/span&gt;: total, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;currency&amp;#34;&lt;/span&gt;: currency}
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Concurrency here is ordinary fan-out of I/O. It is the right shape, and it is auditable. The model&amp;rsquo;s private fan-out, if the product did one, is the same shape with none of the logs unless the UI showed sources.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;why-a-close-total-can-still-be-the-wrong-total&#34;&gt;Why a close total can still be the wrong total&lt;/h2&gt;
&lt;p&gt;Cosmetics are a nasty catalog. The photo under-specifies the SKU in ways a fluent answer hides.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Size.&lt;/strong&gt; The 30 ml and the 50 ml share a label design. The price ratio is not the volume ratio.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Shade.&lt;/strong&gt; Two foundations in the same carton differ by a number the model smoothed over.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Channel.&lt;/strong&gt; Boutique list price, drugstore, grey-market seller, travel size. &amp;ldquo;Close&amp;rdquo; often means the right order of magnitude for the hero SKU in the US.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Doubles.&lt;/strong&gt; Two of the same bottle, one counted. Or one bottle counted twice because the box and the bottle were both localized.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Lookalikes.&lt;/strong&gt; A dupe photographed next to the real bottle inherits the real price if appearance outruns the printed text.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Region and date.&lt;/strong&gt; A remembered 2024 USD price is not today&amp;rsquo;s price in another currency. Shopping Graph freshness is why the tool path exists. Memory does not refresh 2 billion listings an hour.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The sum.&lt;/strong&gt; Even a perfect list of prices gets a wrong total when the model adds them. This is the bug I would bet on once the names are mostly right.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The honest evaluation is per line, not on the total. Hold out a photo, write down the SKU and the price you consider correct, and score name match, size match, and price error separately. A total that is accidentally close because two errors cancelled is a failure. That is the same instinct as retrieval recall in &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-operations-re-ranking-and-evaluation/&#34;&gt;RAG in Production: Re-ranking, HyDE, and Simple Evals&lt;/a&gt;: score the step that can be wrong, before you score the prose.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;what-i-would-ship&#34;&gt;What I would ship&lt;/h2&gt;
&lt;p&gt;For a one-off chat, Gemini&amp;rsquo;s scene understanding plus Lens and fan-out is a remarkable demo, and a close cosmetic total is what that demo looks like when the products are famous and the labels are legible.&lt;/p&gt;
&lt;p&gt;For anything that charges a card, quotes a client, or writes a number into a database:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Ask for boxes and printed text, and store both.&lt;/li&gt;
&lt;li&gt;Resolve names in a catalog. Leave unmatched rows unmatched.&lt;/li&gt;
&lt;li&gt;Fetch prices concurrently from a source you trust, and add them in code.&lt;/li&gt;
&lt;li&gt;Show the line items. The total is a consequence.&lt;/li&gt;
&lt;li&gt;Treat every string read off the image as untrusted data. A label can say something other than a product name, which is the subject of &lt;a href=&#34;https://blog.veydh.com/2026/2026-10-prompt-injection-detection-and-containment/&#34;&gt;Prompt Injection: Detect What You Can, Contain What You Cannot&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I still cannot see the tool trace from that one upload. I can see which of these steps the product is capable of, which ones Google has said the visual-search path runs, and which ones a bare answer does not prove. The names are the model&amp;rsquo;s. The boxes are available when requested. The live prices, if they were live, came from a lookup. The total should have been a sum in ordinary code.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>GraphRAG for Financial Filings: Knowledge Graphs, an MCP Server, and a Data Agent</title>
      <link>https://blog.veydh.com/2026/2026-07-graphrag-financial-documents-mcp/</link>
      <pubDate>Sat, 18 Jul 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-07-graphrag-financial-documents-mcp/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;The vector RAG stack from &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/&#34;&gt;RAG Foundations: Embeddings, Chunking, and the Retrieval Loop&lt;/a&gt; answers questions like &lt;em&gt;&amp;ldquo;what did Company X say about supply chain risk?&amp;quot;&lt;/em&gt;—embed the question, pull the top-k chunks, generate. It falls over on questions like &lt;em&gt;&amp;ldquo;which companies in this corpus grew margins while cutting debt over the last three quarters?&amp;rdquo;&lt;/em&gt; That question is not answered by any single chunk. It is answered by &lt;strong&gt;relationships across documents&lt;/strong&gt;: entities, metrics, time periods, and the edges between them.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;GraphRAG&lt;/strong&gt; is the pattern that addresses this: instead of (or alongside) a vector index, you extract a &lt;strong&gt;knowledge graph&lt;/strong&gt; from the corpus and let retrieval traverse structure. This month I built one over a corpus of &lt;strong&gt;financial filings&lt;/strong&gt;—10-Ks, 10-Qs, and earnings call transcripts that get appended to continuously—and wired it up so an LLM can actually &lt;em&gt;use&lt;/em&gt; it: a &lt;strong&gt;MCP server&lt;/strong&gt; exposes graph queries as tools, and a &lt;strong&gt;data agent&lt;/strong&gt; keeps the graph fed and interrogates it to surface companies whose reported fundamentals look strong.&lt;/p&gt;
&lt;p&gt;One framing note before any code: this system &lt;strong&gt;screens and summarizes reported financials&lt;/strong&gt;. It is a retrieval-and-reasoning demo, not investment advice, and the honest output of such a system is &lt;em&gt;&amp;ldquo;here are the companies whose filings show X, with citations&amp;rdquo;&lt;/em&gt;—never &lt;em&gt;&amp;ldquo;buy this.&amp;rdquo;&lt;/em&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;vector-rag-vs-graphrag-what-actually-changes&#34;&gt;Vector RAG vs GraphRAG: what actually changes&lt;/h2&gt;
&lt;p&gt;Both start the same way—ingest, chunk, index. The difference is &lt;em&gt;what&lt;/em&gt; you index and &lt;em&gt;how&lt;/em&gt; you retrieve.&lt;/p&gt;
&lt;table&gt;
  &lt;thead&gt;
      &lt;tr&gt;
          &lt;th&gt;Dimension&lt;/th&gt;
          &lt;th&gt;Vector RAG&lt;/th&gt;
          &lt;th&gt;GraphRAG&lt;/th&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr&gt;
          &lt;td&gt;Index unit&lt;/td&gt;
          &lt;td&gt;Chunk embedding&lt;/td&gt;
          &lt;td&gt;Entities + typed relationships (+ usually chunk embeddings too)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Retrieval&lt;/td&gt;
          &lt;td&gt;Nearest-neighbor similarity&lt;/td&gt;
          &lt;td&gt;Graph traversal, entity-anchored expansion, community summaries&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Sweet spot&lt;/td&gt;
          &lt;td&gt;&amp;ldquo;What did X say about Y?&amp;rdquo; (local, single-document)&lt;/td&gt;
          &lt;td&gt;&amp;ldquo;How do X, Y, Z relate?&amp;rdquo; (multi-hop, cross-document, corpus-global)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Indexing cost&lt;/td&gt;
          &lt;td&gt;One embedding pass, cheap&lt;/td&gt;
          &lt;td&gt;An &lt;strong&gt;LLM call per chunk&lt;/strong&gt; for extraction—orders of magnitude more compute&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Update story&lt;/td&gt;
          &lt;td&gt;Append new vectors, done&lt;/td&gt;
          &lt;td&gt;Upsert nodes/edges, re-resolve entities, refresh community summaries&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Failure mode&lt;/td&gt;
          &lt;td&gt;Retrieves plausible-but-irrelevant chunks&lt;/td&gt;
          &lt;td&gt;Extraction errors become &lt;strong&gt;persistent wrong facts&lt;/strong&gt; in the graph&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Explainability&lt;/td&gt;
          &lt;td&gt;&amp;ldquo;These chunks were similar&amp;rdquo;&lt;/td&gt;
          &lt;td&gt;&amp;ldquo;Here is the path of facts, each with a source span&amp;rdquo;&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;h3 id=&#34;the-pros-honestly-stated&#34;&gt;The pros, honestly stated&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Multi-hop questions work.&lt;/strong&gt; &amp;ldquo;Supplier of a supplier,&amp;rdquo; &amp;ldquo;companies exposed to the same customer,&amp;rdquo; &amp;ldquo;subsidiaries of firms that raised guidance&amp;rdquo;—these are one or two edge traversals, not a prayer that some chunk mentions everything at once.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Global questions work.&lt;/strong&gt; The Microsoft GraphRAG paper’s key contribution was &lt;strong&gt;community detection + summarization&lt;/strong&gt;: cluster the graph with hierarchical &lt;strong&gt;Leiden&lt;/strong&gt; (Louvain is the older method some libraries still expose), have an LLM write a summary per community, and answer corpus-wide questions (&amp;ldquo;what are the dominant risk themes this quarter?&amp;rdquo;) by map-reducing over community summaries instead of over ten thousand chunks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Provenance is structural.&lt;/strong&gt; Every edge carries the chunk id and character span it was extracted from. An answer becomes a path through the graph, and every hop cites a filing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Structured facts stop being prose.&lt;/strong&gt; Revenue, margin, debt—extracted once into typed edges—can be &lt;em&gt;compared and sorted&lt;/em&gt;, which embeddings fundamentally cannot do. Cosine similarity does not know that 12% &amp;gt; 8%.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&#34;the-cons-equally-honestly&#34;&gt;The cons, equally honestly&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Indexing is expensive.&lt;/strong&gt; Every chunk goes through an LLM for entity/relation extraction. For a corpus that grows weekly, this is a real, recurring compute bill—which is exactly why self-hosting the extractor on &lt;strong&gt;vLLM&lt;/strong&gt; (below) matters.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Extraction quality is the ceiling.&lt;/strong&gt; A hallucinated edge is worse than a bad retrieval, because it &lt;em&gt;persists&lt;/em&gt; and gets cited confidently later. You need validation gates, not vibes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Entity resolution is genuinely hard.&lt;/strong&gt; &amp;ldquo;Alphabet,&amp;rdquo; &amp;ldquo;Google,&amp;rdquo; &amp;ldquo;GOOGL,&amp;rdquo; and &amp;ldquo;Alphabet Inc. Class A&amp;rdquo; must collapse to one node or the graph silently fragments.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;More moving parts.&lt;/strong&gt; A graph store, an extraction pipeline, a community-summary refresher, and a resolver—each a thing that can drift, each needing the same versioning discipline as the vector index in the foundations post.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Latency.&lt;/strong&gt; Multi-hop traversal plus summary assembly is slower than one ANN lookup. Fine for analysis workloads; think twice for chat-latency products.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The pragmatic verdict: &lt;strong&gt;keep the vector index&lt;/strong&gt;. GraphRAG is a second retrieval mode layered on top, not a replacement. Local &amp;ldquo;what did they say&amp;rdquo; questions still route to vectors; relational and global questions route to the graph.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;architecture-three-components-one-contract&#34;&gt;Architecture: three components, one contract&lt;/h2&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     ┌──────────────────────────────┐
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;   new filings ────► │  DATA AGENT (ingestion loop)  │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;   (10-K, 10-Q,      │  fetch → chunk → extract →    │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    transcripts)     │  resolve → upsert → summarize │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     └──────────────┬───────────────┘
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                                    │ writes
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                                    ▼
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     ┌──────────────────────────────┐
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     │  GRAPHRAG STORE               │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     │  graph DB (nodes/edges w/     │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     │  period + provenance) +       │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     │  vector index for chunks      │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     └──────────────┬───────────────┘
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                                    │ read-only tools
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                                    ▼
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     ┌──────────────────────────────┐
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     │  MCP SERVER                   │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     │  find_company, get_metrics,   │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     │  neighbors, screen_companies, │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     │  community_themes, get_chunk  │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     └──────────────┬───────────────┘
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                                    │ tool calls
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                                    ▼
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     ┌──────────────────────────────┐
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     │  ANALYST LLM (any MCP client) │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     │  plans → calls tools → cites  │
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     └──────────────────────────────┘
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The separation earns its keep in two ways. First, the &lt;strong&gt;MCP server is read-only&lt;/strong&gt;—the analyst LLM can never write a fact into the graph, so a bad generation cannot poison the store. Only the ingestion side of the data agent writes, and everything it writes passes validation. Second, MCP means the graph is a &lt;strong&gt;capability, not an integration&lt;/strong&gt;: Claude Desktop, Cursor, a custom agent loop—any MCP client gets the same tools with the same schemas, and I never write bespoke glue per client.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;ingestion-chunking-financial-documents-without-destroying-them&#34;&gt;Ingestion: chunking financial documents without destroying them&lt;/h2&gt;
&lt;p&gt;Financial filings punish naive chunking harder than any corpus I have worked with. Three structural facts drive the strategy:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Filings have a canonical section structure.&lt;/strong&gt; A 10-K&amp;rsquo;s &lt;code&gt;Item 1A&lt;/code&gt; (Risk Factors) and &lt;code&gt;Item 7&lt;/code&gt; (MD&amp;amp;A) are semantically different universes. Chunks must &lt;strong&gt;never span section boundaries&lt;/strong&gt;, and every chunk carries its item number as metadata—&amp;ldquo;risk&amp;rdquo; language inside Risk Factors is boilerplate; the same language inside MD&amp;amp;A is a signal.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The numbers live in tables, and tables are not prose.&lt;/strong&gt; Splitting a consolidated income statement mid-table produces chunks where revenue has lost its fiscal-year column header. Worse, filings state scale &lt;em&gt;once&lt;/em&gt;, at the top: &lt;em&gt;&amp;quot;(in thousands, except per share data)&amp;rdquo;&lt;/em&gt;. A chunk that contains &lt;code&gt;4,127&lt;/code&gt; without that header is a &lt;strong&gt;1000× error&lt;/strong&gt; waiting to be extracted. The fix: parse tables as units, re-attach the scale header to every table chunk, and prefer &lt;strong&gt;XBRL&lt;/strong&gt; (the machine-readable facts embedded in EDGAR filings) for core financial metrics—those go &lt;strong&gt;straight into the graph as structured edges, no LLM in the loop&lt;/strong&gt;. The LLM extraction budget is spent on narrative text, where it is actually needed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Earnings calls are dialogues.&lt;/strong&gt; Chunk transcripts by &lt;strong&gt;speaker turn&lt;/strong&gt;, keeping Q&amp;amp;A pairs together—an analyst&amp;rsquo;s question is the antecedent for the CFO&amp;rsquo;s &amp;ldquo;as I said, we expect that to normalize.&amp;rdquo; Splitting them orphans the answer, the same &amp;ldquo;lost antecedent&amp;rdquo; failure the foundations post flagged, but worse because the &lt;em&gt;speaker&lt;/em&gt; (CEO guidance vs. an analyst&amp;rsquo;s skeptical premise) changes what a sentence means.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2 id=&#34;extraction-at-scale-with-vllm&#34;&gt;Extraction at scale with vLLM&lt;/h2&gt;
&lt;p&gt;Extraction is the recurring cost center: every narrative chunk, every week, forever. Two properties make &lt;strong&gt;vLLM&lt;/strong&gt; (see &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/&#34;&gt;Serving Small Models Behind an HTTP API&lt;/a&gt; for the serving fundamentals) the right tool here rather than a metered API:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Continuous batching.&lt;/strong&gt; Extraction is embarrassingly parallel—thousands of independent chunks. vLLM keeps the GPU saturated across concurrent requests, which is precisely the workload shape its scheduler was built for.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Guided decoding.&lt;/strong&gt; Current vLLM constrains generation with &lt;code&gt;structured_outputs&lt;/code&gt;, or with OpenAI-style &lt;code&gt;response_format&lt;/code&gt;. The old &lt;code&gt;guided_json&lt;/code&gt; field was &lt;strong&gt;removed in vLLM 0.12.0&lt;/strong&gt; (late 2025). A current server still returns HTTP 200 if you send it, then &lt;strong&gt;ignores&lt;/strong&gt; it, so the output is not constrained. A schema only blocks relation names you did not intend when &lt;code&gt;relation&lt;/code&gt; is an enum in that schema. A plain string field does not. Truncation can still stop mid-object, so parse and validate the reply. Do not treat a 200 as proof the grammar ran.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-bash&#34; data-lang=&#34;bash&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# Pin the image tag and model revision in real manifests.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# Qwen2.5-14B-Instruct is a 2025 dense checkpoint used as a concrete extractor,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# not a claim that it is the best 2026 model. Re-benchmark before you swap it.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# On vLLM &amp;gt;= 0.12.0, guided_json is ignored; the Python below uses response_format.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;docker run --gpus all -p 8000:8000 &lt;span style=&#34;color:#ae81ff&#34;&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  vllm/vllm-openai:&amp;lt;pinned-tag&amp;gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  --model Qwen/Qwen2.5-14B-Instruct &lt;span style=&#34;color:#ae81ff&#34;&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  --max-model-len &lt;span style=&#34;color:#ae81ff&#34;&gt;16384&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  --dtype bfloat16
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The extraction schema is deliberately narrow—a closed relation vocabulary, mandatory evidence spans, mandatory period:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# extraction.py — illustrative; pin versions and model revision in production&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; typing &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; Literal
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; pydantic &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; BaseModel
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; openai &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; OpenAI
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Relation &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; Literal[
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;REPORTS_METRIC&amp;#34;&lt;/span&gt;,  &lt;span style=&#34;color:#75715e&#34;&gt;# company -&amp;gt; metric value, for a period&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;GUIDES&amp;#34;&lt;/span&gt;,          &lt;span style=&#34;color:#75715e&#34;&gt;# forward-looking guidance (kept separate on purpose)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;SUPPLIES&amp;#34;&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;COMPETES_WITH&amp;#34;&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;SUBSIDIARY_OF&amp;#34;&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;CUSTOMER_OF&amp;#34;&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;EXPOSED_TO_RISK&amp;#34;&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;]
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Triple&lt;/span&gt;(BaseModel):
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    subject: str
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    relation: Relation
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    object: str
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    value: float &lt;span style=&#34;color:#f92672&#34;&gt;|&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;      &lt;span style=&#34;color:#75715e&#34;&gt;# numeric metrics, normalized units&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    period: str &lt;span style=&#34;color:#f92672&#34;&gt;|&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;       &lt;span style=&#34;color:#75715e&#34;&gt;# e.g. &amp;#34;FY2025&amp;#34;, &amp;#34;Q1-2026&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    evidence: str            &lt;span style=&#34;color:#75715e&#34;&gt;# verbatim quote from the chunk&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Extraction&lt;/span&gt;(BaseModel):
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    triples: list[Triple]
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;client &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; OpenAI(base_url&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;http://localhost:8000/v1&amp;#34;&lt;/span&gt;, api_key&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;unused&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;extract&lt;/span&gt;(chunk_text: str, meta: dict) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; Extraction:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    schema &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; Extraction&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;model_json_schema()
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#75715e&#34;&gt;# Some grammar backends reject a schema that points at $defs via $ref.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#75715e&#34;&gt;# If the server returns 400, inline the relation enum on the field.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    resp &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; client&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;chat&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;completions&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;create(
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        model&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Qwen/Qwen2.5-14B-Instruct&amp;#34;&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        messages&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;[
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            {&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;role&amp;#34;&lt;/span&gt;: &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;system&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;content&amp;#34;&lt;/span&gt;: EXTRACTION_PROMPT},  &lt;span style=&#34;color:#75715e&#34;&gt;# relation defs + examples&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            {&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;role&amp;#34;&lt;/span&gt;: &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;user&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;content&amp;#34;&lt;/span&gt;: &lt;span style=&#34;color:#e6db74&#34;&gt;f&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;[&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;{&lt;/span&gt;meta[&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#39;ticker&amp;#39;&lt;/span&gt;]&lt;span style=&#34;color:#e6db74&#34;&gt;}&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt; &lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;{&lt;/span&gt;meta[&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#39;form&amp;#39;&lt;/span&gt;]&lt;span style=&#34;color:#e6db74&#34;&gt;}&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt; &lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;{&lt;/span&gt;meta[&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#39;section&amp;#39;&lt;/span&gt;]&lt;span style=&#34;color:#e6db74&#34;&gt;}&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;]&lt;/span&gt;&lt;span style=&#34;color:#ae81ff&#34;&gt;\n&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;{&lt;/span&gt;chunk_text&lt;span style=&#34;color:#e6db74&#34;&gt;}&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&lt;/span&gt;},
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        ],
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#75715e&#34;&gt;# Portable across servers that speak OpenAI json_schema.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#75715e&#34;&gt;# vLLM-native equivalent: extra_body={&amp;#34;structured_outputs&amp;#34;: {&amp;#34;json&amp;#34;: schema}}&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        response_format&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;{
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;type&amp;#34;&lt;/span&gt;: &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;json_schema&amp;#34;&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;json_schema&amp;#34;&lt;/span&gt;: {&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;name&amp;#34;&lt;/span&gt;: &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;extraction&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;schema&amp;#34;&lt;/span&gt;: schema},
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        },
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        temperature&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ae81ff&#34;&gt;0.0&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    )
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; Extraction&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;model_validate_json(resp&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;choices[&lt;span style=&#34;color:#ae81ff&#34;&gt;0&lt;/span&gt;]&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;message&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;content)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Schema-valid is not the same as &lt;em&gt;true&lt;/em&gt;, so every triple passes &lt;strong&gt;validation gates&lt;/strong&gt; before touching the graph:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Evidence must be verbatim.&lt;/strong&gt; If &lt;code&gt;evidence&lt;/code&gt; is not a substring of the source chunk, the triple is dropped. That catches an invented quote. It does &lt;strong&gt;not&lt;/strong&gt; catch a wrong relation attached to a real sentence. The negation, hypothetical, and numeric gates below are what catch that.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Numbers must appear in the source.&lt;/strong&gt; For &lt;code&gt;value&lt;/code&gt;, check that the digits exist in the chunk (allowing for scale-header multiplication). A &lt;code&gt;value&lt;/code&gt; the model &amp;ldquo;helpfully&amp;rdquo; computed is rejected—derived metrics are the &lt;em&gt;query layer&amp;rsquo;s&lt;/em&gt; job, where the arithmetic is auditable.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Negation and hypothetical filters.&lt;/strong&gt; Risk Factors are full of &amp;ldquo;if we were to lose our largest customer…&amp;quot;—an extractor happily emits &lt;code&gt;CUSTOMER_OF&lt;/code&gt; from a hypothetical. A cheap second-pass classifier on the evidence sentence (&amp;ldquo;is this asserted as fact, negated, or hypothetical?&amp;rdquo;) gates these; hypotheticals become &lt;code&gt;EXPOSED_TO_RISK&lt;/code&gt; edges instead, which is what they actually are.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Forward-looking stays quarantined.&lt;/strong&gt; Guidance (&amp;ldquo;we expect FY2027 revenue of…&amp;rdquo;) lands as &lt;code&gt;GUIDES&lt;/code&gt;, never &lt;code&gt;REPORTS_METRIC&lt;/code&gt;. Blending projections into reported facts is exactly the corruption a financial graph cannot survive.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id=&#34;the-edge-cases-that-define-the-system&#34;&gt;The edge cases that define the system&lt;/h2&gt;
&lt;p&gt;These consumed far more of the month than the happy path, and each one is a design decision, not a bug fix.&lt;/p&gt;
&lt;h3 id=&#34;entity-resolution-one-company-one-node&#34;&gt;Entity resolution: one company, one node&lt;/h3&gt;
&lt;p&gt;Filings refer to the same firm as &amp;ldquo;Alphabet Inc.,&amp;rdquo; &amp;ldquo;Alphabet,&amp;rdquo; &amp;ldquo;Google,&amp;rdquo; &amp;ldquo;the Company,&amp;rdquo; and &amp;ldquo;GOOGL&amp;rdquo;—sometimes all five in one document. Without resolution the graph fragments into disconnected aliases and every traversal silently misses facts. The workable recipe is layered: &lt;strong&gt;CIK/ticker lookup first&lt;/strong&gt; (filings carry the SEC&amp;rsquo;s canonical company identifier—use it as the node key, it is free ground truth), then an alias table for well-known names, then embedding similarity over entity names &lt;em&gt;with a human-review queue&lt;/em&gt; for low-confidence merges. Wrongly merging two companies is far worse than temporarily keeping duplicates—a merge contaminates both entities&amp;rsquo; facts, so the threshold stays conservative and merges are logged and reversible.&lt;/p&gt;
&lt;h3 id=&#34;time-facts-expire-edges-must-carry-periods&#34;&gt;Time: facts expire, edges must carry periods&lt;/h3&gt;
&lt;p&gt;&amp;ldquo;Revenue was $4.2B&amp;rdquo; is meaningless without &lt;em&gt;which quarter&lt;/em&gt;. Every metric edge carries &lt;code&gt;period&lt;/code&gt;, and queries default to &lt;strong&gt;latest available, per company&lt;/strong&gt;—not one global cutoff, because a lagging filer&amp;rsquo;s newest 10-Q is older than a prompt filer&amp;rsquo;s. Two sharper sub-cases:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Restatements.&lt;/strong&gt; A company reissues corrected financials; the old fact is now &lt;em&gt;wrong&lt;/em&gt; but must remain queryable (&amp;ldquo;what did they originally report?&amp;rdquo;). Edges get &lt;code&gt;superseded_by&lt;/code&gt; links rather than deletion—the graph is &lt;strong&gt;append-only with supersession&lt;/strong&gt;, which also makes index rebuilds reproducible.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fiscal-year misalignment.&lt;/strong&gt; Company A&amp;rsquo;s &amp;ldquo;Q1 2026&amp;rdquo; and Company B&amp;rsquo;s &amp;ldquo;Q1 2026&amp;rdquo; can be different calendar months. Edges store both the company&amp;rsquo;s fiscal label and a normalized calendar range; cross-company comparisons (&amp;ldquo;this quarter, sector-wide&amp;rdquo;) join on the calendar range.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&#34;incremental-updates-without-weekly-full-rebuilds&#34;&gt;Incremental updates without weekly full rebuilds&lt;/h3&gt;
&lt;p&gt;The corpus grows continuously, and re-extracting everything weekly is unaffordable. New filings upsert nodes and edges incrementally—cheap. The expensive part is that &lt;strong&gt;community summaries go stale&lt;/strong&gt;: a new 10-K can change what a cluster of companies is &amp;ldquo;about.&amp;rdquo; Full Leiden re-clustering on every filing is overkill, so summaries are marked &lt;strong&gt;dirty when any member entity gains edges&lt;/strong&gt; and refreshed on a schedule (nightly worked), with full re-clustering monthly or when the dirty fraction crosses a threshold. Between refreshes, global queries can hit slightly stale summaries—acceptable for analysis, but the MCP layer exposes an &lt;code&gt;as_of&lt;/code&gt; timestamp on every response so the consumer &lt;em&gt;knows&lt;/em&gt;, the same &amp;ldquo;as of&amp;rdquo; honesty the foundations post demanded of vector indexes.&lt;/p&gt;
&lt;h3 id=&#34;duplicate-facts-from-overlapping-chunks&#34;&gt;Duplicate facts from overlapping chunks&lt;/h3&gt;
&lt;p&gt;Chunk overlap—insurance in vector RAG—produces the &lt;em&gt;same triple twice&lt;/em&gt; in GraphRAG. Dedupe on &lt;code&gt;(subject, relation, object, period)&lt;/code&gt; and keep the union of evidence spans. A fact extracted from three chunks is not three facts; it is one fact with three citations, which is actually &lt;em&gt;stronger&lt;/em&gt; provenance.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;how-an-llm-actually-queries-a-rag-system&#34;&gt;How an LLM actually queries a RAG system&lt;/h2&gt;
&lt;p&gt;A point worth slowing down for, because it is the most commonly hand-waved part of every RAG diagram: &lt;strong&gt;in classic RAG, the LLM never queries anything.&lt;/strong&gt; The arrow from &amp;ldquo;model&amp;rdquo; to &amp;ldquo;vector database&amp;rdquo; that appears in a hundred architecture sketches does not exist. There are two genuinely different mechanics, and knowing which one you are running changes how you debug the system.&lt;/p&gt;
&lt;h3 id=&#34;mode-1-orchestrated-retrieval--the-model-is-a-passive-reader&#34;&gt;Mode 1: Orchestrated retrieval — the model is a passive reader&lt;/h3&gt;
&lt;p&gt;In the loop from &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/&#34;&gt;RAG Foundations&lt;/a&gt;, retrieval happens &lt;em&gt;before&lt;/em&gt; the LLM is ever invoked, performed by ordinary application code:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The &lt;strong&gt;orchestrator&lt;/strong&gt; (your Python service, LangChain chain, whatever) takes the user&amp;rsquo;s question.&lt;/li&gt;
&lt;li&gt;It embeds the question with the &lt;strong&gt;embedding model&lt;/strong&gt;—a separate, much smaller model than the generator. The LLM&amp;rsquo;s own weights are not involved.&lt;/li&gt;
&lt;li&gt;It runs nearest-neighbor search against the vector index, applies metadata filters, maybe re-ranks.&lt;/li&gt;
&lt;li&gt;It &lt;strong&gt;pastes the winning chunks into the prompt&lt;/strong&gt;, delimited and labeled, and only &lt;em&gt;then&lt;/em&gt; calls the LLM.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;What the generator actually receives looks like this—and this is the entire &amp;ldquo;query&amp;rdquo; from the model&amp;rsquo;s perspective:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;SYSTEM: Answer using only the provided context. Cite passage ids.
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        If the context does not support an answer, say so.
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;CONTEXT:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;[passage id=chunk-0412 source=&amp;#34;ACME 10-K FY2025, Item 7&amp;#34;]
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Revenue for fiscal 2025 increased 12% to $4.2 billion, driven by...
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;[passage id=chunk-0977 source=&amp;#34;ACME Q3-2026 earnings call, CFO&amp;#34;]
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;We expect gross margin to normalize toward 41% as inventory...
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;USER: How has ACME&amp;#39;s revenue been trending?
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The model reads context that showed up in its window and writes prose about it. It cannot ask a follow-up, cannot request &amp;ldquo;the next page,&amp;rdquo; cannot say &amp;ldquo;these chunks are irrelevant, search again.&amp;rdquo; If retrieval fetched the wrong passages, the model&amp;rsquo;s only honest move is to refuse—and its dishonest move, the one you will actually observe, is to improvise. &lt;strong&gt;Every retrieval decision was made by code before the model woke up.&lt;/strong&gt; This is why the foundations post insists chunking and embedding quality matter so much: in this mode they are the &lt;em&gt;whole&lt;/em&gt; retrieval intelligence.&lt;/p&gt;
&lt;p&gt;One refinement blurs the line without changing the mechanic: the orchestrator can use &lt;em&gt;an&lt;/em&gt; LLM call to improve the query before searching—&lt;strong&gt;query rewriting&lt;/strong&gt; (turn &amp;ldquo;what about their debt?&amp;rdquo; plus chat history into the standalone &amp;ldquo;what is ACME Corp&amp;rsquo;s debt position as of FY2025?&amp;rdquo;), &lt;strong&gt;decomposition&lt;/strong&gt; (split a compound question into sub-queries retrieved separately), or &lt;strong&gt;HyDE&lt;/strong&gt; (generate a hypothetical answer and embed &lt;em&gt;that&lt;/em&gt;, since a fake answer often lives closer to real passages than the question does—covered in &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-operations-re-ranking-and-evaluation/&#34;&gt;RAG in Production&lt;/a&gt;). But note who is in charge: the orchestrator decides to rewrite, decides to search, decides what k is. The LLM is a subroutine.&lt;/p&gt;
&lt;h3 id=&#34;mode-2-agentic-retrieval--the-model-drives-through-tool-calls&#34;&gt;Mode 2: Agentic retrieval — the model drives, through tool calls&lt;/h3&gt;
&lt;p&gt;The second mode inverts control, and it is how the analyst agent in this post works. The LLM is told—in its system prompt, via the standard tool-calling API—that tools exist, with names, descriptions, and typed JSON schemas. When the model wants information, it does not emit prose; it emits a &lt;strong&gt;structured tool call&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-json&#34; data-lang=&#34;json&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;{
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#f92672&#34;&gt;&amp;#34;name&amp;#34;&lt;/span&gt;: &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;get_metrics&amp;#34;&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  &lt;span style=&#34;color:#f92672&#34;&gt;&amp;#34;arguments&amp;#34;&lt;/span&gt;: {&lt;span style=&#34;color:#f92672&#34;&gt;&amp;#34;company_id&amp;#34;&lt;/span&gt;: &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;CIK-0001652044&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#f92672&#34;&gt;&amp;#34;metrics&amp;#34;&lt;/span&gt;: [&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;revenue&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;gross_margin&amp;#34;&lt;/span&gt;], &lt;span style=&#34;color:#f92672&#34;&gt;&amp;#34;periods&amp;#34;&lt;/span&gt;: &lt;span style=&#34;color:#ae81ff&#34;&gt;8&lt;/span&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;}
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The runtime executes the call (here, the MCP client forwards it to the MCP server, which runs the real graph query), appends the JSON result to the conversation as a &lt;strong&gt;tool message&lt;/strong&gt;, and hands the transcript back to the model, which now decides: answer, or call another tool. The loop repeats until the model produces a final response.&lt;/p&gt;
&lt;p&gt;This is the crucial mental shift: &lt;strong&gt;the model still never touches the database.&lt;/strong&gt; It emits &lt;em&gt;intentions&lt;/em&gt; in JSON; deterministic code executes them. What changed from Mode 1 is &lt;em&gt;who plans&lt;/em&gt;. The model can now chain queries (&amp;ldquo;resolve the ticker first, then fetch metrics, then check neighbors&amp;rdquo;), react to results (&amp;ldquo;the screen returned six companies—too many, tighten the threshold&amp;rdquo;), and recover from misses (&amp;quot;&lt;code&gt;find_company(&#39;Alphabet&#39;)&lt;/code&gt; before guessing an id&amp;rdquo;). Retrieval becomes a &lt;em&gt;dialogue&lt;/em&gt; instead of a single pre-baked lookup—which is exactly what multi-hop graph questions need, since the second hop depends on the first hop&amp;rsquo;s answer, something no one-shot retrieval can know in advance.&lt;/p&gt;
&lt;p&gt;The cost is the flip side: each hop is a full model round-trip (latency), the transcript grows with every tool result (tokens), and a model with freedom to plan has freedom to plan badly—hence small tool counts, sharp descriptions, and typed arguments. The docstrings in the MCP server below are not documentation for humans; they are &lt;strong&gt;the prompt&lt;/strong&gt; that teaches the model when to reach for each tool.&lt;/p&gt;
&lt;h3 id=&#34;where-mcp-fits-how-the-model-learns-the-tools-exist-at-all&#34;&gt;Where MCP fits: how the model learns the tools exist at all&lt;/h3&gt;
&lt;p&gt;A fair question hides inside Mode 2: how does the model &lt;em&gt;know&lt;/em&gt; about &lt;code&gt;get_metrics&lt;/code&gt;? It was not trained on my server. The answer is that it does not know anything until each session starts—and the machinery that tells it is exactly what MCP standardizes.&lt;/p&gt;
&lt;p&gt;The demystifying fact first: &lt;strong&gt;the LLM never speaks MCP.&lt;/strong&gt; MCP is a protocol between two pieces of ordinary software—the &lt;strong&gt;client&lt;/strong&gt; (the host application: Claude Desktop, Cursor, my agent loop) and the &lt;strong&gt;server&lt;/strong&gt; (the process wrapping my graph). The model only ever sees its native tool-calling format. The client is the translator in the middle, and a session unfolds in four steps:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Discovery.&lt;/strong&gt; On connect, the client calls the server&amp;rsquo;s &lt;code&gt;tools/list&lt;/code&gt; endpoint (JSON-RPC under the hood). The server replies with a manifest: every tool&amp;rsquo;s name, its natural-language description, and a &lt;strong&gt;JSON Schema&lt;/strong&gt; for its arguments.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Injection.&lt;/strong&gt; The client translates that manifest into the model&amp;rsquo;s tool-definition format and includes it in the request—alongside the system prompt, part of the context on every single call. This is the step that answers &amp;ldquo;how does it know the options available&amp;rdquo;: &lt;strong&gt;the tool catalog is simply text in the context window.&lt;/strong&gt; The model reads the schemas the same way it reads the user&amp;rsquo;s question. No fine-tuning on my tools, no registration—if a tool is in the manifest, the model can see it this session; if I add a tool to the server tomorrow, every client picks it up on the next &lt;code&gt;tools/list&lt;/code&gt; with zero model-side changes. In the server sketch below, that manifest is generated &lt;em&gt;from the code itself&lt;/em&gt;—the function name, the docstring, and the Python type hints become the name, description, and schema. Nothing is written twice.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Invocation.&lt;/strong&gt; When the model emits a tool call, the client validates the arguments against the schema, wraps the call as an MCP &lt;code&gt;tools/call&lt;/code&gt; request, and sends it to the server, which runs the real query and returns the result. The client appends that result to the transcript as a tool message and re-invokes the model.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Repeat&lt;/strong&gt; until the model answers in prose.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;So &amp;ldquo;how does the model know &lt;em&gt;how to use&lt;/em&gt; the tools&amp;rdquo; decomposes into two different mechanisms. The &lt;em&gt;mechanics&lt;/em&gt; of emitting well-formed tool calls come from the model&amp;rsquo;s training—modern chat models are post-trained heavily on tool-use transcripts, which is why they can pick up arbitrary unseen tools at inference time. The &lt;em&gt;semantics&lt;/em&gt;—when to call &lt;code&gt;screen_companies&lt;/code&gt; versus &lt;code&gt;neighbors&lt;/code&gt;, what &lt;code&gt;period: &amp;quot;FY2025&amp;quot;&lt;/code&gt; means—come entirely from the descriptions and schemas in the manifest. This is why I said the docstrings are the prompt: they are the only channel you have to teach the model your tools, and vague ones produce an agent that guesses. A description like &lt;em&gt;&amp;ldquo;query the graph&amp;rdquo;&lt;/em&gt; gets misused; &lt;em&gt;&amp;ldquo;reported metrics for the last N periods, with filing citations&amp;rdquo;&lt;/em&gt; gets called at the right moment with the right arguments.&lt;/p&gt;
&lt;p&gt;What MCP buys over rolling your own tool plumbing is the &lt;strong&gt;standardization of steps 1 and 3&lt;/strong&gt;. Before MCP, every application hand-maintained its own tool list and its own dispatch code per backend—N clients × M data sources of bespoke glue. With MCP, the server declares its capabilities once and any compliant client—today&amp;rsquo;s or next year&amp;rsquo;s—discovers and calls them the same way. That is the concrete meaning of the earlier claim that the graph becomes &amp;ldquo;a capability, not an integration.&amp;rdquo;&lt;/p&gt;
&lt;h3 id=&#34;how-a-graph-gets-queried-the-three-graphrag-retrieval-patterns&#34;&gt;How a graph gets queried: the three GraphRAG retrieval patterns&lt;/h3&gt;
&lt;p&gt;Whichever mode drives, a natural-language question must still become an actual graph operation. In practice there are three patterns, and this system uses the first two:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Local (entity-anchored) search&lt;/strong&gt; — for &amp;ldquo;tell me about X and its relationships.&amp;rdquo; Extract the entity mentions from the question, resolve them to canonical nodes (the same resolver ingestion uses—&lt;code&gt;find_company&lt;/code&gt; in the tool surface), expand the neighborhood one or two hops, collect the attached facts, evidence chunks, and any community summaries the entities belong to, then rank and pack that bundle into the context. It is vector RAG&amp;rsquo;s &amp;ldquo;retrieve then read,&amp;rdquo; except the retrieval unit is a &lt;strong&gt;subgraph&lt;/strong&gt; instead of a similarity list.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Global (community) search&lt;/strong&gt; — for questions with no entity anchor at all: &amp;ldquo;what are the dominant risk themes this quarter?&amp;rdquo; No node to start from, so traversal cannot help. Instead, &lt;strong&gt;map-reduce over community summaries&lt;/strong&gt;: score or partially answer against each community&amp;rsquo;s pre-computed summary (map), then synthesize the partials into one answer (reduce). This is the Microsoft GraphRAG insight—pre-summarizing clusters at index time is what makes corpus-global questions answerable at query time without reading ten thousand chunks. &lt;code&gt;community_themes&lt;/code&gt; is this pattern behind a tool name.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Text-to-Cypher&lt;/strong&gt; — have the LLM translate the question into a graph query language directly. Maximum flexibility, minimum reliability: the model must know your schema exactly, and a subtly wrong &lt;code&gt;MATCH&lt;/code&gt; clause returns a confidently empty (or subtly wrong) result set with no error. This is the fragility argument for the constrained tool surface below—each MCP tool is effectively a &lt;strong&gt;pre-written, parameterized, tested Cypher/SQL template&lt;/strong&gt;, so the model fills in arguments instead of composing queries. The model contributes &lt;em&gt;intent&lt;/em&gt;; the template contributes &lt;em&gt;correctness&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The router question—&amp;ldquo;which pattern does this query need?&amp;quot;—is itself either a cheap classifier in Mode 1 or, in Mode 2, simply the agent&amp;rsquo;s tool choice: picking &lt;code&gt;neighbors&lt;/code&gt; versus &lt;code&gt;community_themes&lt;/code&gt; &lt;em&gt;is&lt;/em&gt; the local/global routing decision, delegated to the model that read the question.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;the-mcp-server-making-the-graph-a-first-class-tool&#34;&gt;The MCP server: making the graph a first-class tool&lt;/h2&gt;
&lt;p&gt;MCP&amp;rsquo;s job here is to turn &amp;ldquo;we have a graph&amp;rdquo; into &amp;ldquo;any LLM can use the graph.&amp;rdquo; Design the tools around &lt;strong&gt;questions analysts ask&lt;/strong&gt;, not around graph primitives—an LLM given only a raw &amp;ldquo;run arbitrary Cypher&amp;rdquo; tool writes bad Cypher and hallucinates schema. Constrained, purposeful tools with typed arguments get dramatically better agent behavior (and are safely read-only).&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# server.py — illustrative. Official MCP Python SDK 2.x renamed FastMCP.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# `from mcp.server.fastmcp import FastMCP` does not import on current SDK releases.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# The standalone `fastmcp` package still ships a class of that name.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; mcp.server.mcpserver &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; MCPServer
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;mcp &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; MCPServer(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;finance-graphrag&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#a6e22e&#34;&gt;@mcp.tool&lt;/span&gt;()
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;find_company&lt;/span&gt;(query: str) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; list[dict]:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&amp;#34;&amp;#34;Resolve a name/ticker to canonical companies (id, name, ticker, sector).&amp;#34;&amp;#34;&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; resolver&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;search(query)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#a6e22e&#34;&gt;@mcp.tool&lt;/span&gt;()
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;get_metrics&lt;/span&gt;(company_id: str, metrics: list[str], periods: int &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;4&lt;/span&gt;) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; dict:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&amp;#34;&amp;#34;Reported metrics for the last N periods, with filing citations and as_of.&amp;#34;&amp;#34;&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; graph&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;metric_history(company_id, metrics, periods)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#a6e22e&#34;&gt;@mcp.tool&lt;/span&gt;()
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;neighbors&lt;/span&gt;(company_id: str, relation: str &lt;span style=&#34;color:#f92672&#34;&gt;|&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;, hops: int &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;1&lt;/span&gt;) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; dict:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&amp;#34;&amp;#34;Related entities: suppliers, customers, competitors, subsidiaries, shared risks.&amp;#34;&amp;#34;&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; graph&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;traverse(company_id, relation, max_hops&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;min(hops, &lt;span style=&#34;color:#ae81ff&#34;&gt;2&lt;/span&gt;))
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#a6e22e&#34;&gt;@mcp.tool&lt;/span&gt;()
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;screen_companies&lt;/span&gt;(min_revenue_growth: float &lt;span style=&#34;color:#f92672&#34;&gt;|&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     max_debt_to_equity: float &lt;span style=&#34;color:#f92672&#34;&gt;|&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     min_margin_trend: float &lt;span style=&#34;color:#f92672&#34;&gt;|&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;                     sector: str &lt;span style=&#34;color:#f92672&#34;&gt;|&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; list[dict]:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&amp;#34;&amp;#34;Screen on metric thresholds computed from reported figures. Deterministic SQL/Cypher—the arithmetic happens here, not in the LLM.&amp;#34;&amp;#34;&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; graph&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;screen(locals())
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#a6e22e&#34;&gt;@mcp.tool&lt;/span&gt;()
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;community_themes&lt;/span&gt;(sector: str &lt;span style=&#34;color:#f92672&#34;&gt;|&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; list[dict]:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&amp;#34;&amp;#34;Community summaries: dominant themes/risks across the corpus (global search).&amp;#34;&amp;#34;&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; graph&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;community_summaries(sector)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#a6e22e&#34;&gt;@mcp.tool&lt;/span&gt;()
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;get_chunk&lt;/span&gt;(chunk_id: str) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; dict:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&amp;#34;&amp;#34;Verbatim source text for a citation—the audit trail&amp;#39;s last hop.&amp;#34;&amp;#34;&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; store&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;chunk(chunk_id)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Two of these deserve emphasis. &lt;code&gt;screen_companies&lt;/code&gt; exists because &lt;strong&gt;LLMs should not do arithmetic over retrieved prose&lt;/strong&gt;—growth rates and ratios are computed in the database, deterministically, and the model only &lt;em&gt;interprets&lt;/em&gt; the results. And &lt;code&gt;get_chunk&lt;/code&gt; closes the provenance loop: every fact the agent cites can be traced to verbatim filing text by anyone reviewing the output.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;the-analyst-agent-from-graph-to-recommendation&#34;&gt;The analyst agent: from graph to recommendation&lt;/h2&gt;
&lt;p&gt;With the tools in place, the analyst LLM needs no special training—just a system prompt establishing the workflow and the guardrails, running the agentic loop (Mode 2 above): plan, call a tool, read the result, decide the next hop. A real trace from the working system, condensed:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;User:&lt;/strong&gt; &amp;ldquo;Which companies in the corpus look strongest based on their recent reporting?&amp;rdquo;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Agent&lt;/strong&gt; → &lt;code&gt;screen_companies(min_revenue_growth=0.05, max_debt_to_equity=1.0, min_margin_trend=0.0)&lt;/code&gt; → 6 candidates
&lt;strong&gt;Agent&lt;/strong&gt; → &lt;code&gt;get_metrics(...)&lt;/code&gt; for each → drops one (single strong quarter, longer trend flat)
&lt;strong&gt;Agent&lt;/strong&gt; → &lt;code&gt;neighbors(company_id, relation=&amp;quot;EXPOSED_TO_RISK&amp;quot;)&lt;/code&gt; → flags two sharing heavy customer-concentration risk with the same downstream buyer
&lt;strong&gt;Agent&lt;/strong&gt; → &lt;code&gt;community_themes(sector=&amp;quot;semiconductors&amp;quot;)&lt;/code&gt; → notes sector-wide inventory-correction theme, contextualizes one firm&amp;rsquo;s margin dip as industry-wide rather than idiosyncratic
&lt;strong&gt;Agent&lt;/strong&gt; → final answer: three companies, each with metric trajectories, the risk caveats, and &lt;strong&gt;filing citations per claim&lt;/strong&gt;, closing with the system&amp;rsquo;s standing disclaimer.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Notice what the graph bought: the risk-overlap step (&lt;strong&gt;shared exposure discovered via traversal&lt;/strong&gt;) and the sector context (&lt;strong&gt;community summary&lt;/strong&gt;) are the parts vector RAG could not have produced. The screen itself is just SQL; the &lt;em&gt;judgment&lt;/em&gt;—dropping the one-quarter wonder, discounting the industry-wide dip—is the LLM doing what it is actually good at, on top of numbers it did not compute and facts it did not invent.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;ingestion half&lt;/strong&gt; of the data agent is the unglamorous twin: a scheduled loop that polls EDGAR for new filings, runs fetch → chunk → extract → validate → resolve → upsert, marks communities dirty, and writes an ingestion report (chunks processed, triples accepted/rejected, unresolved entities queued for review). The rejection rate is the metric to watch—when it spikes, either the extractor regressed or a new document format arrived, and either way you want the alarm &lt;em&gt;before&lt;/em&gt; the graph degrades.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;what-i-would-tell-a-colleague-starting-this&#34;&gt;What I would tell a colleague starting this&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Start with the vector index; add the graph when questions demand it.&lt;/strong&gt; If nobody asks multi-hop or corpus-global questions, GraphRAG is expensive ceremony.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Spend the LLM budget on narrative, not numbers.&lt;/strong&gt; XBRL gives you core financials structured for free. Extracting &lt;code&gt;REPORTS_METRIC&lt;/code&gt; from prose when the same fact exists as machine-readable data is paying for hallucination risk.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Evidence-span validation is the highest-leverage line of code in the pipeline.&lt;/strong&gt; Verbatim-quote checking rejected the majority of bad triples in my runs, at the cost of a substring check.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Entity resolution and temporal modeling are the product.&lt;/strong&gt; Community summaries are the flashy part of GraphRAG; alias tables and &lt;code&gt;period&lt;/code&gt; fields are what make the answers &lt;em&gt;true&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Constrain the tool surface.&lt;/strong&gt; Purpose-built MCP tools with typed arguments beat a raw query tool—every time—for agent reliability, and read-only enforcement belongs at the server, not in the prompt.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Keep the model out of the arithmetic.&lt;/strong&gt; Screens and ratios are computed in the store; the LLM interprets. The moment a growth rate is generated rather than queried, your citations stop meaning anything.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;GraphRAG earns its complexity exactly when the questions are relational or global—and a continuously growing corpus of financial filings generates those questions constantly. The stack that emerged is a pipeline of familiar disciplines: the chunking care from &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/&#34;&gt;RAG Foundations&lt;/a&gt;, the self-hosted serving economics from &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/&#34;&gt;Serving Small Models Behind an HTTP API&lt;/a&gt; applied to extraction throughput, and the evaluation instinct from &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-operations-re-ranking-and-evaluation/&#34;&gt;RAG in Production: Re-ranking, HyDE, and Simple Evals&lt;/a&gt; pointed at a new target—triple accuracy instead of retrieval hit-rate.&lt;/p&gt;
&lt;p&gt;The MCP layer is what turns the whole thing from a pipeline into a &lt;em&gt;capability&lt;/em&gt;: the graph becomes a set of tools any agent can pick up, the agent&amp;rsquo;s answers become paths through cited facts, and the human reviewing a recommendation can walk every hop back to the filing that said it. That auditability—not the recommendation itself—is the real deliverable of putting a knowledge graph under an LLM.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>I Ran a Random .exe From GitHub: An Audit Instead of a Reformat</title>
      <link>https://blog.veydh.com/2026/2026-06-running-untrusted-exes/</link>
      <pubDate>Sat, 20 Jun 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-06-running-untrusted-exes/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;I did that thing you are not supposed to do: Digging up a random &lt;code&gt;.exe&lt;/code&gt; in a GitHub repo, and running it before I audited it or built it from its source. It was an unofficial &amp;ldquo;pro&amp;rdquo; fork of an otherwise legitimate open-source developer tool—the kind of repo that ships a compiled binary next to the source and asks you to trust that the two match. It worked. Then, about 2 minutes later, the &lt;strong&gt;paranoia&lt;/strong&gt; set in. Was that gonna keylog me? Screenshot my desktop? Did it just phone home with my session tokens? Had it quietly installed persistence so it survives a reboot?&lt;/p&gt;
&lt;p&gt;That nagging feeling to nuke the drive, reinstall Windows, rotate every password in a panic was starting to set in. The calmer reaction to answer that question with evidence: &lt;em&gt;is there anything malicious here, and did running it leave anything behind?&lt;/em&gt; This post is the workflow I used to address this calmly/sainly. It is two-pronged: &lt;strong&gt;static source review&lt;/strong&gt; of the repository, and &lt;strong&gt;live host forensics&lt;/strong&gt; on the machine where the binary had already executed. Every host command below is a &lt;strong&gt;read-only diagnostic&lt;/strong&gt;—nothing here changes the system, which matters when you are trying to preserve evidence rather than stomp on it.&lt;/p&gt;
&lt;p&gt;The tools are &lt;strong&gt;PowerShell&lt;/strong&gt;, &lt;code&gt;rg&lt;/code&gt; (ripgrep), and Windows&amp;rsquo; own security stack. The ethics frame is the same one I use for &lt;a href=&#34;https://blog.veydh.com/2023/2023-08-metasploit-lab-workflow/&#34;&gt;Metasploit in a Controlled Lab After Nmap&lt;/a&gt; and &lt;a href=&#34;https://blog.veydh.com/2023/2023-06-sqlmap-basics-defensive-mindset/&#34;&gt;sqlmap Basics with a Defensive Mindset&lt;/a&gt;: only touch systems you own, and stay honest in the write-up.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;framing-malware-and-untrustworthy-are-two-different-verdicts&#34;&gt;Framing: &amp;ldquo;malware&amp;rdquo; and &amp;ldquo;untrustworthy&amp;rdquo; are two different verdicts&lt;/h2&gt;
&lt;p&gt;Before touching a command, separate the two questions that paranoia fuses together:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Is it malware?&lt;/strong&gt; Does it keylog, capture the screen, exfiltrate data, install persistence, or open a command-and-control channel?&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Is it trustworthy?&lt;/strong&gt; Is it signed, does it match its source, and does it do only what it claims?&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;An executable can be &lt;strong&gt;not malware&lt;/strong&gt; and still &lt;strong&gt;not trustworthy&lt;/strong&gt;—an unsigned binary from an anonymous fork author is exactly that. Keeping these separate stops you from either declaring &amp;ldquo;it&amp;rsquo;s fine&amp;rdquo; too early or &amp;ldquo;it&amp;rsquo;s a virus&amp;rdquo; without proof. The output you want at the end is a small verdict table, not a vibe.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;part-1--static-source-review&#34;&gt;Part 1 — Static source review&lt;/h2&gt;
&lt;p&gt;The repo shipped source &lt;em&gt;and&lt;/em&gt; a binary. The source cannot prove the binary is clean (more on that later), but it is the cheapest place to find intent, and it tells you what the app &lt;em&gt;believes&lt;/em&gt; it does.&lt;/p&gt;
&lt;h3 id=&#34;11-hunt-for-keylogging-and-screen-capture&#34;&gt;1.1 Hunt for keylogging and screen capture&lt;/h3&gt;
&lt;p&gt;Case-insensitive &lt;code&gt;rg&lt;/code&gt; across &lt;code&gt;src/&lt;/code&gt; for the APIs that spyware actually needs:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;rg -i &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;getDisplayMedia|desktopCapturer|screenshot|captureScreen|getUserMedia|MediaRecorder&amp;#34;&lt;/span&gt; src
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;rg -i &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;keylog|keystroke|robotjs|iohook|GetAsyncKeyState|SetWindowsHookEx&amp;#34;&lt;/span&gt; src
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;rg -i &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;keydown|keypress|keyup|onKeyDown|addEventListener\(.key&amp;#34;&lt;/span&gt; src
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The trick is reading the &lt;strong&gt;context&lt;/strong&gt;, not counting hits. In my case:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;No&lt;/strong&gt; screen-capture APIs anywhere.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No&lt;/strong&gt; keyboard-logging libraries (&lt;code&gt;robotjs&lt;/code&gt;, &lt;code&gt;iohook&lt;/code&gt;) or Win32 hooks.&lt;/li&gt;
&lt;li&gt;Every &lt;code&gt;keydown&lt;/code&gt;/&lt;code&gt;keyup&lt;/code&gt; was a &lt;strong&gt;legitimate UI handler&lt;/strong&gt;—accessibility, search filters, editor focus, tab/list navigation.&lt;/li&gt;
&lt;li&gt;The scary-looking &lt;code&gt;keyLog&lt;/code&gt; matches were a &lt;strong&gt;TLS key log file&lt;/strong&gt; feature (&lt;code&gt;SSLKEYLOGFILE&lt;/code&gt;, for decrypting your &lt;em&gt;own&lt;/em&gt; captured TLS in Wireshark)—&lt;strong&gt;not&lt;/strong&gt; keyboard logging.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That last one is the whole lesson: a substring match is a &lt;strong&gt;question&lt;/strong&gt;, not a finding. &lt;code&gt;keyLog&lt;/code&gt; and &lt;em&gt;keylogger&lt;/em&gt; share five letters and nothing else.&lt;/p&gt;
&lt;h3 id=&#34;12-look-for-obfuscation-and-dynamic-execution&#34;&gt;1.2 Look for obfuscation and dynamic execution&lt;/h3&gt;
&lt;p&gt;Payloads hide behind runtime evaluation and encoding:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;rg -i &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;eval\(|new Function|atob\(|fromCharCode|\\\\x[0-9a-f]{2}&amp;#34;&lt;/span&gt; src
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Here the matches were all in &lt;strong&gt;developer tools&lt;/strong&gt; components—base64/hex/JWT/AES/QR helpers—which is exactly what an HTTP-debugging-style app is &lt;em&gt;supposed&lt;/em&gt; to contain. No packed blobs, no hidden second stage.&lt;/p&gt;
&lt;h3 id=&#34;13-trace-the-network--exfiltration-surface&#34;&gt;1.3 Trace the network / exfiltration surface&lt;/h3&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;rg -i &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;fetch\(|axios|\.post\(|XMLHttpRequest|sendBeacon|new WebSocket\(&amp;#34;&lt;/span&gt; src
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;rg -o -i &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;https?://[a-z0-9._/-]{4,80}&amp;#34;&lt;/span&gt; src | Sort-Object -Unique
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Account for &lt;strong&gt;every&lt;/strong&gt; outbound destination:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;App/server calls targeted &lt;strong&gt;localhost only&lt;/strong&gt; (&lt;code&gt;127.0.0.1&lt;/code&gt; on a fixed port, &lt;code&gt;ws://127.0.0.1:...&lt;/code&gt;), confirmed in the &lt;code&gt;.env.*&lt;/code&gt; files.&lt;/li&gt;
&lt;li&gt;Service-worker &lt;code&gt;fetch&lt;/code&gt; was same-origin cache logic.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;only&lt;/strong&gt; external telemetry was &lt;strong&gt;Google Firebase Analytics&lt;/strong&gt;—normal-shape analytics (event names, error messages, stack traces), but pointed at the &lt;strong&gt;fork author&amp;rsquo;s&lt;/strong&gt; project rather than upstream.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Telemetry redirected to a stranger&amp;rsquo;s account is a &lt;strong&gt;trust&lt;/strong&gt; problem, not a keylogger. Naming it precisely is the point.&lt;/p&gt;
&lt;h3 id=&#34;14-the-crack-finding&#34;&gt;1.4 The &amp;ldquo;crack&amp;rdquo; finding&lt;/h3&gt;
&lt;p&gt;The account/licensing module had been rewritten so &lt;code&gt;isLoggedIn&lt;/code&gt; and &lt;code&gt;isPaidUser&lt;/code&gt; are hardcoded &lt;code&gt;true&lt;/code&gt;, with a dummy user object. That confirms the repo is a &lt;strong&gt;pirated build&lt;/strong&gt; of the tool&amp;rsquo;s commercial features. Again: a &lt;strong&gt;licensing/trust&lt;/strong&gt; issue, not malware—but exactly the sort of thing that tells you &lt;em&gt;why&lt;/em&gt; an anonymous author bothered to fork and rebuild.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;part-2--binary-analysis&#34;&gt;Part 2 — Binary analysis&lt;/h2&gt;
&lt;p&gt;Source review only covers the source. The shipped &lt;code&gt;.exe&lt;/code&gt; is what actually ran, and there is no buildable desktop source to rebuild it from—so it has to be inspected as an opaque artifact.&lt;/p&gt;
&lt;h3 id=&#34;21-identity-and-hashing&#34;&gt;2.1 Identity and hashing&lt;/h3&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-FileHash .\mystery.exe -Algorithm SHA256
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;(Get-Item .\mystery.exe).VersionInfo | Format-List
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Record the &lt;strong&gt;SHA-256&lt;/strong&gt; and the embedded version metadata. The hash is your anchor for a &lt;strong&gt;VirusTotal&lt;/strong&gt; lookup—paste it into &lt;code&gt;https://www.virustotal.com/gui/file/&amp;lt;sha256&amp;gt;&lt;/code&gt;. If the hash has never been seen, submit the file for a fresh multi-engine scan. (Mind that uploading a private build shares it publicly; a hash lookup alone does not.)&lt;/p&gt;
&lt;h3 id=&#34;22-digital-signature&#34;&gt;2.2 Digital signature&lt;/h3&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-AuthenticodeSignature .\mystery.exe | Format-List
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Mine came back &lt;strong&gt;&lt;code&gt;NotSigned&lt;/code&gt;&lt;/strong&gt;. That single word is the core trust verdict: the binary &lt;strong&gt;cannot be attributed to a publisher&lt;/strong&gt; and cannot be verified against source. Not proof of malice—plenty of legitimate hobby builds are unsigned—but it is why &amp;ldquo;not malware&amp;rdquo; is the ceiling on how much you can trust it.&lt;/p&gt;
&lt;h3 id=&#34;23-strings-and-capability-inspection&#34;&gt;2.3 Strings and capability inspection&lt;/h3&gt;
&lt;p&gt;You can read a surprising amount straight out of a binary with &lt;code&gt;rg -a&lt;/code&gt; (treat-as-text):&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;rg -a -o &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;https?://[a-zA-Z0-9._/-]{4,80}&amp;#34;&lt;/span&gt; mystery.exe | Sort-Object -Unique
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;rg -a -c -i &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;GetAsyncKeyState|SetWindowsHookEx|keybd_event|BitBlt|GetDC|CreateCompatibleBitmap|GetClipboardData&amp;#34;&lt;/span&gt; mystery.exe
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;rg -a -o &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;.{60}GetAsyncKeyState.{60}&amp;#34;&lt;/span&gt; mystery.exe
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;rg -a -o &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;.{60}BitBlt.{60}&amp;#34;&lt;/span&gt; mystery.exe
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This is where paranoia peaks and then deflates. &lt;code&gt;GetAsyncKeyState&lt;/code&gt; and &lt;code&gt;BitBlt&lt;/code&gt; &lt;strong&gt;do&lt;/strong&gt; appear in the binary—both classic keylogger/screen-grabber primitives. But read the neighbours:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;...EnableMenuItem SetWindowLongW GetKeyboardState GetAsyncKeyState CreateIcon DrawIconEx...
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;...DwmGetWindowAttribute BitBlt CreateDIBSection SelectObject DeleteDC ReleaseDC...
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Those are the &lt;strong&gt;standard GUI/windowing runtime&lt;/strong&gt;—menu accelerators and window drawing pulled in by the desktop framework (a Tauri/WebView2 shell, per other strings like &lt;code&gt;tauri_runtime_wry&lt;/code&gt; and WebView2 references). There was &lt;strong&gt;no&lt;/strong&gt; &lt;code&gt;SetWindowsHookEx&lt;/code&gt;, &lt;strong&gt;no&lt;/strong&gt; &lt;code&gt;keybd_event&lt;/code&gt;, &lt;strong&gt;no&lt;/strong&gt; &lt;code&gt;GetClipboardData&lt;/code&gt;, and no screenshot-to-network chain. An API being &lt;em&gt;present&lt;/em&gt; is not the same as it being &lt;em&gt;wired into a malicious flow&lt;/em&gt;. Context—the surrounding symbols and whether any exfiltration path consumes them—is what separates a keylogger from a menu bar.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;part-3--live-host-forensics-it-already-ran&#34;&gt;Part 3 — Live host forensics (it already ran)&lt;/h2&gt;
&lt;p&gt;The binary had executed, so the real question shifts from &amp;ldquo;what could it do&amp;rdquo; to &amp;ldquo;what did it leave behind.&amp;rdquo; Everything here is read-only.&lt;/p&gt;
&lt;h3 id=&#34;31-processes-and-their-children&#34;&gt;3.1 Processes and their children&lt;/h3&gt;
&lt;p&gt;Malware often spawns shells, script hosts, or droppers. Walk the tree:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-Process | Where-Object { $_.ProcessName &lt;span style=&#34;color:#f92672&#34;&gt;-like&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;*mystery*&amp;#34;&lt;/span&gt; } |
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  Select-Object Id, ProcessName, Path, StartTime
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-CimInstance Win32_Process -Filter &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;ParentProcessId=&amp;lt;PID&amp;gt;&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The only child was the expected embedded browser process (&lt;code&gt;msedgewebview2.exe&lt;/code&gt;) launched by the desktop shell. &lt;strong&gt;No&lt;/strong&gt; shells, no &lt;code&gt;powershell.exe&lt;/code&gt;/&lt;code&gt;wscript.exe&lt;/code&gt; children, no dropper.&lt;/p&gt;
&lt;h3 id=&#34;32-network-connections&#34;&gt;3.2 Network connections&lt;/h3&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-NetTCPConnection -OwningProcess &amp;lt;PID&amp;gt; |
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  Where-Object { $_.RemoteAddress -notin @(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#39;127.0.0.1&amp;#39;&lt;/span&gt;,&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#39;0.0.0.0&amp;#39;&lt;/span&gt;,&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#39;::&amp;#39;&lt;/span&gt;,&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#39;::1&amp;#39;&lt;/span&gt;) }
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;No non-local TCP connections&lt;/strong&gt; from the process or its WebView child at inspection time. No command-and-control beacon holding a socket open.&lt;/p&gt;
&lt;h3 id=&#34;33-persistence&#34;&gt;3.3 Persistence&lt;/h3&gt;
&lt;p&gt;The high-value question for &amp;ldquo;will it survive a reboot.&amp;rdquo; Check every common autostart surface:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-ItemProperty &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#39;HKCU:\Software\Microsoft\Windows\CurrentVersion\Run&amp;#39;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-ItemProperty &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#39;HKLM:\Software\Microsoft\Windows\CurrentVersion\Run&amp;#39;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-ItemProperty &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#39;HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce&amp;#39;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-ChildItem &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&lt;/span&gt;$env:APPDATA&lt;span style=&#34;color:#e6db74&#34;&gt;\Microsoft\Windows\Start Menu\Programs\Startup&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-ScheduledTask | Where-Object { $_.TaskName &lt;span style=&#34;color:#f92672&#34;&gt;-like&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;*mystery*&amp;#34;&lt;/span&gt; }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-CimInstance Win32_Service | Where-Object { $_.PathName &lt;span style=&#34;color:#f92672&#34;&gt;-like&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;*mystery*&amp;#34;&lt;/span&gt; }
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The &lt;code&gt;Run&lt;/code&gt; keys held only pre-existing, recognizable software; &lt;code&gt;RunOnce&lt;/code&gt; and the Startup folder were empty; &lt;strong&gt;no&lt;/strong&gt; matching scheduled task or service. &lt;strong&gt;Nothing&lt;/strong&gt; tied itself to boot. This is the check that most directly dissolves the &amp;ldquo;it&amp;rsquo;s still in there&amp;rdquo; fear.&lt;/p&gt;
&lt;h3 id=&#34;34-files-it-created&#34;&gt;3.4 Files it created&lt;/h3&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-ChildItem &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&lt;/span&gt;$env:LOCALAPPDATA&lt;span style=&#34;color:#e6db74&#34;&gt;\&amp;lt;app-data-dir&amp;gt;&amp;#34;&lt;/span&gt; -Recurse
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-ChildItem &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&lt;/span&gt;$env:USERPROFILE&lt;span style=&#34;color:#e6db74&#34;&gt;\Desktop\&amp;lt;extract-folder&amp;gt;&amp;#34;&lt;/span&gt; -Force
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Everything mapped to a &lt;strong&gt;standard Edge WebView2 profile&lt;/strong&gt; (Crashpad, GPUCache, ShaderCache, Local State) plus the tool&amp;rsquo;s own bundled Node server directory. Nothing anomalous, nothing written outside the app&amp;rsquo;s own folders.&lt;/p&gt;
&lt;h3 id=&#34;35-root-ca-certificates--the-one-that-actually-matters-here&#34;&gt;3.5 Root CA certificates — the one that actually matters here&lt;/h3&gt;
&lt;p&gt;For any tool in the traffic-interception family, the &lt;strong&gt;most security-sensitive&lt;/strong&gt; artifact it can create is a &lt;strong&gt;trusted root CA&lt;/strong&gt;. If one is installed, the tool (or anyone with its key) can transparently MITM your HTTPS. So check both stores explicitly:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-ChildItem Cert&lt;span style=&#34;color:#960050;background-color:#1e0010&#34;&gt;:&lt;/span&gt;\CurrentUser\Root  | Where-Object { $_.Subject &lt;span style=&#34;color:#f92672&#34;&gt;-like&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;*&amp;lt;tool-name&amp;gt;*&amp;#34;&lt;/span&gt; }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-ChildItem Cert&lt;span style=&#34;color:#960050;background-color:#1e0010&#34;&gt;:&lt;/span&gt;\LocalMachine\Root | Where-Object { $_.Subject &lt;span style=&#34;color:#f92672&#34;&gt;-like&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;*&amp;lt;tool-name&amp;gt;*&amp;#34;&lt;/span&gt; }
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;None installed.&lt;/strong&gt; (Such a CA is only added when interception is actively started, which had not happened.) If you &lt;em&gt;do&lt;/em&gt; find a rogue root CA, that is the one artifact worth removing immediately, not just noting.&lt;/p&gt;
&lt;h3 id=&#34;36-antivirus-status-and-an-on-demand-scan&#34;&gt;3.6 Antivirus status and an on-demand scan&lt;/h3&gt;
&lt;p&gt;Finally, ask the defender that was already watching:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-powershell&#34; data-lang=&#34;powershell&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-MpComputerStatus | Select-Object AntivirusEnabled, RealTimeProtectionEnabled,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  AntivirusSignatureLastUpdated, IsTamperProtected
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Get-MpThreatDetection | Where-Object { $_.InitialDetectionTime &lt;span style=&#34;color:#f92672&#34;&gt;-gt&lt;/span&gt; (Get-Date).AddHours(&lt;span style=&#34;color:#ae81ff&#34;&gt;-3&lt;/span&gt;) }
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;Start-MpScan -ScanPath &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&amp;lt;path-to-exe&amp;gt;&amp;#34;&lt;/span&gt; -ScanType CustomScan
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;Windows Defender&lt;/strong&gt; was fully active—real-time protection on, tamper protection on, current signatures—&lt;strong&gt;with zero detections&lt;/strong&gt;, both when the file executed and on a follow-up scan. Real-time protection having been &lt;em&gt;on the whole time and silent&lt;/em&gt; is meaningful evidence, not nothing.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;the-verdict-table&#34;&gt;The verdict table&lt;/h2&gt;
&lt;p&gt;The whole point of the exercise is to collapse the anxiety into a defensible summary:&lt;/p&gt;
&lt;table&gt;
  &lt;thead&gt;
      &lt;tr&gt;
          &lt;th&gt;Area&lt;/th&gt;
          &lt;th&gt;Verdict&lt;/th&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr&gt;
          &lt;td&gt;Keylogging (source + binary)&lt;/td&gt;
          &lt;td&gt;&lt;strong&gt;Not present&lt;/strong&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Screen capture&lt;/td&gt;
          &lt;td&gt;&lt;strong&gt;Not present&lt;/strong&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Covert exfiltration&lt;/td&gt;
          &lt;td&gt;&lt;strong&gt;Not present&lt;/strong&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Persistence on host&lt;/td&gt;
          &lt;td&gt;&lt;strong&gt;None found&lt;/strong&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;External C2 connections&lt;/td&gt;
          &lt;td&gt;&lt;strong&gt;None observed&lt;/strong&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Antivirus detection&lt;/td&gt;
          &lt;td&gt;&lt;strong&gt;None&lt;/strong&gt; (real-time protection active)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Signed / verifiable&lt;/td&gt;
          &lt;td&gt;&lt;strong&gt;No&lt;/strong&gt; (&lt;code&gt;NotSigned&lt;/code&gt;, anonymous author)&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Overall&lt;/td&gt;
          &lt;td&gt;&lt;strong&gt;No malware indicators in this pass; not trustworthy&lt;/strong&gt;&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;A clean snapshot is not a proof. A process that already exited, a payload that ran and deleted itself, or a task under a name these filters did not guess will not appear. The table is “nothing showed up in this pass,” which is enough to skip a panic reinstall and not enough to call the machine proven clean.&lt;/p&gt;
&lt;p&gt;The residual concerns were exactly the ones I could not wave away with forensics: an &lt;strong&gt;unsigned&lt;/strong&gt; binary I can&amp;rsquo;t verify against source, a &lt;strong&gt;paywall bypass&lt;/strong&gt;, and &lt;strong&gt;analytics redirected&lt;/strong&gt; to the fork author. Trust problems. This pass did not show a virus.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;cleanup-and-hardening-after-the-read-only-pass&#34;&gt;Cleanup and hardening (after the read-only pass)&lt;/h2&gt;
&lt;p&gt;Once the diagnostics are done, &lt;em&gt;then&lt;/em&gt; you make changes, deliberately:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Prefer the &lt;strong&gt;official, signed&lt;/strong&gt; build from the real vendor over a cracked fork—always.&lt;/li&gt;
&lt;li&gt;Submit the hash (or file) to &lt;strong&gt;VirusTotal&lt;/strong&gt; for a second opinion.&lt;/li&gt;
&lt;li&gt;Run &lt;code&gt;Start-MpScan -ScanType QuickScan&lt;/code&gt; for a fast second pass. A quick scan is not a full scan. Use &lt;code&gt;-ScanType FullScan&lt;/code&gt; when you want the whole machine.&lt;/li&gt;
&lt;li&gt;If interception was ever started, re-check and &lt;strong&gt;remove any rogue root CA&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;To fully remove: &lt;code&gt;Stop-Process -Id &amp;lt;PID&amp;gt; -Force&lt;/code&gt;, delete the extracted folder, and clear its &lt;code&gt;AppData\Local\&amp;lt;app-data-dir&amp;gt;&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2 id=&#34;the-lesson-sometimes-you-gotta-fight-the-paranoia&#34;&gt;The lesson: sometimes you gotta fight the paranoia&lt;/h2&gt;
&lt;p&gt;The instinct to reformat is really an admission that you don&amp;rsquo;t know what happened. Running forensics can at least increase confidence that you didn&amp;rsquo;t get totally pwned, and it saves a day or two of reinstalling your OS. The reusable checklist that came out of this:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Signature and hash first&lt;/strong&gt;—cheap, and they set the trust ceiling immediately.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Grep for capability, then read context&lt;/strong&gt;—a matched API name is a lead, not a conviction.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;On a host that already ran it, chase five things&lt;/strong&gt;: child processes, live network connections, persistence, files written, and (for interception tools) root CAs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Keep the host commands read-only&lt;/strong&gt; until you understand the picture; you cannot un-stomp evidence.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Separate &amp;ldquo;malware&amp;rdquo; from &amp;ldquo;untrustworthy.&amp;rdquo;&lt;/strong&gt; Most sketchy GitHub binaries are the latter—which is still a good enough reason to delete them and use the signed original.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I admit the paranoia might still stick around because it&amp;rsquo;s hard to squash that feeling of &amp;lsquo;what if that process spawned other processes somehow and maybe I&amp;rsquo;m just not looking in the right place&amp;hellip;&amp;rsquo;. Thankfully there are built in defences around that, and that kind of behavior is flaggable and catchable with a little digging and can be eliminated as a possibility. Blackhats do be finding creative ways to stay silent and hidden but sometimes life just has to go on. Save that system wipe for a rainy day lol.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Deciding whether a binary is dangerous is the operational cousin of reading one for fun. The static half of this post—strings, capabilities, mapping symbols to intent—is the same literacy I built in &lt;a href=&#34;https://blog.veydh.com/2023/2023-05-ghidra-hello-reverse-engineering/&#34;&gt;GHIDRA on a Tiny C++ Binary: Strings and Control Flow&lt;/a&gt;; the forensic half is just applying that same &amp;ldquo;verify, don&amp;rsquo;t assume&amp;rdquo; discipline to a whole host. The best defense against a random &lt;code&gt;.exe&lt;/code&gt; is not fear—it is a checklist you trust more than the download.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Qwen3-TTS and Multilingual Neural TTS Trade-offs</title>
      <link>https://blog.veydh.com/2026/2026-04-qwen3-tts-and-multilingual-neural-tts/</link>
      <pubDate>Sat, 04 Apr 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-04-qwen3-tts-and-multilingual-neural-tts/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;Large &lt;strong&gt;multilingual TTS&lt;/strong&gt; stacks—including &lt;strong&gt;Qwen3-TTS&lt;/strong&gt;-class models—aim for natural &lt;strong&gt;prosody&lt;/strong&gt;, broad &lt;strong&gt;language coverage&lt;/strong&gt;, and assistant-grade clarity. They occupy the opposite corner of the design space from &lt;a href=&#34;https://blog.veydh.com/2026/2026-03-kokoro-tts-lightweight-synthesis/&#34;&gt;Kokoro TTS: Lightweight Neural Speech and Where It Fits&lt;/a&gt;’s lightweight engines: more expressive, heavier to run, and proportionally more complex to operate.&lt;/p&gt;
&lt;p&gt;This post is not a benchmark manifesto; it is a frame for deciding &lt;strong&gt;when&lt;/strong&gt; to pay that cost.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Qwen3-TTS&lt;/strong&gt; itself shipped on 22 January 2026. The released 12 Hz family is &lt;strong&gt;0.6B and 1.7B&lt;/strong&gt; parameters, &lt;strong&gt;Apache-2.0&lt;/strong&gt;, and ten languages: Chinese, English, Japanese, Korean, German, French, Russian, Portuguese, Spanish, and Italian. The Base checkpoints clone a voice from about &lt;strong&gt;3 seconds&lt;/strong&gt; of reference audio. CustomVoice and VoiceDesign add preset timbres and natural-language style control. The technical report (arXiv:2601.15621) gives first-packet latency of about &lt;strong&gt;97 ms&lt;/strong&gt; for the 0.6B and &lt;strong&gt;101 ms&lt;/strong&gt; for the 1.7B. Those are the authors’ figures, not your p95. A 1.7B model is heavy next to Kokoro-82M and still fits on &lt;strong&gt;one&lt;/strong&gt; GPU. Extra GPUs are for concurrent streams, not because one copy of the model needs to be split.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;when-heavy-tts-earns-its-gpus&#34;&gt;When heavy TTS earns its GPUs&lt;/h2&gt;
&lt;p&gt;Moving up-stack makes sense when:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The product is &lt;strong&gt;voice-first&lt;/strong&gt;—users judge quality in seconds.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Multilingual&lt;/strong&gt; parity matters; lightweight bundles do not cover locales we sell into.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Controllability&lt;/strong&gt; (rate, style, explicit speaker control when supported) is part of the UX contract.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In those cases, cost per minute is still tracked, but it is weighed against churn and brand perception—not against batch IVR pricing alone.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;operational-reality&#34;&gt;Operational reality&lt;/h2&gt;
&lt;p&gt;Bigger models mean &lt;strong&gt;more VRAM&lt;/strong&gt;, longer cold starts unless kept warm, and trickier autoscaling. TTS capacity is co-designed with &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/&#34;&gt;Serving Small Models Behind an HTTP API&lt;/a&gt;’s LLM serving: both contend for GPU pools unless fleets are split.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Licensing&lt;/strong&gt; and &lt;strong&gt;voice rights&lt;/strong&gt; do not disappear because audio is synthetic. Terms of use for checkpoints, commercial redistribution, and cloned speaker data still bind shipping products. Legal review belongs in the same loop as for third-party LLM APIs.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;comparison-back-to-kokoro-class&#34;&gt;Comparison back to Kokoro-class&lt;/h2&gt;
&lt;p&gt;&lt;a href=&#34;https://blog.veydh.com/2026/2026-03-kokoro-tts-lightweight-synthesis/&#34;&gt;Kokoro TTS: Lightweight Neural Speech and Where It Fits&lt;/a&gt;’s lightweight path trades &lt;strong&gt;range and nuance&lt;/strong&gt; for &lt;strong&gt;efficiency&lt;/strong&gt;. Heavy TTS inverts that trade. Neither is “correct” globally—&lt;strong&gt;requirements&lt;/strong&gt; pick the winner.&lt;/p&gt;
&lt;p&gt;When marketing later demands a &lt;strong&gt;specific&lt;/strong&gt; timbre not native to the TTS roster, &lt;strong&gt;RVC&lt;/strong&gt; (&lt;a href=&#34;https://blog.veydh.com/2026/2026-04-rvc-voice-conversion-architecture/&#34;&gt;RVC in the Stack: Voice Conversion After TTS&lt;/a&gt;) becomes the bridge: synthesize with a strong base, then convert timbre—at the cost of latency and governance overhead.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;decision-worksheet-fill-before-you-buy-gpus&#34;&gt;Decision worksheet (fill before you buy GPUs)&lt;/h2&gt;
&lt;table&gt;
  &lt;thead&gt;
      &lt;tr&gt;
          &lt;th&gt;Question&lt;/th&gt;
          &lt;th&gt;If “yes” →&lt;/th&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr&gt;
          &lt;td&gt;Do we sell into locales beyond the lightweight roster?&lt;/td&gt;
          &lt;td&gt;Bias toward &lt;strong&gt;heavy multilingual&lt;/strong&gt;; prove MOS, speaker similarity, and intelligibility per locale. ASR word-error on the synthesized audio is a proxy, and it is not the same number as an ASR model’s WER.&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Is voice a &lt;strong&gt;primary&lt;/strong&gt; differentiator (podcast, companion app)?&lt;/td&gt;
          &lt;td&gt;Bias toward &lt;strong&gt;heavy&lt;/strong&gt;; budget warm pools.&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Is this &lt;strong&gt;IVR / notifications&lt;/strong&gt; at huge volume?&lt;/td&gt;
          &lt;td&gt;Bias toward &lt;strong&gt;light&lt;/strong&gt; (&lt;a href=&#34;https://blog.veydh.com/2026/2026-03-kokoro-tts-lightweight-synthesis/&#34;&gt;Kokoro TTS: Lightweight Neural Speech and Where It Fits&lt;/a&gt;); measure RTF.&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Must timbre match a &lt;strong&gt;specific&lt;/strong&gt; human?&lt;/td&gt;
          &lt;td&gt;&lt;strong&gt;Qwen3-TTS Base&lt;/strong&gt; clones from a few seconds of consented reference audio. Add &lt;strong&gt;RVC&lt;/strong&gt; (&lt;a href=&#34;https://blog.veydh.com/2026/2026-04-rvc-voice-conversion-architecture/&#34;&gt;RVC in the Stack: Voice Conversion After TTS&lt;/a&gt;) when the TTS model cannot clone, or when that clone is not good enough. Consent rules are the same either way.&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;hr&gt;
&lt;h2 id=&#34;operational-comparison-vs-lightweight-kokoro-class-tts&#34;&gt;Operational comparison vs lightweight Kokoro-class TTS&lt;/h2&gt;
&lt;table&gt;
  &lt;thead&gt;
      &lt;tr&gt;
          &lt;th&gt;Dimension&lt;/th&gt;
          &lt;th&gt;Heavy multilingual (Qwen3-TTS-class)&lt;/th&gt;
          &lt;th&gt;Lightweight TTS (&lt;a href=&#34;https://blog.veydh.com/2026/2026-03-kokoro-tts-lightweight-synthesis/&#34;&gt;Kokoro TTS: Lightweight Neural Speech and Where It Fits&lt;/a&gt;)&lt;/th&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr&gt;
          &lt;td&gt;GPU RAM&lt;/td&gt;
          &lt;td&gt;One GPU for the 0.6B and 1.7B checkpoints; more GPUs means more concurrent streams&lt;/td&gt;
          &lt;td&gt;Low; CPU viable&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Cold start&lt;/td&gt;
          &lt;td&gt;Keep-warm or pay latency&lt;/td&gt;
          &lt;td&gt;Usually friendly to autoscale&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Voice control&lt;/td&gt;
          &lt;td&gt;Richer style/locale knobs&lt;/td&gt;
          &lt;td&gt;Smaller roster&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Upgrade risk&lt;/td&gt;
          &lt;td&gt;Large checkpoint swaps&lt;/td&gt;
          &lt;td&gt;Smaller binary swaps&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;Reproducibility:&lt;/strong&gt; pin &lt;strong&gt;checkpoint&lt;/strong&gt;, &lt;strong&gt;speaker/style tokens&lt;/strong&gt;, &lt;strong&gt;sample rate&lt;/strong&gt;, and &lt;strong&gt;inference framework commit&lt;/strong&gt; the same way &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-mistral-huggingface-lora-training-notes/&#34;&gt;Fine-Tuning a Mistral-Class Checkpoint with LoRA on Hugging Face&lt;/a&gt; pins LLM Hub revisions.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Choose &lt;strong&gt;heavy TTS&lt;/strong&gt; when quality and multilingual breadth dominate unit economics; choose &lt;strong&gt;light TTS&lt;/strong&gt; when cost per minute and footprint dominate. For an optional &lt;strong&gt;RVC&lt;/strong&gt; second stage aimed at timbre control, see &lt;a href=&#34;https://blog.veydh.com/2026/2026-04-rvc-voice-conversion-architecture/&#34;&gt;RVC in the Stack: Voice Conversion After TTS&lt;/a&gt;.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>RVC in the Stack: Voice Conversion After TTS</title>
      <link>https://blog.veydh.com/2026/2026-04-rvc-voice-conversion-architecture/</link>
      <pubDate>Sat, 04 Apr 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-04-rvc-voice-conversion-architecture/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Retrieval-based Voice Conversion (RVC)&lt;/strong&gt; maps &lt;strong&gt;audio&lt;/strong&gt; from one timbre toward another using models trained on &lt;strong&gt;target-speaker&lt;/strong&gt; data. It is not a text front-end: it consumes waveforms. That is why the common assistant pattern chains &lt;strong&gt;TTS → RVC&lt;/strong&gt; when you want machine-generated speech to resemble a &lt;strong&gt;specific&lt;/strong&gt; voice embedding learned from clean clips.&lt;/p&gt;
&lt;p&gt;This is separate from “pick speaker ID 3 in the TTS API.” RVC is about &lt;strong&gt;conversion&lt;/strong&gt;, not selecting a bundled persona—though the two blur in product marketing.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;reference-architecture&#34;&gt;Reference architecture&lt;/h2&gt;
&lt;p&gt;The TTS-first pipeline:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Text → TTS engine (neutral or roster speaker) → waveform → RVC → output audio&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Each hop adds &lt;strong&gt;latency&lt;/strong&gt; and a &lt;strong&gt;failure domain&lt;/strong&gt;. TTS prosody mistakes propagate; RVC adjusts timbre but cannot always rewrite cadence or emotion wholesale.&lt;/p&gt;
&lt;p&gt;An alternate path is &lt;strong&gt;human speech → RVC&lt;/strong&gt; for dubbing, anonymization, or creative workflows. Consent and contract terms differ sharply from synthetic pipelines; governance checklists should not be reused blindly across those use cases.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;why-add-rvc-at-all&#34;&gt;Why add RVC at all&lt;/h2&gt;
&lt;p&gt;When branding demands a &lt;strong&gt;recognizable&lt;/strong&gt; voice and the base TTS cannot reproduce it natively, RVC offers a &lt;strong&gt;reskin&lt;/strong&gt; without retraining the entire synthesis stack. You can also swap TTS backends while retaining a stable timbre layer—if ops accepts the extra GPU work.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;costs-and-risks&#34;&gt;Costs and risks&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Cascaded errors&lt;/strong&gt; are the engineering tax: two models mean two places to tune, monitor, and version.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Extra latency&lt;/strong&gt; per second of audio matters for interactive assistants; batch offline jobs tolerate it more easily.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Data ethics&lt;/strong&gt; are non-negotiable. Train only on speakers who &lt;strong&gt;consented&lt;/strong&gt;; treat unauthorized cloning as an abuse incident, not a support ticket. &lt;strong&gt;Deepfakes&lt;/strong&gt; carry legal exposure; product, legal, and security should sign the same threat model.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;operations&#34;&gt;Operations&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;RVC model revision&lt;/strong&gt;, &lt;strong&gt;voice profile ID&lt;/strong&gt;, and linkage back to &lt;strong&gt;TTS engine version&lt;/strong&gt; should be logged—the same audit trail mindset as logging embedder IDs in RAG. Without that, debugging “she sounded different last Tuesday” is guesswork.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;step-by-step-train-and-convert-engineering-outline&#34;&gt;Step-by-step: train-and-convert (engineering outline)&lt;/h2&gt;
&lt;p&gt;Training recipes change with upstream repos; the &lt;strong&gt;invariants&lt;/strong&gt; to enforce are:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Consent artifact&lt;/strong&gt; — Written permission + scope (commercial, regions, duration) stored beside the dataset hash.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Clean reference clips&lt;/strong&gt; — Denoise, strip silence, single speaker; 10–30 minutes often beats hours of noisy data.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Feature extract&lt;/strong&gt; — Use the RVC toolchain’s pinned &lt;strong&gt;content encoder&lt;/strong&gt; (often HuBERT-based); record its revision.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Train&lt;/strong&gt; — Fixed seed, fixed batch, validation loss curve saved; no “best guess” checkpoint without eval listening.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Export&lt;/strong&gt; — Versioned &lt;code&gt;.pth&lt;/code&gt; / ONNX / whatever the inference server loads; &lt;strong&gt;never&lt;/strong&gt; overwrite in place.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Inference test&lt;/strong&gt; — &lt;code&gt;TTS(reference_speaker) → RVC(target)&lt;/code&gt; on held-out text; compare to golden wavs.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Latency math:&lt;/strong&gt; &lt;code&gt;T_tts + T_rvc + buffering&lt;/code&gt; must fit your assistant turn budget; profile with &lt;strong&gt;batch size = 1&lt;/strong&gt; first.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;when-not-to-use-rvc&#34;&gt;When &lt;strong&gt;not&lt;/strong&gt; to use RVC&lt;/h2&gt;
&lt;p&gt;Skip the second stage when &lt;strong&gt;native multispeaker TTS&lt;/strong&gt; already matches brand needs, or when &lt;strong&gt;extra GPU + governance&lt;/strong&gt; cannot be justified. RVC shines when &lt;strong&gt;timbre&lt;/strong&gt; is non-negotiable and &lt;strong&gt;base TTS&lt;/strong&gt; is fungible.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;RVC is a &lt;strong&gt;power tool&lt;/strong&gt; with &lt;strong&gt;policy weight&lt;/strong&gt;: it changes timbre, it does not create consent, and it does not repair a weak TTS. Since January 2026, &lt;a href=&#34;https://blog.veydh.com/2026/2026-04-qwen3-tts-and-multilingual-neural-tts/&#34;&gt;Qwen3-TTS and Multilingual Neural TTS Trade-offs&lt;/a&gt;’s Base checkpoints can clone a voice from a few seconds of reference audio, so this second stage is optional when that clone is good enough. When you keep RVC, version the converter beside the TTS engine, and treat unauthorized cloning as an incident.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Whisper in the Loop: ASR, Not TTS</title>
      <link>https://blog.veydh.com/2026/2026-04-whisper-in-the-speech-stack-asr/</link>
      <pubDate>Sat, 04 Apr 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-04-whisper-in-the-speech-stack-asr/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Whisper&lt;/strong&gt; is &lt;strong&gt;automatic speech recognition&lt;/strong&gt;: audio in, text out. Listing it next to Kokoro and Qwen3-TTS still makes sense because voice products need &lt;strong&gt;both&lt;/strong&gt; directions. The failure mode to watch for is teams treating Whisper like a speech &lt;em&gt;generator&lt;/em&gt; or expecting TTS to “listen.” Naming the loop clearly saves weeks of misfired tickets.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;strengths-to-lean-on&#34;&gt;Strengths to lean on&lt;/h2&gt;
&lt;p&gt;Whisper-class models are a strong &lt;strong&gt;open baseline&lt;/strong&gt; for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Captions&lt;/strong&gt; and meeting notes when privacy policy allows cloud or self-hosted inference.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Voice commands&lt;/strong&gt; where vocabulary is broad and accents vary.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;RAG ingestion&lt;/strong&gt; over spoken content: transcribe audio, chunk text, embed—&lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/&#34;&gt;RAG Foundations: Embeddings, Chunking, and the Retrieval Loop&lt;/a&gt;’s loop with a microphone upstream.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The robustness across noise and accents is why Whisper became the default mental model for ASR in many stacks. As of late 2026 it is a &lt;strong&gt;baseline&lt;/strong&gt;, not the English accuracy or speed leader. NVIDIA’s Canary-Qwen and Parakeet model cards claim stronger English or European-language numbers, and &lt;code&gt;large-v3-turbo&lt;/code&gt; (4 decoder layers instead of 32) is the practical Whisper when latency matters more than the full decoder. The loop below does not change if you swap the recognizer. Pin whichever checkpoint you actually run.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;costs-and-real-time-constraints&#34;&gt;Costs and real-time constraints&lt;/h2&gt;
&lt;p&gt;Larger tiers improve accuracy and robustness; they also raise &lt;strong&gt;latency&lt;/strong&gt; and &lt;strong&gt;compute&lt;/strong&gt;. Real-time use often means &lt;strong&gt;chunked&lt;/strong&gt; inference, voice activity detection (&lt;strong&gt;VAD&lt;/strong&gt;) to skip silence, or smaller distilled ASR models when Whisper is overkill.&lt;/p&gt;
&lt;p&gt;Hardware is sized the same way as LLM serving: expected concurrency, SLO for end-to-end voice turns, and batching strategy.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;failure-modes-hallucinations-and-music&#34;&gt;Failure modes: hallucinations and music&lt;/h2&gt;
&lt;p&gt;ASR models can emit plausible text in &lt;strong&gt;silent&lt;/strong&gt; segments or under &lt;strong&gt;music&lt;/strong&gt;—classic hallucination territory. Mitigations include VAD, confidence heuristics, and post-filters that reject empty-audio transcripts. None are perfect; residual risk should be documented for product and legal review.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;architecture-placement&#34;&gt;Architecture placement&lt;/h2&gt;
&lt;p&gt;For assistants, Whisper belongs &lt;strong&gt;before&lt;/strong&gt; the LLM:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;microphone → ASR → text → (RAG + LLM) → text → TTS → speaker&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;That ordering keeps responsibilities clean. &lt;a href=&#34;https://blog.veydh.com/2026/2026-04-qwen3-tts-and-multilingual-neural-tts/&#34;&gt;Qwen3-TTS and Multilingual Neural TTS Trade-offs&lt;/a&gt; focuses on &lt;strong&gt;neural TTS&lt;/strong&gt; output quality; &lt;a href=&#34;https://blog.veydh.com/2026/2026-04-rvc-voice-conversion-architecture/&#34;&gt;RVC in the Stack: Voice Conversion After TTS&lt;/a&gt; adds &lt;strong&gt;RVC&lt;/strong&gt; when the output timbre must match a specific speaker profile.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;step-by-step-batch-transcription-you-can-regression-test&#34;&gt;Step-by-step: batch transcription you can regression-test&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Pin model&lt;/strong&gt; — &lt;code&gt;large-v3&lt;/code&gt; vs &lt;code&gt;medium&lt;/code&gt; is a product choice; record &lt;strong&gt;checkpoint file hash&lt;/strong&gt; or &lt;code&gt;faster-whisper&lt;/code&gt; wheel version.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Normalize audio&lt;/strong&gt; — Resample to what the model expects (often 16 kHz mono); store &lt;strong&gt;ffmpeg&lt;/strong&gt; command lines in the ADR.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Chunk long files&lt;/strong&gt; — VAD-based segments (silero, WebRTC VAD) reduce hallucinated text in music-only regions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Decode&lt;/strong&gt; — &lt;code&gt;faster-whisper&lt;/code&gt; or &lt;code&gt;whisper.cpp&lt;/code&gt; with fixed &lt;code&gt;beam_size&lt;/code&gt; / &lt;code&gt;temperature&lt;/code&gt; for reproducibility; log &lt;strong&gt;language&lt;/strong&gt; explicitly or force &lt;code&gt;language=&amp;quot;en&amp;quot;&lt;/code&gt; when appropriate.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Post-filter&lt;/strong&gt; — Drop segments with &lt;strong&gt;no speech&lt;/strong&gt; per VAD; optionally cap &lt;strong&gt;max segment duration&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;CLI-shaped reproducible run&lt;/strong&gt; (&lt;code&gt;faster-whisper&lt;/code&gt; example):&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-bash&#34; data-lang=&#34;bash&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;python - &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;lt;&amp;lt;&amp;#39;PY&amp;#39;
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;from faster_whisper import WhisperModel
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;model = WhisperModel(&amp;#34;large-v3&amp;#34;, device=&amp;#34;cuda&amp;#34;, compute_type=&amp;#34;float16&amp;#34;)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;segments, info = model.transcribe(&amp;#34;sample.wav&amp;#34;, beam_size=5, vad_filter=True)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;print(&amp;#34;lang&amp;#34;, info.language, &amp;#34;prob&amp;#34;, info.language_probability)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;for s in segments:
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;    print(f&amp;#34;[{s.start:.2f}-{s.end:.2f}] {s.text}&amp;#34;)
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;PY&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;Pros:&lt;/strong&gt; excellent out-of-the-box WER on diverse accents; &lt;strong&gt;Cons:&lt;/strong&gt; GPU memory and latency for &lt;code&gt;large-*&lt;/code&gt;; hallucinations under silence/music unless VAD + policy.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;feeding-rag-from-audio-retrieval-loop--microphone-upstream&#34;&gt;Feeding RAG from audio (retrieval loop + microphone upstream)&lt;/h2&gt;
&lt;p&gt;After ASR, the pipeline is plain text: &lt;strong&gt;transcript → chunk → embed → index&lt;/strong&gt; (same shape as &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/&#34;&gt;RAG Foundations: Embeddings, Chunking, and the Retrieval Loop&lt;/a&gt;). Record &lt;strong&gt;ASR model id&lt;/strong&gt; as metadata on derived chunks so you can re-index when ASR improves. Do &lt;strong&gt;not&lt;/strong&gt; embed raw audio in a text embedder without a dedicated multimodal model—that is a different architecture.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Whisper is the &lt;strong&gt;ears&lt;/strong&gt; of the stack, not the &lt;strong&gt;mouth&lt;/strong&gt;. Treating ASR and TTS symmetrically at the API layer—timeouts, quotas, logging—makes the full voice pipeline operable.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Kokoro TTS: Lightweight Neural Speech and Where It Fits</title>
      <link>https://blog.veydh.com/2026/2026-03-kokoro-tts-lightweight-synthesis/</link>
      <pubDate>Wed, 04 Mar 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-03-kokoro-tts-lightweight-synthesis/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;Text-to-speech sits at the far end of the assistant pipeline: the LLM (and maybe RAG) decides &lt;em&gt;what&lt;/em&gt; to say; &lt;strong&gt;TTS&lt;/strong&gt; turns that text into audio users actually hear. &lt;strong&gt;Kokoro&lt;/strong&gt;-class engines target &lt;strong&gt;efficiency&lt;/strong&gt;—fast cold start, modest RAM, and throughput that fits small VMs or edge devices. Exact checkpoints and revisions evolve; the &lt;strong&gt;design trade-off&lt;/strong&gt; to anchor is footprint versus expressiveness.&lt;/p&gt;
&lt;p&gt;The checkpoint this post means is &lt;strong&gt;Kokoro-82M&lt;/strong&gt; (&lt;code&gt;hexgrad/Kokoro-82M&lt;/code&gt;, v1.0, January 2025): about &lt;strong&gt;82 million&lt;/strong&gt; parameters, a StyleTTS 2 stack with an ISTFTNet decoder, &lt;strong&gt;24 kHz&lt;/strong&gt; audio, &lt;strong&gt;Apache-2.0&lt;/strong&gt;, &lt;strong&gt;8 languages&lt;/strong&gt;, and &lt;strong&gt;54&lt;/strong&gt; bundled voices. It does not clone an arbitrary speaker from a short sample. Pin the weight hash if you ship it.&lt;/p&gt;
&lt;p&gt;This post is the lightweight leg of the 2026 speech arc; &lt;a href=&#34;https://blog.veydh.com/2026/2026-04-qwen3-tts-and-multilingual-neural-tts/&#34;&gt;Qwen3-TTS and Multilingual Neural TTS Trade-offs&lt;/a&gt; contrasts it with heavier multilingual stacks; &lt;a href=&#34;https://blog.veydh.com/2026/2026-04-rvc-voice-conversion-architecture/&#34;&gt;RVC in the Stack: Voice Conversion After TTS&lt;/a&gt; adds &lt;strong&gt;RVC&lt;/strong&gt; when timbre cloning enters the picture.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;where-lightweight-tts-wins&#34;&gt;Where lightweight TTS wins&lt;/h2&gt;
&lt;p&gt;Smaller neural TTS fits when:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Cost per minute&lt;/strong&gt; dominates—IVR prompts, notification speech, or high-volume read-aloud.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Provisioning&lt;/strong&gt; is tight—no room for multi-gigabyte multispeaker servers on every node.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Latency&lt;/strong&gt; budgets are aggressive and the script is short.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In those regimes, “good enough” prosody beats “stunning but slow.” Users forgive a slightly flat delivery on a parking confirmation more than they forgive a three-second wait.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;trade-offs-to-expect-up-front&#34;&gt;Trade-offs to expect up front&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Prosody and emotional range&lt;/strong&gt; rarely match the largest commercial or open giants. You get clarity and speed; you may not get nuanced acting.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Voice roster&lt;/strong&gt; may be limited to bundled speakers. If marketing demands a &lt;strong&gt;specific&lt;/strong&gt; timbre, you either fine-tune within the engine’s constraints or add a &lt;strong&gt;second stage&lt;/strong&gt;—see &lt;a href=&#34;https://blog.veydh.com/2026/2026-04-rvc-voice-conversion-architecture/&#34;&gt;RVC in the Stack: Voice Conversion After TTS&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Language coverage&lt;/strong&gt; varies by checkpoint. Every claimed locale should be validated; multilingual tokenization issues are not unique to LLMs.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;integration-beside-the-llm-layer&#34;&gt;Integration beside the LLM layer&lt;/h2&gt;
&lt;p&gt;TTS belongs &lt;strong&gt;behind the same API discipline&lt;/strong&gt; as &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/&#34;&gt;Serving Small Models Behind an HTTP API&lt;/a&gt;’s chat surface: timeouts, quotas, and structured errors when synthesis fails mid-utterance. Streaming audio raises questions of chunking and buffering; clients should handle partial playback and cancellation when the user interrupts.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;relation-to-the-rest-of-the-stack&#34;&gt;Relation to the rest of the stack&lt;/h2&gt;
&lt;p&gt;&lt;a href=&#34;https://blog.veydh.com/2026/2026-04-whisper-in-the-speech-stack-asr/&#34;&gt;Whisper in the Loop: ASR, Not TTS&lt;/a&gt; covers &lt;strong&gt;Whisper&lt;/strong&gt; on the &lt;strong&gt;listening&lt;/strong&gt; side (ASR). The mental model is directional: &lt;strong&gt;Whisper → text → LLM/RAG → text → TTS → audio&lt;/strong&gt;. Mixing ASR and TTS responsibilities is a common beginner confusion; naming the boundary clearly keeps architecture reviews honest.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;reproducible-evaluation-loop-lightweight-tts&#34;&gt;Reproducible evaluation loop (lightweight TTS)&lt;/h2&gt;
&lt;p&gt;Treat TTS like any other model artifact: &lt;strong&gt;pin revision&lt;/strong&gt;, &lt;strong&gt;pin voice&lt;/strong&gt;, &lt;strong&gt;record sample rate&lt;/strong&gt;, &lt;strong&gt;store golden waveforms&lt;/strong&gt; for regression.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Freeze the stack&lt;/strong&gt; — Note Python version, package versions, and whether you run ONNX, CPU, or GPU build. One-line smoke: synthesize the same 3 sentences on every deploy.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Measure what product cares about&lt;/strong&gt; — &lt;strong&gt;RTF&lt;/strong&gt; (real-time factor) = audio_duration / wall_time; &lt;strong&gt;cold start&lt;/strong&gt; ms until first byte; &lt;strong&gt;RSS&lt;/strong&gt; at steady state for N concurrent streams.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ABX or MOS-lite&lt;/strong&gt; — For internal QA, maintain a spreadsheet of &lt;code&gt;{text, reference_wav}&lt;/code&gt; pairs; reviewers rate naturalness 1–5. Cheap, catches prosody regressions automated metrics miss.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Illustrative Python call pattern&lt;/strong&gt; (replace with the actual Kokoro / edge engine API you standardize on—the shape stays the same):&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# Pseudocode shape: engine.load(voice_id, revision=REV)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# audio = engine.synthesize(text, sample_rate=24000)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# Path(&amp;#34;golden/hello.wav&amp;#34;).write_bytes(audio.to_wav())&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Log &lt;code&gt;voice_id&lt;/code&gt;, &lt;code&gt;engine_revision&lt;/code&gt;, and &lt;code&gt;sample_rate&lt;/code&gt; beside the &lt;code&gt;request_id&lt;/code&gt; discipline from &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/&#34;&gt;Serving Small Models Behind an HTTP API&lt;/a&gt; so ops can answer “what spoke this?”&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;tool-comparison-same-text-in-audio-out&#34;&gt;Tool comparison (same text in, audio out)&lt;/h2&gt;
&lt;table&gt;
  &lt;thead&gt;
      &lt;tr&gt;
          &lt;th&gt;Option&lt;/th&gt;
          &lt;th&gt;Footprint&lt;/th&gt;
          &lt;th&gt;Quality headroom&lt;/th&gt;
          &lt;th&gt;Ops note&lt;/th&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr&gt;
          &lt;td&gt;Lightweight neural TTS (Kokoro-class)&lt;/td&gt;
          &lt;td&gt;Low RAM/CPU&lt;/td&gt;
          &lt;td&gt;Moderate prosody&lt;/td&gt;
          &lt;td&gt;Best for alerts/IVR-scale volume&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Cloud vendor TTS&lt;/td&gt;
          &lt;td&gt;Zero local GPU&lt;/td&gt;
          &lt;td&gt;High&lt;/td&gt;
          &lt;td&gt;Contract + egress + voice licensing&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Heavy open multilingual (&lt;a href=&#34;https://blog.veydh.com/2026/2026-04-qwen3-tts-and-multilingual-neural-tts/&#34;&gt;Qwen3-TTS and Multilingual Neural TTS Trade-offs&lt;/a&gt;)&lt;/td&gt;
          &lt;td&gt;High GPU&lt;/td&gt;
          &lt;td&gt;High&lt;/td&gt;
          &lt;td&gt;Fleet planning + checkpoint compliance&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Kokoro-tier TTS is a &lt;strong&gt;practical default&lt;/strong&gt; when efficiency matters more than maximal expressiveness. &lt;a href=&#34;https://blog.veydh.com/2026/2026-04-qwen3-tts-and-multilingual-neural-tts/&#34;&gt;Qwen3-TTS and Multilingual Neural TTS Trade-offs&lt;/a&gt; compares &lt;strong&gt;Qwen3-TTS&lt;/strong&gt;-class heavy stacks when quality and control win the negotiation.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Token Budgets: Enforcing Limits at the API Layer</title>
      <link>https://blog.veydh.com/2026/2026-03-token-limits-budgets-and-truncation/</link>
      <pubDate>Wed, 04 Mar 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-03-token-limits-budgets-and-truncation/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;Uncapped generation is how you burn &lt;strong&gt;VRAM&lt;/strong&gt;, &lt;strong&gt;money&lt;/strong&gt;, and &lt;strong&gt;user patience&lt;/strong&gt; in a single request. Limits belong in &lt;strong&gt;middleware&lt;/strong&gt;—before the GPU does heavy work—not as a vague suggestion in the front-end. Token budgets are &lt;strong&gt;policy&lt;/strong&gt;: product, security, and finance get a say; engineering implements them deterministically.&lt;/p&gt;
&lt;p&gt;This pairs directly with &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/&#34;&gt;Serving Small Models Behind an HTTP API&lt;/a&gt;’s serving layer and with &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/&#34;&gt;RAG Foundations: Embeddings, Chunking, and the Retrieval Loop&lt;/a&gt;’s RAG context stuffing: the same window is contested by system prompts, retrieved chunks, tool outputs, and the user’s message history.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;hard-caps-max_tokens-and-friends&#34;&gt;Hard caps: &lt;code&gt;max_tokens&lt;/code&gt; and friends&lt;/h2&gt;
&lt;p&gt;Server-side &lt;strong&gt;&lt;code&gt;max_new_tokens&lt;/code&gt;&lt;/strong&gt; (or API &lt;code&gt;max_tokens&lt;/code&gt;, depending on the stack) is the simplest brake: stop after N new tokens regardless of whether the model “feels done.” Defaults should be sane per tier, with higher quotas for authenticated power users where appropriate.&lt;/p&gt;
&lt;p&gt;The important detail is &lt;strong&gt;consistent semantics&lt;/strong&gt; across streaming and non-streaming paths. Partial streams must surface a &lt;strong&gt;stop reason&lt;/strong&gt; so clients know the answer was truncated by length, not completed naturally.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;pre-flight-token-counting&#34;&gt;Pre-flight token counting&lt;/h2&gt;
&lt;p&gt;Rejecting oversize prompts &lt;strong&gt;before&lt;/strong&gt; allocation saves money. Token counts should use the same tokenizer family the model uses—approximations from rough character heuristics drift and cause surprise denials.&lt;/p&gt;
&lt;p&gt;When a prompt is too large, responses should be &lt;strong&gt;actionable&lt;/strong&gt;: which limit tripped, whether retry is possible after truncation, and never a generic 500 when the fix is user-side editing.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;truncation-strategies-for-long-threads&#34;&gt;Truncation strategies for long threads&lt;/h2&gt;
&lt;p&gt;For chat history, naive “keep the last K messages” drops important early instructions. Alternatives to mix and match:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Drop middle&lt;/strong&gt;: keep system/developer instructions and recent turns; summarize or elide the middle.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Summarize&lt;/strong&gt;: periodically roll older turns into a running summary (watch for summary drift and stale facts).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Retrieve instead of paste&lt;/strong&gt;: RAG pulls fresh chunks rather than embedding entire old threads in the prompt.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Each strategy has failure modes; the right choice depends on whether the product is &lt;strong&gt;support&lt;/strong&gt; (needs ticket context) or &lt;strong&gt;creative&lt;/strong&gt; (needs recent style).&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;streaming-and-client-contracts&#34;&gt;Streaming and client contracts&lt;/h2&gt;
&lt;p&gt;With &lt;strong&gt;SSE&lt;/strong&gt; or chunked responses, clients must handle incremental tokens, &lt;strong&gt;finish reasons&lt;/strong&gt;, and errors mid-stream. Whether partial JSON tool calls can arrive and how to recover should be documented—same care as any long-lived HTTP stream.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;observability-and-fairness&#34;&gt;Observability and fairness&lt;/h2&gt;
&lt;p&gt;Histograms for &lt;strong&gt;prompt length&lt;/strong&gt;, &lt;strong&gt;output length&lt;/strong&gt;, and &lt;strong&gt;time-to-first-token&lt;/strong&gt; expose abusive patterns and misconfigured clients before finance does. Per-tenant &lt;strong&gt;quotas&lt;/strong&gt; pair with these metrics so one noisy integration does not starve the rest.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;implementation-sketch-pre-flight-with-the-models-own-tokenizer&#34;&gt;Implementation sketch: pre-flight with the model’s own tokenizer&lt;/h2&gt;
&lt;p&gt;Use the &lt;strong&gt;same tokenizer&lt;/strong&gt; the model uses. &lt;code&gt;tiktoken&lt;/code&gt; counts OpenAI tokenizers and will mis-count Mistral, Qwen, and Llama. A &lt;code&gt;len(text)//4&lt;/code&gt; heuristic drifts the same way.&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; transformers &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; AutoTokenizer
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;tok &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; AutoTokenizer&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;from_pretrained(MODEL_ID, revision&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;MODEL_REV)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;count_messages&lt;/span&gt;(messages) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; int:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#75715e&#34;&gt;# Prefer the model&amp;#39;s chat template when available&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; len(tok&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;apply_chat_template(messages, tokenize&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;True&lt;/span&gt;, add_generation_prompt&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;True&lt;/span&gt;))
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;assert_within_budget&lt;/span&gt;(messages, max_prompt_tokens: int) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;None&lt;/span&gt;:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    n &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; count_messages(messages)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; n &lt;span style=&#34;color:#f92672&#34;&gt;&amp;gt;&lt;/span&gt; max_prompt_tokens:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;raise&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;ValueError&lt;/span&gt;(&lt;span style=&#34;color:#e6db74&#34;&gt;f&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;prompt_tokens=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;{&lt;/span&gt;n&lt;span style=&#34;color:#e6db74&#34;&gt;}&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt; exceeds max_prompt_tokens=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;{&lt;/span&gt;max_prompt_tokens&lt;span style=&#34;color:#e6db74&#34;&gt;}&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;In &lt;strong&gt;middleware&lt;/strong&gt;, return &lt;strong&gt;HTTP 413&lt;/strong&gt; or &lt;strong&gt;400&lt;/strong&gt; with a JSON body &lt;code&gt;{ &amp;quot;error&amp;quot;: &amp;quot;context_length&amp;quot;, &amp;quot;prompt_tokens&amp;quot;: n, &amp;quot;limit&amp;quot;: max_prompt_tokens }&lt;/code&gt; so clients know to truncate or summarize—mirroring how public APIs surface limits.&lt;/p&gt;
&lt;p&gt;For &lt;strong&gt;RAG&lt;/strong&gt;, count tokens &lt;strong&gt;after&lt;/strong&gt; you assemble system + retrieved passages + user message; if over budget, drop lowest-scoring chunks first (&lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-operations-re-ranking-and-evaluation/&#34;&gt;RAG in Production: Re-ranking, HyDE, and Simple Evals&lt;/a&gt;’s reranker makes that ordering meaningful).&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;reproducible-truncation-regression-test&#34;&gt;Reproducible truncation regression test&lt;/h2&gt;
&lt;p&gt;Keep a &lt;strong&gt;fixture&lt;/strong&gt; of long threads in &lt;code&gt;tests/fixtures/long_chat.json&lt;/code&gt;. After any change to truncation or summarization:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Token-count before/after.&lt;/li&gt;
&lt;li&gt;Golden hash of the &lt;strong&gt;exact&lt;/strong&gt; byte sequence sent to the model (or the list of chunk ids injected for RAG).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;CI fails when the fixture’s effective context changes without a version bump—same instinct as index versioning in &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/&#34;&gt;RAG Foundations: Embeddings, Chunking, and the Retrieval Loop&lt;/a&gt;.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Fine-Tuning a Mistral-Class Checkpoint with LoRA on Hugging Face</title>
      <link>https://blog.veydh.com/2026/2026-02-mistral-huggingface-lora-training-notes/</link>
      <pubDate>Fri, 13 Feb 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-02-mistral-huggingface-lora-training-notes/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Mistral&lt;/strong&gt;-family checkpoints are common bases for assistants: strong quality per dollar, good tooling, and a large community of derivative models. &lt;code&gt;Mistral-7B-Instruct-v0.3&lt;/code&gt; is an instruct-tuned 7B, not a distilled student. Pulling weights from the Hub is only the first step. Training &lt;strong&gt;without&lt;/strong&gt; the model’s official &lt;strong&gt;chat template&lt;/strong&gt;—or mixing tokenizer specials inconsistently—is how you get sparkling loss curves and broken inference.&lt;/p&gt;
&lt;p&gt;The snippets below assume &lt;strong&gt;PyTorch + Transformers + PEFT&lt;/strong&gt;; translate the same invariants to your runner of choice.&lt;/p&gt;
&lt;p&gt;This post is a checklist to run before any serious LoRA SFT job on Mistral-class bases. It mirrors the dependency-pinning mindset from earlier DevOps writing: reproducibility beats heroics.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;pin-the-checkpoint-not-just-the-name&#34;&gt;Pin the checkpoint, not just the name&lt;/h2&gt;
&lt;p&gt;Hub models move. &lt;strong&gt;&lt;code&gt;revision&lt;/code&gt;&lt;/strong&gt; should be pinned to a commit hash for training &lt;em&gt;and&lt;/em&gt; for inference. The same applies to tokenizer files bundled with that revision. “Latest” is fine for a weekend experiment; it is a liability when you need to diff a regression three weeks later.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;chat-templates-and-special-tokens&#34;&gt;Chat templates and special tokens&lt;/h2&gt;
&lt;p&gt;Instruction-tuned models expect &lt;strong&gt;BOS/EOS&lt;/strong&gt; and role markers in a specific layout. Training on raw concatenated strings—user and assistant blobs jammed together without structure—teaches the adapter the wrong conditional distribution.&lt;/p&gt;
&lt;p&gt;Always:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Load &lt;code&gt;tokenizer&lt;/code&gt; from the same revision as &lt;code&gt;model&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Apply the model card’s recommended &lt;strong&gt;chat template&lt;/strong&gt; (or &lt;code&gt;tokenizer.apply_chat_template&lt;/code&gt; when available) to build training examples.&lt;/li&gt;
&lt;li&gt;Mask labels so loss applies only to &lt;strong&gt;assistant&lt;/strong&gt; tokens when that is the objective; masking prevents the model from learning to imitate user prefixes.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If any of those steps feel optional, revisit &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/&#34;&gt;RAG Foundations: Embeddings, Chunking, and the Retrieval Loop&lt;/a&gt;: garbage structure upstream becomes garbage behavior downstream.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;memory-precision-and-sequence-length&#34;&gt;Memory, precision, and sequence length&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Gradient checkpointing&lt;/strong&gt; trades compute for activation memory; on long contexts it is often mandatory. &lt;strong&gt;bf16&lt;/strong&gt; is used when hardware supports it well; &lt;strong&gt;fp16&lt;/strong&gt; can work but needs watching for overflow. &lt;strong&gt;OOM&lt;/strong&gt; during the first real batch is a signal to shorten sequences, reduce micro-batch, or enable ZeRO-style sharding—not to immediately give up on LoRA.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;saving-and-merging-adapters&#34;&gt;Saving and merging adapters&lt;/h2&gt;
&lt;p&gt;During iteration, &lt;strong&gt;adapter weights only&lt;/strong&gt; are saved—small, easy to diff and A/B swap. &lt;strong&gt;Merging&lt;/strong&gt; adapters into a full weight file is useful for some deployment paths (single artifact, certain runtimes); it complicates updates because every merge is a new binary. Which path production uses should be documented so nobody confuses “adapter v3” with “merged full model v3”.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;documentation-alongside-the-weights&#34;&gt;Documentation alongside the weights&lt;/h2&gt;
&lt;p&gt;An &lt;strong&gt;ADR-style&lt;/strong&gt; note (even a short Markdown file in the repo) should record Hub IDs, dataset hashes, seeds, learning rate schedule, and eval commands. That is the same habit as recording Docker base images and lockfiles: future you is also a teammate.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;end-to-end-recipe-sft-on-jsonl-chat-rows&#34;&gt;End-to-end recipe (SFT on JSONL chat rows)&lt;/h2&gt;
&lt;p&gt;Assume each training row is &lt;code&gt;{&amp;quot;messages&amp;quot;: [{&amp;quot;role&amp;quot;:&amp;quot;system&amp;quot;,&amp;quot;content&amp;quot;:...}, {&amp;quot;role&amp;quot;:&amp;quot;user&amp;quot;,...}, {&amp;quot;role&amp;quot;:&amp;quot;assistant&amp;quot;,...}]}&lt;/code&gt; — one assistant turn per example for simplicity.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1 — Load pinned revision&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; torch
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; transformers &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; AutoModelForCausalLM, AutoTokenizer
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;MODEL_ID &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;mistralai/Mistral-7B-Instruct-v0.3&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;REV &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;abc123deadbeef...&amp;#34;&lt;/span&gt;  &lt;span style=&#34;color:#75715e&#34;&gt;# Hub commit sha&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;tokenizer &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; AutoTokenizer&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;from_pretrained(MODEL_ID, revision&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;REV)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;model &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; AutoModelForCausalLM&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;from_pretrained(
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    MODEL_ID, revision&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;REV, torch_dtype&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;torch&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;bfloat16
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;model&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;config&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;use_cache &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;False&lt;/span&gt;  &lt;span style=&#34;color:#75715e&#34;&gt;# required once gradient checkpointing is on&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;Step 2 — Apply chat template and mask user/system tokens&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Use &lt;code&gt;tokenizer.apply_chat_template&lt;/code&gt; with &lt;code&gt;return_dict=True&lt;/code&gt; and token masks, or build labels manually: set &lt;code&gt;labels[i] = -100&lt;/code&gt; for tokens that belong to system + user prefixes so &lt;strong&gt;only assistant tokens contribute loss&lt;/strong&gt;. Skipping this is how you get a model that parrots the user channel.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 3 — Attach LoRA and train&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Match &lt;code&gt;target_modules&lt;/code&gt; to Mistral’s linear names (&lt;code&gt;q_proj&lt;/code&gt;, &lt;code&gt;k_proj&lt;/code&gt;, &lt;code&gt;v_proj&lt;/code&gt;, &lt;code&gt;o_proj&lt;/code&gt; are the usual set). Watch &lt;strong&gt;train loss&lt;/strong&gt; &lt;em&gt;and&lt;/em&gt; a small &lt;strong&gt;held-out generation&lt;/strong&gt; set weekly—loss can fall while JSON/tool format falls apart.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 4 — Save adapter + manifest&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-text&#34; data-lang=&#34;text&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;lora-out/
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  adapter_config.json
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  adapter_model.safetensors
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;manifest.json   # { &amp;#34;base&amp;#34;: MODEL_ID, &amp;#34;revision&amp;#34;: REV, &amp;#34;dataset_sha256&amp;#34;: &amp;#34;...&amp;#34;, &amp;#34;seed&amp;#34;: 42 }
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;Step 5 — Inference smoke test&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Load base + adapter, run the same &lt;code&gt;apply_chat_template&lt;/code&gt; path used in training, and compare against a &lt;strong&gt;golden&lt;/strong&gt; transcript file in CI if possible.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;cli-alternative-trl--axolotl--llama-factory&#34;&gt;CLI alternative: &lt;code&gt;trl&lt;/code&gt; / Axolotl / LLaMA-Factory&lt;/h2&gt;
&lt;p&gt;Higher-level runners (&lt;code&gt;trl&lt;/code&gt; SFT, Axolotl, LLaMA-Factory YAMLs) encode the same steps: dataset → template → masked labels → PEFT. &lt;strong&gt;Pros:&lt;/strong&gt; less boilerplate, proven configs on Discord. &lt;strong&gt;Cons:&lt;/strong&gt; another layer to debug when templates change between library versions—still pin the &lt;strong&gt;library version&lt;/strong&gt; and export the rendered tokenization for one row to disk when incidents happen.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Mistral-class fine-tunes are won or lost on &lt;strong&gt;tokenizer fidelity&lt;/strong&gt; and &lt;strong&gt;pinned revisions&lt;/strong&gt;. &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-qwen-and-llama-distills-lora-on-hf/&#34;&gt;Qwen and LLaMA Checkpoints: LoRA Gotchas&lt;/a&gt; extends the same discipline to &lt;strong&gt;Qwen&lt;/strong&gt; and &lt;strong&gt;LLaMA&lt;/strong&gt; derivatives where multilingual vocabs and RoPE extensions add their own footguns.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Qwen and LLaMA Checkpoints: LoRA Gotchas</title>
      <link>https://blog.veydh.com/2026/2026-02-qwen-and-llama-distills-lora-on-hf/</link>
      <pubDate>Thu, 12 Feb 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-02-qwen-and-llama-distills-lora-on-hf/</guid>
      <description>&lt;h2 id=&#34;preamble-plain-english&#34;&gt;Preamble (plain English)&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Hugging Face (HF)&lt;/strong&gt; hosts thousands of model checkpoints. Among them, &lt;strong&gt;Qwen&lt;/strong&gt; and &lt;strong&gt;LLaMA&lt;/strong&gt; families are everywhere: raw bases, chat-tuned “instruct” versions, and &lt;strong&gt;distilled&lt;/strong&gt; smaller models trained to imitate bigger ones for speed.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;LoRA&lt;/strong&gt; (Low-Rank Adaptation) means you do not retrain the whole model—you add a thin trainable “side path” and leave most weights frozen. That is cheap and fast, but the adapter is not a free-floating brain: it is tied to &lt;strong&gt;one specific base checkpoint&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The training recipe from &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-mistral-huggingface-lora-training-notes/&#34;&gt;Fine-Tuning a Mistral-Class Checkpoint with LoRA on Hugging Face&lt;/a&gt; still applies. This post is the “read me before you merge adapters” note: &lt;strong&gt;tokenizer&lt;/strong&gt;, &lt;strong&gt;position encoding (RoPE)&lt;/strong&gt;, &lt;strong&gt;attention layout (GQA)&lt;/strong&gt;, and &lt;strong&gt;licenses&lt;/strong&gt; differ by family. Getting any of those wrong often fails &lt;strong&gt;silently&lt;/strong&gt; (the model runs, but quality drifts or breaks in edge cases).&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;tiny-glossary-terms-that-show-up-in-configs-and-papers&#34;&gt;Tiny glossary (terms that show up in configs and papers)&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Tokenizer&lt;/strong&gt; — The piece that turns raw text into integer &lt;strong&gt;tokens&lt;/strong&gt; the model sees. Different families use different tokenizers; swap the tokenizer and you have effectively changed the “alphabet” the model was trained on.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;RoPE&lt;/strong&gt; — &lt;strong&gt;Rotary Positional Embedding&lt;/strong&gt;. A standard way to tell the model &lt;strong&gt;how far apart tokens are&lt;/strong&gt; in the sequence (position information) without paying the full cost of older absolute-position schemes. “&lt;strong&gt;RoPE scaling&lt;/strong&gt;” tweaks that math so the model can &lt;strong&gt;pretend&lt;/strong&gt; it was trained on longer sequences than it mostly saw—useful for long context, but easy to get wrong between train and serve.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;GQA&lt;/strong&gt; — &lt;strong&gt;Grouped-Query Attention&lt;/strong&gt;. A memory-saving trick: several &lt;strong&gt;query&lt;/strong&gt; heads share the same &lt;strong&gt;key/value&lt;/strong&gt; heads instead of every query head getting its own K/V. Layout differs across checkpoints; mixing configs can break loading or silently change behavior if something maps layers wrong.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;SFT&lt;/strong&gt; — &lt;strong&gt;Supervised Fine-Tuning&lt;/strong&gt;. You show (prompt, desired answer) pairs and train the model to imitate them—typical “instruction tuning.”&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;PEFT&lt;/strong&gt; — &lt;strong&gt;Parameter-Efficient Fine-Tuning&lt;/strong&gt; (e.g. LoRA via the &lt;code&gt;peft&lt;/code&gt; library). You train few parameters; the rest stay frozen.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ADR&lt;/strong&gt; — &lt;strong&gt;Architecture Decision Record&lt;/strong&gt; — a short doc in your repo that says &lt;em&gt;why&lt;/em&gt; you picked a base model and how you pin versions.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id=&#34;qwen-multilingual-tokenization-changes-the-effective-budget&#34;&gt;Qwen: multilingual tokenization changes the effective budget&lt;/h2&gt;
&lt;p&gt;Think of the tokenizer as a &lt;strong&gt;ruler&lt;/strong&gt; that measures text in &lt;strong&gt;tokens&lt;/strong&gt;, not characters. Qwen’s tokenizer is built for &lt;strong&gt;many languages&lt;/strong&gt;. That is great for products that are not English-only; it also changes planning in ways people miss.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Gotcha 1 — Same “length” in characters ≠ same token budget. The direction depends on the tokenizer.&lt;/strong&gt;&lt;br&gt;
A context window is &lt;strong&gt;tokens&lt;/strong&gt;, not letters. Qwen2, Qwen2.5, and Qwen3 use a large vocabulary that is relatively &lt;strong&gt;efficient for Chinese&lt;/strong&gt; and several other languages people actually ship. A Chinese paragraph is often &lt;em&gt;fewer&lt;/em&gt; tokens than the same content in English on Qwen. That is the opposite of Llama- and Mistral-family tokenizers, where CJK and many other scripts inflate. Some scripts are still expensive on Qwen. Tokenize one fixed paragraph in every locale you ship instead of copying an English character budget, or the “non-English always costs more” story, onto this family.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Gotcha 2 — English-only metrics lie.&lt;/strong&gt;&lt;br&gt;
If you only watch loss or accuracy on English dev data, you can ship something that looks fine in dashboards but degrades in other languages. Check &lt;strong&gt;each language you actually ship&lt;/strong&gt;, including formatting quirks (dates, numbers, mixed scripts).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Gotcha 3 — RAG stacks compound the bias.&lt;/strong&gt;&lt;br&gt;
If your chunking, embedders, and eval sets were built English-first, retrieval quality drops where the tokenizer and embeddings were not aligned with real user text. The LoRA cannot fix upstream retrieval that never surfaces the right chunks.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;llama-rope-gqa-and-long-context-bases&#34;&gt;LLaMA: RoPE, GQA, and “long context” bases&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;RoPE and “long context” marketing&lt;/strong&gt;&lt;br&gt;
A checkpoint may advertise a large context window, but pretraining data is still &lt;strong&gt;mostly shorter&lt;/strong&gt; sequences. The model learns long-context behavior partly through &lt;strong&gt;extrapolation&lt;/strong&gt; (math and scaling tricks). If your &lt;strong&gt;SFT&lt;/strong&gt; data jumps wildly between very short and very long examples without a clear pattern, you can get brittle behavior at the lengths you care about in production.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Gotcha 4 — Train-time vs serve-time RoPE settings must match.&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;rope_scaling&lt;/code&gt;, &lt;code&gt;max_position_embeddings&lt;/code&gt;, and related flags in &lt;code&gt;config.json&lt;/code&gt; are not cosmetic. If training uses scaling recipe &lt;strong&gt;A&lt;/strong&gt; and your inference server uses &lt;strong&gt;B&lt;/strong&gt; (or an older Transformers version interprets them differently), you often get &lt;strong&gt;no crash&lt;/strong&gt;—just &lt;strong&gt;worse answers&lt;/strong&gt;, especially on long prompts. Pin library versions and dump the effective config next to your adapter in the same manifest.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Gotcha 5 — GQA layout is part of the architecture contract.&lt;/strong&gt;&lt;br&gt;
Community and vendor builds differ in how many heads group together. An adapter trained on one revision is &lt;strong&gt;not&lt;/strong&gt; a guaranteed drop-in on another revision if attention layout or hidden sizes changed. Treat “same model name, different revision” like a &lt;strong&gt;different car engine&lt;/strong&gt;—the body looks similar, parts may not interchange.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Gotcha 6 — “Eval average loss” hides long-context bugs.&lt;/strong&gt;&lt;br&gt;
Short training runs and average metrics smooth over failures that only appear at &lt;strong&gt;max production context&lt;/strong&gt;. Smoke tests at 200 steps are fine for wiring; you still need at least one eval that stresses &lt;strong&gt;the longest context you plan to use&lt;/strong&gt; (or the longest you can afford to simulate).&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;licenses-and-redistribution&#34;&gt;Licenses and redistribution&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Gotcha 7 — LoRA does not reset licensing.&lt;/strong&gt;&lt;br&gt;
You still ship a story that includes the &lt;strong&gt;base weights&lt;/strong&gt; (loaded at runtime) &lt;strong&gt;plus&lt;/strong&gt; your adapter (or a &lt;strong&gt;merged&lt;/strong&gt; full checkpoint). Some variants restrict &lt;strong&gt;commercial&lt;/strong&gt; use, require &lt;strong&gt;attribution&lt;/strong&gt;, or impose &lt;strong&gt;compliance&lt;/strong&gt; steps. “We only fine-tuned a little” does not exempt you from the base model’s terms.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Gotcha 8 — Document Hub IDs like you document dependencies.&lt;/strong&gt;&lt;br&gt;
Put license notes beside &lt;strong&gt;exact&lt;/strong&gt; model IDs and &lt;strong&gt;revisions&lt;/strong&gt; (git-style hashes on the Hub) in the same ADR where you record dataset hashes and seeds. That is what legal and security reviews actually read.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;one-adapter-per-base-revision&#34;&gt;One adapter per base revision&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Gotcha 9 — Do not casually “port” adapters across bases.&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;One LoRA per base revision&lt;/strong&gt; is the safe default. Research sometimes transfers adapters between related checkpoints; in production that is &lt;strong&gt;unforced risk&lt;/strong&gt;—small numerical differences in layernorms, embeddings, or RoPE implementation can accumulate into large behavior changes.&lt;/p&gt;
&lt;p&gt;If you must try transfer, treat it like a &lt;strong&gt;new model&lt;/strong&gt;: full eval gates, regression tests on golden prompts, and no “we eyeballed one benchmark screenshot.”&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;step-by-step-when-switching-families-qwen--llama&#34;&gt;Step-by-step when switching families (Qwen ↔ LLaMA)&lt;/h2&gt;
&lt;p&gt;&lt;a href=&#34;https://blog.veydh.com/2026/2026-01-lora-and-small-distilled-models-primer/&#34;&gt;LoRA: Fine-Tuning Small Models Without Full Weights&lt;/a&gt; and &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-mistral-huggingface-lora-training-notes/&#34;&gt;Fine-Tuning a Mistral-Class Checkpoint with LoRA on Hugging Face&lt;/a&gt;’s &lt;strong&gt;PEFT&lt;/strong&gt; recipe stays; below are &lt;strong&gt;extra&lt;/strong&gt; gates per family.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Tokenizer probe&lt;/strong&gt; — For each locale you ship, tokenize a &lt;strong&gt;fixed&lt;/strong&gt; paragraph of representative text. Record &lt;strong&gt;token count&lt;/strong&gt; and verify &lt;strong&gt;round-trip&lt;/strong&gt;: for string inputs, &lt;code&gt;decode(encode(x))&lt;/code&gt; should equal &lt;code&gt;x&lt;/code&gt; (or document intentional normalization). Multilingual bases punish “character budget” planning that assumed English token density.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Template probe&lt;/strong&gt; — Dump &lt;code&gt;tokenizer.apply_chat_template&lt;/code&gt; on one golden multi-turn example to a &lt;code&gt;.txt&lt;/code&gt; file in git; &lt;strong&gt;diff&lt;/strong&gt; that file in PRs that touch chat formatting. Qwen and LLaMA instruct variants use different &lt;strong&gt;role markers&lt;/strong&gt; and spacing; mixing templates means you train the model to expect the wrong framing at inference.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;RoPE / context flags&lt;/strong&gt; — Copy into your run manifest: &lt;code&gt;rope_scaling&lt;/code&gt;, &lt;code&gt;max_position_embeddings&lt;/code&gt;, and any other fields your &lt;strong&gt;training&lt;/strong&gt; and &lt;strong&gt;serving&lt;/strong&gt; stacks read from &lt;code&gt;config.json&lt;/code&gt;. Training with scaling &lt;strong&gt;A&lt;/strong&gt; and serving with scaling &lt;strong&gt;B&lt;/strong&gt; is a classic &lt;strong&gt;silent&lt;/strong&gt; quality regression.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Train short, eval long&lt;/strong&gt; — Run a short smoke job for plumbing; then evaluate at &lt;strong&gt;max context&lt;/strong&gt; you intend in production (or the nearest affordable subset). Extrapolation bugs show up here, not in smoothed training loss.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Merge policy&lt;/strong&gt; — Decide early whether production loads &lt;strong&gt;&lt;code&gt;PeftModel&lt;/code&gt;&lt;/strong&gt; (base + adapter at runtime) or a &lt;strong&gt;merged&lt;/strong&gt; &lt;code&gt;save_pretrained&lt;/code&gt; directory. &lt;strong&gt;Merge&lt;/strong&gt; simplifies some C++ or single-binary servers; it complicates “swap adapter only” deploys and can blur audit trails if you lose the separation between base and delta.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Optional merge&lt;/strong&gt; (when you explicitly want one directory of full weights):&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; torch
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; transformers &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; AutoModelForCausalLM
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; peft &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; PeftModel
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;base &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; AutoModelForCausalLM&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;from_pretrained(BASE_ID, revision&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;BASE_REV, torch_dtype&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;torch&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;bfloat16, device_map&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;cpu&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;base &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; PeftModel&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;from_pretrained(base, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;./lora-out&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;merged &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; base&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;merge_and_unload()
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;merged&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;save_pretrained(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;./merged-model&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;tokenizer&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;save_pretrained(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;./merged-model&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;Gotcha 10 — Re-evaluate after merge.&lt;/strong&gt;&lt;br&gt;
Run the &lt;strong&gt;same&lt;/strong&gt; eval suite on merged weights. Do not assume merge is bitwise-identical to “base + adapter” forward pass in every runtime without checking—numerical paths and optimizations can differ.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;hub--tooling-matrix-same-training-different-ergonomics&#34;&gt;Hub / tooling matrix (same training, different ergonomics)&lt;/h2&gt;
&lt;table&gt;
  &lt;thead&gt;
      &lt;tr&gt;
          &lt;th&gt;Workflow&lt;/th&gt;
          &lt;th&gt;Tooling&lt;/th&gt;
          &lt;th&gt;When to use it&lt;/th&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr&gt;
          &lt;td&gt;Notebook → script&lt;/td&gt;
          &lt;td&gt;Transformers + PEFT + &lt;strong&gt;TRL&lt;/strong&gt; (Transformer Reinforcement Learning library—helpers for SFT/RLHF-style training on HF)&lt;/td&gt;
          &lt;td&gt;Small teams, full control&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;YAML-driven SFT&lt;/td&gt;
          &lt;td&gt;LLaMA-Factory, Axolotl&lt;/td&gt;
          &lt;td&gt;Faster iteration when configs are shared&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Managed fine-tune&lt;/td&gt;
          &lt;td&gt;Cloud vendor jobs&lt;/td&gt;
          &lt;td&gt;When compliance wants a hosted trail; still export adapter + manifest&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The &lt;strong&gt;reproducibility&lt;/strong&gt; invariant is the same: pinned &lt;strong&gt;base&lt;/strong&gt; revision, frozen dataset hash, logged &lt;code&gt;lora_config&lt;/code&gt;, &lt;strong&gt;identical&lt;/strong&gt; chat template in train and serve.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;In one sentence: &lt;strong&gt;family-specific tokenizer and RoPE (and attention layout) details&lt;/strong&gt; decide whether your fine-tune is stable—or fragile in ways that only show up under real prompts and real languages. &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/&#34;&gt;Serving Small Models Behind an HTTP API&lt;/a&gt; moves from training to &lt;strong&gt;serving&lt;/strong&gt;: HTTP boundaries, OpenAI-compatible APIs, and runtime choices once the adapter exists.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Serving Small Models Behind an HTTP API</title>
      <link>https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/</link>
      <pubDate>Mon, 09 Feb 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;Training a LoRA is pretty satisfying (once you see the results start leaning closer to the thing you&amp;rsquo;re striving towards); &lt;strong&gt;serving&lt;/strong&gt; it is where software engineering returns. Clients should see stable JSON, explicit errors, and predictable latency—not a Jupyter cell calling &lt;code&gt;model.generate&lt;/code&gt;. The HTTP layer is a &lt;strong&gt;contract&lt;/strong&gt;: versioning, observability, and back-pressure belong there, not buried inside CUDA kernels.&lt;/p&gt;
&lt;p&gt;This post frames &lt;strong&gt;OpenAI-compatible&lt;/strong&gt; surfaces and the runtimes behind them, in the same spirit as the interop and API-design posts from 2024.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;why-openai-compatible-routes-help&#34;&gt;Why OpenAI-compatible routes help&lt;/h2&gt;
&lt;p&gt;Exposing &lt;code&gt;/v1/chat/completions&lt;/code&gt; (or a close cousin) means existing SDKs, proxies, and internal tools often &lt;strong&gt;drop in&lt;/strong&gt; without a rewrite. You still document your own limits—max context, supported modalities, tool-calling quirks—but you avoid inventing yet another message schema for every new service.&lt;/p&gt;
&lt;p&gt;Compatibility is not perfection. Deltas should be documented explicitly (streaming format, stop sequences, tool JSON) so client teams do not rely on undocumented behavior.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;runtime-choices-vllm-tgi-llamacpp-and-friends&#34;&gt;Runtime choices: vLLM, TGI, llama.cpp, and friends&lt;/h2&gt;
&lt;p&gt;The right engine depends on constraints more than on hype:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Multi-GPU, high throughput, Python ecosystem&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;vLLM&lt;/strong&gt; and similar servers emphasize batching, PagedAttention-style memory use, and throughput. Good when you have NVIDIA hardware and want many concurrent sessions.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;SGLang&lt;/strong&gt;&lt;br&gt;
The other high-throughput GPU server worth benchmarking next to vLLM. Same OpenAI-shaped HTTP surface, different scheduler and kernel choices.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Hugging Face TGI&lt;/strong&gt;&lt;br&gt;
Entered maintenance on 11 December 2025. The repository was archived in March 2026. Keep an existing deployment if it is already serving; do not start a new one. vLLM or SGLang is the replacement.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;CPU or edge, smaller models&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;llama.cpp&lt;/strong&gt;-family servers shine when GPUs are scarce or you need a portable binary. Latency per token differs; total cost of ownership may still win. The server binary has been &lt;code&gt;llama-server&lt;/code&gt; since June 2024. &lt;code&gt;./server&lt;/code&gt; is the old name.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The choice rests on &lt;strong&gt;SLO&lt;/strong&gt;, &lt;strong&gt;hardware&lt;/strong&gt;, and &lt;strong&gt;team familiarity&lt;/strong&gt;—not benchmark leaderboard bragging rights alone.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;operations-health-versions-request-ids&#34;&gt;Operations: health, versions, request IDs&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Health checks&lt;/strong&gt; should validate more than “process is up”: load the tokenizer, warm the model, and optionally run a tiny forward pass in staging. &lt;strong&gt;Model version&lt;/strong&gt; belongs in response headers or metadata so clients can log which revision answered.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Request IDs&lt;/strong&gt; propagate through auth, rate limiting, inference, and logging—the same discipline as wiring gRPC and HTTP across Python and Java services. When something regresses, one string traces the path.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;cost-control-restricting-token-usage&#34;&gt;Cost control: restricting token usage&lt;/h2&gt;
&lt;p&gt;Cost tracks &lt;strong&gt;tokens processed&lt;/strong&gt; (prompt + completion) and &lt;strong&gt;how often&lt;/strong&gt; you run inference. To manage spend you need &lt;strong&gt;hard limits&lt;/strong&gt; clients cannot bypass, &lt;strong&gt;visibility&lt;/strong&gt; into who burned what, and &lt;strong&gt;fairness&lt;/strong&gt; so one integration cannot exhaust the pool.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Cap generation length server-side.&lt;/strong&gt; OpenAI-shaped APIs accept &lt;code&gt;max_tokens&lt;/code&gt; (or &lt;code&gt;max_completion_tokens&lt;/code&gt;) on the request; that only helps if you &lt;strong&gt;enforce a ceiling&lt;/strong&gt;: ignore values above your tier’s cap, or clamp them downward before the request reaches the engine. Otherwise a buggy or malicious client can ask for tens of thousands of new tokens per call. The engine should still return a clear &lt;strong&gt;finish reason&lt;/strong&gt; when generation stops on length.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. Bound the context window at the runtime.&lt;/strong&gt; Engines expose a maximum sequence length (e.g. vLLM’s &lt;code&gt;--max-model-len&lt;/code&gt;, llama.cpp’s &lt;code&gt;-c&lt;/code&gt;). That limits &lt;strong&gt;worst-case&lt;/strong&gt; memory and per-request work. It does not replace &lt;strong&gt;policy&lt;/strong&gt;: you still want pre-flight checks (same tokenizer as the model) so oversize prompts fail fast with a 4xx instead of tying up a slot—see &lt;a href=&#34;https://blog.veydh.com/2026/2026-03-token-limits-budgets-and-truncation/&#34;&gt;Token Budgets: Enforcing Limits at the API Layer&lt;/a&gt; for counting, truncation, and streaming semantics.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Rate-limit and quota by tenant or key.&lt;/strong&gt; Tokens per minute (TPM) and requests per minute (RPM), optionally combined with daily or monthly &lt;strong&gt;budgets&lt;/strong&gt;, belong in the &lt;strong&gt;gateway or auth layer&lt;/strong&gt; (API gateway, Envoy, Kong, or a thin BFF) keyed off API keys or JWT claims. That caps &lt;strong&gt;aggregate&lt;/strong&gt; burn even when each individual request is small.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;4. Meter and alert.&lt;/strong&gt; Log or export &lt;code&gt;prompt_tokens&lt;/code&gt;, &lt;code&gt;completion_tokens&lt;/code&gt;, and &lt;strong&gt;total&lt;/strong&gt; per request ID and tenant; chart burn rate and set alerts before the bill surprises anyone. Chargeback by team or product line turns “model cost” from a black box into an engineering lever.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;5. Operational knobs that are not a substitute for policy.&lt;/strong&gt; Continuous batching and high concurrency improve &lt;strong&gt;throughput&lt;/strong&gt;; they do not stop runaway prompts. Default &lt;strong&gt;low&lt;/strong&gt; &lt;code&gt;max_tokens&lt;/code&gt; for anonymous or trial tiers; require review or higher entitlements for large completions.&lt;/p&gt;
&lt;p&gt;In short: &lt;strong&gt;runtime&lt;/strong&gt; caps define physics (max length, VRAM); &lt;strong&gt;API/gateway&lt;/strong&gt; caps define &lt;strong&gt;product and finance&lt;/strong&gt; (per-call generation limit, per-tenant TPM, monthly budget). You want both.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;concrete-runtimes-commands-and-trade-offs&#34;&gt;Concrete runtimes: commands and trade-offs&lt;/h2&gt;
&lt;p&gt;These are &lt;strong&gt;illustrative&lt;/strong&gt;; pin container tags and model revisions in your own manifests.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;vLLM (multi-session GPU throughput)&lt;/strong&gt; — OpenAI-compatible server, good when you already have CUDA and want continuous batching:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-bash&#34; data-lang=&#34;bash&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# Example only: replace model path and image tag with pinned versions&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# --max-model-len caps context (and thus per-request upper bound on work)&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;docker run --gpus all -p 8000:8000 &lt;span style=&#34;color:#ae81ff&#34;&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  vllm/vllm-openai:latest &lt;span style=&#34;color:#ae81ff&#34;&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  --model mistralai/Mistral-7B-Instruct-v0.3 &lt;span style=&#34;color:#ae81ff&#34;&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  --dtype bfloat16 &lt;span style=&#34;color:#ae81ff&#34;&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  --max-model-len &lt;span style=&#34;color:#ae81ff&#34;&gt;8192&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;SGLang&lt;/strong&gt; — Benchmark it beside vLLM when GPU throughput is the SLO. Pin the image tag the same way.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;llama.cpp server&lt;/strong&gt; — CPU or smaller GPUs; compile with the same quant you evaluated (&lt;code&gt;Q4_K_M&lt;/code&gt;, etc.):&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-bash&#34; data-lang=&#34;bash&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;./llama-server -m ./models/model.gguf --port &lt;span style=&#34;color:#ae81ff&#34;&gt;8080&lt;/span&gt; -c &lt;span style=&#34;color:#ae81ff&#34;&gt;4096&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;Runtime choice:&lt;/strong&gt; &lt;strong&gt;vLLM or SGLang&lt;/strong&gt; when concurrent GPU sessions and batching dominate SLOs; &lt;strong&gt;llama.cpp&lt;/strong&gt; when footprint, CPU-only, or edge packaging matters more than peak tokens/sec. TGI is in maintenance and is not a new-deploy choice. &lt;strong&gt;Always&lt;/strong&gt; re-benchmark &lt;strong&gt;your&lt;/strong&gt; adapter + prompt template on the chosen runtime—kernel and quant interact with LoRA paths.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;minimal-openai-shaped-curl-contract-test&#34;&gt;Minimal OpenAI-shaped &lt;code&gt;curl&lt;/code&gt; contract test&lt;/h2&gt;
&lt;p&gt;After deploy, hit &lt;strong&gt;non-streaming&lt;/strong&gt; chat with a frozen prompt and compare &lt;strong&gt;SHA&lt;/strong&gt; of normalized JSON (strip volatile fields like &lt;code&gt;id&lt;/code&gt; timestamps if needed):&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-bash&#34; data-lang=&#34;bash&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;curl -s http://localhost:8000/v1/chat/completions &lt;span style=&#34;color:#ae81ff&#34;&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  -H &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Content-Type: application/json&amp;#34;&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  -d &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#39;{&amp;#34;model&amp;#34;:&amp;#34;mistralai/Mistral-7B-Instruct-v0.3&amp;#34;,&amp;#34;messages&amp;#34;:[{&amp;#34;role&amp;#34;:&amp;#34;user&amp;#34;,&amp;#34;content&amp;#34;:&amp;#34;Say OK.&amp;#34;}],&amp;#34;max_tokens&amp;#34;:8,&amp;#34;temperature&amp;#34;:0}&amp;#39;&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;\
&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;  | jq .
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Check &lt;code&gt;choices[0].finish_reason&lt;/code&gt;, token usage fields, and error schema for oversize prompts—those are the surfaces &lt;a href=&#34;https://blog.veydh.com/2026/2026-03-token-limits-budgets-and-truncation/&#34;&gt;Token Budgets: Enforcing Limits at the API Layer&lt;/a&gt; tightens.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;This post closes the loop from “weights on disk” to “service behind a load balancer,” including &lt;strong&gt;where&lt;/strong&gt; to enforce token and rate limits so costs stay predictable: ceilings on completion length and context at the engine, plus TPM/RPM and budgets at the gateway. &lt;a href=&#34;https://blog.veydh.com/2026/2026-03-token-limits-budgets-and-truncation/&#34;&gt;Token Budgets: Enforcing Limits at the API Layer&lt;/a&gt; goes deeper on &lt;strong&gt;pre-flight counting&lt;/strong&gt;, truncation strategies, and client contracts—stack it with the serving layer you run here.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>RAG Foundations: Embeddings, Chunking, and the Retrieval Loop</title>
      <link>https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/</link>
      <pubDate>Wed, 14 Jan 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Retrieval-Augmented Generation&lt;/strong&gt; is the pattern everyone names when they want the model to cite &lt;em&gt;your&lt;/em&gt; PDFs, tickets, or runbooks instead of improvising from weights alone. It is less like a single model feature and more like a small &lt;strong&gt;data product&lt;/strong&gt;: you ingest documents, turn them into searchable units, pull the best candidates at query time, and only then hand text to the generator.&lt;/p&gt;
&lt;p&gt;This month locks in vocabulary and failure modes before the later posts go deeper on re-ranking, evaluation, and the small-model stack paired with RAG through the rest of 2026.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;the-core-loop-end-to-end&#34;&gt;The core loop, end to end&lt;/h2&gt;
&lt;p&gt;The happy path looks boring on purpose—that is a good sign.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Ingest&lt;/strong&gt;&lt;br&gt;
You load sources (HTML, Markdown, PDF text, Slack exports, whatever). Normalization matters: strip boilerplate headers, fix encoding, and keep enough metadata (source URL, section, &lt;code&gt;updated_at&lt;/code&gt;) that you can filter later.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Chunk&lt;/strong&gt;&lt;br&gt;
Models do not read whole repositories in one gulp. You split text into overlapping segments—classically hundreds to low thousands of &lt;strong&gt;tokens&lt;/strong&gt; per chunk, with &lt;strong&gt;overlap&lt;/strong&gt; so sentences at boundaries are not orphaned. Tables and lists punish naive “split every N characters” strategies; Structure-aware splitting is preferable when the format allows it.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Embed&lt;/strong&gt;&lt;br&gt;
An embedding model maps each chunk to a dense vector. At query time you embed the user question (sometimes the query and the document live better with &lt;strong&gt;asymmetric&lt;/strong&gt; encoders—one flavor for passages, one for questions—but many stacks use a single model for both).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Retrieve&lt;/strong&gt;&lt;br&gt;
You score candidates with cosine similarity, dot product (when vectors are normalized differently), or a hybrid of &lt;strong&gt;BM25 + vectors&lt;/strong&gt;. You return &lt;strong&gt;top-k&lt;/strong&gt; chunks, optionally after metadata filters (tenant, product line, language).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Generate&lt;/strong&gt;&lt;br&gt;
The LLM receives a system or developer instruction, the retrieved passages in a clearly delimited block, and the user message. The model’s job is to &lt;strong&gt;ground&lt;/strong&gt; the answer in those passages while refusing when nothing supports a claim.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That loop is simple to diagram and surprisingly easy to get subtly wrong in production.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;chunking-where-the-most-silent-damage-shows-up&#34;&gt;Chunking: where the most silent damage shows up&lt;/h2&gt;
&lt;p&gt;If chunks are too large, you dilute relevance—the vector averages over too many topics and retrieval becomes fuzzy. If chunks are too small, you lose definitions and antecedents (“it”, “the policy”) that only make sense in a wider window.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Overlap&lt;/strong&gt; is not waste; it is insurance that a sentence sliced in half still appears whole in at least one neighbor chunk. Overlap percentage is a tunable knob alongside chunk size, not a fixed constant from a tutorial.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tables&lt;/strong&gt; deserve a callout. Row-wise splitting can destroy joins across columns; sometimes keeping a whole small table in one chunk is better than perfect token parity. When tables are huge, consider extracting them to a structured store and retrieving them by key while still RAG-ing the narrative docs.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;embeddings-and-the-vector-store&#34;&gt;Embeddings and the vector store&lt;/h2&gt;
&lt;p&gt;The embedding model defines the geometry of your search. A model trained for &lt;strong&gt;semantic&lt;/strong&gt; similarity helps with paraphrases; a weaker or badly matched embedder sends the generator irrelevant paragraphs that &lt;em&gt;look&lt;/em&gt; related in keyword space only.&lt;/p&gt;
&lt;p&gt;Vector databases and libraries differ in filtering, hybrid search, quantization, and ops maturity. For early work, &lt;strong&gt;reproducibility&lt;/strong&gt; (fixed model revision, recorded chunking parameters) matters more than shaving microseconds off single-query latency. Once traffic grows, batching, caching query embeddings, and separating hot tenants matter.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;pitfalls-to-plan-for-explicitly&#34;&gt;Pitfalls to plan for explicitly&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Stale corpora&lt;/strong&gt;&lt;br&gt;
If the retrieval index lags the truth, the model confidently cites outdated policy. Version your index builds and expose “as of” metadata when users need it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Lost in the middle&lt;/strong&gt;&lt;br&gt;
Stuffing ten long chunks into the context window does not mean the model weighs them evenly. Keeping k modest, summarizing long threads, or using re-ranking (&lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-operations-re-ranking-and-evaluation/&#34;&gt;RAG in Production: Re-ranking, HyDE, and Simple Evals&lt;/a&gt;) presents fewer, sharper passages.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Evaluation theater&lt;/strong&gt;&lt;br&gt;
Eyeballing answers in a notebook is not a test harness. Hold out question–answer pairs, measure whether the &lt;em&gt;right&lt;/em&gt; chunk would be retrieved, and track regressions when you change embedder or chunking.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;tooling-map-how-teams-actually-wire-the-loop&#34;&gt;Tooling map: how teams actually wire the loop&lt;/h2&gt;
&lt;p&gt;The loop above is runtime-agnostic. In practice you glue &lt;strong&gt;ingest → chunk → embed → index → query → generate&lt;/strong&gt; with one of these families (often mixed):&lt;/p&gt;
&lt;table&gt;
  &lt;thead&gt;
      &lt;tr&gt;
          &lt;th&gt;Layer&lt;/th&gt;
          &lt;th&gt;Representative tools&lt;/th&gt;
          &lt;th&gt;What you trade&lt;/th&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr&gt;
          &lt;td&gt;Orchestration&lt;/td&gt;
          &lt;td&gt;&lt;a href=&#34;https://python.langchain.com/&#34;&gt;LangChain&lt;/a&gt;, &lt;a href=&#34;https://www.llamaindex.ai/&#34;&gt;LlamaIndex&lt;/a&gt;, &lt;a href=&#34;https://haystack.deepset.ai/&#34;&gt;Haystack&lt;/a&gt;, custom Python&lt;/td&gt;
          &lt;td&gt;LangChain/LlamaIndex ship fast demos and integrations; custom code minimizes magic and keeps dependencies thin.&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Chunking&lt;/td&gt;
          &lt;td&gt;Framework splitters, &lt;a href=&#34;https://unstructured.io/&#34;&gt;Unstructured&lt;/a&gt; for messy PDFs, &lt;code&gt;langchain_text_splitters&lt;/code&gt;, hand-rolled Markdown headers&lt;/td&gt;
          &lt;td&gt;PDFs/HTML reward structure-aware parsers; naive &lt;code&gt;CharacterTextSplitter&lt;/code&gt; is fine only for clean text.&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Embeddings&lt;/td&gt;
          &lt;td&gt;&lt;a href=&#34;https://www.sbert.net/&#34;&gt;sentence-transformers&lt;/a&gt;, OpenAI/Cohere/Voyage APIs, models on the Hub&lt;/td&gt;
          &lt;td&gt;APIs = ops simplicity + cost; self-hosted = reproducibility + no egress; pin &lt;strong&gt;model revision&lt;/strong&gt;.&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Vector index&lt;/td&gt;
          &lt;td&gt;&lt;a href=&#34;https://github.com/facebookresearch/faiss&#34;&gt;FAISS&lt;/a&gt; (in-process), &lt;a href=&#34;https://www.trychroma.com/&#34;&gt;Chroma&lt;/a&gt;, &lt;a href=&#34;https://qdrant.tech/&#34;&gt;Qdrant&lt;/a&gt;, &lt;a href=&#34;https://github.com/pgvector/pgvector&#34;&gt;pgvector&lt;/a&gt;, managed cloud DBs&lt;/td&gt;
          &lt;td&gt;FAISS/Chroma for prototypes; &lt;strong&gt;pgvector&lt;/strong&gt; when you already own Postgres and want SQL + metadata filters; Qdrant/Milvus when you outgrow a single node.&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Lexical / hybrid&lt;/td&gt;
          &lt;td&gt;&lt;a href=&#34;https://en.wikipedia.org/wiki/Okapi_BM25&#34;&gt;BM25&lt;/a&gt; via Elasticsearch/OpenSearch, built-in hybrid in some vector DBs&lt;/td&gt;
          &lt;td&gt;Pure vectors miss exact SKUs and codes; hybrid fixes “semantic near-miss” failures.&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Generation&lt;/td&gt;
          &lt;td&gt;Any chat API or vLLM/SGLang self-host (see &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/&#34;&gt;Serving Small Models Behind an HTTP API&lt;/a&gt;)&lt;/td&gt;
          &lt;td&gt;Same RAG stack; swap generator without re-indexing if prompts stay stable. TGI is in maintenance as of December 2025.&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;Pros / cons in one sentence each:&lt;/strong&gt; &lt;em&gt;Framework-first&lt;/em&gt; (LangChain/LlamaIndex) accelerates time-to-demo but can hide tokenizer/chunk bugs until production. &lt;em&gt;Vector-in-Postgres&lt;/em&gt; reduces moving parts for teams that already run Postgres and need row-level security. &lt;em&gt;Separate vector DB&lt;/em&gt; scales ANN search and hybrid features but adds another backup and monitoring target.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;minimal-reproducible-path-self-hosted-embed--local-index&#34;&gt;Minimal reproducible path (self-hosted embed + local index)&lt;/h2&gt;
&lt;p&gt;Goal: one machine, fixed dependency versions, same chunks every run.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Environment&lt;/strong&gt; — Python 3.11+, &lt;code&gt;pip install chromadb sentence-transformers&lt;/code&gt; (pin versions in &lt;code&gt;requirements.txt&lt;/code&gt;; record &lt;code&gt;pip freeze&lt;/code&gt; hash in your ADR). For header-aware splitting later, add &lt;code&gt;langchain-text-splitters&lt;/code&gt; or Unstructured and &lt;strong&gt;record the extra dependency&lt;/strong&gt; as part of the index version.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Corpus&lt;/strong&gt; — Start with a folder of &lt;code&gt;.md&lt;/code&gt; or &lt;code&gt;.txt&lt;/code&gt; files; later swap in Unstructured for PDFs. Record file list + checksums.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Chunk&lt;/strong&gt; — Fixed &lt;code&gt;chunk_size&lt;/code&gt; (tokens or characters), fixed &lt;code&gt;chunk_overlap&lt;/code&gt;, single splitter implementation. Log the parameters beside the index name.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Embed&lt;/strong&gt; — Load one Hub model id with &lt;code&gt;revision=&lt;/code&gt;; embed documents in batches; persist the Chroma collection name + embed model id.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Retrieve&lt;/strong&gt; — For each eval question, &lt;code&gt;collection.query(query_texts=[q], n_results=k)&lt;/code&gt;; log returned chunk ids + scores.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Generate&lt;/strong&gt; — Build one prompt template: system instruction + &lt;code&gt;---&lt;/code&gt; delimited passages + user question. Pin chat model &lt;strong&gt;revision&lt;/strong&gt; the same way as the embedder.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;A compact indexing sketch (adapt names and paths):&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# index_build.py — illustrative; pin package versions in production&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; chromadb
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; chromadb.utils &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; embedding_functions
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;CHUNK_SIZE &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;800&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;CHUNK_OVERLAP &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;120&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;chunk_text&lt;/span&gt;(text: str, size: int &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; CHUNK_SIZE, overlap: int &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; CHUNK_OVERLAP) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; list[str]:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&amp;#34;&amp;#34;Character-based chunks; swap for structure-aware splitters when format allows.&amp;#34;&amp;#34;&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    chunks: list[str] &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; []
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    start &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;0&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    n &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; len(text)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;while&lt;/span&gt; start &lt;span style=&#34;color:#f92672&#34;&gt;&amp;lt;&lt;/span&gt; n:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        end &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; min(start &lt;span style=&#34;color:#f92672&#34;&gt;+&lt;/span&gt; size, n)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        chunks&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;append(text[start:end])
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; end &lt;span style=&#34;color:#f92672&#34;&gt;==&lt;/span&gt; n:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;            &lt;span style=&#34;color:#66d9ef&#34;&gt;break&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        start &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; max(end &lt;span style=&#34;color:#f92672&#34;&gt;-&lt;/span&gt; overlap, start &lt;span style=&#34;color:#f92672&#34;&gt;+&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;1&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; chunks
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;load_docs&lt;/span&gt;(paths: list[str]) &lt;span style=&#34;color:#f92672&#34;&gt;-&amp;gt;&lt;/span&gt; list[str]:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    chunks: list[str] &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; []
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;for&lt;/span&gt; p &lt;span style=&#34;color:#f92672&#34;&gt;in&lt;/span&gt; paths:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        text &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; open(p, encoding&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;utf-8&amp;#34;&lt;/span&gt;)&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;read()
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        chunks&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;extend(chunk_text(text))
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; chunks
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;def&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;main&lt;/span&gt;():
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    ef &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; embedding_functions&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;SentenceTransformerEmbeddingFunction(
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#75715e&#34;&gt;# 22M-parameter model from 2021, 384 dimensions. Wiring example only,&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        &lt;span style=&#34;color:#75715e&#34;&gt;# not a 2026 retrieval default.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;        model_name&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;sentence-transformers/all-MiniLM-L6-v2&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    )
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    client &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; chromadb&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;PersistentClient(path&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;./chroma_db&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    col &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; client&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;get_or_create_collection(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;docs&amp;#34;&lt;/span&gt;, embedding_function&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;ef)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    chunks &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; load_docs([&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;./corpus/a.md&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;./corpus/b.md&amp;#34;&lt;/span&gt;])
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    ids &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; [&lt;span style=&#34;color:#e6db74&#34;&gt;f&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;chunk-&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;{&lt;/span&gt;i&lt;span style=&#34;color:#e6db74&#34;&gt;}&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;for&lt;/span&gt; i &lt;span style=&#34;color:#f92672&#34;&gt;in&lt;/span&gt; range(len(chunks))]
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    col&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;add(ids&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;ids, documents&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;chunks)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    print(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;indexed&amp;#34;&lt;/span&gt;, len(chunks), &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;chunks&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; __name__ &lt;span style=&#34;color:#f92672&#34;&gt;==&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;__main__&amp;#34;&lt;/span&gt;:
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    main()
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;What “reproducible” means here:&lt;/strong&gt; anyone with the same corpus bytes, splitter parameters, embedder revision, and index path gets the same retrieval ids for the same queries. Change any of those without a version bump and you should expect eval drift.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;when-to-add-hybrid-search-or-metadata-first&#34;&gt;When to add hybrid search or metadata first&lt;/h2&gt;
&lt;p&gt;If users query &lt;strong&gt;IDs, error codes, or proper nouns&lt;/strong&gt;, add &lt;strong&gt;BM25 or hybrid&lt;/strong&gt; before chasing a larger embedder. If you have &lt;strong&gt;tenant_id&lt;/strong&gt; or &lt;strong&gt;product_line&lt;/strong&gt;, add &lt;strong&gt;metadata filters&lt;/strong&gt; on the vector store before raising &lt;code&gt;k&lt;/code&gt;. Both are cheaper than swapping a 7B generator to “fix” bad retrieval.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;RAG is &lt;strong&gt;systems engineering&lt;/strong&gt;: ingestion quality, chunk boundaries, and retrieval metrics matter as much as the chat model’s charisma. The small LLMs fine-tuned later in this series only shine when the passages they read are the right passages.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-operations-re-ranking-and-evaluation/&#34;&gt;RAG in Production: Re-ranking, HyDE, and Simple Evals&lt;/a&gt; picks up &lt;strong&gt;re-ranking, query reformulation, and lightweight evaluation&lt;/strong&gt; so naive top-k does not become the ceiling.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>RAG in Production: Re-ranking, HyDE, and Simple Evals</title>
      <link>https://blog.veydh.com/2026/2026-01-rag-operations-re-ranking-and-evaluation/</link>
      <pubDate>Sun, 11 Jan 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-01-rag-operations-re-ranking-and-evaluation/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;Naive &lt;strong&gt;top-k&lt;/strong&gt; vector search is a decent demo and a fragile production strategy. Users paraphrase; documents use different jargon; multi-hop questions need facts that never co-occur in a single chunk. When the backend is a &lt;strong&gt;smaller&lt;/strong&gt; model (Mistral-class, Qwen, LLaMA derivatives), the generator is less able to “paper over” bad retrieval with parametric knowledge—so the retrieval layer has to pull its weight. Size is what matters here, not whether the checkpoint was distilled.&lt;/p&gt;
&lt;p&gt;This post collects upgrades worth reaching for &lt;strong&gt;before&lt;/strong&gt; touching fancier graph RAG or agent loops. They pair well with the foundations in &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/&#34;&gt;RAG Foundations: Embeddings, Chunking, and the Retrieval Loop&lt;/a&gt; and with the LoRA/serving posts that follow (&lt;a href=&#34;https://blog.veydh.com/2026/2026-01-lora-and-small-distilled-models-primer/&#34;&gt;LoRA: Fine-Tuning Small Models Without Full Weights&lt;/a&gt;, &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-llm-serving-apis-openai-compatible/&#34;&gt;Serving Small Models Behind an HTTP API&lt;/a&gt;).&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;re-ranking-a-second-opinion-on-query-passage-pairs&#34;&gt;Re-ranking: a second opinion on (query, passage) pairs&lt;/h2&gt;
&lt;p&gt;Bi-encoders (your embedding model) score candidates cheaply because query and document vectors are precomputed. &lt;strong&gt;Cross-encoders&lt;/strong&gt; and learned &lt;strong&gt;re-rankers&lt;/strong&gt; jointly attend to query and text; they are heavier per pair but far sharper at deciding whether a chunk truly answers the question.&lt;/p&gt;
&lt;p&gt;In production the usual pattern is:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Retrieve a &lt;strong&gt;wider&lt;/strong&gt; candidate set (e.g. 50–200) with fast vectors.&lt;/li&gt;
&lt;li&gt;Re-rank down to &lt;strong&gt;3–10&lt;/strong&gt; with a cross-encoder or a small reranker model.&lt;/li&gt;
&lt;li&gt;Pass only that short list to the LLM.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The latency trade-off is real. &lt;strong&gt;p95&lt;/strong&gt; end-to-end warrants watching, and reranking is sometimes limited to “high value” intents or gated behind a cheap ambiguity classifier.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;query-expansion-and-hyde&#34;&gt;Query expansion and HyDE&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Query expansion&lt;/strong&gt; adds terms or sub-questions so lexical and embedding gaps shrink. Simple forms include synonyms from a domain glossary or LLM-generated bullet points that rephrase the user ask.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;HyDE&lt;/strong&gt; (Hypothetical Document Embeddings) flips the idea: ask the LLM to write a &lt;em&gt;fake&lt;/em&gt; answer as if it knew the corpus, embed that synthetic paragraph, and search with it. It can bridge vocabulary mismatch; it can also amplify hallucinated specifics if you are not careful. HyDE fits better as an optional path behind a feature flag, not the default for regulated domains.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;metadata-filters-and-tenancy&#34;&gt;Metadata filters and tenancy&lt;/h2&gt;
&lt;p&gt;Vectors without filters become a soup. Retrieval should be scoped by &lt;strong&gt;tenant&lt;/strong&gt;, &lt;strong&gt;product&lt;/strong&gt;, &lt;strong&gt;language&lt;/strong&gt;, &lt;strong&gt;document type&lt;/strong&gt;, or &lt;strong&gt;time range&lt;/strong&gt; whenever those axes exist in the source system. That mirrors the “bounded context” thinking from earlier architecture writing: fewer collisions, easier debugging, and less chance of leaking one customer’s chunk into another’s session.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;evaluation-that-catches-regressions&#34;&gt;Evaluation that catches regressions&lt;/h2&gt;
&lt;p&gt;Three layers of signal beat one pretty demo:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Retrieval quality&lt;/strong&gt;&lt;br&gt;
Labeled (query, relevant_chunk_id) pairs—or weaker proxies like “any gold paragraph in top-k”—give you recall@k and MRR. When embedders or chunking change, this layer screams first.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Answer groundedness&lt;/strong&gt;&lt;br&gt;
Does the final answer stick to retrieved text? LLM-as-judge helps &lt;strong&gt;if&lt;/strong&gt; the judge is validated against human ratings and prompts stay versioned. A single automated score should not pass as compliance evidence alone.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Latency and cost&lt;/strong&gt;&lt;br&gt;
Track histograms for embed, search, rerank, and generate. A “smarter” stack that misses SLOs is a failed deploy.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Automate a regression job when the corpus or models change. Same discipline as pinning dependencies: &lt;strong&gt;record model revisions, index build IDs, and dataset hashes&lt;/strong&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;step-by-step-widen--re-rank--generate&#34;&gt;Step-by-step: widen → re-rank → generate&lt;/h2&gt;
&lt;p&gt;This is the default production upgrade path once naive &lt;code&gt;top_k&lt;/code&gt; plateaus.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Vector retrieve&lt;/strong&gt; — Pull &lt;code&gt;k_wide&lt;/code&gt; (50–200) ids + texts with scores from your index (same embedder revision as in &lt;a href=&#34;https://blog.veydh.com/2026/2026-01-rag-foundations-embeddings-and-retrieval/&#34;&gt;RAG Foundations: Embeddings, Chunking, and the Retrieval Loop&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Re-rank&lt;/strong&gt; — Score each &lt;code&gt;(query, passage)&lt;/code&gt; pair with a cross-encoder or hosted rerank API; sort descending; keep &lt;code&gt;k_tight&lt;/code&gt; (3–10).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Prompt&lt;/strong&gt; — Inject only &lt;code&gt;k_tight&lt;/code&gt; passages into the chat template; log their ids on the response object for debugging.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Measure&lt;/strong&gt; — Offline: recall@k on labeled data &lt;em&gt;before&lt;/em&gt; and &lt;em&gt;after&lt;/em&gt; rerank (rerank can hurt if the bi-encoder already ranked gold in position 80 and the cross-encoder mis-scores length-biased chunks).&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2 id=&#34;tooling-comparison-for-re-ranking&#34;&gt;Tooling comparison for re-ranking&lt;/h2&gt;
&lt;table&gt;
  &lt;thead&gt;
      &lt;tr&gt;
          &lt;th&gt;Approach&lt;/th&gt;
          &lt;th&gt;Examples&lt;/th&gt;
          &lt;th&gt;Pros&lt;/th&gt;
          &lt;th&gt;Cons&lt;/th&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr&gt;
          &lt;td&gt;Cross-encoder (self-hosted)&lt;/td&gt;
          &lt;td&gt;&lt;code&gt;sentence-transformers&lt;/code&gt; &lt;code&gt;CrossEncoder&lt;/code&gt;, small Hub models&lt;/td&gt;
          &lt;td&gt;Strong accuracy; no per-query API bill; full control&lt;/td&gt;
          &lt;td&gt;GPU latency; batching complexity at high QPS&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;Hosted rerank&lt;/td&gt;
          &lt;td&gt;Cohere rerank, Voyage, Jina rerank APIs&lt;/td&gt;
          &lt;td&gt;Fast integration; scales with vendor&lt;/td&gt;
          &lt;td&gt;Cost + egress; must pin API version behavior&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;LLM pointwise scoring&lt;/td&gt;
          &lt;td&gt;“Rate 0–5 how well this passage answers…”&lt;/td&gt;
          &lt;td&gt;Flexible rubric&lt;/td&gt;
          &lt;td&gt;Slow, expensive, judge drift; validate against humans&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td&gt;ColBERT-style late interaction&lt;/td&gt;
          &lt;td&gt;RAGatouille, ColBERT indexes&lt;/td&gt;
          &lt;td&gt;Excellent retrieval quality for some corpora&lt;/td&gt;
          &lt;td&gt;Heavier index + ops than flat vectors&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;Cross-encoder or hosted rerank&lt;/strong&gt; is the usual workhorse; LLM-as-judge for reranking is a last resort after simpler baselines fail.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Illustrative cross-encoder pass&lt;/strong&gt; (after you already have candidate strings &lt;code&gt;passages&lt;/code&gt;):&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; sentence_transformers &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; CrossEncoder
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;model &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; CrossEncoder(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;cross-encoder/ms-marco-MiniLM-L-6-v2&amp;#34;&lt;/span&gt;)  &lt;span style=&#34;color:#75715e&#34;&gt;# 2021 MS MARCO baseline, not a 2026 quality pick&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;pairs &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; [[query, p] &lt;span style=&#34;color:#66d9ef&#34;&gt;for&lt;/span&gt; p &lt;span style=&#34;color:#f92672&#34;&gt;in&lt;/span&gt; passages]
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;scores &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; model&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;predict(pairs)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;ranked &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; [p &lt;span style=&#34;color:#66d9ef&#34;&gt;for&lt;/span&gt; _, p &lt;span style=&#34;color:#f92672&#34;&gt;in&lt;/span&gt; sorted(zip(scores, passages), reverse&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;True&lt;/span&gt;)]
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;tight &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; ranked[:&lt;span style=&#34;color:#ae81ff&#34;&gt;8&lt;/span&gt;]
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Pin the &lt;code&gt;CrossEncoder&lt;/code&gt; weights the same way you pin Hub LLM revisions.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;hyde-and-query-expansion-controlled-experiments&#34;&gt;HyDE and query expansion: controlled experiments&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Query expansion&lt;/strong&gt; — Maintain a domain glossary JSON; at query time append synonyms, or ask a small LLM for 3 paraphrases and embed the centroid / run multi-query fusion (retrieve per variant, merge with max score). Log which variant hit gold.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;HyDE&lt;/strong&gt; — (1) Prompt LLM: “Write a short factual paragraph that would answer: …” (2) Embed that paragraph. (3) Search. &lt;strong&gt;A/B&lt;/strong&gt; behind a flag: measure precision@k on a holdout set; watch for hallucinated proper nouns in the synthetic paragraph polluting retrieval.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;lightweight-eval-harness-copy-paste-structure&#34;&gt;Lightweight eval harness (copy-paste structure)&lt;/h2&gt;
&lt;p&gt;Keep a &lt;code&gt;questions.jsonl&lt;/code&gt; with &lt;code&gt;question&lt;/code&gt;, &lt;code&gt;gold_chunk_ids[]&lt;/code&gt;, optional &lt;code&gt;metadata_filter&lt;/code&gt;. For each line:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Run retrieval (and optional rerank).&lt;/li&gt;
&lt;li&gt;Compute &lt;strong&gt;recall@k&lt;/strong&gt;: did any gold id appear in the top k returned ids?&lt;/li&gt;
&lt;li&gt;Emit a CSV: &lt;code&gt;question_id, gold_hit@20, gold_rank, latency_ms&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Gate merges on &lt;strong&gt;recall@k&lt;/strong&gt; not moving backward when you change chunking, embedder, or reranker. The “answer groundedness” layer in this post stacks on top once retrieval is no longer random.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Treat RAG as a &lt;strong&gt;product surface&lt;/strong&gt;. Log which chunk IDs supported each answer; wire request IDs through search and generation; and assume smaller backends will not hide bad retrieval.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;https://blog.veydh.com/2026/2026-01-lora-and-small-distilled-models-primer/&#34;&gt;LoRA: Fine-Tuning Small Models Without Full Weights&lt;/a&gt; picks up &lt;strong&gt;LoRA&lt;/strong&gt; on those same backends so domain tone and tools improve without full fine-tunes.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>LoRA: Fine-Tuning Small Models Without Full Weights</title>
      <link>https://blog.veydh.com/2026/2026-01-lora-and-small-distilled-models-primer/</link>
      <pubDate>Sat, 10 Jan 2026 00:00:00 +0000</pubDate>
      <author>Veydh Gooljar</author>
      
      <guid>https://blog.veydh.com/2026/2026-01-lora-and-small-distilled-models-primer/</guid>
      <description>&lt;h2 id=&#34;preamble&#34;&gt;Preamble&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Low-Rank Adaptation (LoRA)&lt;/strong&gt; is the compromise when a model should sound like &lt;em&gt;our&lt;/em&gt; support desk, respect &lt;em&gt;our&lt;/em&gt; JSON tool schema, or stop doing &lt;em&gt;that one thing&lt;/em&gt;—without paying the full price of updating every weight in a multi-billion-parameter checkpoint.&lt;/p&gt;
&lt;p&gt;The idea is elementary linear algebra dressed as a training trick: instead of learning a full update matrix for a layer, you learn a &lt;strong&gt;low-rank factorization&lt;/strong&gt; added to frozen weights. VRAM drops, iteration speed rises, and you can often ship &lt;strong&gt;adapter-only&lt;/strong&gt; artifacts that are easy to version beside your data.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;why-a-small-base-and-when-distilled-is-the-right-word&#34;&gt;Why a small base, and when “distilled” is the right word&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Small instruct checkpoints&lt;/strong&gt; (Mistral-7B-Instruct, Qwen instruct sizes, Llama 3.1 8B) trade some ceiling capability for &lt;strong&gt;throughput&lt;/strong&gt; and &lt;strong&gt;cost&lt;/strong&gt;. You can serve them on fewer GPUs or smaller batches. Most of those checkpoints were &lt;strong&gt;pretrained, then instruction-tuned&lt;/strong&gt;. They are not distilled just because they are small.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Distillation&lt;/strong&gt; is a separate procedure: a student is trained to imitate a larger teacher. Public examples include Llama 3.2 1B and 3B (pruned and distilled from Llama 3.1) and the DeepSeek-R1-Distill Qwen and Llama checkpoints. LoRA works on both kinds of base. The adapter is tied to the exact checkpoint you attach it to.&lt;/p&gt;
&lt;p&gt;The recipe below uses &lt;code&gt;mistralai/Mistral-7B-Instruct-v0.3&lt;/code&gt;. That is an instruct-tuned 7B, not a distilled student.&lt;/p&gt;
&lt;p&gt;LoRA sits on top of the size trade: you keep the frozen base as a stable anchor, then nudge behavior with a thin adapter trained on curated SFT data. You are not trying to re-teach the entire internet—just &lt;strong&gt;steer&lt;/strong&gt; tone, format, and domain vocabulary.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;what-actually-gets-trained&#34;&gt;What actually gets trained&lt;/h2&gt;
&lt;p&gt;Implementations differ, but the mental model is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Frozen&lt;/strong&gt;: most of the transformer—embedding tables and the bulk of attention/MLP weights stay put.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Trainable&lt;/strong&gt;: small matrices injected into chosen projections (&lt;code&gt;q_proj&lt;/code&gt;, &lt;code&gt;k_proj&lt;/code&gt;, &lt;code&gt;v_proj&lt;/code&gt;, &lt;code&gt;o_proj&lt;/code&gt;, sometimes MLP gates). The library merges or applies these at forward time.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Rank &lt;code&gt;r&lt;/code&gt;&lt;/strong&gt; controls adapter capacity. Tiny &lt;code&gt;r&lt;/code&gt; underfits quirky datasets; large &lt;code&gt;r&lt;/code&gt; inches toward full fine-tune behavior and cost.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Alpha scaling&lt;/strong&gt; (often paired with &lt;code&gt;r&lt;/code&gt;) scales the effective strength of the adapter. Both are tuned together rather than leaving defaults unquestioned.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Dropout&lt;/strong&gt; on adapter paths helps when the SFT set is small; it fights memorization of noisy examples.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;data-hygiene-beats-clever-hyperparameters&#34;&gt;Data hygiene beats clever hyperparameters&lt;/h2&gt;
&lt;p&gt;Datasets are versioned like code: &lt;strong&gt;git&lt;/strong&gt;, manifests, and hashes. Deduplication matters—paraphrased duplicates inflate metrics and encourage verbatim regurgitation. &lt;strong&gt;System&lt;/strong&gt; vs &lt;strong&gt;user&lt;/strong&gt; turns should be labeled or separated consistently so chat templates do not scramble during training.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;step-by-step-lora-with-transformers--peft-mental-checklist&#34;&gt;Step-by-step: LoRA with Transformers + PEFT (mental checklist)&lt;/h2&gt;
&lt;p&gt;This is the “one canonical recipe” kept stable; &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-mistral-huggingface-lora-training-notes/&#34;&gt;Fine-Tuning a Mistral-Class Checkpoint with LoRA on Hugging Face&lt;/a&gt; and &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-qwen-and-llama-distills-lora-on-hf/&#34;&gt;Qwen and LLaMA Checkpoints: LoRA Gotchas&lt;/a&gt; only swap tokenizer/template details.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Pin base&lt;/strong&gt; — &lt;code&gt;model_id&lt;/code&gt; + &lt;code&gt;revision&lt;/code&gt; (git commit on the Hub) for weights &lt;em&gt;and&lt;/em&gt; tokenizer JSON.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Choose targets&lt;/strong&gt; — Default: attention projections (&lt;code&gt;q_proj&lt;/code&gt;, &lt;code&gt;k_proj&lt;/code&gt;, &lt;code&gt;v_proj&lt;/code&gt;, &lt;code&gt;o_proj&lt;/code&gt;). Add MLP only if evals plateau and VRAM allows.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Set PEFT&lt;/strong&gt; — &lt;code&gt;LoraConfig(r=8 or 16, lora_alpha=16 or 32, lora_dropout=0.05, target_modules=[...], bias=&amp;quot;none&amp;quot;, task_type=&amp;quot;CAUSAL_LM&amp;quot;)&lt;/code&gt;. Treat &lt;code&gt;r&lt;/code&gt; and &lt;code&gt;alpha&lt;/code&gt; as &lt;strong&gt;coupled&lt;/strong&gt;: effective scale is roughly &lt;code&gt;alpha/r&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Load in bf16&lt;/strong&gt; — &lt;code&gt;model = AutoModelForCausalLM.from_pretrained(..., torch_dtype=torch.bfloat16)&lt;/code&gt; when the GPU supports it; enable &lt;strong&gt;gradient checkpointing&lt;/strong&gt; if sequence length × batch threatens OOM.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tokenize with chat template&lt;/strong&gt; — Build &lt;code&gt;messages&lt;/code&gt; list → &lt;code&gt;tokenizer.apply_chat_template(..., tokenize=True, return_tensors=&amp;quot;pt&amp;quot;, add_generation_prompt=False)&lt;/code&gt; for SFT; mask &lt;strong&gt;non-assistant&lt;/strong&gt; token positions with &lt;code&gt;-100&lt;/code&gt; in &lt;code&gt;labels&lt;/code&gt; so loss applies only where you want imitation (&lt;a href=&#34;https://blog.veydh.com/2026/2026-02-mistral-huggingface-lora-training-notes/&#34;&gt;Fine-Tuning a Mistral-Class Checkpoint with LoRA on Hugging Face&lt;/a&gt; expands Mistral-specific layout).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Train&lt;/strong&gt; — &lt;code&gt;Trainer&lt;/code&gt; or &lt;code&gt;SFTTrainer&lt;/code&gt; with small &lt;strong&gt;learning rate&lt;/strong&gt; (e.g. &lt;code&gt;1e-4&lt;/code&gt; to &lt;code&gt;2e-4&lt;/code&gt; for adapters, lower if unstable), &lt;strong&gt;cosine&lt;/strong&gt; or linear decay, &lt;strong&gt;weight decay&lt;/strong&gt; 0–0.1, &lt;strong&gt;max_steps&lt;/strong&gt; or &lt;strong&gt;epochs&lt;/strong&gt; chosen from a tiny dry run that completes without NaN.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Save&lt;/strong&gt; — &lt;code&gt;trainer.model.save_pretrained(&amp;quot;./lora-out&amp;quot;)&lt;/code&gt; saves &lt;strong&gt;adapter-only&lt;/strong&gt; shards; record dataset hash, seed, and CLI args beside the folder.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Load for inference&lt;/strong&gt; — &lt;code&gt;PeftModel.from_pretrained(base, &amp;quot;./lora-out&amp;quot;)&lt;/code&gt; or merge for deployment paths that require a single weight file.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Minimal wiring&lt;/strong&gt; (abbreviated; align with your model family’s &lt;code&gt;target_modules&lt;/code&gt; names):&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;&#34;&gt;&lt;code class=&#34;language-python&#34; data-lang=&#34;python&#34;&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; torch
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; transformers &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#f92672&#34;&gt;from&lt;/span&gt; peft &lt;span style=&#34;color:#f92672&#34;&gt;import&lt;/span&gt; LoraConfig, get_peft_model, TaskType
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;MODEL_ID &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;mistralai/Mistral-7B-Instruct-v0.3&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;REV &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&amp;lt;pin-a-commit-sha&amp;gt;&amp;#34;&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;tokenizer &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; AutoTokenizer&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;from_pretrained(MODEL_ID, revision&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;REV)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;model &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; AutoModelForCausalLM&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;from_pretrained(
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    MODEL_ID,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    revision&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;REV,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    torch_dtype&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;torch&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;bfloat16,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# Single-GPU training: let Trainer place the model.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# device_map=&amp;#34;auto&amp;#34; shards for inference. With Trainer plus gradient&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# checkpointing it often fails to produce gradients. Set use_cache off&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# before checkpointing; a cache fights that memory trade.&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;model&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;config&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;use_cache &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;False&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;lora &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; LoraConfig(
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    r&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ae81ff&#34;&gt;16&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    lora_alpha&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ae81ff&#34;&gt;32&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    lora_dropout&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ae81ff&#34;&gt;0.05&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    bias&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;none&amp;#34;&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    task_type&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;TaskType&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;CAUSAL_LM,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    target_modules&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;[&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;q_proj&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;k_proj&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;v_proj&amp;#34;&lt;/span&gt;, &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;o_proj&amp;#34;&lt;/span&gt;],
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;model &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; get_peft_model(model, lora)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;&lt;span style=&#34;color:#75715e&#34;&gt;# ... build tokenized dataset with masked labels, then:&lt;/span&gt;
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;args &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; TrainingArguments(
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    output_dir&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;./lora-run&amp;#34;&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    per_device_train_batch_size&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ae81ff&#34;&gt;1&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    gradient_accumulation_steps&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ae81ff&#34;&gt;8&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    learning_rate&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ae81ff&#34;&gt;2e-4&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    num_train_epochs&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ae81ff&#34;&gt;1&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    logging_steps&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ae81ff&#34;&gt;10&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    save_steps&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#ae81ff&#34;&gt;200&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    bf16&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;True&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;    gradient_checkpointing&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;True&lt;/span&gt;,
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;trainer &lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt; Trainer(model&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;model, args&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;args, train_dataset&lt;span style=&#34;color:#f92672&#34;&gt;=&lt;/span&gt;tokenized_train)
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;trainer&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;train()
&lt;/span&gt;&lt;/span&gt;&lt;span style=&#34;display:flex;&#34;&gt;&lt;span&gt;trainer&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;model&lt;span style=&#34;color:#f92672&#34;&gt;.&lt;/span&gt;save_pretrained(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;./lora-out&amp;#34;&lt;/span&gt;)
&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;Pros of this path:&lt;/strong&gt; battle-tested libraries, easy diff between runs, adapter artifacts stay small. &lt;strong&gt;Cons:&lt;/strong&gt; you still own data hygiene, template correctness, and eval gates—PEFT does not fix mis-tokenized chats.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&#34;conclusion&#34;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Pick &lt;strong&gt;one canonical training recipe&lt;/strong&gt;—Transformers + PEFT, or a higher-level runner—and change only data and hyperparameters between experiments. &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-mistral-huggingface-lora-training-notes/&#34;&gt;Fine-Tuning a Mistral-Class Checkpoint with LoRA on Hugging Face&lt;/a&gt; and &lt;a href=&#34;https://blog.veydh.com/2026/2026-02-qwen-and-llama-distills-lora-on-hf/&#34;&gt;Qwen and LLaMA Checkpoints: LoRA Gotchas&lt;/a&gt; walk &lt;strong&gt;family-specific&lt;/strong&gt; quirks (Mistral templates, Qwen tokenization, LLaMA RoPE) so the same LoRA discipline does not stumble on tokenizer details.&lt;/p&gt;
</description>
    </item>
    
  </channel>
</rss>
