<?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 Muhammad Junaid on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Junaid on Medium]]></description>
        <link>https://medium.com/@mjunaid7843?source=rss-18f87f50440d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S4_qvw5H6afqm0mXdNRrMQ.jpeg</url>
            <title>Stories by Muhammad Junaid on Medium</title>
            <link>https://medium.com/@mjunaid7843?source=rss-18f87f50440d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:07:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mjunaid7843/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[How I cut token usage by 75% and stopped trusting hallucinated coverage.]]></title>
            <link>https://medium.com/@mjunaid7843/how-i-cut-token-usage-by-75-and-stopped-trusting-hallucinated-coverage-c8ab3989b8db?source=rss-18f87f50440d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8ab3989b8db</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[level-up-coding]]></category>
            <category><![CDATA[legacy-code]]></category>
            <category><![CDATA[itnext]]></category>
            <category><![CDATA[cursor]]></category>
            <dc:creator><![CDATA[Muhammad Junaid]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 14:37:28 GMT</pubDate>
            <atom:updated>2026-07-17T14:37:28.892Z</atom:updated>
            <content:encoded><![CDATA[<h3>The real cost of AI on legacy codebases isn’t the work. It’s the discovery.</h3><p>The usage meter hit 100% and Claude hadn’t migrated a single file yet.</p><p>I’m working on a legacy code migration right now. The codebase is the kind of thing that makes you laugh when you first open it. 14,221 connected symbols. 38,031 dependency edges. Thousands of files, all referencing each other in ways nobody documented, written by people who left years ago.</p><p>I threw Claude at it the way most of us do. Point it at the repo, ask it to understand the system, start planning the migration. And it burned through my entire Claude Max plan doing nothing but reading.</p><p>Not migrating. Reading.</p><h3>The discovery phase is where the money goes</h3><p>Here’s what actually happens when you ask an AI to work on a large legacy system. Every task turns into an expedition. To change one method, the model has to figure out what calls it, what it calls, what shares state with it, and what breaks if it moves. So it opens a file. That file references four others. Each of those references more.</p><p>The tokens weren’t going into work. They were going into navigation.</p><p>And it gets worse than expensive. With that much noise in context, the model starts missing things. A helper function here. An edge case three files deep. Then it does something more dangerous than missing things: it confidently tells you it has full coverage when it doesn’t.</p><p>That’s the part that scared me. Wasted tokens cost money. Hallucinated coverage costs you the migration.</p><h3>The model wasn’t failing, it was navigating blind</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_pw4M063EzjMlu7VXpgVg.png" /><figcaption>Code graph visualization of a legacy codebase with 14,221 connected symbols used to guide an AI-assisted migration.</figcaption></figure><p>My first instinct was to blame the model. Too big a codebase, maybe this needs a bigger context window, maybe I wait for the next release.</p><p>Wrong direction. The model was doing exactly what I’d asked, which was to reconstruct the architecture of a massive system from scratch, one file at a time, on every single task. No human engineer works that way either. We draw diagrams. We keep a mental map. We know where things live.</p><p>The model had no map. So I gave it one.</p><p>I ran Graphify on the codebase. It’s an open source tool that parses the whole project and builds an actual code graph: every symbol, every relationship, laid out visually and queryable. Instead of Claude crawling through files to figure out what depends on what, it queries the graph and gets the answer directly.</p><p>Token usage dropped to a quarter of what it was. Same codebase, same tasks, 75% less spend. But the cost drop turned out to be the smaller win.</p><h3>Coverage became a fact, not a vibe</h3><p>The bigger win was what happened to trust.</p><p>Before the graph, “coverage” meant Claude telling me it had accounted for everything, and me choosing to believe it. That’s not engineering. That’s hope with a subscription fee.</p><p>Now the graph is the source of truth. Every file gets marked as migrated only after its tests pass. At any moment I can look at the graph and see exactly what’s done, what’s pending, and what’s still untouched. When something claims to be complete, I don’t have to trust the claim. I can check it against a structure that doesn’t hallucinate.</p><p>That changed how I think about AI on big projects generally. Most of the “AI can’t handle large codebases” complaints I read aren’t really about model capability. They’re context problems wearing a capability costume. The model isn’t weak. It’s blind, and we keep asking it to sprint.</p><h3>Give the model a map before you ask it to move anything</h3><p>If you’re doing anything serious with AI on a legacy system, spend the first hour building structure the model can lean on. A code graph, a dependency map, even a generated index of what lives where. It feels like a detour. It’s the opposite.</p><p>My migration is still running. My plan hasn’t maxed out since. And for the first time in this project, when I say a module is fully migrated, I’m not quoting the model.</p><p>I’m quoting the tests.</p><p>What’s your setup for pointing AI at codebases too big to fit in anyone’s head? I’m collecting approaches, because I don’t think mine is the last word on this.</p><p><strong>Tags</strong>: Artificial Intelligence, Programming, Software Engineering, Claude, Legacy Code</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8ab3989b8db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A small language model (SLM) on an 8GB laptop wrote flawless business logic]]></title>
            <link>https://medium.com/@mjunaid7843/a-small-language-model-slm-on-an-8gb-laptop-wrote-flawless-business-logic-d5c0f4158c77?source=rss-18f87f50440d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5c0f4158c77</guid>
            <category><![CDATA[small-language-model]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[legacy-code]]></category>
            <dc:creator><![CDATA[Muhammad Junaid]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 12:37:46 GMT</pubDate>
            <atom:updated>2026-07-08T12:37:46.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fstlQcXnBQ5OVkb4AJAxsA.png" /></figure><p><em>Most people will tell you a small local model can’t write real business logic. I believed it too, until a 3-billion-parameter coder model on an 8GB MacBook scored a perfect 12 out of 12 on a pricing engine. What got it there had nothing to do with making the model bigger or smarter.</em></p><p>A few weeks ago I read Muhammad Ansar’s piece, <a href="https://www.linkedin.com/pulse/coding-small-language-models-hosted-your-local-ansar-bbbxf">Coding with Small Language Models Hosted on Your Local Machine</a>. He asks a question I keep coming back to: can a model running entirely on your own laptop, with no cloud API, no per-token bill, and nothing leaving the machine, produce business logic that is correct? Not code that looks right. Code whose output matches the ground truth to the cent, on every row.</p><p>Ansar’s answer came with a recipe: rewrite the spec into the model’s “dialect” and a 3B starts passing. I forked his repo and went after the part that bugged me. Where exactly does a small model break, and why? I ended up running the same ten-rule pricing problem a few hundred times across two model sizes, and the answer surprised me enough that I threw out my own first explanation.</p><h3>The setup</h3><p>Everything runs on an entry-level 8GB M1 MacBook using Apple’s MLX framework. On 8GB, a 7B model is about the ceiling; anything larger will not load. The model is Qwen2.5-Coder-Instruct, 4-bit quantized. The 3B is a 1.8 GB download and does most of the work. The 7B, which I bring in later, is about 4.3 GB and still fits, one model resident at a time.</p><p>The task never changes. The model has to write a Python function, process_calculations(csv_path), that reads a CSV of transactions and returns one number per row: total_receivables. Getting there means a chain of rules. Look up a base rate by product and customer type, multiply by volume, take three stacking discounts off, add a regional and a payment loading, scale those into a commission with a category multiplier, then withhold tax on unverified rows. Passing means all 12 rows match the reference to within half a cent.</p><p>What keeps this honest is a ground-truth oracle. A reference implementation computes the correct answer for every row, the model’s generated code runs against it, and each row is scored. Nobody eyeballs the output and nobody grades the prose. It is test-driven development pointed at a language model, and the test set has the final say.</p><h3>It is not the number of rules</h3><p>The obvious guess is that fewer rules make an easier job. I walked it down:</p><ul><li>At 17 rules, everything failed. The smallest model, the 0.5B, called a column that did not exist and crashed. The 3B and 7B both went 0 for 19.</li><li>At 10 rules, the 3B limped to 3 out of 12. The 7B got the whole structure right and still landed 2 to 5% off on every row, undone by a couple of small bugs.</li><li>At 5 rules, the 3B passed 12 out of 12 on the first try.</li></ul><p>So far this matches the intuition. Then I changed one thing and the intuition fell apart. I took the same ten rules and only reworded them into the model’s dialect. The 3B jumped from 3 out of 12 to a clean 12 out of 12 on the first greedy attempt, on the same problem, with the arithmetic untouched to the last decimal. The only thing I had changed was the wording. (There is also a scale test in the repo where a freshly written spec of roughly thirty rules, written the same way, passes 23 out of 23 first try.)</p><p>So rule count was never the thing that mattered. How each rule is written is.</p><h3>A ladder to find the exact breaking point</h3><p>If wording is the lever, I wanted the precise point where a 3B stops producing correct code. So I built a ladder of eight specs. Every rung describes the same ten rules against the same targets. The harness is frozen: same instruction wrapper, same decoding, same scorer. The only thing that changes from one rung to the next is how the spec is written, so any change in the score comes down to phrasing alone.</p><p>The first five rungs strip away one layer of hand-holding at a time, from the heavily engineered dialect down to plain business writing:</p><ul><li>L1, step-by-step pseudocode. Literal lookup tables, the volume rule spelled out as two additive checks with an explicit “no elif”, bare decimals. This is the anchor.</li><li>L2, plain declarative prose, but the lookup tables are still handed over verbatim.</li><li>L3, business prose. The tables are gone. Rates now show up as dollars and percentages the model has to turn into its own data structures.</li><li>L4, L3 plus the volume rule written as natural tiers (“under 100, 100 to 999, 1000 or more”).</li><li>L5, L4 plus the original True/False booleans. This is the original spec, word for word.</li></ul><p>Sampling each rung ten times and taking the best result, the picture is stark:</p><ul><li>L1 reaches 12/12, and passed on 7 of 10 tries.</li><li>L2 reaches 12/12, on 5 of 10.</li><li>L3 tops out at 4/12, and never passed once in 10.</li><li>L4 tops out at 3/12, 0 of 10.</li><li>L5 tops out at 6/12, 0 of 10.</li></ul><p>The cliff sits between L2 and L3. Dropping the step-by-step recipe from L1 to L2 costs nothing; plain prose is fine. The moment the literal tables come out, at L3, the model never once reaches 12 out of 12 in ten tries. A single deterministic greedy run draws the same line: every rung that keeps the tables passes on the first shot, every rung that drops them fails.</p><h3>The twist: it was not the traps I blamed</h3><p>Here is where I had to correct myself. The original write-up, and my own first instinct, pinned the failure on two classic traps:</p><ol><li>The volume tier. A three-way rule (under 100 gets nothing, under 1000 gets 5%, otherwise 10%) gets collapsed into something like 0.05 if v&lt;100 else (0.1 if v&lt;1000 else 0.1), wrong in two of three branches.</li><li>The boolean. The “tax verified” cell arrives as the text “False”, which is truthy in Python, so a not verified check skips the withholding on exactly the rows that need it.</li></ol><p>Both are real. So I ran controls: keep the literal tables, but put both traps back. If the traps were the problem, these rungs should fail.</p><p>They passed. The tier trap alone, the boolean trap alone, and both together all reached 12 out of 12, as long as the tables were present. Meanwhile every tables-removed rung failed. So the picture is clean: with the tables in the spec, every dialect is reachable; with the tables pulled out, none of them is. The literal lookup tables are doing the load-bearing work. The two famous traps are close to a red herring.</p><p>So what breaks at L3? I looked at which rows survived, and it was always the same four: the ones where the region and payment loadings are both zero, which means the commission is zero. Every wrong row had a non-zero loading, and the error was exactly the missing commission. One electronics-and-EMEA row, for instance, comes out at a ratio of 0.8929, which is 1 divided by 1.12, precisely what you get when you drop commission = (region loading + payment loading) x 1.2 from the subtotal. Strip the scaffolding and the 3B still nails the price table, all three discounts, the volume tier, and the tax withholding. What it cannot do is assemble a three-step derived quantity from prose. Narrate a multi-step formula in one sentence and a 3B loses the thread.</p><h3>But maybe it just doesn’t know the tables</h3><p>That was my next theory. Maybe the prose starves the model of the actual rates. So I handed the tables back three ways: I let the model extract them from the prose itself, I pre-seeded its answer with the tables already written as code, and I had the bigger 7B extract them for the 3B to use.</p><p>The extraction was correct every single time. Every model size, every rung, every run rebuilt the rate tables perfectly. And the code still failed.</p><p>So knowledge was never the constraint. With the correct tables in hand, its own tables, the coder still botched the same step. It reads “a 10% surcharge” as receivable *= 1.10 instead of creating a separate 0.10 * receivable amount, so the two loading values never exist as variables and the commission has nothing to add up. (In the two-stage version it even trips over itself: the extractor writes &quot;1&quot; as a string key, and half the time the coder indexes it as an integer.) What the good specs give the model is not the numbers in the tables. It is the shape of the code around them: bare decimals and named quantities that force each step to exist as its own variable.</p><h3>Does a bigger model just fix it?</h3><p>I cannot go past 7B on 8GB, but I ran the whole ladder on the 7B anyway to see whether scale moves the cliff.</p><p>On a single greedy attempt, it does not move at all. The 7B fails every tables-removed rung too, at 4 out of 12 against the 3B’s 3. That one extra row comes from cleaner text handling, not from any progress on the commission chain; the same missing-commission signature is right there in the output. Doubling the parameter count does not buy a first-try pass on business prose. Put bluntly, the way the spec is written was worth more than four billion extra parameters.</p><p>Scale does buy something quieter. When I sampled the 7B ten times, it could reach 12 out of 12 on the hard rungs the 3B never solved, but only as a 1-in-10 to 2-in-10 event. The well-structured rungs, by contrast, run at 8 to 10 out of 10. Scale turns “impossible” into “occasionally”, not into “reliable”.</p><p>It also swaps one bug for another. On the natural-tier rungs the 7B gets stuck at exactly 10 out of 12 in 17 of 20 samples, always on the two large-volume rows, because it writes the tier as a misordered chained ternary: 0.05 if volume &gt;= 100 else 0.10 if volume &gt;= 1000 else 0.0. The first condition catches everything at or above 100, so the 0.10 branch is dead code and the biggest orders get half their discount. That is the original volume-tier bug wearing a new outfit. The 3B collapsed the bounds; the 7B misorders the ternary. Only the additive phrasing, add 5% at 100 and another 5% at 1000, held up at both sizes.</p><h3>Can a smarter repair loop win the argument?</h3><p>The built-in repair loop just tells the model “row 3, you got X, expected Y.” That single number cannot say which of ten steps went wrong, so the model tends to rewrite the same bug with more confidence. I built a white-box loop instead. A reference computes every intermediate value, and on each failing row the loop names the first step that diverges: “correct through the payment loading, but commission is 0.00, should be 3206.25.”</p><p>The localization works. At a low temperature it pulled the boolean rung all the way to 12 out of 12 in a single repair iteration, and lifted the tier rung to 8 out of 12. The fully de-scaffolded prose rung still would not close.</p><p>Then the strangest result in the whole project. For round two of the repair loop I added what looked like obvious improvements: put the model’s previous code in the prompt and tell it to edit only the broken step, freeze the steps already verified correct, and so on. It got worse, and not by a little. Every repair candidate scored an identical 3 out of 12, iteration after iteration, even though the localization was working fine. Show a small model its own code and it copies it. When I took the previous code back out and forced the model to regenerate from the feedback alone, the variance came back, candidate scores in a single round would spread like 12, 2, 0, and the loop started climbing. On the 3B that was enough to rescue the boolean rung. On the 7B, fresh regeneration plus the per-step feedback closed the entire board: all three prose rungs converged to 12 out of 12 within five iterations, including L3, the business-prose rung that had resisted every other lever at both sizes.</p><p>The design rule that falls out of this is worth writing on a sticky note: give a small model feedback about its code, never the code itself.</p><h3>One boring methodology note that matters</h3><p>A single greedy generation is a knife-edge. At one point a one-line change to a spec’s title flipped a passing rung from 12 out of 12 to 0 out of 12, because it quietly dropped a table definition from the model’s output. If you judge a small model on one roll of the dice, you are measuring luck as much as capability. Everything above is best-of-ten with a pass-rate next to it, because reachable and reliable are different questions and shipping code needs both. Two other gotchas bit me along the way: an instruction to “strip spaces from headers” made the model delete the space inside “payment type” and crash, and telling it to “never crash” made it wrap everything in a try/except that swallowed the real bug. I took both out so the wrapper says exactly what it means, identically for every rung.</p><h3>Where this is useful</h3><p>The scope is narrower than “small models can code,” and the narrowness is the point. This works when three things line up: you can write the logic down as explicit rules, you can build a test set that says what the right answer is, and you have a reason to keep the work off the cloud. Where those hold, the fit is good.</p><p>The domains that share the shape of what I tested:</p><ul><li>Pricing, rating, and billing. Insurance premium rating, utility and telecom billing, metered SaaS billing, discount and promotion logic, freight rate cards. Rule-dense, changed often, and usually written by business people rather than engineers.</li><li>Commission, payout, and revenue-share math. Sales commissions, affiliate and partner payouts, bonus schedules. The tiered, conditional part, which is the exact commission chain that was the hardest thing to get right here.</li><li>Eligibility and determination. Benefits eligibility, loan pre-qualification, underwriting checks, discount qualification. Decision-table logic with a definite right answer.</li><li>Tax, fee, and statutory calculations. Withholding, VAT and GST, tariffs and duties, payroll deductions. Deterministic, auditable, and unforgiving of “close.”</li><li>Data transformation and validation. Field mappings, normalization, reconciliation checks. This is the shape I ran: a CSV in, a computed column out.</li></ul><p>Two things make it hold up in production. First, the model is not in the loop at runtime. It writes the function once; after that you run plain Python over as many rows as you like, at normal code speed, for nothing per run, and the output is deterministic. There is no per-record inference, so there is no “it hallucinated on row four million.” Second, once the test set passes, the function is ordinary code you own and can read and diff like anything else.</p><p>There are also settings where running locally is the whole reason to bother, whatever the domain: regulated or air-gapped environments where the data legally cannot leave the building, in healthcare, finance, legal, defense, and government; and offline or edge work with no reliable connection.</p><p>The use case I find most interesting is organizational. The person who owns the pricing rules writes them in a structured spec, and the model turns them into tested code without a trip through an engineering backlog. The skill that matters becomes writing a clear spec and a real test set, which is where a lot of the value was hiding to begin with.</p><h3>What I take from it</h3><p>The headline is not “small models are good now” or “small models are bad.” It is that at this scale, the model was rarely the bottleneck. The specification was. That reframes the work in a way I find useful.</p><p>The recipe, cheapest first:</p><ol><li>Write the spec in the model’s dialect. Hand over the lookup tables verbatim, use bare decimals instead of percentages, and give every multi-step quantity its own named step. Do that and a 3B passes on the first try, on a laptop, for free.</li><li>Keep the business prose, but add a 7B and a white-box repair loop that regenerates from per-step feedback. Slower and heavier, but it converged every prose rung in a handful of iterations.</li><li>Sample a 7B and take the best of several runs. It gets there, unreliably.</li></ol><p>What did not work: handing the tables back in any form, since the knowledge was never missing; showing a small model its own code during repair; and expecting raw size to rescue a first-try failure.</p><p>A few things I am keeping:</p><ul><li>Close is the worst kind of wrong. For business logic, a number that is 2 to 5% off is more dangerous than one that is obviously broken, because it looks shippable and is wrong on every row. Score against ground truth to a tight tolerance or do not bother.</li><li>A small model transcribes far better than it reasons. So do the reasoning in the spec and let the model transcribe. The thing you control is the words it reads, not the weights it runs.</li><li>The work moves, it does not vanish. The effort shifts from writing the implementation to writing an unambiguous spec and a real test set, and those were always the hard parts. Think of the model as a fast junior developer who follows a precise ticket to the letter and never emails your data to anyone.</li></ul><p>For a whole class of well-specified, rule-based logic, think pricing, commissions, eligibility, fee schedules, that is a real capability, and it runs on hardware you already own with nothing leaving the machine. It will not invent an algorithm and it will not save you from a vague brief. But if you can write the ticket precisely, the small model on your laptop can write the code.</p><p>The full project is open source, every spec rung, the harness, the datasets, and both write-ups: <a href="https://github.com/IjunaidI/LocalCodingModelExp">github.com/IjunaidI/LocalCodingModelExp</a>. It builds on Muhammad Ansar’s <a href="https://www.linkedin.com/pulse/coding-small-language-models-hosted-your-local-ansar-bbbxf">original piece</a>, which is worth reading first.</p><p>If you have run a local coding model against real rule-based logic, I would like to know where your cliff was, and whether handing over the tables verbatim moves it for you the way it did for me.</p><p><em>#SmallLanguageModels #SLM #LocalLLM #OnDeviceAI #AIEngineering #Qwen</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5c0f4158c77" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>