OPEN SOURCE DEEP DIVE
MiniMind: A Reproducible 64M LLM Stack Trained From Scratch on One GPU
MiniMind is a native-PyTorch, single-GPU teaching stack that covers tokenization, pretraining, SFT, LoRA, DPO, PPO/GRPO/CISPO, Agentic RL, and OpenAI-compatible serving for a roughly 64M-parameter model.
What MiniMind is, and what it is not
MiniMind is a compact, end-to-end laboratory for training a language model from scratch. It is not a frontier assistant and does not hide its limitations behind benchmark marketing. The current main line includes MiniMind-3, a fully trained dense model with roughly 64 million parameters, and MiniMind-3-MoE, which has about 198 million total parameters but activates roughly 64 million per token. The project follows the pipeline from tokenizer construction and pretraining through supervised fine-tuning, distillation, low-rank adaptation, preference optimization, reinforcement learning, multi-turn tool use, and an OpenAI-compatible serving interface.
The audience is similarly specific. It fits people who want to inspect losses and model weights directly, small teams that need a local testbed for post-training algorithms, and engineers who want to understand how data formats, training scripts, checkpoints, and inference endpoints fit together. It is a poor fit for general knowledge work, reliable factual answering, long-form authoring, or production tool execution. The source code is Apache-2.0 licensed, while the training corpus draws from multiple public and synthetic sources. Anyone redistributing data or derived weights should audit the upstream data terms separately.
A deliberately small Qwen3-style decoder
MiniMind-3 uses eight decoder layers with a hidden width of 768. Attention has eight query heads and four key-value heads, giving it grouped-query attention with a head dimension of 96. The vocabulary contains 6400 tokens, the maximum position count is 32768, and rotary position embeddings use a base of one million. The implementation combines RMSNorm, a SwiGLU feed-forward network, per-head query and key normalization, causal attention, tied input and output embeddings, and an inference-time key-value cache. YaRN scaling can extend the positional range without retraining the position table.
The attention path is defined inside the repository rather than assembled from an opaque modeling package. It includes rotary embedding precomputation, grouped key-value expansion, cache concatenation, a scaled-dot-product fast path, and a masked fallback. Training and generation share the same model code, which shortens the path between a numerical symptom and the responsible implementation detail. The generator also exposes temperature, top-k, top-p, repetition penalty, and streaming callbacks, so sampling behavior can be measured rather than guessed.
| Configuration | MiniMind-3 | MiniMind-3-MoE |
|---|---|---|
| Parameters | About 64M | About 198M total, about 64M active |
| Layers and width | 8 and 768 | 8 and 768 |
| Query and KV heads | 8 and 4 | 8 and 4 |
| Vocabulary and positions | 6400 and 32768 | 6400 and 32768 |
| Feed-forward design | Dense SwiGLU | Four experts, top-1 routing |
The architecture is implemented in model/model_minimind.py.
MoE separates stored capacity from per-token computation
The MoE variant replaces each dense feed-forward block with four experts and a linear router. Every token selects the single highest-scoring expert. There is no shared expert, and training adds an auxiliary load-balancing loss to discourage a small subset of experts from absorbing nearly all tokens. At inference time only the selected expert runs, so the compute path resembles the dense model while the stored parameter count is substantially larger.
Keeping the same outer decoder makes the two variants useful for controlled experiments. A reader can compare training time, loss behavior, routing, and downstream behavior without changing the tokenizer or surrounding pipeline. The experiment also exposes a practical caveat: with roughly 64M active parameters, routing noise, expert utilization, batch composition, and the auxiliary-loss weight can matter as much as the nominal expert count. The repository demonstrates one working configuration, not a universal scaling law.
A 6400-token vocabulary trades compression for parameter budget
The included tokenizer uses byte-level byte-pair encoding with a vocabulary of 6400. Its special-token budget includes chat boundaries, tool calls, tool responses, thinking markers, multimodal placeholders, and reserved slots. The small vocabulary makes Chinese and English text less compact than it would be with a large multilingual vocabulary. In exchange, the input embedding and output projection consume a smaller fraction of the model, leaving more capacity for transformer layers at a fixed parameter count.
The repository explicitly recommends against casually retraining the tokenizer. A new vocabulary breaks checkpoint and chat-template compatibility, changes token-level perplexity, and makes community weights harder to reuse. The tokenizer experiment remains useful for learning, but a serious reproduction should keep the published tokenizer fixed and focus instead on data quality, truncation policy, and optimization behavior.
See trainer/train_tokenizer.py for construction and a compatibility-oriented warning.
Pretraining and the data budget behind the cost claim
Pretraining data is stored as line-delimited text. Each sample is tokenized, wrapped with beginning and end markers, padded, and converted into next-token labels, with padding excluded from the loss. The lightweight pretraining set is about 1.2 GB and is intended for a quick reproduction. The fuller main-line set is about 10 GB. The corresponding supervised sets are about 1.6 GB and 14 GB, while the repository also lists about 86 MB of agent reinforcement data, 53 MB of preference data, and 24 MB of reinforcement-learning feedback data.
Those distinctions matter because the headline training cost applies to the lightweight combination. On one RTX 3090, the repository estimates about 2.31 hours and CNY 3.0 for lightweight dense pretraining plus supervised fine-tuning. The MoE route is estimated at about 3.23 hours and CNY 4.2. These are rough figures based on the author's rental rate. They are a useful reproducibility signal, not a promise that every machine, data mixture, sequence length, or training configuration will produce the same result.
Supervised fine-tuning learns only assistant spans
The supervised data loader does not train on the entire conversation. It searches for the assistant start boundary, locates the matching end marker, and assigns labels only to the assistant response and its closing token. System prompts and user messages receive the ignore value. The model therefore learns what to say after a prompt rather than spending objective capacity on copying the user or reproducing a system message.
Samples can receive a system prompt probabilistically, and empty thinking blocks are removed in most cases so that the model sees both thinking and non-thinking formats. Tool-use samples retain their structured calls and responses. The chat template expands tool definitions, calls, and observations into special segments, which means the data loader, tokenizer, template, and serving parser form one contract. Changing any one of them without the others can produce a model that trains successfully but serves malformed calls.
The masking logic is in dataset/lm_dataset.py.
Distillation covers hard answers and token distributions
MiniMind demonstrates both black-box and white-box distillation. The black-box path is supervised learning on teacher-generated answers. The student sees the question, the final text, reasoning patterns, and tool-call structure, but not the teacher's preference among all candidate tokens at each position. Much of the synthetic instruction, reasoning, and tool-use material in the main data mix belongs to this category.
The white-box path additionally aligns teacher and student output distributions. Its loss combines a supervised cross-entropy term with a temperature-scaled Kullback-Leibler term. The default objective is a weighted sum, and the temperature defaults to 1.5. The script handles dual-model loading, mixed dense or MoE outputs, checkpoint recovery, and distributed training. It is best treated as a clear reference implementation of the mechanics, not evidence that one teacher or one temperature is optimal for every downstream task.
LoRA stays small, inspectable, and mergeable
The LoRA implementation attaches a low-rank branch to square linear projections. Rank defaults to 16. The first matrix receives a small Gaussian initialization and the second starts at zero, so the initial adapter perturbs the base model by exactly zero. The default scaling is one. Saving collects only adapter parameters. Loading can either add the branch at inference time or merge its delta into the base weight, producing a standalone full checkpoint.
This is a useful implementation for readers who want to see what a parameter-efficient fine-tune actually changes. It does not use a third-party adapter wrapper, so the forward path, save format, loading behavior, and merge arithmetic are all visible. The current selector only targets square linear layers. Expanding it to other projections requires checking fan-in, fan-out, name matching, and checkpoint compatibility rather than simply attaching more branches.
See model/model_lora.py and trainer/train_lora.py.
Direct preference optimization learns between two answers
The DPO dataset supplies a chosen response and a rejected response for each prompt. Both paths receive assistant-only loss masks. The objective compares the current policy's relative log-probability for the two answers against a reference policy, increasing the chosen answer's relative score without needing an online rollout or a separately trained reward model. This makes DPO comparatively easy to run on a small GPU and suitable for style, safety, or preference alignment.
The limitation is equally important. DPO learns from a fixed set of preferences. It does not discover new solution paths, execute a test, verify an equation, or benefit directly from an environment reward. Placing DPO after supervised fine-tuning and before reinforcement learning reflects that distinction: preference optimization can shape which plausible answer is favored, while reinforcement learning can optimize a policy through sampled trajectories and verifiable feedback.
PPO, GRPO, and CISPO differ inside one problem frame
PPO uses an actor, a critic, and generalized advantage estimation. GRPO removes the standalone critic and normalizes rewards across multiple generations of the same prompt, producing a group-relative advantage. CISPO keeps the group-relative signal but changes the policy term: it multiplies a clipped importance weight by the log probability, preserving a gradient path even when the ratio itself is capped. These are different instantiations of sampling, advantage construction, and policy loss rather than unrelated training pipelines.
At this model scale, degenerate groups are a concrete failure mode. If every sampled answer for a prompt receives nearly the same reward, the within-group standard deviation approaches zero and GRPO or CISPO receives little useful direction. A reward model can also reward superficial length or formatting instead of task success. An upward reward curve therefore proves that this implementation can optimize its chosen objective. It does not by itself prove broader language or reasoning ability.
Agentic reinforcement learning treats tool use as a trajectory
The agent dataset adds a set of allowed tools and a final verification target to each prompt. A trajectory can contain up to three tool-use turns. The model emits a call, the environment executes a simulated calculator, unit converter, clock, weather lookup, exchange-rate function, or translation function, and the observation is returned to the context for another generation. Rewards account for valid tool choice, argument validity, expected call count, answer hits, malformed tags, and unfinished trajectories.
The rollout layer can run on native PyTorch or through SGLang. The latter separates generation from training and refreshes the policy through a weight-update endpoint, exposing a more realistic data flow for rollout-heavy reinforcement learning. The implementation connects templates, execution, multi-turn expansion, delayed reward, and training-serving separation. It remains a lightweight agent track rather than an industrial orchestration system, and the author notes that agent-focused weights can become less stable on open-ended factual questions.
Trajectory and reward logic is in trainer/train_agent.py; rollout backends are in trainer/rollout_engine.py.
Serving preserves reasoning and structured calls
The repository includes a FastAPI chat-completions endpoint in OpenAI request and response shape. Requests can supply messages, tools, sampling controls, streaming, and a thinking toggle. The service expands the chat template, generates text, and separates reasoning content, visible answer text, and tool calls. Streaming mode emits reasoning deltas and content deltas separately, then emits tool-call objects and a finish reason when appropriate.
This server is a local compatibility layer, not a production gateway. Authentication, tenant isolation, rate limits, queues, tracing, abuse controls, and high availability remain the deployer's responsibility. Its research value comes from making the trajectory observable. A developer can see when the model enters reasoning, when it emits a tool call, what arguments it chooses, and whether the final answer resumes cleanly after an observation.
See scripts/serve_openai_api.py.
What the evidence supports, and where the benchmarks stop
The repository reports the following MiniMind-3 results: C-Eval 24.89, CMMLU 25.38, ARC-Easy 28.49, PIQA 50.65, OpenBookQA 23.60, HellaSwag 28.28, and Social-IQa 34.19. These are useful for understanding the behavior of a low-cost micro-scale model, but they do not support claims of reliable knowledge or complex reasoning. Several scores are near random-guess baselines, and the training mix is not optimized for every English task.
| Benchmark | MiniMind-3 | Interpretation |
|---|---|---|
| C-Eval / CMMLU | 24.89 / 25.38 | Insufficient for factual answering |
| ARC-Easy / OpenBookQA | 28.49 / 23.60 | Weak results typical of a very small model |
| PIQA | 50.65 | Close to a two-class chance baseline |
| HellaSwag / Social-IQa | 28.28 / 34.19 | Limited common-sense and social inference |
The repository also reports a higher-scoring MiniMind-3-exam variant. It is the base model with a lightweight LoRA alignment on multiple-choice context and option formatting, then merged back into the full weights. The author explains that this is primarily input-format alignment rather than added knowledge. Any comparison should therefore separate parameter count, data exposure, format adaptation, and statistical uncertainty.
The right adoption boundary
The strongest use case is a decomposable training lab. Change an architectural component and watch the loss. Replace a preference objective and compare rewards with generations. Add a real tool and test whether templates, trajectories, and rewards close the loop. Apply LoRA to a narrow domain and decide whether the adaptation justifies further investment. MiniMind is valuable because the entire path is transparent, inexpensive to start, and small enough that a failure can usually be localized.
It should not be deployed as the decision-making core of a customer-support, medical, legal, financial, or production agent system. Knowledge capacity, factual reliability, long-context stability, and tool generalization remain limited, and an improving reward curve is not a substitute for independent task evaluation. A sound route is to use MiniMind to validate data contracts and training ideas, then carry the proven evaluation and reward design to a larger base model. That preserves the project's real contribution: making language-model training inspectable without turning reproducibility into a claim of production readiness.
The complete source and run instructions are at jingyaogong/minimind.