[{"content":"I pretrained TinyGPT on tiny-shakespeare, fine-tuned it to say one sentence and stop, then used DPO to prefer a fuller line. TinyGPT has 12 layers, 8 heads, 128-dimensional embeddings, the GPT-2 byte-pair vocabulary, and about 15 million parameters. The pretrained checkpoint is out_bpe\/tinygpt_shakespeare.pt. DPO at the fine-tuning learning rate raised the metrics and broke the generated text. The run kept here cuts that rate by ten. Every comparison uses ROMEO:, MENENIUS:, JULIET:, and KING RICHARD III:.\nThe run Pretrain the next token, fine-tune to one sentence and a stop, then use DPO to prefer one reply.\nflowchart LR pre[\"Pretrain\\nnext token\"] sft[\"Fine-tune\\none sentence, then stop\"] dpo[\"DPO\\nprefer one reply\"] pre --> sft --> dpo Pretraining Pretraining predicts the next byte-pair token. For a window $x_1, \\ldots, x_T$, the loss is the average cross-entropy of the next token:\n$$ \\mathcal{L}_{\\mathrm{pretrain}} = -\\frac{1}{T}\\sum_{t=1}^{T} \\log p_\\theta(x_{t+1} \\mid x_{\\le t}) $$\nTiny-shakespeare is one long file. It has no document boundary, so the end-of-text token is never a target, and that row of the embedding stays random. A loss in subword units is a different number from a character-level loss on the same file. It also says nothing about whether a line is finished.\nTwo thousand steps, batch size 8, learning rate 3e-4. Training loss fell from 10.83 to 3.84. Validation loss fell from 10.82 to 4.78. Validation perplexity ended near 120. The curves separate after a few hundred steps.\nThe W&amp;B run is tinygpt-bpe-v1.\nAsked for Romeo, it holds the shape for a clause and then walks into other characters:\nROMEO: And I will not a man. LADYea, I do you. ROMEO: I'll not my lord. WARWICK: Why woe no more than thou wast thou art\nThe word is a prince,\nI'll find your grace, my lord; and let him. Second Senator: Rome are it; Pretraining got us a model of the file. A clause can sound right, and then the next tokens are whoever speaks next, because that is what the file does. More steps on the same file would only make that continuation smoother. The next step is fine-tuning: take a speaker, say one sentence, and stop.\nThe training script is train.py, run with gpt_small_bpe.yaml.\nFine-tuning I wanted a new behavior: given a speaker, say one sentence and stop. The raw play treats that stop as a mistake, because the likely next tokens are the rest of the scene. Training on the raw file again would have practiced the drift.\nSpeaker, then one sentence Blank lines separate speeches. A prompt is the first line of a speech. The target is the first sentence after it, with the end-of-text token appended. Pretraining never asked for that token, and sampling needs a stop.\nRule Prompt ends in :, at most 30 characters, no ., ?, or ! before the colon Target the speech joined across wraps, then the first sentence of 8 to 150 characters ending in ., ?, or ! Second Citizen Prompt Second Citizen: Target What he cannot help in his nature, you account a vice in him. Left out You must in no way say he is covetous. The break after &ldquo;account a&rdquo; is the line wrap. The cut is the period. &ldquo;Cousin, farewell:&rdquo; ends in a colon and is still dialogue, so it is not a prompt.\nThat filter made 6,344 pairs. Shuffled with seed 1337, 5,710 went to training and 634 to eval. The filter is sft_data.py. The pairs are in sft.csv.\nTraining The loss is the same cross-entropy, on fewer positions. Prompt tokens are labeled -100 and drop out. The reply, including the end-of-text token, stays in. The mean is over those tokens, so a longer line counts more than a short one:\n$$ \\mathcal{L}_{\\mathrm{SFT}} = -\\frac{1}{|y|}\\sum_{t=1}^{|y|} \\log p_\\theta(y_t \\mid \\text{speaker},, y_{&lt;t}) $$\nTraining was 3 epochs, 1,000 steps, batch size 16, learning rate 5e-5, about 83 seconds. The script is train_sft.py with sft_bpe.yaml. The W&amp;B run for these 1,000 steps is tinygpt-bpe-sft-v1.\nResults Validation loss falls from 4.91 at step 100 to 4.35 at step 1,000, then flattens. The train line is a single batch at each logged step, so it jumps around. The same prompts stopped:\nPrompt After supervised fine-tuning ROMEO: I will not be gone, and see the king. MENENIUS: You hear us! JULIET: What, that knows not to do not to me? KING RICHARD III: O, I never swear, to give me here. Each line ends on the end-of-text token. None of them brings in a second speaker. Juliet&rsquo;s line is still loose. Fine-tuning changed when the model stops, and which speaker it stays on. The lines themselves were still uneven.\nDPO Fine-tuning had used up the signal in a single correct sentence. The model stopped, and it stayed on the speaker it was given. What still varied was the line itself. King Richard&rsquo;s was tighter than Juliet&rsquo;s. The next loss had to prefer one reply over another.\nWhy DPO over PPO PPO trains a reward model first and then holds it fixed. Every step draws new lines from the model being trained, and the reward model scores them. DPO compares a chosen line and a rejected line that are already in a file. The model writes no new lines while it trains.\nThese runs were on a MacBook Pro M4 with 24GB of memory. The logits are batch by time by 50,257, and pretraining at batch 64 had already filled that machine. PPO would have added a sampling pass and a reward-model pass on every step. DPO writes the pairs once, Haiku supplying some of the chosen lines, then does one forward pass on each line under the training model and under a frozen copy of the fine-tuned model. After that file exists, training is local and the same run fits a local GPU.\nWhich line is better The fine-tuning file has one sentence per row. DPO needs two replies to the same prompt, and a label for which one is better, so I had to build a new file.\nThe model already stopped, and it already stayed on the speaker it was given. King Richard&rsquo;s line was tighter than Juliet&rsquo;s. The pairs had to capture that leftover difference.\nThe prompts are the 287 speaker tags from the fine-tuning training split. That list stays fixed. The pair count changes because of what gets multiplied.\nflowchart LR tags[\"287 speaker tags\"] draw[\"6 lines from the fine-tuned model\\ntemperature 0.9, top-k 40\"] score[\"preference reward\\nform, register, words\"] pick[\"highest vs lowest\\ndrop ties\"] few[\"168 training pairs\"] write[\"Haiku writes 3 lines\\n861 chosen lines\"] cross[\"each chosen line\\n\u00d7 3 model lines\"] many[\"2,325 training pairs\"] tags --> draw --> score --> pick --> few tags --> write --> cross --> many Preference reward, both lines from the fine-tuned model A yes-or-no check tied 284 of the 287 prompts. The preference reward of a line $y$ scores each slip instead. A small miss costs less than a broken line. It only labels the file. The training step does not call it.\n$$ r(y) = \\mathrm{form}(y) + \\mathrm{register}(y) + \\mathrm{words}(y) $$\nPart When Score form stops on the end-of-text token +1 form misses that token \u22122 form the line is empty \u22125 more form ends in ., ?, or ! +0.5 form misses that mark \u22121 form fewer than two words \u22122 form each word past twenty \u22120.15 form each repeated pair or triple, as in &ldquo;my lord, my lord&rdquo; \u22120.5 form commas and semicolons are more than 30% of the words \u22121 register one hit from thee, thou, thy, thine, hath, doth, dost, prithee, wherefore, whilst, naught 1, else 0 words share of the words already in tiny-shakespeare 0 to 1 It is the king. stops and ends in a period, so form is 1.5, register is 0, and words is 1: $r = 2.5$. I have not not not to thy knee. is form 1.0, register 1, words 1: $r = 3.0$. The worse line wins, and both lines came from the fine-tuned model. Six draws per tag gave 186 pairs, then 168 for training.\nChosen line from Haiku The chosen line in the scored file could be no better than the fine-tuned model&rsquo;s own best draw, and the reward had just ranked a worse draw higher. I needed the preferred line written by something else, and kept short, because this model will not go from You hear us! to a full speech in a few hundred steps. Haiku wrote that side once, and the file stayed fixed. Haiku is the teacher and the fine-tuned model is the student. I had the teacher&rsquo;s text, so the teacher&rsquo;s line is $y_w$ and a line from the student is $y_l$. The student is trained to prefer the teacher&rsquo;s line.\nHaiku writes three chosen lines for each of the 287 tags. A line is 5 to 15 words and ends in ., ?, or !. Each of those lines is paired with three samples from the fine-tuned model. That is $287 \\times 3 = 861$ chosen lines and $861 \\times 3 = 2{,}583$ pairs, of which 2,325 are for training. The 861 lines cost $0.16. One pair:\nBoatswain Chosen, $y_w$ The storm doth rage with fury against our poor vessel&rsquo;s hull! Rejected, $y_l$ I must not well. The 186 scored pairs are in dpo_data.py and dpo_scored.csv. The 861 Haiku lines are in haiku_lines.csv. The 2,583 pairs are in dpo_gold_data.py and dpo_haiku.csv.\nTraining DPO compares the chosen reply with the rejected reply, under the model being trained and under a frozen copy of the fine-tuned model:\n$$ \\mathcal{L}_{\\mathrm{DPO}} = -\\log \\sigma \\left(\\beta \\left[ \\log \\frac{\\pi_\\theta(y_w \\mid x)}{\\pi_{\\mathrm{ref}}(y_w \\mid x)} - \\log \\frac{\\pi_\\theta(y_l \\mid x)}{\\pi_{\\mathrm{ref}}(y_l \\mid x)} \\right] \\right) $$\nEach $\\log \\pi(y \\mid x)$ is the sum of token log-probabilities over the reply. Pretraining and fine-tuning averaged. This sum is a larger step at the same learning rate. While the training model still matches the frozen copy, the loss is $\\ln 2 \\approx 0.693$.\nThree earlier runs kept the fine-tuning learning rate, 5e-5. The eval numbers rose and the lines broke. Those runs are in the appendix.\nThe run I kept uses the Haiku pairs, beta 0.1, and learning rate 5e-6. Training is train_dpo.py, with dpo_bpe_gold_lowlr.yaml. The W&amp;B run is tinygpt-bpe-dpo-gold-lowlr-v1.\nResults Eval accuracy stayed at 0.955. Eval loss ended at 0.136. The reward margin climbed to 3.33 and stayed there. The train line is a single batch at each logged step, so it jumps around.\nPrompt Fine-tuned DPO, learning rate 5e-6 ROMEO: I will not be gone, and see the king. I dare assure thee for time that Montague and victory! MENENIUS: You hear us! I warrant you take good sir, take my father withal. JULIET: What, that knows not to do not to me? The moon of Edward&rsquo;s queen&rsquo;s blood of their blood, and Margaret was patient: For triumph is England hast made their heads and slaughter&rsquo;d me down the Tower. KING RICHARD III: O, I never swear, to give me here. But Richard Stanley shall make that Warwick from my heart the world thy words in mine eyes dost Plantagenet is brief. Romeo names Montague. Juliet names Edward, Margaret, and the Tower. King Richard names Stanley, Warwick, and Plantagenet. His line still runs on, and some other samples still glue a contraction (amll'd, Iiolanus). This is the first checkpoint that is clearly ahead of the fine-tuned model. It is out_dpo_gold_bpe_lowlr\/tinygpt_dpo.pt.\nWhat changed Pretraining gave the model the Shakespeare sound and the speaker format, and the turn ran on. Fine-tuning made the turn stop. DPO, once the step size matched a summed loss, preferred a fuller line inside that turn.\nEach stage needed data the previous one lacked. The play continues, so a stop had to be cut out as speaker, one sentence, and an end-of-text token. Those sentences are single answers, so DPO needed two answers and a reason to prefer one. Ranking the model&rsquo;s own lines failed once the winner was still a bad line. Haiku wrote the chosen side, in the same short shape.\nI would not trust preference accuracy on its own again. On the two broken runs it said the model was learning. The four prompts said otherwise.\nAppendix The other DPO runs Three earlier runs kept the fine-tuning learning rate, 5e-5. The eval numbers moved the right way. The lines did not.\nRun Pairs Beta Learning rate Eval loss Margin Accuracy Romeo Scored pairs 168 0.1 5e-5 0.395 1.02 0.833 And he that I will not so, that is a bloody day. Haiku pairs 2,325 0.1 5e-5 0.015 8.80 0.996 I&rsquo;ll imitate yawn castlesel you watch my rage here beheld my son is Haiku, lower beta 2,325 0.02 5e-5 0.082 5.18 0.977 Announce kingrophe me The configs are dpo_bpe.yaml, dpo_bpe_gold.yaml, and dpo_bpe_gold_lowbeta.yaml.\nPreference accuracy asks whether the chosen line outranks the rejected one when the true prefix is filled in. It reached 0.996 on a model whose samples were broken tokens. The free samples were what separated these runs from the one I kept.\nOther checks A few checks that failed once.\nNext-token shift. The target is the next token. input_ids drops the last token and labels drops the first, the same shift as pretraining. Prompt positions in labels are -100, except the last prompt position, which predicts the first reply token. An earlier fine-tuning run had this shift backwards, so the loss predicted the current token. That run collapsed into him him him and ROMEO:::::. End of text. Pretraining never uses the end-of-text token, so it is appended to the fine-tuning reply. Speaker tags. A raw line is a wrap, so the speech is rejoined and then cut at the first sentence. A colon is a speaker tag only when the line is short and has no sentence punctuation before it. A scan for colons returned about 2,500 tags, mostly dialogue. Tied scores. A tied pair is dropped. A score that only checks stopping tied 284 of 287 prompts after fine-tuning had taught stopping. Where the parameters sit. Most of the 15 million parameters are the vocabulary. The token embedding and the output projection are each 50,257 by 128. The logits are batch by time by vocabulary, and batch 64 with that vocabulary thrashed the machine. Batch 8 fit. Removing layers would leave that tensor the same size. A character model, 4 layers and about 843,000 parameters, did train. Its samples were letter salad, so later stages had nothing readable to judge. References post-training-roadmap. The code, the configs, and the four CSV tables. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. Language Models are Unsupervised Multitask Learners, 2019. The GPT-2 byte-pair vocabulary. Long Ouyang, Jeffrey Wu, Xu Jiang, Diogo Almeida, Carroll Wainwright, and others. Training language models to follow instructions with human feedback, 2022. A separate reward model, then PPO. John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, and Oleg Klimov. Proximal Policy Optimization Algorithms, 2017. The PPO update. Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, and Chelsea Finn. Direct Preference Optimization: Your Language Model is Secretly a Reward Model, 2023. A loss on a fixed preference file. ","permalink":"https:\/\/rajathpatel23.github.io\/posts\/tiny-shakespeare-sft-dpo\/","summary":"<p>I pretrained TinyGPT on tiny-shakespeare, fine-tuned it to say one sentence and stop, then used DPO to prefer a fuller line. TinyGPT has 12 layers, 8 heads, 128-dimensional embeddings, the GPT-2 byte-pair vocabulary, and about 15 million parameters. The pretrained checkpoint is <code>out_bpe\/tinygpt_shakespeare.pt<\/code>. DPO at the fine-tuning learning rate raised the metrics and broke the generated text. The run kept here cuts that rate by ten. Every comparison uses <code>ROMEO:<\/code>, <code>MENENIUS:<\/code>, <code>JULIET:<\/code>, and <code>KING RICHARD III:<\/code>.<\/p>","title":"Pretrain, SFT, then the DPO run that held"},{"content":"When you build an agent, you&rsquo;re not building one system. You&rsquo;re building several small ML problems composed together, each one making a quality judgment, each one capable of failing silently.\nI learned this while building a deep research agent. At a high level, the system takes a question, breaks it into smaller research questions, searches for sources, extracts claims, and keeps a structured record of what it has found. A planner reads that record after every search and decides whether to investigate a new question, challenge an existing claim, or stop.\nI initially focused on that planner as the intelligence of the agent. What I didn&rsquo;t anticipate was how much of its behavior had already been decided by the components beneath it. The planner only sees the queries that were generated, the sources that survived retrieval, the claims that were extracted, and the signal describing whether the last step was useful.\nThis post is about how I started identifying those sub-problems, giving each one a signal, and deciding where to spend the system&rsquo;s budget. Each component has its own version of the exploitation vs exploration tradeoff, but the settings have to work together. I&rsquo;ll use the research agent as the running example (post 1), but the framework applies to any agent you&rsquo;re building.\nWhere you spend your tokens is a decision Before getting into the sub-problems, there&rsquo;s a framing that makes everything else click.\nAny agent worth running in production needs to work within a finite budget. Tokens per call, API calls per run, search steps per session all have real costs. How you allocate across them is the same problem as one of the oldest challenges in reinforcement learning: exploitation vs exploration.\nExploit means spending your budget on what you already know works: query formulations that return good sources, domains that produce extractable claims, sub-questions that have already yielded evidence. Explore means spending it on uncertain paths: a new query angle, a source domain you haven&rsquo;t tried, a sub-question that&rsquo;s been silent so far.\nEvery component in your agent has this tension. The question isn&rsquo;t &ldquo;should I exploit or explore?&rdquo; It&rsquo;s: what&rsquo;s the right dial setting for this component, at this stage of the run?\nThis is the same mindset you bring to any ML system. You don&rsquo;t configure it once and ship. You instrument, measure, and revise as the system evolves. The exploit\/explore settings at each component are no different from any other parameter you&rsquo;d tune: initialize, run, understand the performance, adjust.\nAgents are compositions of ML sub-problems In the research agent I built, five sub-problems emerged clearly: how to formulate the search query, which sources to retrieve, how to rerank them, how to classify what came back, and what to prune or stop pursuing.\nComposition of a deep research agent: five sub-problems, each with its own failure mode, each needing its own signal.\nI&rsquo;ll go through three of them in depth. The pattern is the same for each: identify what the component decides, define what good looks like, give it its own signal, and treat it as its own experiment. Reranking and pruning follow the same structure.\n1. Search: query quality The first decision is how to translate a research question into something a search engine can answer. A research goal and a search query are not the same thing. Bridging that gap is the actual problem.\nA sub-question like When does chain-of-thought prompting fail to improve LLM performance or show minimal benefit? passed directly to a search API returns overview articles about chain-of-thought prompting. That&rsquo;s not what you asked. The query needs to be reformulated: shorter, keyword-dense, targeted at the specific claim type you&rsquo;re looking for.\nWhen I added query rewriting, each sub-question produced two or three retrieval-optimized variants before searching. The agent could now try different formulations instead of assuming the first one was correct. Not because the available knowledge changed. Because the agent had more than one way to ask for it.\nQuery formulation is where the exploit\/explore tradeoff became most visible to me. If a query returns nothing useful, there are two possibilities: the evidence is not available, or the system is asking the wrong way. Retrying the same formulation tells me very little. Trying a different formulation tests whether the failure came from the question or from the available sources.\nI implemented that as a recovery ladder: empirical and benchmark terms first, then ablation and comparator language, then paper-oriented terms, and finally targeted site:arxiv.org or site:openreview.net queries. The specific levels depend on the domain. A coding agent might escalate from function-name queries to library documentation to GitHub issue search; the structure is the same either way: ordered escalation with logged outcomes. It is hand-written today, but every attempt logs what was tried and what happened.\nThe signal at this layer: did the query produce new evidence, repeat what I already had, or produce nothing useful? Logging that outcome for every formulation creates the beginning of a dataset for improving query generation.\n\u2192 retriever.py: query preparation, domain routing, research_mode flag\n2. Retrieval: source quality Once the query is sent, the next decision is which returned sources deserve more compute. The agent cannot read everything. Every source passed forward consumes extraction tokens, conflict checks, and storage.\nNot every result that matches a query is useful. Without source filtering, retrieval returns whatever matches the keywords. Some of those have zero extractable claims. That can look like a query problem: the agent searched and produced nothing. But the query may be fine. The source selection is the issue. That distinction changes what you fix.\nThe exploit\/explore tradeoff here is about source scope. Exploit means restricting to sources you know produce high-quality, extractable content: academic databases and lab pages in a research agent, official docs and trusted repos in a coding agent. Explore means opening to a wider pool, trading precision for recall. The right setting depends on what the sub-question is asking for: if you need verified, structured evidence, restrict hard; if you&rsquo;re looking for real-world failures or practitioner experience, open up; that content rarely makes it into curated sources.\nMaking retrieval stricter can make the complete system worse. Tighter filtering improved precision in my build but created dead zones on hard sub-questions: the system retrieved and extracted, then rejected everything as insufficient. Retrieval cannot be optimized in isolation. Its setting affects extraction yield, coverage, planner behavior, and when the agent stops.\n\u2192 retriever.py#L126: research_mode flag: switches between include_domains (exploit) and exclude_domains (explore)\n3. Step classification: did the search actually help? After every search, the classifier compares the evidence state before and after and assigns one of four labels: new evidence, conflict found, repeated evidence, or no progress. No LLM in the loop, just state diffs.\nBut a classifier that only measures state changes can miss why the step mattered. A search explicitly looking for counter-evidence might return one contradicting claim and still get marked as no progress under a count-based signal. The classifier understands what changed, not what the search was trying to accomplish.\nSignal quality sets the ceiling on planner behavior. A coarse signal produces a coarse planner; a precise signal misaligned with the research goal produces confident wrong decisions. The rule-based version I built is a starting point. A learned classifier could judge the full transition: what the agent knew, what it tried, what came back, and whether that moved the research forward. The harder problem is not training it. It is defining what &ldquo;useful&rdquo; should mean.\nOptimize one at a time During the build, I was changing query formulation, domain filtering, extraction prompts, and planner behavior at the same time. The output would improve, but I couldn&rsquo;t say which change caused it. I had a better run, not a better understanding of the system.\nThe same problem showed up in ablation. The baseline cycled through sub-questions in a fixed order; the guided version used evidence to decide what to search next. But search API results aren&rsquo;t deterministic: both versions were reading different documents even from the same query. When guided outperformed baseline, I couldn&rsquo;t tell whether the planner was better or the sources were. The fix: decompose once, fetch once, pass the same documents to both modes. That made the planning policy the only variable under test.\nThe larger lesson: treat each sub-problem like its own experiment. Hold the surrounding system fixed, define the signal for that component, change one thing, and inspect what moved. Then put it back into the complete system and check whether the end-to-end result improved.\nMy working principle became: fix the signal, optimize the component, then evaluate the composition.\nWithout that separation, I could make the agent better without understanding why, and the next change could easily remove the gain.\nThe exploitation\/exploration dial is per sub-problem Exploit\/explore isn&rsquo;t a planner-level choice. It&rsquo;s happening inside every component simultaneously: the query rewriter choosing between a known formulation and a new one, retrieval choosing between trusted domains and a wider pool, the planner choosing between deepening one thread and moving on.\nThe coordination challenge is that each layer sees different state. The planner tracks what&rsquo;s still unanswered. The query and retrieval layers track what&rsquo;s been tried and what came back. Without a connection between them, the planner can keep allocating budget to a sub-question the lower layers have already exhausted, not because the decision is wrong, but because the planner doesn&rsquo;t have visibility into what&rsquo;s been attempted below.\nThe fix is to surface component-level signal upward: how many times has this sub-question been tried, what strategies were attempted, did any yield anything? With that, the planner can distinguish &ldquo;unanswered&rdquo; from &ldquo;unanswerable with the current approach&rdquo; and either change the query strategy or move on. That distinction is what makes the budget go further.\nEach component needs its own exploit\/explore setting, but none can be optimized in isolation. The settings don&rsquo;t just affect quality; they determine where the budget goes. Better planning exposes weaker retrieval. Earlier stopping leaves the writer with thinner evidence. A local improvement only counts when the complete system produces a better result.\nWhere this goes Once the component-level signals are reliable, the run traces become potential training data. But the more immediate value is diagnostic clarity: when something breaks, you know which component failed and why. That&rsquo;s what separates a system you can improve from one you can only restart.\nThe agent that looks like one system is actually several. Build accordingly.\nResources\nCode: deep-research-agent Slides: Small ML Sub-Problems Inside Agents ","permalink":"https:\/\/rajathpatel23.github.io\/posts\/small-ml-subproblems-inside-agents\/","summary":"<p>When you build an agent, you&rsquo;re not building one system. You&rsquo;re building several small ML problems composed together, each one making a quality judgment, each one capable of failing silently.<\/p>\n<p>I learned this while building a deep research agent. At a high level, the system takes a question, breaks it into smaller research questions, searches for sources, extracts claims, and keeps a structured record of what it has found. A planner reads that record after every search and decides whether to investigate a new question, challenge an existing claim, or stop.<\/p>","title":"Small ML Sub-Problems Inside Agents"},{"content":"Deep research agents have gotten significantly better. Tools like Perplexity, OpenAI Deep Research, and Gemini can search, synthesize, and return structured answers across dozens of sources. The quality of the output has improved fast.\nWhat these tools don&rsquo;t make visible is the process. When they stop searching, you don&rsquo;t know if the work is done or the budget ran out. When two sources conflict, you don&rsquo;t know if that got noticed or smoothed over. The output looks the same either way.\nThe core idea was to build a research agent where those questions have explicit answers, not by retraining a model, but by designing the right structure around it: an explicit evidence state, step-level reward signals, and a planner that uses those signals to decide what to do next. This is what I built, how I designed it, and what it taught me.\nThe design challenge: measuring research quality without retraining Most research pipelines evaluate quality at the end: how good does the final report look? That&rsquo;s a reasonable starting point, but it leaves a lot invisible. You can&rsquo;t tell from the report alone whether the search was principled, whether the agent explored the right sub-questions, or whether it stopped because the work was done or because it hit a time limit.\nThe challenge I wanted to tackle: how do you build visibility into the research process itself without retraining the underlying model?\nThe field has a well-developed answer to this for chain-of-thought reasoning: Process Reward Models: models that score the quality of each intermediate reasoning step rather than just the final output. Each step either advances the goal or it doesn&rsquo;t.\nThe question I started with: what does a step-level reward signal look like for a research agent?\nThe approach I took: evidence state improvement is the reward. The evidence state is a structured record of what the system has found, confirmed, disputed, and still needs to explore. Improving it means adding a new claim from a new source, surfacing a contradiction, covering an unexplored sub-question. If a step doesn&rsquo;t change the evidence state, it contributed nothing, regardless of how good the retrieved text looks.\nThe architecture The high-level flow:\nQuery -&gt; Decomposer -&gt; Planner (baseline or guided) -&gt; Retriever (search + rerank + domain filtering) -&gt; Claim Extractor (+ claim filter) -&gt; Conflict Engine -&gt; Evidence Store update -&gt; Evaluator (step signal) -&gt; Stop criteria check -&gt; Report + Traces (run_trace captures the full step sequence for analysis) The architecture is a single research loop: one evidence state that every component reads from and writes to. The planner decides what to search next, the retrieval pipeline extracts and filters claims, and the evidence store tracks what&rsquo;s confirmed, what&rsquo;s disputed, and what&rsquo;s still missing. The report is generated from whatever is in that record at the end.\nDecomposition: supporting and adversarial sub-questions The first thing the system does is decompose the query into sub-questions. But not just supporting ones: it generates adversarial sub-questions too.\nSupporting sub-questions search for evidence in favor of a claim. Adversarial sub-questions explicitly search for counter-evidence, edge cases, and reasons a claim might not hold. This matters because most research agents stop when they find a confident answer. This one is designed to keep looking for reasons to doubt it.\nBoth types feed into the same evidence store. The planner tracks which sub-questions have been covered and which haven&rsquo;t, and uses that coverage state to decide what to search next.\nThe retrieval pipeline Each search action runs through a multi-stage retrieval pipeline before anything reaches the evidence store: Query rewriting: the original sub-question gets rewritten into multiple variants to improve recall across different phrasings and keyword choices.\nRetrieval: each variant gets sent to the search API. Results are pooled and deduplicated.\nReranking: retrieved documents are reranked by relevance to the original sub-question, not just the rewritten variant.\nClaim extraction: an LLM extracts discrete claims from the top-ranked documents. Claims are atomic statements that can be evaluated individually, not paragraphs, not summaries.\nClaim filtering: extracted claims are classified as direct (updates the main belief state), adjacent (related but not core), or irrelevant. Only direct claims update the evidence state.\nConflict detection: new claims are compared against existing claim groups. When a new claim contradicts an existing high-confidence claim group (a cluster of related claims about the same assertion) both get marked as disputed. The system doesn&rsquo;t resolve the conflict: it surfaces it.\nThis pipeline runs inside every search step. The evidence store update only happens at the end of the full pipeline, once claims have been extracted, filtered, and checked for conflicts.\nAt the end of the research loop, the synthesizer reads from the evidence store directly to generate the final report: surfacing supported claims, flagging disputes, and disclosing gaps.\nThe evaluator: classifying each step After every step, an evaluator classifies what happened to the evidence state:\nSignal What it means NEW_EVIDENCE New claim from a new source on an uncovered sub-question CONFLICT_FOUND Surfaces a real contradiction in existing evidence REDUNDANT Confirms existing evidence, nothing new DEAD_END No extractable claims NO_RETRIEVAL_RESULTS Search returned nothing The evaluator is deterministic: it checks observable conditions without an LLM call. Did new claims appear? Did a new source domain get added? Did a claim group flip to disputed?\nThis is a proxy for a trained process reward model. A trained PRM (Lightman et al., 2023) would score the full evidence state transition end-to-end. This one checks surface signals. But the signal structure is right, and that&rsquo;s what matters for the planner to work.\nCONFLICT_FOUND is treated as more valuable than REDUNDANT for a deliberate reason: surfacing a contradiction advances the evidence state more than confirming what you already know. Most research agents collapse conflicting evidence into a synthesis. This system marks it explicitly and discloses it in the report.\nThe guided planner The planner reads evaluator signals and makes one of three decisions each step: search a new sub-question, issue a challenge (a targeted query designed to find contradicting evidence for a high-confidence claim), or stop.\nBaseline mode cycles through sub-questions in fixed order and stops only when the step budget runs out. Guided mode reads the evidence state at every step: prioritizing uncovered angles, challenging high-confidence claims, and stopping when evidence is genuinely exhausted.\nIn guided mode, the planner follows three priorities:\n1. Cover uncovered sub-questions first. Always explore unseen territory before reinvestigating what you already know. The planner maintains a priority queue over sub-questions weighted by coverage status and evidence density: how many claims have already been collected for that sub-question.\n2. Challenge high-confidence claims. When a claim group reaches high confidence, the planner issues a Challenge Action: it builds a query specifically designed to find contradicting evidence. This is the adversarial behavior made operational.\n3. Stop on diminishing returns. When the last 3 consecutive steps are all REDUNDANT or DEAD_END and all sub-questions have at least one evidence-backed claim, stop. This is principled stopping: the system stops because the research is done, not because the budget ran out.\n4. Adapt to signals at every step. Baseline treats evaluator signals as noise: it cycles sub-questions in fixed order regardless of what the evaluator returns. Guided uses each signal as a decision input: DEAD_END escalates the query before moving on, REDUNDANT surfaces an uncovered sub-question, NEW_EVIDENCE on a high-confidence group may trigger a challenge. Failures get handled early; budget goes toward sub-questions that still have open territory.\nWhat the ablation showed I ran two ablation pairs (same query, same model, baseline versus guided) and measured what changed. Two queries is a small sample and the metrics are self-defined proxies, not external ground truth. But the pattern is consistent across both runs, and the stopping behavior difference is visible in the step traces, not just the numbers.\nRun 1 (chain-of-thought prompting):\nQuery: &ldquo;Is chain-of-thought prompting an effective technique?&rdquo;\nMetric Baseline Guided \u0394 Total steps 15 6 -9 Termination BUDGET_EXHAUSTED COVERAGE_MET N\/A Coverage completeness 0.80 1.00 +0.20 Search efficiency 0.53 0.83 +0.30 Summary grounding rate\u00b9 0.67 1.00 +0.33 Disputes surfaced 0 2 +2 The key result: baseline exhausted its full budget and left one sub-question uncovered. Guided stopped at COVERAGE_MET with two conflicts surfaced. Baseline found zero.\n\u00b9 Summary grounding rate: fraction of summary sentences traceable to evidence claims or run metadata.\nRun 2 (inference-time compute scaling):\nQuery: &ldquo;What is the current state of inference-time compute scaling for LLM reasoning? Separate what has been empirically validated from what is still speculative, and identify where the evidence is too thin to draw conclusions.&rdquo;\nMetric Baseline Guided \u0394 Total steps 10 8 -2 Termination BUDGET_EXHAUSTED COVERAGE_MET N\/A Sub-questions covered 3\/5 5\/5 +2 Total LLM calls 113 116 +3 Summary grounding rate\u00b9 0.67 1.00 +0.33 Run 2 is the result I find most interesting. Same compute envelope (113 versus 116 LLM calls) but guided reached full coverage while baseline left two sub-questions unexplored. The gain isn&rsquo;t from spending more. It&rsquo;s from spending better.\nThe connection to PRMs and GRPO What I built is a hand-engineered approximation of something the research community is working toward more formally.\nA trained Process Reward Model does what my deterministic evaluator does (scores each step) but learns to do it from data rather than from rules. The training signal comes from (evidence state before, action, evidence state after) triples labeled by an LLM-as-judge for step quality. Once you have that, you replace the rule-based evaluator with a model call. Same interface, better generalization.\nEvery session already generates the training data: run_trace.json captures the full step sequence with evidence state snapshots and every LLM call with its inputs and outputs. The corpus is there. The trained scorer is what comes next.\nThe step beyond a trained PRM is using it to train the orchestrator itself with GRPO:\nPolicy: the LLM that generates search queries and decides what to challenge Reward: PRM score per step + final report quality Group: generate K research trajectories for the same query, rank by total PRM reward Update: GRPO policy gradient on the higher-reward trajectories This is Search-R1&rsquo;s approach applied to evidence-driven research rather than math reasoning. The difference from outcome-only RL: you&rsquo;re rewarding good intermediate steps, so the model learns when to challenge, when to stop, and which source domains are worth pursuing, not just how to write a fluent report.\nWhat I&rsquo;d build next The honest gaps:\nTrained PRM: the deterministic evaluator needs to become a learned scorer. The training data exists. The path is: LLM-as-judge labels at scale \u2192 fine-tune a small model \u2192 replace the evaluator. Same interface, better generalization.\nBetter conflict detection: the current conflict pipeline is preliminary. In the inference-time compute run, the conflict pipeline found zero contradictions on a query specifically designed to invite disagreement. The structure is right. The detection needs to be more aggressive.\nDecomposition evaluation: the system never measures whether the initial sub-question decomposition was good. It&rsquo;s the first thing that runs and the least evaluated component.\nAdaptive failure recovery: when searches repeatedly fail on a sub-question, the planner escalates through hardcoded recovery tiers: simpler keywords \u2192 comparator language \u2192 paper-oriented terms \u2192 forcing a specific source domain. A learned policy would adapt these tiers based on query type and retrieval history rather than following a fixed sequence.\nThe takeaway The core insight from building this: you don&rsquo;t need to retrain a model to build a research agent that knows what it knows. You need the right architecture around it: an explicit evidence state, step-level signals that classify what each action contributed, and a planner that uses those signals deliberately.\nThe models are capable. The question is whether the structure around them is. That&rsquo;s an architecture problem, and it&rsquo;s one you can solve today with the compute you have.\nThe path from here runs through trained PRMs and GRPO-trained orchestrators but the foundation is the design, not the scale.\nFull design docs, experiment configs, and ablation results: deep-research-agent\n","permalink":"https:\/\/rajathpatel23.github.io\/posts\/deep-research-agent\/","summary":"<p>Deep research agents have gotten significantly better. Tools like Perplexity, OpenAI Deep Research, and Gemini can search, synthesize, and return structured answers across dozens of sources. The quality of the output has improved fast.<\/p>\n<p>What these tools don&rsquo;t make visible is the process. When they stop searching, you don&rsquo;t know if the work is done or the budget ran out. When two sources conflict, you don&rsquo;t know if that got noticed or smoothed over. The output looks the same either way.<\/p>","title":"Evidence-Driven Deep Research Agent"},{"content":"This document is my personal deep-dive into how modern open-source GPT-style language models are actually built. It&rsquo;s not meant to be a full survey of the literature; instead, it captures the pieces that helped me build an intuition for these models: how text becomes vectors, how positional information is injected, how attention is optimized, and how FFN variants like MoE increase capacity without blowing up compute.\n1. Tokenization &amp; Embeddings The journey from human-readable text to a format the model understands begins here.\n1.1. Tokenization:\nFirst, raw text is converted into a sequence of integers called &ldquo;tokens&rdquo; using a tokenizer (e.g., Byte-Pair Encoding or BPE, as mentioned in tokenization.md). This process breaks down words into common sub-words. For example, tokenization might become [&quot;token&quot;, &quot;ization&quot;]. This allows the model to handle unknown words and understand morphological similarities (e.g., run, running). The set of all possible tokens forms the model&rsquo;s vocabulary. 1.2. Token Embeddings:\nProcess: Each token ID is mapped to a high-dimensional vector. Input Text: &#34;Hello world&#34; Token IDs: [15496, 995] Embeddings: [[0.1, -0.2, ...], [0.4, 0.9, ...]] \/\/ Each vector has dimension `d_model` (e.g., 2880) Goal: To represent tokens in a continuous vector space where semantic relationships are captured by distance and direction. Learned, Not Pre-trained: These embedding vectors are initialized randomly and are learned parameters. During training, the model adjusts them via backpropagation to place semantically similar tokens closer together. This is far more powerful than using static, pre-trained embeddings like Word2Vec because the meanings become contextualized to the model&rsquo;s task. 2. Positional Information: Rotary Positional Embeddings (RoPE) 2.1 Why Transformers Need Positional Information As we try to understand positional embeddings, it helps to first ask why they exist at all. The self-attention mechanism by itself is position-invariant: if you shuffle the tokens and apply the same shuffle to Q, K and V, you get the same outputs, just shuffled. The math has no built-in notion of \u201cfirst token\u201d, \u201csecond token\u201d, or \u201cthis token is 3 steps after that one\u201d.\nThat\u2019s a problem, because in language the order of tokens carries meaning. We want the model to know not just what the tokens are, but also where they appear and how far apart they are. To fix this, the Attention Is All You Need paper introduced positional encodings: extra information that we add to the token embeddings so that attention can take order into account.\n2.2 Sinusoidal Positional Encodings \u2013 Circle and Wavelength Intuition The original Transformer uses sinusoidal positional encodings. The idea is to associate each position index pos with an angle $\\theta$, and then use $(\\cos \\theta, \\sin \\theta)$ as a 2-D code. You can visualize this as a point moving around a unit circle:\neach position pos corresponds to some angle $\\theta(\\text{pos})$ the x-coordinate is $\\cos \\theta(\\text{pos})$ the y-coordinate is $\\sin \\theta(\\text{pos})$ Different dimensions of the positional encoding use different &ldquo;speeds&rdquo; around this circle, controlled by a wavelength $\\lambda$. A smaller $\\lambda$ means that as pos increases, $\\theta = \\text{pos} \/ \\lambda$ grows faster, so the point spins around the circle more quickly (higher frequency). A larger $\\lambda$ means a slower rotation (lower frequency). Across all dimensions you get a mix of high- and low-frequency waves over position.\nThe key bit is what happens when you move from position pos to position $\\text{pos} + k$. On the circle, that is just a rotation by a fixed angle that depends only on $k$. So the code at $\\text{pos} + k$ is the code at pos rotated by a fixed amount. Because of this, linear layers can learn to detect relative offsets (&ldquo;how far apart are these two positions?&rdquo;) just by looking at how their sin\/cos coordinates relate. That&rsquo;s what people mean when they say sinusoidal encodings make it easier for the model to attend by relative position, even though we only ever feed in absolute indices.\n2.3 Rotary Positional Embeddings (RoPE) \u2013 What GPT OSS Actually Uses The Core Idea: Instead of adding positional information to the token embedding, RoPE encodes positional information by rotating the Query and Key vectors. The amount of rotation depends on the token&rsquo;s absolute position in the sequence.\nHow It Works: Vector Rotation\nPairing Dimensions: The d-dimensional Query and Key vectors are viewed as a sequence of d\/2 two-dimensional vectors. For a vector v, this would be [(v_0, v_1), (v_2, v_3), ..., (v_{d-2}, v_{d-1})].\nDefining Frequencies: A set of\u00a0d\/2\u00a0different angular frequencies (or &ldquo;wavelengths&rdquo;)\u00a0theta_i\u00a0are defined. These are fixed and not learned, typically set to\u00a0theta_i = 10000^(-2i\/d). This means the first pairs rotate slowly (long wavelength) and later pairs rotate quickly (short wavelength).\nApplying Rotation: For a token at position\u00a0m, each 2D pair\u00a0(v_i, v_{i+1})\u00a0is rotated by an angle of\u00a0m * theta_i. This is done using a 2D rotation matrix:This operation is applied to both the Query vector\u00a0q\u00a0and the Key vector\u00a0k\u00a0before the attention score is calculated.\n[x&#39;_i] [cos(m*theta_i) -sin(m*theta_i)] [x_i] [x&#39;_{i+1}] = [sin(m*theta_i) cos(m*theta_i)] [x_{i+1}] The Magic: Encoding Relative Position\u00a0The brilliance of RoPE is that the dot product between a rotated query\u00a0q'\u00a0at position\u00a0m\u00a0and a rotated key\u00a0k'\u00a0at position\u00a0n\u00a0depends\u00a0only on their relative distance\u00a0m-n.\nDerivation Sketch: The dot product\u00a0q'_m \u00b7 k'_n\u00a0can be expanded using the rotation matrix formula. After applying trigonometric identities (like\u00a0cos(A-B) = cosAcosB + sinAsinB), the terms involving the absolute positions\u00a0m\u00a0and\u00a0n\u00a0cancel out, leaving a function that depends only on the original vectors\u00a0q,\u00a0k, and the relative position\u00a0m-n. Result: The attention score between\u00a0q_m\u00a0and\u00a0k_n\u00a0becomes a function of their content and their relative distance, which is exactly what we want. Key Advantages:\nRelative Position Encoding: It naturally captures relative positional information, which is more intuitive for language. Good Extrapolation: Because it&rsquo;s not tied to a fixed-length learned embedding, RoPE can generalize better to sequence lengths longer than those seen during training. Stability: Rotation is a norm-preserving operation, meaning it doesn&rsquo;t change the length of the vectors, which helps maintain training stability. 2.4 Comparing different positional encoding schemes Feature Absolute (Traditional) Relative Rotary (RoPE) Method Add a vector to the token embedding Add a bias to the attention scores Rotate the token\u2019s Q\/K vectors Analogy House numbers (\u201cHouse #5\u201d) Directions (\u201c3 steps left\u201d) Clock angles (\u201cangle difference\u201d) Generalization Poor (struggles with unseen lengths) Good (invariant to shifts) Excellent (naturally encodes relative distance) Complexity Low (simple addition) High (pairwise distance computation) Medium (rotation via small matrix multiplies) 3. RMS Normalization (RMSNorm) A simple and efficient normalization layer used throughout the transformer blocks to stabilize training.\nFormula: $$ \\text{output} = \\frac{x}{\\text{RMS}(x)} \\cdot g \\quad \\text{where} \\quad \\text{RMS}(x) = \\sqrt{\\frac{1}{d}\\sum_{i=1}^{d} x_i^2 + \\epsilon} $$\nx is the input vector, g (gain) is a learned parameter vector, and epsilon is a small constant for numerical stability. Advantages over LayerNorm: Simplicity &amp; Speed: By omitting the mean-centering step of LayerNorm (x - mean(x)), RMSNorm is computationally simpler and faster (~7-14% on GPUs). Equivalent Performance: In practice, for large transformer models, the centering operation provides little to no benefit, and RMSNorm performs just as well or better. The network can implicitly learn to offset values if needed. 4. The Transformer Block The core repeating unit of the model. A model is a deep stack of these blocks. A single block consists of two main sub-layers: an attention mechanism and a feed-forward network.\n4.1. Attention Sub-Layer This layer allows tokens to &ldquo;look at&rdquo; and gather information from other tokens in the sequence.\nOptimized Attention Variants: To manage the computational and memory costs of standard Multi-Head Attention (MHA), modern models use more efficient variants. Variant Query (Q) Heads Key (K) Heads Value (V) Heads Benefit Multi-Head (MHA) N N N High model quality, high memory cost. Multi-Query (MQA) N 1 1 Drastically reduces KV cache size, fastest inference. Grouped-Query (GQA) N G (e.g., 4) G (e.g., 4) A balance between MHA&rsquo;s quality and MQA&rsquo;s speed. Sliding Window Attention (SWA): To handle very long sequences efficiently, some models employ SWA. Instead of allowing every token to attend to every other previous token (which has a quadratic O(n^2) cost), SWA restricts each token to only attend to a fixed-size window of recent tokens (e.g., the last 4096 tokens). Benefit: This reduces the computational complexity to O(n * w), where w is the window size, enabling the model to process much longer contexts with a linear cost.\nExample: The Mistral 7B model is a prominent example that uses Sliding Window Attention to achieve a large effective context window while maintaining high efficiency. Interaction with KV Cache: SWA&rsquo;s most significant impact is on the KV Cache. Instead of growing indefinitely, the cache becomes a fixed-size rolling buffer. It only needs to store the keys and values for the last w tokens. When a new token is generated, the oldest token&rsquo;s K\/V pair is discarded, and the new one is added. This keeps memory usage constant and bounded, regardless of the total sequence length. 4.1.1 Information Propagation Beyond the Sliding Window A common question about SWA is: if a token can only see the last W tokens, isn&rsquo;t all prior information lost? The answer is no, due to a transitive information flow. Information from outside the window is not accessed directly, but its essence is carried forward through two mechanisms:\nHorizontal Propagation (Token-to-Token):\nThe token at position N attends to the token at position N-1. The token at N-1 has already attended to the token at N-2, and so on, back to N-W. Therefore, the representation of token N-1 contains a summary of its own attention window. When token N attends to N-1, it indirectly accesses this summarized information. This creates a &ldquo;ripple effect&rdquo; where the semantic context is passed down from one token to the next. Vertical Propagation (Layer-to-Layer):\nThis effect is amplified across the model&rsquo;s layers. The output representation of a token from Layer 1, which has gathered information from its local window, becomes the input to Layer 2. In Layer 2, when a token attends to its neighbors, it&rsquo;s attending to representations that have already summarized information from the previous layer. Because of this, the &ldquo;effective receptive field&rdquo; of a token grows with each layer. By the final layer, a token&rsquo;s representation has been influenced by information that originated far outside its immediate W-sized attention window. KV Cache Size Impact: The choice of attention mechanism directly impacts the size of the KV Cache. MQA and GQA reduce the cache size by reducing the number of K\/V heads. SWA reduces it by limiting the sequence length dimension of the cache. 4.1.2. Attention Bias Definition: The attention logits are computed as attn_logits = (Q @ K^T) * scale + bias, where bias is added before the softmax and can be broadcast across heads and\/or sequence positions. Typical shapes: [num_heads, 1, seq_len, seq_len], [1, seq_len, seq_len], or block-sparse masks. Common uses: Causal Masking: Setting scores for future tokens to -infinity to prevent a token from &ldquo;cheating&rdquo; and seeing the future. This is essential for auto-regressive generation. Attention Linear Bias (ALiBi) (linear distance penalty): Implementing alternative positional encoding schemes like ALiBi (Attention with Linear Biases), where the bias penalizes attention between distant tokens. Relative position bias (T5-style): Learned bucketed biases that favor nearby tokens without explicit rotations. Segment\/turn\/document biases: Down-weight cross-segment attention (e.g., between chat turns) or up-weight separators. Task-specific nudges: Small positive bias to encourage attending to prefixes, BOS, or special control tokens. Implementation notes: The bias is added additively and can be static (no gradients; e.g., causal mask, ALiBi) or learned. Works independently of RoPE\/MQA\/GQA and with FlashAttention by fusing masks\/biases into the softmax kernel. Memory cost is minimal due to broadcasting; compute overhead is negligible. 4.1.3. Attention Sinks Intuition: Reserve a small number of early positions (e.g., the first m tokens) as &ldquo;sink&rdquo; tokens that every query can always attend to. These serve as stable anchors that preserve global context, especially under streaming or sliding-window inference. Why it helps: Prevents quality drop when tokens outside the current window are no longer directly visible. Provides a consistent fallback target, stabilizing attention distributions and downstream normalization statistics. Acts like a &ldquo;heat sink&rdquo;: it can absorb a small, consistent fraction of attention mass to avoid brittle sparsity. Mechanism: Keep the K\/V for the sink positions permanently in the KV cache, even when using SWA that evicts old tokens. Add a small positive bias +b_sink to logits targeting sink indices so that they receive a modest probability mass after softmax (e.g., 1\u20135%). Optionally insert dedicated sink tokens (or reuse BOS) with embeddings tuned for summarization\/aggregation. Practical guidance: Choose m in the range 1\u20134; set b_sink to achieve a small but nontrivial attention share. Can be introduced at inference-time only, but works best if the model is trained or finetuned with sink behavior. Compatible with RoPE, MQA\/GQA, SWA, and FlashAttention. Reference: Efficient Streaming of Language Models with Attention Sinks (arXiv:2309.17453). # Pseudocode (inference-time biasing with m sink tokens) def add_attention_bias(attn_logits, sink_indices, b_sink): # attn_logits: [batch, heads, q_len, k_len] # sink_indices: list\/tensor of length m with K-side positions to favor attn_logits[..., sink_indices] += b_sink return attn_logits # With sliding-window caching: always retain K\/V at sink_indices def update_kv_cache(cache, new_k, new_v, sink_indices, window_size): # Keep sinks + last (window_size - len(sink_indices)) positions retained = concat(cache.kv_at(sink_indices), cache.kv_last(window_size - len(sink_indices))) cache.k, cache.v = roll_and_append(retained, new_k, new_v) return cache 4.2. Feed-Forward Network (FFN) Sub-Layer This is where the model does much of its &ldquo;thinking&rdquo; and knowledge recall.\nStandard FFN: A simple two-layer MLP: FFN(x) = ReLU(x @ W1 + b1) @ W2 + b2.\nSwiGLU Variant: Modern models often use a more advanced variant called SwiGLU (Gated Linear Unit with a Swish\/SiLU activation) for better performance.\nSwiGLU(x) = (SiLU(x @ W1) * (x @ W_gate)) @ W2\nIt uses three weight matrices instead of two. The gating mechanism (x @ W_gate) allows the network to dynamically control how much information flows through the main path, leading to improved training and final model quality. Mixture of Experts (MoE): To scale up model size efficiently, the FFN sub-layer can be replaced with an MoE layer.\nArchitecture: Instead of one large FFN, there are multiple smaller FFNs (the &ldquo;experts&rdquo;). Routing: A small &ldquo;gating network&rdquo; or &ldquo;router&rdquo; (a simple linear layer + softmax) looks at each token&rsquo;s hidden state and outputs probabilities for which expert should process it. Sparse Activation: Typically, only the top-2 experts are chosen for each token. The final output is a weighted sum of the outputs from these two experts. Benefit: This allows for a massive increase in the total number of parameters in the model, while the computational cost per token remains constant. A &ldquo;load balancing loss&rdquo; is often added during training to ensure all experts are utilized. Load Balancing Loss \u2013 My Mental Picture\nMixture-of-Experts only helps if different experts actually get used. In practice, the router tends to fall in love with a few &ldquo;easy win&rdquo; experts early in training and send almost every token to them. Those experts get lots of gradient updates and become even better, while the others starve and never learn anything useful. This is called router collapse.\nTo prevent that, modern MoE layers add a small auxiliary load balancing loss. Over a batch of tokens, we look at two things for each expert:\nhow much the router wants to use that expert (its average routing probability), and how many tokens actually go to that expert (its share of the routed tokens). The load balancing loss pushes these quantities toward being roughly uniform across experts. Intuitively, it penalizes solutions where one expert is overloaded and others are idle. The main language modeling loss still decides what each expert should learn, but the load balancing loss makes sure every expert gets a steady stream of training data instead of the router sending everything to a single &ldquo;favorite&rdquo; expert.\n4.3. Residual Connections Residual connections (or &ldquo;skip connections&rdquo;) are the architectural glue that holds the transformer block together and, more importantly, allows the model to be trained at great depths.\nHow it Works: A residual connection is a direct data path that bypasses a sub-layer (like attention or FFN). The output of the sub-layer is then added to the original input that went into it.\noutput = input + SubLayer(LayerNorm(input))\nWhy They Are Critical:\nCombating Vanishing Gradients: This is the primary reason for their existence. In very deep networks, gradients can shrink exponentially as they are propagated backward from the final layer to the initial layers. This causes the early layers to learn extremely slowly or not at all. The residual connection acts as an &ldquo;information superhighway,&rdquo; allowing the gradient to flow directly and unimpeded back through the network. This ensures that even the earliest layers receive a strong learning signal. Preserving Information: Each sub-layer transforms its input. The residual connection guarantees that the original, untransformed information from the beginning of the block is carried forward. The sub-layer&rsquo;s job is simplified: it only needs to learn the residual (the change or update that should be applied to the original vector) rather than the entire transformation from scratch. This makes learning easier and prevents information loss. Without residual connections, training transformers with dozens or hundreds of layers would be practically impossible.\n5. Key-Value (KV) Cache A critical optimization that makes auto-regressive text generation practical and fast.\nThe Problem: During generation, to predict token N+1, the model needs to attend to all previous tokens 1...N. Naively re-calculating the Key (K) and Value (V) vectors for the entire context at every single step is computationally prohibitive. The Solution: The KV cache is a memory buffer that stores the K and V vectors once they are computed. Step 1: Process prompt &ldquo;The cat&rdquo;. Compute and cache K_the, V_the, K_cat, V_cat. Step 2: Generate next token. Let&rsquo;s say it&rsquo;s &ldquo;sat&rdquo;. The model computes Q_sat and attends to the cached [K_the, K_cat] and [V_the, V_cat]. Step 3: After generating &ldquo;sat&rdquo;, compute K_sat and V_sat and append them to the cache. The cache now holds K\/V for &ldquo;The cat sat&rdquo;. Note: With Sliding Window Attention, this cache would be a fixed-size rolling buffer rather than an ever-growing list (see section 4.1). This turns a quadratic operation (recomputing everything) into a linear one (computing for one new token), making generation feasible for long sequences. 6. Overall Architecture &amp; Workflow Putting it all together, a GPT-style model processes data roughly like this:\nInput\nRaw text is passed to the tokenizer, producing a sequence of token IDs.\nEmbedding layer\nToken IDs are converted into token embeddings. Positional information (e.g., RoPE) is applied to the Q\/K projections inside attention layers.\nTransformer blocks (stacked L times)\nThe sequence is processed through L identical blocks. For each block:\na. Pre-attention norm\nx_norm1 = RMSNorm(x)\nb. Attention\nattn_out = GQA(Q = x_norm1, K = x_norm1, V = x_norm1)\n(with RoPE applied to Q and K, plus any attention bias, SWA masking, sinks, etc.)\nc. First residual\nx_res1 = x + attn_out\nd. Pre-FFN norm\nx_norm2 = RMSNorm(x_res1)\ne. Feed-forward \/ MoE\nffn_out = MoE(x_norm2) (or a SwiGLU FFN in non-MoE models)\nf. Second residual\nx = x_res1 + ffn_out\n(this x becomes the input to the next block)\nFinal projection\na. Apply a final RMSNorm to the last block\u2019s output.\nb. Use a linear layer (the LM head) to project to vocabulary size, producing logits for each token position.\nSoftmax &amp; loss\nDuring training, apply softmax to get probabilities and use cross-entropy against the next token as the main loss. For MoE layers, add the auxiliary load balancing loss on top. Inference loop &amp; KV cache\nFor generation, the model runs step-by-step:\nFor each new token, compute Q (and the new K\/V), attend to cached past keys\/values, and append the new K\/V to the KV cache. With Sliding Window Attention, the KV cache becomes a rolling buffer that only retains the last W tokens (plus any sink positions), keeping memory usage bounded even for long conversations. ","permalink":"https:\/\/rajathpatel23.github.io\/posts\/gpt_oss_architecture\/","summary":"<p>This document is my personal deep-dive into how modern open-source GPT-style language models are actually built. It&rsquo;s not meant to be a full survey of the literature; instead, it captures the pieces that helped <em>me<\/em> build an intuition for these models: how text becomes vectors, how positional information is injected, how attention is optimized, and how FFN variants like MoE increase capacity without blowing up compute.<\/p>\n<hr>\n<h2 id=\"1-tokenization--embeddings\">1. Tokenization &amp; Embeddings<\/h2>\n<p>The journey from human-readable text to a format the model understands begins here.<\/p>","title":"GPT OSS Style Architectures"},{"content":"This guide explores the core attention variants in modern transformers, focusing on the mechanisms themselves: Multi-Head Attention (MHA), Multi-Query Attention (MQA), and Grouped-Query Attention (GQA). We&rsquo;ll understand why each exists and their fundamental architectural differences.\nQuick Overview Self-Attention: Each token looks at other tokens to build contextualized representations Multi-Head Attention (MHA): Multiple independent attention &ldquo;heads&rdquo; in parallel; each head has its own Q, K, V projections Multi-Query Attention (MQA): Share Key\/Value projections across all query heads; reduces parameters significantly Grouped-Query Attention (GQA): Groups of query heads share K\/V projections; balances expressiveness and efficiency 1. Self-Attention Foundations Core Intuition Self-attention is a content-based lookup over the sequence:\nQueries (Q) ask &ldquo;what do I need?&rdquo; Keys (K) say &ldquo;what do I offer?&rdquo; Values (V) contain the information to aggregate Core computation: softmax((Q @ K^T) \/ sqrt(d)) @ V Mathematical Formulation Notation: batch B, sequence length L, model width D\nSingle-head projections:\nQ = X W_q, K = X W_k, V = X W_v Shapes: X: [B, L, D], W_q\/W_k\/W_v: [D, d], Q\/K\/V: [B, L, d] Attention computation:\n1. Attention logits: A = (Q @ K^T) \/ sqrt(d) \u2192 [B, L, L] 2. Apply causal mask: A[i,j] = -inf for j &gt; i (generation) 3. Attention weights: P = softmax(A, dim=-1) 4. Output: Y = P @ V \u2192 [B, L, d] Implementation def scaled_dot_product_attention(Q, K, V, mask=None): # Q,K,V: [B, L, d] scale = 1.0 \/ math.sqrt(Q.size(-1)) logits = torch.einsum(&#39;bld,bmd-&gt;blm&#39;, Q, K) * scale # [B,L,L] if mask is not None: logits = logits.masked_fill(mask == 0, float(&#39;-inf&#39;)) probs = torch.softmax(logits, dim=-1) return torch.einsum(&#39;blm,bmd-&gt;bld&#39;, probs, V) Limitations A single head blends all relations into one pattern, which can be too coarse for complex linguistic structure.\n2. Multi-Head Attention (MHA) - The Gold Standard Why Multiple Heads? Different heads specialize in different aspects:\nSyntactic patterns: Subject-verb relationships, phrase boundaries Long-range dependencies: Coreference resolution, discourse structure Entity tracking: Following entities across long sequences Semantic relationships: Similarity, causation, temporal ordering Architecture Details Head configuration:\nModel width D, number of heads H, head width d_h = D \/ H Combined projections: W_q\/W_k\/W_v: [D, H\u00d7d_h] After projection, reshape to heads: Q\/K\/V: [B, H, L, d_h] Processing flow:\n# Multi-head projection Q = X @ W_q; K = X @ W_k; V = X @ W_v # [B,L,D] Q = Q.view(B, L, H, d_h).transpose(1, 2) # [B,H,L,d_h] # ... attention per head ... Y = Y_heads.transpose(1, 2).contiguous().view(B, L, D) @ W_o Computational Cost Attention compute: O(B \u00d7 H \u00d7 L\u00b2 \u00d7 d_h) Memory for logits: O(B \u00d7 H \u00d7 L\u00b2) Typical settings: D=4096, H=32, d_h=128 (many 7-70B models use H \u2208 [24,40]) Trade-offs \u2705 Advantages:\nHighest model quality and representational richness Each head can specialize in different linguistic phenomena Well-established training dynamics \u274c Disadvantages:\nKV cache scales with num_heads, increasing inference memory Higher bandwidth requirements during generation More expensive for long-context applications 3. Multi-Query Attention (MQA) - Maximum Efficiency Core Innovation Share Key and Value projections across all query heads while keeping query heads independent.\nWhy This Works Parameter efficiency: Dramatically reduces the number of parameters in attention layers Key insight: Queries can be diverse, but Keys\/Values can be shared across heads Result: Significant parameter reduction with minimal quality loss in many tasks Architecture Changes Projection differences:\n# MHA projections self.w_q = nn.Linear(d_model, d_model) # H heads worth self.w_k = nn.Linear(d_model, d_model) # H heads worth self.w_v = nn.Linear(d_model, d_model) # H heads worth # MQA projections self.w_q = nn.Linear(d_model, d_model) # H heads worth self.w_k = nn.Linear(d_model, d_k) # 1 head only (shared) self.w_v = nn.Linear(d_model, d_k) # 1 head only (shared) Runtime sharing:\nProjection weights: One W_k: [D, d_h] and W_v: [D, d_h] for all heads Runtime tensors: Single K: [B, L, d_h] and V: [B, L, d_h] referenced by every query head Queries remain multi-headed: Q: [B, H, L, d_h] for diverse attention patterns Attention Pattern Differences What changes in MQA:\nQuery diversity maintained: Each head still has independent query patterns Shared key\/value space: All heads attend over the same key-value representations Reduced expressiveness: Some loss in ability to learn specialized key-value transformations per head When to Use MQA \u2705 Advantages:\nSignificant parameter reduction (46.9% in our experiments) Faster training due to fewer parameters Maintains most attention expressiveness through diverse queries \u26a0\ufe0f Trade-offs:\nSlightly lower quality than MHA on some complex tasks Less specialized key-value transformations per head May require careful hyperparameter tuning Real-World Usage PaLM: Uses MQA for efficiency in large-scale deployment Falcon: Adopted MQA for fast inference Chinchilla: Demonstrated MQA effectiveness at scale 4. Grouped-Query Attention (GQA) - The Sweet Spot Design Philosophy Compromise between MHA quality and MQA efficiency by dividing heads into groups that share K\/V.\nArchitecture Details Group organization:\nDivide H heads into G groups Each group shares one K\/V set: num_kv_heads = G Queries per group: H \/ G Projection structure:\n# GQA projections (G groups) self.w_q = nn.Linear(d_model, d_model) # H heads worth self.w_k = nn.Linear(d_model, num_kv_heads * d_k) # G heads worth self.w_v = nn.Linear(d_model, num_kv_heads * d_k) # G heads worth Runtime organization:\nPer group: One W_k^g: [D, d_h] and W_v^g: [D, d_h] Runtime tensors per group: K^g: [B, L, d_h], V^g: [B, L, d_h] Head mapping: Query head index \u2192 group index for K\/V routing Parameter Scaling Memory and computation:\nParameters scale with: num_kv_heads instead of num_heads Example (D=4096, H=32, d_h=128, G=4): GQA parameters: Proportional to 4 KV heads instead of 32 Reduction: ~8\u00d7 fewer K\/V parameters than MHA Performance Characteristics Quality vs. Efficiency:\nvs MHA: 90-95% of quality with major memory savings vs MQA: Better quality with moderate memory increase Sweet spot: G \u2208 {4,8} groups work well empirically Implementation Considerations # Head-to-group mapping def get_kv_group(head_idx, num_heads, num_groups): return head_idx \/\/ (num_heads \/\/ num_groups) # Attention routing for head in range(num_heads): group = get_kv_group(head, num_heads, num_groups) attention_output[head] = attention(Q[head], K[group], V[group]) Real-World Adoption Llama-2: Uses GQA with optimized group configurations Code Llama: Balances code understanding with efficiency Mistral: Adopted GQA for production deployments 5. Practical Implementation Results Experimental Setup Our implementation demonstrates these mechanisms using Shakespeare&rsquo;s text:\nInput: &ldquo;To be or not to be, that is the question&rdquo; Model dimensions: d_model=256, num_heads=16, num_kv_heads=4 (for GQA) Framework: PyTorch with custom implementations Parameter Comparison \ud83d\udcca Attention Mechanisms Efficiency Analysis Model dimension (d_model): 256, Number of heads: 16 Multi-Head Attention (MHA): 263,168 parameters Multi-Query Attention (MQA): 139,808 parameters (46.9% reduction) Grouped-Query Attention (GQA): 164,480 parameters (37.5% reduction) Parameter Breakdown MHA (Traditional):\nQ projection: 256 \u00d7 256 = 65,536 parameters K projection: 256 \u00d7 256 = 65,536 parameters V projection: 256 \u00d7 256 = 65,536 parameters Output projection: 256 \u00d7 256 = 65,536 parameters Total: ~262K parameters MQA (Maximum Efficiency):\nQ projection: 256 \u00d7 256 = 65,536 parameters (16 heads) K projection: 256 \u00d7 16 = 4,096 parameters (1 shared head) V projection: 256 \u00d7 16 = 4,096 parameters (1 shared head) Output projection: 256 \u00d7 256 = 65,536 parameters Total: ~139K parameters (46.9% reduction) GQA (Balanced):\nQ projection: 256 \u00d7 256 = 65,536 parameters (16 heads) K projection: 256 \u00d7 64 = 16,384 parameters (4 KV heads) V projection: 256 \u00d7 64 = 16,384 parameters (4 KV heads) Output projection: 256 \u00d7 256 = 65,536 parameters Total: ~164K parameters (37.5% reduction) 6. Selection Guide: When to Use Each Mechanism Decision Matrix Criterion MHA GQA MQA Model Quality Highest High Good Parameter Efficiency Lowest Good Best Training Speed Slowest Fast Fastest Attention Expressiveness Maximum High Limited Implementation Simplicity Simple Moderate Simple Concrete Recommendations Choose MHA when:\nMaximum model quality is required Parameter count is not a constraint Research\/experimentation phase You need maximum attention expressiveness Choose GQA when:\nNeed balance between quality and efficiency Building production systems with parameter constraints Want to reduce model size while maintaining good performance Quality-sensitive tasks with efficiency requirements Choose MQA when:\nParameter efficiency is critical Training on limited computational resources Building lightweight models for deployment Maximum parameter reduction is needed Model Size Considerations Large models (&gt;10B parameters): Parameter efficiency becomes more important, GQA\/MQA more attractive Medium models (1B-10B): GQA often provides the best balance Small models (&lt;1B): MHA may be preferred for maximum quality with manageable parameter count 7. Key Implementation Insights Attention Pattern Differences How each mechanism processes information:\nMHA (Multi-Head Attention):\nEach head learns completely independent attention patterns Maximum expressiveness: heads can specialize in different linguistic phenomena Each head has its own &ldquo;view&rdquo; of what&rsquo;s important in the sequence MQA (Multi-Query Attention):\nAll heads share the same Key\/Value representations Query heads maintain diversity in what they &ldquo;ask for&rdquo; Reduced specialization in how information is represented (shared K\/V) GQA (Grouped-Query Attention):\nGroups of heads share Key\/Value representations Balances specialization (within groups) with efficiency (shared K\/V) Creates &ldquo;clusters&rdquo; of heads that work with similar information representations Common Implementation Pitfalls \u26a0\ufe0f Watch out for:\nForgetting sqrt(d_h) scaling in attention computation Wrong head\u2192group mapping in GQA implementation Inconsistent tensor shapes when switching between mechanisms Not properly reshaping tensors for multi-head computation Conclusion The evolution from MHA \u2192 GQA \u2192 MQA represents a fundamental trade-off in attention mechanisms: expressiveness vs. efficiency.\nOur Experimental Results Show: Parameter Efficiency: MQA achieves 46.9% reduction, GQA achieves 37.5% reduction Quality Trade-offs: GQA maintains ~90-95% of MHA quality with major efficiency gains Practical Impact: The choice of attention mechanism significantly affects model size and training efficiency Key Takeaway Understanding these attention variants is essential for modern transformer development. The &ldquo;best&rdquo; choice depends on your specific constraints:\nResearch\/Maximum Quality: MHA Production Balance: GQA Resource Constraints: MQA Each mechanism represents a different point on the quality-efficiency spectrum, and the field continues to find new ways to optimize this fundamental trade-off in transformer architectures.\n","permalink":"https:\/\/rajathpatel23.github.io\/posts\/attention_mechanism\/","summary":"<p>This guide explores the core attention variants in modern transformers, focusing on the mechanisms themselves: Multi-Head Attention (MHA), Multi-Query Attention (MQA), and Grouped-Query Attention (GQA). We&rsquo;ll understand why each exists and their fundamental architectural differences.<\/p>\n<hr>\n<h2 id=\"quick-overview\">Quick Overview<\/h2>\n<ul>\n<li><strong>Self-Attention<\/strong>: Each token looks at other tokens to build contextualized representations<\/li>\n<li><strong>Multi-Head Attention (MHA)<\/strong>: Multiple independent attention &ldquo;heads&rdquo; in parallel; each head has its own Q, K, V projections<\/li>\n<li><strong>Multi-Query Attention (MQA)<\/strong>: Share Key\/Value projections across all query heads; reduces parameters significantly<\/li>\n<li><strong>Grouped-Query Attention (GQA)<\/strong>: Groups of query heads share K\/V projections; balances expressiveness and efficiency<\/li>\n<\/ul>\n<hr>\n<h2 id=\"1-self-attention-foundations\">1. Self-Attention Foundations<\/h2>\n<h3 id=\"core-intuition\">Core Intuition<\/h3>\n<p>Self-attention is a <strong>content-based lookup<\/strong> over the sequence:<\/p>","title":"Attention Mechanisms in Transformers: MHA vs MQA vs GQA"},{"content":"Introduction Language models are mathematical functions; they operate on numbers, not raw text. Tokenization is the crucial first step in converting human-readable text into a sequence of integers (tokens) that a model can process. These tokens are then mapped to embedding vectors.\n1. Naive Approaches and Their Flaws Word-Level Tokenization The most intuitive approach: split text by spaces and punctuation.\nProblems: Vocabulary Explosion: A language like English has hundreds of thousands of words. The model&rsquo;s vocabulary would be enormous, making the final embedding and output layers computationally massive. Out-of-Vocabulary (OOV) Words: If the model encounters a word not seen during training (e.g., a new slang term, a typo, or a technical name), it has no token for it. It typically maps it to an &lt;UNK&gt; (unknown) token, losing all semantic meaning. Poor Generalization: The model treats eat, eating, and eaten as three completely separate, unrelated tokens. It fails to capture the shared root eat, making it harder to learn morphological relationships. Character-Level Tokenization The opposite extreme: split text into individual characters.\nAdvantage: The vocabulary is tiny and fixed (e.g., ~256 for bytes). There are no OOV words. Problems: Loss of Semantic Meaning: A single character like t has very little semantic value on its own. The model must expend significant capacity just to learn the structure of common words from characters. Long Sequences: A simple sentence becomes a very long sequence of tokens. This makes it computationally difficult for the model to learn long-range dependencies and can quickly exceed the context window. 2. The Solution: Subword Tokenization Modern LLMs use a hybrid approach called subword tokenization, which combines the best of both worlds.\nCore Idea: Common words are kept as single, unique tokens (e.g., the, is, and), while rare or complex words are broken down into smaller, meaningful sub-units (e.g., tokenization -&gt; token + ization). Benefits: It gracefully handles OOV words by breaking them into known subwords. It captures morphological relationships (e.g., eating -&gt; eat + ing). It keeps the vocabulary size manageable while maintaining semantic richness. Algorithm: Byte-Pair Encoding (BPE) BPE is a data-driven algorithm used to create a subword vocabulary. It starts with a base vocabulary of individual characters (or bytes) and learns merge rules from a large text corpus.\nInitialization: The initial vocabulary consists of all single bytes (0-255). Iteration: a. Count the frequency of all adjacent token pairs in the training corpus. b. Find the most frequent pair (e.g., ('e', 'r')). c. Merge this pair into a new, single token ('er'). d. Add this new token to the vocabulary and replace all occurrences of the pair in the corpus with the new token. Repeat: Continue this process for a predetermined number of merges, which defines the final vocabulary size. The byte_pair_encoding_algo.py script in this repository provides a simple, hands-on example of this process.\nBPE Training Process Visualization Our implementation shows the BPE training process in real-time:\nPre-processing: The tokenizer processes ~1MB of Shakespeare text Word Tokenization: Identifies 15,057 unique word tokens Pair Counting: Analyzes frequency of adjacent character\/token pairs Merge Computation: Learns 12,455 merge rules to build the final vocabulary This creates a vocabulary that efficiently represents Shakespeare&rsquo;s linguistic patterns, learning common words like &ldquo;the&rdquo;, &ldquo;and&rdquo;, &ldquo;to&rdquo; as single tokens while breaking down rare words into meaningful subparts.\n3. Modern Tokenizers in GPT Models OpenAI&rsquo;s models use a library called tiktoken for high-performance BPE tokenization.\ncl100k_base: The tokenizer used for models like GPT-3.5 and GPT-4. It has a vocabulary size of ~100,000. o200k_base: A newer tokenizer for more advanced models. It has a larger vocabulary of ~200,000 and includes special tokens designed for chat and instruction-following. Special Tokens for Chat Modern tokenizers reserve special tokens to encode conversational structure, which is critical for chat models.\nChat Formatting: Tokens like &lt;|im_start|&gt; and &lt;|im_end|&gt; are used to delineate turns in a conversation, allowing the model to understand the flow of a multi-speaker dialogue. Role-Based Prompting: Tokens are used to specify roles (e.g., system, user, assistant), preserving the instructions and context for how the model should behave. These special tokens are not part of the regular text but are essential metadata that the model uses to understand its task. As shown in tokenizer.py, you can enable them with allowed_special=&quot;all&quot;.\nComprehensive Tokenization Comparison Let&rsquo;s compare different tokenization approaches with practical examples:\nExample 1: Simple Text Input: &quot;Hello world!&quot;\nCharacter-level: 12 tokens ['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'] Word-level: 2 tokens ['Hello', 'world!'] GPT-4 BPE: 3 tokens ['Hello', ' world', '!'] Custom BPE: 4 tokens ['H', 'ello', ' world', '!'] Example 2: Complex Words Input: &quot;Supercalifragilisticexpialidocious&quot;\nCharacter-level: 34 tokens (one per character) Word-level: 1 token (entire word, likely OOV) GPT-4 BPE: 11 tokens ['Sup', 'erc', 'al', 'if', 'rag', 'il', 'istic', 'exp', 'ial', 'id', 'ocious'] This demonstrates BPE&rsquo;s key advantage: it gracefully handles unknown words by breaking them into meaningful subparts.\nExample 3: Modern Terms Input: &quot;COVID-19 vaccination appointments&quot;\nGPT-4 BPE: 5 tokens ['COVID', '-', '19', ' vaccination', ' appointments'] Custom Shakespeare BPE: 10 tokens (struggles with modern terms) This shows how tokenizer training data affects performance on different domains.\nBPE Benefits Analysis Morphological Understanding &quot;running&quot; \u2192 1 token (common word, learned as whole) &quot;unhappiness&quot; \u2192 3 tokens ['un', 'h', 'appiness'] (breaks down prefix\/suffix) &quot;tokenization&quot; \u2192 2 tokens ['token', 'ization'] (recognizes root + suffix) Compression Efficiency From our analysis of a technical paragraph:\nCharacter-level: 344 tokens (1:1 ratio) Word-level: 49 tokens (7x compression) BPE: 67 tokens (5.1x compression vs characters, better vocabulary management) Key Insights Vocabulary Size: BPE requires much smaller vocabulary than word-level OOV Handling: Never encounters truly unknown tokens Compression: Balances sequence length with vocabulary size Domain Adaptation: Learns patterns specific to training data Practical Demonstration: Shakespeare Tokenizer in Action Now that we understand the theory, let&rsquo;s see tokenization in action using our custom BPE tokenizer trained on Shakespeare&rsquo;s complete works:\nShakespeare-Optimized Tokenization Our custom tokenizer shows interesting domain-specific behavior:\nExample 1: Classic Shakespeare\nInput: &#34;To be or not to be, that is the question&#34; Tokens: [&#39;To&#39;, &#39;\u0120be&#39;, &#39;\u0120or&#39;, &#39;\u0120not&#39;, &#39;\u0120to&#39;, &#39;\u0120be&#39;, &#39;,&#39;, &#39;\u0120that&#39;, &#39;\u0120is&#39;, &#39;\u0120the&#39;, &#39;\u0120question&#39;] Token Count: 11 tokens Example 2: Shakespearean Language\nInput: &#34;Thou art more lovely and more temperate&#34; Tokens: [&#39;Thou&#39;, &#39;\u0120art&#39;, &#39;\u0120more&#39;, &#39;\u0120lovely&#39;, &#39;\u0120and&#39;, &#39;\u0120more&#39;, &#39;\u0120temperate&#39;] Token Count: 7 tokens Example 3: Famous Shakespeare Quote\nInput: &#34;All the world&#39;s a stage, and all the men and women merely players&#34; Tokens: [&#39;All&#39;, &#39;\u0120the&#39;, &#39;\u0120world&#39;, &#34;&#39;s&#34;, &#39;\u0120a&#39;, &#39;\u0120stage&#39;, &#39;,&#39;, &#39;\u0120and&#39;, &#39;\u0120all&#39;, &#39;\u0120the&#39;, &#39;\u0120men&#39;, &#39;\u0120and&#39;, &#39;\u0120women&#39;, &#39;\u0120merely&#39;, &#39;\u0120players&#39;] Token Count: 15 tokens Implementation Code Our tokenizer training implementation demonstrates the BPE process:\ndef train_tokenizer(data_path: str, tokenizer_path: str): # Initialize BPE tokenizer tokenizer = Tokenizer(BPE()) tokenizer.pre_tokenizer = ByteLevelPreTokenizer(add_prefix_space=False) tokenizer.post_processor = ByteLevelPostProcessor(trim_offsets=False) tokenizer.decoder = decoder.ByteLevel() # Train with special tokens and minimum frequency trainer = BpeTrainer(special_tokens=[&#34;&lt;|endoftext|&gt;&#34;], min_frequency=2) tokenizer.train([data_path], trainer) return tokenizer Analysis of Results Domain Adaptation Success:\nArchaic Words: &ldquo;Thou&rdquo;, &ldquo;art&rdquo; are learned as single tokens (common in Shakespeare) Complex Words: &ldquo;temperate&rdquo; stays whole, showing efficient learning from corpus Modern Efficiency: Our tokenizer has ~12,521 tokens, optimized for Early Modern English Technical Insights:\nSpace Encoding: The &lsquo;\u0120&rsquo; prefix indicates spaces (ByteLevel encoding standard) Punctuation Handling: Contractions like &ldquo;&rsquo;s&rdquo; and punctuation are separate tokens Compression: Achieves good balance between sequence length and vocabulary size This demonstrates how BPE tokenizers adapt to their training domain, making them highly effective for specific text types while maintaining the flexibility to handle any input text through subword decomposition.\n","permalink":"https:\/\/rajathpatel23.github.io\/posts\/tokenizers\/","summary":"<h2 id=\"introduction\">Introduction<\/h2>\n<p>Language models are mathematical functions; they operate on numbers, not raw text. Tokenization is the crucial first step in converting human-readable text into a sequence of integers (tokens) that a model can process. These tokens are then mapped to embedding vectors.<\/p>\n<hr>\n<h3 id=\"1-naive-approaches-and-their-flaws\">1. Naive Approaches and Their Flaws<\/h3>\n<h4 id=\"word-level-tokenization\">Word-Level Tokenization<\/h4>\n<p>The most intuitive approach: split text by spaces and punctuation.<\/p>\n<ul>\n<li><strong>Problems<\/strong>:\n<ol>\n<li><strong>Vocabulary Explosion<\/strong>: A language like English has hundreds of thousands of words. The model&rsquo;s vocabulary would be enormous, making the final embedding and output layers computationally massive.<\/li>\n<li><strong>Out-of-Vocabulary (OOV) Words<\/strong>: If the model encounters a word not seen during training (e.g., a new slang term, a typo, or a technical name), it has no token for it. It typically maps it to an <code>&lt;UNK&gt;<\/code> (unknown) token, losing all semantic meaning.<\/li>\n<li><strong>Poor Generalization<\/strong>: The model treats <code>eat<\/code>, <code>eating<\/code>, and <code>eaten<\/code> as three completely separate, unrelated tokens. It fails to capture the shared root <code>eat<\/code>, making it harder to learn morphological relationships.<\/li>\n<\/ol>\n<\/li>\n<\/ul>\n<h4 id=\"character-level-tokenization\">Character-Level Tokenization<\/h4>\n<p>The opposite extreme: split text into individual characters.<\/p>","title":"Understanding Tokenization: From Text to Integers"},{"content":"Introduction Reinforcement Learning (RL) has exploded in popularity: first in game-playing agents, and now in large language models via methods like RLHF (Reinforcement Learning from Human Feedback). These approaches don&rsquo;t just help models learn context better; they also improve reasoning by teaching them to &ldquo;think in steps.&rdquo;\nMy fascination with RL began when the GPT-3 paper was published and ChatGPT emerged as the so-called &ldquo;tool of the decade.&rdquo; I wanted to go beyond using these models: I wanted to understand how they work under the hood. That meant building RL concepts from the ground up: deriving equations, implementing toy solutions in environments like CartPole and FrozenLake, and seeing theory come alive in code.\nThis post is the first in a series where we&rsquo;ll start with foundations:\nWhat is an MDP and how does it differ from an HMM? How do rewards and value functions actually work? How can we move from knowing state values to learning optimal actions with Q-learning? And how do we scale that to Deep Q-Learning when the state space explodes? By the end, you&rsquo;ll have a baseline RL toolkit covering mathematical definitions and runnable code, and a clear picture of how these pieces fit together when building agents.\nWhy This Series? When I first encountered MDPs, I assumed they were simply an extension of Hidden Markov Models. I quickly learned this was wrong. HMMs deal with hidden states and observations, while MDPs deal with fully observable states and decision-making under uncertainty. Understanding this difference changed how I approached RL problems.\nThis blog is written in a learning-by-doing style: meaning you&rsquo;ll see the concepts, math, and code side by side, along with real-world analogies (including fraud detection examples) and small &ldquo;try-it-yourself&rdquo; prompts.\nPart 1: Foundations with MDPs (and a &ldquo;HMM aside&rdquo;) Markov Decision Process (MDP) Markov Decision Process (MDP) models an agent interacting with an environment over discrete time steps. It&rsquo;s defined by the 5-tuple $(S, A, P, R, \\gamma)$ where:\n$S$ = states $A$ = actions $P(s&rsquo;|s,a)$ = transition probability of reaching $s&rsquo;$ after taking action $a$ in state $s$ $R(s,a,s&rsquo;)$ = reward for this transition $\\gamma \\in [0,1)$ = discount factor for future rewards The Markov Property The future is conditionally independent of the past, given the present state.\nFormally: $$P(s_{t+1} \\mid s_t, a_t, s_{t-1}, \\ldots) = P(s_{t+1} \\mid s_t, a_t)$$\nWhy MDPs Matter They formalize sequential decision making: robotics, games, recommendation systems. They give a clear mathematical foundation for defining and solving RL problems via value functions, policy search, and dynamic programming. How do Markov Decision Processes differ from Hidden Markov Models HMMs deal with partial observability (you only see observations, not the actual underlying states). The context window for HMMs is technically just 1 since they&rsquo;re first-order Markov models, meaning they depend only on the current hidden state. HMM vs MDPs Aspect HMM MDP State Hidden (unobserved) Fully observed Observations Emitted from hidden states Not applicable (agent directly observes state) Actions No actions; just a generative sequence model Agent chooses actions $a$ in each state $s$ Transition Model $P(h_{t+1} \\mid h_t)$ $P(s_{t+1} \\mid s_t,a_t)$ Emission\/Reward Emission: $P(o_t \\mid h_t)$ Reward: $R(s_t,a_t,s_{t+1})$ Objective Compute likelihood or decode hidden path Maximize expected cumulative reward Algorithms Forward\/backward; Viterbi; Baum\u2013Welch (EM) Value iteration; policy iteration; Q-learning; policy gradients Use Cases Sequence labeling (speech, POS, bioinfo) Sequential decision-making (robotics, games, control) Reward Functions Definition A reward function tells you how &ldquo;good&rdquo; a single transition is. Formally:\n$$R(s,a,s&rsquo;) = \\text{expected immediate reward when you take action } a \\text{ in state } s \\text{ and end up in } s&rsquo;$$\nSymbol Meaning $s$ Current state $a$ Action taken $s'$ Next state $R(s,a,s&rsquo;)$ Reward you get for that $(s \\to s&rsquo;)$ transition Intuition In a game, you might get +10 points for eating a pellet or \u2013100 if you hit a ghost. In finance, you might receive +$5 if a trade succeeds or \u2013$2 if it fails. In fraud detection, you might get +$10 if you correctly detect fraud, -$100 if you miss fraud, -$20 for a false positive, and +$5 if you correctly detect non-fraud. State-Value Function $V^\\pi(s)$ Under a given policy $\\pi$, the value of a state $s$ is the expected, discounted sum of future rewards when you start in $s$ and follow $\\pi$:\n$$V^\\pi(s) = \\mathbb{E}_\\pi\\left[\\sum_{t=0}^{\\infty}\\gamma^t r_{t+1} \\mid S_0=s\\right]$$\n$\\gamma$ trades off immediate vs. long-term reward. High $V^\\pi(s)$ means &ldquo;good to be here under $\\pi$&rdquo; $r_{t+1} = R(S_t, A_t, S_{t+1})$ $\\mathbb{E}$ = average over all possible futures under $\\pi$ Action Value Function $Q^\\pi(s,a)$ $Q^\\pi(s, a)$ is the expected (average) discounted return if you take action $a$ in state $s$ now and then follow the policy $\\pi$ afterwards.\nWhy do we need the Action-Value function $Q(s,a)$? Short answer:\nBecause if you only know how good a state is (that&rsquo;s $V(s)$), you still don&rsquo;t know which action to take from that state without either (a) a model of the world to look ahead, or (b) evaluating every action by trial. $Q(s,a)$ tells you the expected return if you take action $a$ now in state $s$, then behave well after. That lets you pick the best action locally without a model.\nIntuition (intersection analogy) You&rsquo;re at a road intersection (state $s$). Knowing &ldquo;this intersection is promising&rdquo; (high $V(s)$) doesn&rsquo;t tell you whether to turn left or right. The thing you actually need at the decision point is: &ldquo;If I turn left right now, how good is that?&rdquo; That number is $Q(s,\\text{left})$. Likewise for right.\n$$Q^\\pi(s,a) = \\mathbb{E}_\\pi\\left[\\sum_{k=0}^{\\infty}\\gamma^k r_{t+1+k} \\mid S_t=s, A_t=a\\right]$$\nAction-Value as an Expectation (from returns to Bellman) TL;DR:\nWe turn the scary infinite return into a local recursion: &ldquo;reward now + discounted value later,&rdquo; averaged over what can happen next. This uses two facts:\nthe law of total expectation the Markov property Step 1: Start from the definition (returns view)\n$$Q^\\pi(s,a) = \\mathbb{E}_\\pi\\left[\\sum_{k=0}^{\\infty}\\gamma^k r_{t+1+k} \\mid S_t=s, A_t=a\\right]$$\nStep 2: Peel off one step\nSeparate the immediate reward from everything after:\n$$Q^\\pi(s,a) = \\mathbb{E}\\left[r_{t+1} + \\gamma G_{t+1} \\mid S_t=s, A_t=a\\right]$$\nwhere $G_{t+1} = \\sum_{k=0}^{\\infty}\\gamma^k r_{t+2+k}$ is &ldquo;the return starting next step.&rdquo;\nStep 3: Condition on the next state $s&rsquo;$ (law of total expectation)\n$$Q^\\pi(s,a) = \\mathbb{E}_{s&rsquo; \\sim P(\\cdot|s,a)}\\left[\\mathbb{E}\\left[r_{t+1} + \\gamma G_{t+1} \\mid S_t=s,A_t=a,S_{t+1}=s&rsquo;\\right]\\right]$$\nStep 4: Use the Markov property (make it local)\nGiven $(s,a,s&rsquo;)$:\nImmediate reward depends only on that transition: $\\mathbb{E}[r_{t+1}|s,a,s&rsquo;] = R(s,a,s&rsquo;)$ The future return depends only on the next state (and then following $\\pi$): $\\mathbb{E}[G_{t+1}|S_{t+1}=s&rsquo;] = V^\\pi(s&rsquo;)$ So the inner expectation becomes $R(s,a,s&rsquo;) + \\gamma V^\\pi(s&rsquo;)$, yielding:\n$$Q^\\pi(s,a) = \\mathbb{E}_{s&rsquo; \\sim P(\\cdot|s,a)}\\big[R(s,a,s&rsquo;) + \\gamma V^\\pi(s&rsquo;)\\big]$$\nStep 5: Expand $V^\\pi$ over next actions\nBy definition of the state value: $V^\\pi(s&rsquo;) = \\sum_{a&rsquo;} \\pi(a&rsquo;|s&rsquo;) Q^\\pi(s&rsquo;,a&rsquo;)$\nPutting it all together gives the Bellman expectation equation for $Q^\\pi$:\n$$\\boxed{Q^\\pi(s,a) = \\sum_{s&rsquo;} P(s&rsquo;|s,a)\\Big[R(s,a,s&rsquo;) + \\gamma \\sum_{a&rsquo;} \\pi(a&rsquo;|s&rsquo;) Q^\\pi(s&rsquo;,a&rsquo;)\\Big]}$$\nSimple toy example From state $s$, action $a$ leads to:\n$s_1$ with prob 0.7, reward 5 $s_2$ with prob 0.3, reward 0 Let $\\gamma=0.9$, and suppose $V^\\pi(s_1)=10$ and $V^\\pi(s_2)=2$. Then:\n$$\\begin{align} Q^\\pi(s,a) &amp;= 0.7(5 + 0.9 \\times 10) + 0.3(0 + 0.9 \\times 2) \\ &amp;= 0.7(14) + 0.3(1.8) \\ &amp;= 9.8 + 0.54 \\ &amp;= \\mathbf{10.34} \\end{align}$$\nIt&rsquo;s a weighted average of &ldquo;reward now + discounted value later&rdquo; over possible next states.\nQ-Learning Knowing state value is great if you also have a model of the world to look ahead. But when you don&rsquo;t, you want to know directly: How good is taking action a in state s right now? That&rsquo;s the action-value ($Q(s,a)$), and Q-learning learns it from experience with no model required.\nTabular Q-Learning: from optimality to an update you can code 1) Objective: optimal action-values $$Q^(s,a) = \\sum_{s&rsquo;} P(s&rsquo;|s,a)\\Big[R(s,a,s&rsquo;) + \\gamma \\max_{a&rsquo;} Q^(s&rsquo;,a&rsquo;)\\Big]$$\nThis is the Bellman optimality equation. If we had $Q^$, the greedy policy $\\pi^(s) = \\arg\\max_a Q^*(s,a)$ is optimal.\n2) One-step TD target (what we aim at each step) Replace the expectation over $s&rsquo;$ with a sample from the environment:\n$$y_{\\text{target}} = r + \\gamma \\max_{a&rsquo;} Q(s&rsquo;,a&rsquo;)$$\nThis is a sampled estimate of the right-hand side of Bellman optimality.\n3) Q-learning update (move toward the target) $$Q(s,a) \\leftarrow Q(s,a) + \\alpha \\Big[r + \\gamma \\max_{a&rsquo;} Q(s&rsquo;,a&rsquo;) - Q(s,a)\\Big]$$\n$\\alpha$ is the learning rate We bootstrap using our own $Q$ on $s'$ Using $\\max_{a&rsquo;}$ (rather than the next action actually taken) makes Q-learning off-policy: it learns about the greedy policy even if behavior is exploratory 4) Exploration: \u03b5-greedy behavior policy We still need to visit state-actions to learn them:\nWith probability \u03b5: take a random action (explore) Otherwise: take $\\arg\\max_a Q(s,a)$ (exploit) Typical schedule: start \u03b5 at 1.0, decay to 0.1 (or 0.01) over many episodes.\n5) Tiny numeric example (feel the TD step) Suppose at $(s,a)$ you observe:\nreward $r=1.0$, next state $s'$ current $Q(s,a)=0.50$ $\\max_{a&rsquo;} Q(s&rsquo;,a&rsquo;) = 0.80$ $\\gamma=0.9$, $\\alpha=0.5$ Target: $y = r + \\gamma \\max_{a&rsquo;} Q(s&rsquo;,a&rsquo;) = 1.0 + 0.9 \\times 0.80 = 1.72$\nUpdate: $Q_{\\text{new}}(s,a) = 0.50 + 0.5 \\times (1.72 - 0.50) = \\mathbf{1.11}$\nYou&rsquo;ve moved halfway toward the target.\n6) SARSA vs Expected SARSA vs Q-learning (quick contrast) SARSA (on-policy) uses the actual next action $a&rsquo; \\sim \\pi$: $$Q \\leftarrow Q + \\alpha[r + \\gamma Q(s&rsquo;,a&rsquo;) - Q]$$ Expected SARSA computes the average over next actions: $$Q \\leftarrow Q + \\alpha[r + \\gamma \\sum_{a&rsquo;} \\pi(a&rsquo;|s&rsquo;)Q(s&rsquo;,a&rsquo;) - Q]$$ Q-learning (off-policy) uses the max over actions: $$Q \\leftarrow Q + \\alpha[r + \\gamma \\max_{a&rsquo;} Q(s&rsquo;,a&rsquo;) - Q]$$ 7) Minimal NumPy implementation (FrozenLake, tabular) import numpy as np, gym env = gym.make(&#39;FrozenLake-v1&#39;, is_slippery=False) nS, nA = env.observation_space.n, env.action_space.n Q = np.zeros((nS, nA)) alpha, gamma = 0.8, 0.9 eps, eps_min, eps_decay = 1.0, 0.1, 0.995 episodes = 2000 def eps_greedy(s): if np.random.rand() &lt; eps: return env.action_space.sample() return np.argmax(Q[s]) for ep in range(episodes): s, done = env.reset(), False while not done: a = eps_greedy(s) s2, r, done, _ = env.step(a) target = r + (0 if done else gamma * np.max(Q[s2])) Q[s, a] += alpha * (target - Q[s, a]) s = s2 eps = max(eps_min, eps * eps_decay) print(&#34;Q-table:\\n&#34;, Q) Terminal states: if done, set the bootstrapped term to 0 (as above).\nDeep Q-Learning Q-learning works only to an extent where it is possible to keep track of states and actions at a given time. However, as we move away from simple games like tic-tac-toe to something as complex as Chess, the number of states and actions at a given time increases exponentially. At that stage, keeping track of a Q-table becomes very compute intensive, doesn&rsquo;t scale well, and is very slow. Hence, the paradigm of Deep Q-learning provides the potential to overcome this barrier.\nTabular methods break when the state space is huge. DQN replaces the table with a neural net $Q_\\theta(s,a)$ that outputs all action values from a state.\nCore ideas (why DQN works) Function approximation: $Q_\\theta(s,a)$ via a neural net Experience replay: Store $(s,a,r,s&rsquo;,\\text{done})$ transitions, train on random mini\u2011batches to break correlation Loss and targets For a batch $\\mathcal{B}$ of transitions:\n$$y_i = r_i \\quad \\text{if episode is done}$$\n$$y_i = r_i + \\gamma \\max_{a&rsquo;} Q_{\\theta^-}(s&rsquo;_i, a&rsquo;) \\quad \\text{otherwise}$$\nSquared loss (often Huber in practice):\n$$\\mathcal{L}(\\theta) = \\frac{1}{|\\mathcal{B}|}\\sum_{i \\in \\mathcal{B}} \\big( y_i - Q_\\theta(s_i, a_i) \\big)^2$$\nGradient step: $\\theta \\leftarrow \\theta - \\eta \\nabla_\\theta \\mathcal{L}(\\theta)$\nTarget network update (periodic hard update every $C$ steps): $\\theta^- \\leftarrow \\theta$\n(or soft update: $\\theta^- \\leftarrow \\tau \\theta + (1-\\tau)\\theta^-$)\nDouble DQN (reduces overestimation bias) Use the online net to pick the action and the target net to evaluate it:\n$$y_i = r_i + \\gamma Q_{\\theta^-}(s&rsquo;_i, a^*)$$\nwhere $a^* = \\text{argmax}_{a&rsquo;} Q_\\theta(s&rsquo;_i,a&rsquo;)$\nCode Example for Deep Q-Learning For a complete implementation example, check out this GitHub gist with a working DQN on CartPole.\nWhat&rsquo;s Next? In the next post, we&rsquo;ll dive deeper into:\nPolicy Gradient methods (REINFORCE, Actor-Critic) Advanced DQN variants (Dueling DQN, Prioritized Experience Replay) Real-world applications in fraud detection and recommendation systems Stay tuned for more hands-on RL content! \ud83d\ude80\nHave questions or thoughts about this post? Feel free to reach out - I&rsquo;d love to discuss RL concepts and applications!\n","permalink":"https:\/\/rajathpatel23.github.io\/posts\/reinforcement-learning-foundations\/","summary":"<h2 id=\"introduction\">Introduction<\/h2>\n<p>Reinforcement Learning (RL) has exploded in popularity: first in game-playing agents, and now in large language models via methods like RLHF (Reinforcement Learning from Human Feedback). These approaches don&rsquo;t just help models learn context better; they also improve reasoning by teaching them to &ldquo;think in steps.&rdquo;<\/p>\n<p>My fascination with RL began when the GPT-3 paper was published and ChatGPT emerged as the so-called &ldquo;tool of the decade.&rdquo; I wanted to go beyond using these models: I wanted to understand <em>how<\/em> they work under the hood. That meant building RL concepts from the ground up: deriving equations, implementing toy solutions in environments like CartPole and FrozenLake, and seeing theory come alive in code.<\/p>","title":"Reinforcement Learning Foundations: From MDPs to Deep Q-Learning"}]