<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Himanshu on Medium]]></title>
        <description><![CDATA[Stories by Himanshu on Medium]]></description>
        <link>https://medium.com/@himanshunakrani0?source=rss-f1ad9ce503ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ELB_6dao40_WqbO8c8UOOg.png</url>
            <title>Stories by Himanshu on Medium</title>
            <link>https://medium.com/@himanshunakrani0?source=rss-f1ad9ce503ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:04:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@himanshunakrani0/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I post-trained a 1B model with SFT + GRPO for $0 (Part 2 of 2)]]></title>
            <link>https://generativeai.pub/how-i-post-trained-a-1b-model-with-sft-grpo-for-0-part-2-of-2-b283dff7d996?source=rss-f1ad9ce503ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/b283dff7d996</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Himanshu]]></dc:creator>
            <pubDate>Thu, 28 May 2026 23:03:14 GMT</pubDate>
            <atom:updated>2026-05-30T02:46:40.525Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong><em>Supervised fine-tuning, GRPO reinforcement learning across three different GPUs, and the full $0-cash credit-stacking story.</em></strong></h4><p>In <a href="https://medium.com/@himanshunakrani0/how-i-pretrained-a-1b-language-model-for-0-part-1-of-2-a57063b91fd6">[Part 1]</a> I walked through pretraining: tokenizer, data, TPU run, and the painful Orbax → HuggingFace conversion. At the end of that I had a 1.12B base model that could predict tokens but didn’t know how to be helpful, didn’t know to put answers after <em>&lt;think&gt;</em> tags, and would happily fall into infinite LaTeX loops on hard prompts.</p><p>This is <strong>Part 2</strong>: SFT, GRPO, evaluation, and how the whole 40-day project cost $0 out of pocket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OclOrDvRObjAnMSF3cbv7w.png" /></figure><h3><strong>Step 5: SFT — teaching it to follow instructions</strong></h3><p>The base model knows how to predict the next token. It doesn’t know how to be helpful. SFT (Supervised Fine-Tuning) is where you show it labeled examples of “user asks → model answers correctly” and let it imitate.</p><p>I ran SFT on an <strong>AMD MI300X</strong> (192GB VRAM, ~$2/hour list). I got the time through the <a href="https://www.amd.com/en/developer/resources/cloud-access/amd-developer-cloud.html">AMD Developer Cloud</a> program — they hand out $100 in free MI300X credits if you apply. HuggingFace Transformers + TRL’s <em>SFTTrainer</em>.</p><p><strong>The data flow:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Yveef_gblbQMWDK8N4S7w.png" /></figure><p>The actual mix was two stages: Stage 1 = 52k Alpaca examples for a conversational prior (the curriculum mistake — see point 3 below), then Stage 2 = ~662k math examples = MetaMathQA (~395k) + MathInstruct (~260k) + GSM8K train (~7.5k). ChatML-wrapped, two epochs on stage 2.</p><h4><strong>The config that worked (mostly)</strong></h4><pre>from trl import SFTConfig, SFTTrainer<br><br>config = SFTConfig(<br>    output_dir=&quot;./sft-out&quot;,<br>    num_train_epochs=2,              # I&#39;d use 5-10 next time<br>    per_device_train_batch_size=4,<br>    gradient_accumulation_steps=16,  # effective batch 64<br>    learning_rate=2e-5,              # I&#39;d use 5e-6 next time<br>    lr_scheduler_type=&quot;cosine&quot;,<br>    warmup_ratio=0.03,<br>    bf16=True,<br>    max_seq_length=2048,<br>    dataset_text_field=&quot;text&quot;,<br>    save_strategy=&quot;epoch&quot;,<br>    logging_steps=10,<br>    # The flag I should have set:<br>    # assistant_only_loss=True,<br>)</pre><h4><strong>The three things I’d change</strong></h4><p><strong>1. Use <em>assistant_only_loss=True</em>.</strong> This is the single most important SFT flag. Without it, <em>SFTTrainer</em> computes loss over the <em>entire</em> sequence — system prompt, user question, assistant answer, all of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nc83LmiWsDqbwJKfMZxFzQ.png" /></figure><p>More than half of every gradient was wasted on memorizing my own system prompt. One flag. Three to five percentage points of efficiency.</p><p><strong>2. Initialize new token embeddings properly.</strong> When you <em>model.resize_token_embeddings()</em> to add <strong><em>&lt;think&gt;</em></strong> and <strong><em>&lt;/think&gt;</em></strong>, HF initializes the new rows from a small random normal. That’s enough to perturb the LM head and regress your general benchmarks. ARC-Easy crashed 29.9% → 25.5% in my SFT. Classic symptom.</p><p>The <a href="https://nlp.stanford.edu/~johnhew/vocab-expansion.html">Hewitt 2021 fix</a> — initialize new rows to the mean of the existing embedding/output matrices:</p><pre>import torch<br>orig_vocab_size = model.config.vocab_size<br>model.resize_token_embeddings(len(tokenizer))<br>with torch.no_grad():<br>    emb  = model.get_input_embeddings().weight<br>    head = model.get_output_embeddings().weight<br>    mean_in  = emb[:orig_vocab_size].mean(dim=0)<br>    mean_out = head[:orig_vocab_size].mean(dim=0)<br>    for tid in tokenizer.convert_tokens_to_ids([&quot;&lt;think&gt;&quot;, &quot;&lt;/think&gt;&quot;]):<br>        emb[tid]  = mean_in<br>        head[tid] = mean_out</pre><p>Three lines. Saves you a 4-percentage-point regression on general benchmarks.</p><p><strong>3. Math first, chat last.</strong> I did Alpaca first, then math, on the intuition that “easy chat warms up the model, hard reasoning specializes it.” The DeepSeek-R1 and Tulu-3 reports convinced me afterwards that this is backwards: when reasoning is the goal, train math hard <em>first</em> so the chain-of-thought circuits get the bulk of the gradient, then polish with broad chat to keep helpfulness intact. Doing chat first dilutes the reasoning signal and you spend the math epochs partially undoing it. Or just skip the curriculum entirely with a single-stage mix like 70% NuminaMath-CoT + 15% OpenMathInstruct-2 + 10% GSM8K + 5% Tulu-3.</p><p>SFT took about 15 hours on the MI300X across 660k examples × 2 epochs. Bill: $0 out of pocket — covered by the AMD Developer Cloud credits.</p><h3><strong>Step 6: GRPO — when RL gets weird</strong></h3><p>GRPO (Group Relative Policy Optimization) is the simplest “real” RL algorithm for LLMs. The idea is dead simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ug5m0s9FbTn12WuO2QmlPg.png" /></figure><p>That’s it. No value network. No critic. Just rollouts and group-relative advantage.</p><p><strong>Why GRPO, not DPO?</strong> DPO needs preference <em>pairs</em> — “completion A is better than completion B.” With ~1% correctness in my SFT model, almost every pair would be “rejected vs. rejected.” No signal. GRPO sidesteps this by working with absolute rewards.</p><h4><strong>My GRPO config</strong></h4><pre>from trl import GRPOConfig, GRPOTrainer<br><br>config = GRPOConfig(<br>    output_dir=&quot;./grpo-out&quot;,<br>    num_train_epochs=3,<br>    per_device_train_batch_size=2,<br>    gradient_accumulation_steps=4,<br>    learning_rate=5e-6,<br>    lr_scheduler_type=&quot;cosine&quot;,<br>    warmup_ratio=0.05,<br>    beta=0.01,                    # KL coefficient (anchors to SFT policy)<br>    num_generations=8,            # group size G<br>    max_completion_length=512,    # I&#39;d raise to 2048<br>    temperature=0.9,<br>    bf16=True,<br>)<br><br>trainer = GRPOTrainer(<br>    model=&quot;./hf_sft_model&quot;,<br>    args=config,<br>    train_dataset=dataset,<br>    reward_funcs=[correctness_reward_func, format_reward_func,<br>                  repetition_penalty_func],<br>    tokenizer=tokenizer,<br>)<br>trainer.train()</pre><h4><strong>Three things you have to add that the tutorial won’t tell you</strong></h4><p><strong>1. AST-based correctness checking.</strong> Don’t string-match math answers. Use SymPy via <em>math_verify</em> so <em>1/2</em>, <em>0.5</em>, and <em>2/4</em> all count as equal:</p><pre>from math_verify import parse, verify<br><br>def correctness_reward_func(prompts, completions, answer, **kwargs):<br>    rewards = []<br>    for completion, gt in zip(completions, answer):<br>        if &quot;&lt;/think&gt;&quot; in completion:<br>            pred = completion.split(&quot;&lt;/think&gt;&quot;, 1)[1].strip()<br>        else:<br>            pred = completion.strip()<br>        try:<br>            rewards.append(1.0 if verify(parse(gt), parse(pred)) else 0.0)<br>        except Exception:<br>            rewards.append(0.0)<br>    return rewards</pre><p><strong>2. Tokenizer decode monkey-patch.</strong> This one took me hours to figure out. TRL internally calls <em>tokenizer.decode(…, skip_special_tokens=True)</em> before passing text to your reward functions. That strips <strong><em>&lt;think&gt;</em></strong> and <strong><em>&lt;/think&gt;</em></strong> along with everything else, so your format-reward function never sees them and always returns 0.</p><pre>_orig_decode = tokenizer.decode<br><br>def patched_decode(self, token_ids, **kwargs):<br>    kwargs[&quot;skip_special_tokens&quot;] = False<br>    text = _orig_decode(token_ids, **kwargs)<br>    # Strip only ChatML control tokens, preserve reasoning tags<br>    for t in [&quot;&lt;|im_start|&gt;&quot;, &quot;&lt;|im_end|&gt;&quot;, &quot;&lt;|bos|&gt;&quot;, &quot;&lt;|eos|&gt;&quot;, &quot;&lt;|pad|&gt;&quot;]:<br>        text = text.replace(t, &quot;&quot;)<br>    return text<br><br>tokenizer.decode = patched_decode.__get__(tokenizer)</pre><p><strong>3. N-gram repetition penalty.</strong> When the model collapses into a loop, the unique-3-gram ratio drops below 0.2. I scale a penalty up to -1.5 in those cases. Across 22,419 training steps it never fired — but I’d added it after watching the post-SFT model fall into infinite LaTeX loops on hard prompts (think `e^x + e^x + e^x …` until it hits max tokens — a classic absorbing-Markov mode collapse on a low-entropy pretraining budget). Cheap insurance against the same mode reappearing under RL pressure. Probably overkill in retrospect, but I’d add it again.</p><h4><strong>The reward-shape mistake I’d undo</strong></h4><p>My total reward was additive: `correctness + format + repetition`. The problem is that with correctness rare (~1.4%) and format common (~50%), format dominated the gradient by <em>~35×</em>. The model’s rational optimum was: “produce a valid <strong><em>&lt;think&gt;</em></strong> shell with any content inside.” Exactly the reward-hacking behavior I saw in the outputs.</p><p><strong>The fix is to gate, not sum:</strong></p><pre># What I did (wrong):<br>total_reward = correctness + format + repetition<br><br># What I should have done:<br>total_reward = format_pass * (1.0 if correct else -0.1) + repetition_penalty</pre><p>Format becomes a <em>precondition</em> for any positive reward, not a competing objective. No format → 0. Bad answer → small negative. Correct → +1.</p><h4><strong>The infrastructure odyssey</strong></h4><p>GRPO ran across <strong>three different GPUs</strong> because of quota issues. The resume-from-checkpoint flow worked perfectly through all of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYoFDzOfRHvsXcg8sDH_rg.png" /></figure><p>Total wall time: 13h 32m across the three machines. The two MI300X stints came out of the AMD Developer Cloud credit, and the L4 finish came out of free Google Cloud developer credits. Cash bill: $0.</p><h3><strong>Step 7: evaluate honestly</strong></h3><p>For evaluation I used a small A100 instance on <strong>Thunder Compute</strong>, paid out of $25 of free trial credit they hand to new accounts. lm-evaluation-harness is light enough that this is plenty.</p><pre>lm_eval --model hf \<br>    --model_args pretrained=./hf_grpo_model,dtype=bfloat16 \<br>    --tasks gsm8k,minerva_math,arc_easy,arc_challenge,hellaswag,mmlu \<br>    --batch_size 8 \<br>    --apply_chat_template \<br>    --output_path ./eval_results</pre><p><strong>The flag everyone misses:</strong> — <em>apply_chat_template</em>. If your model was trained with ChatML, the default lm-eval-harness raw few-shot text is out-of-distribution for it. I lost ~1pp on the SFT GSM8K score until I noticed.</p><p>For more interesting eval, run <strong>self-consistency</strong> at inference time — sample N=32 completions at temperature 0.7, take the majority-vote final answer. For small models on math this is typically +5–15pp essentially free.</p><pre>from collections import Counter<br><br>def cons_at_n(model, tokenizer, prompt, n=32, temperature=0.7):<br>    answers = []<br>    for _ in range(n):<br>        out = model.generate(<br>            **tokenizer(prompt, return_tensors=&quot;pt&quot;).to(model.device),<br>            do_sample=True, temperature=temperature, max_new_tokens=512,<br>        )<br>        answers.append(extract_answer(tokenizer.decode(out[0])))<br>    return Counter(answers).most_common(1)[0][0]</pre><h3><strong>What it actually cost</strong></h3><p>The honest answer: <strong>$0 out of pocket.</strong> The honest-with-an-asterisk answer: at list pricing, this would have run roughly ~$15k spot, almost all of it pretraining.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8B9khao1qj9pD_qpNCUWtg.png" /></figure><p>Pretraining is ~99% of what the bill <strong><em>would</em></strong> have been. Everything else is rounding.</p><p>None of these programs are secret. They’re public, the applications are short, and they’re explicitly meant for this kind of work:</p><ul><li><a href="https://sites.research.google/trc/about/"><strong>Google TPU Research Cloud</strong></a> — free TPU time for open research. Apply with a one-page proposal.</li><li><a href="https://www.amd.com/en/developer/resources/cloud-access/amd-developer-cloud.html"><strong>AMD Developer Cloud</strong></a> — $100 of MI300X credits to anyone with a developer account.</li><li><a href="https://cloud.google.com/free"><strong>Google Cloud free tier + new-user credits</strong></a> — what funded the L4 hop.</li><li><a href="https://www.vultr.com/promo/"><strong>Vultr free trial</strong></a> — $150 credit for new accounts.</li><li><a href="https://www.thundercompute.com/"><strong>Thunder Compute</strong></a> — $25 trial credit, enough for an evaluation pass.</li></ul><h3><strong>What I’d tell someone starting this from scratch</strong></h3><p>The numbered list version, in priority order — the first five are from <a href="https://medium.com/@himanshunakrani0/how-i-pretrained-a-1b-language-model-for-0-part-1-of-2-a57063b91fd6">[Part 1]</a>(#); the post-training ones are below:</p><p>6.<strong> Use <em>assistant_only_loss=True</em> in SFT.</strong> Just do it. It’s one flag.</p><p>7. <strong>Mean-init new token embeddings</strong>, not random. Three lines of code. Saves you a 4pp regression.</p><p>8. <strong>Gate your RL rewards, don’t sum them</strong>. Format as precondition, not competing objective.</p><p>9. <strong>Have a clean checkpoint resume path</strong> between cloud providers. You’ll need it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MxyFlgr5VkpAPY-uBfeeA.png" /></figure><p>The model I shipped isn’t a strong math model — 57B tokens just isn’t enough at this parameter count, and the tokenizer caps arithmetic. But the <em>pipeline</em> is solid, and most of the lessons apply at any scale.</p><p>Everything is open source: <a href="https://github.com/himanshu-nakrani/TinyMathReason-1B">github.com/himanshu-nakrani/TinyMathReason-1B</a>. The model weights are on Hugging Face under <a href="https://huggingface.co/himanshunakrani9">himanshunakrani9</a>.</p><p>The two files that hold most of the real decisions in this half of the pipeline:</p><ul><li>src/sft/train_sft.py — SFT pipeline</li><li><em>src/dpo/train_grpo.py</em> — the hardened GRPO setup, monkey-patches and all</li></ul><p>That’s the playbook. Now go build something with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*p1sdqV6eJKRXLK-p.png" /></figure><p>This story is published on <a href="https://generativeai.pub/">Generative AI</a>. Connect with us on <a href="https://www.linkedin.com/company/generative-ai-publication">LinkedIn</a> and follow <a href="https://www.zeniteq.com/">Zeniteq</a> to stay in the loop with the latest AI stories.</p><p>Subscribe to our <a href="https://www.generativeaipub.com/">newsletter</a> and <a href="https://www.youtube.com/@generativeaipub">YouTube</a> channel to stay updated with the latest news and updates on generative AI. Let’s shape the future of AI together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*5Roa3kdXnyQvz6uJ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b283dff7d996" width="1" height="1" alt=""><hr><p><a href="https://generativeai.pub/how-i-post-trained-a-1b-model-with-sft-grpo-for-0-part-2-of-2-b283dff7d996">How I post-trained a 1B model with SFT + GRPO for $0 (Part 2 of 2)</a> was originally published in <a href="https://generativeai.pub/">Generative AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I pretrained a 1B language model for $0 (Part 1 of 2)]]></title>
            <link>https://generativeai.pub/how-i-pretrained-a-1b-language-model-for-0-part-1-of-2-a57063b91fd6?source=rss-f1ad9ce503ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/a57063b91fd6</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[pretrained-language-model]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Himanshu]]></dc:creator>
            <pubDate>Thu, 28 May 2026 23:01:20 GMT</pubDate>
            <atom:updated>2026-05-30T02:46:58.220Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong><em>Tokenizer, data, TPU pretraining, and the five-day fight to get the checkpoint into HuggingFace.</em></strong></h4><p>I built a 1B language model — TinyMathReason-1B — from scratch. Tokenizer up through GRPO reinforcement learning. The final model gets 2.2% on GSM8K, which is roughly in the band peer 1B-class models land in (TinyLlama-1.1B-Chat, Pythia-1B), and TinyLlama needed ~50× more pretraining tokens to get there. The point of this post isn’t the score; it’s the pipeline, and the half-dozen places along it where a wrong default or a silent bug can quietly cost you a week.</p><p>This is <strong>Part 1 of 2</strong>. It covers the pretraining half — tokenizer, data, TPU run, and the painful Orbax → HuggingFace conversion. <a href="https://medium.com/@himanshunakrani0/how-i-post-trained-a-1b-model-with-sft-grpo-for-0-part-2-of-2-b283dff7d996">[Part 2]</a> covers SFT, GRPO, and evaluation.</p><p>Here’s the half of the pipeline this post covers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6hnK8H15c_ZkDYWHBZOKQ.png" /></figure><p>About three weeks of wall time, and<strong> $0 out of pocket</strong>. TPU time came from Google’s TPU Research Cloud; CPU data work came from a Vultr trial credit. At list prices this half of the pipeline would have run ~$15k spot (~$50k on-demand). Full cost breakdown is in Part 2.</p><h3><strong>Step 0: pick the architecture</strong></h3><p>Before I touched a keyboard I spent two days writing down four things on one page: target architecture, data sources, infra budget, and how I’d decide the run had succeeded. That’s it — no Gantt chart, no design doc. The point isn’t ceremony; it’s that you can write a tokenizer in an afternoon but the consequences of that tokenizer follow you for weeks. Cheap to plan, expensive to redo.</p><p>I went with a Llama-2 lookalike. Here’s the shape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*idjN9nchQg6EZ6t871DjTA.png" /></figure><p>The diagram covers the standard choices. The three I want to call out, because they’re the ones I’d actually defend in a code review:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ipwxf9jDZjh13uwJw64YQ.png" /></figure><p><strong>Why so similar to TinyLlama?</strong> I wanted my <em>pipeline</em> to be the variable I was testing, not my architecture. If something went wrong I needed to be able to say “it’s not the architecture” with confidence.</p><p>The exact final parameter count: <strong><em>1,123,117,056</em></strong>. I computed this by hand before writing any code. If you don’t, you’ll be staring at a checkpoint six weeks from now wondering why the embedding shape doesn’t match.</p><h3><strong>Step 1: train the tokenizer</strong></h3><p>The tokenizer is what turns text into integers the model can consume. Sounds simple, hides traps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTpjhujXGp9PgrQ81ONGTg.png" /></figure><p>A BPE tokenizer learns to merge frequently-co-occurring character sequences into single tokens. “the” becomes one token. “ing” becomes one token. For a math model, the question is: what happens to numbers?</p><p>Here’s the code I ran:</p><pre>from tokenizers import ByteLevelBPETokenizer<br><br>tokenizer = ByteLevelBPETokenizer()<br>tokenizer.train(<br>    files=[...],<br>    vocab_size=32_000,<br>    min_frequency=2,<br>    special_tokens=[&quot;&lt;|bos|&gt;&quot;, &quot;&lt;|eos|&gt;&quot;, &quot;&lt;|pad|&gt;&quot;, &quot;&lt;|unk|&gt;&quot;,<br>                    &quot;&lt;|im_start|&gt;&quot;, &quot;&lt;|im_end|&gt;&quot;]<br>)</pre><p>Reserved <em>&lt;|im_start|&gt;</em> and <em>&lt;|im_end|&gt;</em> for ChatML templating, and saved <em>&lt;think&gt;</em> / <em>&lt;/think&gt;</em> for adding later during SFT.</p><p><strong>Here’s the test I should have run before training:</strong></p><pre>for s in [&quot;1234567&quot;, &quot;382 + 491 = 873&quot;, &quot;1/2 + 3/4&quot;]:<br>    print(s, &quot;-&gt;&quot;, tokenizer.encode(s).tokens)</pre><p>If multi-digit numbers stay as single tokens or split at unpredictable boundaries, fix it now. The fix is either:</p><ul><li><strong>Pre-split every digit</strong> (Llama-3, DeepSeek-Math do this). Now “42” becomes `[“4”, “2”]` always.</li><li><strong>Use a much larger vocab</strong> (Qwen2.5 uses 151k). With more vocabulary slots the merges become stable.</li></ul><p>I did neither, and the consequences cascaded through every later stage. My audit later showed “100” → 1 token, “2024” → 2 tokens, “1234567” → 3 chunks at arbitrary boundaries. Inconsistent chunking is the <em>worst</em> case for arithmetic. Don’t ship this.</p><h3><strong>Step 2: build the data pipeline</strong></h3><p>The boring stage nobody writes about. Roughly a third of the total work.</p><p>I rented two Vultr c2-standard-30 CPU instances ($1.50/hour each, paid out of $150 in trial credits Vultr gives new accounts) and ran the pipeline in parallel. Six stages, six Python scripts: download → clean/filter → mix → tokenize-and-pack → shard → upload to GCS.</p><h4><strong>The corpus mix (and a happy accident)</strong></h4><p>The mix I actually ended up training on:</p><ul><li><strong>FineWeb-Edu: 40% </strong>— general educational web text</li><li><strong>OpenWebMath: 35%</strong> — the high-quality math web corpus</li><li><strong>MathPile: 15%</strong> — curated math textbooks and paper</li><li><strong>Stack-Edu: 10%</strong> — educational code</li><li><strong>Proof-Pile-2: 15%</strong>—<strong> <em>planned, but never downloaded</em></strong></li></ul><p>I originally planned a 5-dataset mix including Proof-Pile-2. Due to an oversight in the download script, it was never fetched. My mixing script auto-normalized probabilities based on folders present on disk, which concentrated my high-quality math web data to <strong>35% OpenWebMath</strong> (up from a planned 30%) — a happy accident, not a happy plan.</p><p>A Makefile drives the whole pipeline. <em>make all</em> end-to-end. The output was ~1000 shards averaging 50MB compressed each, totaling<strong> ~57 billion tokens</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwAtu1F9zIJSk3-6Iod_4Q.png" /></figure><h4><strong>Two things I’d change next time</strong></h4><p><strong>Document-boundary attention masks.</strong> I packed sequences by concatenating documents with an EOS token between them. The problem is that vanilla attention can still flow <em>across</em> documents inside a single packed sequence. For math, that’s especially bad — each problem should be self-contained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Lox4DYT4cnjT6yRXDoZfg.png" /></figure><p>Fix: use FlashAttention’s varlen mode, or emit segment IDs and add a block-diagonal attention mask.</p><p><strong>Real MinHash, not exact-string dedup.</strong> I claimed MinHash in my docs. The code shipped <em>hash(text)</em> exact-string dedup. Result: lots of near-duplicate web pages slipped through. The <em>datasketch</em> library makes real MinHash trivial; I just didn’t bother.</p><p>The expensive part of data work isn’t compute. It’s your future self debugging your past self’s shortcuts.</p><h3><strong>Step 3: TPU pretraining</strong></h3><blockquote><strong>If you read nothing else in this section, read this.</strong> Two flags in maxtext_config.yml are the difference between a working 1B run and a week of wasted compute:</blockquote><blockquote><strong>scan_layers: False</strong> — True is faster but in the MaxText/NNX combo I was on it silently produced checkpoints with <strong>zero transformer layers</strong>. I lost a week to this.</blockquote><blockquote><strong>per_device_batch_size: 2 </strong>— <strong>8</strong> triggers XLA host-RAM allocations large enough to OOM the host (not the HBM) during compilation.</blockquote><p>This is the part that <strong><em>would</em></strong> cost real money. I trained on a TPU v4–64 - 64 chips spread across 8 host VMs — using the preemptible queue that TRC allocations run on. About a week of compute, ~10 days of wall time after preemption restarts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPcEvcRI9hSuahQ3OpyaqQ.png" /></figure><h4><strong>Setup: the parts they don’t put in the tutorial</strong></h4><p>I wrote <em>scripts/setup_tpu.sh</em> to do everything on every worker:</p><ol><li>Install Python 3.12 (MaxText needs it; the default 3.10 segfaults instantly)</li><li>Create a <em>venv312</em> virtualenv per worker</li><li>Clone MaxText, run their `setup.sh`</li><li>Apply two <strong>critical</strong> compatibility shims:</li></ol><ul><li>Alias <em>jax.Ref → typing.Any</em> (JAX 0.6.2 removed <em>jax.Ref</em>, MaxText still imports it)</li><li>Register a <em>MetaPathFinder</em> that spoofs Google-internal Pallas modules, so <em>from jax.experimental.pallas.ops.tpu.splash_attention import … </em>succeeds without crashing on the public JAX</li></ul><p>The Pallas thing in particular ate me alive. Python 3.12’s strict import system wouldn’t let me stub these modules with simple `MagicMock`. The fix is a proper `MetaPathFinder` subclass that returns a real-looking module spec.</p><h4><strong>The actual config</strong></h4><p><em>src/train/maxtext_config.yml</em>:</p><pre>model_name: tinymath-1b<br><br># Architecture<br>base_emb_dim: 2048<br>base_num_query_heads: 16<br>base_num_kv_heads: 4<br>base_mlp_dim: 5632<br>base_num_decoder_layers: 22<br>head_dim: 128<br>vocab_size: 32768          # padded for FSDP alignment<br>max_target_length: 4096<br><br># The flags that mattered most<br>per_device_batch_size: 2   # 8 OOMs host RAM during compile<br>pure_nnx_decoder: True<br>scan_layers: False         # True silently drops all layers!<br><br># Optimizer<br>learning_rate: 3.0e-4<br>adam_b1: 0.9<br>adam_b2: 0.95<br>adam_weight_decay: 0.1<br>warmup_steps_fraction: 0.0066<br>cosine_learning_rate_final_fraction: 0.1<br>steps: 54363</pre><p>Expanding on the two flags from the callout above:</p><ul><li><strong><em>scan_layers: False</em></strong> — <strong><em>True</em></strong> is faster, but in my setup (MaxText `main` ~May 2026, JAX/jaxlib 0.6.2, `pure_nnx_decoder: True`) it silently produced checkpoints with zero transformer layers. Worth re-checking on newer MaxText, but until you’ve verified your layers actually got serialized, leave it `False`.</li><li><strong><em>per_device_batch_size: 2</em></strong> — On the same stack, XLA compilation with batch=8 wanted <em>&gt;300GB of host RAM</em> (not HBM, host RAM). Batch=2 fits comfortably and gives an effective batch of 64 sequences × 4096 tokens = <strong>~262k tokens/step</strong>.</li></ul><h4><strong>Launching the run</strong></h4><pre>gcloud compute tpus tpu-vm ssh tinymath-tpu \<br>  --worker=all --zone=us-central2-b \<br>  --command=&quot;cd ~/maxtext &amp;&amp; source ~/venv312/bin/activate &amp;&amp; \<br>             python MaxText/train.py MaxText/configs/tinymath_1b.yml \<br>                    run_name=tinymath-1b-prod-run11&quot;</pre><p><em>— worker=all</em> is the magic word. It runs the command on every host in parallel, which is what you need to bring up the JAX distributed mesh.</p><h4><strong>Handling preemption</strong></h4><p>Spot TPUs get preempted. A lot. I ran<em> src/train/preemption_handler.py</em> in the background — it polls the GCP metadata server for preemption notices and logs them. MaxText’s built-in checkpointing handles the actual resume.</p><p>If a worker reboots while the others don’t, the JAX mesh collapses with <em>SSH 255</em> errors. The fix is a <em>rolling reboot of all 8 hosts followed by a 5-minute sync wait</em> so they all come up at nearly identical uptimes. I have a Makefile target for it now.</p><h4><strong>What came out</strong></h4><ul><li><strong>Throughput</strong>: ~8,900 tokens/sec/chip, ~66 TFLOP/s/device</li><li><strong>Total tokens:</strong> ~57 billion</li><li><strong>Final loss:</strong> ~2.6 (stable convergence)</li><li><strong>Bill</strong>: $0 out of pocket. At list/spot pricing this would have been ~$15k spot (~$50k on-demand).</li></ul><h3><strong>Step 4: convert the checkpoint to HuggingFace</strong></h3><p>This was the single most technically demanding part of the project. I budgeted a day. It took five.</p><p>MaxText saves checkpoints in <strong>Orbax</strong> format — a JAX-native serialization with arrays stored as <strong>Zarr</strong> chunks in GCS. HuggingFace wants <strong>safetensors</strong> in PyTorch tensor layout. These aren’t just different file formats. They’re different <em>tensor layouts</em> with different scaling conventions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcCBcNWFMOGELNB8BZWUcQ.png" /></figure><h4><strong>Write the inspector first</strong></h4><p>This is the single most important piece of advice in this whole post. Write the inspector before you write the converter. You will iterate on the converter 5–10 times. Each iteration is bearable if you can see exactly what’s in the source checkpoint.</p><p><em>inspect_checkpoint.py</em>:</p><pre>from orbax.checkpoint import PyTreeCheckpointer<br><br>ckpt = PyTreeCheckpointer().restore(checkpoint_dir)<br><br>def walk(obj, prefix=&quot;&quot;):<br>    if hasattr(obj, &quot;shape&quot;):<br>        print(f&quot;{prefix}: shape={obj.shape}, dtype={obj.dtype}&quot;)<br>    elif isinstance(obj, dict):<br>        for k, v in obj.items():<br>            walk(v, f&quot;{prefix}/{k}&quot;)<br><br>walk(ckpt)</pre><p>That’s the whole thing. Output looks like:</p><pre>/params/decoder/layers/self_attention/query/kernel: shape=(22, 2048, 16, 128)<br>/params/decoder/layers/self_attention/key/kernel:   shape=(22, 2048, 4, 128)<br>/params/decoder/embedder/embedding:                 shape=(32768, 2048)</pre><p>Now you can see exactly what’s in there. Without it you’re debugging blind.</p><h4><strong>The five bugs in the converter</strong></h4><p>Remember the “5 days” in the pipeline diagram? Here’s where they went. In rough order of how long they took me to find:</p><p><strong>1. Vocab padding.</strong> MaxText padded my 32k vocab to 32,768 for FSDP alignment. HF needs `vocab_size=32768` explicitly. Easy bug — fails loudly.</p><p><strong>2. Query scaling.</strong> MaxText bakes the <em>1/√head_dim</em> attention scaling <em>into</em> the query weights at save time. HF applies it at runtime. So when you load MaxText Q weights into an HF model, the scaling gets applied twice. Fix:</p><pre>import math<br>q_weight = orbax_q_kernel * math.sqrt(head_dim)</pre><p><strong>3. GQA tensor splitting.</strong> MaxText stores Q, K, V as stacked tensors with the layer index as a dimension. The shapes differ between Q (16 heads) and KV (4 heads). Splitting them correctly is just careful slicing, but I got it wrong three times before I got it right.</p><p><strong>4. RoPE interleaving</strong>. This is the bug that produces eerily convincing nonsense. MaxText and HuggingFace use different interleaving orders for rotary position embeddings. The model still generates fluent-looking English, but the meaning is gone. The fix is a permutation:</p><pre>def maxtext_to_hf_rope_perm(w, head_dim):<br>    w = w.reshape(-1, head_dim)<br>    perm = list(range(0, head_dim, 2)) + list(range(1, head_dim, 2))<br>    return w[:, perm].reshape(w.shape[0], head_dim)</pre><p>If your converted model outputs grammatical word salad, this is almost certainly it.</p><p><strong>5. Tokenizer config.</strong> My<em> tokenizer_config.json</em> had ”tokenizer_class”: “TokenizersBackend”, which isn’t a real class. <em>AutoTokenizer</em> was failing <em>silently</em>. Change it to ”PreTrainedTokenizerFast”.</p><h4><strong>Running the conversion</strong></h4><p>You don’t need a GPU. CPU with ~8GB RAM is plenty. Then verify with a forward pass — this is the moment of truth:</p><pre>from transformers import AutoModelForCausalLM, AutoTokenizer<br>model = AutoModelForCausalLM.from_pretrained(&quot;./hf_1b_model&quot;, torch_dtype=&quot;bfloat16&quot;)<br>tok = AutoTokenizer.from_pretrained(&quot;./hf_1b_model&quot;)<br>out = model.generate(**tok(&quot;The square root of 16 is&quot;, return_tensors=&quot;pt&quot;),<br>                     max_new_tokens=20)<br>print(tok.decode(out[0]))</pre><p>Fluent-looking text means your conversion is structurally correct. Garbled bytes mean it’s not. Word salad in correct English means RoPE.</p><h3><strong>What’s next</strong></h3><p>At this point you have a base model that can predict tokens. It doesn’t know how to be helpful, it doesn’t know to put answers after <em>&lt;think&gt;</em> tags, and it’ll happily fall into infinite LaTeX loops on hard prompts. That’s all post-training, and that’s <a href="https://medium.com/@himanshunakrani0/how-i-post-trained-a-1b-model-with-sft-grpo-for-0-part-2-of-2-b283dff7d996">[Part 2]</a>: SFT, GRPO, evaluation, the full cost breakdown across all five free-credit programs I stacked, and the priority-ordered list of lessons I’d actually pass on.</p><h4><strong>Lessons from pretraining alone</strong></h4><p>1. <strong>Architecture: copy a proven one.</strong> TinyLlama or Llama-3.2 shape. Don’t innovate here.</p><p>2. <strong>Audit your tokenizer before pretraining</strong>. Especially digit behavior. Cheapest decision to get right, most expensive to fix later.</p><p>3. <strong>Treat your data pipeline like real software.</strong> Tests, logs, sampled outputs. The README/code gap is real and you will pay for it.</p><p>4.<strong> Read MaxText (or whatever) end-to-end</strong> before you launch the first multi-day training run — even on free credits, your time is the limited resource. Find the config bugs in the documentation, not in your checkpoint.</p><p>5. <strong>Write the checkpoint inspector before the checkpoint converter</strong>. You’ll iterate the converter 5–10 times. Each iteration is bearable if you can see the source.</p><p>Everything is open source:<strong><em> </em></strong><a href="https://github.com/himanshu-nakrani/TinyMathReason-1B"><em>TinyMathReason-1B</em></a>. The two files that hold most of the real decisions in this half of the pipeline:</p><ul><li><em>src/train/maxtext_config.yml</em> — every pretraining flag</li><li><em>src/train/convert_checkpoint.py </em>— all five conversion bugs and how I fixed them</li></ul><p><a href="https://medium.com/@himanshunakrani0/how-i-post-trained-a-1b-model-with-sft-grpo-for-0-part-2-of-2-b283dff7d996">Continue to Part 2: SFT, GRPO, and the full cost story →</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*p1sdqV6eJKRXLK-p.png" /></figure><p>This story is published on <a href="https://generativeai.pub/">Generative AI</a>. Connect with us on <a href="https://www.linkedin.com/company/generative-ai-publication">LinkedIn</a> and follow <a href="https://www.zeniteq.com/">Zeniteq</a> to stay in the loop with the latest AI stories.</p><p>Subscribe to our <a href="https://www.generativeaipub.com/">newsletter</a> and <a href="https://www.youtube.com/@generativeaipub">YouTube</a> channel to stay updated with the latest news and updates on generative AI. Let’s shape the future of AI together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*5Roa3kdXnyQvz6uJ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a57063b91fd6" width="1" height="1" alt=""><hr><p><a href="https://generativeai.pub/how-i-pretrained-a-1b-language-model-for-0-part-1-of-2-a57063b91fd6">How I pretrained a 1B language model for $0 (Part 1 of 2)</a> was originally published in <a href="https://generativeai.pub/">Generative AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>