In partnership with

SnackOnAI Engineering | Senior AI Systems Researcher | Technical Deep Dive | November 25, 2026

Promise and Fence

The promise: by the end of this issue you will know where every one of MiniMind's 63,912,192 parameters lives, why its vocabulary choice matters more than its depth, how its MoE router fakes a weight of 1.0 and still learns, and what "2 hours, 3 RMB" really buys you.

The fence: this is not a tutorial for running the scripts, and not a ranking against SmolLM. I cloned the repo at commit 858008e (Nov 23, 2026), built both configs, counted parameters, ran the shipped tokenizer and timed a training step on CPU. I did not run the full 3090 training job. Throughput figures for the 3090 are the README's own estimates, plus my arithmetic, labeled as such.

What It Actually Does

MiniMind is a complete LLM training stack in plain PyTorch, sized so that one consumer GPU can run every stage:

  • Model: minimind-3, a Qwen3 style decoder with 8 layers, d_model 768, 8 query heads and 4 KV heads, plus a minimind-3-moe variant (198M total, 64M active, 4 experts with top-1 routing).

  • Tokenizer: a custom BPE with 6,400 tokens, including <think>, <tool_call> and <tool_response> tokens.

  • Training pipeline: pretrain → SFT → LoRA → DPO → PPO / GRPO / CISPO → agentic RL → distillation. Each stage is one script in trainer/, implemented from scratch, with no trl or peft wrappers.

  • Data: every stage's data is open, from pretrain_t2t_mini.jsonl (1.2 GB) to agent_rl.jsonl (86 MB).

  • Exits: weights load in transformers, llama.cpp, vllm and ollama, and it ships an OpenAI compatible server.

The whole model is 292 lines (model/model_minimind.py), and the eleven files in trainer/ total 2,876 lines. That is the product.

The community has noticed. Star History listed it at 54.3k stars and a global rank of #418 on Aug 3, 2026, and our input card puts it near 65k today. A Sohu writeup credits the project to Gong Jingyao (GitHub name jingyaogong) of Nanjing University and says it topped GitHub's daily Trending list.

The Architecture, Unpacked

Read the bottom line first: 70% of the model is feed-forward, and the embedding is under 8% only because the vocabulary is 6,400. With Qwen2's vocabulary, the embedding alone would be 1.8× the entire model.

Three design decisions carry the project.

1. Tiny vocabulary, on purpose. Llama 3 uses 128,000 tokens and Qwen2 uses 151,643. At d_model 768, a Qwen2 sized embedding is 116.5M parameters, more than MiniMind's whole budget. MiniMind pays for 6,400 with worse compression (the README quotes 1.5 to 1.7 Chinese characters per token; my classical poetry test got 1.0), and in return almost every parameter goes into layers that actually think.

2. Wide and shallow, against its own citation. The README cites MobileLLM, which found that at 125M and 350M parameters, narrow models with 30 to 42 layers beat wide ones with about 12. MiniMind still picks 8 layers at width 768, because a shallow network trains faster per step and the author found that below d_model 512 heads get too thin. This is an honest speed versus quality trade, made in the open.

3. A Qwen3 shaped skeleton. QK-norm, GQA, rope_theta 1e6, tied embeddings and an MoE without a shared expert all match the Qwen3 / Qwen3-MoE configs, so the weights convert straight to llama.cpp and vllm. Version 3 removed the shared expert that DeepSeek-V2 popularized. For a model this small, compatibility with existing tools beat architectural novelty.

The Code, Annotated

The MoE router that lies about its weight (real code, model_minimind.py)

def forward(self, x):
    batch_size, seq_len, hidden_dim = x.shape
    x_flat = x.view(-1, hidden_dim)
    scores = F.softmax(self.gate(x_flat), dim=-1)          # router over 4 experts
    topk_weight, topk_idx = torch.topk(scores, k=self.config.num_experts_per_tok, dim=-1, sorted=False)
    if self.config.norm_topk_prob:
        if self.config.num_experts_per_tok > 1:
            topk_weight = topk_weight / (topk_weight.sum(dim=-1, keepdim=True) + 1e-20)
        else:
            # Top-1: normalizing one weight by itself gives exactly 1.0, and the
            # constant 1.0 has zero gradient, so the router would never learn.
            top1 = torch.topk(F.softmax(self.gate(x_flat.detach()), dim=-1), k=1, dim=-1, sorted=False)[0]
            topk_weight = top1 - top1.detach() + 1.0      # ← THIS is the trick
            # Forward value: p - p + 1 = 1.0, so the expert output is unscaled.
            # Backward: d/dp = 1, so gradient still reaches the gate weights.
            # x_flat.detach() means that gradient trains the router only, not
            # the layers below it.
    y = torch.zeros_like(x_flat)
    for i, expert in enumerate(self.experts):
        mask = (topk_idx == i)
        if mask.any():
            token_idx = mask.any(dim=-1).nonzero().flatten()
            weight = topk_weight[mask].view(-1, 1)
            y.index_add_(0, token_idx, (expert(x_flat[token_idx]) * weight).to(y.dtype))
        elif self.training:
            # An expert that got zero tokens this batch has no gradient, and
            # DDP crashes waiting for it. Touching every parameter with *0
            # keeps the autograd graph complete at almost no cost.
            y[0, 0] += 0 * sum(p.sum() for p in expert.parameters())

A straight-through estimator in one line: the forward pass behaves like hard top-1, while the backward pass behaves like a soft gate. The 0 * line is the kind of production scar tissue that tutorials never show.

The config that decides the budget (real code, trimmed)

class MiniMindConfig(PretrainedConfig):
    def __init__(self, hidden_size=768, num_hidden_layers=8, use_moe=False, **kwargs):
        ...
        self.vocab_size = kwargs.get("vocab_size", 6400)          # 4.9M embedding, not 116M
        self.num_attention_heads = kwargs.get("num_attention_heads", 8)
        self.num_key_value_heads = kwargs.get("num_key_value_heads", 4)  # GQA halves KV cache
        # SwiGLU usually uses 8/3·d (= 2,048 here). MiniMind uses π·d rounded up
        # to a multiple of 64: ceil(768·π/64)·64 = 2,432, about 19% more FFN
        # width, which the parameters saved on the vocabulary pay for.
        self.intermediate_size = kwargs.get("intermediate_size",
                                            math.ceil(hidden_size * math.pi / 64) * 64)  # ← THIS is the trick
        self.rope_theta = kwargs.get("rope_theta", 1e6)           # Qwen3 value, long-context friendly
        self.tie_word_embeddings = kwargs.get("tie_word_embeddings", True)  # one matrix, two jobs
        self.num_experts = kwargs.get("num_experts", 4)
        self.num_experts_per_tok = kwargs.get("num_experts_per_tok", 1)
        self.router_aux_loss_coef = kwargs.get("router_aux_loss_coef", 5e-4)

Every default here is a budget transfer: parameters saved on the vocabulary and on KV heads are moved into FFN width, which is where a 64M model has the most to gain.

Verification: where the parameters go (mine, run against the repo)

import sys; sys.path.insert(0, ".")
from model.model_minimind import MiniMindConfig, MiniMindForCausalLM

for moe in (False, True):
    m = MiniMindForCausalLM(MiniMindConfig(use_moe=moe))
    total = sum(p.numel() for p in m.parameters())        # tied weights counted once
    emb   = m.model.embed_tokens.weight.numel()
    attn  = sum(p.numel() for n, p in m.named_parameters() if "self_attn" in n)
    ffn   = sum(p.numel() for n, p in m.named_parameters() if "mlp" in n)
    print(moe, total, emb, attn, ffn)

# False 63912192   4915200 14157312  44826624   → "64M" checks out
# True  198416640  4915200 14157312 179331072   → "198M-A64M" checks out:
#       active per token = 198.4M - 3 idle experts × 44.8M = 63.9M

Both headline sizes reproduce exactly from the shipped code. The MoE variant stores 3.1× the parameters but activates the same 63.9M per token.

It In Action

Input: the chat prompt 请介绍一下自己。 ("Please introduce yourself."), run through the shipped tokenizer and chat template.

Step

What happens

Real number

Tokenize text

白日依山尽 (5 chars)

5 tokens (README says 4)

Tokenize English

The sun sets in the west (24 chars)

8 tokens (README says 6)

Chat template

<|im_start|>user…<|im_end|>…assistant\n<think>\n\n</think>\n\n

22 tokens, empty think block by default

Untrained forward

random init, 4 × 340 tokens

loss 8.14 vs ln(6400) = 8.76

Train step on CPU

2 cores, batch 4 × 340, AdamW

3.82 s/step, 356 tokens/s

Pretrain on 3090

pretrain_t2t_mini, 1 epoch (README)

1.21 h, ≈1.57 RMB

SFT on 3090

sft_t2t_mini, 1 epoch (README)

1.10 h, ≈1.43 RMB

Weights

BF16

128 MB

KV cache

8 layers × 2 × 4 heads × 96 × 2 B

12 KiB/token, 384 MiB at 32,768 tokens

Two things fall out of this table.

First, the tokenizer examples in the README are stale: on the shipped tokenizer.json, the Chinese line is one token per character and the English line splits sets and west. Small, but it is exactly the kind of drift a teaching repo should not have.

Second, at full context the KV cache (384 MiB) is three times the weights (128 MB). On a model this small, long context, not parameter count, sets the memory floor.

Sanity check on the 3090 number (my estimate). One optimizer step under the default pretrain settings sees 32 × 340 × 8 = 87,040 tokens. At about 4.5 to 5 bytes per token for this mostly Chinese corpus, the 1.2 GB mini set is roughly 240M to 270M tokens. Training FLOPs ≈ 6 × 63.9M × 255M ≈ 9.8 × 10¹⁶, and spread over 1.21 hours that is about 21 to 23 TFLOPS sustained. That is believable for a 3090 in BF16, and it means the mini run gives the model only about 4 tokens per parameter, a fifth of Chinchilla's 20.

Why This Design Works

It optimizes for the reader's iteration speed, not the model's quality. A 2.3 hour loop means you can change one line, rerun pretraining overnight four times, and actually see the effect. That feedback loop is the curriculum.

Every abstraction is one hop deep. LoRA is 70 lines. Every stage sits in its own file in trainer/, between 165 and 484 lines. You can diff GRPO against PPO and see exactly what changed.

Compatibility is the escape hatch. Because the config mirrors Qwen3, a model you train can leave the teaching repo and run in llama.cpp, vllm or ollama. Most from-scratch tutorials produce a checkpoint nothing else can load.

What it trades away. Depth (8 layers, against MobileLLM's advice), compression (6,400 tokens), English ability (the training mix is mostly Chinese) and MoE efficiency. The README itself admits that its native PyTorch MoE loop runs about 50% slower than dense, and its own cost table shows 1.69 h vs 1.21 h for pretraining, 1.4×, because it loops over experts in Python instead of using fused kernels.

Technical Moats

  1. The data, not the code. Cleaned, deduplicated, template aligned data for every stage, from pretraining to agentic RL math, is the hard part. Anyone can write 292 lines of model; few will curate 10 GB of pretraining text and 14 GB of SFT that already includes tool calls and think tags.

  2. End-to-end coverage that actually runs. Pretrain through agentic RL in one repo, on one GPU, with resume across GPU counts. Most educational repos stop at SFT.

  3. Two years of compounding trust. Three model generations since August 2024, a breaking migration to Qwen3 compatibility done in public, and contamination warnings in its own README. That track record is why courses build on it: a CSDN course syllabus builds its whole Tokenizer → Pretrain → SFT → LoRA → RLHF → Agent RL → deployment curriculum on MiniMind.

Insights

1. The benchmark table is a random-guess table, and the README says so. MiniMind-3 scores 24.89 on C-Eval (four options, chance is 25) and 50.65 on PIQA (two options, chance is 50). The author's own note says gaps under about 3 points on these sets are inside the error bars. Then comes the twist: a LoRA trained on format only (minimind-3-exam) adds about 2.9 points on average. At 64M parameters, a good share of the "capability" these benchmarks measure is whether the model understands the multiple-choice layout. Stop quoting small-model benchmark tables without the chance line next to them.

2. "Two hours, three yuan" is a best case, defined two ways in the same README. The project note says "2 hours" is one epoch of SFT. The cost table says pretrain plus SFT, one epoch each, which comes to 2.31 hours and 3.0 RMB. And the shipped scripts default to --epochs 2, so an out-of-the-box run of both stages is closer to 4.6 hours and 6 RMB. The README also recommends max_seq_len≈768 for the mini pretrain set while train_pretrain.py defaults to 340. The claim is still true in spirit, and still astonishing: a full LLM pipeline for under a dollar. But copy the numbers from the cost table, not the tagline.

❝

Surprising Takeaway: at 64M parameters, vocabulary size is the architecture. MiniMind's 6,400-token embedding costs 4.9M parameters. Swap in Qwen2's 151,643-token tokenizer at the same width and the embedding alone becomes 116.5M, 1.8× the entire model, leaving nothing for the eight layers that do the thinking.

TL;DR For Engineers

  • 63,912,192 parameters, verified: 70% FFN (SwiGLU at π·d = 2,432), 22% GQA attention, 8% tied embedding thanks to a 6,400-token vocabulary.

  • The MoE variant (198M total, 64M active) uses a one-line straight-through trick so top-1 routing still trains, plus a 0 * hack so DDP survives idle experts.

  • Real cost from the README table: 2.31 h and 3.0 RMB for one epoch each of pretrain and SFT on a 3090; the default scripts run two epochs.

  • Benchmarks sit at chance; a format-only LoRA adds 2.9 points. Treat it as a lab bench, not an assistant.

  • Qwen3-compatible config means your homemade model runs in llama.cpp, vllm and ollama.

Explain It Like I'm New

Most people learn about large language models the way you might learn about cars by renting one. You can drive it, maybe change the radio settings, but you never see the engine. Big models are so expensive to build that almost nobody gets to see how one is made from nothing.

MiniMind is a kit car. It is a deliberately tiny language model, thousands of times smaller than the chatbots you use, together with every tool needed to build it yourself: the dictionary it uses to chop text into pieces, the reading phase where it learns language by guessing the next word billions of times, the coaching phase where it learns to answer questions, and the newer techniques that reward good answers.

The whole build fits on one gaming graphics card and takes a couple of hours, for roughly the price of a coffee in rented computer time. That is the point. When an experiment costs a few dollars, you can try something, break it, and try again the same evening.

The finished model is not smart. On standard tests it scores about as well as guessing. But that is fine, because the goal is understanding, not a product.

As AI becomes core infrastructure, the number of people who understand it from the inside matters. Projects like this turn a black box into a bench you can take apart.

See It In Action

  • MiniMind video introduction (Bilibili, the author's own channel): bilibili.com/video/BV12dHPeqE72. The project's official walkthrough, linked from the README: what MiniMind is, how training is staged, and a live chat with a trained model.

  • MiniMind online demo (ModelScope Studio): modelscope.cn/studios/gongjy/MiniMind. Chat with the released weights in a browser and see first-hand what 64M parameters can and cannot do.

  • Project page (jingyaogong.github.io): jingyaogong.github.io/minimind. A one-screen overview of the pipeline, model specs and changelog, useful as a map before reading the code.

  • Coding LLMs from the Ground Up (Sebastian Raschka): sebastianraschka.com course. The pretraining video alone runs 2:36:44; it is the best companion for understanding the GPT-2 style code paths MiniMind modernizes.

Community Conversation

  • Star History (star-history.com): 54.3k stars and a global rank of #418 as of Aug 3, 2026. The curve keeps climbing with each model generation, which is unusual for a tutorial repo.

  • Sohu / 智猩猩AI (sohu.com): this writeup is careful about the headline, noting that "2 hours" means one epoch of the SFT stage on a single 3090, and "3 yuan" is the GPU rental for that time, not the total for every stage.

  • Kevin Riedl, wavect (wavect.io): a reproduction-minded look at the claim, concluding that MiniMind estimates 2.31 GPU hours for the dense 64M Zero model on one RTX 3090, covering one epoch of pretraining and one of supervised fine-tuning.

  • 0dev GitHub Trend (0dev.duckdns.org): reports that the repository gained nearly 2,000 GitHub stars in a single week, a sign that the from-scratch angle still pulls in new learners two years in.

  • CSDN course syllabus (aicoding.csdn.net): educators are adopting it as a textbook because it is implemented in pure PyTorch with no black-box wrappers, so students can read every layer line by line.

Stop Grading MiniMind as a Model, Start Using It as a Curriculum

MiniMind is the best evidence yet that the LLM training stack, from tokenizer to agentic RL, fits in one person's head and one gaming GPU. Its benchmark scores are a rounding error. Its value is that every trade-off, from the 6,400-token vocabulary to the 8-layer depth to the Python loop over experts, sits in plain sight and can be changed in minutes.

If you lead an ML team, give new hires this repo before they touch your training stack. If you are learning, run the mini pipeline twice: once as shipped, once with 16 layers at width 512, and watch MobileLLM's argument play out on your own GPU. That experiment costs about six yuan and teaches more than a month of reading model cards.

References

  • Liu et al., MobileLLM: Optimizing Sub-billion Parameter Language Models for On-Device Use Cases (2024). arXiv:2402.14905

  • DeepSeek-AI, DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model (2024). arXiv:2405.04434

  • Qwen Team, Qwen3 Technical Report (2025). arXiv:2505.09388

  • Hoffmann et al., Training Compute-Optimal Large Language Models (2022). arXiv:2203.15556

  • Fedus, Zoph, Shazeer, Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity (2021). arXiv:2101.03961

MiniMind packs a Qwen3-compatible 64M LLM and a complete pretrain → SFT → RL → agent pipeline into readable PyTorch that trains on one 3090 for about 3 RMB per epoch pair. Its model scores at chance, by design and by its own admission. The real lesson is in the budget: at this scale, the vocabulary decides the architecture.

Sponsored Ad If you enjoy practical AI insights, check out SnackOnAI and support the newsletter by subscribing, sharing, and exploring our sponsored ad—it helps us keep building and delivering value 🚀

Your biggest deal just asked for a SOC 2 report. Can you send one?

Your champion is sold. Then procurement sends the security questionnaire, and line one asks for your SOC 2 report. No report, no signature.

Sprinto gets you audit-ready in 14 days, so the report lands before the deal goes cold. You give three working sessions; AI agents collect the evidence and ISO-certified experts guide the audit.

No consultants. No compliance hire. No engineers pulled off the roadmap.

State of Product reveals what AI still hasn’t solved

80% of product professionals say AI helps them ship faster, but customers aren’t seeing value any sooner. Atlassian’s State of Product 2027 explores the gains AI is delivering and the challenges that remain, from decision-making that hasn’t kept pace to gut instinct overriding customer evidence.

Recommended for you

View all
caret-right