๐Ÿง  MiniMind

From-Scratch LLM Training Framework
4
Sub-modules
Python
Language
21
Files
~3.9K
Lines
๐Ÿ”ต Transformer ยท GQA ๐ŸŸข MoE ยท LoRA ๐ŸŸก RLHF ยท DPO ยท GRPO ๐Ÿ”ด 26Mโ€“145M Params

๐Ÿ’ก What is this?

MiniMind is a minimalist open-source project that lets you train a GPT-style language model entirely from scratch. Think of it as a teaching hospital for LLMs: small enough to understand every layer, yet complete enough to cover the full training lifecycle โ€” from BPE tokenizer training through pretraining, supervised fine-tuning (SFT), LoRA adaptation, and reinforcement learning from human feedback (DPO, PPO, GRPO, SPO). The smallest config (26M params) trains on a single consumer GPU, making it ideal for learning how transformers really work.

Architecture Overview

The system is organised into four sub-modules. model/ defines the transformer backbone, trainer/ orchestrates every training recipe, dataset/ provides data loaders, and scripts/ handles deployment and inference.

flowchart LR
  subgraph model["model/"]
    MC[MiniMindConfig]
    MM[MiniMindModel
RoPE + GQA] MCL[MiniMindForCausalLM
GenerationMixin] ATT[Attention
Flash + KV Cache] FF[FeedForward
SwiGLU] MOE[MOEFeedForward
MoEGate + SharedExpert] RMS[RMSNorm] LORA[LoRA Module] MC --> MM MM --> MCL ATT --> MM FF --> MM MOE --> MM RMS --> MM LORA -.-> MCL end subgraph trainer["trainer/"] PT[pretrain.py] SFT[train_sft.py] TLORA[train_lora.py] DPO[train_dpo.py] PPO[train_ppo.py] GRPO[train_grpo.py] SPO[train_spo.py] KD[train_distillation.py] TR[train_reasoning.py] TOK[train_tokenizer.py] TU[trainer_utils.py] end subgraph dataset["dataset/"] PD[PretrainDataset] SD[SFTDataset] DD[DPODataset] RD[RLAIFDataset] end subgraph scripts["scripts/"] API[serve_api.py
FastAPI] WEB[web_demo.py
Streamlit] CVT[convert_model.py] CLI[api_client.py] end dataset --> trainer model --> trainer model --> scripts

Training Data Flow

Every training recipe follows a similar pipeline. Raw text is tokenised, batched by the dataset classes, passed through the model, and gradients flow back through the optimizer.

sequenceDiagram
    participant T as Tokenizer
(BPE, vocab=6400) participant D as Dataset
(PretrainDataset / SFTDataset) participant M as MiniMindForCausalLM
(Transformer + MoE) participant L as Loss
(CE / DPO / PPO) participant O as Optimizer
(AdamW) T->>D: Encode raw text โ†’ token IDs D->>M: Batched input_ids + labels M->>M: Embedding โ†’ Nร—(RMSNorm โ†’ Attention โ†’ RMSNorm โ†’ FFN) โ†’ LM Head M->>L: logits + labels โ†’ loss L->>O: loss.backward() O->>M: parameter update (lr=5e-4, weight_decay=0.1) Note over M,L: MoE adds aux_loss for load balancing

Narrated Walkthrough

๐Ÿšถ Following the Full Training Pipeline

Step 1 โ€” Tokenizer Training (trainer/train_tokenizer.py): Train a BPE tokenizer on your corpus to produce a 6,400-token vocabulary. This creates the tokenizer.model file consumed by all downstream stages.

Step 2 โ€” Pretraining (trainer/pretrain.py): Feed raw text through PretrainDataset into MiniMindForCausalLM with standard cross-entropy loss. The model learns general language patterns over ~10B tokens. Distributed training via DDP is supported.

Step 3 โ€” Supervised Fine-Tuning (trainer/train_sft.py): Switch to SFTDataset with instruction/response pairs. The loss mask ignores prompt tokens so the model only learns to generate responses.

Step 4 โ€” LoRA Adaptation (trainer/train_lora.py): Freeze the base model, inject LoRA low-rank matrices into Q/V projections, and fine-tune on domain data with ~0.1% trainable params.

Step 5 โ€” Preference Alignment (trainer/train_dpo.py): Use DPODataset to learn from chosen/rejected response pairs. DPO directly optimises the policy without a separate reward model.

Step 6 โ€” GRPO Reinforcement (trainer/train_grpo.py): Group Relative Policy Optimization samples multiple completions per prompt, ranks them, and updates the policy using relative advantages โ€” no critic network needed.

Step 7 โ€” Deployment (scripts/serve_api.py): Wrap the trained model in an OpenAI-compatible FastAPI server. The scripts/web_demo.py Streamlit app provides a chat interface for interactive testing.

Key Components

Class / FunctionFileRole
MiniMindConfigmodel/model_minimind.pyHuggingFace-compatible config holding hidden_size, num_layers, MoE params, RoPE theta
MiniMindModelmodel/model_minimind.pyCore transformer stack: token embedding โ†’ N ร— MiniMindBlock โ†’ RMSNorm
MiniMindForCausalLMmodel/model_minimind.pyFull causal LM wrapping MiniMindModel + LM head + loss; inherits GenerationMixin
Attentionmodel/model_minimind.pyGrouped Query Attention (GQA) with KV cache, RoPE, optional Flash Attention
FeedForwardmodel/model_minimind.pySwiGLU feed-forward: gate_proj ยท up_proj โ†’ SiLU โ†’ down_proj
MoEGatemodel/model_minimind.pyTop-k softmax gating with auxiliary load-balancing loss
MOEFeedForwardmodel/model_minimind.pyMixture of Experts layer dispatching tokens to top-k experts + shared expert
RMSNormmodel/model_minimind.pyRoot Mean Square Layer Normalization (no centering, faster than LayerNorm)
LoRAmodel/model_lora.pyLow-Rank Adaptation module injected into attention Q/V projections
PretrainDatasetdataset/lm_dataset.pyStreams tokenised raw-text chunks for next-token pretraining
SFTDatasetdataset/lm_dataset.pyInstruction-response pairs with prompt masking for supervised fine-tuning
DPODatasetdataset/lm_dataset.pyChosen/rejected pairs for Direct Preference Optimization
RLAIFDatasetdataset/lm_dataset.pyPrompt dataset for RL-based training (PPO, GRPO, SPO)
CriticModeltrainer/train_ppo.pyPPO value network extending MiniMindForCausalLM with a scalar value head
AutoAdaptiveValueTrackertrainer/train_spo.pySPO adaptive baseline tracker for reward normalisation

Deep-Dive Topics

Focused explorations of key architectural decisions and training strategies.

๐Ÿ—๏ธ Transformer Architecture

RoPE positional encoding, Grouped Query Attention with KV cache, RMSNorm, and SwiGLU feed-forward โ€” how MiniMind assembles a GPT-style decoder.

model/model_minimind.py

๐Ÿ”„ Training Pipeline Flow

From pretrain through SFT, DPO, PPO, GRPO, and SPO โ€” the complete lifecycle of training a language model with MiniMind.

trainer/*.py

๐Ÿ”€ MoE Routing

MoEGate softmax scoring, top-k expert selection, shared expert path, and auxiliary load-balancing loss for stable training.

model/model_minimind.py โ†’ MoEGate

๐ŸŽฏ LoRA Fine-tuning

Low-rank decomposition of weight updates, injection into Q/V projections, rank selection, and merging for efficient adaptation.

model/model_lora.py โ†’ LoRA

Directory Map

minimind/ โ”œโ”€โ”€ model/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ”œโ”€โ”€ model_minimind.py # MiniMindConfig, MiniMindModel, MiniMindForCausalLM, Attention, FeedForward, MoEGate, MOEFeedForward, RMSNorm โ”‚ โ””โ”€โ”€ model_lora.py # LoRA module, apply_lora(), merge_lora() โ”œโ”€โ”€ trainer/ โ”‚ โ”œโ”€โ”€ pretrain.py # Pretraining loop (DDP, gradient accumulation) โ”‚ โ”œโ”€โ”€ train_sft.py # Supervised fine-tuning โ”‚ โ”œโ”€โ”€ train_lora.py # LoRA fine-tuning pipeline โ”‚ โ”œโ”€โ”€ train_dpo.py # Direct Preference Optimization โ”‚ โ”œโ”€โ”€ train_ppo.py # PPO with CriticModel value network โ”‚ โ”œโ”€โ”€ train_grpo.py # Group Relative Policy Optimization โ”‚ โ”œโ”€โ”€ train_spo.py # Self-Play Optimization with AutoAdaptiveValueTracker โ”‚ โ”œโ”€โ”€ train_distillation.py # Knowledge distillation from teacher model โ”‚ โ”œโ”€โ”€ train_reasoning.py # Reasoning-focused fine-tuning โ”‚ โ”œโ”€โ”€ train_tokenizer.py # BPE tokenizer training (vocab_size=6400) โ”‚ โ””โ”€โ”€ trainer_utils.py # Shared utilities: lr schedulers, logging, checkpointing โ”œโ”€โ”€ dataset/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ””โ”€โ”€ lm_dataset.py # PretrainDataset, SFTDataset, DPODataset, RLAIFDataset โ”œโ”€โ”€ scripts/ โ”‚ โ”œโ”€โ”€ serve_api.py # OpenAI-compatible FastAPI server โ”‚ โ”œโ”€โ”€ web_demo.py # Streamlit chat interface โ”‚ โ”œโ”€โ”€ convert_model.py # Model format converter (HF โ†” custom) โ”‚ โ””โ”€โ”€ api_client.py # API client for testing serve_api.py โ””โ”€โ”€ eval_llm.py # Evaluation harness (imports model + trainer_utils)

Model Configuration (MiniMindConfig)

Key knobs exposed via MiniMindConfig(PretrainedConfig). The three standard model sizes are Small-26M, MoE-145M, and Base-104M.

ParameterSmall-26MMoE-145MBase-104MDescription
hidden_size512640768Transformer hidden dimension
num_hidden_layers8816Number of transformer blocks
num_attention_heads888Query heads in multi-head attention
num_key_value_heads222KV heads for Grouped Query Attention
vocab_size6400BPE tokenizer vocabulary size
max_position_embeddings32768Maximum sequence length (with YaRN RoPE scaling)
rope_theta1000000.0RoPE base frequency for long-context extrapolation
use_moefalsetruefalseEnable Mixture of Experts layers
num_expertsโ€”8โ€”Total expert count per MoE layer
num_experts_per_tokโ€”2โ€”Top-k experts activated per token
n_shared_expertsโ€”1โ€”Always-on shared experts alongside routed ones
flash_attntrue (if available)Use Flash Attention 2 for memory-efficient attention

Sub-Module Index

Drill down into each sub-module for class-level documentation, diagrams, and code walkthroughs.

๐Ÿ“ฆ model/

Core transformer architecture โ€” MiniMindForCausalLM, Attention with GQA + RoPE, MoE routing, LoRA adaptation, RMSNorm, SwiGLU FFN.

3 files ยท model_minimind.py ยท model_lora.py

๐Ÿ‹๏ธ trainer/

Complete training pipeline โ€” pretrain, SFT, LoRA, DPO, PPO, GRPO, SPO, knowledge distillation, reasoning, tokenizer training, shared utilities.

11 files ยท pretrain.py โ€ฆ trainer_utils.py

๐Ÿ“Š dataset/

Data loading and preprocessing โ€” PretrainDataset for raw text, SFTDataset for instructions, DPODataset for preferences, RLAIFDataset for RL prompts.

2 files ยท lm_dataset.py

๐Ÿš€ scripts/

Deployment and tooling โ€” OpenAI-compatible FastAPI server, Streamlit web demo, model format converter, API test client.

4 files ยท serve_api.py ยท web_demo.py

Cross-Module Dependencies

flowchart TD
  dataset["dataset/
lm_dataset.py"] model_mm["model/
model_minimind.py"] model_lora["model/
model_lora.py"] trainer["trainer/*
(11 training scripts)"] scripts["scripts/*
(API, demo, converter)"] eval["eval_llm.py"] utils["trainer/
trainer_utils.py"] dataset -->|"PretrainDataset, SFTDataset, DPODataset"| trainer model_mm -->|"MiniMindForCausalLM"| trainer model_mm -->|"MiniMindForCausalLM"| scripts model_lora -->|"LoRA, apply_lora"| scripts model_mm -->|"MiniMindForCausalLM"| eval model_lora -->|"LoRA"| eval utils -->|"lr_scheduler, logging"| eval style dataset fill:#1a3a2a,stroke:#3fb950,color:#c9d1d9 style model_mm fill:#1a2a3a,stroke:#58a6ff,color:#c9d1d9 style model_lora fill:#1a2a3a,stroke:#58a6ff,color:#c9d1d9 style trainer fill:#3a2a1a,stroke:#d29922,color:#c9d1d9 style scripts fill:#3a1a1a,stroke:#f85149,color:#c9d1d9