AI Infra Interviews logo

Learn LLM Training with MiniMind: A Code-Reading Guide

Trace MiniMind's tokenizer, model, SFT labels and checkpoints. Use an original training map and a practical reading route to learn what each stage actually changes.

BY OWEN HARTLEY · AIINFRAINTERVIEWS EDITORIAL · UPDATED NOVEMBER 23, 2026 · 4 MIN READ

PRACTICE THIS:Train a tiny language model (free) ·Run the post-training project (Premium) ·Practice the SFT debugging question (Premium) ·Explore the Agent Post-Training course

MiniMind is useful for learning LLM training because the model, data transformations and update loops are small enough to follow across source files. Start by tracing one example from text to token IDs, targets, loss and a saved checkpoint. Then compare what changes under supervised fine-tuning (SFT) and preference or reward-based training.

The goal is to explain an update before making the run bigger. The MiniMind repository provides the external implementation; the route below connects it to our runnable projects, concepts and interview exercises. Source references are pinned to revision 858008eb98da4428f78053a1cc4d3a3bd5973629, reviewed on November 23, 2026.

What the “64M model in two hours” claim covers

The English README at that revision lists MiniMind-3 at approximately 64 million parameters and describes a broader collection of training methods. Its timing footnote qualifies “two hours” as one SFT epoch on an NVIDIA . Treat that as the project's reported measurement, not an end-to-end budget or a result reproduced here.

Data preparation, pretraining, evaluation and separate post-training experiments all need their own accounting. A small checkpoint is a useful teaching scale; it does not imply that each experiment will run in minutes or that the model can replace a production assistant.

If this is your first training run, begin with Train a tiny language model with PyTorch, our free CPU project. It gives you a smaller environment in which to check prediction, validation and resume behavior before reading MiniMind's additional machinery.

Read the pipeline as artifacts and decisions

The model configuration defaults to eight layers, width 768, eight query heads and four KV heads. It uses a 6,400-token vocabulary. Inspect these values before assuming that an older MiniMind tutorial describes the current model.

A tokenizer defines the integer vocabulary; a chat template defines how roles and tool messages become a token sequence. Those choices travel with the weights. A model that learned one serialization cannot be evaluated fairly by silently substituting another.

Training passes artifacts forward; post-training introduces choices
  1. Tokenizer and model configuration

    Token IDs, special tokens and tensor shapes define the starting contract.

  2. Pretraining checkpoint

    Plain-text next-token learning produces weights to initialize a later stage.

  3. SFT checkpoint

    Demonstrations select the assistant behavior to learn.

What supervision is available for the next behavior change?

Chosen and rejected responses

  1. Preference optimization

    DPO compares response likelihoods relative to a reference.

A reward for generated responses

  1. Online policy optimization

    Sample responses, score them and update using the chosen RL objective.

Evaluate each candidate against the same held-out task contract.

This is a learning route, not a requirement to run every script. LoRA is a parameter-update choice that can accompany suitable training objectives.

For the vocabulary behind those branches, use Pretraining, Fine-Tuning and Distillation, a Premium concept. Keep the objective, trainable parameters and numerical representation as separate decisions.

Trace one SFT example through three files

Read dataset/lm_dataset.py first. SFTDataset builds a conversation through the tokenizer's chat template, truncates the token sequence and creates labels for assistant spans. Other labels are -100, the ignored-target value used by the loss.

Next inspect MiniMindForCausalLM.forward in the model file. Its loss compares logits[..., :-1, :] with labels[..., 1:]. The model performs the causal shift. Shifting this dataset's labels yourself would change the training target again. Other dataset classes in the same repository have different interfaces, so read each caller before reusing a batch.

Finally follow trainer/train_full_sft.py. It obtains the loss, adds the auxiliary term, divides by accumulation steps, backpropagates and performs optimizer updates at the configured boundary. That sequence connects the selected targets to the parameter change.

Follow the boundary where a target becomes a gradient

Step 1 of 4: Conversation to SFTDataset

  1. ConversationSFTDataset

    Apply the template, tokenize and truncate. Mark the assistant target positions.

  2. DatasetModel forward

    Pass input_ids and labels with matching sequence positions.

  3. Model forwardCross-entropy

    Pair each retained logit with the following label; ignore targets marked −100.

  4. LossOptimizer

    Accumulate gradients, apply the configured update and clear gradients for the next update.

The shift belongs to this model interface. Confirm that location before adapting a training loop from another project.

Before a long run, inspect an ordinary conversation, a multi-turn tool exchange and an example truncated inside an assistant reply. Count the retained target tokens after the shift. A nonempty input can still have no useful supervised targets. The Premium SFT debugging question develops this investigation into an interview answer.

Count useful targets before comparing training speed

Consider an illustrative run with 16 sequences per microbatch, 768 positions per sequence and four accumulation steps on one device:

positions per optimizer update = 16 × 768 × 4 = 49,152
if 25% are retained loss targets: 49,152 × 0.25 = 12,288 targets

The 25% is an explicit hypothetical measurement, not a MiniMind default. Padding, truncation and masking determine the real count. Reporting 49,152 “training tokens” without defining the counter obscures how much direct supervision the update receives. Masked prompt tokens still provide context and consume computation.

Compare runs using the same target definition, data and sequence lengths. Record elapsed update time and peak memory alongside counts. Training FLOPs: 6ND supplies the free compute reference; it is a model of work, not a prediction of wall-clock time on your device.

Test the handoff before adding another method

The checkpoint helper distinguishes exported weights from richer resume state containing model, optimizer and progress information. Being able to load weights proves less than resuming the same optimization trajectory.

As an exercise, compare a short uninterrupted run with an interrupted run resumed at an optimizer boundary. Keep the data order and random-state handling under inspection; use tolerances appropriate to the execution path. Record the first differing batch, loss or parameter update. Source inspection alone does not certify deterministic resume, and this guide does not claim a MiniMind training reproduction.

Then choose one post-training branch. Our Premium CPU post-training project lets you inspect SFT, DPO, PPO and GRPO on a small checkable task. The Agent Post-Training course develops evaluation, rewards and rollout infrastructure. Its catalog shows lesson access levels.

Keep a run only when its held-out behavior improves under the stated budget. If you cannot explain a changed result, return to the serialized example and update boundary before spending more compute.

PRACTICE THIS

Turn it into offers. Work the real questions and concepts this maps to:

FAQ

MiniMind exposes a small language model and its training pipeline in readable PyTorch source. It is useful for tracing tokenization, model computation, training targets and post-training objectives. Its small-model results do not establish frontier-model capability.

Discussion (4)

Morgan FosterEditor

Keep the evaluation prompts before changing the template. Otherwise a better-looking conversation can be caused by the new prompt instead of the update you meant to measure.

Owen HartleyEditor

Agreed. Save the serialized token IDs too. Identical visible text can still reach the model through different special tokens.

Ruiqi ZhouEditor

A tied embedding appears in two computations but owns one parameter tensor. Counting state-dict keys can double-count it.

Deepa VenkateshEditor

For the first resume test, stop at an optimizer boundary. An arbitrary interruption also asks whether partially accumulated gradients were saved. That is a separate contract to test.