<?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 Atif Sultan on Medium]]></title>
        <description><![CDATA[Stories by Atif Sultan on Medium]]></description>
        <link>https://medium.com/@sultanatif30?source=rss-60a3f3653de5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KMPcuyaYbdB4CEvL0UiusQ.jpeg</url>
            <title>Stories by Atif Sultan on Medium</title>
            <link>https://medium.com/@sultanatif30?source=rss-60a3f3653de5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:24:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sultanatif30/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[Entropy-Guided Self-Correction: A Lightweight Thinking Mode for Fine-Tuned Small Language Models]]></title>
            <link>https://medium.com/@sultanatif30/entropy-guided-self-correction-a-lightweight-thinking-mode-for-fine-tuned-small-language-models-e77dc2c390b2?source=rss-60a3f3653de5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e77dc2c390b2</guid>
            <category><![CDATA[small-language-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hallucinations]]></category>
            <category><![CDATA[julia-programming]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Atif Sultan]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 06:28:47 GMT</pubDate>
            <atom:updated>2026-08-07T07:18:46.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLM3xm9w9f1AZVovlHubTw.webp" /><figcaption>Credits: Tom Fish Burne <a href="https://marketoonist.com/">https://marketoonist.com/</a></figcaption></figure><p>I’m a writer. I use AI to brainstorm — not to write for me, but to think alongside me in my own voice. The problem is most AI models don’t sound like me. They sound like AI.</p><p>So I thought, what if I train an AI on my own writing, my own stories and teach it to talk like my characters, that way I can brainstorm ideas and what happens next without getting stuck in the doomed writer’s block.</p><p>So I collected all the relevant writing I had and fine tuned a Mistral 7B model. It worked great… Until it didn’t.</p><p>The conversation was good but every three or four exchanges it would hallucinate and I would have to regenerate a whole new response, this constantly burned time and of course my CPU resources since I was running everything on my Laptop.</p><p>I eventually gave up and took a break. That’s when I got curious, I dived deep into why language models hallucinate which led me to try and understand how language models work that in turn led me to Linear Algebra — specifically the series Essence of Linear Algebra by ThreeBlue1Brown. I watched a few videos and his visualizations really helped clear the foundations of the tools I would need.</p><p>The thing is, whenever a language model generates text it’s making probabilistic decisions at every step. When it’s confident those decisions are grounded in patterns it learned during training. When it isn’t — when the model drifts into unfamiliar territory — it starts guessing. That guessing is what we call hallucination.</p><p>The question I couldn’t stop thinking about: can the model detect its own uncertainty in real time? And if it can detect it, can it correct itself before the hallucination takes hold?</p><p>It turns out it can. Here’s how.</p><h3>Measuring Uncertainty with Shannon Entropy</h3><p>When a language model generates text it produces a probability score for every possible next token at each step. Shannon Entropy measures how spread out those probabilities are. Low entropy means the model is confident — probability is concentrated on one or two likely tokens. High entropy means it’s uncertain — probability is scattered across many possibilities. That scattered uncertainty is typically where hallucination begins.</p><p>The formula itself is straightforward:</p><p>H = -Σ p(x) log p(x)</p><p>For every possible next token, multiply its probability by the log of that probability, sum everything up and flip the sign. The result is a single number representing how uncertain the model is at that position. A low score means probability is concentrated — the model knows what comes next. A high score means probability is scattered across thousands of possibilities — the model is guessing.</p><p>In practice we set a threshold. In our implementation anything above 5.0 triggers the correction mechanism.</p><pre>function entropy(logits_row::Vector{Float32})<br>    probs = softmax(logits_row)<br>    return Float32(-sum(p * log(p + 1e-10) for p in probs))<br>end<br><br>const ENTROPY_THRESHOLD = 5.0<br><br>function is_uncertain(e::Real)<br>    return e &gt; ENTROPY_THRESHOLD<br>end</pre><p>Here’s the implementation in Julia (which is mainly what’s been used to create the engine)</p><p>But… detecting uncertainty is only half the problem. The real question is what to do when entropy spikes above the threshold.</p><p>This is where things get interesting. We have the model play charades with itself to get back to certain territory. Here’s how:</p><h3>Charades Method</h3><p>I call this the charades method because it really just follows the mechanism of a traditional charades game. Instead of letting the model blindly guess the next token, and producing gibberish like this:</p><pre>aries entered the room. One carried a litter.</pre><p>We embed certain tags in the dataset and say hey here are the relevant tags for most of the data defined in my dataset. Whenever you<strong> </strong>get into uncertain territory look up the tags which contain the coordinates you need to course correct. For now the tags are set manually per session — you define the context of your conversation upfront. Where tags are embedded directly into the training dataset so the model learns to recognize its own context automatically, is planned as a future improvement. But the method is the same for both ways.</p><p>Here’s how the structure for hints.json looks right now:</p><pre>{<br>    &quot;scenes&quot;: [<br>        {<br>            &quot;scene_id&quot;: &quot;dark_comedy_unlikely_bond&quot;,<br>            &quot;tags&quot;: [<br>                &quot;dark_comedy&quot;,<br>                &quot;satire&quot;,<br>                &quot;unlikely_bond&quot;<br>            ],<br>            &quot;coherence_anchors&quot;: [<br>                &quot;vulnerability hidden behind aggression or dark humor&quot;,<br>                &quot;threatening character deflects emotion through jokes they don&#39;t fully commit to&quot;,<br>                &quot;two broken things finding common ground without admitting it&quot;,<br>                &quot;moments of unexpected gentleness immediately undercut by something dark&quot;,<br>                &quot;self awareness about the absurdity of the situation&quot;<br>            ],<br>            &quot;elimination_criteria&quot;: [<br>                &quot;genuine unprovoked violence breaking an established bond&quot;,<br>                &quot;sentimental speech not undercut by humor&quot;,<br>                &quot;monster losing threatening edge entirely&quot;,<br>                &quot;modern slang in non-modern setting&quot;<br>            ]<br>        },<br>        {<br>            &quot;scene_id&quot;: &quot;atmospheric_horror_solo&quot;,<br>            &quot;tags&quot;: [<br>                &quot;psychological_horror&quot;,<br>                &quot;atmospheric_horror&quot;,<br>                &quot;solo_atmospheric&quot;<br>            ],<br>            &quot;coherence_anchors&quot;: [<br>                &quot;dread built through specific physical details not abstract description&quot;,<br>                &quot;character notices wrong small things before the big thing&quot;,<br>                &quot;silence and absence used as threat&quot;,<br>                &quot;body reacts before mind catches up&quot;,<br>                &quot;short sentences during peak tension&quot;<br>            ],<br>            &quot;elimination_criteria&quot;: [<br>                &quot;over explanation of the horror source&quot;,<br>                &quot;character monologues about their fear&quot;,<br>                &quot;comic relief breaking tension prematurely&quot;,<br>                &quot;generic phrases like a sense of dread filled the air&quot;,<br>                &quot;resolution that fully explains the mystery&quot;<br>            ]<br>        },<br>        {<br>            &quot;scene_id&quot;: &quot;epic_fantasy_confrontation&quot;,<br>            &quot;tags&quot;: [<br>                &quot;epic_fantasy&quot;,<br>                &quot;dark_fantasy&quot;,<br>                &quot;confrontation&quot;,<br>                &quot;antagonist_theatrical&quot;,<br>                &quot;villain_philosophical&quot;<br>            ],<br>            &quot;coherence_anchors&quot;: [<br>                &quot;villain savors the moment before acting&quot;,<br>                &quot;philosophical exchange before or during combat&quot;,<br>                &quot;power demonstrated through restraint not action&quot;,<br>                &quot;hero defiance through words when outmatched physically&quot;,<br>                &quot;stakes established through specific loss not generic threat&quot;<br>            ],<br>            &quot;elimination_criteria&quot;: [<br>                &quot;villain monologues their full plan unprompted&quot;,<br>                &quot;hero wins through sudden power spike&quot;,<br>                &quot;combat described without tactical detail&quot;,<br>                &quot;modern idioms in medieval setting&quot;,<br>                &quot;villain becomes cartoonish or loses menace&quot;<br>            ]<br>        },<br>        {<br>            &quot;scene_id&quot;: &quot;gruff_mentor_earned_respect&quot;,<br>            &quot;tags&quot;: [<br>                &quot;gruff_mentor&quot;,<br>                &quot;earned_respect&quot;,<br>                &quot;unlikely_bond&quot;,<br>                &quot;tough_love&quot;<br>            ],<br>            &quot;coherence_anchors&quot;: [<br>                &quot;respect shown through criticism that has raised standards&quot;,<br>                &quot;warmth expressed through practical action not words&quot;,<br>                &quot;mentor tests before trusting&quot;,<br>                &quot;student proves worth through competence not charm&quot;,<br>                &quot;banter that builds rather than tears down&quot;<br>            ],<br>            &quot;elimination_criteria&quot;: [<br>                &quot;mentor immediately opens up emotionally&quot;,<br>                &quot;student earns respect through speech alone&quot;,<br>                &quot;relationship jumps to warmth without friction&quot;,<br>                &quot;mentor becomes soft and encouraging without cause&quot;,<br>                &quot;conflict resolved through a single dramatic moment&quot;<br>            ]<br>        },<br>        {<br>            &quot;scene_id&quot;: &quot;tolerant_partnership&quot;,<br>            &quot;tags&quot;: [<br>                &quot;tolerant_partnership&quot;,<br>                &quot;unconventional_duo&quot;,<br>                &quot;tough_love&quot;<br>            ],<br>            &quot;coherence_anchors&quot;: [<br>                &quot;characters disagree but function anyway&quot;,<br>                &quot;care expressed through practical intervention not sentiment&quot;,<br>                &quot;one character&#39;s stubbornness acknowledged without being fixed&quot;,<br>                &quot;silence between them carries weight not awkwardness&quot;,<br>                &quot;neither character fully validates the other&quot;<br>            ],<br>            &quot;elimination_criteria&quot;: [<br>                &quot;sudden emotional breakthrough resolving core tension&quot;,<br>                &quot;one character abandons their defining trait to please the other&quot;,<br>                &quot;excessive verbal affirmation between characters&quot;,<br>                &quot;conflict that disappears without acknowledgment&quot;,<br>                &quot;pedestal syndrome - one character treating the other as infallible&quot;<br>            ]<br>        },<br>        {<br>            &quot;scene_id&quot;: &quot;unreliable_narrator_journal&quot;,<br>            &quot;tags&quot;: [<br>                &quot;unreliable_narrator&quot;,<br>                &quot;journal_entry&quot;,<br>                &quot;document_format&quot;,<br>                &quot;political_drama&quot;,<br>                &quot;guilt&quot;<br>            ],<br>            &quot;coherence_anchors&quot;: [<br>                &quot;writer records observations that contradict their stated worldview&quot;,<br>                &quot;justifications that reveal more than they conceal&quot;,<br>                &quot;clinical detachment from emotionally heavy content&quot;,<br>                &quot;to-do items and logistics appearing after morally heavy admissions&quot;,<br>                &quot;sentences trailing off or cutting out under emotional weight&quot;<br>            ],<br>            &quot;elimination_criteria&quot;: [<br>                &quot;writer explicitly acknowledges their own bias&quot;,<br>                &quot;emotional outpouring inconsistent with established voice&quot;,<br>                &quot;clean resolution or moral clarity&quot;,<br>                &quot;modern therapeutic language&quot;,<br>                &quot;fourth wall awareness of being read&quot;<br>            ]<br>        },<br>        {<br>            &quot;scene_id&quot;: &quot;mother_child_domestic&quot;,<br>            &quot;tags&quot;: [<br>                &quot;mother_child&quot;,<br>                &quot;protective_parent&quot;,<br>                &quot;slice_of_life&quot;,<br>                &quot;domestic&quot;<br>            ],<br>            &quot;coherence_anchors&quot;: [<br>                &quot;love shown through small rituals and routines&quot;,<br>                &quot;parent suppresses their own reaction to protect child&quot;,<br>                &quot;child&#39;s fear handled with practical redirection not dismissal&quot;,<br>                &quot;warmth expressed through specific actions not declarations&quot;,<br>                &quot;internal monologue reveals what the parent cannot say aloud&quot;<br>            ],<br>            &quot;elimination_criteria&quot;: [<br>                &quot;parent delivers a perfect speech that resolves the child&#39;s fear&quot;,<br>                &quot;sentimentality that stops the scene&#39;s momentum&quot;,<br>                &quot;child immediately accepts parental reassurance&quot;,<br>                &quot;domestic details that feel generic rather than specific&quot;,<br>                &quot;parent loses composure in front of the child without reason&quot;<br>            ]<br>        },<br>        {<br>            &quot;scene_id&quot;: &quot;post_apocalyptic_abandoned&quot;,<br>            &quot;tags&quot;: [<br>                &quot;dystopian_scifi&quot;,<br>                &quot;post_apocalyptic&quot;,<br>                &quot;abandoned_world&quot;,<br>                &quot;political_drama&quot;<br>            ],<br>            &quot;coherence_anchors&quot;: [<br>                &quot;world building through what is missing not what is present&quot;,<br>                &quot;characters treat extraordinary circumstances as mundane&quot;,<br>                &quot;political systems shown through individual consequence not exposition&quot;,<br>                &quot;technology or infrastructure described through its failure&quot;,<br>                &quot;hope expressed obliquely never directly stated&quot;<br>            ],<br>            &quot;elimination_criteria&quot;: [<br>                &quot;exposition dumps explaining how the world ended&quot;,<br>                &quot;characters expressing wonder at their own familiar world&quot;,<br>                &quot;villain embodying the system without human complexity&quot;,<br>                &quot;resolution that fully defeats the system&quot;,<br>                &quot;modern comfort items appearing without explanation&quot;<br>            ]<br>        },<br>        {<br>            &quot;scene_id&quot;: &quot;body_horror_corruption&quot;,<br>            &quot;tags&quot;: [<br>                &quot;body_horror&quot;,<br>                &quot;psychological_horror&quot;,<br>                &quot;unreliable_narrator&quot;,<br>                &quot;grief&quot;,<br>                &quot;guilt&quot;<br>            ],<br>            &quot;coherence_anchors&quot;: [<br>                &quot;corruption shown through specific physical detail not abstract dread&quot;,<br>                &quot;character rationalizes symptoms before acknowledging them&quot;,<br>                &quot;identity erosion shown through small behavioral shifts&quot;,<br>                &quot;moments of clarity surrounded by confusion&quot;,<br>                &quot;fear of self expressed through anger at others&quot;<br>            ],<br>            &quot;elimination_criteria&quot;: [<br>                &quot;character fully accepts their corruption without resistance&quot;,<br>                &quot;graphic description for shock value without character consequence&quot;,<br>                &quot;other characters immediately recognize and respond to the change&quot;,<br>                &quot;corruption reverses cleanly&quot;,<br>                &quot;protagonist narrates their own deterioration with full clarity&quot;<br>            ]<br>        },<br>        {<br>            &quot;scene_id&quot;: &quot;solo_atmospheric_observation&quot;,<br>            &quot;tags&quot;: [<br>                &quot;solo_atmospheric&quot;,<br>                &quot;quiet_vulnerability&quot;,<br>                &quot;internal_monologue&quot;<br>            ],<br>            &quot;coherence_anchors&quot;: [<br>                &quot;character revealed through what they notice not what they think&quot;,<br>                &quot;memory surfaces through sensory detail not explicit recall&quot;,<br>                &quot;emotional state expressed through physical observation&quot;,<br>                &quot;silence in the scene carries narrative weight&quot;,<br>                &quot;no dialogue needed to carry the scene&quot;<br>            ],<br>            &quot;elimination_criteria&quot;: [<br>                &quot;character explains their feelings directly to themselves&quot;,<br>                &quot;another character appearing to fill the silence&quot;,<br>                &quot;action interrupting before the quiet has settled&quot;,<br>                &quot;generic atmospheric description without character specificity&quot;,<br>                &quot;internal monologue that reads as therapy session&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>For a generic hints.json file you would replace the scene_id with context_id which could be the name of whatever exactly your context for which the data is tagged. Coherence anchors are short descriptions of patterns that belong in your context — they tell the model what good continuations look like that let the model judge how well its next token works in the context of its next generation. Finally, elimination criteria says: “Hey if your next token is going to go into any of these contexts don’t do that, your generation will be wrong.”</p><p>All of this is converted into vector embeddings at runtime we don’t use actual word matching to guide the model — remember language models process everything in vectors so we need to speak their language.</p><p>Here’s how the engine lets the model play Charades:</p><pre>function charades(model, prompt, logits_at_position,<br>                 active_tags, hints, embed_model, strategy=:any)<br><br>    relevant_hints = get_relevant_hints(hints, active_tags, strategy)<br>    top_ids = sortperm(logits_at_position, rev=true)[1:N_CANDIDATES]<br>    results = CandidateResult[]<br><br>    for id in top_ids<br>        result = evaluate_candidate(model, prompt, id, relevant_hints, embed_model)<br>        push!(results, result)<br>    end<br><br>    best = results[argmin([r.avg_entropy - r.coherence_score for r in results])]<br>    return best, best.entropy_trajectory, results<br>end</pre><p>The function takes the logits at the uncertain position, pulls the top N candidate tokens by probability, generates a short continuation for each and scores them on two criteria: average entropy of the continuation (lower is better — the model found confident ground) and coherence score against the hint embeddings (higher is better — the continuation matches known good patterns). The candidate with the best combined score wins.</p><p>The result looks something like this:</p><pre>Active tags: [&quot;dark_comedy&quot;, &quot;unlikely_bond&quot;]<br>Matching strategy: any<br>Matched 2 hint scenes<br>Continuation: &#39;aries entered the room. One carried a litter.&#39;<br>&#39; function&#39; → avg_entropy: 2.52 | coherence: -0.011<br>  Continuation: &#39; they entered the room. The air inside was hot&#39;<br> &#39;e&#39; → avg_entropy: 2.45 | coherence: 0.033<br>  Continuation: &#39;ing and the stranger walked towards the dimly lit&#39;<br>  &#39;Field&#39; → avg_entropy: 2.93 | coherence: 0.008<br><br>   Winner: &#39;e&#39;<br>   avg_entropy: 2.45<br>   coherence_score: 0.033<br>   Charades eval:    65.31s</pre><p>The generation for this specific prompt is like this:</p><p>Prompt: “The door opened slowly. Neither of them spoke as”</p><p>Generation: “they entered the room. The air inside was hot”</p><p>See how much it’s already better than: “aries entered the room. One carried a litter.” It actually makes sense and provides an atmospheric description for our vague prompt.</p><h3>Profiling the decision</h3><p>Detecting uncertainty and making a correction is one thing. Knowing whether the correction was actually good is another. This is where the profiler comes in.</p><p>After charades picks a winner we measure the entropy slope of the continuation that follows. A negative slope means entropy dropped after the decision — the model found its footing and stayed there. A positive slope means entropy kept rising — the correction didn’t help.</p><p>Here’s what our first test produced:</p><pre>Total decisions: 1<br>Good decisions:  1<br>Accuracy:        100.0%<br><br>Context: &#39; The&#39; → &#39;e&#39;<br>slope=-0.4345 | entropy=2.45 | coherence=0.033</pre><p>slope=-0.4345 confirms the model steered itself back to confident territory after the correction. The negative slope is exactly what we want to see.</p><p>and here’s what it looks like as a chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*wPPur9wjsFlwyYiegPmO9g.png" /></figure><p>This confirms that our system worked for our intended usecase.</p><h3>Wrap up and what’s next</h3><p>After all this, we end up with an Entropy guided self correction system for fine tuned models which is basically a lightweight thinking mode for SLMs.</p><p>The foundation is built but the system is far from perfect. There are optimizations to be done, experimentation with more layers in hints.json along with tests on tags baked into the dataset itself.</p><p>The goal of this system is to provide a more robust and attachable way for data sensitive organizations and those running their own models or model running on edge servers to reduce hallucinations without writing and wiring custom code for everything that could<strong> </strong>go wrong, the engine handles everything else while the people can focus on the data and implementations.</p><p>With all that said, hope you found this article insightful.</p><p>The full implementation including all Julia files, hints.json are available at: <a href="https://github.com/sultanatif344/Charades-Engine">https://github.com/sultanatif344/Charades-Engine</a></p><p>Next I’ll share how well the optimizations go and the plan is to do more business centric use cases that drift away from creative writing.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e77dc2c390b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>