<?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 Muskan khandelwal on Medium]]></title>
        <description><![CDATA[Stories by Muskan khandelwal on Medium]]></description>
        <link>https://medium.com/@muskankh03?source=rss-469054eefb6e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2gMVy2AJjEx7ySpVTahsCw.jpeg</url>
            <title>Stories by Muskan khandelwal on Medium</title>
            <link>https://medium.com/@muskankh03?source=rss-469054eefb6e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:20:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muskankh03/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[RAG Evaluation: Begin Your Journey from Here.]]></title>
            <link>https://medium.com/@muskankh03/rag-evaluation-begin-your-journey-from-here-c23fd54c7a6a?source=rss-469054eefb6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c23fd54c7a6a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Muskan khandelwal]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 18:25:18 GMT</pubDate>
            <atom:updated>2026-06-07T18:25:18.487Z</atom:updated>
            <content:encoded><![CDATA[<h4>Everything you need to stop flying blind and start measuring what actually matters.</h4><p>You built a RAG pipeline. You threw a prompt at it, watched it retrieve chunks, and marveled at the answer. It worked. So you shipped it.</p><p>Then the answers started drifting. Then a user screenshot landed in your inbox with something confidently, completely wrong. Then your teammate swapped the embedding model and nobody knew if it helped or hurt. Then someone asked “why did it say that?” and you had no way to answer.</p><blockquote>This is what happens when you don’t think about evaluation from the start. Not a dramatic failure but a slow erosion. Components change, quality degrades, and because you never built the instrumentation to measure it, you’re always reacting instead of catching it early.</blockquote><p>Most engineers hit this wall at the same point and answers start degrading, you swap a component, and you have no idea if it helped or hurt. You can’t trace the hallucination back to a specific retrieval failure. You’re A/B testing chunking strategies based on vibes.</p><p>This article is a practical map for building evaluation in from the beginning. We’ll cover the full evaluation stack: retrieval metrics, answer metrics, LLM-as-a-judge, production libraries, and the most asked BONUS interview questions.</p><h3>First: Evaluation vs. Monitoring</h3><p>Before anything else, get this distinction right and it’ll shape how you instrument everything.</p><p><strong>Evaluation</strong> is what you do <em>during development</em>. You run your pipeline against a fixed test set, measure quality, change something, and measure again. It’s offline, deterministic, and comparable.</p><p><strong>Monitoring</strong> is what you do <em>after deployment</em>. You’re watching live traffic, tracking drift, catching regressions, and collecting signal from real users in production.</p><p>Both matter. This article focuses on evaluation; the foundation you need before monitoring makes any sense.</p><h3>The Two Surfaces You’re Evaluating</h3><p>RAG has two failure modes, and they’re independent:</p><ol><li><strong>Retrieval fails</strong> — the right document isn’t in the top-k results. The generator never even had a chance; search metrics.</li><li><strong>Generation fails</strong> — retrieval was perfect, but the LLM hallucinated, ignored the context, or stitched chunks together incorrectly.</li></ol><p>RAG combines 2 main components: Retrieval and Generation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYrtYW2v-MqfqFRodwZQpQ.png" /><figcaption>Figure 1. Retrieval and generation fail independently. Improving one does not guarantee improvements in the other.</figcaption></figure><h3>Part 1: Retrieval Metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IW8Y7i3mQUav2Mv_4NS1Zw.png" /><figcaption>Figure 2. Retrieval metrics measure different properties: coverage, ranking quality, and noise in retrieved results</figcaption></figure><p>Retrieval metrics measure whether your retriever is surfacing the right content. They’re computed <em>offline</em>, against a labeled dataset where each query has a known set of relevant documents.</p><h4><strong>The Core Metrics</strong></h4><p><strong>Precision@k: </strong>The fraction of retrieved documents that are actually relevant. If you retrieve 5 documents and 3 are relevant, precision@5 = 0.6. It penalizes noise — irrelevant documents in the context window aren’t free, they confuse the generator.</p><pre>precision@k = (relevant docs in top-k) / k</pre><p><strong>Hit Rate: </strong>The percentage of queries where at least one relevant document appears anywhere in the retrieved set. Simpler than recall@k but useful as a quick sanity check — especially when building a new retriever from scratch.</p><pre>hit_rate = (queries with ≥1 relevant doc retrieved) / total queries</pre><p><strong>Recall@k:</strong> The probability that at least one relevant document appears in the top-k results. This is your most important signal. If recall@5 is 0.6, 40% of queries are going to the generator with zero useful context — no amount of prompt engineering fixes that.</p><pre>recall@k = (queries where ≥1 relevant doc is in top-k) / total queries</pre><p><strong>Context Recall: </strong>A more granular version of recall that checks whether <em>all</em> the relevant information needed to answer the query is present in the retrieved context and not just whether a relevant document appeared, but whether the context is <em>complete</em>. Particularly important for multi-hop or complex questions where partial context leads to incomplete answers.</p><p><strong>MRR (Mean Reciprocal Rank)</strong> Captures <em>where</em> the relevant document appears in the ranked list. recall@k doesn’t distinguish between a relevant doc at rank 1 vs. rank k. MRR does.</p><pre>MRR = (1/|Q|) * Σ (1 / rank_i)</pre><p>If the first relevant document is always ranked #1, MRR = 1.0. If it’s always ranked #5 in a top-5 list, MRR = 0.2.</p><p><strong>NDCG (Normalized Discounted Cumulative Gain):</strong> When you have <em>graded</em> relevance (highly relevant, somewhat relevant, not relevant), NDCG accounts for both position and degree of relevance. Most useful when evaluating hybrid retrieval systems or rerankers where partial relevance matters and you have the annotation budget to grade documents beyond binary relevant/not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4O20TNxz_GoB0i6cmQHMwQ.png" /><figcaption>Figure 3. The full evaluation stack for RAG systems. Retrieval quality, generation quality, response quality, and answer correctness can be evaluated independently.</figcaption></figure><h3>Part 2: Answer Metrics</h3><p>Once retrieval surfaces context, you need to measure what the generator does with it.</p><p><strong>Exact Match / F1: </strong>For tasks with a single correct answer (factual QA, numerical extraction), these are clean signals. Exact match is binary; F1 measures token overlap between predicted and reference answers.</p><p>Useful for constrained domains. Breaks down immediately for open-ended generation.</p><p><strong>Semantic Similarity: </strong>Use an embedding model to compare the meaning of the generated answer against a reference answer. Cosine similarity between the two vectors gives you a score.</p><pre>from sentence_transformers import SentenceTransformer, util<br><br>model = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br>score = util.cos_sim(<br>    model.encode(generated_answer),<br>    model.encode(reference_answer)<br>)</pre><p>This is more forgiving than F1 — it doesn’t penalize paraphrasing. But it also won’t catch hallucinations that happen to be semantically adjacent to the truth.</p><p><strong>Faithfulness / Groundedness: </strong>This is the metric most teams under-invest in, and it’s the one that matters most for production RAG.</p><p>Faithfulness measures whether every claim in the generated answer is actually supported by the retrieved context. A high-faithfulness answer only says things the context supports. A low-faithfulness answer introduces facts, inferences, or embellishments not traceable to the retrieved chunks.</p><p>You cannot measure faithfulness with simple string matching or embeddings. You need something that understands claims.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrYqa8kSWSzpEynkJkt1XA.png" /><figcaption>Figure 5: LLM-as-a-Judge evaluates whether claims in the generated answer are supported by retrieved context.</figcaption></figure><p><strong>LLM-as-a-Judge for Faithfulness: </strong>LLM-as-judge is now the standard approach for evaluating groundedness at scale. The idea: use a strong LLM to assess whether the generated answer is faithful to the retrieved context, following a structured rubric.</p><p><strong>Why it works:</strong> Manual evaluation doesn’t scale. For every chunking experiment or model swap, you’d need human reviewers to read hundreds of (context, answer) pairs. LLM judges give you consistent, automatable scoring and when calibrated against human judgments, they correlate well.</p><p>The standard prompt structure for a groundedness judge:</p><pre>System: You are evaluating a RAG system. Given a context and a generated answer,<br>assess whether every factual claim in the answer is supported by the context.<br><br>Score 1–5 where:<br>  5 = Fully grounded. Every claim is traceable to the context.<br>  3 = Partially grounded. Most claims supported, some unsupported additions.<br>  1 = Not grounded. Answer introduces facts not present in the context.<br><br>Return your score and a brief explanation identifying any unsupported claims.<br><br>Context: {retrieved_chunks}<br>Answer: {generated_answer}</pre><p>The judge examines each claim in the generated answer and checks whether it can be traced back to the retrieved context. This surfaces hallucinations that pass semantic similarity checks — an answer can be <em>about</em> the right topic while being factually wrong about what the context actually says.</p><h3>Toolkit 1: Ground Truth &amp; Golden Datasets</h3><p>Every retrieval metric requires labeled data. Every answer metric needs reference answers. This is the hardest part to skip.</p><h4><strong>What a Golden Dataset Looks Like:</strong></h4><p>A minimal golden record:</p><pre>{<br>  &quot;query&quot;: &quot;What are the retention limits for audit logs?&quot;,<br>  &quot;relevant_doc_ids&quot;: [&quot;doc_847&quot;, &quot;doc_291&quot;],<br>  &quot;reference_answer&quot;: &quot;Audit logs are retained for 90 days by default, with optional extension to 365 days for enterprise plans.&quot;,<br>  &quot;metadata&quot;: {<br>    &quot;source&quot;: &quot;human_annotated&quot;,<br>    &quot;domain&quot;: &quot;billing&quot;,<br>    &quot;difficulty&quot;: &quot;medium&quot;<br>  }<br>}</pre><h4>Building Your Dataset</h4><p><strong>Human annotation</strong> — domain experts write queries and label relevant documents. Gold standard quality, high cost. Prioritize for high-stakes query types.</p><p><strong>LLM-generated, human-verified</strong> — use an LLM to generate candidate (query, relevant doc) pairs from your corpus, then have humans verify and filter. Faster, still requires a human pass.</p><pre>prompt = f&quot;&quot;&quot;<br>Given this document excerpt, generate 3 realistic questions a user might ask<br>that this document would answer. Return only the questions, one per line.<br><br>Document: {chunk_text}<br>&quot;&quot;&quot;</pre><h3>Toolkit 2: Comparing Models &amp; Configurations</h3><p>You’ve changed your chunking strategy. Or swapped your embedding model. Or added a reranker. How do you know if it helped?</p><h4>The Evaluation Loop</h4><pre>1. Fix your golden dataset<br>2. Run configuration A → collect (retrieved_docs, generated_answers)<br>3. Run configuration B → collect (retrieved_docs, generated_answers)<br>4. Compute retrieval metrics for A and B → compare recall@k, MRR<br>5. Compute answer metrics for A and B → compare faithfulness, semantic similarity<br>6. Investigate regressions: did B improve recall but hurt faithfulness?</pre><h4>What to Watch For</h4><p><strong>Retrieval-answer decoupling</strong> — it’s common to improve recall@k but see faithfulness drop. This happens when you retrieve more documents but the generator starts hallucinating across a noisier context window.</p><p><strong>Metric gaming</strong> — a longer answer will often score higher on semantic similarity against a reference, simply due to overlap. Normalize for length or use LLM judges instead.</p><p><strong>Evaluation set overfitting</strong> — if you tune hyperparameters against the same golden set too many times, you’ll optimize for it specifically. Hold out a test split you don’t touch during development.</p><h3>Part 3: Libraries Used in Production</h3><p>You don’t have to build this from scratch. Here’s what teams are actually using.</p><p><strong>RAGAS: </strong>The most widely adopted RAG evaluation framework. Provides out-of-the-box metrics for faithfulness, answer relevancy, context precision, context recall, and context entity recall — all computed using LLM-as-a-judge under the hood.</p><pre>from ragas import evaluate<br>from ragas.metrics import faithfulness, answer_relevancy, context_recall<br><br>result = evaluate(<br>    dataset,<br>    metrics=[faithfulness, answer_relevancy, context_recall]<br>)</pre><p><strong>Watch out for:</strong> RAGAS metrics are LLM-computed, so evaluation costs add up at scale. Cache aggressively.</p><p><strong>DeepEval: </strong>A pytest-style evaluation framework that treats RAG evaluation like unit testing. Write test cases with assertions, run them in CI, catch regressions before they ship.</p><pre>from deepeval import assert_test<br>from deepeval.test_case import LLMTestCase<br>from deepeval.metrics import FaithfulnessMetric, ContextualRecallMetric<br><br>def test_rag_response():<br>    test_case = LLMTestCase(<br>        input=&quot;What is the refund policy?&quot;,<br>        actual_output=rag_pipeline.query(&quot;What is the refund policy?&quot;),<br>        retrieval_context=retrieved_chunks<br>    )<br>    assert_test(test_case, [FaithfulnessMetric(threshold=0.7)])</pre><p><strong>TruLens: </strong>Built around the “RAG triad”, answer relevance, context relevance, and groundedness. Provides a local dashboard to inspect individual traces and scores, making it easier to debug <em>why</em> a particular response scored poorly.</p><h3>Interview Questions: RAG Evaluation</h3><p>These come up regularly in AI roles. Concise answers follow each.</p><p><strong>Q1. Your RAG system has high recall@5 but users are still getting hallucinated answers. What do you investigate?</strong></p><p>High retrieval recall means the right documents are being surfaced and the failure is in generation. I’d compute faithfulness scores using an LLM judge to quantify how often the generator is going off-context. Then I’d look at context window size: if k is large, the model may be cherry-picking or getting confused by conflicting chunks. I’d also check whether the retrieved chunks are actually complete; high recall@k doesn’t guarantee the relevant information is fully contained in the chunk, which context recall addresses. Finally, I’d check whether the prompt is explicitly instructing the model to stay grounded in the provided context.</p><p><strong>Q2. How do you build a golden dataset when you have no existing labeled data?</strong></p><p>Start with LLM-generated candidates: prompt a strong model to generate question-answer pairs from each document chunk. Filter aggressively — remove questions answerable without the document, questions with ambiguous answers, and duplicates. Then have domain experts or stakeholders validate a sample. For the rest, use human review on the highest-uncertainty items (low LLM confidence, edge cases) and treat the remainder as silver-quality labels. In parallel, instrument production early: even a simple thumbs up/down or session completion signal gives you weak supervision to expand the dataset over time.</p><p><strong>Q3. How would you set up RAG evaluation in a CI/CD pipeline?</strong></p><p>Use a framework like DeepEval or a custom pytest harness. The pipeline runs on every PR against a fixed golden dataset stored in version control. Metrics computed: recall@5, faithfulness (via LLM judge), and semantic similarity against reference answers. Set thresholds, any metric dropping more than 0.05 below the baseline on the golden set blocks the merge. Cache LLM judge calls to keep evaluation costs manageable. Log all results with experiment metadata (commit hash, model version, config) so you can trace regressions back to a specific change.</p><p><strong>Q4. What’s the risk of using LLM-as-a-judge for faithfulness evaluation, and how do you mitigate it?</strong></p><p>The main risks are model bias (the judge may favor outputs that match its own generation style), inconsistency across runs (same input, slightly different scores), and cost at scale. Mitigation: use a model stronger than your generator as the judge — capability gap reduces style bias. Log the judge’s reasoning, not just the score, and periodically audit a random sample against human ratings. For consistency, set temperature to 0 and use a structured output schema. For cost, cache judge calls keyed on (context_hash, answer_hash) so repeated evaluation runs don’t re-score identical pairs.</p><p><strong>Q5. How do you detect that your RAG system is degrading in production?</strong></p><p>Track a rolling window of faithfulness scores from your LLM judge on live traffic (sampled, not every call). Watch for recall proxy signals: user follow-up rates (“that didn’t answer my question”), session abandonment, explicit negative feedback. If your knowledge base updates frequently, monitor embedding drift — new documents may fall outside the distribution your retriever was optimized for. Set up alerts on p25 faithfulness drop and on retrieval latency outliers, which often indicate index health issues. The golden dataset eval should also run on a scheduled basis against production, not just on PRs.</p><p><strong>Q6. How do you ensure the output from LLMs is consistent and accurate?</strong></p><p>Consistency and accuracy are two different problems and I’d address them separately.</p><p>For consistency: structured output schemas (JSON mode, tool use), temperature set to 0 for deterministic tasks, and prompt versioning so the same input always hits the same prompt. I’d also cache responses for identical inputs in high-volume systems.</p><p>For accuracy: the answer depends on what “accurate” means for the task. For factual QA it means groundedness, the output is traceable to a source. I enforce this through retrieval augmentation, explicit grounding instructions in the prompt (“answer only from the provided context”), and post-generation faithfulness scoring via an LLM judge. For tasks with a known correct answer, I’d run exact match or F1 against a golden set. I’d also set up continuous evaluation in production — sampling live outputs and scoring them on a rolling basis so I catch accuracy degradation before users do.</p><p><strong>Q10. How do you detect and mitigate hallucinations?</strong></p><p>Detection first. There are three layers: automated scoring using an LLM judge that checks each claim in the output against the retrieved context (faithfulness score), semantic similarity against reference answers to catch factual drift, and production signals including follow-up rates, negative feedback, session abandonment as proxy indicators. For high-stakes domains I’d also run a fact-checking pass where the model is asked to cite the specific chunk supporting each claim.</p><p>Mitigation: the root cause is usually one of three things; the relevant information wasn’t retrieved (retrieval failure), the context window was too noisy (precision problem), or the model filled gaps with parametric memory (prompt/instruction failure). Fix each at the source: improve recall@k for retrieval failures, add a reranker to clean up the context for noise, and strengthen grounding instructions plus add a “say I don’t know if the context doesn’t support this” instruction for the third case. In production, a confidence threshold below which the system returns a fallback response rather than hallucinating.</p><h3>References</h3><ol><li><a href="https://www.evidentlyai.com/llm-guide/rag-evaluation#what-is-rag-evaluation">https://www.evidentlyai.com/llm-guide/rag-evaluation#what-is-rag-evaluation</a></li><li><a href="https://github.com/DataTalksClub/llm-zoomcamp/tree/main/04-evaluation">https://github.com/DataTalksClub/llm-zoomcamp/tree/main/04-evaluation</a></li><li><a href="https://www.databricks.com/sites/default/files/2026-03/Databricks_033026_eBook_Compact_Guide_To_RAG-2nd-edition.pdf?itm_source=www&amp;itm_category=resources&amp;itm_page=thank-you&amp;itm_location=body&amp;itm_component=hero&amp;itm_offer=databricks_033026_ebook_compact_guide_to_rag-2nd-edition.pdf">https://www.databricks.com/sites/default/files/2026-03/Databricks_033026_eBook_Compact_Guide_To_RAG-2nd-edition.pdf?itm_source=www&amp;itm_category=resources&amp;itm_page=thank-you&amp;itm_location=body&amp;itm_component=hero&amp;itm_offer=databricks_033026_ebook_compact_guide_to_rag-2nd-edition.pdf</a></li><li><a href="https://huggingface.co/learn/cookbook/en/rag_evaluation">https://huggingface.co/learn/cookbook/en/rag_evaluation</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c23fd54c7a6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing ML Systems That Actually Work Part 3: Running It Live]]></title>
            <link>https://medium.com/@muskankh03/designing-ml-systems-that-actually-work-part-3-running-it-live-e51886f43316?source=rss-469054eefb6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e51886f43316</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Muskan khandelwal]]></dc:creator>
            <pubDate>Fri, 20 Mar 2026 13:50:04 GMT</pubDate>
            <atom:updated>2026-03-20T13:50:04.069Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deployment, monitoring, continual learning, and building responsibly</h4><p><em>Part 3 of 3 based on “Designing Machine Learning Systems” by Chip Huyen (O’Reilly, 2022). With LLM parallels throughout.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EG32nWFGkb_mBktfTVWk_A.png" /></figure><p>“I used to think that an ML project is done after the model is deployed. I was seriously mistaken.” That’s Chip Huyen’s own reflection after her first production deployment. Deploying is easy if you ignore all the hard parts — wrapping a predict function in a Flask endpoint takes an afternoon. The hard parts are making it available to millions of users with millisecond latency, knowing immediately when something breaks, figuring out what went wrong, and seamlessly rolling out fixes.</p><p>This article covers everything that happens after a model ships: the four deployment myths that mislead newcomers, how models fail silently in production, the mechanics of keeping them fresh, the infrastructure that holds it all together, and the human responsibilities that come with it.</p><h3>Four Myths That Will Mislead You</h3><p><strong>Myth 1: You only deploy one or two models at a time.</strong> Reality: Uber has thousands of models in production. Google runs hundreds of billions of parameters concurrently. Among organizations with over 25,000 employees, 41% have more than 100 models in production. Netflix uses ML for artwork personalization, search ranking, content recommendation, encoding optimization, and dozens of other tasks simultaneously. Plan for artifact management from day one monitoring, retraining, and reproducing 100 models requires a fundamentally different approach than managing one.</p><p><strong>Myth 2: If you don’t do anything, model performance stays the same.</strong> Reality: ML systems suffer from data distribution shifts — the world changes, and a model trained on historical data becomes increasingly misaligned with production data. A model performs best right after training and degrades from that point forward.</p><p><strong>Myth 3: You won’t need to update your models much.</strong> The right question isn’t “how often should I update?” It’s “how often <em>can</em> I update?” Weibo’s iteration cycle for some ML models is 10 minutes. Etsy deployed 50 times a day in 2015. As Josh Wills (ex-Google, ex-Slack) put it: <em>“We’re always trying to bring new models into production just as fast as humanly possible.”</em></p><p><strong>Myth 4: Most ML engineers don’t need to worry about scale.</strong> Most ML engineers work at companies with at least 100 employees. Most companies with 100+ employees serve a meaningful number of users. Scale is your problem.</p><h3>Batch vs. Online Prediction — A Decision You Can’t Easily Reverse</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*wgOgNVzCnLc9bcHdlpdMgw.png" /><figcaption>Batch vs Online Prediction</figcaption></figure><p>The most consequential architectural decision in deployment is how your model serves predictions:</p><p><strong>Batch prediction:</strong> Generate predictions periodically and store them. Netflix pre-computes movie recommendations every few hours; when you log in, it fetches precomputed results. Fast retrieval, but the model can’t adapt to what you just watched. It can’t answer unpredictable queries (you can’t pre-translate every possible sentence). Good for high-throughput, latency-tolerant use cases.</p><p><strong>Online prediction:</strong> Generate predictions at request time. Required for fraud detection (catching a transaction before it completes), autonomous vehicles, voice assistants, and any task where the right answer depends on what’s happening right now.</p><p>Most serious systems use both. DoorDash uses batch prediction for restaurant recommendations (too many restaurants to rank in real time) but online prediction for food item recommendations once you click into a restaurant.</p><p>The hardest version — <strong>streaming prediction</strong> — uses both batch features (historical user behavior) and streaming features (what’s happening in the last 5 minutes) simultaneously. This requires unifying two different pipelines that have historically been maintained by different teams, causing one of the most common bug patterns in production: the batch training pipeline and the streaming inference pipeline compute features slightly differently, and the model silently degrades.</p><p><strong>For LLMs:</strong> Batch vs. online is equally consequential. Precomputing embeddings for RAG retrieval is batch processing. Generating responses is online. The training-serving skew problem manifests as prompt templates or context assembly logic differing between development and production.</p><h3>How Models Fail in Production</h3><p>60 out of 96 ML pipeline failures at Google over 15 years were caused by non-ML issues — distributed system bugs, incorrect data joins, wrong data structures. “ML engineering is mostly engineering, not ML.”</p><p>But the ML-specific failures are the dangerous ones, because they fail silently. model.predict() executes without error while returning garbage. Users keep using the system without knowing it&#39;s broken.</p><p><strong>Three ML-specific failure modes:</strong></p><p><strong>1. Distribution shift.</strong> The world changes; the model doesn’t. Three types:</p><ul><li><em>Covariate shift:</em> Input distribution P(X) changes but the relationship P(Y|X) holds. Demographic shift after a marketing campaign.</li><li><em>Label shift:</em> Output distribution P(Y) changes. Fraud patterns spike during a new attack.</li><li><em>Concept drift:</em> The relationship itself changes. Pre-COVID, searching “Wuhan” meant travel. Post-COVID, it meant something different.</li></ul><p>Shifts happen suddenly (competitor pricing change), gradually (cultural norms), and seasonally (holiday demand). Most shifts that look like data distribution changes on monitoring dashboards are actually caused by internal errors — bugs in the data pipeline, wrong feature statistics, inconsistencies between training and serving.</p><p><strong>2. Edge cases.</strong> Inputs so extreme the model fails catastrophically. A self-driving car that handles 99.99% of situations but causes fatalities in the other 0.01% is unusable. A customer service chatbot that works fine most of the time but occasionally outputs racist content is a brand liability that makes the whole system unusable.</p><p><strong>3. Degenerate feedback loops.</strong> A recommendation system shows Song A above Song B. Users click Song A more. The model becomes more confident Song A is better. Song A’s ranking increases further. The loop amplifies the initial tiny difference until Song A dominates all recommendations. This is why popular items keep getting more popular, and new items never break through.</p><p>TikTok’s defense: assign each new video a random initial pool of traffic to get unbiased feedback before using that signal to determine wider distribution. Introducing randomization breaks the feedback loop — at some cost to short-term user experience.</p><p><strong>For LLMs:</strong> Concept drift manifests as <em>prompt drift</em> — user phrasing evolves, topics shift, and base model updates change behavior. Degenerate feedback loops manifest as sycophancy: models trained on human preference data learn to say what users want to hear rather than what’s true, because agreement gets higher ratings.</p><h3>Monitoring: You Can’t Fix What You Can’t See</h3><p>Monitoring is about metrics. Observability is about designing your system so that metrics actually tell you what’s happening internally.</p><p><strong>Four layers to monitor, from easiest to hardest to interpret:</strong></p><ol><li><strong>Operational metrics</strong> — latency, throughput, CPU/GPU utilization, uptime. These apply to any software system. AWS EC2’s SLA guarantees 99.99% monthly uptime that’s only ~4 minutes of allowed downtime per month.</li><li><strong>Model accuracy metrics</strong> — requires ground truth labels, which are often delayed or unavailable. Track proxy metrics when labels aren’t immediate: click-through rate, completion rate, re-query rate.</li><li><strong>Prediction distributions</strong> — monitor whether your model’s output distribution is shifting. A model suddenly predicting all NEGATIVE for 10 minutes is detectable immediately, even without labels.</li><li><strong>Feature distributions</strong> — validate that incoming features match expected schemas (min/max ranges, null rates, value sets). Tools like Great Expectations and AWS Deequ automate this. Warning: features drift constantly, and most drifts are benign. Alert fatigue is real — if every feature shift triggers a page, the team stops responding to alerts.</li><li>Use <strong>sliding statistics</strong> (computed within a time window) rather than cumulative statistics. Cumulative accuracy hides sudden dips by averaging them with better-performing periods.</li></ol><p><strong>For LLMs:</strong> Monitoring accuracy requires LLM-as-judge pipelines since there’s no ground truth label. Monitor token usage, latency, refusal rates, and output length distributions as proxies for model health. A sudden spike in output length often indicates prompt injection or model behavior change after an upstream update.</p><h3>Continual Learning: Keeping Models Fresh</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSXDPTUuEv-rNr8TJsD4fQ.png" /><figcaption>Continual Learning Loop</figcaption></figure><p>Most companies do <strong>stateless retraining</strong> — train from scratch on fresh data periodically. This is expensive but reliable. The question every ML engineer is asked: “How often should I retrain?”</p><p>The right answer: run experiments. Train model versions on data from different time windows in the past, evaluate on recent data, and measure how performance changes with data freshness. Facebook found that switching from weekly to daily retraining reduced their ad click-through prediction loss by 1% — significant enough to justify the infrastructure cost. Weibo found value in retraining every 10 minutes for certain models.</p><p><strong>Stateful training</strong> (fine-tuning from the last checkpoint rather than from scratch) is far more efficient. Grubhub switched from daily stateless retraining to daily stateful training and achieved:</p><ul><li>45× reduction in training compute cost</li><li>20% increase in purchase-through rate</li></ul><p>The four stages of continual learning maturity:</p><pre>Stage 1: Manual retraining   — ad hoc, someone notices degradation<br>Stage 2: Scheduled           — cron job, fixed cadence (most companies)<br>Stage 3: Triggered           — automated when drift detected<br>Stage 4: Continual           — updates whenever distributions shift, edge deployment</pre><p>Most teams should target Stage 3 — automated monitoring feeding automated retraining pipelines, without the instability risks of fully online learning.</p><p><strong>Testing updated models in production safely:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vp5_C8kV540bZmsjX5aiGg.png" /></figure><p>Bandits require 12,000 samples to reach the same confidence that A/B testing needs 630,000 samples for, according to a Google experiment. But bandits are stateful — you need to track each model’s performance in real time, which requires online prediction infrastructure that many teams don’t yet have.</p><p><strong>For LLMs:</strong> RAG index refresh is the LLM equivalent of stateful retraining — update the knowledge without touching the model. Prompt regression testing is the equivalent of A/B testing — validate that a prompt change doesn’t degrade performance on held-out evaluation examples before rolling it out.</p><h3>MLOps Infrastructure: The Platform That Makes It Sustainable</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSo5DJpbU0VJesDU2g01Sg.png" /><figcaption>Infrastructure</figcaption></figure><p>The ML platform is the shared infrastructure that makes deploying, monitoring, and updating models sustainable across multiple teams and use cases.</p><p><strong>Three essential components:</strong></p><p><strong>Model store</strong> — storing a serialized model in S3 is not a model store. A real model store tracks: model definition and parameters, featurize and predict functions, dependencies (container), data version used for training, model generation code, experiment artifacts, and owner tags. Without this, debugging a production failure requires knowing which data version was used, which code commit generated the model, and who wrote it information that disappears when data scientists leave or switch projects.</p><p><strong>Feature store</strong> — solves the training-serving skew problem by providing a single feature computation layer used by both training and serving pipelines. Uber had ~10,000 features across teams by 2017. Without a feature store, the same feature gets computed differently in the Python training pipeline and the Java production service, causing silent model degradation that’s nearly impossible to trace.</p><p><strong>Deployment service</strong> — not just pushing a model to an endpoint, but managing canary releases, A/B tests, shadow deployments, and rollbacks. The open problem: ensuring model quality before deployment. Most teams still evaluate models ad hoc. The goal is CI/CD for ML — automated evaluation pipelines that run on every model update, similar to unit tests running on every code commit.</p><h3>Responsible AI: A Design Constraint, Not a Checklist</h3><p>In the summer of 2020, the UK used an algorithm to assign A-level grades to students during COVID-19. The model’s objective was to maintain historical school-level grade distributions, not to accurately grade individual students. A students from historically low-performing schools were downgraded to Bs and Cs. The public outcry forced the government to abandon the algorithm within days.</p><p>Three failures in that system mirror the most common failures in production ML:</p><p><strong>Wrong objective.</strong> The model optimized for fairness between schools rather than accuracy for individual students perpetuating exactly the socioeconomic inequalities it was supposed to be neutral about. Your loss function shapes what your model learns. If your business objective doesn’t translate correctly into your ML objective, the model will optimize for the wrong thing.</p><p><strong>Insufficient slice-based evaluation.</strong> Ofqual acknowledged their model had poor data for small schools. For those schools, they switched to teacher assessments which happened to favor private schools with smaller classes. Fine-grained evaluation across school size, demographics, and socioeconomic status would have surfaced these disparities before deployment.</p><p><strong>Lack of transparency.</strong> Teachers didn’t know how their assessments would be used until after submission. The public didn’t know the objective until grades were published. Independent statistical experts were not given access to scrutinize the model. Any system that makes consequential decisions about people’s lives should be reviewable by independent experts and transparent about its objectives before deployment.</p><p><strong>Two structural principles for responsible AI:</strong></p><p><strong>Act early.</strong> NASA research shows that the cost of fixing errors escalates by an order of magnitude at each stage of the project lifecycle. A fairness issue discovered during problem framing costs 1×. The same issue discovered after deployment costs 1,000×. Involving subject matter experts, affected communities, and fairness auditors during design not after launch is not idealism, it’s risk management.</p><p><strong>Model cards.</strong> Short documents that accompany every model in production, specifying: intended use cases and out-of-scope uses, training data composition, evaluation methodology and slice-based results, known limitations, and ethical considerations. When a model in production behaves unexpectedly, the model card is the first place to look. Without it, debugging requires reconstructing decisions made months ago by people who may no longer be on the team.</p><p><strong>For LLMs:</strong> Hallucination is the LLM equivalent of a model failing silently confident output that’s factually wrong. Responsible deployment requires grounding (cite sources), output validation (verify factual claims against a knowledge base), and human oversight for high-stakes decisions. LLMs trained on preference data inherit the biases of their raters; responsible teams audit outputs across demographic slices, not just aggregate quality scores.</p><h3>Key Takeaways</h3><ul><li>Deploying a model isn’t the end of the process , it’s the beginning of a continuous cycle of monitoring, updating, and maintaining.</li><li>Batch prediction is simpler; online prediction is more responsive. Most systems eventually need both. Unifying the two pipelines is one of the hardest engineering challenges in production ML.</li><li>60% of ML pipeline failures at Google are non-ML software issues. ML engineering is mostly engineering.</li><li>Models fail silently. Distribution shift, edge cases, and degenerate feedback loops are invisible without deliberate monitoring.</li><li>The right retraining question isn’t “how often?” it’s “how much performance do I gain from fresher data?” Run experiments to find out.</li><li>A model store, feature store, and deployment service are not optional infrastructure they are what makes ML sustainable at scale.</li><li>Responsible AI is a design constraint applied throughout the project lifecycle, not a compliance checkbox at the end. The earlier you act, the cheaper it is to get right.</li></ul><p><a href="https://medium.com/@muskankh03/designing-ml-systems-that-actually-work-part-1-the-foundation-2c005d64372d"><em>Part 1 </em></a><em>covered Chapters 1–3: when to use ML, research vs. production gaps, system requirements, problem framing, and data engineering fundamentals.</em></p><p><a href="https://medium.com/@muskankh03/designing-ml-systems-that-actually-work-part-2-building-the-core-9c815b4ab79e"><em>Part 2</em></a><em> covered Chapters 4–6: training data, labeling, class imbalance, feature engineering, data leakage, and model evaluation.</em></p><p><em>Part 3 covered Chapters 7–11: deployment, distribution shift, monitoring, continual learning, MLOps infrastructure, and responsible AI.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e51886f43316" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing ML Systems That Actually Work Part 2: Building the Core]]></title>
            <link>https://medium.com/@muskankh03/designing-ml-systems-that-actually-work-part-2-building-the-core-9c815b4ab79e?source=rss-469054eefb6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c815b4ab79e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Muskan khandelwal]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 15:11:34 GMT</pubDate>
            <atom:updated>2026-03-05T15:11:34.915Z</atom:updated>
            <content:encoded><![CDATA[<p>Training data, features, and models — everything before a model ships</p><blockquote>Part 2 of 3 based on “Designing Machine Learning Systems” by Chip Huyen (O’Reilly, 2022). With LLM parallels throughout.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGPSHvGGnjnDHqMQg12OHQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@fakurian?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Milad Fakurian</a> on <a href="https://unsplash.com/photos/a-white-tiled-wall-with-a-design-word-on-it-scphgwqi_dU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>The Unglamorous Work That Actually Determines Success</h3><p>“Having the right features is the most important thing in developing ML models.” That’s not a research opinion it’s the opening claim of Facebook’s 2014 production paper on click prediction. Yet most ML curricula spend 80% of time on model architecture and barely touch data and features.</p><p>Production inverts this completely. Once you have a working model, better features consistently outperform better algorithms. And before features, there’s training data the foundation everything else depends on. This article covers the three steps that precede deployment and determine whether your system actually works.</p><h3>Training Data: Garbage In, Garbage Out</h3><h4>Sampling Bias Is Everywhere</h4><p>How you sample data determines what your model can and cannot learn. Most production data is collected by <strong>nonprobability sampling</strong> — you use what’s convenient. Language models trained on Wikipedia and Reddit. Self-driving car data collected in Phoenix (sunny, lax regulations). Sentiment models trained on Amazon reviews (biased toward people willing to leave reviews online).</p><p>This is how most projects start, and it’s fine for getting off the ground. But understanding <em>how</em> your data was collected is essential for understanding <em>what your model has actually learned</em>.</p><p>For reliable systems, move toward probability-based methods: <strong>stratified sampling</strong> ensures rare classes appear in every split; <strong>weighted sampling</strong> corrects for known distribution mismatches; <strong>reservoir sampling</strong> handles streaming data where you can’t know the total size in advance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MuA6J5QNnzuCVJA0_PrZMQ.png" /></figure><h4>Labeling Is the Real Bottleneck</h4><p>Most production ML is supervised. Labels are expensive, slow, noisy, and subject to privacy constraints. When Andrej Karpathy decided to build an in-house labeling team at Tesla, his recruiter asked how long the team would be needed. His answer: <em>“How long do we need an engineering team for?”</em></p><p>Three under appreciated labeling problems:</p><p><strong>Label multiplicity.</strong> Three annotators given the same sentence for named entity recognition identified 3, 6, and 4 entities respectively. Disagreement is normal the higher the domain expertise required, the higher the disagreement. Always track data lineage (which data came from which annotator) so that when your model degrades mysteriously, you can trace it to a batch of low-quality labels rather than blaming the architecture.</p><p><strong>Natural labels and feedback loops.</strong> Recommender systems, search ranking, and ad click prediction have natural labels, user behavior tells you whether a prediction was good. 63% of companies work on tasks with natural labels, likely because those tasks are easier to start on. But natural labels have <strong>feedback loop length</strong>: fraud detection labels take 1–3 months (dispute window); clothing recommendations take weeks (delivery + try-on). A broken model can go undetected for the entire length of that loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1vWlv02Q3iB8e96abDaVw.png" /><figcaption>Feedback loop length</figcaption></figure><p><strong>When labels don’t exist.</strong> Four strategies, in order of practicality:</p><ul><li><strong>Weak supervision</strong> (Snorkel): encode domain expertise as labeling functionsheuristics that generate noisy labels at scale. A Stanford Medicine study showed models trained on 8 hours of a radiologist writing labeling functions matched models trained on nearly a year of hand labels.</li><li><strong>Semi-supervision</strong>: propagate labels from a small seed set using structural assumptions (similar examples share labels).</li><li><strong>Transfer learning</strong>: pretrain on a cheap related task, fine-tune on your target. The foundation of every modern NLP system.</li><li><strong>Active learning</strong>: let the model identify which examples it’s most uncertain about, and label those achieving higher accuracy with fewer labels.</li></ul><h4>Class Imbalance Is the Norm</h4><p>Fraud: 6.8¢ per $100 is fraudulent. Cancer screening: 0.01% of X-rays show cancer. Resume screening: 98% of applicants eliminated at first pass. <strong>Imbalance is not the exception it’s what production data looks like.</strong></p><p>Three things go wrong: the model has insufficient signal for rare classes, it exploits a simple majority-class heuristic (99.99% accuracy by always predicting “not cancer”), and the loss function treats all errors equally when the cost of errors is wildly asymmetric.</p><p>The fix starts with the metric. Accuracy is useless. Two models can both hit 90% accuracy on a cancer detection task while one catches 90% of cancers and the other catches 10%. Use F1, AUC-PR, and per-class accuracy. Then address the imbalance: class-weighted loss, SMOTE oversampling, or threshold tuning always after splitting, never before.</p><h3>Feature Engineering: Still the Highest-Leverage Work</h3><p>Deep learning eliminated manual feature engineering for raw images and text. But ML systems need structured data too user history, account age, device type, time of day. For these, feature engineering remains critical.</p><p>Three decisions that consistently trip up production systems:</p><p><strong>Scaling.</strong> A model doesn’t know that 150,000 (income) and 40 (age) represent different things. The larger number dominates. Always scale features to similar ranges and always fit the scaler on training data only, then apply it to all splits. Fitting on the full dataset leaks test statistics into training.</p><p><strong>Encoding categorical features.</strong> Static categories are easy. Production categories change. Amazon had 2 million brands in 2019; new brands join daily. Encoding only known brands and bucketing the rest as UNKNOWN means new luxury brands get treated like bottom-1% unpopular brands. The <strong>hashing trick</strong> hashing each category to a fixed-size index space — handles this gracefully. Booking.com showed that even 50% collision rates cause less than 0.5% performance loss.</p><p><strong>Data leakage.</strong> The most dangerous failure mode in production. Leakage is when label information contaminates your features in a way that won’t exist at inference time. MIT Technology Review’s 2021 investigation into COVID prediction models found one model had learned to predict severity from whether the patient was lying down or standing — because seriously ill patients were scanned lying down. Another learned from the font hospitals used to label scans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zuWZhaplGgmhWnnY3qliA.png" /><figcaption>How improper data handling can cause leaks</figcaption></figure><p>The most common causes: scaling before splitting, computing aggregate features on full data instead of training data only, and randomly splitting time-series data instead of splitting by time. The detection rule: if a feature has suspiciously high predictive power, investigate how it was generated.</p><h3>Model Development: Start Simple, Evaluate Honestly</h3><h4>Six Principles That Actually Matter</h4><p><strong>Avoid the SOTA trap.</strong> State-of-the-art means better on a specific static benchmark not faster, cheaper, or better on your data. A simpler solution that ships is worth more than a SOTA model that doesn’t.</p><p><strong>Start with the simplest model.</strong> It validates your pipeline, gives you a baseline to beat, and is easier to debug. Martin Zinkevich’s rule: “If you think ML will give you a 100% boost, a heuristic will get you 50% of the way there.”</p><p><strong>Watch for human bias in comparisons.</strong> An engineer excited about BERT runs 100 experiments on it and 3 on gradient-boosted trees. BERT wins but only because of unequal effort. Compare architectures under comparable experimental budgets.</p><p><strong>Know your model’s assumptions.</strong> Linear classifiers assume linear boundaries. Naive Bayes assumes feature independence. Neural networks assume IID examples. Violating assumptions silently degrades performance without obvious errors.</p><h4>Evaluation: Baselines and Slices</h4><p>Metrics mean nothing without a baseline. Every model should beat five bars before deployment: random prediction, majority class, a simple heuristic, the previous production model, and human performance.</p><p>Aggregate metrics hide subgroup failures. Two models can both achieve 95% overall accuracy while one is 80% accurate on a minority subgroup and the other is 95% accurate across all groups. Without <strong>slice-based evaluation</strong> measuring performance on guests vs. hosts, mobile vs. desktop, new users vs. experienced you’ll optimize the wrong thing and discover the failure in production.</p><p>Simpson’s paradox makes this even more important: a model can outperform another in aggregate while losing on every individual subgroup. Aggregate metrics don’t just miss the truth they can actively reverse it.</p><h3>Case Study: How Airbnb Rebuilt Its Customer Support AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvlSi4wvM_6VFZNe_LzCIg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@veryinformed?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Oberon Copeland @veryinformed.com</a> on <a href="https://unsplash.com/photos/graphical-user-interface-application-zq0K6AVDtu8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Airbnb’s customer support ran on rigid hand-designed decision trees for years. Every new scenario required engineers to manually build new workflows. In 2024, they migrated to a hybrid LLM-powered system — <strong>Automation Platform v2</strong> and published the details. Every challenge in this article appears in their system.</p><p><strong>Labeling:</strong> Evaluating whether an LLM response was <em>good</em> is harder than V1’s binary “did the workflow complete?” Airbnb built LLM-oriented observability tracking every interaction: latency, token usage, and conversation logs. A guardrails framework monitors each response for hallucinations, policy violations, and off-topic content. This layered approach reflects the same principle from Chapter 4: when no single signal is sufficient, you stack multiple weaker signals across different timescales.</p><p><strong>Feature engineering as context assembly:</strong> Before every LLM call, the system assembles context from multiple sources, conversation history, user profile, and trip details. The direct equivalent of a feature vector. Airbnb explicitly built point-in-time data retrieval so context reflects the state at conversation time, not stale cached values. Same rule as Chapter 5: don’t carry stale statistics from training into inference.</p><p><strong>Class imbalance — the architectural response:</strong> Airbnb explicitly chose not to handle sensitive operations refund claims, listing modifications, strict validations with the LLM. Their stated reasons: latency requirements, hallucination risk, and the need for strict data validation. In ML terms this maps directly to cost-sensitive design: when the cost of a wrong prediction on certain inputs is too high, you don’t let the general model handle them.</p><p><strong>Why rules beat LLMs for sensitive ops a leakage parallel:</strong> When an LLM is given access to case history and policy outcomes, it can learn to predict resolutions and shape responses accordingly telling customers what they want to hear rather than what policy says. Airbnb avoids this by strictly separating what the LLM can see from what determines decisions. The LLM handles tone and explanation; rule-based workflows handle the actual decision. This is the same structural problem as the COVID CT scan leakage context that encodes outcome information produces models that perform well on training data but behave badly in production.</p><p>The meta-lesson is the most important one Airbnb documented publicly:</p><blockquote>“It is too early to fully rely on [LLMs] for large scale and diverse experience for millions of customers. It’s more suitable to use a transition workflow instead of LLM to process a claim related product that requires sensitive data and strict validations.”</blockquote><p>They didn’t replace their ML system with an LLM. They identified exactly which sub-problems an LLM solves better and kept everything else. That judgment knowing which component to upgrade and which to leave alone is what ML systems design is actually about.</p><blockquote><em>📖 </em><strong><em>Source:</em></strong><em> </em><a href="https://medium.com/airbnb-engineering/automation-platform-v2-improving-conversational-ai-at-airbnb-d86c9386e0cb"><em>Automation Platform v2: Improving Conversational AI at Airbnb</em></a><em> — Airbnb Engineering Blog, 2024</em></blockquote><p><em>Next: </em><strong><em>Part 3 — Running It Live</em></strong></p><p><em>Based on “Designing Machine Learning Systems” by Chip Huyen (O’Reilly, 2022)</em> <em>Case study: Airbnb Engineering Blog, “Automation Platform v2” (2024)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c815b4ab79e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing ML Systems That Actually Work Part 1: The Foundation]]></title>
            <link>https://medium.com/@muskankh03/designing-ml-systems-that-actually-work-part-1-the-foundation-2c005d64372d?source=rss-469054eefb6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c005d64372d</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Muskan khandelwal]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 15:42:34 GMT</pubDate>
            <atom:updated>2026-02-26T15:42:34.705Z</atom:updated>
            <content:encoded><![CDATA[<p>What you need to understand before writing a single line of model code</p><blockquote>Part 1 of 3 a technical deep-dive based on “Designing Machine Learning Systems” by Chip Huyen (O’Reilly, 2022). Written for practitioners studying ML system design, with LLM parallels throughout.</blockquote><h3>The Algorithm Is the Small Part Nobody Warns You About</h3><p>When Google incorporated neural machine translation into Google Translate in 2016, quality improved more in one leap than in the previous 10 years combined. That success story cemented a misconception that still derails ML projects today: that an ML system <em>is</em> the ML algorithm.</p><p>It isn’t. In production, the model is a small component inside a much larger system that includes business logic, a data stack, feature pipelines, serving infrastructure, monitoring, and the people who own each piece. <strong>Change one component and the others are affected.</strong> This interdependence is why ML systems design demands a holistic view not “how do I improve my model?” but “how do I design a system where all parts work together?”</p><p>The same is true for LLM systems. Swapping GPT-3 for GPT-4 is easy. Building the data pipeline that feeds it relevant context, the evaluation harness that catches regressions, and the monitoring layer that detects when outputs degrade that’s the real work.</p><h3>When to Use ML and When Not To</h3><p>Before writing any code, ask whether ML is the right tool. A precise definition helps:</p><blockquote>Machine learning learns complex patterns from existing data to make predictions on unseen data.</blockquote><p>Every word is a constraint. There must be <strong>patterns</strong> you don’t build an ML system to predict a fair die roll. The patterns must be <strong>complex</strong> if zip codes map to states via a lookup table, use a lookup table. <strong>Data must exist</strong> ML cannot learn from nothing. And <strong>unseen data must share patterns with training data</strong> a model trained on 2008 app downloads will fail on 2024 Christmas predictions.</p><p>Beyond these fundamentals, ML is especially well-suited when the task is repetitive (patterns appear many times), wrong predictions are cheap (a bad restaurant recommendation is forgiven; a wrong surgical diagnosis is not), the problem operates at scale (ML’s upfront cost justifies itself only when you make many predictions), and patterns are constantly changing (hardcoded rules go stale; ML retrains).</p><p><strong>ML is the wrong choice when:</strong> a simpler solution works, it’s not cost-effective, or it’s unethical. When ML can’t solve your whole problem, it might solve a component, a classifier that routes customer tickets to the right department is more tractable than a bot that answers everything.</p><p>For LLMs, the same logic applies with a twist: their flexibility makes the “is this the right tool?” question harder. An LLM can classify, generate, summarize, and rank but that doesn’t mean it should. A fine-tuned BERT classifier is faster, cheaper, and more predictable for a fixed classification task than GPT-4. Use LLMs when the task genuinely requires open-ended reasoning across multiple subtasks, not because they’re impressive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_d972fsXve_N8QrQ9KbcYg.png" /><figcaption>The algorithm(highlighted) is one of the 7 components and rarely the hardest one</figcaption></figure><h3>Research vs. Production — Five Gaps That Bite</h3><p>Most ML practitioners learn through academia. The production gap is steep and specific:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xRbAJIOV0jk5ykrskvMWw.png" /></figure><p><strong>The stakeholder problem</strong> is the most under appreciated. Consider a restaurant recommendation app: the ML engineer wants to maximize click probability, the sales team wants to promote expensive restaurants (higher service fees), the product team needs responses under 100ms, and the infrastructure team wants to freeze model updates. None of these is “maximize AUC.” The ML system must navigate all of them simultaneously.</p><p><strong>The latency problem</strong> is more subtle. Research prizes throughput samples processed per second during training. Production prizes latency : time to return a prediction to a user. A 100ms delay hurts conversion rates by 7% (Akamai, 2017). And latency is not a number it’s a distribution. Never report average latency:</p><pre>Requests (ms): 100, 102, 100, 100, 99, 104, 110, 90, 3000, 95<br>Average:  390ms  ← skewed by one outlier, misleading<br>p50:      100ms  ← what most users experience<br>p90:     3000ms  ← reveals the outlier that needs investigation</pre><p>Always report p90/p95/p99. Your p99 users are often your most valuable they have the most purchase history, the most data in their accounts.</p><p><strong>The silent failure problem</strong> cuts across both traditional ML and LLMs. Traditional software fails loudly stack traces, 404s, crashes. ML systems can fail silently: model.predict() executes without error while returning entirely wrong predictions, and users keep using the system as if it&#39;s working. LLM hallucinations are the purest form of this confident, fluent, factually wrong, with no signal to the user that anything is broken.</p><h3>Designing for Four Requirements</h3><p>Every production ML system and every LLM system must satisfy four properties. These are design constraints, not afterthoughts.</p><p><strong>Reliability:</strong> The system performs correctly even under adversity. For ML, “correctly” is hard to define the model might execute fine while producing wrong predictions. Build fallbacks. A recommendation model that fails should fall back to popularity-based rankings, not return an error.</p><p><strong>Scalability:</strong> ML systems grow in three distinct ways model complexity, traffic volume, and model count. A startup described in the book had 8,000 models in production for 8,000 enterprise customers, each with its own retraining cadence and feature set. Scalability isn’t just adding machines it’s artifact management. You can manually monitor one model; you cannot manually monitor hundreds. Monitoring and retraining must be automated from the start.</p><p><strong>Maintainability:</strong> Code, data, and models must all be versioned and documented. Different contributors — ML engineers, DevOps, domain experts must be able to work on different parts without breaking each other’s work. Models must be reproducible by people who weren’t the original authors.</p><p><strong>Adaptability:</strong> Because ML systems are part data, and data changes quickly, the system must evolve without service interruption. A system that can’t adapt to shifting data distributions or changing business requirements will require expensive rewrites rather than updates.</p><p>For LLM systems these same requirements manifest differently: reliability means output validation and retry logic for malformed responses; scalability means managing prompt versions and evaluation suites across hundreds of prompts; maintainability means treating prompt templates as versioned code artifacts; adaptability means updating RAG indexes without redeploying the model.</p><h3>Business Objectives, ML Objectives, and the Chain Between Them</h3><p>Projects die when data scientists optimize ML metrics while managers track business metrics, and nobody traces the connection between them.</p><blockquote>“Most companies don’t care about increasing a model’s accuracy from 94% to 94.2% unless it moves some business metrics.”</blockquote><p>The fix is explicit mapping:</p><pre>Business metric:  Purchase-through rate<br>      ↓<br>ML metric:        Recommender accuracy<br>      ↓<br>Evidence:         Each 1% accuracy lift → $X revenue historically<br>      ↓<br>Proposal:         Online prediction gives ~Y% accuracy gain → $Z impact</pre><p>Netflix does this rigorously — their recommender metric, take-rate (quality plays ÷ recommendations shown), is explicitly traced to streaming hours and subscription cancellation rates. That’s why their ML team survives budget reviews.</p><p>The same discipline applies to LLMs. An LLM-powered support bot should be evaluated not just on BLEU score or response quality ratings, but on ticket resolution rate, customer satisfaction, and escalation rate. If those don’t move, the project doesn’t matter.</p><h3>Framing ML Problems and Decoupling Objectives</h3><p>Good problem framing can make the same task dramatically easier or harder. When a manager says “use ML to speed up customer support,” none of the three ML requirements inputs, outputs, objective function are obvious. The bottleneck turns out to be routing tickets to one of four departments. That’s a multiclass classification problem with a clean definition.</p><p>Framing choices have long-term operational consequences. Predicting which app a user will open next can be framed as multiclass classification (one prediction over N apps) or as regression (one score per app, run N times). The regression framing is far more maintainable adding a new app means new inputs, not model retraining.</p><p>When systems have multiple objectives filter spam, filter misinformation, rank by quality, rank by engagement the naive approach combines them into one loss:</p><pre># Combined loss — every business rebalancing requires retraining<br>loss = alpha * quality_loss + beta * engagement_loss + gamma * spam_loss</pre><p>The better approach trains separate models and combines scores at serving time:</p><pre>quality_score    = quality_model.predict(post)<br>engagement_score = engagement_model.predict(post)<br>is_spam          = spam_model.predict(post)<br># alpha/beta are business knobs - tunable without touching any model<br>final_score = -inf if is_spam else alpha * quality_score + beta * engagement_score</pre><p>Now business tuning is decoupled from model retraining. Spam detection (which evolves daily) and quality ranking (which evolves slowly) can have completely independent retraining schedules. This same pattern applies directly to LLM systems separate reward models for helpfulness, harmlessness, and factuality, combined at inference time, rather than one opaque RLHF objective trying to optimize everything simultaneously.</p><h3>Data Engineering: The Foundation Everything Else Depends On</h3><p>The rise of ML is inseparable from the rise of big data. Data engineering decisions made early have long-term consequences for everything downstream.</p><h3>Format and Storage</h3><p>How you store data determines how efficiently you can use it. The most important distinction: <strong>row-major vs. column-major formats</strong>.</p><p>CSV is row-major consecutive elements in a row are stored together, making individual record access fast. Parquet is column-major consecutive elements in a column are stored together, making feature-level access across all records fast. ML training repeatedly scans features across all examples exactly what column-major is built for. AWS reports Parquet is up to 2× faster to unload and 6× more storage-efficient than text formats. A 14MB CSV converts to 6MB Parquet for the same data.</p><pre># pandas DataFrames are column-major (a common misuse source)<br># Iterating by column:  ~0.07 seconds<br># Iterating by row:     ~2.41 seconds  ← 34× slower on same data<br># Fix: convert to NumPy ndarray when row access is needed<br>import numpy as np<br>arr = df.to_numpy()  # now row access is fast</pre><p>Beyond format, the data model shapes what queries are efficient or even possible:</p><ul><li><strong>Relational (SQL):</strong> data normalized into tables with enforced schema. Best for structured data with complex joins. Declarative queries let the optimizer find the fastest execution plan but schema changes are painful and join-heavy queries are expensive.</li><li><strong>Document (MongoDB, Firestore):</strong> self-contained JSON/BSON documents with flexible schema. Better locality than relational all information about an entity lives in one document. But cross-document joins are expensive.</li><li><strong>Graph (Neo4j):</strong> nodes and edges, where relationships are first-class. Finding all people born in the USA is trivial in a graph (traverse edges) but requires complex recursive SQL. Use when relationships between entities are as important as the entities themselves.</li></ul><p>Modern systems increasingly use multiple models PostgreSQL supports both relational and document operations. The key is matching the model to the query patterns of your application.</p><h3>Dataflow: How Data Moves Between Services</h3><p>In production, multiple services need to share data. Three modes, each with different trade-offs:</p><p><strong>Through databases:</strong> Process A writes, Process B reads. Simple, but database round-trips are too slow for latency-sensitive applications.</p><p><strong>Through services (REST/RPC):</strong> Synchronous request-response. Process A calls Process B’s API. If B is down, A’s request fails. At scale, direct service-to-service calls create O(n²) connections each of n services potentially calling all others.</p><p><strong>Through real-time transport (Kafka, Kinesis):</strong> Event-driven, asynchronous. Services publish events to a broker; subscribers receive them. This reduces n services’ connections from O(n²) to O(n) each service only talks to the broker. A piece of data broadcast to the transport is an <strong>event</strong>; the architecture is <strong>event-driven</strong>.</p><pre>Direct service calls (3 services):     Event-driven (same 3 services):<br>  A ←──────→ B                           A → [Broker] ← B<br>  A ←──────→ C    6 connections          C → [Broker]   3 connections<br>  B ←──────→ C                           (any service publishes/subscribes)</pre><p>For LLM systems, this maps to the pipeline that feeds context into prompts. A RAG system is essentially event-driven data engineering: documents are ingested, embedded, and written to a vector store (the broker), and the LLM query service reads from it at inference time without knowing how the index was built.</p><h3>Batch vs. Stream: The Feature Freshness Trade-off</h3><p>Once in storage, data is processed in one of two paradigms:</p><p><strong>Batch processing</strong> runs periodically on stored historical data, producing <strong>static features</strong> that change slowly — a driver’s average rating over hundreds of rides, a user’s 30-day purchase history. Tools: Spark, dbt, MapReduce.</p><p><strong>Stream processing</strong> runs continuously on live data, producing <strong>dynamic features</strong> that change quickly drivers available right now, ride requests in the last two minutes, surge pricing in this zone. Tools: Apache Flink, KSQL, Kafka Streams.</p><p>Most serious ML systems need both. A ride price prediction model needs the driver’s historical rating (batch) and the current supply/demand in the zone (stream). The architecture must join static and dynamic features at prediction time.</p><pre>Batch feature:    driver_avg_rating = 4.7  (recomputed nightly from all trips)<br>Stream feature:   drivers_available_now = 3  (computed in real-time from event stream)<br>Combined at serving: price_model.predict([driver_avg_rating, drivers_available_now, ...])</pre><p>For LLMs, the equivalent distinction is between <strong>static knowledge</strong> (what’s baked into model weights during training) and <strong>dynamic context</strong> (what’s retrieved at inference time via RAG). Static knowledge is like batch featuresrich but potentially stale. Dynamic context is like stream features current but limited in scope. Most production LLM systems need both.</p><h3>Key Takeaways</h3><ul><li>The ML algorithm is a small part of the ML system. Business requirements, data infrastructure, deployment, and monitoring matter just as much and are usually harder.</li><li>ML is appropriate only when there are complex patterns in existing data, the task is predictive, and unseen data shares those patterns. For LLMs: apply the same filter simpler models often suffice.</li><li>The five production gaps stakeholder complexity, latency vs. throughput, shifting data, fairness, and interpretability cannot be retrofitted after the system is built.</li><li>The four requirements — reliability, scalability, maintainability, adaptability are design constraints from day one, not properties to add later.</li><li>Decouple multiple objectives into separate models combined at serving time. This separates model retraining from business tuning and allows independent update schedules.</li><li>Data format (row vs. column-major), data model (relational vs. document vs. graph), and dataflow mode (database vs. service vs. event-driven) are architectural decisions with long-term consequences.</li><li>Most ML systems need both batch (static) and stream (dynamic) features. For LLMs, this maps to model weights (static knowledge) and RAG context (dynamic retrieval).</li></ul><p><em>Next: </em><strong><em>Part 2 — Building the Core</em></strong></p><p><em>Based on “Designing Machine Learning Systems” by Chip Huyen (O’Reilly, 2022)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c005d64372d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-On Large Language Models: Training and Fine-Tuning (Part 3)]]></title>
            <link>https://medium.com/@muskankh03/hands-on-large-language-models-training-and-fine-tuning-part-3-5b9f890cedc3?source=rss-469054eefb6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b9f890cedc3</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Muskan khandelwal]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 14:35:42 GMT</pubDate>
            <atom:updated>2025-11-20T14:35:42.072Z</atom:updated>
            <content:encoded><![CDATA[<p>From Using Models to Shaping Them: Making LLMs Your Own</p><h3>Why Care About Part 3?</h3><p>In <strong>Part 1</strong>, we learned how LLMs work: tokens, embeddings, and transformers.<br> In <strong>Part 2</strong>, we explored the pretrained toolbox: classification, RAG, and agents.</p><p>If Parts 1 and 2 of Jay Alammar’s <em>Hands-On Large Language Models</em> were about understanding and using LLMs, <strong>Part 3 is where everything becomes real. </strong>This is the part that turns you from someone who <em>prompts</em> models into someone who can <em>teach</em> them.</p><p>Part 3 is all about one question:</p><blockquote><strong><em>When should you use a pretrained model as-is, and when do you need to train or fine-tune your own?</em></strong></blockquote><p>To answer that, Jay introduces a spectrum four levels of model customization from “most expensive and powerful” to “cheapest and most practical.” And once you understand this spectrum, fine-tuning stops being mysterious and becomes a tool you can apply confidently.</p><p>Let’s break Part 3 down into exactly what you need to know.</p><h3>The Training Spectrum: Four Levels of Customization</h3><p>Think of training as a spectrum from “most expensive and powerful” to “cheapest and most targeted”:</p><h3>1. Pretraining from Scratch</h3><p>Building the base model</p><p><strong>What it is</strong>: Training an LLM on massive unlabeled text corpora (billions of tokens) to learn language itself. This is how GPT, LLaMA, and BERT were born. They were trained on enormous text collections so they could learn the structure of human language.</p><p><strong>When to use it</strong>: Almost never, unless you’re a research lab with millions in compute budget. This is included for completeness, not practicality.</p><p><strong>Key Takeaway</strong>: Pretraining creates the <em>base model</em> everyone else fine-tunes. It’s the 99% of training time that makes the model “understand” language.</p><h3>2. Full Fine-Tuning</h3><p>Updating every parameter</p><p><strong>What it is</strong>: Taking a pretrained model and updating <em>all</em> its parameters on your task-specific dataset.</p><p><strong>Example Use Cases</strong>:</p><ul><li>Medical chatbot (train on medical literature)</li><li>Legal document analyzer (train on case law)</li><li>Code assistant for your company’s internal APIs</li></ul><p><strong>The Trade-off</strong>: Very effective, but requires:</p><ul><li>Thousands of labeled examples</li><li>Significant GPU resources</li><li>It can cause the model to “forget” general knowledge</li></ul><p><strong>Key Takeaway</strong>: This is the “traditional” fine-tuning approach. It works, but it’s rarely the first choice today.</p><h3>3. Parameter-Efficient Fine-Tuning (PEFT)</h3><p>A small adjustment with big effect</p><p><strong>What it is</strong>: Instead of updating billions of parameters, PEFT freezes the main model and trains only tiny add-on modules. The three main techniques:</p><h4>LoRA (Low-Rank Adaptation) — The Most Popular</h4><ul><li>Adds small “adapter” matrices to the model</li><li>Trains only 0.1% of parameters</li><li><strong>Result</strong>: 90%+ of full fine-tuning performance at 1% of the cost</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJwM2G5pPWWOCMaAQY40cQ.png" /></figure><h4>Prompt Tuning</h4><ul><li>Prepends learnable “virtual tokens” to every input</li><li>The model learns the perfect prompt automatically</li><li><strong>Result</strong>: No prompt engineering needed</li></ul><h4>Prefix Tuning</h4><ul><li>Similar to prompt tuning, but adds trainable prefixes to each layer</li><li>Slightly more powerful than prompt tuning</li></ul><p><strong>When to use it</strong>: For most real-world tasks in 2025, <strong>LoRA is the go-to method</strong></p><p><strong>Key Takeaway</strong>: PEFT is the democratization of fine-tuning. Anyone can adapt a 70B parameter model on a single GPU now.</p><h3>4. Instruction Tuning &amp; RLHF</h3><p>Training models to follow directions</p><p><strong>What it is</strong>: Fine-tuning the model to follow instructions better and align with human preferences.</p><p><strong>Two Key Techniques</strong>:</p><h4>Instruction Tuning</h4><p>Train on examples such as:</p><ul><li>“Summarize this…”</li><li>“Translate this…”</li><li>“Answer the question…”</li><li><strong>Result</strong>: The model becomes a better assistant</li></ul><h4>RLHF (Reinforcement Learning from Human Feedback)</h4><ul><li>Humans rank model outputs (good vs. bad)</li><li>A reward model learns human preferences</li><li>The LLM is optimized to maximize that reward</li><li><strong>Result</strong>: Helpful, harmless, and honest responses (This is how ChatGPT was made)</li></ul><p><strong>Key Takeaway</strong>: This is the final step that turns a “text predictor” into a “helpful assistant.”</p><h3>The Decision Tree: Which Approach Should You Use?</h3><p>Here’s the practical guide from Part 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFv_mz-dmwT88r5fmJAhJg.png" /><figcaption>Choosing the Right LLM Strategy</figcaption></figure><h3>Three Simple Experiments From Part 3</h3><p>Here are the three experiments that make fine-tuning <em>real</em>:</p><h3>1. Experiment: The 10-Line LoRA Fine-Tuning</h3><p>This is shockingly simple with modern libraries.</p><pre># Install: pip install transformers peft datasets accelerate<br>from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments<br>from peft import LoraConfig, get_peft_model<br>from datasets import load_dataset<br><br># 1. Load a tiny model for testing<br>model = AutoModelForCausalLM.from_pretrained(&quot;gpt2&quot;)<br>tokenizer = AutoTokenizer.from_pretrained(&quot;gpt2&quot;)<br><br># 2. Add LoRA adapters (train only 0.1% of parameters!)<br>lora_config = LoraConfig(<br>    r=8,  # Rank of the adapter matrices<br>    lora_alpha=32,<br>    target_modules=[&quot;c_attn&quot;],  # Which layers to adapt<br>    lora_dropout=0.1<br>)<br>model = get_peft_model(model, lora_config)<br><br>print(model.print_trainable_parameters())<br># Output: trainable params: 294,912 || all params: 124,439,808 || trainable%: 0.237%<br><br># 3. Load your dataset (example: code generation)<br>dataset = load_dataset(&quot;your-dataset-here&quot;)<br><br># 4. Train <br>training_args = TrainingArguments(<br>    output_dir=&quot;./lora-out&quot;,<br>    per_device_train_batch_size=2,<br>    learning_rate=2e-4,<br>    num_train_epochs=1,<br>    logging_steps=10<br>)<br><br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=dataset[&quot;train&quot;]<br>)<br><br>trainer.train()</pre><p><strong>What you’ll notice</strong>: The model trains 100x faster than full fine-tuning, and the results are nearly identical.</p><h3>2. Experiment: Compare Pretrained vs. Fine-Tuned</h3><p>Test the difference yourself.</p><pre>from transformers import pipeline<br><br># Before fine-tuning: Generic model<br>base_model = pipeline(&quot;text-generation&quot;, model=&quot;gpt2&quot;)<br>print(base_model(&quot;Translate to French: Hello&quot;, max_length=20))<br># Output: (Probably nonsense or continues in English)<br><br># After fine-tuning on translation data: Specialized model<br># (You&#39;d load your fine-tuned LoRA checkpoint here)<br># finetuned_model = pipeline(&quot;text-generation&quot;, model=&quot;your-finetuned-model&quot;)<br># print(finetuned_model(&quot;Translate to French: Hello&quot;, max_length=20))<br># Output: (Actual French translation)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Bv03S8j9fOqE0bSg3rszw.png" /><figcaption>The base model “knows” French exists, but fine-tuning teaches it <em>when</em> and <em>how</em> to use that knowledge.</figcaption></figure><h3>3. Experiment: The RLHF Simulation (Conceptual)</h3><p>You won’t run real RLHF (it requires massive compute), but you can simulate the idea:</p><pre># The core loop of RLHF:<br><br># Step 1: Generate multiple responses to a prompt<br>prompt = &quot;Explain quantum computing&quot;<br>input_ids = tokenizer(prompt, return_tensors=&quot;pt&quot;).input_ids<br><br>responses = []<br>for _ in range(5):<br>    output_ids = model.generate(input_ids, max_length=120)<br>    response_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)<br>    responses.append(response_text)<br><br># Step 2: Human ranks them (1 = best, 5 = worst)<br># Example: manual scores for illustration<br>rankings = [3, 1, 5, 2, 4]  <br><br># Step 3: Train a reward model to predict these rankings<br># (This is a classification model that learns &quot;good&quot; vs. &quot;bad&quot;)<br><br># Step 4: Use that reward to optimize the LLM<br># (This is where reinforcement learning kicks in)</pre><p><strong>Key Insight</strong>: RLHF is why ChatGPT doesn’t just predict text it predicts <em>helpful</em> text.</p><h3>The Three Big Lessons from Part 3</h3><h3>1. Fine-Tuning is Not Always the Answer</h3><p>Before you fine-tune, try:</p><ul><li>Better prompts (Part 2)</li><li>RAG with your data (Part 2)</li><li>Few-shot examples (Part 2)</li></ul><p>Fine-tuning is for when those fail.</p><h3>2. LoRA is the New Default</h3><p>Full fine-tuning is dead for most use cases. LoRA gives you 90% of the benefit at 1% of the cost.</p><h3>3. Assistant behavior is trained, not accidental</h3><p>Instruction tuning and RLHF are what make a model respond politely, helpfully, and safely.</p><h3>Where This Leaves You</h3><p>By now you’ve seen the full picture:</p><ul><li><strong>Part 1:</strong> how LLMs think</li><li><strong>Part 2:</strong> how to use them</li><li><strong>Part 3:</strong> how to modify them</li></ul><p>You’ve moved from being a user of these tools to someone who can shape how they behave.</p><p><strong>You’re no longer just a user of AI you’re a builder.</strong></p><p>The next time you use ChatGPT, you’ll understand:</p><ul><li>Why it tokenizes your input</li><li>How it encodes meaning with embeddings</li><li>How attention finds relevant context</li><li>How fine-tuning made it helpful</li><li>How RLHF taught it to be harmless</li></ul><h3>What to Do After This</h3><p>You don’t need a huge project. Start small:</p><ol><li>Pick a problem in your field.</li><li>Try prompting and RAG first.</li><li>If that’s not enough, fine-tune with LoRA.</li><li>Build something real and improve it over time.</li></ol><p>The tools are here. The knowledge is yours. Go build something amazing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b9f890cedc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-On Large Language Models: The Pretrained Toolbox (Part 2)]]></title>
            <link>https://medium.com/@muskankh03/hands-on-large-language-models-the-pretrained-toolbox-part-2-89340583d59a?source=rss-469054eefb6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/89340583d59a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Muskan khandelwal]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 00:34:52 GMT</pubDate>
            <atom:updated>2025-10-28T00:34:52.572Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Understanding Text (Classification &amp; Clustering) to Creating Solutions (RAG &amp; Multimodal)</h4><h4>Why Care About Part 2?</h4><p>In Part 1, we learned the “R vs. G” modes: <strong>Representation</strong> (for understanding) and <strong>Generation</strong> (for creating).</p><p>Part 2 of Jay Alammar’s book is the hands-on guide to the <em>entire toolbox</em> built on those two modes. It’s how we go from “theory” to “building real apps.” We’ll explore two distinct toolkits: one for <em>understanding</em> data and one for <em>creating</em> solutions.</p><h3>Toolkit #1: The “Representation” (R) Apps</h3><blockquote>This first set of tools uses embeddings (the “R” mode) to analyze and organize your existing text. We aren’t asking the model to write; we’re asking it to <em>understand</em>.</blockquote><h4>1. Text Classification (The “Labeler”)</h4><ul><li><strong>What it is:</strong> The classic task of sorting text into buckets:</li><li>Sentiment (Positive/Negative)</li><li>Support tickets (Urgent/Billing/Tech)</li><li>Email (Spam/Not Spam)</li><li><strong>Key Takeaway:</strong> You don’t train the whole 7-billion-parameter LLM. You freeze it and train a <em>tiny</em> new layer on top. This is fast, cheap, and highly effective.</li></ul><h4>2. Text Clustering &amp; Topic Modeling (The “Discoverer”)</h4><ul><li><strong>What it is:</strong> Finding hidden themes in thousands of documents <em>without</em> labels. (e.g., “What are my customers complaining about in 10,000 reviews?”)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UC2l61nBs-dc_1l68sdwoA.png" /><figcaption>Discovering Topics with Embeddings</figcaption></figure><p><strong>Key Takeaway:</strong> This turns embeddings into a powerful discovery tool. You can find what you didn’t even know to look for. (This is the concept behind modern tools like BERTopic).</p><h3>Toolkit #2: The “Generation” (G) Apps</h3><p>This second set of tools uses next-token prediction (the “G” mode) to create new text, from simple answers to complex, multi-step plans.</p><h4>3. Prompt Engineering (The “Control Levers”)</h4><ul><li><strong>What it is:</strong> The foundation for all “G” tools. It’s the skill of designing inputs that get you the <em>exact</em> output you need.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*857-fuT8NvxLLfeyvu_V_Q.png" /><figcaption>Prompt Engineering: small changes in input, huge differences in output</figcaption></figure><ul><li><strong>Key Takeaway:</strong> This section covers techniques like <strong>Few-Shot Prompting</strong> (showing 1–2 examples) and <strong>Chain-of-Thought</strong> (adding “Let’s think step-by-step” to force better reasoning).</li></ul><h4>4. RAG (The “R+G” Super-Tool)</h4><ul><li><strong>What it is:</strong> The most important pattern in LLM apps. It connects a generator model to <em>your</em> private data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nW1gw6yZkstaRY4RMnlsw.png" /><figcaption>RAG bridges reasoning and retrieval to eliminate hallucinations</figcaption></figure><ul><li><strong>Key Takeaway:</strong> This solves hallucinations. The model is “grounded” in your facts, allowing it to “chat with your data.”</li></ul><h4>5. Agents (The “Problem-Solver”)</h4><ul><li><strong>What it is:</strong> The next step up from RAG. An agent is an LLM that can <em>use tools</em> (like Google Search, a calculator, or even your RAG pipeline) to solve a problem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*wXPnOMdnSAC2wN3naj8WnA.png" /></figure><ul><li><strong>Key Takeaway:</strong> This turns the LLM from a passive text generator into an <em>active</em> system that can take actions to find new information.</li></ul><h3>The Future: The Multimodal Toolbox (Beyond Text)</h3><blockquote><em>Part 2 finishes by combining both R and G toolkits and applying them to images.</em></blockquote><ul><li><strong>What it is:</strong> Models like CLIP that understand both images and text <em>at the same time</em>.</li></ul><h3>What Clicked for Me and Quick Experiments You Can Try</h3><p><em>(You’ll need to install some libraries: </em><em>pip install transformers torch sentence-transformers)</em></p><p><strong>1. Experiment: The 1-Line Classification “R-Tool”</strong></p><p>See how easy it is to use a pre-trained classification model.</p><pre>from transformers import pipeline<br><br># This downloads a model fine-tuned for sentiment<br>classifier = pipeline(&quot;text-classification&quot;, model=&quot;distilbert-base-uncased-finetuned-sst-2-english&quot;)<br><br>print(classifier(&quot;This is an amazing book!&quot;))<br># Output: [{&#39;label&#39;: &#39;POSITIVE&#39;, &#39;score&#39;: 0.999...}]<br><br>print(classifier(&quot;I was pretty disappointed with the ending.&quot;))<br># Output: [{&#39;label&#39;: &#39;NEGATIVE&#39;, &#39;score&#39;: 0.999...}]</pre><p><strong>2. Experiment: The 5-Line Semantic Search “R-Tool”</strong></p><p>This is the core of clustering and RAG. Find the most similar sentence using embeddings.</p><pre>from sentence_transformers import SentenceTransformer, util<br><br># This downloads a tiny, powerful embedding model<br>model = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br><br># Our &quot;knowledge base&quot;<br>corpus = [<br>    &quot;A man is eating food.&quot;,<br>    &quot;A man is playing a guitar.&quot;,<br>    &quot;The new movie was awesome.&quot;<br>]<br><br># 1. Embed the corpus<br>corpus_embeddings = model.encode(corpus, convert_to_tensor=True)<br><br># 2. Embed our query<br>query = &quot;What is he playing?&quot;<br>query_embedding = model.encode(query, convert_to_tensor=True)<br><br># 3. Find the most similar vector<br>hits = util.semantic_search(query_embedding, corpus_embeddings, top_k=1)<br>print(f&quot;Most similar sentence: {corpus[hits[0][0][&#39;corpus_id&#39;]]}&quot;)<br># Output: Most similar sentence: A man is playing a guitar.2</pre><p><strong>3. Experiment: The 1-Line Multimodal “R+G Tool”</strong></p><p>Use a VQA (Visual Question Answering) model to “chat” with an image.</p><pre>from transformers import pipeline<br>from PIL import Image<br>import requests # Need to install: pip install pillow requests<br><br># This downloads a VQA model<br>vqa_pipeline = pipeline(&quot;visual-question-answering&quot;, model=&quot;dandelin/vilt-b32-finetuned-vqa&quot;)<br><br># Any image URL will work<br>image_url = &quot;place_your_image_url&quot;<br>image = Image.open(requests.get(image_url, stream=True).raw)<br><br>question = &quot;What color is in the image?&quot;<br><br>result = vqa_pipeline(image, question, top_k=1)<br>print(f&quot;Image: {image_url}&quot;)<br>print(f&quot;Question: {question}&quot;)<br>print(f&quot;Answer: {result[0][&#39;answer&#39;]}&quot;)<br># Output: Answer: red</pre><h3>Your Toolbox is Complete</h3><p>From classification to RAG, you now have the full set of tools for <em>using</em> pre-trained models. These patterns are the foundation of modern AI applications.</p><p>But what happens when <em>using</em> a model isn’t enough, and you need to <em>change</em> it?</p><p>In <strong>Part 3</strong>, we’ll dive into <strong>Fine-Tuning</strong> — the art of training the model itself to become an expert for your specific needs. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89340583d59a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-On Large Language Models: LLMs Demystified]]></title>
            <link>https://medium.com/@muskankh03/hands-on-large-language-models-llms-demystified-dc17c2974e30?source=rss-469054eefb6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc17c2974e30</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Muskan khandelwal]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 21:07:56 GMT</pubDate>
            <atom:updated>2025-10-07T21:07:56.988Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-On Large Language Models: LLMs Demystified Part — 1</h3><blockquote>Tokens, embeddings, and transformers in plain English.</blockquote><p><strong>Why care about how LLMs work?</strong></p><p>When you first use ChatGPT or any AI assistant, it feels like magic. Part 1 of Jay Alammar’s <em>Hands-On Large Language Models</em> takes the magic apart — gently — and shows the gears inside. Knowing the basics helps you write better prompts, choose the right tool for a task, and avoid common mistakes (like assuming the model “knows” facts instead of predicting text). Alammar’s Part 1 is exactly about that foundation: <strong>what LLMs are doing under the hood</strong> — with modern, 2024-era explanations and visuals.</p><figure><img alt="LLMs turn text into tokens, map them to vectors, then use attention to predict the next token." src="https://cdn-images-1.medium.com/max/631/1*-mK8DayUKwWfcjO6P9gKyw.png" /><figcaption>LLMs turn text into tokens, map them to vectors, then use attention to predict the next token.</figcaption></figure><p><strong>Tokens: chopping text into model-friendly pieces</strong></p><p>Computers don’t read words the way we do. Before an LLM can process “Large Language Models,” it needs to split the text into <strong>tokens</strong> — small pieces like “Large,” “ Language,” “ Models,” or even subword fragments like “Lang,” “##uage,” depending on the tokenizer. Different models tokenize the same sentence differently (they’re picky about spaces, punctuation, Unicode, even code). This matters because tokenization affects:</p><ul><li><strong>Context length &amp; cost:</strong> More tokens = more compute and cost.</li><li><strong>Edge cases:</strong> Emojis, multilingual text, numbers, and code can tokenize in surprising ways. Part 1 illustrates these differences and even points to code you can run to visualize tokenization across models using the Hugging Face ecosystem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9lVBi7E3E0_oapSJ-Zb9g.png" /><figcaption>Same sentence, different tokenizers: BPE vs WordPiece</figcaption></figure><p><strong>Embeddings: turning meaning into numbers</strong><br> Once text becomes tokens, each token is mapped to a <strong>vector</strong> — a list of numbers that captures aspects of meaning. Put simply, embeddings place words/sentences/documents on a coordinate system where “similar meanings live closer together.” That’s why embeddings power search, clustering, classification, and recommendations (not just chitchat). Alammar emphasizes this duality early: LLMs aren’t only about generating text — they’re also <strong>representation machines</strong> you can use for search and reasoning pipelines.</p><p>A simple mental model:</p><ul><li>If you need <strong>find-me-something-like-this</strong>, you’re in embedding land (representation).</li><li>If you need <strong>write/continue/translate/summarize</strong>, you’re in generation land.</li></ul><p><strong>Transformers in plain English</strong><br> Transformers — introduced in 2017 — are the core architecture behind today’s LLMs. Part 1 includes an updated, modernized explanation building on Alammar’s famous “Illustrated Transformer.” The key intuition: transformers use <strong>attention</strong> to look at the most relevant parts of the input when predicting the next token. Instead of reading text strictly left-to-right like older RNNs, attention lets the model “peek” at relationships anywhere in the sequence, which massively improves quality and parallelization.</p><p><strong>Representation vs. Generation: two model “modes”</strong><br> One of Part 1’s clearest framing devices is color-coding models into two families:</p><ul><li><strong>Representation models</strong> (think embeddings, retrieval, classification).</li><li><strong>Generative models</strong> (think autocomplete, summarization, translation, coding). This distinction shows up across the book and helps you choose the right technique for your problem. In practice, real apps often <strong>combine both</strong>: retrieve relevant info using embeddings, then feed it to a generator (RAG).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7E_a_YhY1wksNgmOlI5xg.png" /><figcaption>Two model modes: <strong>retrieve with embeddings, then generate with an LLM (RAG)</strong></figcaption></figure><p><strong>What clicked for me and quick experiments you can try</strong><br> Here are a few practical takeaways you can test quickly:</p><ol><li><strong>Compare tokenizers on the same sentence.</strong><br>Grab a few models and visualize their tokenization (the book links to a Colab-friendly notebook; code for the book lives on GitHub). Try strings with emojis, numbers, and code. You’ll <em>see</em> why token counts vary and how this affects cost and behavior.</li><li><strong>Build a tiny semantic search. </strong><br>Use any embedding model to vectorize a small set of notes and then cosine-search them. You’ll experience how “meaning” search differs from keyword search and why embeddings underpin modern retrieval workflows. (This is the representation side in action.)</li><li><strong>Prompt with structure.</strong><br>After you grasp tokens/attention, structured prompts make more sense: you’re guiding the model’s next-token predictions with context, examples, and constraints. Try a simple instruction + 1–2 examples, and note the stability you gain.</li><li><strong>Mix R + G (mini-RAG).</strong><br> Create a micro knowledge base (a few markdown files), embed and retrieve the top 3 chunks for a query, and feed those chunks into a generator to answer. You’ll see why “don’t just ask the model — ground it” is the 2025 default.</li></ol><h3>References</h3><ol><li>Jay Alammar &amp; Boris Dayma, <strong><em>Hands-On Large Language Models</em></strong> (O’Reilly, 2024). Overview and visual explanations throughout Part 1. <a href="https://www.oreilly.com/library/view/hands-on-large-language/9781098150952/?utm_source=chatgpt.com">O’Reilly Media</a></li><li>Jay Alammar, <strong>The Illustrated Transformer</strong> — approachable visuals for attention and Transformers. <a href="https://jalammar.github.io/illustrated-transformer/?utm_source=chatgpt.com">jalammar.github.io</a></li><li><strong>Attention Is All You Need</strong> (2017) — the original Transformer paper. <a href="https://arxiv.org/abs/1706.03762?utm_source=chatgpt.com">arXiv+2papers.neurips.cc+2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc17c2974e30" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>