Read the text
Load a plain-text dataset and inspect the exact characters the model will learn from.
01_read_text.pyAn executable course, now visible
From raw text to a trainable decoder-only Transformer. Every transformation shows the tensors, the reasoning, and the Python code actually introduced.
Start from text“We build GPT.”text → [T][tokens] → [B, T][B, T] → [B, T, V][B, T] → [B, T, C][B, T, C] → [B, T, C][B, T, C] ⇢ [B, T, C]loss → weights → tokenEvery shape follows from the previous one.
Diffs come from all 42 snapshots.
Small examples, authentic structure.
42 CHECKPOINTS · 7 TRANSFORMATIONS
Lessons stay below the surface: what you see is one system growing.
Load a plain-text dataset and inspect the exact characters the model will learn from.
01_read_text.pyCollect the unique characters and assign a stable integer ID to each one.
02_character_tokenizer.pyTurn text into token IDs, then reconstruct the original text from those IDs.
03_encode_decode.pyMove vocabulary, encode, and decode into reusable functions shared by later checkpoints.
tokenizer.pyReserve one part of the token sequence for learning and another for measuring generalization.
tokenizer.pyShift one token sequence by a single position so every input prefix has a correct next-token target.
tokenizer.pyChoose valid start positions and slice many context windows from the training sequence.
tokenizer.pyCollect multiple input and target windows so they can be processed together.
tokenizer.pyConvert nested Python lists into integer tensors with shape [batch, context].
tokenizer.pyTurn window sampling and tensor construction into one checked, reusable create_batch function.
batching.pyCheck tensor shapes, dtypes, and the selected compute device before building the first neural model.
batching.pyUse an embedding table that maps each current token directly to logits for the next token.
batching.pyFlatten batch and time into independent predictions, then compare logits with targets using cross entropy.
batching.pyClear gradients, run the forward pass, backpropagate the loss, and update model weights.
batching.pyTake the final logits, apply softmax, sample a token, append it, and repeat.
batching.pyCompare sequences that share the same final token and observe that the model predicts the same distribution.
batching.pyRepresent every token as a learned C-dimensional vector, then project that vector back to vocabulary logits.
batching.pyLook up a learned vector for each position and add it to the corresponding token embedding.
batching.pyProject embeddings into query, key, and value vectors, mask future positions, and compute contextual outputs.
batching.pyCompute several independent attention views and concatenate their outputs along the embedding dimension.
batching.pyAdd a learned C-to-C projection after concatenating all attention heads.
batching.pyAdd the original embeddings to the attention output without changing [B, T, C].
batching.pyApply LayerNorm to each token vector before sending it through multi-head attention.
batching.pyExpand each token from C to 4C, apply GELU, and project it back to C.
batching.pyPackage pre-normalized attention, feed-forward processing, and two residual additions into one module.
batching.pyPass the same [B, T, C] representation through a sequence of independently learned blocks.
batching.pyNormalize the output of the Transformer stack before projecting it to vocabulary logits.
batching.pyConnect batching, the full Transformer forward pass, cross entropy, backward, and optimizer updates.
batching.pyAverage loss across several batches in evaluation mode without computing gradients or changing weights.
batching.pyPersist model weights, optimizer state, configuration, tokenizer information, and the current step.
batching.pyReconstruct the model, restore learned weights, encode a prompt, and run generation without training.
batching.pyAdjust temperature and top-k to reshape the next-token distribution before multinomial sampling.
batching.pySave a new best model only when its validation loss improves.
batching.pyAdd AdamW configuration, learning-rate warmup and cosine decay, plus gradient clipping.
batching.pyRegularize intermediate activations and share parameters between token embeddings and the output head.
batching.pyApply weight decay to matrix-like weights while excluding biases and normalization parameters.
batching.pySplit one effective batch into micro-batches, scale each loss, and update weights only after accumulation.
batching.pyMove scattered settings into configuration objects and continue from the step stored in a checkpoint.
batching.pyKeep full logits for training but apply the output head only to the final position during inference.
batching.pyOptionally route causal attention through PyTorch’s fused scaled_dot_product_attention implementation.
batching.pyIntroduce optional mixed precision, torch.compile, and distributed data parallel controls.
batching.pyConnect GPT-2 BPE tokenization, FineWeb-Edu data, the complete model, training, checkpoints, and generation.
batching.pyLIVE MODEL BLUEPRINT
[B,T]ln_1 → attention → + → ln_2 → MLP → +ln_f ↓output headlm_headAdamW → weightsLoad a plain-text dataset and inspect the exact characters the model will learn from.
From language to indices
text → [T]Every later tensor begins here. Seeing the raw source first keeps the path from language to numbers explicit.
Synchronized code
study/lessons/01_read_text.py===================================================================@@ -0,0 +1,31 @@+"""+Changes compared with the previous file:+- This lesson script uses the English project layout and imports lesson-specific+ snapshot code.+- It belongs to lesson 01 of the guided LearnGPT path.++File purpose:+- Run the lesson example in a reproducible way.+- Print the relevant intermediate values, tensor shapes, losses, or generated+ text for inspection.+"""++from pathlib import Path+++PROJECT_DIR = Path(__file__).resolve().parents[2]+DATASET_PATH = PROJECT_DIR / "data" / "raw" / "fineweb_edu_sample.txt"+++def main():+ text = DATASET_PATH.read_text(encoding="utf-8")++ print("File read:", DATASET_PATH)+ print("Number of characters:", len(text))+ print()+ print("First 500 characters:")+ print(text[:500])+++if __name__ == "__main__":+ main() DIDACTIC SCALE ≠ ORIGINAL WEIGHTS
| Configuration | C | Heads | Blocks | V |
|---|---|---|---|---|
| LearnGPT smoke | 64 | 4 | 2 | 50,257 |
| GPT-2 Small | 768 | 12 | 12 | 50,257 |
LearnGPT reconstructs the path and components of a decoder-only GPT. Small values keep tensors and operations inspectable; GPT-2 Small uses the same family of components at a much larger scale.