jingyaogong/minimind describes itself as a project to train a ~64M-parameter LLM from scratch (the README cites about 2 hours and about RMB 3 of GPU rental). This post is a source reading at commit 96de892: I cloned the repo and read model/model_minimind.py, model/model_lora.py, dataset/lm_dataset.py, trainer/trainer_utils.py, trainer/train_pretrain.py, trainer/train_full_sft.py and trainer/train_lora.py, plus the README. Facts come from that code; interpretation is marked.
Companion tutorial: how to run the pretrain, SFT and chat loop yourself is on Cui.Guru: Train a 64M LLM from scratch with MiniMind.
The workflow in motion
Architecture
The README states the motivation: transformers, trl and peft expose highly abstract interfaces, so MiniMind implements the core algorithms natively in PyTorch. The LLM training-stage scripts (pretrain, SFT, LoRA and the others) are standalone and share helpers from trainer_utils.py.
The config defaults are the whole model spec: hidden_size=768, num_hidden_layers=8, vocab_size=6400, 8 attention heads with 4 key/value heads, rope_theta=1e6, tied input/output embeddings. The README table lists this as minimind-3, 64M parameters, plus a minimind-3-moe variant at 198M with about 64M active.
The core design idea
One small, readable model class serves every training stage; stages differ only in data, labels and which weights train. The pretraining and SFT scripts are nearly identical loops. What changes is the dataset’s label mask.
Pretraining trains on every real token, ignoring only padding:
# dataset/lm_dataset.py (PretrainDataset)
tokens = [self.tokenizer.bos_token_id] + tokens + [self.tokenizer.eos_token_id]
...
labels = input_ids.clone()
labels[input_ids == self.tokenizer.pad_token_id] = -100
SFT instead scans for the assistant header and unmasks only the assistant reply, so the model is not trained to predict the user’s turn:
# dataset/lm_dataset.py (SFTDataset.generate_labels)
labels = [-100] * len(input_ids)
...
if input_ids[i:i + len(self.bos_id)] == self.bos_id:
start = i + len(self.bos_id)
...
for j in range(start, min(end + len(self.eos_id), self.max_length)):
labels[j] = input_ids[j]
The loss itself lives in the model’s forward, a plain shifted cross-entropy where -100 is ignored:
# model/model_minimind.py
x, y = logits[..., :-1, :].contiguous(), labels[..., 1:].contiguous()
loss = F.cross_entropy(x.view(-1, x.size(-1)), y.view(-1), ignore_index=-100)
SFT then starts from the pretrain weight: train_full_sft.py defaults --from_weight to pretrain, while train_pretrain.py defaults it to none.
Grouped-query attention with QK-norm
Attention projects queries to num_attention_heads and keys/values to num_key_value_heads (4 by default), repeats KV heads with repeat_kv, normalizes q and k with RMSNorm, applies rotary embeddings, and uses PyTorch’s scaled_dot_product_attention when the flash path applies, otherwise an explicit masked softmax:
# model/model_minimind.py
xq, xk = self.q_norm(xq), self.k_norm(xk)
cos, sin = position_embeddings
xq, xk = apply_rotary_pos_emb(xq, xk, cos, sin)
precompute_freqs_cis also contains a YaRN branch, enabled only when inference_rope_scaling is set; the README says YaRN extrapolation can extend context to 2048 and beyond at inference without extra training.
A compact cosine schedule
# trainer/trainer_utils.py
def get_lr(current_step, total_steps, lr, warmup_ratio=0.0):
...
angle = math.pi * (current_step - warmup) / max(1, total_steps - warmup)
return lr * (0.1 + 0.45 * (1 + math.cos(angle)))
With the default warmup_ratio=0 the rate starts at lr and decays to 0.1 * lr (interpretation of the formula: at the end the cosine term is 0, leaving 0.1 * lr).
LoRA, written by hand
model_lora.py implements LoRA in 70 lines instead of using peft. A is Gaussian-initialized and B is zero-initialized, so the adapter starts as a no-op; apply_lora attaches an adapter to every nn.Linear whose input and output sizes are equal and patches its forward:
# model/model_lora.py
self.A.weight.data.normal_(mean=0.0, std=0.02)
self.B.weight.data.zero_()
...
if isinstance(module, nn.Linear) and module.in_features == module.out_features:
train_lora.py then sets requires_grad for parameters whose name contains lora and logs the LoRA parameter count and share. merge_lora folds B @ A * scaling back into the base weights.
A top-1 MoE with a straight-through gate
MOEFeedForward routes each token to num_experts_per_tok of num_experts (4 experts, top-1 by default), and adds a load-balancing auxiliary loss scaled by router_aux_loss_coef (5e-4). For k=1 the code keeps the forward weight at exactly 1.0 and passes gradient to the gate via a straight-through trick:
# model/model_minimind.py
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 # k=1: 1.0 forward on purpose, gradient via straight-through
The README notes MoE is slower to train in native PyTorch because tokens are bucketed per expert, and measures the 4-expert top-1 setup at about 50% slower than dense.
Takeaways
- Keep the whole model in one file you can read top to bottom; here it is one file of under 300 lines including config, attention, MoE and generation.
- Separate the stages by label masks, not by different model code: padding-only masking for pretraining, assistant-only for SFT.
- Hand-rolled LoRA is small enough to audit: zero-init
B, wrap square linear layers, train onlyloraparameters. - Resume support is built into the training scripts examined here (
--from_resume 1restores model, optimizer and step), which matters for long runs. - Treat the README’s “2 hours / RMB 3” as a measured single-3090 SFT epoch, not a promise for every stage or dataset.
Want help training or fine-tuning a small model for your own domain? Get in touch.
Click to load Disqus comments