<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rohit Kushwaha on Medium]]></title>
        <description><![CDATA[Stories by Rohit Kushwaha on Medium]]></description>
        <link>https://medium.com/@imrohitkushwaha2001?source=rss-9d49c6e4b94b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mHyqUtTdwNeQG64G39lSLA.jpeg</url>
            <title>Stories by Rohit Kushwaha on Medium</title>
            <link>https://medium.com/@imrohitkushwaha2001?source=rss-9d49c6e4b94b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 01:09:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imrohitkushwaha2001/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Your AI Training Data Could Be Exposing Personal Information. Here’s How to Fix It.]]></title>
            <link>https://medium.com/@imrohitkushwaha2001/your-ai-training-data-could-be-exposing-personal-information-heres-how-to-fix-it-43d39b34741f?source=rss-9d49c6e4b94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/43d39b34741f</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rohit Kushwaha]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 04:56:00 GMT</pubDate>
            <atom:updated>2026-11-19T04:56:00.918Z</atom:updated>
            <content:encoded><![CDATA[<p>AI models need data to learn. But real-world customer conversations are full of sensitive information.</p><p>Think about a simple support message:</p><p><em>“Hi, I’m Rahul Sharma. My email is </em><a href="/service/mailto:rahul@gmail.com"><em>rahul@gmail.com</em></a><em>, and I live at 221 Baker Street. I need help with my booking.”</em></p><p>If this message goes directly into an AI training dataset, personal information goes with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZ49xYC5bq6pzCbX1QsVJA.png" /><figcaption>PII Detection</figcaption></figure><p>So how do you remove sensitive information without destroying the meaning of the original text?</p><p>One practical approach is <strong>PII de-identification</strong>.</p><h3>1. Start with Microsoft Presidio</h3><p><a href="https://github.com/microsoft/presidio">Microsoft Presidio</a> is an open-source framework designed to detect and anonymize personally identifiable information (PII).</p><p>It has two key components:</p><ul><li><strong>Analyzer:</strong> Detects sensitive information and identifies its entity type.</li><li><strong>Anonymizer:</strong> Replaces, masks, or removes detected information.</li></ul><p>But detecting every type of personal information isn’t as simple as it sounds.</p><h3>2. Detect PII using different recognizers</h3><p>A reliable detection pipeline can combine three approaches.</p><p><strong>Regex and Pattern Matching</strong></p><p>Useful for structured information such as:</p><ul><li>Email addresses</li><li>Phone numbers</li><li>Credit card numbers</li><li>IDs</li></ul><p><strong>Named Entity Recognition (NER)</strong></p><p>Regex struggles with unstructured information such as people’s names and street addresses.</p><p>NER models help identify entities based on context.</p><p>For example, GLiNER can detect:</p><ul><li>PERSON: Rahul Sharma</li><li>LOCATION: New York</li><li>ADDRESS: 221 Baker Street</li></ul><p><strong>Custom Recognizers</strong></p><p>Generic models may not understand business-specific identifiers.</p><p>Custom recognizers allow you to detect domain-specific entities such as listing IDs, booking IDs, and gift card IDs.</p><h3>3. Replace real information with realistic fake data</h3><p>Once PII is detected, the next step is anonymization.</p><p>Instead of replacing everything with generic placeholders, you can use libraries like <a href="https://faker.readthedocs.io/">Faker</a> to generate realistic replacement values.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdQaydgVNORFQSOGh5EA4A.png" /></figure><p>This preserves the structure and readability of the original text while removing real personal information.</p><p>An important detail: replacements should remain consistent within a processing run. If the same person appears multiple times, they should receive the same fake identity in that run.</p><h3>4. Add a final PII verification layer</h3><p>Detection systems are not perfect. Some sensitive information can slip through.</p><p>A final verification step can scan the anonymized text again to identify any remaining PII.</p><p>If something is detected, the text can be sent back for reprocessing or manual review.</p><h3>5. Measure the quality</h3><p>A de-identification pipeline should be evaluated using:</p><ul><li><strong>Precision:</strong> How many detected entities were actually PII?</li><li><strong>Recall:</strong> How much of the actual PII did the system detect?</li><li><strong>Throughput:</strong> How much text can the pipeline process?</li></ul><p>These metrics help balance privacy, accuracy, and processing speed.</p><h3>The Bigger Picture</h3><p>Building a PII de-identification pipeline isn’t just about finding email addresses and phone numbers.</p><p>It requires combining multiple techniques:</p><p><strong>Regex + NER + Custom Recognizers + Anonymization + Final Verification</strong></p><p>The goal is simple: make data safe enough to use while preserving as much of its original meaning as possible.</p><p>That’s what makes high-quality de-identification an important part of building production-ready AI systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43d39b34741f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your AI Agents Are Burning Money on Simple Questions! Here’s How to Cut LLM Costs by 30–50%]]></title>
            <link>https://medium.com/@imrohitkushwaha2001/your-ai-agents-are-burning-money-on-simple-questions-heres-how-to-cut-llm-costs-by-30-50-c8c59f711b8f?source=rss-9d49c6e4b94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c59f711b8f</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <dc:creator><![CDATA[Rohit Kushwaha]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 05:12:28 GMT</pubDate>
            <atom:updated>2026-11-18T05:12:28.877Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What if your AI agent didn’t need an LLM for every single question? A hybrid architecture combining PyBot, deterministic execution, semantic caching, and AI-powered quality gates could significantly reduce inference costs without sacrificing answer quality.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9tfd-I-XH_teXD6qyN3ug.png" /></figure><h3>1. The Hidden Cost Problem in Agentic AI</h3><p>We are building increasingly powerful AI agents.</p><p>They can connect to databases, call APIs, search documents, execute workflows, analyze data, and even coordinate with other agents.</p><p>But there is one problem that most agentic systems still have:</p><p><strong>We are using expensive LLMs to solve problems that don’t always require an LLM.</strong></p><p>Consider a CRM application with an AI assistant.</p><p>A user asks:</p><ul><li>How many leads came in today?</li><li>Show my pending leads.</li><li>Which deals are closing this week?</li><li>Show my overdue tasks.</li><li>What is our total revenue this month?</li></ul><p>These are normal questions in a business application.</p><p>The agent receives the query, sends it to an LLM, generates SQL or calls a tool, processes the result, and generates a response.</p><p>But think about it.</p><p>Does every one of these queries really need an expensive LLM for reasoning?</p><p>Not necessarily.</p><p>Most of these questions involve understanding an intent, extracting a few parameters, retrieving structured data, and formatting a response.</p><p>We can handle a significant portion of these operations using lightweight processing and deterministic execution.</p><p>This leads to an interesting architectural question:</p><p><strong>Can we make an LLM-powered system intelligent enough to know when NOT to use an LLM?</strong></p><p>Let’s explore how.</p><h3>2. Introducing PyBot: A Chatbot Without an LLM</h3><p>Recently, Hugging Face introduced an interesting experimental project called <a href="https://github.com/huggingface/pybot">PyBot</a>.</p><p>The concept is unusual.</p><p>It is a chatbot written entirely in Python, without neural network weights, model training, or an inference engine.</p><p>It uses:</p><ul><li>Python rules and conditional logic.</li><li>Regular expressions.</li><li>Pattern matching.</li><li>Lookup tables.</li><li>Conversation memory.</li><li>A knowledge base.</li><li>Multiple response modules.</li></ul><p>What makes this project particularly interesting is how it was developed.</p><p>Hugging Face used a swarm of more than 1,000 AI coding agents to build it.</p><p>According to the project’s authors, these agents:</p><ul><li>Worked on different parts of the chatbot.</li><li>Exchanged approximately 175,000 messages.</li><li>Merged around 8,000 pull requests.</li><li>Evaluated more than 5,000 versions.</li></ul><p>The resulting project contains approximately 640,000 lines of Python code and 550,000 lines of tests.</p><p>Its reported SmolTalkBench win rate improved from 0% to 26%.</p><p>This is a benchmark comparison, not a claim of 26% general-purpose accuracy.</p><p>The interesting takeaway isn’t that PyBot can replace ChatGPT.</p><p>It is that a sufficiently extensive collection of deterministic rules can handle a surprising range of everyday conversational interactions.</p><p>And that creates an interesting opportunity for existing AI architectures.</p><h3>3. Why Do We Need an LLM for Every Query?</h3><p>Let’s take a practical example.</p><p>Imagine an AI assistant integrated into a CRM.</p><p>A user asks:</p><p><strong>“How many leads did we receive today?”</strong></p><p>A typical LLM-powered workflow might look like this:</p><ol><li>Receive the user query.</li><li>Send the query and conversation context to an LLM.</li><li>Ask the LLM to understand the intent.</li><li>Generate a SQL query or select a database tool.</li><li>Execute the query.</li><li>Send the result back to the LLM.</li><li>Generate a natural-language response.</li></ol><p>Now consider another question:</p><p><strong>“How many new leads came in today?”</strong></p><p>The intent is almost identical.</p><p>The system still needs to understand the question, retrieve the lead count, and return the answer.</p><p>We are potentially paying for repeated reasoning when the underlying operation is relatively simple.</p><p>This is where a lightweight processing layer can help.</p><p>Instead of sending every request directly to an LLM, we can introduce a system that handles routine queries first.</p><h3>4. The Proposed Architecture: PyBot + Quality Gate + LLM Fallback</h3><p>The idea is to introduce PyBot as the first processing layer.</p><p>However, PyBot alone is not a complete CRM query engine. We need to integrate it with our application’s database, APIs, and business logic.</p><p>The proposed architecture looks like this:</p><pre>flowchart TD<br>    A[&quot;User Query&quot;] --&gt; B[&quot;PyBot Engine&quot;]</pre><pre>    DB[(&quot;CRM Database / APIs&quot;)] &lt;--&gt; B</pre><pre>    B --&gt; C[&quot;Generate Candidate Answer + Context&quot;]</pre><pre>    C --&gt; D[&quot;AI Quality Evaluator&quot;]</pre><pre>    D --&gt; E{&quot;Quality Gate 1: Context Valid?&quot;}</pre><pre>    E --&gt;|Yes| F{&quot;Quality Gate 2: Answer Quality Pass?&quot;}</pre><pre>    E --&gt;|No| H[&quot;LLM Fallback&quot;]</pre><pre>    F --&gt;|Yes| G[&quot;Return PyBot Answer&quot;]</pre><pre>    F --&gt;|No| H</pre><pre>    H --&gt; I[&quot;LLM Reasoning / Agent / RAG&quot;]</pre><pre>    I --&gt; J[&quot;Post-Answer Validation&quot;]</pre><pre>    J --&gt; K[&quot;Final Response&quot;]</pre><pre>    G --&gt; L[&quot;User&quot;]<br>    K --&gt; L</pre><pre>    D -.-&gt; M[&quot;Monitoring and Evaluation&quot;]<br>    H -.-&gt; M</pre><p>Let’s understand each component.</p><h3>Step 1: User Query</h3><p>The user can ask a question in natural language.</p><p>For example:</p><ul><li>How many leads today?</li><li>Show me pending leads.</li><li>Give me a summary of this month’s revenue.</li><li>Any overdue tasks assigned to me?</li></ul><p>The user doesn’t need to know whether the underlying system uses rules, SQL, an LLM, or a combination of these.</p><h3>Step 2: PyBot Engine</h3><p>PyBot receives the query first.</p><p>Its job is to understand the user’s intent, identify relevant context, and propose a response or structured operation.</p><p>For example:</p><p>User:</p><p>“How many leads did we receive today?”</p><p>PyBot should ideally identify:</p><pre>{<br>  &quot;intent&quot;: &quot;count_leads&quot;,<br>  &quot;entity&quot;: &quot;leads&quot;,<br>  &quot;filters&quot;: {<br>    &quot;created_at&quot;: &quot;today&quot;<br>  }<br>}</pre><p>Now consider these variations:</p><ul><li>How many new leads came in today?</li><li>Show me today’s leads.</li><li>Give me the number of leads created today.</li><li>Any new leads since morning?</li></ul><p>A capable understanding layer should map these variations to the same underlying intent.</p><p>This is an important part of the experiment.</p><p>We should test PyBot’s actual understanding and parameter extraction against real application queries instead of assuming every variation will work.</p><h3>Step 3: Database / API Integration</h3><p>Understanding a query is not enough.</p><p>The system needs real data.</p><p>For CRM applications, we can connect PyBot’s output to existing database queries, APIs, and business functions.</p><p>For example:</p><pre>SELECT COUNT(*)<br>FROM leads<br>WHERE DATE(created_at) = CURRENT_DATE;</pre><p>The database returns the actual count.</p><p>PyBot or the application layer can then format a candidate answer:</p><p>“Your CRM received 42 new leads today.”</p><p>Notice something important here.</p><p>We are not asking an LLM to calculate the number, interpret the database result, or generate an unnecessary SQL query every time.</p><p>The application executes a predefined, validated operation.</p><h3>Step 4: AI-Powered Quality Gate</h3><p>This is where the architecture becomes interesting.</p><p>We don’t want PyBot to return an answer simply because it found a matching rule.</p><p>We need to validate whether the generated answer actually addresses the user’s request.</p><p>For this, we can integrate an AI-based evaluator.</p><p>Potential options include:</p><ul><li>Gemini models.</li><li>OpenAI models and decision/evaluation workflows.</li><li>TypeSafe’s Jev.</li><li>Other lightweight evaluation models.</li></ul><p>The evaluator receives:</p><ol><li>Original user query.</li><li>Conversation context.</li><li>PyBot’s interpretation.</li><li>Retrieved database records or evidence.</li><li>Generated answer.</li></ol><p>It evaluates whether the answer is relevant, supported by the available data, and consistent with the requested context.</p><p>We can implement two quality gates.</p><p><strong>Quality Gate 1: Context Validation</strong></p><p>Check:</p><ul><li>Was the user’s intent understood correctly?</li><li>Were important filters extracted?</li><li>Is the required conversation context available?</li><li>Are any mandatory parameters missing?</li></ul><p><strong>Quality Gate 2: Answer Validation</strong></p><p>Check:</p><ul><li>Does the answer address the original query?</li><li>Does it match the retrieved records?</li><li>Is there any factual mismatch?</li><li>Is the answer supported by the available evidence?</li></ul><p>We can introduce configurable thresholds.</p><p>A score of 0.90 can be an initial experimental threshold, but it must be calibrated using real evaluation data.</p><p>Also, an important point: an LLM evaluator is not a perfect truth detector. For database-driven answers, deterministic validation of the SQL, permissions, filters, and returned records should remain the primary source of truth.</p><h3>Step 5: LLM Fallback</h3><p>What happens when PyBot cannot understand a query or generate a reliable answer?</p><p>We route it to our existing LLM-based agent.</p><p>The LLM receives:</p><ul><li>Original user query.</li><li>Conversation history.</li><li>PyBot’s interpretation.</li><li>Retrieved data, if available.</li><li>Quality gate’s failure reason.</li></ul><p>Now the LLM can perform more complex reasoning, use RAG, call tools, or generate an alternative answer.</p><p>The LLM-generated response should also go through appropriate validation before being returned.</p><p>This means the LLM is no longer the default processor for every request.</p><p>It becomes the fallback reasoning engine for cases where lightweight processing is insufficient.</p><h3>5. PyBot vs Semantic Caching: Are They the Same?</h3><p>No.</p><p>Both approaches can reduce LLM calls, but they solve different problems.</p><p>Semantic caching is already an established optimization technique in LLM applications.</p><p>It stores previous queries and their responses as embeddings or semantic representations.</p><p>When a similar query arrives, the system checks whether a sufficiently similar query has already been answered.</p><p>If a valid match exists, it can return the cached result without calling the LLM.</p><p>PyBot takes a different approach.</p><p>It attempts to understand and process new conversational inputs through predefined rules, patterns, memory, and knowledge.</p><p>There is an important opportunity here.</p><p><strong>We can combine Semantic Caching and PyBot instead of choosing only one.</strong></p><p>For example:</p><ol><li>Check whether a valid semantic cache entry exists.</li><li>If not, send the query to PyBot.</li><li>Retrieve live data from the database when required.</li><li>Validate the answer.</li><li>If validation fails, route to the LLM.</li></ol><p>However, cache keys and cache validation must account for tenant, user permissions, filters, and data freshness.</p><p>A query from one CRM user must never return another user’s cached data.</p><h3>6. How Much Can We Actually Save?</h3><p>Let’s use a practical example.</p><p>Suppose an AI-powered application currently spends:</p><p><strong>$100 per day on LLM inference.</strong></p><p>Assume the system receives a mixture of routine and complex queries.</p><p>If PyBot and deterministic processing successfully resolve some queries, the number of LLM calls decreases.</p><p>Here is a simplified calculation.</p><p>Queries resolved without LLMRemaining LLM expenditureGross daily savings10%$90$1020%$80$2030%$70$3040%$60$4050%$50$50</p><p>Assumptions:</p><ul><li>Initial LLM expenditure is $100/day.</li><li>Average LLM cost per query remains approximately equal.</li><li>The percentages represent successfully resolved queries, not merely queries routed to PyBot.</li><li>Verifier and infrastructure costs are excluded.</li></ul><p>Let’s look at the potential monthly impact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FmItXoyjjOVyC2k9xoOkow.png" /></figure><p>These numbers are illustrative, not measured PyBot performance.</p><p>Actual savings depend on query distribution, token consumption, model pricing, and the cost of the additional processing layers.</p><p>For example, if the quality evaluator costs $0.005 per query and evaluates 10,000 queries daily, that’s another $50/day.</p><p>That could eliminate much of the expected saving.</p><p>Therefore, we need to measure the complete architecture rather than just counting avoided LLM calls.</p><p>The actual calculation should be:</p><p><strong>Net Savings = Avoided LLM Cost − Verification Cost − PyBot Infrastructure Cost − Additional Operational Cost</strong></p><p>The goal should be to maximize verified direct resolutions at the lowest possible total cost.</p><h3>7. Which Queries Can We Handle Without an LLM?</h3><p>This is where CRM and business applications become particularly interesting.</p><p>A large number of queries in these applications are structured around existing business data.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzoAPL1XGbiCXr_WOMOGTw.png" /></figure><p>But there is another important detail.</p><p>Users rarely ask questions in exactly the same way.</p><p>For example:</p><p>“Show pending leads.”</p><p>Then:</p><p>“Only the ones assigned to me.”</p><p>Then:</p><p>“What about those created this week?”</p><p>The system needs to maintain conversational context and correctly update the filters.</p><p>This is where we should evaluate PyBot’s understanding engine and memory capabilities.</p><p>If it can correctly understand these variations, we can potentially handle a larger portion of routine application queries without using an LLM.</p><p>However, the database execution layer must still enforce authorization, tenant isolation, and business rules.</p><h3>8. Runtime Evaluation: Make the System Better Over Time</h3><p>One more interesting component is runtime monitoring.</p><p>Every time PyBot fails the quality gate, we should record why.</p><p>For example:</p><pre>{<br>  &quot;original_query&quot;: &quot;Show me the deals that might close soon&quot;,<br>  &quot;pybot_intent&quot;: &quot;list_deals&quot;,<br>  &quot;failure_reason&quot;: &quot;Missing closing probability context&quot;,<br>  &quot;quality_score&quot;: 0.54,<br>  &quot;fallback_used&quot;: true<br>}</pre><p>Over time, we can analyze these failures.</p><p>Possible improvements include:</p><ul><li>Adding new patterns to PyBot.</li><li>Improving intent mappings.</li><li>Adding missing database operations.</li><li>Improving conversation memory.</li><li>Fixing ambiguous query handling.</li><li>Improving the fallback routing logic.</li></ul><p>We can also use these logs to create new test cases automatically.</p><p>This creates a feedback loop:</p><p><strong>User Query → PyBot → Quality Evaluation → Fallback → Failure Logging → Improvement → Better Coverage</strong></p><p>The important thing is that runtime logs should help improve the system through controlled updates and evaluation, rather than automatically trusting every LLM-generated correction.</p><h3>9. How Should We Implement This?</h3><p>I would approach implementation in five phases.</p><h3>Phase 1: Understand Your Query Distribution</h3><p>Before writing any code, analyze real application queries.</p><p>Collect approximately 1,000 representative queries.</p><p>Categorize them into:</p><ul><li>Simple database queries.</li><li>Filtering and sorting.</li><li>Aggregations.</li><li>Conversational follow-ups.</li><li>Complex reasoning.</li><li>RAG-based queries.</li></ul><p>This tells us how much of the existing workload can realistically be handled without an LLM.</p><h3>Phase 2: Integrate PyBot</h3><p>Clone the <a href="https://github.com/huggingface/pybot">PyBot repository</a> and evaluate its existing capabilities.</p><p>Don’t immediately modify its entire codebase.</p><p>Start by building an adapter around it.</p><p>The adapter should convert PyBot’s understanding into structured application intents and parameters.</p><p>For example:</p><pre>{<br>  &quot;intent&quot;: &quot;list_leads&quot;,<br>  &quot;filters&quot;: {<br>    &quot;status&quot;: &quot;pending&quot;,<br>    &quot;assigned_to&quot;: &quot;current_user&quot;<br>  }<br>}</pre><p>Then connect those intents to validated database functions.</p><h3>Phase 3: Implement the Quality Gate</h3><p>Integrate one evaluator first.</p><p>It could be Gemini, OpenAI, Jev, or another suitable evaluation model.</p><p>Define a structured evaluation output:</p><pre>{<br>  &quot;context_valid&quot;: true,<br>  &quot;answer_relevant&quot;: true,<br>  &quot;evidence_supported&quot;: true,<br>  &quot;missing_context&quot;: false,<br>  &quot;confidence&quot;: 0.96,<br>  &quot;decision&quot;: &quot;ACCEPT&quot;<br>}</pre><p>The routing engine can use this output to decide whether to return the candidate answer or invoke the LLM.</p><p>Do not treat the confidence score as a guarantee of correctness.</p><h3>Phase 4: Implement LLM Fallback</h3><p>Connect the existing agent or LLM workflow.</p><p>When PyBot fails validation, pass the original context and failure reason to the LLM.</p><p>Validate the resulting response and provide a safe fallback if it still cannot answer reliably.</p><h3>Phase 5: Measure Everything</h3><p>Run the same query dataset against four configurations:</p><ol><li>Existing LLM-only architecture.</li><li>PyBot-only architecture.</li><li>PyBot + Quality Gate + LLM fallback.</li><li>Semantic Cache + PyBot + Quality Gate + LLM fallback.</li></ol><p>Compare:</p><ul><li>Answer accuracy.</li><li>Intent understanding accuracy.</li><li>Context preservation.</li><li>False acceptance rate.</li><li>LLM calls avoided.</li><li>Total cost per query.</li><li>Average response latency.</li></ul><p>This will tell us whether the new architecture is actually better.</p><h3>10. The Bigger Picture: Stop Treating LLMs as the Default for Everything</h3><p>LLMs are incredibly powerful.</p><p>But not every application operation requires their reasoning capabilities.</p><p>If a user asks for a database count, we don’t necessarily need an LLM to reason about that count.</p><p>If a user asks for a simple filter, we don’t necessarily need an expensive model to construct the same operation repeatedly.</p><p>If a user asks a complex question requiring reasoning across multiple sources, that’s where an LLM becomes valuable.</p><p>The future of cost-efficient agentic systems might not be about finding cheaper LLMs alone.</p><p>It might be about designing better architectures that use LLMs only when they provide meaningful value.</p><p>PyBot makes this idea particularly interesting because it demonstrates how far a large collection of explicit conversational rules can go.</p><p>Combining that idea with deterministic database execution, semantic caching, and an AI-powered quality gate gives us a practical architecture to experiment with.</p><p><strong>The objective isn’t to replace LLMs. It’s to stop paying for LLM reasoning when deterministic processing is already enough.</strong></p><h3>Final Thoughts</h3><p>If I were optimizing an existing AI-powered CRM or agentic application today, I would start with one simple experiment.</p><p>Take 1,000 real user queries.</p><p>Run them through a lightweight processing layer first.</p><p>Validate the results.</p><p>Route only failed or genuinely complex queries to an LLM.</p><p>Then compare the total cost and answer quality against the existing architecture.</p><p>Even a verified 20–30% reduction in LLM usage could produce meaningful savings at scale.</p><p>And if the application has a large volume of repetitive, structured queries, exploring a 40–50% reduction target could be worthwhile.</p><p>The real opportunity is not another model.</p><p><strong>It’s a smarter way to decide when a model is actually needed.</strong></p><h3>References &amp; Further Reading</h3><ol><li><a href="https://github.com/huggingface/pybot">Hugging Face — PyBot: Can Python Be a Chatbot?</a></li><li><a href="https://github.com/huggingface/pybot">Hugging Face — PyBot GitHub Repository</a></li></ol><p>#ArtificialIntelligence #AgenticAI #LLM #AIEngineering #HuggingFace #PyBot #SemanticCaching #CostOptimization #GenerativeAI #SoftwareArchitecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c59f711b8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[S3 Is Way Cheaper Than EBS. So Why Does Nobody Run Kafka on It?]]></title>
            <link>https://medium.com/@imrohitkushwaha2001/s3-is-way-cheaper-than-ebs-so-why-does-nobody-run-kafka-on-it-85b466f9dbfe?source=rss-9d49c6e4b94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b466f9dbfe</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Rohit Kushwaha]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 05:14:44 GMT</pubDate>
            <atom:updated>2026-11-07T05:14:44.895Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The answer has less to do with speed than you think, and it changed how I look at cloud storage.</em></p><p>A few days ago I asked myself a question that felt almost too simple.</p><p>Amazon S3 is cheap and it can hold practically unlimited data. EBS costs more. So why do companies running Kafka on AWS keep their data on EBS instead of just dumping everything into S3 and saving money?</p><p>I assumed the answer would be “S3 is slow.” That turned out to be only part of the story. The real reason is more interesting, and once it clicked, a lot of other cloud design decisions started making sense too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1CvL7IW4hA68qzmn2zpQTg.png" /><figcaption>EBS vs S3</figcaption></figure><p>Let me walk you through it the way I wish someone had explained it to me.</p><h3>First, what are these two things, really?</h3><p>Forget the official definitions for a minute.</p><p><strong>EBS</strong> is like an extra hard drive plugged into your server. Your server sees it as a normal disk. You can create folders on it, open a file, change one small part of it, add a few lines at the end, and save. Databases and apps treat it exactly like the drive inside your laptop.</p><p><strong>S3</strong> is more like Google Drive for your applications. You upload a file, you download a file, you delete a file. Every action is a request sent over the internet-style connection to Amazon’s storage service. It is incredibly reliable and can store almost endless amounts of data, but you don’t work <em>inside</em> a file the way you do on a disk. You hand files over and ask for them back.</p><p>That difference, working inside a file versus handing whole files back and forth, is the heart of this entire article.</p><h3>How Kafka actually stores your messages</h3><p>To see why this matters, you need to know one thing about how Kafka works.</p><p>Think of Kafka as a giant diary. Every time a new message arrives, Kafka writes it as a new line at the end of the diary. It never goes back and edits old lines. It just keeps adding, line after line, very fast.</p><p>On the other side, the apps reading from Kafka each keep a bookmark. One app might be reading the latest lines. Another app might be catching up from yesterday. Another might suddenly say “take me back to line 4,500,000” because it crashed and needs to replay old data.</p><p>So Kafka needs storage that can do three things well:</p><ol><li>Add small pieces of data to the end of a file, constantly, without delay.</li><li>Let readers start from any position in that file.</li><li>Do all of this at a steady, predictable pace, even when millions of messages arrive every second.</li></ol><p>A normal disk is built for exactly this. And EBS behaves like a normal disk.</p><h3>So why not just use S3?</h3><p>Here’s where it gets clear.</p><p><strong>Reason 1: You can’t simply add a line to a regular S3 file.</strong></p><p>On a disk, Kafka opens a file and keeps writing to the end of it. With a regular S3 bucket, there’s no “open the file and keep adding” option. If you want to change a file, you upload the whole thing again. Imagine having to re-send your entire diary to Google Drive every time you write one new sentence. That’s the problem in a nutshell.</p><p><strong>Reason 2: Every action is a separate request over the network.</strong></p><p>Each upload or download to S3 is its own request. For big files that’s perfectly fine. But Kafka deals with a flood of tiny writes. Sending a separate request for each small batch adds waiting time, and on top of that, AWS charges you for every request. Millions of small requests can quietly turn “cheap storage” into an expensive bill.</p><p><strong>Reason 3: Readers jump around.</strong></p><p>Remember the bookmarks? When a reader asks for data from a specific position, Kafka needs to grab that exact spot quickly. On a disk, that’s routine. Doing it constantly through S3 requests adds delay and cost every single time.</p><p>So the real issue isn’t just “S3 is slower.” The bigger issue is that <strong>S3 works with whole files, while Kafka needs to work inside files.</strong> It’s the wrong shape of tool for the job, not just a slower version of the right one.</p><h3>The plot twist: S3 is actually great for Kafka</h3><p>This is the part I didn’t expect.</p><p>Kafka data has a natural life cycle. Fresh messages are read all the time. Messages from last week are read rarely, maybe only when someone needs to replay history or debug something.</p><p>Newer versions of Kafka support something called <strong>tiered storage</strong>, and the idea is simple:</p><ul><li>Recent data stays on EBS, where it’s fast to write and read.</li><li>Older data gets moved to S3, where it’s much cheaper to keep.</li></ul><p>For example, a company might keep the last 24 hours of messages on EBS and push everything older to S3. If someone asks for a message from seven days ago, Kafka quietly fetches that older chunk from S3. It takes a bit longer, but since it happens rarely, nobody minds.</p><p>The result: you get the speed of a disk for today’s work and the low price of S3 for your history. You stop paying premium disk prices for data nobody touches.</p><p>There’s even a newer wave of Kafka-compatible systems designed to sit directly on S3. They work around the problems above by collecting lots of messages into bigger batches before uploading them, and they accept a little extra delay in exchange for much lower storage costs. That tells you the tradeoff is real, and engineers are actively playing with it.</p><h3>Where else does each one show up?</h3><p>Once you understand the “work inside a file” versus “hand over whole files” idea, you start seeing the pattern everywhere.</p><p><strong>EBS shows up wherever software needs a real working disk:</strong></p><ul><li>Databases like PostgreSQL and MySQL, which constantly update small parts of their files.</li><li>Search engines like Elasticsearch, which store their search indexes on disk.</li><li>Kafka’s active, recent data.</li><li>The main system drive of almost every EC2 server.</li></ul><p><strong>S3 shows up wherever you need to store lots of complete files:</strong></p><ul><li>Photos, videos and documents uploaded by users.</li><li>Backups of databases.</li><li>Old logs you want to keep but rarely read.</li><li>Huge datasets for analytics and machine learning, plus saved copies of trained models.</li></ul><p>Netflix is a well-known example. They’ve written publicly that their main data warehouse sits on S3, organized into a table format called Iceberg, which Netflix itself originally created. Massive amounts of data, read in big chunks for analysis. That’s the kind of work S3 is built for.</p><p>Picture a typical AI app built on AWS. The app server runs on EC2 with an EBS drive. The PostgreSQL database lives on EBS. Kafka’s recent messages live on EBS. But the PDFs users upload, the training data, the saved models and the nightly backups all go to S3. Each piece of data lands where its usage pattern fits best.</p><h3>Three things I had to unlearn</h3><p>While digging into this, a few of my assumptions turned out to be wrong.</p><p><strong>“EBS is a physical disk inside my server.”</strong> It isn’t. EBS is connected to your server over Amazon’s network. It just behaves like a local disk. If you want a disk that’s physically inside the machine, AWS offers that separately as “instance store,” and some teams do run Kafka on it.</p><p><strong>“EBS is always faster than S3.”</strong> Not always. It depends on which type of EBS volume you pick and what kind of work you’re doing. For downloading huge files in parallel, S3 can move an enormous amount of data. The difference shows up most with small, frequent reads and writes.</p><p><strong>“S3 is always cheaper.”</strong> The price per gigabyte is lower, yes. But you also pay per request and for moving data out. A workload with millions of tiny operations can end up costing more on S3 than you’d expect.</p><h3>The one line worth remembering</h3><p>If you take nothing else from this article, take this:</p><p><strong>EBS is your working desk. S3 is your storage room.</strong></p><p>You do your daily work on the desk, where everything is within reach and you can scribble, edit and flip pages instantly. You keep the old files in the storage room, where there’s endless space and it costs very little, but you don’t sit in there to do your daily work.</p><p>Kafka needs a desk. Its history belongs in the storage room. And the smartest setups use both.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b466f9dbfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your AI Agent Has 200 Tools. It Should Only See 3 at a Time.]]></title>
            <link>https://medium.com/@imrohitkushwaha2001/your-ai-agent-has-200-tools-it-should-only-see-3-at-a-time-0a0310d788f6?source=rss-9d49c6e4b94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a0310d788f6</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rohit Kushwaha]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 05:00:48 GMT</pubDate>
            <atom:updated>2026-10-21T05:00:48.351Z</atom:updated>
            <content:encoded><![CDATA[<p>Picture this. You’re building an AI agent for a company, and it needs to work with everything the team already uses: Salesforce, HubSpot, Slack, Gmail, Google Calendar, a few databases, a ticketing system, and a long tail of other tools. On a good day, that’s a couple of hundred different operations the agent could perform.</p><p>Then a user walks up and asks something simple: “Find all the pending support tickets for this customer.”</p><p>Here’s the question worth sitting with for a second. To answer that, does your agent really need to know how to send an email, book a calendar slot, update a CRM deal, and run a database report? Of course not. It needs the handful of tools that deal with support tickets. Nothing else.</p><p>Yet in most tool-calling setups, that’s exactly what happens. The application hands the model every tool definition it owns, right at the start of the request. With ten tools, fine. With two hundred, you’re paying a tax on every single message, whether those tools get used or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3hFkG0HSe-85w-Wqkns8A.png" /><figcaption>dynamic tool loading</figcaption></figure><p>That tax is the reason dynamic tool loading exists.</p><h3>So what is it, really?</h3><p>Dynamic tool loading is a simple idea with a slightly clumsy name. Instead of putting every tool definition in front of the model at the start, you make those definitions available only when the model actually needs them. The catalog is there. The model just doesn’t carry all of it around at once.</p><p>To see why that matters, it helps to look at what a tool definition actually is.</p><p>Say you’ve got a CRM tool for looking up a customer. Its definition might read something like this:</p><pre>{<br>  &quot;name&quot;: &quot;search_customer&quot;,<br>  &quot;description&quot;: &quot;Search for a customer in the CRM&quot;,<br>  &quot;parameters&quot;: {<br>    &quot;customer_id&quot;: &quot;string&quot;<br>  }<br>}</pre><p>That’s one tool. A name, a description, the parameters it takes, the shape of its input. Short on its own. Now multiply it by two hundred and feed all of it to the model on every request. Most of those definitions describe things the user never asked about, and the model has to read past them anyway.</p><p>The dynamic version flips the order. The user asks for something, the model works out what kind of operation that needs, it searches for tools that fit, the system hands back only the matching definitions, and the model picks one and runs it. The full schema for everything else never shows up.</p><p>OpenAI describes this in its own docs under tool search and deferred tool loading. We’ll get to the specifics in a bit.</p><h3>What this looks like in the wild</h3><p>Take an assistant wired into a stack like this:</p><ul><li>Salesforce, for searching customers, creating leads, updating opportunities</li><li>HubSpot, for finding contacts and updating deals</li><li>Slack, for searching and sending messages</li><li>Gmail, for searching emails and drafting replies</li><li>Google Calendar, for finding events and setting up meetings</li><li>Jira, for searching issues and creating tickets</li><li>A database, for querying records and pulling reports</li></ul><p>As integrations pile up, you can easily end up with hundreds of operations. Now a user asks:</p><p>“Find the latest email from this customer and open a Jira ticket describing the issue they reported.”</p><p>Two steps. Find the email, then file the ticket. And notice what the agent doesn’t need along the way: it never has to touch Salesforce, HubSpot, Calendar, or any of the rest. It just needs to find the right email-search tool and the right ticket-creation tool, and wire them together.</p><p>Roughly, the flow goes like this:</p><pre>                 User request<br>                        |<br>                        v<br>                      AI agent<br>                        |<br>                        v<br>          Search for the tools this task needs<br>                        |<br>            +-----------------------+<br>            |                       |<br>            v                       v<br>      Email search          Jira ticket creation<br>            |                       |<br>            v                       v<br>     Retrieve the email        Create the ticket<br>            |                       |<br>            +-----------+-----------+<br>                        |<br>                        v<br>                   Final response</pre><p>That’s the shape of it, not a literal blueprint. The exact steps depend on your framework, and in practice the agent often runs the two operations one after another rather than in parallel. The point that holds across all of it: the system discovers the tools the task needs instead of laying the whole catalog on the table.</p><h3>The problems it actually solves</h3><p>This is where the idea stops being clever and starts being useful.</p><p><strong>The context bill.</strong> Every tool definition in a request eats into the model’s input context. Imagine two hundred tools whose definitions together run to something like thirty thousand tokens. That’s thirty thousand tokens spent describing what the agent can do, before a single word of the user’s actual problem gets a look in. If the task needs three of those tools, the model still had to wade through the other hundred and ninety-seven. Load them only when they’re wanted, and that budget goes back to instructions, conversation history, and the work itself. How much you save depends on how many schemas there are, how big they are, and how the search is wired, but the direction is clear.</p><p>One honest caveat: deferred loading doesn’t always hide everything. Depending on how it’s built, the model may still see tool names or short descriptions before it pulls the full schemas. It’s leaner, not invisible.</p><p><strong>Picking the right tool gets harde</strong>r. Say your agent has a cluster of lookups: search_customer, search_customer_orders, search_customer_emails, search_customer_tickets, search_customer_transactions. All related, all subtly different. The more near-identical options sit in front of the model, the easier it is to grab the wrong one. Narrowing the field to what the request is actually about takes some of that pressure off. It’s not a guarantee, though. Search can surface the wrong tools, and the model can still misfire on the right list. Good descriptions and sane validation still earn their keep.</p><p><strong>The catalog outgrows the limits. </strong>Some providers cap how many tool definitions, or how much total size, a single request will take. A big enough catalog simply runs into the wall. A search-and-execute design sidesteps it: instead of registering every operation as its own model-facing tool, you expose a small handful of discovery and execution tools. StackOne’s Google ADK plugin, for instance, has a search_and_execute mode that registers just two model-facing tools, tool_search and tool_execute, no matter how large the underlying catalog is. The interface the model sees stays tiny.</p><p><strong>Onboarding new integrations gets messier.</strong> Now picture a platform serving lots of businesses. One customer connects Salesforce. Another just HubSpot. A third brings Salesforce, HubSpot, Slack, Jira, and a few more. If you eagerly register every operation for every tenant, the configuration balloons and turns into a maintenance headache. Make tools discoverable through one shared interface instead, and you surface the relevant operations as you go. To be fair, the integrations themselves still need to be set up, authenticated, kept alive, and secured. Dynamic loading trims the catalog; it doesn’t do your plumbing for you.</p><h3>How OpenAI does it</h3><p>OpenAI ships this as a feature called Tool Search in its API. The mechanism lets the model discover and pull in deferred tool definitions when it needs them. It’s documented for the Responses API, supported from GPT-5.4 onward.</p><p>Two settings do the heavy lifting. tool_search turns discovery on. defer_loading: true marks which tool definitions are eligible to be loaded later rather than upfront. Put simply: a request comes in, the model gets its starting context, and if it needs a deferred tool, it searches, loads the matching definitions, calls the one it wants, and returns the result.</p><p>There are two flavours of the search itself. With hosted tool search, OpenAI looks through the deferred tools you declared in the request and hands back the relevant ones. With client-executed tool search, the model asks for a search and your own application runs the lookup against whatever registry or system you control. That second option earns its place when tool availability depends on context OpenAI can’t see, like which tenant, project, or permission level the request belongs to.</p><p>One thing worth underlining: Tool Search does not build your integrations for you. Your application still has to execute the actual function calls and return their results, unless you’re leaning on a tool integration that handles execution on your behalf.</p><h3>How Google ADK gets there with StackOne</h3><p>Google ADK can reach a similar place through the StackOne plugin. Worth being precise here: this comes from StackOne’s integration, not from a claim that ADK’s own core ships the same native feature as OpenAI’s Tool Search. StackOne connects agents to tools across supported SaaS providers, covering CRM, HR, productivity, ticketing, and scheduling platforms.</p><p>The plugin has a mode called search_and_execute. Setting it up looks roughly like this:</p><pre>from stackone_adk import StackOnePlugin<br><br>plugin = StackOnePlugin(<br>    mode=&quot;search_and_execute&quot;,<br>    search={<br>        &quot;method&quot;: &quot;auto&quot;,<br>        &quot;top_k&quot;: 5<br>    }<br>)<br><br>tools = plugin.get_tools()</pre><p>The top_k of 5 just tells the search to return up to five candidate tools, subject to how the search is implemented. The model sees two tools: tool_search, which looks for relevant operations and returns candidates, and tool_execute, which runs a chosen operation with its parameters. The whole catalog never arrives as a long list of individual tools at the start.</p><p>So when a user says “find the latest customer emails,” the model searches for the right email-search operation, gets a short list of candidates back, and picks one to run. Same instinct as OpenAI’s approach, different machinery underneath.</p><p>The quick comparison: OpenAI’s Tool Search is a native API capability with hosted or client-executed search, and execution that depends on how you’ve wired your integration. Google ADK with StackOne gets there through the plugin’s search-and-execute workflow, with tool_execute handling the run through StackOne. OpenAI fits best if you’re already on its supported models and APIs; ADK plus StackOne fits best if you’re building on ADK and want StackOne’s connected integrations. Same goal, different details.</p><h3>Does it make things faster? Not on its own.</h3><p>This is the trade-off people tend to skip over. Discovering tools at runtime adds work: searching the catalog, returning candidates, sometimes another model call or an extra round trip. For a single request, that can actually make things slower. But if loading hundreds of schemas upfront was expensive to begin with, deferring them can cut the context the model has to chew through and come out ahead overall. Which way it lands depends on the model, the size of the catalog, how fast the search is, caching, and how many tool calls the task needs.</p><p>Loading everything upfront means no separate discovery step, but more context burned. Searching and loading on demand means a smaller tool set in front of the model, but search adds overhead. Caching what you’ve already discovered can save you from repeating the lookup, but cached tools can go stale. There’s no universal winner here, which is exactly why OpenAI’s own advice is to benchmark: compare task completion, token usage, and latency on realistic tasks before you commit to a loading strategy.</p><h3>Does it fix the context window for good? No.</h3><p>Dynamic tool loading tackles one source of context pressure: tool definitions. But the context window holds a lot more than that. System and developer instructions. The user’s messages. The conversation so far. Retrieved documents. Tool outputs. The model’s own intermediate reasoning. A single database result can be enormous. A long back-and-forth adds up fast.</p><p>So deferred loading handles the tool-definition slice, and other techniques handle the rest: compacting the conversation, retrieval, trimming bloated tool outputs. The goal was never to drive context to zero. It’s to stop spending it on things the current task doesn’t need.</p><h3>A word on security</h3><p>Discovery is not authorization. Keep those two apart in your head. Picture a platform with fifty customers, each with their own connected apps and their own permissions. A tool search might return exactly the right operation, and the backend still has to confirm that this particular user is allowed to run it.</p><p>Think about who can do what to a single ticket:</p><ul><li>A support agent might be allowed to read it</li><li>A manager might be allowed to update it</li><li>Only an authorized admin might be allowed to delete certain records</li></ul><p>Those rules have to live in the execution layer. You can’t lean on the model to pick a safe tool and call it a day. Tool definitions need validating too, and anything discovered dynamically should come from a source you trust. OpenAI makes a point of this in its own docs: validate your schemas when you’re using advanced patterns that can introduce tools which weren’t in the original request.</p><h3>Why this matters if you build agents</h3><p>As AI applications reach into more and more business systems, the number of things an agent could do keeps climbing. Hand the model every tool definition at the start and you waste context, push up your input-token bill, and make the model’s job of picking the right tool harder than it needs to be.</p><p>Dynamic tool loading offers a calmer design: find the tools the task needs, make their definitions available, run the ones that got picked. OpenAI gives you this natively through Tool Search. ADK developers can reach the same pattern through integrations like StackOne’s search-and-execute plugin. The upside can be real, but it still rides on good search, careful execution, and actual performance testing rather than hope.</p><p>If you’re building enterprise agents, the lesson underneath all of this is a quiet one. An agent doesn’t need to see everything it can do at every moment. It needs a reliable way to find the one capability that fits the task in front of it. Give it that, and a catalog of two hundred tools stops being a burden and starts being an advantage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a0310d788f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your RAG Re-Ranker Might Be Obsolete: This New AI Model Costs $0.042]]></title>
            <link>https://medium.com/@imrohitkushwaha2001/your-rag-re-ranker-might-be-obsolete-this-new-ai-model-costs-0-042-c732133892ec?source=rss-9d49c6e4b94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c732133892ec</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Rohit Kushwaha]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 12:38:41 GMT</pubDate>
            <atom:updated>2026-09-23T12:38:41.267Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your RAG Re-Ranker Might Be Obsolete: This New AI Model Costs $0.042 per Million Tokens, and Output Is Free</h3><h3>A company swapped out its production re-ranker for it. Precision jumped from 34.8% to 46.4%. Here’s how Jev works, how to plug it into your RAG pipeline today, and the one mistake that will make it perform worse than what you have now.</h3><p>If you’ve built a RAG (Retrieval-Augmented Generation) system, you’ve probably seen this failure.</p><p>A user asks a question. Your vector database returns the “top 5” chunks. Your LLM reads them and confidently gives the wrong answer.</p><p>Your data was fine. Your LLM was fine. The problem was the <strong>ranking</strong>. The chunk that actually held the answer came in at position 4, behind three chunks that only sounded related.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPVhTvtwxGoWrO-CXwcaRw.png" /><figcaption>Your RAG Re-Ranker Might Be Obsolete</figcaption></figure><p>That’s why most serious RAG pipelines add a <strong>re-ranker</strong>. A new model called <strong>Jev</strong> has just made re-ranking more interesting.</p><h3>First, a 60-second refresher: why RAG needs a re-ranker</h3><p>Every RAG system runs two pipelines.</p><p><strong>1. The indexing pipeline.</strong> You split your documents into chunks, turn them into embeddings, and store them in a vector database.</p><p><strong>2. The retrieval pipeline.</strong> A user asks a question. You embed the question, pull the most similar chunks from the vector DB, and send those chunks, the question, and your prompt to the LLM. The LLM writes the answer.</p><p>The weak link is step 2. Vector similarity is fast but blunt. It finds chunks that <em>look like</em> the question, which is different from chunks that <em>answer</em> it. When the ordering is wrong, the LLM works from bad evidence and produces low-precision answers.</p><p>A <strong>re-ranker</strong> fixes this. It sits between the vector DB and the LLM, reads each retrieved chunk alongside the query, and reorders the chunks by actual relevance. The best evidence goes first, and the noise gets cut.</p><p>Today you’d usually reach for Cohere’s managed Rerank API, or self-host an open model such as Jina, BGE, or Qwen’s rerankers.</p><p>Now there’s a new option.</p><h3>Meet Jev: an AI model that doesn’t write text</h3><p>Jev is the first model from TypeSafe AI, a San Francisco lab founded by Diogo Almeida, a co-author of the InstructGPT paper that led to ChatGPT. The company emerged from stealth on September 15, 2026 with $40 million in seed funding led by DCVC.</p><p>The unusual part is that <strong>Jev doesn’t generate text.</strong> TypeSafe calls it a <strong>“System One” model</strong>. The name comes from Daniel Kahneman’s <em>Thinking, Fast and Slow</em>: System 1 is fast, instinctive judgment, and System 2 is slow, step-by-step reasoning. A chatty LLM does System 2 work. Jev is built for System 1 snap decisions.</p><p>The name has a story too. Jev is named after economist William Stanley Jevons, whose paradox says that making a resource cheaper increases how much of it gets used. TypeSafe’s bet is that once decisions are cheap enough, you’ll make them everywhere.</p><h3>How it works: state in, decisions out</h3><p>Every Jev call has the same shape. You send a <strong>state</strong> (any text or JSON) and a set of <strong>questions</strong>. Each question is one of three types:</p><ul><li><strong>Choice</strong> asks “which of these options?” and returns the pick, a probability for every option, and a confidence score.</li><li><strong>Score</strong> asks “where does this fall on a rubric?” and returns a numeric score and a confidence.</li><li><strong>Noul</strong> asks “is this true?” and returns a single probability between 0 and 1. The name is short for Bernoulli.</li></ul><p>All the questions run in parallel against the same state in a single call, so adding more questions barely changes the response time.</p><h3>Why output is free</h3><p>A normal LLM produces its answer one token at a time, with each token depending on the last. Jev skips generation entirely. It reads the state once and produces every answer in the same forward pass, so there are no output tokens to charge for.</p><p>The pricing is <strong>$0.042 per million input tokens, free output, and 70 to 500 ms end-to-end latency.</strong></p><p>The probabilities are also trained to be <em>calibrated</em>. TypeSafe uses a method it calls Reinforcement Learning for Calibrated Decisions (RLCD), which aims for probabilities that match reality: if Jev says 0.9 on a hundred inputs, about ninety of them should be true. For a re-ranker, that matters a lot, as you’ll see below.</p><h3>Using Jev as your RAG re-ranker</h3><p>The idea is simple. Where your pipeline currently calls a re-ranker, call Jev instead. Give it the user’s query and the retrieved chunks, ask one yes/no question per chunk (“does this chunk help answer the question?”), and sort by the probabilities it returns.</p><p>There are two ways to structure that call. <strong>One of them is much better than the other.</strong></p><h3>❌ The naive way: one call per chunk</h3><p>You send each (query, chunk) pair as its own request with a single Noul. It looks like a classic cross-encoder, and it underperforms.</p><p>Unblocked, a company that tested Jev in production, found that this per-pair approach scored <em>below</em> their existing cross-encoder while also costing one request per candidate. Their explanation: when the model sees a single note in isolation, it has nothing to compare against, so it grades too generously. When it sees twenty, it can tell which three actually matter.</p><h3>✅ The right way: fan-out</h3><p>Put the query and a batch of chunks into the state, and ask one Noul per chunk, all in a single request:</p><pre># Illustrative sketch — check docs.typesafe.ai for the current SDK<br>from typesafe_sdk import TypeSafeClient, Noul</pre><pre>jev = TypeSafeClient()  # reads TYPESAFE_API_KEY</pre><pre>def jev_rerank(query: str, chunks: list[str], top_k: int = 5, threshold: float = 0.5):<br>    # Build one shared state: the question + every candidate chunk<br>    state = [f&quot;Question: {query}&quot;] + [<br>        f&quot;Chunk c{i}: {text}&quot; for i, text in enumerate(chunks)<br>    ]</pre><pre>    # One yes/no question per chunk, all answered in parallel<br>    questions = {<br>        f&quot;c{i}&quot;: Noul(instructions=f&quot;Chunk c{i} helps answer the question.&quot;)<br>        for i in range(len(chunks))<br>    }</pre><pre>    result = jev.system_one(state=state, questions=questions)</pre><pre>    scored = [<br>        (result.answers[f&quot;c{i}&quot;].noul, chunks[i])<br>        for i in range(len(chunks))<br>    ]<br>    scored.sort(key=lambda x: -x[0])</pre><pre>    # Calibrated probabilities make &quot;keep nothing&quot; a real option<br>    return [text for prob, text in scored[:top_k] if prob &gt;= threshold]<br></pre><pre># In your RAG pipeline:<br>candidates = vector_db.search(user_query, k=40)<br>context = []<br>for i in range(0, len(candidates), 20):          # batches of ~20 chunks<br>    context += jev_rerank(user_query, candidates[i:i+20], top_k=5)<br>answer = llm.generate(prompt, user_query, context[:5])</pre><p>Batching also saves money. The expensive part of a rerank call is the query context, and it’s identical for every candidate, so fan-out sends it once. Unblocked used batches of <strong>twenty chunks per request</strong> to stay well inside Jev’s 64k-token limit and to keep tail latency bounded.</p><h3>The numbers: does it actually beat a real re-ranker?</h3><p>Here’s the evidence so far.</p><p><strong>TypeSafe’s own test (legal documents).</strong> In TypeSafe’s reranking cookbook, a BM25 shortlist followed by Jev scoring moved top-1 accuracy from 5% to 18% and top-10 from 38% to 62%, and all 1,200 scoring calls cost $0.0645. That’s a vendor demo, so keep some skepticism.</p><p><strong>Unblocked’s production test.</strong> This is the more convincing one. Unblocked replaced the cross-encoder that decides which memories its agent sees with Jev, and measured both on 12,927 labeled question/note pairs from 292 real production questions.</p><p>With fan-out scoring:</p><ul><li><strong>Precision</strong> of the injected notes rose from <strong>34.8% to 46.4%</strong></li><li><strong>Recall</strong> of relevant notes rose from <strong>63.8% to 77.6%</strong></li><li><strong>Staying silent when nothing was relevant</strong> rose from <strong>48.4% to 59.4%</strong></li></ul><p>The last number is underrated. A RAG system that injects a wrong-but-confident chunk produces a wrong-but-confident answer. A re-ranker that can say “none of these are relevant” is worth a lot.</p><h3>The catch: what the hype won’t tell you</h3><p>This is where I disagree with a lot of the “Jev kills re-rankers” takes going around.</p><p><strong>1. It’s not dramatically cheaper than a hosted re-ranker.</strong> Jev’s pricing is tiny compared with a frontier LLM, but dedicated rerankers are already cheap. In Unblocked’s test, cost per 1,000 questions was $1.76 for Jev versus $1.87 for the incumbent, with p50 latency of 0.35 s versus 0.20 s. Their summary was that cost and latency came out about even. <strong>The reason to switch is quality and calibration, not a 100× cost cut.</strong> Where Jev really does save you money is when you’re currently using an LLM call as your re-ranker or judge.</p><p><strong>2. The call structure matters.</strong> As shown above, per-pair scoring <em>lost</em> to the incumbent. If you drop Jev in the lazy way, you might make your RAG worse.</p><p><strong>3. Tune the threshold, not the prompt.</strong> Unblocked spent a day testing nine instruction variants, and none beat the plain wording by more than about three points in either direction. One stricter wording cost twenty points of recall. With calibrated probabilities, the threshold is the setting that actually moves results.</p><p><strong>4. “Can’t hallucinate” is narrower than it sounds.</strong> Jev can’t return a value outside your schema, but it can still pick the wrong option, and TypeSafe’s own docs list its failure modes. Those include literal reading of your question, weak arithmetic and date comparison, trouble with multi-hop questions, distraction from large noisy state, and susceptibility to injected instructions.</p><p><strong>5. It’s one workload.</strong> Unblocked says so directly: their numbers aren’t a benchmark. Test Jev on your own data.</p><p><strong>6. Access.</strong> Direct API access is by waitlist at typesafe.ai, and Jev is also available on Vercel AI Gateway as typesafe-ai/jev, callable from AI SDK 7&#39;s evaluate method without the waitlist.</p><h3>How to test it on your RAG this week</h3><ol><li><strong>Take 100 to 300 real user questions</strong> from your logs.</li><li><strong>Reconstruct the full candidate set</strong> for each one, not just what your current re-ranker kept.</li><li><strong>Label relevance independently</strong>, with a human or a strong LLM judge that never sees either ranker’s scores. Don’t grade the new ranker with labels your old ranker produced, because the old one will win by construction.</li><li><strong>Run your current re-ranker and Jev fan-out</strong> side by side.</li><li><strong>Compare precision, recall, and “silent when nothing is relevant”</strong> at a matched threshold.</li></ol><p>Unblocked says its whole evaluation cost about twelve dollars and a couple of days. That’s cheap insurance before swapping out a core part of your pipeline.</p><h3>The bigger idea</h3><p>The most interesting thing about Jev isn’t the price. It’s the question it raises:</p><p><strong>How much of what your AI pipeline does is really a <em>decision</em> that you’re paying an LLM to phrase as text?</strong></p><p>Re-ranking is a decision. So are routing, “is this relevant?”, “is this safe to run?”, and “does this source actually support this claim?” RAG is everywhere, and every RAG pipeline makes these decisions thousands of times a day.</p><p>For re-ranking specifically, Jev probably won’t make your pipeline 400× cheaper, despite the headlines. But a calibrated re-ranker that knows when to say nothing could make it noticeably <em>more accurate</em>, and for high-precision answers, that’s what counts.</p><p><em>If this helped you think about your RAG stack differently, give it a clap 👏 and follow for more practical breakdowns of new AI tools, tested against reality instead of hype.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c732133892ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenDynamicGGUF: An Open, Measured, Reproducible Optimizer for Per-Tensor GGUF Quantization]]></title>
            <link>https://medium.com/@imrohitkushwaha2001/opendynamicgguf-an-open-measured-reproducible-optimizer-for-per-tensor-gguf-quantization-6ca130764ee4?source=rss-9d49c6e4b94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ca130764ee4</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm-quantization]]></category>
            <dc:creator><![CDATA[Rohit Kushwaha]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 15:21:49 GMT</pubDate>
            <atom:updated>2026-09-12T15:21:49.032Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why uniform Q4_K_M is leaving quality on the table — and how an open 15-step pipeline picks the right bits for every tensor, under your hardware budget.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_SRUpicN5mBZTVZ2i0h5A.png" /><figcaption>OpenDynamicGGUF</figcaption></figure><p>If you run local LLMs, you already live in GGUF land. You pick a model, you pick a preset — Q4_K_M, Q5_K_M, Q8_0 — and you hope the quality drop is acceptable.</p><p>That hope is the problem.</p><p>A uniform preset treats every tensor the same. The embedding table that every token touches gets the same bit-width as a mid-layer MLP up-projection that barely moves the output distribution. Attention-V, which is small and brutally sensitive, gets squeezed as hard as FFN-gate, which is huge and often cheap to compress. You save bytes. You also spend quality in the worst possible places.</p><p>Closed dynamic quantizers proved the alternative works: assign different precisions per tensor, measure KL divergence against full precision, and keep the bits where they actually matter. The catch is that the heuristics stay proprietary. You get a file. You do not get the recipe, the measurements, or a way to rebuild the file bit-for-bit.</p><p><strong>OpenDynamicGGUF</strong> is the open version of that idea.</p><p>It is an Apache-2.0, measurement-driven optimizer that takes <em>any</em> model reference — a Hugging Face repo, an Ollama tag like functiongemma:latest, an MLX id, or a local checkpoint — traces it back to original full-precision weights, measures how sensitive each tensor group is to quantization, and searches for the bit assignment that costs the least quality per byte saved.</p><pre>odg quantize --model functiongemma:latest --target-size 3.2GB</pre><pre>  → functiongemma-UD.gguf     # the dynamic-quantized model<br>  → recipe.yaml               # fully reproducible quantization recipe<br>  → report.html               # KLD / perplexity / benchmark validation report</pre><p>Instead of one opaque preset, the output looks like this:</p><pre>token_embd            -&gt; Q8_0     (pinned: touched by every token)<br>attn_v    (all)       -&gt; Q6_K     (pinned: high sensitivity, small size)<br>attn_q/k  (early)     -&gt; Q5_K<br>attn_q/k  (mid/late)  -&gt; Q4_K<br>ffn_gate  (mid)       -&gt; Q3_K     (cheap bits: large tensor, low sensitivity)<br>ffn_up    (mid)       -&gt; Q3_K<br>ffn_down  (all)       -&gt; Q4_K<br>output                -&gt; Q8_0     (pinned)</pre><p>This article is the full story: <strong>why</strong> the project exists, <strong>how</strong> the pipeline actually works, the <strong>architecture</strong> from resolver to validation gates, what ships <strong>today</strong>, and the <strong>platform</strong> we are building next — hardware-aware fitting, same-model benchmarking, a recipe marketplace, a public leaderboard, Hugging Face publishing, a Web UI, a backend, CI/CD, more models, and more.</p><p><strong>Repo:</strong> <a href="https://github.com/imrrohitt/OpenDynamicGGUF">github.com/imrrohitt/OpenDynamicGGUF</a></p><p><strong>Status today:</strong> alpha. Python 3.10+. Built on <a href="https://github.com/ggml-org/llama.cpp">llama.cpp</a>. License: Apache 2.0.</p><h3>1. The problem nobody owns</h3><p>The quantization <em>methods</em> are excellent. GPTQ, AWQ, SmoothQuant, HQQ, AQLM, llama.cpp k-quants, IQ formats, importance matrices — the research and the kernels are there.</p><p>What the ecosystem does <strong>not</strong> have is a broadly adopted, <strong>open automatic quantization optimizer</strong>: a tool that, given a size or memory budget, discovers the best tensor-wise precision assignment and exports a ready-to-use GGUF with receipts.</p><p>Three things are broken at once.</p><p><strong>Uniform presets waste bits.</strong> Q4_K_M is a reasonable average. It is a terrible allocation. Embeddings and the language-model head are touched by every token. Attention-V is small and high-impact. Mid-layer FFN-up and FFN-gate are large and often low-sensitivity. Treating them identically is leaving quality on the table at the same file size — or leaving size on the table at the same quality.</p><p><strong>Closed dynamic quants work, and you cannot inspect them.</strong> Unsloth Dynamic 2.0 GGUFs showed that selective per-tensor bit-widths, guided by a curated calibration set and KL-divergence measurements, beat uniform quantization — especially on MoE models, where dynamic quantization has become the de-facto standard. Their pipeline is proprietary. You cannot read the heuristic, you cannot replay the search, you cannot prove the file matches a recipe.</p><p><strong>Most published GGUFs have no receipts.</strong> A Hub repo with a .gguf and a copy-pasted model card is the norm. No calibration split. No held-out KL. No paired benchmark against BF16. No way to tell whether the quant overfit Wikipedia. Users download binaries from strangers daily.</p><p>OpenDynamicGGUF exists to close that gap with three adjectives that are also design constraints:</p><ul><li><strong>Open</strong> — every heuristic is code you can read.</li><li><strong>Reproducible</strong> — every released GGUF ships with a recipe.yaml that rebuilds it bit-for-bit.</li><li><strong>Measured</strong> — every bit decision traces back to a number produced by a sensitivity probe, not a hand-wave.</li></ul><p>Crucially, we do <strong>not</strong> reimplement quantization kernels. llama.cpp already provides the execution layer:</p><ul><li>convert_hf_to_gguf.py — Hugging Face → GGUF</li><li>llama-imatrix — importance matrix from calibration text</li><li>llama-quantize --tensor-type / --tensor-type-file — per-tensor overrides (regex supported)</li><li>--token-embedding-type / --output-tensor-type — embedding and output overrides</li><li>llama-perplexity --kl-divergence — KL vs full-precision logits</li><li>llama-quantize --dry-run — size estimation without writing files</li></ul><p>OpenDynamicGGUF is the <strong>measurement, search, and validation loop around those tools</strong>.</p><h3>2. What “dynamic” actually means</h3><p>A uniform quant says: every weight is Q4_K.</p><p>A dynamic quant says: groups of tensors get different types from a ladder such as:</p><pre>Q8_0 → Q6_K → Q5_K → Q4_K → Q3_K → Q2_K</pre><p>You still pick a <em>size class</em> (q4_k_m, q5_k_m, iq4_xs, …). That class is a <strong>budget</strong>, not a flat type. Under the hood OpenDynamicGGUF still builds a mixed assignment: hard tensors stay higher precision, easy tensors go lower, so accuracy is better than a flat single-type quant at the same file size.</p><p>A typical everyday target:</p><ul><li><strong>Q4_K_M</strong> — ~4.0–4.5 bits per weight, ~72% smaller than BF16, the default.</li><li><strong>Q5_K_M</strong> — more budget; more tensors stay Q5_K / Q6_K where it matters.</li><li><strong>Q3_K_M</strong> — aggressive; easy groups drop to Q3_K, hard groups stay protected.</li><li><strong>IQ formats</strong> — even tighter size classes when you need them.</li></ul><p>The user-facing contract is simple:</p><pre>BF16 model + size budget → best per-tensor GGUF</pre><p>The question users actually ask is bigger, and that is where the <strong>platform</strong> is going:</p><pre>&quot;I have this hardware and this workload — give me the best model, prove it, and let me share it.&quot;</pre><h3>3. Design principles (the rules that keep results honest)</h3><p>Seven rules. If you remember nothing else about the architecture, remember these.</p><p><strong>1. Never requantize quantized weights.</strong> Quantization error compounds. An Ollama Q4 blob or an MLX 4-bit repo is rejected as a <em>source</em>. The resolver traces every reference back to original full-precision weights before anything else happens.</p><p><strong>2. KL divergence to the full-precision model is the primary objective.</strong> Not perplexity alone, and not benchmark scores during search. Logit-level fidelity is cheap, sensitive, and does not saturate the way accuracy metrics do.</p><p><strong>3. Statistics prioritize; probes decide.</strong> Weight features (mean, variance, sparsity, entropy, norms, outliers) and activation features (range, channel importance) only <em>rank</em> which groups and bit-widths to try first. Two layers can share identical weight stats and still diverge wildly after quantization. Only measured ΔKLD is authoritative.</p><p><strong>4. Hard wall between search data and judging data.</strong> The optimizer never sees the data it will be validated on. Calib / search / held-out is a 60 / 20 / 20 split with a fixed seed. This is the single rule that keeps results honest instead of overfit to their own calibration set.</p><p><strong>5. Search over tensor groups, not individual tensors.</strong> Role × depth grouping reduces ~300 tensors to ~25 groups. The search becomes tractable. The recipe becomes readable.</p><p><strong>6. Everything is content-addressed and cached.</strong> A re-run recomputes only what changed. Probes, logits, imatrices, and candidate GGUFs are keyed by the hash of their full input configuration.</p><p><strong>7. Gates are statistical where the metric is noisy.</strong> Benchmark comparisons are paired per-question against the BF16 model with confidence intervals — never raw score thresholds. Benchmark noise would randomly pass and fail good quants.</p><p>The one-line version, used in every step doc:</p><blockquote><em>Statistics and features </em>prioritize<em>. Measured ΔKLD </em>decides<em>. Held-out validation </em>ships<em>.</em></blockquote><h3>4. How it works — the 15-step engine</h3><p>The pipeline is not a monolith. It is sixteen small, checkpointed steps (00 is the run store). Each step writes JSON artifacts into artifacts/runs/&lt;run-id&gt;/steps/&lt;step&gt;/ with input.json, output.json, status.json, and a log. Re-running a completed step is a no-op unless you pass --force. --new-run starts a fresh run. You can stop after catalog, resume from optimize, inspect status, and never lose work.</p><pre>User model ref (Ollama / MLX / HF / local)<br>        │<br>        ▼<br>1 · Resolve to original BF16 safetensors<br>        │<br>        ▼<br>2 · Load → enumerate → classify roles → tensor catalog → features<br>        │<br>        ▼<br>3 · Freeze BF16 GGUF (+ SHA-256)<br>        │<br>        ▼<br>4 · Calibration corpus (3-way split)<br>        │<br>        ▼<br>5 · Reference artifacts (imatrix + BF16 logits)<br>        │<br>        ▼<br>6 · Sensitivity: features rank → trial quant → measure ΔKLD<br>        │<br>        ▼<br>7 · Optimizer (bytes_saved / ΔKLD under budget)<br>        │<br>        ▼<br>8 · Export GGUF from recipe<br>        │<br>        ▼<br>9 · Validation gates → release</pre><p>There are <strong>two views of the same weights</strong>. Stage 2 loads the checkpoint in PyTorch (or reads a GGUF index) to <em>inspect</em> every tensor. Stage 3 converts the same checkpoint to a frozen BF16 GGUF so <em>probes and export</em> run through llama.cpp. Both must share the same source SHA / content hash. If they do not, sensitivity measured on one build and export on another become silently incomparable — and the recipe stops being reproducible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2w2UYRb5w3O-J-pVbgnSGQ.png" /><figcaption>OpenDynamicGGUF</figcaption></figure><p>Below is what each stage actually does, and which failure it exists to prevent.</p><h3>Stage 1 — Universal model resolver</h3><p>The generalization that makes this work for <em>any</em> model: the pipeline never starts from what you typed. It starts from what the resolver traces it back to.</p><ul><li><strong>You type </strong><strong>gemma4:e2b-mlx.</strong> That is an MLX repo — weights already 4-bit. <strong>Rejected as a source.</strong> Traced automatically to the original BF16 Hugging Face repo.</li><li><strong>You type </strong><strong>functiongemma:latest.</strong> That is an Ollama tag pointing at a Q4 (or Q8) GGUF blob. The Ollama manifest is read; the upstream fine-tune repo on Hugging Face is resolved. Pass --prefer-hf if you want the BF16 checkpoint instead of the local blob.</li><li><strong>You type </strong><strong>google/gemma-4-e2b-it.</strong> BF16 safetensors on the Hub. Used directly.</li><li><strong>You type </strong><strong>./my-finetune/.</strong> A local full-precision checkpoint. Used directly.</li></ul><p><strong>Produces:</strong> a working path plus an <em>architecture descriptor</em> — family, layer count, MoE / SSM flags, chat template, specialty domain. That descriptor later selects the tensor-role taxonomy and which domain checks to add (function-calling traces and JSON-validity gates for a FunctionGemma-style fine-tune, extra code for a coder model, and so on).</p><p><strong>Failure prevented:</strong> requantizing already-quantized weights. No downstream search can recover compounded error.</p><h3>Stage 2 — Load, classify, catalog, features</h3><p>No quantization decisions happen here. The goal is to know every tensor, what role it plays, and what its weight (and later activation) features look like — so Stage 6 can prioritize probes intelligently.</p><p><strong>Load.</strong> Open the resolved GGUF or Hugging Face checkpoint and build a tensor index. If the original is safetensors:</p><pre>from transformers import AutoModelForCausalLM<br>import torch</pre><pre>model = AutoModelForCausalLM.from_pretrained(<br>    MODEL_PATH,                 # path from the resolver — never an MLX/Ollama quant<br>    torch_dtype=torch.bfloat16,<br>)</pre><p><strong>Enumerate.</strong> Walk state_dict(). Every parameter is one tensor: name, shape, dtype, nbytes.</p><pre>model.embed_tokens.weight<br>model.layers.0.self_attn.q_proj.weight<br>model.layers.0.self_attn.k_proj.weight<br>model.layers.0.self_attn.v_proj.weight<br>model.layers.0.self_attn.o_proj.weight<br>model.layers.0.mlp.gate_proj.weight<br>model.layers.0.mlp.up_proj.weight<br>model.layers.0.mlp.down_proj.weight<br>model.layers.0.input_layernorm.weight<br>model.norm.weight<br>lm_head.weight</pre><p>MoE and hybrid models add expert and SSM names. The catalog records whatever is present. Nothing is assumed.</p><p><strong>Classify (role taxonomy).</strong> Names are mapped into roles. This is more informative than treating all tensors identically — humans and the optimizer already know that attention-V is usually more sensitive than MLP-up.</p><p>Typical mapping:</p><ul><li>embedding — embed_tokens, tok_embeddings — often pinned high</li><li>attn_q / attn_k / attn_v / attn_o — projections; V is often high sensitivity</li><li>ffn_gate / ffn_up / ffn_down — MLP; gate/up are often cheap bits</li><li>ffn_*_exps — MoE experts</li><li>router — MoE gate; pin / careful</li><li>ssm_* — hybrid / Mamba paths</li><li>norm — usually <strong>skip</strong> (leave F16/F32)</li><li>lm_head — often pinned high</li></ul><p>Layer index is parsed from the name. Depth is bucketed: early / middle / late. <strong>Role × depth is the grouping key</strong> used later — ~25 groups instead of hundreds of tensors.</p><p>Each tensor also gets a GGUF name (blk.12.attn_q.weight) so export can pass --tensor-type without guessing.</p><p><strong>Weight features (no text needed).</strong> Read from the parameter tensor itself: mean, variance, sparsity, entropy, weight norm, spectral norm, outlier ratio. Available as soon as the model is loaded. Used only to estimate <em>hardness</em> and rank probe order.</p><p><strong>Activation features (need calibration text).</strong> A forward pass on real prompts yields activation range, outliers, and per-channel importance. Without inference you only know weights. You do <strong>not</strong> know which neurons fire, which channels spike on code vs chat, or which experts activate. The same Layer-12 channel may sit near 0.2 on &quot;What is AI?&quot; and spike to 15.2 on &quot;Write Python code.&quot; Only activation stats reveal that.</p><p>If a real forward pass is unavailable, the step falls back to a <strong>proxy</strong> so the pipeline still completes. Real activations are preferred.</p><p><strong>Catalog.</strong> One content-addressed tensor_catalog.json is the source of truth for every later step:</p><pre>{<br>  &quot;model_source&quot;: &quot;google/gemma-3-270m&quot;,<br>  &quot;source_sha256&quot;: &quot;…&quot;,<br>  &quot;tensors&quot;: {<br>    &quot;model.layers.12.self_attn.q_proj.weight&quot;: {<br>      &quot;shape&quot;: [640, 640],<br>      &quot;role&quot;: &quot;attn_q&quot;,<br>      &quot;layer&quot;: 12,<br>      &quot;depth&quot;: &quot;middle&quot;,<br>      &quot;gguf_name&quot;: &quot;blk.12.attn_q.weight&quot;,<br>      &quot;quantizable&quot;: true,<br>      &quot;weight_features&quot;: {<br>        &quot;mean&quot;: 0.001,<br>        &quot;variance&quot;: 0.05,<br>        &quot;entropy&quot;: 6.8,<br>        &quot;sparsity&quot;: 0.72,<br>        &quot;outlier_ratio&quot;: 0.002<br>      }<br>    }<br>  }<br>}</pre><p><strong>Failure prevented:</strong> probing blind — not knowing which tensors exist, which roles they play, or which names to pass to --tensor-type.</p><h3>Stage 3 — Freeze a hashed BF16 GGUF</h3><p>Same checkpoint, second representation, for the llama.cpp path:</p><pre>python llama.cpp/convert_hf_to_gguf.py ./model-src --outtype bf16 --outfile model-bf16.gguf<br>sha256sum model-bf16.gguf</pre><p>The SHA is recorded in every downstream artifact. Probing, export, and validation all derive from these exact bytes.</p><p>If Hugging Face conversion is not available, freeze can <strong>promote</strong> a working local GGUF (for example an Ollama Q8_0 blob) so the rest of the pipeline still runs. That is valid plumbing. It is <strong>not</strong> a paper-quality BF16 study. For a true BF16 freeze:</p><pre>odg freeze-gguf --model &lt;model&gt; --mode hf-convert --require-bf16 --force</pre><p><strong>Failure prevented:</strong> measuring sensitivity on one build while exporting another.</p><h3>Stage 4 — Calibration corpus and the three-way split</h3><p>This is one of the most important parts of the project.</p><p>Activation statistics, the importance matrix, and KL divergence are <strong>not</strong> computed on random noise or from weights alone. They require running real text through the model:</p><pre>Prompt → Model → Hidden activations / logits → Stats, imatrix, ΔKLD</pre><p>Weights alone never answer: which neurons activate on real workloads, which channels spike, which experts fire, how much quantizing group X shifts the output distribution.</p><p>The corpus is plain text — thousands of prompts concatenated, <strong>rendered with the model’s chat template</strong> for instruct models. Raw WikiText never exercises the format instruct models actually see. That is a documented weakness of many community imatrix quants.</p><p>OpenDynamicGGUF is more deliberate than Wikipedia-only. Target mix:</p><ul><li>Conversation / chat — ~30% — matches instruct use</li><li>Code — ~30% — stresses different channels than prose</li><li>Math / reasoning — ~20% — exact-answer sensitivity</li><li>Multilingual — ~10% — avoid English-only activation bias</li><li>Domain-specific — ~10% — from resolver metadata (function-calling traces for FunctionGemma, extra code for a coder, and so on)</li></ul><p>Scale: roughly 0.3M–1.5M tokens depending on model size.</p><p>Then the <strong>hard walls</strong>:</p><ul><li><strong>calib (~60%)</strong> — llama-imatrix and activation-feature hooks. Guides rounding.</li><li><strong>search (~20%)</strong> — sensitivity prober and optimizer. ΔKLD objective during search.</li><li><strong>held-out (~20%)</strong> — validation gates <strong>only</strong>. Search never touches it.</li></ul><p><strong>Failure prevented:</strong> calibrating and evaluating on the same distribution. Wikipedia in → Wikipedia KLD out looks better than it is.</p><p>Three data sources, three jobs:</p><pre>    BF16 Model<br>        │<br>   ┌────┴─────────────────────┐<br>   │                          │<br>Weight tensors        Calibration / search text<br>   │                           │<br>   ▼                           ▼<br>Mean, variance             Forward pass<br>Entropy, sparsity              │<br>Weight / spectral norms        ▼<br>Weight outlier ratio    Hidden activations ──► range, importance, imatrix<br>                         Logits (BF16 vs quant) ──► ΔKLD, top-token agree</pre><h3>Stage 5 — Reference artifacts (compute once)</h3><p>Two expensive full-precision artifacts are computed exactly once and cached for every candidate that follows.</p><p><strong>Importance matrix.</strong> llama-imatrix automates the activation-importance path over the calib split. llama-quantize later uses that file so rounding <em>inside</em> each tensor is guided by how the model actually activates — not by uniform assumptions.</p><p><strong>Reference logits.</strong> llama-perplexity --kl-divergence-base dumps BF16 logits on the search split and the held-out split. Every candidate is compared against those caches. You do not re-run the full-precision forward pass per candidate — the cost that makes naive search infeasible on a workstation.</p><p>Without those binaries, the pipeline still completes in <strong>proxy</strong> mode so you can inspect catalogs, recipes, and size estimates. Proxy ΔKLD is not a measured claim. Install the llama tools and re-run with --mode llama --force when you want the real numbers.</p><p><strong>Failure prevented:</strong> paying a full-precision forward pass for every trial quant.</p><h3>Stage 6 — Sensitivity probing (the heart of the project)</h3><p>This is where OpenDynamicGGUF stops being “a wrapper around llama-quantize” and becomes an optimizer.</p><p>Start from the catalog: groups already classified by role × depth, features already computed. Features <strong>prioritize</strong>. Probes <strong>decide</strong>.</p><p><strong>Why statistics alone are not enough.</strong> Two layers can look identical on paper:</p><pre>Layer A / Layer B<br>  Mean = 0    Variance = 0.05    Sparsity = 80%    Norm = 15</pre><p>After the same Q4 probe, Layer A may show ΔKLD ≈ 0.002 (fine) while Layer B shows ΔKLD ≈ 0.12 (catastrophic). A rule like if variance &lt; 0.1 then compress cannot see this. The true signal is <strong>the model&#39;s sensitivity to quantizing that group</strong>, measured by changing only that group and observing the shift in output distributions.</p><p><strong>Probe pipeline (per group).</strong> Norms and other non-quantizable entries are skipped. That yields ~25 probe groups.</p><pre>Tensor catalog (roles + features)<br>      │<br>      ▼<br>Estimate sensitivity score   from catalog features<br>      │<br>      ▼<br>Rank groups + choose trial bit-widths   (Q2 / Q3 / Q4 / Q5 / Q6 …)<br>      │<br>      ▼<br>Trial quantization — only this group; rest stays BF16<br>      │<br>      ▼<br>Run search-split prompts — cached BF16 logits vs probe logits<br>      │<br>      ▼<br>Measure ΔKLD, top-token agreement, Δbytes<br>      │<br>      ▼<br>Record  bytes_saved / ΔKLD  ← what the optimizer actually maximizes</pre><p>A concrete trial that only lowers mid-layer ffn_up:</p><pre>./llama-quantize --imatrix imatrix.gguf \<br>    --tensor-type &quot;\.(1[0-9])\.ffn_up=q3_k&quot; \<br>    model-bf16.gguf probe-ffnup-mid.gguf q6_k</pre><pre>./llama-perplexity -m probe-ffnup-mid.gguf \<br>    --kl-divergence-base logits-search.bin --kl-divergence</pre><p>How features help without becoming the decision:</p><ul><li>High sparsity + low variance + few outliers → try Q3 first (probably easy)</li><li>Huge activation range + large spectral norm + many outliers → start at Q5/Q6 (probably hard)</li></ul><p>If the Q3 probe returns ΔKLD ≈ 0.003 → keep Q3. If it returns ΔKLD ≈ 0.12 → reject and try Q4 / Q5. The sensitivity score never overrides a measured bad ΔKLD.</p><p><strong>The sensitivity table.</strong> The output is (group, quant_type) → (Δbytes, ΔKLD). Δbytes is computed analytically from bits-per-weight × tensor shapes (--dry-run as a cross-check).</p><p>Illustrative shape for a ~4B dense model (real numbers come from your probe run):</p><p>Tensor group Probe Size saved ΔKLD (mean) Decision ffn_up · mid layers Q4_K → Q3_K −310 MB +0.004 Accept ffn_gate · mid layers Q4_K → Q3_K −305 MB +0.005 Accept ffn_down · mid layers Q4_K → Q3_K −180 MB +0.019 Keep Q4_K attn_v · all layers Q6_K → Q4_K −45 MB +0.037 Pin Q6_K token_embd Q8_0 → Q4_K −190 MB +0.055 Pin Q8_0</p><p>Large MLP tensors often buy cheap savings. Attention and embeddings often buy expensive regret. We only believe that after measuring.</p><p><strong>Failure prevented:</strong> (1) blind search over an enormous per-tensor space, (2) false confidence from statistic thresholds that miss high-sensitivity layers with “easy-looking” distributions.</p><h3>Stage 7 — Recipe optimizer (knapsack, not magic)</h3><p>Bit assignment under a byte budget is approximately a knapsack problem.</p><p><strong>Greedy phase.</strong> Repeatedly downgrade the group with the best ratio of <em>bytes saved per unit of KLD incurred</em> until the size / VRAM budget is met. Per-group effects are roughly additive, so greedy gets ~90% of the way.</p><p><strong>Refinement phase.</strong> Short local search (single-group swaps, ±1 quant level) with <em>joint</em> measurement: quantize the full candidate and measure real KLD, correcting for interaction effects the additivity assumption misses.</p><p><strong>Output.</strong> Not one opaque config — the top few candidates along the <strong>size ↔ quality Pareto frontier</strong>. The user (or odg fit) picks the trade-off. Every choice stays auditable.</p><p>v1 deliberately skips Bayesian optimization and evolutionary search. Each objective evaluation costs a quantize + eval pass, and the published evidence says greedy-plus-refinement captures what matters. Fancier search is a later experiment (Phase 3 AutoML), not a prerequisite.</p><p>Default pins still apply unless you pass --no-pins: embeddings and lm_head at Q8_0, attn_v at Q5_K. Pins are starting constraints, not unmeasured dogma — probes can still justify them.</p><p><strong>Failure prevented:</strong> a single opaque config you cannot explain or rebuild.</p><h3>Stage 8 — Reproducible export</h3><p>A recipe is rendered into a --tensor-type-file and executed:</p><pre>./llama-quantize --imatrix imatrix.gguf --tensor-type-file recipe.tt \<br>    --token-embedding-type q8_0 --output-tensor-type q8_0 \<br>    model-bf16.gguf model-UD.gguf q4_k_m</pre><p>The recipe carries the <strong>model hash, imatrix hash, and every group assignment</strong>, so anyone can rebuild the GGUF bit-for-bit. Provenance metadata is embedded in the output file via --override-kv.</p><p>If llama-quantize is missing, export stays in <strong>dry_run</strong>: it plans the command, writes recipe.yaml / recipe.tt / quantize_command.sh, estimates size — and writes <strong>no </strong><strong>.gguf</strong>. Validate then stages a <strong>PROVISIONAL</strong> release. This is intentional. Silent fake files would be worse than an honest missing artifact.</p><pre>export LLAMA_CPP_DIR=~/llama.cpp<br>odg export --model functiongemma:latest --mode llama --force</pre><p>--mode llama fails hard if the binary is missing. No silent dry-run.</p><p><strong>Failure prevented:</strong> “trust me” quants. Full reproducibility is the differentiator against closed dynamic-quant pipelines.</p><h3>Stage 9 — Validation gates (data the search never saw)</h3><p>Three cost-ordered tiers. A candidate ships only after passing every gate. All of them run on <strong>held-out</strong> data.</p><p><strong>Tier 1 — Logit fidelity</strong> <em>(every candidate, minutes)</em></p><p>llama-perplexity --kl-divergence against cached BF16 logits:</p><ul><li><strong>mean KLD</strong> — overall fidelity</li><li><strong>99.9th-percentile KLD</strong> and <strong>max KLD</strong> — a good mean can hide catastrophic single-token failures; the tail gates catch them</li><li><strong>top-token agreement</strong> — fraction of positions where the quant’s argmax matches BF16</li></ul><p><strong>Tier 2 — Behavioral smoke</strong> <em>(Pareto-frontier candidates, ~1 hour)</em></p><ul><li>Perplexity on an unrelated public set (different from anything used in calibration)</li><li>Generation battery: chat coherence, code that must compile, exact-answer math, long-context retrieval</li><li>Domain checks from resolver metadata — e.g. every emitted tool call must be schema-valid JSON for a function-calling model</li></ul><p>Catches failure modes logit metrics miss: broken chat-template handling, degenerate repetition, formatting collapse.</p><p><strong>Tier 3 — Benchmarks</strong> <em>(final 1–2 candidates, hours)</em></p><p>MMLU / GSM8K / HumanEval-class tasks. The gate is <strong>statistical</strong>: paired per-question comparison against the BF16 model, required to sit inside the confidence interval. Never a raw score threshold.</p><p><strong>Feedback loop.</strong> A gate failure returns to the optimizer as a concrete constraint, not a blind restart. A max-KLD breach is traced to the group that caused it (the sensitivity table makes the lookup trivial), that group is pinned one precision level higher, and the search re-runs — from cache, so only changed artifacts are recomputed.</p><p><strong>Failure prevented:</strong> shipping a quant that only looks good on its own calibration data — the exact overfitting failure this whole design exists to avoid.</p><h3>5. One pipeline, every architecture</h3><p>The probe-and-search loop is identical for every model. Only the <strong>tensor taxonomy and default policies</strong> adapt. The architecture descriptor from the resolver selects the profile.</p><p><strong>Dense transformers (Gemma, Llama, Qwen dense, …)</strong></p><p>MLP tensors dominate the byte count — that is where size is won. Attention and embeddings are where quality is lost.</p><ul><li>ffn_up / ffn_gate — low sensitivity — search down to Q3_K</li><li>ffn_down — medium — typically lands one level above gate/up</li><li>attn_q / attn_k — medium — search Q4–Q5; early layers usually need more</li><li>attn_v / attn_output — high — pin Q5_K–Q6_K (small tensors, outsized KLD)</li><li>token_embd / output — critical — pin Q8_0 (touched by every token)</li></ul><p><strong>MoE models (Qwen-MoE, gpt-oss class)</strong></p><p>Expert tensors are ~90% of the bytes, so dynamic assignment pays off most here — which is why dynamic quantization became the de-facto standard for MoE. Calibration also yields <strong>expert-usage counts</strong>: rarely-routed experts can take fewer bits.</p><ul><li>ffn_up_exps / ffn_gate_exps — low — quantize hard (Q2–Q3), the bulk of the model</li><li>ffn_down_exps — medium — one level above up/gate experts</li><li>shared expert — high — pin high, active on every token</li><li>router / gate — critical — pin; tiny tensor that controls all routing</li><li>attn_* — high — pin Q5–Q6</li></ul><p><strong>Hybrid / SSM models (Mamba–attention hybrids)</strong></p><p>Published probes on hybrids show the recurrent path is the trap: ssm_out at Q2_K explodes KLD for negligible savings, and the few attention layers present are extra sensitive.</p><ul><li>ffn_* — search as in dense models</li><li>ssm_in / conv1d — search cautiously, one level at a time</li><li>attn_* (sparse layers) — pin; they carry long-range mixing</li><li>ssm_out — never below Q6 — max-KLD spike, minuscule savings</li></ul><p><strong>Fine-tunes (e.g. </strong><strong>functiongemma:latest)</strong></p><p>A fine-tune keeps the base architecture, so the taxonomy and the base model’s recipe carry over as a <strong>warm start</strong> — never as the final answer.</p><ul><li><strong>Reuse</strong> the tensor taxonomy and the base recipe to initialize search</li><li><strong>Change</strong> the calibration corpus to include the specialty domain (real function-calling traces rendered in the chat template) or the imatrix optimizes for the wrong distribution</li><li><strong>Re-probe</strong> — fine-tuning shifts weight outliers; sensitivity is re-measured (cheap, thanks to the cache)</li><li><strong>Extra gate</strong> — Tier 2 adds domain smoke tests (schema-valid tool calls, etc.)</li></ul><h3>6. The recipe is the product</h3><p>The GGUF is a build artifact. The <strong>recipe</strong> is the unit of reproducibility — and, later, the unit of sharing.</p><pre># recipe.yaml<br>schema: odg/recipe/v1<br>model:<br>  source: google/gemma-4-e2b-it<br>  bf16_gguf_sha256: &quot;9f2c…&quot;<br>calibration:<br>  corpus_id: odg-corpus-v1<br>  imatrix_sha256: &quot;77aa…&quot;<br>  splits: { calib: 0.6, search: 0.2, heldout: 0.2, seed: 42 }<br>budget:<br>  target_size_gb: 3.2<br>base_type: q4_k_m<br>overrides:<br>  token_embd: q8_0<br>  output: q8_0<br>  &quot;\\.(\\d+)\\.attn_v&quot;: q6_k<br>  &quot;\\.([0-9])\\.attn_q&quot;: q5_k<br>  &quot;\\.(1[0-9]|2[0-9])\\.ffn_up&quot;: q3_k<br>  &quot;\\.(1[0-9]|2[0-9])\\.ffn_gate&quot;: q3_k<br>validation:<br>  tier1: { mean_kld: 0.0081, p999_kld: 0.41, max_kld: 2.9, top1_agree: 0.987 }<br>  tier3: { mmlu_paired_delta: -0.2, ci95: [-0.9, 0.5], pass: true }</pre><p>recipe.tt is the same assignment rendered for llama-quantize --tensor-type-file. Anyone with the source hash and the imatrix hash can rebuild the file.</p><p>That is the difference versus shipping a binary and a vibe.</p><h3>7. What ships today (alpha, but the engine is real)</h3><p>The project is explicitly <strong>alpha</strong>. The full CLI pipeline (odg run, steps 01–15) is available. Without a local llama.cpp build, export stays in dry-run (recipe + size estimate, no .gguf). With llama.cpp, you get a real file.</p><h3>Implemented core (steps 00–15)</h3><ul><li><strong>00 Checkpoint store</strong> — odg status, odg runs. Filesystem run store so no step is lost.</li><li><strong>01 Resolve</strong> — any ref → original BF16 / working GGUF + architecture descriptor.</li><li><strong>02–05 Load, enumerate, classify, catalog</strong> — tensor_catalog.json.</li><li><strong>06 Weight features</strong> — mean / var / norms / hardness.</li><li><strong>07 Calibration corpus</strong> — calib / search / held-out 60/20/20.</li><li><strong>08 Activation features</strong> — forward if possible, else proxy.</li><li><strong>09 Freeze BF16 GGUF</strong> — HF convert optional; promote working GGUF otherwise.</li><li><strong>10 Imatrix</strong> — llama-imatrix or proxy.</li><li><strong>11 Reference logits</strong> — llama-perplexity or proxy.</li><li><strong>12 Sensitivity</strong> — Δbytes / ΔKLD table (proxy table today; llama probes when tools are present).</li><li><strong>13 Optimize</strong> — greedy knapsack + Pareto → recipe.yaml.</li><li><strong>14 Export</strong> — dry-run always; llama-quantize writes the real GGUF.</li><li><strong>15 Validate</strong> — proxy gates + report; strict mode refuses PROVISIONAL if there is no real file.</li></ul><h3>Implemented platform Phase 1 — Decide</h3><p>These wrap the engine without changing its contract:</p><p><strong>odg fit — describe hardware, not bits</strong></p><pre>odg fit --model functiongemma:latest --gpu 12GB<br>odg fit --model qwen3 --device macbook-air-16gb --ctx 8192<br>odg fit --model llama4 --ram 32GB --cpu-only<br>odg devices   # list named device profiles</pre><p>Nobody thinks “3.2 GB target size.” They think “I have a 12 GB GPU” or “I have a MacBook Air.” fit converts a hardware profile + context length into the byte budget step 13 already accepts:</p><pre>budget = memory pool × usable fraction − KV cache(model, ctx) − runtime overhead</pre><p>The KV cache is exact math from the architecture descriptor (layers × ctx × KV width × dtype). Every subtraction is printed and saved as fit_plan.json. Hardware awareness is a <strong>front-end to the current knapsack, not a new optimizer</strong>.</p><p>Named profiles live in hardware.py (odg/hardware/v1): RTX 3060 12 GB, MacBook Air 16 GB, and friends. You can also pass ad-hoc --gpu 24GB / --ram 32GB, or auto-detect (nvidia-smi, sysctl hw.memsize, /proc/meminfo) with an explicit confirmation line so wrong detection never silently misallocates.</p><p>Usable fractions are conservative by design: ~90% of VRAM on GPUs, ~70% of unified memory on Apple Silicon, ~60% of RAM on CPU boxes. Runtime overhead is reserved on top of weights + KV.</p><p><strong>odg experiment + </strong><strong>python benchmark.py — same model, same questions</strong></p><p>A single GGUF score is not a claim. The claim is:</p><blockquote><em>At approximately the same compression level, OpenDynamicGGUF retains more task quality than uniform Q4_K_M.</em></blockquote><p>That requires BF16 (or a documented source GGUF) + uniform Q4_K_M / Q5_K_M / Q6_K + OpenDynamicGGUF, identical harness settings, and a size column sitting next to quality. Quantization is the only independent variable.</p><p>Default subject today: FunctionGemma 270M (functiongemma:latest / google/functiongemma-270m-it).</p><p>Pinned tasks: MMLU, GSM8K, HellaSwag, ARC-Challenge. Test splits only (HellaSwag uses the labeled val split — the public test file has no labels). Training data is never scored. Files are read in their <strong>published formats</strong> (Hendrycks CSV, OpenAI JSONL, HellaSwag JSONL, AI2 JSONL), not rewritten into a custom schema.</p><p>Two suites, never mixed:</p><ul><li><strong>dev</strong> (default) — 500 / 200 / 500 / 200 items (~1,400). Fast loop while changing the quantizer.</li><li><strong>release</strong> — full official splits (~26K items: ~14,042 MMLU, 1,319 GSM8K, ~10,042 HellaSwag val, 1,172 ARC-C). Published comparison.</li></ul><p>Subsets are the <strong>first N rows of the official file order</strong>, so every GGUF sees the same questions.</p><p>The HF-free scorer prefers llama-server. If that binary cannot load a particular GGUF (for example a vocab-size mismatch against an Ollama blob), it falls back to a matching Ollama tag for greedy generation. HellaSwag still needs continuation log-likelihood and is skipped on the Ollama path.</p><p>FunctionGemma 270M is a <strong>function-calling specialist</strong>. Absolute MMLU / GSM8K will be low. Report <strong>retention vs the source GGUF</strong>, not SOTA. A better score at a much larger file than Q4_K_M is not an interesting quantization result. Quality <strong>at similar size</strong> is.</p><p><strong>odg report — one self-contained </strong><strong>report.html</strong></p><p>Renders from artifacts the steps already wrote: bit-allocation table with per-group reasons, byte distribution, sensitivity heatmap, size↔quality Pareto frontier, Tier-1 gates, benchmarks, and a reproducibility block. Sections for steps that have not run render as “not run.” odg run / odg fit auto-render it after validate.</p><pre>odg report --model functiongemma:latest --open</pre><h3>Terminal UI</h3><p>ui.py is a Rich-powered terminal UI: themed panels, step progress, tables, explanations after each step. The engine stays headless; the CLI is a client. The future Web UI will follow the same rule.</p><h3>One-command path</h3><pre>git clone https://github.com/imrrohitt/OpenDynamicGGUF.git<br>cd OpenDynamicGGUF<br>python -m venv .venv &amp;&amp; source .venv/bin/activate<br>pip install -e .</pre><pre># llama.cpp for a real GGUF<br>export LLAMA_CPP_DIR=~/llama.cpp<br>odg run --model functiongemma:latest --quant q4_k_m --no-ask<br>odg status --model functiongemma:latest</pre><p>Useful knobs: --until catalog to stop early, --from-step optimize to resume, --new-run for a fresh run, --prefer-hf for true BF16, --strict on validate to refuse a missing GGUF.</p><p>Cost on a 2–8B model, one workstation (24 GB GPU or Apple Silicon 32 GB+): catalog in minutes; imatrix + logits tens of minutes (once per model/corpus); one probe 5–15 minutes; full ~25-group sweep overnight and embarrassingly parallel; greedy + refinement a few hours; Tier 3 benchmarks hours. Nothing here needs a cluster. 70B+ and large MoE use the same pipeline with more patience.</p><h3>8. From a quantization tool to an open optimization platform</h3><p>The engine answers:</p><pre>BF16 model + size budget → best per-tensor GGUF</pre><p>The platform answers the question people actually type into Discord:</p><pre>&quot;I have this hardware and this workload — give me the best model, prove it, and let me share it.&quot;</pre><p>Nothing already built is thrown away. New layers wrap the 15-step engine:</p><pre>Today                          Platform<br>─────                          ────────<br>BF16                           Model (any ref, any source)<br> ↓                              ↓<br>GGUF                           Analyze     (catalog, features, sensitivity)<br>                                ↓<br>                               Search      (recipes, AutoML, multi-objective)<br>                                ↓<br>                               Optimize    (hardware-aware bit allocation)<br>                                ↓<br>                               Validate    (benchmarks, gates, security scan)<br>                                ↓<br>                               Publish     (reports, model cards, HF, leaderboard)</pre><h3>Layered architecture</h3><pre>┌─────────────────────────────────────────────────────────────────────┐<br>│  INTERFACE LAYER                                                     │<br>│  cli.py (odg)  ·  Web UI  ·  GitHub Action (CI/CD)                   │<br>├─────────────────────────────────────────────────────────────────────┤<br>│  DISTRIBUTION LAYER                                                  │<br>│  Recipe marketplace  ·  Public leaderboard  ·  HF publish  ·  Cards  │<br>├─────────────────────────────────────────────────────────────────────┤<br>│  TRUST LAYER                                                         │<br>│  HTML reports  ·  Explainability  ·  Security scanner  ·  Benchmarks │<br>├─────────────────────────────────────────────────────────────────────┤<br>│  DECISION LAYER                                                      │<br>│  Hardware profiles  ·  Multi-objective optimizer  ·  Recipe search   │<br>│  (AutoML)  ·  Calibration dataset builder                            │<br>├─────────────────────────────────────────────────────────────────────┤<br>│  CORE ENGINE (exists today — steps 01–15)                            │<br>│  resolve · load · enumerate · classify · catalog · features ·        │<br>│  corpus · freeze · imatrix · logits · sensitivity · optimize ·       │<br>│  export · validate — checkpointed run store                         │<br>├─────────────────────────────────────────────────────────────────────┤<br>│  EXTENSION LAYER (cross-cutting)                                     │<br>│  Plugin system: metrics / search algorithms / exporters / eval tasks │<br>└─────────────────────────────────────────────────────────────────────┘</pre><p>Rules per layer:</p><ul><li><strong>Core engine</strong> — measure, search, export, gate. Content-addressed, resumable. The JSON artifact contract never changes.</li><li><strong>Decision</strong> — translate <em>user intent</em> (hardware, workload, trade-offs) into engine inputs (budgets, pins, objectives). Users say “16 GB MacBook,” never “3.2 GB budget.”</li><li><strong>Trust</strong> — every decision inspectable: reports, reasons, benchmarks, checksums. No number without a source artifact.</li><li><strong>Distribution</strong> — move recipes and results between users. Recipes are the unit of sharing, not GGUF files.</li><li><strong>Interface</strong> — CLI first; Web UI and CI are thin clients over the same engine. No logic lives in an interface.</li><li><strong>Extension</strong> — third-party metrics / search / exporters / evals without touching core.</li></ul><h3>Platform invariants (non-negotiable)</h3><ol><li><strong>The engine stays headless.</strong> Web UI, CI action, and marketplace are clients of the same run store and CLI.</li><li><strong>Recipes are the unit of exchange.</strong> GGUF binaries are always rebuildable from recipe + source hash.</li><li><strong>Intent in, budget out.</strong> Only the decision layer translates hardware/workload to bytes/pins.</li><li><strong>No unmeasured claim leaves the system.</strong> Reports, cards, and leaderboard rows link every number to a run artifact hash.</li><li><strong>Paired statistics or nothing.</strong> All published comparisons are paired vs the BF16 reference with confidence intervals.</li><li><strong>Plugins extend; forks are a bug.</strong> If a contributor must patch core to add a metric, search strategy, exporter, or eval, the plugin API is missing a hook.</li></ol><h3>9. Next plans — in detail</h3><p>Phase 1 (Decide) is implemented: hardware-aware odg fit, same-model experiments, HTML reports.</p><p>Everything below is the published roadmap, split into four more phases. Each feature is designed as small, shippable steps — the same way the core pipeline was.</p><h3>Phase 2 — Share (recipes become an ecosystem)</h3><p><strong>Recipe marketplace.</strong> The biggest ecosystem gap: everyone ships better GGUF <em>files</em>, nobody ships shared, reproducible <em>decisions</em>. A recipe is tiny (KB), auditable, and rebuilds the GGUF bit-for-bit. Sensitivity probing is expensive; once one person has paid that cost for Gemma 27B on a 12 GB card, nobody else should have to.</p><pre>odg recipe gemma4-27b --device macbook-air-16gb   # fetch + build best match<br>odg recipe qwen3 --workload coding<br>odg recipe list gemma4-27b<br>odg recipe submit ./my-recipe.yaml                # validate before a PR</pre><p>The marketplace is a recipes/ tree in git (later optionally a dedicated repo). Submission is a pull request — review, history, attribution, hosting for free. Schema v2 adds metadata on top of today&#39;s v1: model family, target hardware, workload (coding | chat | reasoning | math | tools | general), author, and <strong>measured</strong> results (size, mean KLD, perplexity, tok/s) linked to run artifacts.</p><p><strong>Public leaderboard.</strong> Once recipes are shareable and results are standardized, a leaderboard is the flywheel. Comparison drives contribution. Newcomers get an obvious “which quant should I download” answer that no Hub model-page scatter provides today.</p><pre>OpenDynamicGGUF Leaderboard<br>Gemma · Qwen · Llama · DeepSeek · Mistral · GLM · Phi</pre><pre>Recipe          Size     PPL    mean KLD   MMLU Δ vs BF16    tok/s<br>rtx-3060.yaml   10.8 GB  6.91   0.0074     −0.2 [−0.9, +0.5] 34.2</pre><p>No backend. A static site generated from checked-in JSON. Rows are recipes. Each row links to report.html. odg/benchresult/v1 is the only accepted evidence format — no unmeasured claims on the board.</p><p><strong>Hugging Face integration.</strong> Publishing quantized models today is a dozen manual steps, so most quants ship with no recipe, no report, and a copy-pasted card. Make the <em>documented, reproducible</em> release the path of least resistance:</p><pre>odg publish --model unsloth/Qwen3.6 --gpu 16GB --hf-repo me/Qwen3.6-UD</pre><p>Download BF16 → optimize (hardware-aware) → benchmark → generate a model card → upload GGUF(s) + recipe.yaml + report.html + benchresult.json. Resumable like everything else. Refuses to upload if validation gates failed (--allow-ungated stamps a visible warning). Provenance is embedded twice: GGUF KV metadata and a reproduce block on the card.</p><p>Multiple Pareto points can land in one repo (--pareto top3); each GGUF pairs with its own recipe.</p><h3>Phase 3 — Deepen (better answers, not just easier answers)</h3><p><strong>Calibration dataset builder.</strong> Calibration data quality is known to matter a lot, but good corpora are curated privately. The community mostly falls back to WikiText, which does not even exercise chat templates. An <strong>open calibration pipeline</strong> (sources + mixing weights + rendering, all versioned) makes every imatrix and sensitivity table reproducible end-to-end.</p><pre>odg corpus --model qwen3 --workload coding<br>odg corpus --model gemma4 --workload tools --target-tokens 800000<br>odg corpus --model llama4 --mix &quot;chat:0.4,coding:0.3,math:0.2,multilingual:0.1&quot;</pre><p>Workloads: coding, chat, reasoning, math, tools, long-context, general (+ plugins). Step 07’s 60/20/20 split and hard walls stay untouched. This feature upgrades <em>where the text comes from</em>.</p><p><strong>Recipe search (AutoML).</strong> Greedy + local refinement assumes per-group effects are additive. That is ~90% right. Interaction effects are real — especially in MoE and hybrid models — and the remaining 10% is exactly where an open project can beat closed heuristics.</p><pre>odg optimize --model gemma4 --search evolutionary --eval-budget 40</pre><p>Generate many candidate recipes → score cheaply with the additive model from the sensitivity table → measure the promising ones with real joint KLD → return a <em>measured</em> Pareto frontier. Neural-architecture-search methodology applied to bit allocation. Every candidate eval is content-addressed, so repeated configs are free.</p><p><strong>Multi-objective optimization.</strong> Different users sit at different points. A chatbot host wants latency. A laptop user wants RAM headroom. A batch-eval user wants raw quality. Today the optimizer has exactly one currency: bytes saved / ΔKLD.</p><pre>odg fit --model qwen3 --gpu 12GB --objective quality<br>odg fit --model qwen3 --gpu 12GB --objective speed<br>odg fit --model qwen3 --gpu 12GB --objective balanced<br>odg fit --model qwen3 --ram 16GB --objective &quot;quality:0.5,speed:0.3,ram:0.2&quot;</pre><p>Objectives: quality, speed, vram, ram, latency (energy later, once measurable reliably). Quality comes from measured ΔKLD. VRAM/RAM from exact bytes + KV math. Speed from a bandwidth model corrected by dequant cost, validated by llama-bench spot checks. Latency from a prompt-processing model.</p><p><strong>Explainability.</strong> Trust in the optimizer <em>is</em> the product. The data already exists — the sensitivity table and the optimizer log. This feature is a renderer:</p><pre>$ odg explain --model gemma4-27b</pre><pre>token_embd → Q8_0   pinned: touched by every token; probe Q4_K cost<br>                     ΔKLD +0.055 for only 190 MB saved</pre><pre>attn_v (all layers) → Q6_K<br>                     pinned: probe Q4_K showed ΔKLD +0.037 for 45 MB</pre><pre>ffn_up (mid layers) → Q3_K<br>                     cheap bits: 310 MB saved for ΔKLD +0.004</pre><pre>ffn_down (mid layers) → Q4_K<br>                     Q3_K probe rejected: ΔKLD +0.019 exceeded cutoff</pre><p>Cheapest five-star feature in the list. Can ship almost immediately.</p><h3>Phase 4 — Harden (trust + extensibility)</h3><p><strong>Automatic model cards.</strong> Honest model cards for quants are rare because writing one requires collecting exactly the numbers this pipeline already produces. odg card generates an HF-ready README.md from run artifacts: optimization settings, corpus recipe, paired benchmark deltas vs BF16 with CIs, supported hardware and context lengths, memory tables (weights + KV at 4k / 8k / 32k), throughput (measured vs predicted, labeled as such), known limitations, reproduce block.</p><p>Documentation becomes a free by-product. odg publish ships complete repos by default.</p><p><strong>Plugin system.</strong> Every “can you add metric / algorithm / format X” issue currently means a core PR. Four seams already exist implicitly. Make them official:</p><pre>[project.entry-points.&quot;odg.metrics&quot;]<br>js_divergence = &quot;odg_jsd.metric:JSDivergence&quot;</pre><pre>[project.entry-points.&quot;odg.search&quot;]<br>anneal = &quot;odg_anneal.search:SimulatedAnnealing&quot;</pre><pre>[project.entry-points.&quot;odg.exporters&quot;]<br>mlx = &quot;odg_mlx.export:MlxExporter&quot;</pre><pre>[project.entry-points.&quot;odg.evals&quot;]<br>sql_suite = &quot;odg_sql.evals:SqlEvalSuite&quot;</pre><pre>pip install odg-anneal<br>odg optimize --model x --search anneal<br>odg plugins list</pre><p>Built-in implementations register through the same mechanism so the plugin path is exercised constantly, not only by third parties. If a contributor must patch core to add a metric, the API is missing a hook.</p><p><strong>Security scanner.</strong> Research (<em>Mind the Gap</em>) showed that malicious behavior can be hidden specifically in the quantization gap — a model that behaves benignly in full precision and differently when quantized. Users download GGUF binaries from strangers daily with no verification story.</p><p>This project is uniquely positioned to provide one, because reproducibility is already the core design: <strong>a recipe + source hash is a verifiable claim, and the scanner is the verifier.</strong></p><pre>odg scan model-UD.gguf --recipe recipe.yaml</pre><pre>✓ recipe schema + hashes valid<br>✓ source model provenance: google/gemma-4-e2b-it @ 9f2c…<br>✓ per-tensor checksums match reproduced build (312/312)<br>✓ no unexpected tensors / metadata keys<br>✓ quant-type map matches recipe assignments</pre><pre>PASS — bit-for-bit reproducible from recipe</pre><p>No other GGUF tooling can offer this without reinventing the recipe contract.</p><h3>Phase 5 — Broaden (new audiences on a now-stable engine)</h3><p><strong>CI/CD GitHub Action.</strong> Fine-tune authors rarely ship good quants — it is manual, hardware-dependent work outside their release flow. Put the whole pipeline behind one Action:</p><pre># .github/workflows/release-gguf.yml<br>on:<br>  push: {tags: [&quot;v*&quot;]}</pre><pre>jobs:<br>  gguf:<br>    runs-on: [self-hosted, gpu]<br>    steps:<br>      - uses: opendynamicgguf/action@v1<br>        with:<br>          model: ./checkpoint<br>          device-targets: &quot;rtx-3060-12gb,mac-16gb&quot;<br>          workload: chat<br>          suite: standard<br>          hf-repo: me/my-model-GGUF<br>          hf-token: ${{ secrets.HF_TOKEN }}</pre><p>Push a model → optimize → benchmark → scan → publish GGUF + recipe + report + card.</p><p>The action is a <strong>thin client</strong>: a composite action + container that installs odg + llama.cpp and runs odg publish. All logic stays in the CLI. Sensitivity probing wants a GPU, so the documented path is a self-hosted GPU runner. A recipe-only mode skips search and builds from an existing marketplace recipe on CPU runners.</p><p><strong>Web UI (and the backend it sits on).</strong> Every earlier feature made decisions easier for CLI users. The Web UI removes the CLI requirement entirely.</p><pre>odg ui   # → http://localhost:8000</pre><pre>Pick model (HF id / local path / Ollama tag)<br>        ↓<br>Select hardware (device picker or auto-detect)<br>        ↓<br>Select workload + objective + target size<br>        ↓<br>Optimize (live step progress, resumable)<br>        ↓<br>Explore report → Download GGUF + recipe</pre><p><strong>Local-first.</strong> odg ui serves on localhost. The model, the compute, and the artifacts stay on the user&#39;s machine. No hosted SaaS in v1 scope.</p><p><strong>Backend: FastAPI over the run store.</strong> The API mirrors the CLI 1:1:</p><ul><li>POST /runs = odg fit</li><li>GET /runs/{id} = odg status</li><li>log tails stream over SSE</li><li>cancel / resume use the same checkpoints the CLI uses</li></ul><p>If an endpoint needs new logic, that logic goes into core first. <strong>Zero optimization logic in </strong><strong>webui/.</strong> That is a review checklist item, not a slogan.</p><p>Screens:</p><ul><li><strong>New-run wizard</strong> — model → hardware → workload → live budget preview (“your 12 GB → 8.9 GB weight budget”)</li><li><strong>Run monitor</strong> — step list, live logs, cancel/resume (the 15-step checkpoint layout already <em>is</em> a progress model)</li><li><strong>Results</strong> — allocations, explanations, KLD, Pareto picker that triggers export of the chosen alternative</li><li><strong>Recipe browser</strong> — marketplace search, one-click build</li><li><strong>Downloads</strong> — GGUF, recipe, report, card</li></ul><p>Build order is conservative on purpose: API server usable via curl first; read-only run monitor over CLI-started runs second; wizard third; results and marketplace last. Frontend bundled into the wheel so pip install + odg ui works offline with no Node toolchain.</p><p>The CLI Rich UI (ui.py) stays. The Web UI is the same engine, a different glass.</p><p>Later, a hosted control plane can sit in front of the same API — remote runners, shared recipe cache, team leaderboards — without forking the optimizer. The invariant still holds: hosted UI is another client.</p><h3>More models, more evals, more surfaces</h3><p>The architecture is family-agnostic. The practical next work on models:</p><ul><li><strong>More families in the resolver</strong> — new Hugging Face layouts, more Ollama tags, more MLX traces back to BF16.</li><li><strong>Richer role taxonomies</strong> — extra MoE expert grouping, SSM variants, vision-language towers, encoder–decoder if and when GGUF export supports them cleanly.</li><li><strong>True BF16 studies as the default comparison</strong> — --prefer-hf end-to-end, not Ollama Q8 promoted to a &quot;source.&quot;</li><li><strong>Larger default subjects</strong> — 1B–8B dense, then 27B-class, then MoE where dynamic quant pays the most.</li><li><strong>Per-expert bit allocation from usage counts</strong> — deferred from v1, high leverage on MoE.</li><li><strong>KV-cache quantization sensitivity</strong> — weights are only half of what actually fits in VRAM at 8k / 32k context.</li><li><strong>Attention-head and neuron-level importance</strong> — finer than role × depth when the extra probes are worth it.</li><li><strong>Workload-specialized recipes</strong> — coding vs chat vs tools vs math, sharing a catalog but not a corpus.</li></ul><p>On evaluation:</p><ul><li>Finish the <strong>release</strong> suite on FunctionGemma and publish retention-vs-source, not absolute SOTA.</li><li>Add <strong>ARC-Easy</strong>, <strong>TruthfulQA</strong>, a <strong>fixed local perplexity corpus</strong> (task scores miss distributional degradation), and <strong>HumanEval / MBPP</strong> for code models.</li><li>Domain gates for tool-calling: schema-valid JSON, argument types, refusal behavior.</li><li>Throughput (llama-bench) next to quality and size on every comparison row.</li><li>Paired CIs on every public number. No mixing dev tables with release tables.</li></ul><p>On search:</p><ul><li>Evolutionary / annealing search behind --search, beating greedy on joint KLD with a fixed eval budget.</li><li>LLM-in-the-loop failure analysis that <em>suggests</em> recipe changes when a gate fails — never silently applies them.</li></ul><p>None of this requires throwing away the engine. Catalog, probes, knapsack, recipe, gates stay the contract.</p><h3>10. How a full platform run will feel</h3><p>One command, several layers, one run store:</p><pre>odg publish --model unsloth/Qwen3.6 --gpu 16GB --workload coding --hf-repo me/qwen3.6-ud</pre><pre>hardware.py       16GB GPU + ctx target → byte budget + KV reserve<br>calib_builder.py  workload=coding → coding-heavy calib corpus<br>core engine       steps 01–12 → sensitivity table<br>autosearch.py     candidates around greedy → Pareto frontier of recipes<br>objectives.py     quality × speed × vram → pick frontier point for this profile<br>core engine       steps 13–15 → GGUF + gates<br>experiment.py     BF16 / Q4 / Q5 / Q6 / ODG → comparison.md<br>explain.py        sensitivity + recipe → per-group reasons<br>report.py         all artifacts → report.html<br>scan.py           recipe replay + checksums → provenance block<br>modelcard.py      everything above → README.md<br>publish.py        HF Hub → GGUF + recipe + report + card<br>leaderboard       benchresult.json PR → public comparison row</pre><p>Every arrow is a checkpointed step. Resumable. Cached. Content-addressed. The Web UI and the GitHub Action call the same functions.</p><h3>11. Related work (standing on, not replacing)</h3><ul><li><strong>Unsloth Dynamic 2.0 GGUFs</strong> — per-layer/per-tensor dynamic bit assignment, curated chat/code calibration, KLD-first evaluation, the calibration-overfitting critique. The existence proof. Not open.</li><li><strong>llama.cpp</strong> — --tensor-type / --tensor-type-file, imatrix, --dry-run, llama-perplexity --kl-divergence. The execution layer.</li><li><strong>E. Addario’s LWQ/TWQ</strong> — --tensor-type plus imatrix statistics to guide assignment.</li><li><strong>Community calibration sets</strong> — bartowski’s Calibration_v3 / v5, used widely for fair KLD testing.</li><li><strong>GPTQ, AWQ, SmoothQuant, HQQ, AQLM</strong> — post-training methods and calibration methodology.</li><li><strong>“Accuracy is not all you need”</strong> — motivation for KLD / agreement metrics over accuracy-only evaluation of compressed models.</li><li><strong>Mixed-precision / KL-sensitivity literature</strong> — statistics as prior, KL as decision.</li><li><a href="https://github.com/EleutherAI/lm-evaluation-harness"><strong>lm-evaluation-harness</strong></a> — Tier-3 runner (with the known GGUF-eval caveats).</li><li><strong>Mind the Gap</strong> — quantization-time behavioral gaps; the reason a scanner belongs in a GGUF toolchain.</li></ul><p>OpenDynamicGGUF does not invent mixed precision. It makes the <em>optimizer</em>, the <em>recipe</em>, and the <em>proof</em> open.</p><h3>12. Try it</h3><pre>git clone https://github.com/imrrohitt/OpenDynamicGGUF.git<br>cd OpenDynamicGGUF<br>python -m venv .venv &amp;&amp; source .venv/bin/activate<br>pip install -e .</pre><pre>odg formats                                          # q4_k_m, q5_k_m, iq4_xs, …<br>odg run --model functiongemma:latest --quant q4_k_m --no-ask<br>odg fit --model functiongemma:latest --gpu 12GB<br>odg report --model functiongemma:latest --open</pre><p>Full walkthrough (llama.cpp setup, dry-run vs real GGUF, troubleshooting): <a href="https://github.com/imrrohitt/OpenDynamicGGUF/blob/main/docs/USAGE.md">docs/USAGE.md</a></p><p>Step-by-step design docs (each with goal, why, inputs/outputs, done-when): <a href="https://github.com/imrrohitt/OpenDynamicGGUF/tree/main/docs/steps">docs/steps/</a></p><p>Platform feature breakdowns: <a href="https://github.com/imrrohitt/OpenDynamicGGUF/tree/main/docs/platform">docs/platform/</a> and <a href="https://github.com/imrrohitt/OpenDynamicGGUF/blob/main/ARCHITECTURE.md">ARCHITECTURE.md</a></p><pre>pip install -e &quot;.[dev]&quot;<br>pytest</pre><p>Contributions are welcome — additional model families in the resolver, role taxonomies for new architectures, real llama-backed probes, eval tasks, marketplace recipes, UI, anything that respects the contract: <strong>JSON artifacts in the run store; statistics prioritize; ΔKLD decides; held-out validation ships.</strong></p><h3>Closing</h3><p>Local LLMs got good because llama.cpp made inference a file on disk. Quantization got good because k-quants, IQ formats, and imatrix made that file small enough to live on a laptop.</p><p>What is still missing is an <strong>open optimizer</strong> that treats bit allocation as a measured search problem, not a preset — and a <strong>platform</strong> that lets you say “16 GB MacBook, coding workload,” get a GGUF, see why every group got its bits, prove it against BF16 on the same questions, and share the recipe so the next person does not pay the probe cost again.</p><p>That is OpenDynamicGGUF.</p><p>Give it a model. Give it a budget — or just give it your GPU. Get back a file, a recipe, and a report. Then help make the next layer real: more models, honest benchmarks, a marketplace, a leaderboard, a Web UI, a scanner, a one-line GitHub Action.</p><p>The kernels already exist. The missing piece was the loop around them.</p><p><strong>Open. Measured. Reproducible.</strong></p><p><em>Apache License 2.0. Built on </em><a href="https://github.com/ggml-org/llama.cpp"><em>llama.cpp</em></a><em>. Inspired by the dynamic-quantization work published by the community — this project’s goal is to make that process open, measured, and reproducible.</em></p><p><strong>GitHub:</strong> <a href="https://github.com/imrrohitt/OpenDynamicGGUF">imrrohitt/OpenDynamicGGUF</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ca130764ee4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing Nested Try/Except Hell: The AWS Service That Replaces Your Entire Workflow Engine]]></title>
            <link>https://medium.com/@imrohitkushwaha2001/stop-writing-nested-try-except-hell-the-aws-service-that-replaces-your-entire-workflow-engine-c992834fdabb?source=rss-9d49c6e4b94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c992834fdabb</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Rohit Kushwaha]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 02:16:28 GMT</pubDate>
            <atom:updated>2026-09-05T02:16:28.558Z</atom:updated>
            <content:encoded><![CDATA[<h3>If your Lambda functions are calling other Lambda functions wrapped in retry logic wrapped in more retry logic, you’re solving a problem AWS already solved for you.</h3><p>Picture this: you’re building an AI document-processing system. A user uploads a PDF, and behind the scenes you need to extract pages, run OCR, chunk the document, generate embeddings, store them in a vector database, run a quality check, and notify the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIr5kofjvGbAd6_NHgk0PA.jpeg" /><figcaption>AWS Service That Replaces Your Entire Workflow Engine</figcaption></figure><pre>Upload PDF<br>   ↓<br>Extract pages<br>   ↓<br>OCR<br>   ↓<br>Chunk document<br>   ↓<br>Generate embeddings<br>   ↓<br>Store in Vector DB<br>   ↓<br>Run quality check<br>   ↓<br>Notify user</pre><p>That’s five to ten different services — S3, Lambda, ECS, Bedrock, a vector database, SNS — all needing to call each other, handle retries, manage timeouts, branch conditionally, run things in parallel, and track what actually happened at every step.</p><p>Do this by hand, and your code quietly turns into a nightmare:</p><pre>try:<br>    result = service_a()<br>    try:<br>        result = service_b(result)<br>        try:<br>            result = service_c(result)<br>        except:<br>            retry_service_c()<br>    except:<br>        retry_service_b()<br>except:<br>    retry_service_a()</pre><p>Business logic and workflow orchestration get tangled into one unmanageable mess. This is exactly the problem AWS Step Functions was built to solve — it lets you orchestrate a complex, multi-step application without writing your own workflow engine from scratch.</p><p>Here’s how it actually works, and why it matters more than most engineers realize.</p><h3>1. What Step Functions actually is</h3><p>Think of it as a managed <strong>workflow engine</strong>. You define a <strong>state machine</strong> — a diagram of steps and decisions:</p><pre>START<br>  ↓<br>Validate Document<br>  ↓<br>Extract Text<br>  ↓<br>Is OCR required?<br>  ├── YES → OCR<br>  │          ↓<br>  └── NO ───┘<br>       ↓<br>Generate Embeddings<br>       ↓<br>Store Vectors<br>       ↓<br>SUCCESS</pre><p>Each box is a <strong>State</strong>. AWS supports several state types: Task, Choice, Parallel, Map, Wait, Pass, Succeed, and Fail.</p><h3>2. The concept beginners usually miss: it doesn’t do the work itself</h3><p>Step Functions is not a compute engine. It’s the <strong>orchestrator</strong> sitting above your actual compute services.</p><pre>                  Step Functions<br>                       │<br>        ┌──────────────┼──────────────┐<br>        ↓              ↓              ↓<br>      Lambda          ECS           Bedrock<br>        │              │              │<br>      OCR           Processing       LLM</pre><p>Step Functions says “run Lambda,” Lambda does the actual work, and Step Functions receives the result and decides what happens next — “Lambda succeeded, now run ECS,” then “ECS succeeded, call Bedrock.” It has native integrations with hundreds of AWS services: Lambda, ECS/Fargate, EKS, SQS, DynamoDB, Bedrock, SageMaker, Glue, and more.</p><h3>3. Why not just chain Lambda calls directly?</h3><p>Because Step Functions gives you <strong>workflow state</strong> — it remembers exactly where an execution is.</p><p>If step 3 out of 4 fails in a hand-rolled system, you’re often left guessing where things broke. With Step Functions, you can inspect an execution directly:</p><pre>Execution ID: abc123</pre><pre>✓ Validate<br>✓ Extract<br>✓ Chunk<br>✗ Embeddings<br>○ Store<br>○ Notify</pre><p>Standard workflows retain execution history you can view and debug, and Step Functions natively supports retries, catch handlers, and redriving failed executions from where they stopped.</p><h3>4. Error handling, built in</h3><p>Say your embeddings service fails intermittently. You can define the failure path directly in the workflow:</p><pre>Generate Embeddings<br>       │<br>       ├── SUCCESS → Store<br>       │<br>       └── ERROR<br>             ↓<br>           Retry<br>             ↓<br>        Wait 10 seconds<br>             ↓<br>           Retry<br>             ↓<br>        Still failed?<br>             ↓<br>           Catch<br>             ↓<br>        Send to DLQ</pre><p>Retries, catch handlers, timeouts, failure states, and execution tracking all come out of the box — you’re not reimplementing orchestration logic by hand every time.</p><h3>5. Conditional branching</h3><p>Step Functions can also make decisions mid-workflow using a Choice state:</p><pre>                Analyze document<br>                       ↓<br>                 pages &gt; 100?<br>                  /        \<br>                YES         NO<br>                 ↓           ↓<br>             ECS job      Lambda<br>                 \           /<br>                  \         /<br>                   ↓       ↓<br>                     Store</pre><p>Conceptually, this looks like:</p><pre>{<br>  &quot;Type&quot;: &quot;Choice&quot;,<br>  &quot;Choices&quot;: [<br>    {<br>      &quot;Variable&quot;: &quot;$.pages&quot;,<br>      &quot;NumericGreaterThan&quot;: 100,<br>      &quot;Next&quot;: &quot;LargeDocumentProcessor&quot;<br>    }<br>  ],<br>  &quot;Default&quot;: &quot;NormalProcessor&quot;<br>}</pre><p>The orchestration logic lives inside the workflow definition itself instead of being buried in application code.</p><h3>6. Parallel processing</h3><p>Some operations in a pipeline don’t depend on each other at all:</p><pre>Document<br>                 ↓<br>       ┌─────────┼─────────┐<br>       ↓         ↓         ↓<br>      OCR     Metadata   Images<br>       ↓         ↓         ↓<br>       └─────────┼─────────┘<br>                 ↓<br>               Merge</pre><p>Step Functions can run these branches concurrently. For large datasets, its Map state processes each item in a collection, and a Distributed Map mode is designed specifically for large-scale, high-volume workloads.</p><h3>7. Where this gets genuinely interesting for AI systems</h3><p>If you’re building agentic or RAG-based AI pipelines, this pattern should look familiar:</p><pre>User Request<br>                      ↓<br>                  Classifier<br>                      ↓<br>               ┌──────┴──────┐<br>               ↓             ↓<br>            RAG Search    Tool Call<br>               ↓             ↓<br>               └──────┬──────┘<br>                      ↓<br>                 LLM Reasoning<br>                      ↓<br>                 Safety Check<br>                      ↓<br>              Human Approval?<br>                /          \<br>              YES           NO<br>               ↓             ↓<br>         Human Review      Continue<br>               \             /<br>               └──────┬──────┘<br>                       ↓<br>                  Final Answer</pre><p>AWS explicitly documents patterns for using Step Functions for prompt chaining with Bedrock and for orchestrating Bedrock AgentCore workflows — this isn’t a stretch use case, it’s a supported one.</p><h3>8. Human-in-the-loop workflows</h3><p>This is where it gets useful for enterprise-grade systems. Imagine an AI-assisted loan decision:</p><pre>AI generates loan decision<br>        ↓<br>Risk &gt; threshold?<br>        ↓<br>      YES<br>        ↓<br>Wait for human approval<br>        ↓<br>Approved?<br>   /       \<br> YES        NO<br> ↓          ↓<br>Process    Reject</pre><p>The workflow can genuinely <strong>pause</strong> and wait for an external event — no server sitting idle burning compute. This is exactly the kind of thing you need for financial approvals, content moderation, HR processes, procurement, medical workflows, and enterprise agent actions that require a human checkpoint. Step Functions supports this through Wait states and callback/task-token patterns designed for exactly this kind of external completion.</p><h3>9. Step Functions vs. SQS vs. Kafka vs. Celery</h3><p>These tools get confused constantly, so here’s the actual distinction:</p><p><strong>SQS</strong> — “give me a message and process it.”</p><pre>Producer → SQS → Worker</pre><p><strong>Kafka</strong> — “I have a continuous event stream.”</p><pre>Producer → Kafka → Consumers</pre><p><strong>Celery</strong> — “I want distributed background task execution.”</p><pre>API → Redis/RabbitMQ → Celery Workers</pre><p><strong>Step Functions</strong> — “I have a multi-step business process and need to control the entire workflow.”</p><pre>Step Functions<br>                   ↓<br>      ┌────────────┼────────────┐<br>      ↓            ↓            ↓<br>   Lambda         ECS        Bedrock<br>      ↓            ↓            ↓<br>      └────────────┼────────────┘<br>                   ↓<br>                  S3</pre><p>Step Functions isn’t competing with Kafka or SQS — it’s solving a different layer of the problem entirely.</p><h3>10. Standard vs. Express: pick the right one</h3><p>There are two workflow types, and picking wrong will cost you.</p><p><strong>Standard</strong> is built for long-running, durable, auditable business processes — up to a full year in duration. It uses an exactly-once execution model by default. Use it for something like:</p><pre>Order → Payment → Inventory → Shipping → Invoice</pre><p>where you absolutely cannot afford duplicate payment processing.</p><p><strong>Express</strong> is built for high-volume, short-lived workloads — event processing, streaming data, mobile backends — capped at 5 minutes. It uses at-least-once execution semantics, which means your tasks need to be idempotent. Think:</p><pre>Event → Validate → Transform → Store</pre><p>running millions of times a day.</p><h3>11. The cost model nobody reads until the bill arrives</h3><p>Step Functions is serverless, but that doesn’t mean free. Standard workflows are billed primarily by <strong>state transitions</strong>, and AWS provides 4,000 free Standard transitions per month — with retries also counting toward that total.</p><p>Quick math: a workflow with 5 transitions per execution, run 100,000 times:</p><pre>5 × 100,000 = 500,000 transitions</pre><p>At a US East example rate of $0.000025 per Standard transition:</p><pre>500,000 × $0.000025 ≈ $12.50</pre><p>before the free tier, and not counting whatever the actual Lambda, ECS, or Bedrock calls cost underneath it.</p><h3>12. The mental model worth keeping</h3><p>Don’t think of Step Functions as another server. Think of it as <strong>a managed state machine that coordinates distributed services</strong>:</p><pre>EVENT<br>                    ↓<br>             STEP FUNCTIONS<br>                    │<br>       ┌────────────┼────────────┐<br>       ↓            ↓            ↓<br>    Lambda         ECS        Bedrock<br>       │            │            │<br>       └────────────┼────────────┘<br>                    ↓<br>                   S3<br>                    ↓<br>                PostgreSQL</pre><p>What it actually hands you:</p><pre>┌───────────────────────┐<br>│     ORCHESTRATION     │<br>├───────────────────────┤<br>│ ✓ sequencing           │<br>│ ✓ branching            │<br>│ ✓ parallel execution   │<br>│ ✓ retries               │<br>│ ✓ error handling        │<br>│ ✓ timeouts               │<br>│ ✓ waiting                 │<br>│ ✓ state                    │<br>│ ✓ execution tracking        │<br>└───────────────────────┘</pre><p>That’s the actual value proposition.</p><h3>The pattern worth memorizing</h3><p><strong>API/Event → Step Functions → Lambda/ECS/Bedrock → database/vector DB → notification</strong></p><p>Once this pattern clicks, you’ll start spotting it everywhere: RAG pipelines, AI agent workflows, document processing systems, ML pipelines, ETL jobs, payment systems, and general microservice orchestration. It’s not a niche tool — it’s the piece that lets you stop building bespoke workflow engines every time your architecture gets past three or four services deep.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c992834fdabb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Data Paradox No One Talks About: Why AI Companies Are Secretly Building Fake Enterprises to…]]></title>
            <link>https://medium.com/@imrohitkushwaha2001/the-data-paradox-no-one-talks-about-why-ai-companies-are-secretly-building-fake-enterprises-to-b1330320f19b?source=rss-9d49c6e4b94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1330320f19b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rohit Kushwaha]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 03:24:44 GMT</pubDate>
            <atom:updated>2026-09-04T03:24:44.409Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Data Paradox No One Talks About: Why AI Companies Are Secretly Building Fake Enterprises to Train Real Models</h3><h3>You need sensitive data to train a system that detects sensitive data — but you’re legally forbidden from using it. Here’s the workaround nobody’s talking about.</h3><p>Imagine you’re asked to build an AI model that can scan enterprise storage systems and automatically flag sensitive information — Social Security numbers, medical records, bank account details, legal disclosures — before they leak, get mishandled, or violate compliance regulations.</p><p>Sounds straightforward. Except there’s a catch that breaks the entire premise before you even start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bj1-L1Xf2E1bRCZBSDuBKw.png" /><figcaption>sensitive data to train a system that detects sensitive data</figcaption></figure><p><strong>The only data realistic enough to train this model is exactly the data you’re not allowed to touch.</strong></p><p>This isn’t a hypothetical. It’s the exact wall that data infrastructure and governance teams hit when they try to build PII/PHI detection systems, compliance classifiers, or data-governance AI at enterprise scale. And the way teams are solving it is more interesting — and more complicated — than most people realize.</p><p>Let’s break down the entire problem, why the obvious fixes don’t work, and the agentic architecture that’s emerging as the real solution.</p><h3>1. What’s the actual problem?</h3><p>Enterprise customers store millions of documents — healthcare records, financial reports, legal contracts, HR files, customer records, scanned PDFs, images, tables, charts, even handwritten notes.</p><p>Buried inside these documents:</p><pre>Name<br>Address<br>Phone number<br>Email<br>SSN<br>Credit card<br>Bank account<br>Medical information<br>Employee information<br>Company information</pre><p>The goal is to build a model that can answer one question: <strong>where is the sensitive information hiding?</strong></p><pre>Document:<br>Patient: John Smith<br>DOB: 12/04/1987<br>SSN: 123-45-6789<br>Diagnosis: ...</pre><pre>        ↓</pre><pre>  PII/PHI Detection Model</pre><pre>        ↓</pre><pre>SSN        → PII<br>DOB        → PII<br>Diagnosis  → PHI<br>Name       → PII</pre><p>To build this, you need enormous amounts of labeled training data. And that’s exactly where things fall apart.</p><h3>2. Problem #1: Real customer data is off the table</h3><p>The obvious move — “just train on customer documents” — is a non-starter.</p><p>Customer files are loaded with PII, PHI, financial and legal information. Using them for model development creates privacy exposure, regulatory risk, contractual violations, and potential data leakage. No customer wants their confidential files quietly becoming someone else’s training set.</p><p><strong>Real data = maximally realistic, but practically unusable.</strong></p><h3>3. Problem #2: Public datasets don’t cut it either</h3><p>Fine — download public datasets instead. That solves availability, but creates a new problem: public data doesn’t look like enterprise data.</p><p>A typical PII dataset gives you:</p><pre>John → PERSON<br>john@gmail.com → EMAIL<br>123-45-6789 → SSN</pre><p>Useful for basic entity recognition. But a real enterprise document looks more like this:</p><pre>INVESTMENT PROSPECTUS</pre><pre>Company Overview<br>────────────────────────────<br>Green Wage Inc.<br>Founded: 2012</pre><pre>Financial Performance<br>────────────────────────────<br>Revenue    2022   2023   2024<br>           $10M   $18M   $31M</pre><pre>Environmental Risk Assessment<br>...<br>Legal Disclosures<br>...<br>[Tables] [Charts] [Images] [Footnotes]</pre><p>Completely different distribution, structure, and complexity.</p><h3>4. The real gap: enterprise documents are just… complicated</h3><p><strong>Length.</strong> Public datasets are a few sentences or paragraphs. Real enterprise documents run 10, 50, even 100+ pages — some pipelines target generation ranges from roughly 1,000 to 100,000 tokens.</p><p><strong>Structure.</strong> Real files are full of paragraphs, tables, headers, footnotes, multi-column layouts, charts, images, signatures, and forms. Plain-text datasets teach a model none of this.</p><p><strong>Domain diversity.</strong> Enterprise data spans healthcare, finance, legal, HR, research, marketing, and operations — rarely covered comprehensively by one dataset.</p><p><strong>Language diversity.</strong> Global enterprises produce documents in English, French, German, Spanish, and beyond — with names and cultural context that need to actually make sense for the locale.</p><h3>5. Problem #3: Labeling is its own nightmare</h3><p>Say you have:</p><pre>John Smith        → PERSON<br>john@example.com  → EMAIL<br>123-45-6789       → SSN</pre><p>Someone has to label all of this — and human labeling at enterprise scale is expensive, slow, and inconsistent.</p><p>Worse: if you hand real customer documents to human annotators, you’ve just created a second privacy leak on top of the first one.</p><p>So the situation looks like this:</p><ul><li><strong>Real data</strong> → privacy problem</li><li><strong>Public data</strong> → realism problem</li><li><strong>Manual labeling</strong> → cost and privacy problem</li></ul><h3>6. Problem #4: Randomly faked data isn’t enough either</h3><p>“Why not just use a fake-data library?”</p><pre>fake.name()<br>fake.email()<br>fake.address()<br>fake.ssn()</pre><p>That gives you scattered, disconnected values. Now try building a 50-page legal document out of them. Randomly inserted fake values produce nonsense — because a real document needs internal consistency. “John Smith” has to remain John Smith throughout the document, and his address, company, role, and email need to logically match each other.</p><p>This is exactly the kind of relationship-modeling problem a language model is good at — which is where LLMs enter the picture.</p><h3>7. Why bring in a language model at all?</h3><p>Because an LLM can understand relationships, not just spit out isolated fake values.</p><p>Instead of “generate random PII,” you can prompt:</p><blockquote><em>Generate a healthcare document for a cardiologist in France containing realistic patient information, medical procedures, tables, and diagnostic results.</em></blockquote><p>The model can build the semantic structure underneath the document:</p><pre>Hospital → Department → Cardiology → Doctor → Patient → Diagnosis → Treatment → Follow-up</pre><p>That gets you a far more realistic document. But it still doesn’t solve everything.</p><h3>8. Why can’t you just ask an LLM for a 100-page document?</h3><p>Because long-form generation degrades. Ask for a “realistic 100-page financial prospectus” in one shot, and you tend to get:</p><pre>Page 1   → good<br>Page 10  → okay<br>Page 30  → repetitive<br>Page 60  → inconsistent<br>Page 80  → contradictory<br>Page 100 → incoherent</pre><p>The model forgets its own earlier details. Page 5 says the CEO is Alice; page 70 says it’s Michael. Revenue is $20M on one page and $35M on another with no explanation. Long documents need <strong>planning and controlled generation</strong>, not a single giant prompt.</p><h3>9. This is why an agentic pipeline exists</h3><p>Instead of:</p><pre>Prompt → LLM → Document</pre><p>the real architecture looks like:</p><pre>User requirements<br>      ↓<br>   Planner<br>      ↓<br>Vertical / Department / Persona<br>      ↓<br>   Prompt Sets<br>      ↓<br>Segment Generation<br>      ↓<br>Structured Data<br>      ↓<br>Tables / Charts / Images<br>      ↓<br>Quality Evaluation<br>      ↓<br>Safety Evaluation<br>      ↓<br>Final Document</pre><p>The “agent” isn’t magic. Its value is orchestration — planning, tool use, and iterative validation across a long generation process.</p><h3>10. Stage 1: Requirements</h3><p>Something like:</p><pre>Industry: Healthcare<br>Persona: Cardiologist<br>Documents: 5,000<br>Language: French<br>Length: 20–50 pages</pre><p>That defines the target distribution up front.</p><h3>11. Stage 2: Planning a hierarchy</h3><p>The planner builds out realistic organizational structure:</p><pre>Healthcare<br>│<br>├── Hospital<br>│   ├── Cardiology<br>│   │   ├── Doctor<br>│   │   ├── Nurse<br>│   │   └── Administrator<br>│   └── Oncology<br>│       ├── Doctor<br>│       └── Researcher<br>│<br>└── Insurance<br>    ├── Claims<br>    └── Underwriting</pre><p>This is what produces genuine diversity — instead of 50,000 near-identical documents, you get many distinct persona/department combinations.</p><h3>12. Stage 3: Prompt sets per persona</h3><p>For each persona, the system generates multiple document scenarios:</p><pre>Prompt A: Patient medical history<br>Prompt B: Clinical research report<br>Prompt C: Hospital discharge summary<br>Prompt D: Insurance claim<br>Prompt E: Treatment plan</pre><p>Each includes placeholders:</p><pre>{{PATIENT_NAME}} {{ADDRESS}} {{PHONE}} {{SSN}} {{HOSPITAL}} {{DOCTOR}}</pre><p>That gives you a controlled generation template instead of freeform improvisation.</p><h3>13. Stage 4: Let a dedicated tool generate the fake PII</h3><p>Rather than letting the language model invent sensitive-looking values on its own, a dedicated faking library generates the synthetic PII, and the LLM weaves it into the narrative:</p><pre>LLM   → semantic content<br>Faker → synthetic PII values<br>Tools → visual structures</pre><p>Each component has one job. That separation is a deliberate design choice, not an accident.</p><h3>14. Stage 5: Generate segment by segment, not all at once</h3><p>Instead of “generate 100 pages,” the pipeline works section by section:</p><pre>Plan → Section 1 → Evaluate → Section 2 → Evaluate → ... → Section 100</pre><p>The system carries forward memory of prior sections so names, numbers, entities, narrative, and formatting all stay consistent across the whole document.</p><h3>15. Stage 6: Structured data comes before charts</h3><p>This matters a lot for anything visual. If the text says revenue moved from $10M → $15M → $25M, the chart cannot independently show $10M → $12M → $19M.</p><p>So the pipeline generates the underlying structured data first:</p><pre>{&quot;2022&quot;: 10, &quot;2023&quot;: 15, &quot;2024&quot;: 25}</pre><p>and only then builds the chart from those same numbers — keeping text and visuals aligned.</p><h3>16. Stage 7: Visual enrichment via tool-calling</h3><p>Tables, charts, images, infographics, even handwritten-style documents and signatures get added through tool calls rather than the LLM trying to “draw” everything itself:</p><pre>LLM  → &quot;create a revenue chart using these numbers&quot;<br>Tool → actual rendered chart</pre><p>Classic LLM-plus-tool-calling architecture, applied to document generation.</p><h3>17. Stage 8: Let another model grade the work</h3><p>Who checks whether a generated document is actually any good? Another LLM, acting as judge:</p><pre>Generated document → Evaluator →<br>  Does the narrative make sense?<br>  Are entities consistent?<br>  Are sections coherent?<br>  Do tables match the text?<br>  Is the document complete?</pre><p>Some pipelines report hitting over 80% coherence on text-to-graph alignment using this kind of evaluation loop.</p><h3>18. Stage 9: Safety filtering — because synthetic isn’t automatically safe</h3><p>A generated document can still contain toxic content, bias, unsafe medical advice, or other harmful material. So every output runs through a safety classifier, often built against an established harm taxonomy:</p><pre>Document → Safety classifier →<br>  Safe?  No  → reject<br>  Safe? Yes  → training dataset</pre><p>This is the quality gate that keeps “synthetic” from meaning “unchecked.”</p><h3>19. Why not skip the agent and just generate synthetic data directly?</h3><p>Because there’s a real difference between simple synthetic generation and agentic generation.</p><p><strong>Simple synthetic generation</strong> — random templates plus a faking library plus a single LLM call — can produce volume, but tends to be repetitive, weak on long-range consistency, and thin on realistic document structure.</p><p><strong>Agentic generation</strong> — planner, LLM, tools, memory, evaluator, and safety filter working together — produces controlled, diverse, internally consistent output.</p><p>The point of the agent isn’t “agents are inherently better.” It’s that this specific task requires planning, execution, tool use, validation, and rejection working in sequence — which a single prompt simply cannot do.</p><h3>20. Why go synthetic at all? The trade-off table</h3><p>Approach Privacy Realism Scale Cost Enterprise diversity Real customer data Poor Excellent Low High Excellent Public datasets Mixed Weak High Low Weak Manual synthetic data Excellent Moderate Very low Very high Moderate Basic LLM generation Good Good High Medium Moderate <strong>Agentic synthetic pipeline</strong> <strong>Excellent</strong> <strong>Good</strong> <strong>Excellent</strong> <strong>Medium</strong> <strong>Excellent</strong></p><p>The sweet spot: synthetic data buys you scale and privacy; agentic generation buys you realism and control.</p><h3>21. The hidden trap: synthetic data can quietly hurt your model</h3><p>Train exclusively on a million synthetic documents, and the model risks learning “synthetic-document patterns” instead of real-world patterns — a kind of distribution narrowing or mode collapse.</p><p>The safer strategy is blending real and synthetic data:</p><pre>Real / existing dataset + Synthetic dataset → Training → Better generalization</pre><p>rather than synthetic data alone. Early results from this kind of blended approach suggest measurable F-score improvements over synthetic-only training.</p><h3>22. Another trap: synthetic data can still “look” synthetic</h3><p>Imagine training a simple classifier to separate real documents from synthetic ones. If it gets very good at that job, it means your synthetic documents carry detectable artifacts — repeated sentence structures, unnaturally clean phrasing, too-perfect formatting, recycled names, similar layouts, telltale model-specific patterns.</p><p>The actual goal is for synthetic documents to be statistically indistinguishable from real ones, at least from the perspective of downstream models.</p><h3>23. The trap almost nobody mentions: LLM memorization</h3><p>It’s tempting to assume “synthetic” automatically means “zero privacy risk.” It doesn’t.</p><p>Language models are trained on enormous datasets, and there’s a real possibility that a model could reproduce a memorized fragment — a real name, a real address, a real phone number, real company details — even while “generating synthetic data.”</p><p>So synthetic generation on its own doesn’t guarantee privacy. It has to be paired with controlled PII generation, safety filters, and validation layers to actually deliver on that promise.</p><h3>24. The full architecture, end to end</h3><pre>USER<br>                     │<br>                     ▼<br>        Industry / Persona / Scale<br>                     │<br>                     ▼<br>              ┌─────────────┐<br>              │   PLANNER   │<br>              └──────┬──────┘<br>                     │<br>                     ▼<br>      Industry → Department → Persona<br>                     │<br>                     ▼<br>                Prompt Sets<br>                     │<br>                     ▼<br>              ┌─────────────┐<br>              │     LLM     │<br>              └──────┬──────┘<br>                     │<br>          ┌──────────┼──────────┐<br>          ▼          ▼          ▼<br>        Faker      Charts     Images<br>          │          │          │<br>          └──────────┼──────────┘<br>                     ▼<br>             Document Segments<br>                     │<br>                     ▼<br>             Long-Context Memory<br>                     │<br>                     ▼<br>              LLM-as-a-Judge<br>                     │<br>                ┌────┴────┐<br>                ▼         ▼<br>              FAIL      PASS<br>                │         │<br>                ▼         ▼<br>             Reject   Safety Check<br>                          │<br>                     ┌────┴────┐<br>                     ▼         ▼<br>                  UNSAFE     SAFE<br>                     │         │<br>                     ▼         ▼<br>                  Reject    Dataset<br>                                │<br>                                ▼<br>                       Downstream Model<br>                                │<br>                                ▼<br>                          F-score ↑</pre><h3>25. Why does any of this matter?</h3><p>Because the end goal was never “generate realistic-looking documents.” It’s building AI systems that actually understand enterprise data governance — systems that can reliably flag PII, PHI, financial information, sensitive entities, document categories, and compliance-relevant content at scale.</p><p>And the training data used to build that system can’t itself become a compliance liability. That’s the paradox at the center of all of this:</p><p><strong>You need sensitive-looking data to train a system that detects sensitive data — but you can’t safely use the real sensitive data to do it.</strong></p><p>An agentic synthetic-data pipeline is one credible way to break that loop.</p><h3>The whole thing in one paragraph</h3><p>Real enterprise data is too sensitive to use for training, while public datasets aren’t realistic, diverse, long, or well-labeled enough to substitute for it. The fix is an agentic synthetic-data factory: a system that plans realistic enterprise scenarios, generates synthetic PII through controlled tools, produces long and internally consistent documents with an LLM, enriches them with real layouts and visuals, and rejects anything that’s low-quality or unsafe. It’s agentic because generating tens of thousands of realistic, diverse, long, internally consistent enterprise documents isn’t a single-prompt problem — it’s a planning, generation, tool-calling, evaluation, and safety problem, all at once.</p><p>The catch worth remembering: synthetic data isn’t automatically an improvement. It still has to be proven to help downstream models, avoid introducing its own artifacts, avoid collapsing diversity, and avoid accidentally leaking memorized real-world information. Get that balance right, and you’ve solved a problem that looked, at first glance, unsolvable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1330320f19b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airbnb Changed Login Completely — The Server Now Decides How You Authenticate]]></title>
            <link>https://medium.com/@imrohitkushwaha2001/airbnb-changed-login-completely-the-server-now-decides-how-you-authenticate-6375f903476c?source=rss-9d49c6e4b94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6375f903476c</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Rohit Kushwaha]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 05:10:24 GMT</pubDate>
            <atom:updated>2026-08-30T05:10:24.529Z</atom:updated>
            <content:encoded><![CDATA[<p>How Airbnb’s engineering team scrapped hardcoded login logic, moved the brain to the server, and cut client code by 60% in the process.</p><p>If you’ve ever been stuck on a login screen — SMS OTP that never arrives, no fallback option, just a dead end — you’ve experienced exactly the problem Airbnb set out to fix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsl1BWjg5YrWVMcXJ-2B3Q.jpeg" /><figcaption>Airbnb Quietly Rebuilt Login for Millions of Users — And the Trick Was Making the App “Dumber”</figcaption></figure><p>Their solution wasn’t a flashy new feature. It was a complete rethink of <em>who</em> gets to decide how you log in — and the answer, surprisingly, was: not the app.</p><h3>The Problem: Too Many Ways to Log In, Too Little Flexibility</h3><p>Airbnb supports a long list of authentication methods — email, phone, password, SMS OTP, social login, and more. And every user behaves differently:</p><ul><li>A daily user in the US breezes through Google login.</li><li>Someone returning after six months registered with a phone number that may no longer receive SMS.</li><li>A user in Brazil finds WhatsApp far more reliable than SMS.</li><li>A user in South Korea might prefer Naver login entirely.</li></ul><p>The old system hardcoded this logic directly into the Web, iOS, and Android apps. Every tweak — even something as small as reordering login options for one region — meant shipping updates across three separate codebases, waiting for app store review, and hoping the rollout went smoothly.</p><p>That’s not a login system. That’s a maintenance nightmare.</p><h3>The Big Idea: “Identify First, Then Challenge”</h3><p>Here’s the shift, in plain terms.</p><p><strong>Before:</strong> The system asked, <em>“Which login method should I show?”</em> <strong>After:</strong> The system asks, <em>“Who are you? Now let me figure out the best way for you specifically to prove it.”</em></p><h3>Step 1 — Identify</h3><p>The user simply enters an email, phone number, or taps a social login button. The backend uses this to figure out which account it’s probably dealing with.</p><h3>Step 2 — Challenge</h3><p>Once the backend knows <em>who’s likely logging in</em>, a policy engine steps in and evaluates the best authentication method for that specific person, based on account history, region, platform, and available methods. For example:</p><pre>Account<br>   ↓<br>Policy Engine<br>   ↓<br>WhatsApp OTP   → 90% likely to succeed<br>SMS OTP        → 60% likely to succeed<br>Password       → 40% likely to succeed</pre><p>The system then shows WhatsApp OTP first — not because it’s the default, but because it’s statistically the best option for that user, right now.</p><h3>The Real Genius: The Client Stops Making Decisions</h3><p>This is where the architecture gets genuinely clever.</p><p>The client apps — Web, iOS, Android — no longer decide <em>what</em> to show the user. They just render whatever the server tells them to.</p><pre>CLIENT → &quot;Identify me&quot;<br>   ↓<br>SERVER → Policy Engine decides<br>   ↓<br>SERVER → &quot;Show Phone OTP screen&quot;<br>   ↓<br>CLIENT → renders it, nothing more</pre><p>The server sends something like:</p><pre>{<br>  &quot;screen&quot;: &quot;PHONE_OTP&quot;,<br>  &quot;title&quot;: &quot;Confirm it&#39;s you&quot;,<br>  &quot;actions&quot;: [...]<br>}</pre><p>And the client just draws that screen. It doesn’t know <em>why</em> it’s showing this particular method — it doesn’t need to.</p><p>Airbnb calls this <strong>server-driven authentication</strong>, and the payoff is enormous: want to change the login experience for users in Brazil? Update the policy engine. No app releases. No waiting on app store review. No client-side changes at all.</p><h3>No More Dead Ends: “Try Another Way”</h3><p>Anyone who’s had an OTP just… never arrive knows the frustration of being stuck with no alternative.</p><p>Airbnb solved this by ranking fallback options for every login challenge:</p><pre>SMS OTP fails<br>   ↓<br>&quot;Try another way&quot;<br>   ↓<br>Email OTP → Phone call → Password → Social login</pre><p>These aren’t just listed randomly — they’re ranked based on what’s likely to actually work for that specific user. The result: the flow never leaves someone stranded.</p><h3>Client = Renderer, Server = Brain</h3><p>The simplest way to understand this entire redesign is with one mental model:</p><blockquote><strong><em>The server is the brain. The client is just the renderer.</em></strong></blockquote><p>Think of the frontend like a game engine that has no idea what “level” comes next — it just displays whatever the server sends it:</p><pre>Server: SCREEN = LOGIN_EMAIL       → Client renders it<br>User enters email<br>Server: SCREEN = PHONE_OTP         → Client renders it<br>User taps &quot;Try another way&quot;<br>Server: SCREEN = CHALLENGE_PICKER  → Client renders it</pre><p>The client never needs to understand <em>why</em> — it just follows instructions.</p><h3>Why This Matters at Airbnb’s Scale</h3><p>Airbnb operates across web, iOS, and Android, in dozens of regions, with wildly different user behaviors and authentication preferences. If every client had to encode all of that logic independently, complexity would multiply with every new market or method added.</p><p>By centralizing decision-making on the server, Airbnb turned three complex clients into three “thin” renderers, all governed by a single, easily adjustable policy engine.</p><h3>The Results Speak for Themselves</h3><p>Metric Improvement Client code <strong>60% reduction</strong> Web bundle size <strong>100 KB smaller</strong> Authentication success rate <strong>+2.6%</strong> Duplicate accounts <strong>27% reduction</strong> OTP costs <strong>~11% reduction</strong> Experiments run <strong>20+ in 3 months</strong></p><p>That last number is the real story. Before this redesign, testing a new authentication idea could take <em>weeks</em> because it required a client release. Afterward, most experiments were just server-side changes — going from idea to result in days, not weeks.</p><h3>The Bigger Lesson (Beyond Login)</h3><p>It would be easy to read this as “Airbnb redesigned its login screen.” But the real insight goes further:</p><blockquote><strong><em>When a decision depends on context, let the server make it — not the client.</em></strong></blockquote><p>This same principle applies well beyond authentication:</p><ul><li><strong>Checkout</strong> → server decides the next step</li><li><strong>Onboarding</strong> → server decides the next screen</li><li><strong>Payments</strong> → server decides verification requirements</li><li><strong>KYC</strong> → server decides which documents are needed</li><li><strong>Experimentation</strong> → server decides the experience variant</li></ul><blockquote><em>Don’t make the client decide what the user should do next — let the server understand the context, choose the best next step, and let the client simply render it.</em></blockquote><p><em>Source: </em><a href="https://medium.com/airbnb-engineering/flexible-authentication-reimagining-authentication-for-millions-of-users-at-airbnb-3a8a4c917137"><em>Airbnb Engineering — Flexible Authentication: Reimagining Authentication for Millions of Users</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6375f903476c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spot Instances: The Secret to Cutting Cloud Costs by Up to 90% (And Why Every Modern Team Should…]]></title>
            <link>https://medium.com/@imrohitkushwaha2001/spot-instances-the-secret-to-cutting-cloud-costs-by-up-to-90-and-why-every-modern-team-should-c2a8f1b90e6e?source=rss-9d49c6e4b94b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2a8f1b90e6e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rohit Kushwaha]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 17:38:37 GMT</pubDate>
            <atom:updated>2026-08-25T17:38:37.100Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spot Instances: The Secret to Cutting Cloud Costs by Up to 90% (And Why Every Modern Team Should Care)</h3><p>Cloud computing has revolutionized how we build and scale applications, but it has also introduced a new challenge: runaway costs. As companies migrate more workloads to the cloud, their monthly bills can spiral out of control. According to the Flexera 2023 State of the Cloud report, organizations waste an estimated 30% of their cloud spend.</p><p>Enter spot instances — the cloud provider’s spare capacity sold at a massive discount. If you’re not already using them, you’re leaving a fortune on the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9jJRv0nJzYC2jnzUlom9oQ.png" /></figure><p>In this article, I’ll explain what spot instances are, why they matter more than ever, which major companies use them (and how), and how they compare to serverless computing. By the end, you’ll know exactly when and how to adopt spot instances to slash your infrastructure bill without sacrificing reliability.</p><h3>What Are Spot Instances?</h3><p>Spot instances (AWS), preemptible VMs (Google Cloud), and spot VMs (Azure) are unused compute capacity that cloud providers offer at a steep discount — often 60–90% cheaper than on-demand pricing.</p><p>The catch? The provider can reclaim that capacity with very little notice — usually 2 minutes or less — when regular demand spikes.</p><p>At first glance, this sounds risky. But if you design your applications to be resilient, you can harness spot instances for a huge variety of workloads, from batch processing to machine learning training.</p><h3>Why Use Spot Instances?</h3><h3>1. Massive Cost Savings</h3><p>The most obvious benefit is the price. For workloads that can tolerate interruptions, spot instances can reduce compute expenses by up to 90%. For a startup or enterprise running thousands of instances, this can translate into millions of dollars saved each year.</p><h3>2. Fault‑Tolerant and Stateless Workloads</h3><p>Modern applications are increasingly designed to be resilient. Stateless web servers, containerized microservices, CI/CD pipelines, big data analytics, and distributed training jobs can all be checkpointed and resumed. Spot instances fit perfectly because they assume failure and handle it gracefully.</p><h3>3. Elastic Scalability</h3><p>Spot capacity allows you to scale out quickly without paying on-demand prices. For bursty workloads — like nightly batch jobs or seasonal traffic spikes — spot instances provide extra horsepower when you need it, and disappear when you don’t.</p><h3>4. Modern Architectures Are Built for Interruption</h3><p>With Kubernetes, service meshes, and auto‑scaling groups, infrastructure can automatically replace a spot instance that gets reclaimed. Applications no longer need to run on “always available” hardware — they can be designed around ephemeral compute.</p><h3>Why Spot Instances Matter More Now Than Ever</h3><h3>1. Cloud Costs Are Skyrocketing</h3><p>As more companies go all‑in on cloud, their monthly bills have become a major concern. Spot instances are one of the most effective ways to cut waste without sacrificing performance.</p><h3>2. Cloud‑Native and Distributed Systems Are the Norm</h3><p>The shift to microservices, containers, and serverless has made applications inherently more resilient. This architectural evolution makes it easier than ever to adopt spot instances — because the application layer already handles node failures.</p><h3>3. AI/ML and Big Data Workloads Are Exploding</h3><p>Training large machine learning models and processing massive datasets are compute‑intensive and extremely expensive. Spot instances allow data teams to run distributed training jobs (e.g., with PyTorch, TensorFlow) or Spark/Hadoop clusters at a fraction of the cost, thanks to checkpointing and fault tolerance built into these frameworks.</p><h3>4. Competitive Advantage</h3><p>In highly competitive markets (SaaS, fintech, e‑commerce), reducing infrastructure costs directly improves margins. Companies that master spot usage can price their products more aggressively or invest savings into innovation.</p><h3>Companies Using Spot Instances (And How They Do It)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPtK8KhoIt3U1S7z0V5ReQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNYdvl9jQoNqJOxeHjlFAA.png" /></figure><p>These companies typically use a mix of on‑demand and spot instances, relying on:</p><ul><li>Spot Fleets (AWS) — a collection of spot instances across different instance types and availability zones.</li><li>Auto Scaling Groups with mixed instance types — automatically replace terminated spot instances with on‑demand if needed.</li><li>Kubernetes node pools with taints and tolerations — schedule spot workloads separately and drain gracefully.</li></ul><h3>How Do Companies Handle Interruptions?</h3><p>The key to using spot instances successfully is designing for interruption. Here are common strategies:</p><ul><li>Spot Instance Termination Notices — AWS gives a 2‑minute warning via instance metadata. Applications can listen for this and gracefully shut down (flush buffers, checkpoint state).</li><li>Checkpointing and Idempotency — Batch jobs save progress to S3 or a database so they can resume from where they left off.</li><li>Mixed Instance Groups — Combine spot and on‑demand instances in the same auto‑scaling group, ensuring capacity even if spot is reclaimed.</li><li>Kubernetes — Use pod disruption budgets and node termination handlers to migrate workloads automatically.</li></ul><h3>Spot Instances vs. Serverless: Which One Should You Choose?</h3><p>Both spot instances and serverless computing are powerful tools for reducing infrastructure costs and improving scalability. However, they operate on fundamentally different models and suit different workloads.</p><h3>Core Concepts</h3><ul><li>Spot Instances: You rent spare VMs at a discount. You manage the OS, runtime, and scaling. Your code runs on a long‑running server that may be terminated with short notice.</li><li>Serverless (AWS Lambda, Azure Functions, Google Cloud Functions): You upload code, and the provider runs it in response to events. No server management; pay only for execution time. Automatically scales, but functions are stateless and short‑lived (max 15 minutes on AWS Lambda).</li></ul><h3>Detailed Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n50zrC8Mz3o8rwExW_KPlQ.png" /></figure><h3>When to Use Spot Instances</h3><ul><li>You have long‑running, compute‑intensive jobs (batch processing, ML training, ETL) that can be checkpointed and resumed.</li><li>You need full control over the environment (custom OS, specific libraries, GPU).</li><li>You are already using Kubernetes or auto‑scaling groups and can handle interruptions elegantly.</li><li>Your workload runs 24/7 and you want to slash costs while accepting occasional downtime.</li></ul><h3>When to Use Serverless</h3><ul><li>You have event‑driven workloads (file uploads, database changes, HTTP APIs, IoT data).</li><li>Traffic is sporadic or unpredictable.</li><li>You want to minimize operational overhead and focus on code.</li><li>Your tasks are short‑lived and fit within platform limits.</li></ul><h3>Can They Work Together?</h3><p>Absolutely. Many companies use a hybrid approach:</p><ul><li>Use serverless for front‑end APIs and glue code.</li><li>Use spot instances for heavy backend processing (e.g., image recognition, data transformation) triggered by those serverless functions via queues.</li></ul><p>For example, a serverless function receives a user upload, stores it in S3, and sends a message to a queue. A fleet of spot instances (managed by Kubernetes) consumes that queue and processes the uploads in bulk, taking advantage of cheap compute. If a spot instance is terminated, the job is retried automatically.</p><p>Spot instances have evolved from a niche cost‑saving trick to a fundamental component of modern cloud architecture. As cloud spending grows and workloads become more resilient by design, the ability to leverage spare capacity at massive discounts gives companies a real competitive edge.</p><p>The engineering blogs of industry leaders like Netflix, Airbnb, Lyft, and many others demonstrate that spot instances are not just a hack — they are a strategic tool for building scalable, cost‑efficient systems.</p><p>Whether you’re running a startup or a large enterprise, now is the time to evaluate which of your workloads can run on spot instances. The savings are too significant to ignore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2a8f1b90e6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>