Train an LLM from Scratch with MiniMind: A Practical Guide
OutGrow › Blog › Train an LLM from Scratch with MiniMind: A Practical Guide
By Anwar Sheikh, Co-Founder of OutGrow. Published . 5 min read.
Learn how to train LLM from scratch using MiniMind's native PyTorch framework. Complete guide covering pretraining, SFT, LoRA, and agentic RL workflows.
Understanding the internal mechanics of generative artificial intelligence requires looking past black-box APIs and high-level training wrappers. While fine-tuning pre-trained checkpoints with adapter layers is common practice, developing an operational grasp of causal language modeling requires examining the training loop directly. MiniMind is an open-source educational framework built in pure PyTorch designed to help engineers train LLM from scratch—spanning tokenizer training, autoregressive pretraining, supervised fine-tuning (SFT), low-rank adaptation (LoRA), direct preference optimization (DPO), and agentic reinforcement learning.
Why Train an LLM from Scratch with MiniMind?
Most practitioner guides rely on external abstractions that obscure distributed communication, dynamic attention masking, and loss scaling. MiniMind implements these mechanisms explicitly in PyTorch scripts. By removing hidden dependencies, the codebase reveals how tokenizers map text to vocabulary indices, how rotary position embeddings (RoPE) operate on attention projections, and how gradient accumulation keeps GPU memory usage predictable during local training runs.
Inspecting the Repository Architecture and Source Files
The MiniMind repository isolates each phase of the language model lifecycle into focused modules and execution scripts:
model/model_minimind.py: Implements the model architecture, defining MiniMindConfig, RMSNorm normalization layers, precomputed RoPE rotary positional frequencies, causal multi-head self-attention, and optional Mixture of Experts (MoE) routing.trainer/train_pretrain.py: Runs the next-token prediction loop for base pretraining with cosine learning rate scheduling and gradient accumulation.trainer/train_full_sft.py: Handles supervised fine-tuning across multi-turn conversational dialogs and tool-calling templates.trainer/train_distillation.py: Executes knowledge distillation from teacher models to student architectures via combined cross-entropy and Kullback-Leibler divergence losses.trainer/train_agent.py: Orchestrates agentic reinforcement learning loops across tool-use tasks using GRPO or CISPO loss algorithms.model/model_lora.py: Implements parameter-efficient low-rank adaptation natively without external library dependencies, dynamically replacing linear layers with low-rank matrices.dataset/lm_dataset.py: Houses dataset parsers including PretrainDataset and SFTDataset to load JSONL formatted tokens.eval_llm.py: Provides command-line inference, benchmark evaluation, and interactive chat modes supporting both native PyTorch checkpoints and Hugging Face transformer models.scripts/serve_openai_api.py: Serves an OpenAI-compatible completion API backend supporting streaming and tool calls.trainer/train_tokenizer.py: Implements Byte-Pair Encoding (BPE) tokenizer training routines over JSONL datasets.
End-to-End Pipeline: From Raw Tokens to Agent RL
MiniMind divides the causal modeling progression into distinct, sequential stages:
- Tokenizer Construction: The project uses Byte-Pair Encoding with byte-level fallbacks to tokenize raw Chinese and English text without out-of-vocabulary crashes.
- Base Pretraining: The model learns autoregressive next-token prediction across text corpora.
- Instruction Tuning (SFT): The pre-trained network is trained on structured dialogue and function-calling schemas to behave as an assistant.
- Domain Adaptation (LoRA): Low-rank adapter matrices can be trained independently to adapt the base network to specific domains like medicine without catastrophic forgetting.
- Alignment & Agentic RL: Direct Preference Optimization and reinforcement learning algorithms (PPO, GRPO, CISPO) align responses and train the model to output tool invocation blocks.
Dataset Preparation and Formats
MiniMind processes plain JSONL files directly without requiring compilation into custom binary formats. Pretraining scripts consume simple JSON records with text keys:
{"text": "Transformer 通过自注意力机制建模上下文关系,是现代大语言模型的重要基础结构。"}
Supervised fine-tuning expects structured conversational arrays containing user and assistant messages, optionally including tool interactions:
{"conversations": [{"role": "user", "content": "你好"}, {"role": "assistant", "content": "你好!"}]}
The repository ships with multiple dataset options in the ./dataset/ directory. For rapid local experimentation, the mini datasets include pretrain_t2t_mini.jsonl (1.2GB) and sft_t2t_mini.jsonl (1.6GB). Full-scale runs can utilize pretrain_t2t.jsonl (10GB) and sft_t2t.jsonl (14GB).
Vocabulary and Special Tokens
In model/tokenizer_config.json, special control sequences mark system boundaries and tool interactions, including <|im_start|>, <|im_end|>, <tool_call>, and <tool_response>.
Model Architecture and Hyperparameter Defaults
The default minimind-3 architecture balances model expressiveness against consumer hardware memory limits. The configuration parameters defined in model/model_minimind.py and trainer defaults include:
| Hyperparameter | Default Value | Originating File |
|---|
| Hidden Dimension (hidden_size) | 768 | MiniMindConfig |
| Layer Count (num_hidden_layers) | 8 | MiniMindConfig |
| Mixture of Experts (use_moe) | False | MiniMindConfig |
| Pretrain Batch Size | 32 | train_pretrain.py |
| Pretrain Learning Rate | 0.0005 | train_pretrain.py |
| Pretrain Max Sequence Length | 340 | train_pretrain.py |
| Pretrain Epochs | 2 | train_pretrain.py |
| Pretrain Gradient Accumulation Steps | 8 | train_pretrain.py |
| SFT Batch Size | 16 | train_full_sft.py |
| SFT Learning Rate | 1e-05 | train_full_sft.py |
| SFT Max Sequence Length | 768 | train_full_sft.py |
Pretraining applies the AdamW optimizer with mixed precision enabled via torch.cuda.amp.GradScaler supporting bfloat16 and float16.
How to Train LLM from Scratch: Step-by-Step Runbook
Step 1: Clone Repository and Install Dependencies
Begin by cloning the source code and installing the specified Python requirements:
git clone --depth 1 https://github.com/jingyaogong/minimind
cd minimind && pip install -r requirements.txt
Step 2: Launch Base Pretraining
To train the initial causal transformer using default settings on a single device, run:
cd trainer && python train_pretrain.py
For distributed multi-GPU training on a single machine, launch the script using torchrun:
torchrun --nproc_per_node 1 train_pretrain.py # 1 means single GPU training, adjust according to your hardware (set >=2)
Checkpoints are written by default to the ../out directory every 1000 steps as pretrain_*.pth.
Step 3: Run Supervised Fine-Tuning
Once pretraining finishes, transfer the learned representations into an instruction-following assistant by running full parameter SFT:
cd trainer && python train_full_sft.py
This fine-tunes the checkpoint using conversational JSONL files such as ../dataset/sft_t2t_mini.jsonl.
How to Evaluate and Run Inference
MiniMind provides interactive CLI utilities to evaluate model quality immediately following training. To interact with your SFT model, execute:
python eval_llm.py --weight full_sft
To evaluate the raw baseline model before instruction tuning, specify the pretrain weights:
python eval_llm.py --weight pretrain
For models trained to call functions and APIs, verify multi-turn tool calling with:
python eval_toolcall.py --weight full_sft
Hardware Profile, Training Durations, and Rental Cost
According to the project documentation, training a 64M parameter chatbot from zero on the mini dataset path can complete in roughly 2 hours on a single RTX 3090 GPU, with an estimated cloud rental cost of 3 RMB. Actual compute times will scale based on hardware topology, sequence length, and batch accumulation settings.
Trade-offs, Limitations, and Architecture Considerations
Engineers evaluating MiniMind should consider key technical trade-offs:
- Model Capacity: MiniMind-3 defines 64M parameters with a hidden size of 768 across 8 layers. While ideal for learning and rapid experimentation, a 64M model lacks the general reasoning and deep world knowledge of large-scale foundation models.
- Sequence Length Limits: Default pretraining sequence length is capped at 340 tokens, expanding to 768 tokens in SFT, which restricts long-document comprehension without RoPE extrapolation techniques like YaRN.
- Catastrophic Forgetting: Full parameter SFT across specialized tasks without balanced general data mixing risks eroding base language modeling fluency.
- Legacy Compatibility: Project updates noted that models trained before 2025-04-26 are no longer directly supported for inference due to positional encoding shifts.
What Was Not Verified
The inspected repository files do not document multi-node cluster communication scaling benchmarks, hardware thermal behavior outside standard GPU configurations, or validation loss convergence tables for experimental diffusion branches.
Tags: Machine Learning, LLM, PyTorch, Deep Learning, Tutorial.
Published on the OutGrow blog. See how we automate operations, read the case studies, or book an audit.