<?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 Shubham Gupta on Medium]]></title>
        <description><![CDATA[Stories by Shubham Gupta on Medium]]></description>
        <link>https://medium.com/@eshubhamgupta?source=rss-f30f21789ff3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jYd32FpVP252lisV</url>
            <title>Stories by Shubham Gupta on Medium</title>
            <link>https://medium.com/@eshubhamgupta?source=rss-f30f21789ff3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:22:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eshubhamgupta/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[Our Paper Got Accepted to AIES 2026. Here’s What It Found, With Numbers.]]></title>
            <link>https://medium.com/@eshubhamgupta/our-paper-got-accepted-to-aies-2026-heres-what-it-found-with-numbers-05d4bb56424f?source=rss-f30f21789ff3------2</link>
            <guid isPermaLink="false">https://medium.com/p/05d4bb56424f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithmic-bias]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[ai-ethics]]></category>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 20:55:08 GMT</pubDate>
            <atom:updated>2026-07-18T20:55:08.710Z</atom:updated>
            <content:encoded><![CDATA[<p>Most counterfactual explanation research assumes something nobody had actually tested: that minimizing weighted proximity between your loan application and a proposed change is a good stand in for what you’d actually want. We ran real people through two studies to check. The answer is close to no.</p><p>I’m a CS senior at Penn State, and I worked on this alongside PHD student Firdaus Ahmed Choudhury, and advisor Prof. Amulya Yadav (College of IST). The paper, “Do Personalized Evaluation Functions Reflect Human Preferences? A Study of Weighted Proximity in Algorithmic Recourse,” was just accepted to AIES 2026, the 9th AAAI/ACM Conference on AI, Ethics, and Society, happening this October in Malmo, Sweden.</p><p>The Setup</p><p>If a bank’s model rejects your loan application, algorithmic recourse tries to answer a different question than “why was I rejected.” It tries to answer “what would I need to change to get approved.” The dominant way researchers score whether a proposed change is good is weighted proximity: a weighted distance between your original application and the recourse option, where the weights are supposed to capture how much you personally care about changing each feature.</p><p>Nobody had actually checked whether this tracks real human preferences. We did.</p><p>We ran the study in two phases. In Phase 1, participants picked between pairs of recourse options for a simulated loan application and told us why. We used those choices to fit a Bradley Terry model, learning individual feature weights for each person. In Phase 2, we used those personalized weights to predict what the same people would prefer in new pairs. This is the most generous possible test for weighted proximity, since the weights come straight from each person’s own prior choices.</p><p>The Results</p><p>Global weighted proximity (the same weights for everyone) matched what people actually chose 53.21% of the time. Barely above a coin flip.</p><p>Personalized proximity did a bit better overall, 56.91%, but that number hides something more interesting. We ran this across two separate studies with 101 participants total. Study 1 hit 65.65% alignment. Study 2 dropped to 48.17%, meaning in the more realistic setting, personalized proximity actually pointed away from what people wanted more often than toward it.</p><p>We ran sensitivity checks to rule out the obvious explanations: not enough contrast between the paired options, not enough training data to learn good weights, the choice of preference model. None of it explained the gap.</p><p>What the Reviewers Said</p><p>Three reviewers looked at this paper. All of them scored it as relevant, rigorous, and worth publishing. One reviewer put it plainly: papers that challenge a foundational assumption in a field are usually harder to get accepted than papers that confirm one, which makes a result like this more valuable, not less.</p><p>The same reviewer also pushed on something we’d flagged but hadn’t dug into enough: that Study 2 number, personalized proximity landing below chance, is arguably the most important finding in the paper, and we’d buried it inside an aggregate figure. Fair critique. If the lower proximity option in a pair is systematically worse on things people actually care about (whether the change is realistic, whether it makes sense to do first versus last, whether it respects someone’s dignity), then weighted proximity isn’t just failing to predict preferences. It’s actively steering people toward the wrong recourse.</p><p>Another reviewer raised a real methodological question: we learn personalized weights by breaking each recourse choice down into separate per-feature comparisons for the Bradley Terry model, which assumes people evaluate features independently. But our own discussion argues people judge recourse options holistically, where one change’s value depends on what else is changing. If that’s right, some of the Phase 2 failure could be coming from how we learned the weights, not from weighted proximity itself. We don’t think this changes the headline finding, but it’s a real nuance worth sitting with.</p><p>Why This Matters</p><p>If a bank deploys an algorithmic recourse system to satisfy a regulatory requirement (like GDPR’s transparency obligations), and that system optimizes for a metric that doesn’t track what people actually want, the system can be fully compliant on paper while failing the people it’s supposed to help. That’s not a hypothetical. It’s the actual state of a metric most of the field has been using without ever checking it against real people.</p><p>Grateful to Firdaus for leading this project, and to Prof. Yadav for his guidance and support throughout.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05d4bb56424f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We Fine-Tuned Mistral-7B on 795 Definition-Aware Examples. Here’s What We Found.]]></title>
            <link>https://medium.com/@eshubhamgupta/we-fine-tuned-mistral-7b-on-795-definition-aware-examples-heres-what-we-found-092970c5074d?source=rss-f30f21789ff3------2</link>
            <guid isPermaLink="false">https://medium.com/p/092970c5074d</guid>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 03:06:07 GMT</pubDate>
            <atom:updated>2026-07-11T03:06:07.364Z</atom:updated>
            <content:encoded><![CDATA[<p>When political scientists use LLMs to apply codebooks (formal classification schemes with written definitions), they assume the model is reading those definitions. Our research suggests it isn’t — and we now have a way to measure exactly what it’s doing instead.</p><p>I’m a CS senior at Penn State working on an honors thesis with Prof. Qunhua Li (Statistics). We’ve spent the last six months trying to get Mistral-7B to actually follow codebook definitions when classifying political text. Here’s what we found, with numbers.</p><p><strong>The Problem: Label Names vs. Definitions</strong></p><p>Consider classifying protest events into categories like PROTEST, RALLY, DEMONSTRATION, and MARCH. These labels share enormous surface vocabulary. A model trained on billions of web documents has strong pretraining associations between these label names and typical news stories about them.</p><p>The key question: when you give the model a formal definition (“PROTEST: a crowd expressing disapproval AT a specific target”), does it use that definition? Or does it just pattern-match on the label name?</p><p>We tested this with a behavioral experiment: swap every label’s definition with a different category’s definition (no label keeps its own definition), then re-run inference. For each prediction made under the swapped codebook, we classify the outcome into one of three mutually exclusive buckets:</p><ul><li><strong>Definition compliance</strong> — the model predicted where the definition moved (it followed the definition)</li><li><strong>Label name compliance</strong> — the model predicted the original label name (it ignored the definition swap)</li><li><strong>Other</strong> — the model predicted neither (surface features in the document text dominate)</li></ul><p>This extends Halterman &amp; Keith (2025), who ran a swapped-label test but only reported a single aggregate accuracy number. Decomposing into three buckets lets us distinguish between two very different failure modes: a model with a clean, systematic label-name shortcut looks very different from a model that isn’t following names or definitions at all — and they need different fixes.</p><p><strong>CCC zero-shot results (8-category protest event dataset, 200 examples):</strong></p><ul><li>Definition compliance: <strong>16.5%</strong> — the model rarely follows definitions</li><li>Label name compliance: <strong>56.0%</strong> — most predictions follow the label name string</li><li>Other: <strong>27.5%</strong> — surface feature matching</li></ul><p>The model follows the word “PROTEST,” not the definition of protest.</p><p><strong>The Fix We Tried: Definition-Aware Synthetic Fine-Tuning</strong></p><p>The natural fix: fine-tune on data that explicitly conditions on the definitions. We extended Han et al.’s focal rewriting approach with definition-aware QA pairs (question-answer examples that literally quote the codebook definition):</p><blockquote><em>Q: What is the main reason people gather in a protest? A: A protest is a crowd gathering to express their disagreement or disapproval towards a specific individual or organization.</em></blockquote><p>We generated these across three datasets:</p><ul><li>CCC (8 categories, US protest events): 75 training examples</li><li>BFRS (12 categories, Pakistani political violence): 180 training examples</li><li>Manifestos (51 categories, party platform statements): 795 training examples</li></ul><p>We also ran a clarification ablation: two variants of each synthetic dataset — one with codebook clarification text in the prompts, one without (definition only).</p><p><strong>The Results</strong></p><p>Fine-tuning with LoRA (rank 8, q_proj/v_proj, 2 epochs on Mistral-7B-Instruct-v0.2):</p><ul><li>CCC (75 examples): definition-only +0.0022 wF1, with-clarification +0.0013 wF1</li><li>BFRS (180 examples): definition-only -0.0099 wF1 (fine-tuning hurt)</li><li>Manifestos (795 examples): definition-only +0.0512 wF1, with-clarification +0.0448 wF1</li></ul><p>Three findings worth unpacking:</p><p><strong>1. Definition-only prompts consistently beat clarification-enriched prompts.</strong> Across every dataset, removing clarification text from synthetic generation prompts produces better fine-tuning signal. Simpler is better.</p><p><strong>2. Fine-tuning hurts on BFRS.</strong> BFRS labels are rare in pretraining data — ASSASSINATION, DRONE_ASSASSINATION, GUERILLA_ATTACK_ON_GOV_FORCES. But notably, DRONE_ASSASSINATION achieves near-perfect F1 under RAG because “drone” is an unambiguous lexical trigger in the document text — a surface shortcut, not definition-following. High BFRS accuracy doesn’t necessarily mean the model is reading definitions; it may just mean certain label names are unambiguous enough that shortcuts work perfectly. 180 synthetic examples add noise on top of this without meaningfully changing the underlying behavior.</p><p><strong>3. Scale matters more than prompt design.</strong> Manifestos shows the largest improvement (+0.051 wF1) with the most training examples (795 vs. 75 for CCC). At scale, prompt design differences become more visible.</p><p><strong>The Harder Finding: Compliance Still Doesn’t Improve</strong></p><p>Here’s the uncomfortable part. Fine-tuning nudges accuracy up, but the three-way compliance distribution barely moves — and RAG, the method that helps accuracy the most, actively makes compliance worse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W44eT7rQy38TxMYRdQD7rQ.png" /></figure><p>Three things stand out:</p><p><strong>RAG makes the label-name shortcut worse, and it scales with k.</strong> Label name compliance climbs monotonically from 57.5% at k=1 to 67.5% at k=10 — the more retrieved examples we hand the model, the more it leans on label names instead of definitions. RAG is also the single best method for raw accuracy (0.7015 wF1 at k=10), which means the method that helps the most on the metric people usually report is actively working against definitional fidelity.</p><p><strong>Stripping label names from RAG examples only partially helps, and hits a ceiling.</strong> Label-stripped k=10 cuts label-name compliance from 67.5% to 59.5% — a real improvement — but it’s barely different from label-stripped k=5 (58.5%). More retrieved text without labels doesn’t keep helping past a point, which suggests the remaining label-name anchoring is coming from the codebook definitions themselves, not from the retrieved examples. Stripping labels also costs accuracy (0.6596 vs. 0.7015 at k=10) — a real accuracy-compliance tradeoff, not a free lunch.</p><p><strong>Fine-tuning shifts the failure mode without fixing it.</strong> All three fine-tuning variants show label-name compliance dropping (56% → ~51–53%) but “other” rising instead of definition compliance improving. The model becomes less confident in its label-name shortcut without learning to follow definitions — it doesn’t get better, it just gets differently wrong. This is a clean negative result: cross-entropy training rewards getting the right label regardless of how the model arrived at it, so a model pattern-matching on label names and a model reading the definition look identical to the loss function. Fixing this needs a different training objective, not more definition-conditioned data.</p><p><strong>BFRS is a different animal entirely.</strong> 77% of its predictions fall into “other” — neither the original label name nor the swapped definition. This isn’t definitional fidelity; it’s surface-feature matching on the document text itself (as with DRONE_ASSASSINATION and the word “drone”). CCC’s problem is label-name shortcuts; BFRS’s problem is something else — a reminder that “the model isn’t following definitions” can mean genuinely different failure modes across datasets.</p><p><strong>What This Means</strong></p><p>A model that classifies correctly for the wrong reason will fail silently on edge cases, new domains, and codebook updates — exactly the situations where a human coder would rely on the written definition.</p><p>Measuring accuracy isn’t enough. The three-way decomposition gives you a way to measure whether your model is actually reading the definitions, following label names, or doing something else entirely — and RAG, the most common accuracy fix, makes the definitional problem worse rather than better.</p><p>Next steps: hard negatives targeting confusable pairs (PROTEST vs. DEMONSTRATION, which share surface vocabulary but have different definitional targets), and compliance-preserving fine-tuning with a contrastive loss that explicitly penalizes label-name-anchored predictions rather than just rewarding the correct label.</p><p>Code is available at <a href="https://github.com/Shubh3005/codebook-compliance-thesis">github.com/Shubh3005/codebook-compliance-thesis</a>.</p><p><strong>The Stack</strong></p><p>All experiments ran on Penn State’s ICDS Roar Collab HPC cluster (NVIDIA V100/P100 GPUs). Model: Mistral-7B-Instruct-v0.2, 4-bit quantized. Fine-tuning: LoRA via HuggingFace TRL. Evaluation: weighted F1 on held-out dev sets (1,009 / 4,495 / 1,732 examples for CCC / BFRS / Manifestos).</p><p><em>Shubham Gupta is a CS senior at Penn State Schreyer Honors College (Dec. 2026) and AI Innovation Fellow at Deloitte. Find him at shubham.us or @Shubh3005 on GitHub.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=092970c5074d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Made My LLM Ignore Definitions Even More]]></title>
            <link>https://medium.com/@eshubhamgupta/rag-made-my-llm-ignore-definitions-even-more-5e521fb7a639?source=rss-f30f21789ff3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e521fb7a639</guid>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 18:17:31 GMT</pubDate>
            <atom:updated>2026-07-03T18:17:31.461Z</atom:updated>
            <content:encoded><![CDATA[<p>How retrieval-augmented generation increased accuracy while decreasing definition compliance in a political science annotation task</p><p>When you add RAG to an LLM, it gets smarter, right? Better context, more relevant examples, higher accuracy. That’s the story everyone tells. But in my honors thesis research, we found something that surprised us: RAG substantially decreased definition compliance, the degree to which the model actually reads and applies the formal definitions it’s given.</p><p><strong>The task</strong></p><p>We were studying whether LLMs can faithfully apply social-science codebooks, structured classification schemes where each category has a precise written definition. For example, a PROTEST is specifically “a crowd gathering to express disapproval AT a specific target.” A DEMONSTRATION is “a crowd showing support TO an external audience.” These distinctions matter to political scientists. They want the model to apply the definition, not guess from context.</p><p>Standard accuracy metrics can’t distinguish between a model that follows definitions and one that succeeds by memorizing label associations. The metric we built is intended to isolate that distinction.</p><p>Our base model: Mistral-7B-Instruct-v0.2 on the CCC dataset (8 protest event categories, 1,009 dev examples). Zero-shot baseline: 0.6494 weighted F1.</p><p><strong>The compliance metric</strong></p><p>To measure whether the model reads definitions or just pattern-matches on label names, we used a swapped-label behavioral test. Take the codebook. Apply a derangement shuffle, every label gets a different category’s definition, guaranteed. Run the model on 200 examples with this swapped codebook, and compare each prediction to what the model predicted under the original codebook.</p><p>We call the fraction of predictions that <em>change</em> under the swapped codebook the <strong>definition compliance rate</strong>. A model that relies primarily on the supplied definitions should be substantially more sensitive to the definition swap, changing far more of its predictions.</p><p>Zero-shot result: definition compliance = 22% (200 evaluation examples). Only 22% of predictions changed after all category definitions were permuted. The model was mostly following label names, not definitions.</p><p><em>A model that classifies correctly for the wrong reason will fail silently.</em> It will fail on edge cases, new domains, and codebook updates, exactly the situations where a human coder would rely on the written definition. When a political scientist uses an LLM to apply a codebook, this distinction matters as much as raw accuracy.</p><p><strong>We then evaluated RAG. As expected, accuracy improved. Unexpectedly, definition compliance dropped even further.</strong></p><p>RAG k=5 brought accuracy to 0.7012 weighted F1, about an 8% relative improvement. So we ran the compliance test on the RAG predictions too.</p><p>Definition compliance with RAG: 15.5%. Even fewer predictions changed when definitions were swapped.</p><p>In our experiments, RAG improved task accuracy while simultaneously decreasing definition compliance. One plausible explanation: RAG retrieves previously labeled examples and injects them into the prompt. Those examples pair label names such as “PROTEST,” “RALLY,” and “MARCH” with prototypical instances of each category. Our results are consistent with the hypothesis that this repeated pairing strengthens label-name anchoring, reducing the relative influence of the written definitions despite their continued presence in the prompt.</p><p><strong>None of the interventions we tried improved compliance</strong></p><p>We ran over ten experiments across three datasets. Across the prompting and training interventions we evaluated, none substantially improved compliance:</p><ul><li>Synthetic fine-tuning (75 examples): modest accuracy gain, no compliance improvement</li><li>Groq LLaMA-3.3–70B generated data (381 examples): hurt accuracy, similar compliance profile</li><li>Compliance penalty fine-tuning: hurt accuracy (-0.018 wF1); definition compliance rose to 28.5%, higher than RAG (15.5%), but still well below what would suggest strong reliance on the supplied definitions</li><li>Hybrid RAG + post-hoc compliance check: no measurable effect on either metric</li></ul><p>The best-accuracy method (RAG) was the worst for compliance.</p><p><strong>Why this matters</strong></p><p>Our results suggest that pretrained label associations may dominate over both the definitions supplied in the prompt and the signal from LoRA fine-tuning, though we haven’t isolated the mechanism directly, and it’s a hypothesis worth testing further.</p><p>One caveat worth noting: 100% compliance isn’t necessarily achievable even by a perfectly definition-following model. Some examples remain ambiguous after swapping definitions, so a correct prediction can coincidentally stay the same. Higher compliance rates still indicate greater reliance on the supplied definitions, they just don’t have a clean ceiling at 100%.</p><p>While our experiments focus on political-event coding, the same issue may arise in any application where models are expected to follow explicit written definitions rather than rely on learned label associations.</p><p><strong>What comes next</strong></p><p>These findings suggest that simply adding retrieval or additional fine-tuning may not be sufficient to close the compliance gap. Future work may need to target the training objective directly, rather than relying solely on retrieval, prompting, or additional fine-tuning.</p><p>If you’re building LLM systems that need to follow structured definitions rather than surface patterns, this is worth measuring directly rather than assuming accuracy gains imply definitional understanding.</p><p><em>Shubham Gupta is a CS senior at Penn State Schreyer Honors College (Dec. 2026) and AI Innovation Fellow at Deloitte. Find him at shubham.us or @Shubh3005 on GitHub.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e521fb7a639" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Got My First Contribution Merged into pytorch/ignite]]></title>
            <link>https://medium.com/@eshubhamgupta/how-i-got-my-first-contribution-merged-into-pytorch-ignite-4b49fe8b55e8?source=rss-f30f21789ff3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b49fe8b55e8</guid>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 02:25:42 GMT</pubDate>
            <atom:updated>2026-06-30T02:25:42.229Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A step-by-step account of implementing CharacterErrorRate for ASR/OCR evaluation</em></p><p>When I started looking for open-source contributions to build my hiring profile, I did what most people do: searched for “good first issue” labels on popular repos. After striking out on a few major ML libraries where every labeled issue was already claimed or resolved, I found pytorch/ignite (a PyTorch training framework with over 5,000 stars) with a clean, unambiguous issue: implement CharacterErrorRate as a follow-up to an existing WordErrorRate metric.</p><p>Here’s exactly what I did.</p><p><strong>What is CharacterErrorRate?</strong></p><p>Character Error Rate (CER) measures how many character-level edits are needed to turn a predicted string into the reference string, divided by the total number of reference characters:</p><p>CER = (S + D + I) / N</p><p>Where S = substitutions, D = deletions, I = insertions, N = total reference characters.</p><p>It’s the standard metric in Automatic Speech Recognition and Optical Character Recognition, where a single wrong character in a financial figure or medical term is a severe failure, not a minor one.</p><p><strong>Why CER and not WER?</strong></p><p>Word Error Rate splits text into words. CER splits into individual characters. For languages without clear word boundaries, or domains where character-level precision matters like handwriting recognition or license plate reading, CER is the more meaningful metric.</p><p>The ignite codebase already had WER. The natural follow-up was CER: same architecture, different tokenization function.</p><p><strong>The implementation</strong></p><p>The key insight from reading the codebase: ignite has a base error rate class that does all the heavy lifting. WER inherits from it and overrides one method to split on whitespace. CER just needs to split on characters instead. The underlying Levenshtein distance computation, batch accumulation, and distributed sync are all inherited automatically. The entire implementation is about 50 lines of actual logic.</p><p>The test suite was more work: 15 cases covering identical sequences, single deletion, insertion, and substitution, empty inputs, batch accumulation, multi-update accumulation, reset behavior, single string input, whitespace as a character, unicode, and the not-computable error before the first update.</p><p><strong>The contribution process</strong></p><p>I found the open issue and commented to claim it before writing any code. Then I read the existing word-error-rate and BLEU metric files closely to understand the established pattern in the codebase, rather than designing something new from scratch. I implemented the new metric following that exact structure, wrote the 15 tests following the existing test file’s conventions, and ran the full test suite locally before opening the pull request with a clear summary linking back to the original issue.</p><p>The maintainer approved it and brought in a co-reviewer. After one round of feedback on test coverage, it was merged.</p><p><strong>What I learned</strong></p><p>The fastest path to a merged PR is finding a repo with a well-established pattern and extending it cleanly, rather than inventing new architecture. Reading the two most similar existing files was effectively the entire design process.</p><p>The test suite matters as much as the implementation. Maintainers merge code they can trust, and a thorough, clearly-named test suite is how you earn that trust quickly.</p><p>Claiming the issue with a comment before writing code avoids duplicate work and opens a conversation with maintainers early, which makes the eventual review faster.</p><p><strong>Links</strong></p><p>Merged PR: github.com/pytorch/ignite/pull/3785</p><p>pytorch/ignite: github.com/pytorch/ignite</p><p><em>Shubham Gupta is a CS senior at Penn State Schreyer Honors College (Dec. 2026) and AI Innovation Fellow at Deloitte. Find him at </em><a href="https://shubham.us/"><em>shubham.us</em></a><em> or </em><a href="https://github.com/Shubh3005"><em>@Shubh3005</em></a><em> on GitHub.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b49fe8b55e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CodeBase Part 2: Multi-Repo Comparison, Repo Health Summaries, and What I Learned Deploying to…]]></title>
            <link>https://medium.com/@eshubhamgupta/codebase-part-2-multi-repo-comparison-repo-health-summaries-and-what-i-learned-deploying-to-0f3407ce2ff9?source=rss-f30f21789ff3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f3407ce2ff9</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[hackathons]]></category>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 02:44:59 GMT</pubDate>
            <atom:updated>2026-06-26T02:44:59.281Z</atom:updated>
            <content:encoded><![CDATA[<h3>CodeBase Part 2: Multi-Repo Comparison, Repo Health Summaries, and What I Learned Deploying to Production</h3><h4><em>This post was created for the purposes of entering the H0: Hack the Zero Stack hackathon. #H0Hackathon</em></h4><p>Two weeks ago I published <a href="https://medium.com/@eshubhamgupta/building-codebase-an-ai-powered-codebase-onboarding-tool-in-one-day-9189c046590e">Part 1</a> about building CodeBase — a tool that lets you point at any GitHub repo and ask it questions, with answers cited down to the file and line number. The core pipeline worked: ingest → embed → FAISS → Groq → cited answer.</p><p>This week I shipped three new features and deployed the full stack to production. Here’s what I built and what broke along the way.</p><h3>Feature 1: Entry Point Boost</h3><p>The first real user complaint I anticipated: “What is the entry point of this application?” should always return main.py or app.py. But FAISS doesn&#39;t know that — it ranks by semantic similarity, and entry point files are often small with few tokens, so they get buried.</p><p>The fix: after FAISS returns its top-k results, check if the query contains entry point keywords (“how to run”, “where does the app start”, “entrypoint”). If yes, and if none of the top-k results already contain a known entry point file (main.py, app.py, index.js, etc.), inject the first matching entry point file into the results.</p><p>The tricky part was getting the keywords right. “main” and “start” were too broad, “what does the main authentication function do?” would incorrectly trigger the boost. Final keyword list:</p><pre>&quot;entry point&quot;, &quot;how to run&quot;, &quot;how does it start&quot;,<br>&quot;how do i run&quot;, &quot;getting started&quot;, &quot;entrypoint&quot;,<br>&quot;main file&quot;, &quot;main module&quot;, &quot;where does the app start&quot;</pre><p>One injected chunk per query, maximum. Strings are already character sequences in Python — no need to explicitly convert them to lists first. I learned this the hard way reviewing a PR on pytorch/ignite this week.</p><h3>Feature 2: Repo Health Summary</h3><p>After ingestion completes, CodeBase now generates a faiss/{repo_id}.summary.json in S3:</p><p>json</p><pre>{<br>  &quot;repo_name&quot;: &quot;Shubh3005/CodeBase&quot;,<br>  &quot;total_files&quot;: 18,<br>  &quot;total_chunks&quot;: 312,<br>  &quot;languages&quot;: {&quot;Python&quot;: 15, &quot;Other&quot;: 3},<br>  &quot;entry_points&quot;: [&quot;main.py&quot;],<br>  &quot;largest_files&quot;: [...],<br>  &quot;generated_at&quot;: &quot;2026-06-24T...&quot;<br>}</pre><p>This powers a compact sidebar card in the frontend — primary language, file count, entry points detected. Three lines, generated automatically, no extra user action required.</p><p>The implementation detail that matters: this runs <em>after</em> _save_to_s3() in the ingestion pipeline, using the same chunk list already in memory. No extra DynamoDB scan, no extra embedding pass. Pure metadata aggregation over data you already have.</p><h3>Feature 3: Multi-Repo Comparison</h3><p>This is the one I’m most proud of. You can now compare two repos side-by-side with a single question.</p><p>The flow:</p><ol><li>User clicks Compare, enters a second GitHub URL and a question</li><li>Frontend ingests the second repo (same pipeline, new repo_id)</li><li>POST /api/repos/compare runs retrieval on both repos in parallel via asyncio.gather</li><li>Both chunk sets go to the LLM with a modified system prompt: “Answer for each codebase separately, label answers as [Repo 1: owner/repo] and [Repo 2: owner/repo]”</li><li>Citations are parsed separately for each repo: split the answer text at “[Repo 2:” before parsing, so Repo 1’s citations don’t bleed into Repo 2’s attribution</li></ol><p>That last point, citation bleed, was the bug that took the longest to find. The _parse_citations() function scanned the full answer text for citation patterns. Since the LLM mentioned Repo 1&#39;s files in the first half of the answer, those file paths would match against Repo 2&#39;s chunk list too, producing phantom citations. Splitting the answer at the Repo 2 section boundary before parsing fixed it completely.</p><h3>The Production Stack</h3><p>The full architecture for the H0 submission:</p><ul><li><strong>Frontend</strong>: Next.js on Vercel</li><li><strong>Backend</strong>: FastAPI (Python 3.11)</li><li><strong>Vector search</strong>: FAISS (IndexFlatIP, cosine similarity)</li><li><strong>Embeddings</strong>: sentence-transformers all-MiniLM-L6-v2 (384-dim)</li><li><strong>Chunk metadata</strong>: AWS DynamoDB</li><li><strong>FAISS indexes + repo summaries</strong>: AWS S3</li><li><strong>LLM</strong>: Groq running Llama 3.3 70B</li><li><strong>Tunneling for demo</strong>: ngrok (Railway deployment kept hitting a missing git binary issue — gitpython imports at startup, and Railway&#39;s base image doesn&#39;t include git)</li></ul><p>The Railway bug was instructive: gitpython calls git.refresh() at module import time, before any of your code runs. If git isn&#39;t in $PATH, the entire FastAPI app fails to start. The fix is either a nixpacks.toml that installs git, or setting GIT_PYTHON_REFRESH=quiet as an environment variable to suppress the check. We went with both.</p><h3>What’s Next</h3><p>The compliance question from my thesis research is starting to feel relevant to CodeBase too: does the LLM actually <em>understand</em> the code it’s citing, or is it pattern-matching on token similarity? The citation grounding helps, but that’s the user doing the compliance check, not the system.</p><p>Next experiments: adding a re-ranker that filters FAISS results by semantic relevance before passing to the LLM, and testing whether compliance (answer accuracy vs. cited content) degrades as repo size scales.</p><p><em>Built for the H0: Hack the Zero Stack hackathon. Demo video and full submission at devpost.com. Link coming tomorrow.</em></p><p><em>Shubham Gupta is a CS senior at Penn State Schreyer Honors College (Dec. 2026) and AI Innovation Fellow at Deloitte. Find him at </em><a href="https://shubham.us/"><em>shubham.us</em></a><em> or </em><a href="https://github.com/Shubh3005"><em>@Shubh3005</em></a><em> on GitHub.</em></p><p><em>#H0Hackathon #AI #AWS #FastAPI #LLM</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f3407ce2ff9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building CodeBase: An AI-Powered Codebase Onboarding Tool (in One Day)]]></title>
            <link>https://medium.com/@eshubhamgupta/building-codebase-an-ai-powered-codebase-onboarding-tool-in-one-day-9189c046590e?source=rss-f30f21789ff3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9189c046590e</guid>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 15:01:48 GMT</pubDate>
            <atom:updated>2026-06-13T15:01:48.690Z</atom:updated>
            <content:encoded><![CDATA[<p><em>#H0Hackathon</em></p><p>Every engineer knows the feeling: you join a new project, clone the repo, and stare at a folder tree with zero context. Where does auth live? What’s the entry point? Which module actually does the thing the README claims it does?</p><p>For the H0 Hackathon, I built <strong>CodeBase: </strong>a tool that lets you point at any GitHub repo and immediately start asking it questions, with answers cited down to the file and line number.</p><h3>The Pipeline</h3><p>The architecture is a four-stage agent pipeline:</p><ol><li><strong>Ingestion Agent</strong> — clones the target repo, walks the source tree, and parses every Python file into an AST. Each function, class, and module becomes a “chunk” with its own metadata (file path, line range, signature).</li><li><strong>Embedding + Indexing</strong> — each chunk gets embedded and pushed into a FAISS index for fast similarity search. The index itself is persisted to S3, and chunk metadata (including the embedding ID that maps a FAISS result back to actual source code) lives in DynamoDB.</li><li><strong>Retrieval Agent</strong> — given a user’s question, embed the query, hit FAISS, pull back the top-k matching chunks.</li><li><strong>Explanation Agent</strong> — feed those chunks plus the question to an LLM (Groq running Llama 3.3 70B) and generate an answer that cites the exact file:line it came from.</li></ol><p>On top of that sits a Next.js frontend: paste a repo URL, watch it get ingested, then chat with it.</p><h3>The Bug That Took Down the Whole Pipeline</h3><p>Each component alone worked perfectly. Ingestion ran clean, FAISS returned results, Groq generated fluent answers. But every single query came back with <strong>zero retrieved chunks</strong>, no matter what I asked.</p><p>The culprit: DynamoDB’s ProjectionExpression. When fetching chunk metadata by ID, I&#39;d specified which fields to return and embedding_id wasn&#39;t one of them. FAISS was returning the correct vector match, but the lookup step that maps &quot;FAISS index position 47&quot; back to &quot;the actual function at auth/middleware.py:112&quot; was silently returning records missing the one field needed to make that connection. The join failed quietly, so retrieval always came back empty.</p><p>One line fix. Add embedding_id to the projection. Suddenly: 201 chunks parsed, FAISS scoring correctly, Groq generating cited, accurate answers against a real codebase (tested on my own HealthcareAgent repo).</p><h3>Why This Matters</h3><p>This isn’t just a hackathon demo — it’s the tool I wish existed every time I’ve onboarded onto a new codebase, whether for an internship, an open source contribution, or picking up a teammate’s half-finished feature. The “ask the codebase, get a cited answer” loop turns hours of grep-and-guess into seconds.</p><p><strong>Stack:</strong> FastAPI, FAISS, AWS DynamoDB + S3, Groq (Llama 3.3 70B), Next.js, deployed on Vercel.</p><p>More to come as I finish polishing the demo for submission — architecture diagrams and a walkthrough video next.</p><p><em>#H0Hackathon #AI #FastAPI #AWS</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9189c046590e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Networked Storage System from Scratch in C]]></title>
            <link>https://medium.com/@eshubhamgupta/building-a-networked-storage-system-from-scratch-in-c-3dbf2e58f062?source=rss-f30f21789ff3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dbf2e58f062</guid>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[systems-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 17:40:42 GMT</pubDate>
            <atom:updated>2026-06-05T17:40:42.619Z</atom:updated>
            <content:encoded><![CDATA[<h4>10× throughput, 1,000+ concurrent connections, built from raw sockets and pthreads</h4><h4>Building a Networked Storage System from Scratch in C</h4><p>I wanted to understand what actually happens when you read a file over a network. Not the abstraction — the bytes, the sockets, the seek state, the cache invalidation. So I built a networked JBOD (Just a Bunch of Disks) storage system from scratch in C.</p><p>This post walks through the key implementation decisions: the binary wire protocol, reading across block boundaries, write-modify-write for partial writes, and an LRU block cache that cuts network round-trips by 85% on sequential workloads. The result: <strong>10× throughput over a single-threaded baseline</strong> at 1,000+ concurrent connections.</p><blockquote><em>High-concurrency network storage in C — 10× throughput over single-threaded baseline.</em></blockquote><h3>What Is This</h3><p>A networked JBOD (Just a Bunch of Disks) storage system built from scratch in C. The system exposes a unified address space across 16 virtual disks, each with 256 blocks of 256 bytes. Clients connect over TCP, send operations (mount, seek, read, write), and the server handles concurrent requests with correct data integrity guarantees.</p><p>This was built across 5 assignments, incrementally adding: basic I/O → write permissions → network protocol → LRU caching → concurrent client support.</p><h3>Architecture</h3><pre>Client(s) ──TCP──► jbod_connect()<br>                      ↓<br>                  send_packet()     ← custom binary wire protocol<br>                      ↓<br>                  jbod_server       ← pre-compiled server binary<br>                      ↓<br>              [16 virtual disks × 256 blocks × 256 bytes]</pre><p><strong>Address translation:</strong></p><pre>disk_id     = address / JBOD_DISK_SIZE          // which disk<br>block_id    = (address % JBOD_DISK_SIZE) / JBOD_BLOCK_SIZE  // which block<br>offset      = address % JBOD_BLOCK_SIZE         // position within block</pre><h3>Key Implementation Details</h3><h3>1. Custom Binary Wire Protocol (net.c)</h3><p>Every operation is encoded as a 32-bit opcode with disk ID and block ID packed in:</p><pre>uint32_t returnID(jbod_cmd_t command, int diskID, int block) {<br>    command = command &lt;&lt; 12;<br>    block   = block &lt;&lt; 4;<br>    return (command | diskID | block);<br>}</pre><p>Packets are sent over raw TCP sockets with a 5-byte header — 4 bytes for the operation, 1 byte for flags (indicates whether a 256-byte block payload follows). Network byte order handled via htonl/ntohl.</p><h3>2. Read Spanning Multiple Blocks</h3><p>Reading across block and disk boundaries requires seeking, reading 256-byte chunks into a temp buffer, then memcpy-ing only the needed bytes:</p><pre>while (bytes &lt; read_len) {<br>    bytes_left = min(JBOD_BLOCK_SIZE - starting_pos, read_len - bytes);<br>    <br>    // Cache hit? Skip the network round-trip<br>    if (cache_lookup(starting_disk, starting_block, buf) == -1) {<br>        jbod_client_operation(JBOD_READ_BLOCK, buf);<br>        cache_insert(starting_disk, starting_block, buf);<br>    }<br>    <br>    memcpy(read_buf + bytes, buf + starting_pos, bytes_left);<br>    bytes += bytes_left;<br>    starting_pos = 0;  // only non-zero on first block<br>}</pre><h3>3. Write-Modify-Write for Partial Block Writes</h3><p>Writing to the middle of a block requires reading the full 256 bytes first, modifying the target range, then writing the whole block back:</p><pre>// Read existing block<br>jbod_client_operation(JBOD_READ_BLOCK, temp_buf1);</pre><pre>// Patch only the bytes being written<br>memcpy(temp_buf2, temp_buf1, offset);                          // prefix unchanged<br>memcpy(temp_buf2 + offset, write_buf + toWrite, bytesWrite);  // new data<br>memcpy(temp_buf2 + offset + bytesWrite,                        // suffix unchanged<br>       temp_buf1 + offset + bytesWrite,<br>       JBOD_BLOCK_SIZE - (offset + bytesWrite));</pre><pre>// Write full modified block back<br>jbod_client_operation(JBOD_WRITE_BLOCK, temp_buf2);</pre><h3>4. LRU Block Cache (cache.c)</h3><p>To avoid redundant network round-trips to the server, a configurable block cache (2–4096 entries) stores recently accessed disk blocks. Cache eviction uses a clock-based LRU — each access increments a global clock and stamps the entry; eviction replaces the most-recently-used entry when full (MRU eviction under the assumption that recently used blocks are less likely to be reused shortly).</p><pre>// On read: check cache before hitting the network<br>if (cache_lookup(disk, block, buf) == -1) {<br>    jbod_client_operation(JBOD_READ_BLOCK, buf);<br>    cache_insert(disk, block, buf);<br>}</pre><p>Cache hit rate reaches <strong>85%+</strong> on sequential workloads, cutting network operations by the same margin.</p><h3>Results</h3><p>Metric Value Throughput vs. single-threaded baseline <strong>10×</strong> Concurrent connections supported 1,000+ Cache hit rate (sequential workload) ~85% Disks 16 virtual Address space 16 × 256 × 256 = 1,048,576 bytes</p><h3>What I Learned</h3><ul><li><strong>Read-modify-write is unavoidable</strong> for sub-block writes — you can’t partially overwrite a 256-byte block without reading it first</li><li><strong>Network byte order matters</strong> — the server rejects malformed packets silently; debugging required Wireshark to confirm htonl was being called correctly</li><li><strong>Cache eviction policy is non-obvious</strong> — standard LRU evicts the <em>least</em> recently used; for this sequential access pattern, evicting MRU actually performed better in testing</li><li><strong>Seek state is implicit</strong> — the JBOD server maintains a current disk/block cursor; every operation must seek explicitly or risk reading the wrong block</li></ul><h3>Stack</h3><ul><li><strong>Language:</strong> C (C99)</li><li><strong>Concurrency:</strong> POSIX sockets, persistent TCP connections</li><li><strong>Protocol:</strong> Custom binary wire format over TCP</li><li><strong>Data structures:</strong> Array-based block cache with clock-based eviction</li><li><strong>Build:</strong> GNU Make</li></ul><p><em>Built by </em><a href="https://shubham.us/"><em>Shubham Gupta</em></a><em> — Penn State CS, Schreyer Honors College</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dbf2e58f062" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>