# ydeven757/llms-from-scratch architecture

> Architecture diagram of the GitHub repository ydeven757/llms-from-scratch, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-08-20). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/ydeven757/llms-from-scratch
- Repository: https://github.com/ydeven757/llms-from-scratch

## Overview

#### Purpose and Entry Points
This is the companion repository for *Build a Large Language Model (From Scratch)*: an educational, Python/PyTorch codebase that builds GPT-like models, pretrains them, and adapts them for classification and instruction following. Primary entry points are chapter notebooks and runnable scripts, not a unified application: `ch04/01_main-chapter-code/gpt.py`, `ch05/01_main-chapter-code/gpt_train.py`, `ch06/01_main-chapter-code/gpt_class_finetune.py`, and `ch07/01_main-chapter-code/gpt_instruction_finetuning.py`.

#### Reusable Package Boundary
`pkg/llms_from_scratch` is the consolidated importable implementation/test surface, while chapter directories preserve book-oriented, self-contained examples. Chapter modules cover each pipeline stage: `pkg/llms_from_scratch/ch02.py`, `pkg/llms_from_scratch/ch04.py`, and `pkg/llms_from_scratch/ch07.py`. Consumers should treat duplicated `previous_chapters.py` files in chapters as pedagogical snapshots rather than a stable shared library.

#### Text Data and Tokenization
The pipeline begins with raw text, tokenization, and next-token training examples. Chapter 2 implements data loading and BPE exploration in `ch02/01_main-chapter-code/ch02.ipynb` and `ch02/02_bonus_bytepair-encoder/bpe_openai_gpt2.py`; the reusable layer is `pkg/llms_from_scratch/ch02.py`. Token IDs and context windows form the boundary passed into embedding and transformer execution.

#### Transformer Model Construction
Attention mechanisms lead into the baseline decoder-only GPT model: `ch03/01_main-chapter-code/ch03.ipynb`, `ch04/01_main-chapter-code/gpt.py`, and `pkg/llms_from_scratch/ch04.py`. The model converts token sequences through embeddings, causal multi-head attention, feed-forward blocks, residual/normalization structure, and a vocabulary-logit output head. Optional architecture branches compare KV caching, GQA/MLA/SWA, MoE, and KV sharing under `ch04/03_kv-cache`, `ch04/04_gqa`, and `ch04/07_moe`; they are alternatives rather than dependencies of the main path.

#### Pretraining and Generation
Pretraining consumes unlabeled token batches, computes next-token loss, and updates the GPT model with PyTorch training loops. Core scripts are `ch05/01_main-chapter-code/gpt_train.py` and `ch05/01_main-chapter-code/gpt_generate.py`; Gutenberg preparation is separated in `ch05/03_bonus_pretraining_on_gutenberg/prepare_dataset.py`. Model downloading/loading is an external-weight boundary in `ch05/01_main-chapter-code/gpt_download.py`, supporting use of pretrained weights alongside scratch training.

#### Adaptation, Evaluation, and Serving Examples
Classification fine-tuning adapts the pretrained GPT output for labeled text through `ch06/01_main-chapter-code/gpt_class_finetune.py`. Instruction fine-tuning consumes JSON instruction/response datasets and produces response-generating models via `ch07/01_main-chapter-code/gpt_instruction_finetuning.py` and `ch07/01_main-chapter-code/instruction-data-with-response.json`. Evaluation and dataset-generation examples integrate local Ollama and the OpenAI API: `ch07/01_main-chapter-code/ollama_evaluate.py`, `ch07/03_model-evaluation`, and `ch07/05_dataset-generation`. Lightweight interactive UIs are optional demos, e.g. `ch05/06_user_interface/app_own.py`, `ch06/04_user_interface/app.py`, and `ch07/06_user_interface/app.py`.

#### Runtime and Infrastructure
The material runtime is Python with PyTorch, designed for laptop execution while using GPUs when available. Distributed training examples use PyTorch DDP/`torchrun` in `appendix-A/01_main-chapter-code/DDP-script-torchrun.py`. Dependency and package metadata reside in `pyproject.toml`, `requirements.txt`, and `pixi.toml`; optional Docker development support is under `setup/03_optional-docker-environment/.devcontainer/Dockerfile`. GitHub Actions provide cross-platform Python/PyTorch validation.

Main entry points: [`ch05/01_main-chapter-code/gpt_train.py`](https://github.com/ydeven757/llms-from-scratch/blob/main/ch05/01_main-chapter-code/gpt_train.py) (Scratch pretraining), [`pkg/llms_from_scratch/ch02.py`](https://github.com/ydeven757/llms-from-scratch/blob/main/pkg/llms_from_scratch/ch02.py) (Tokenization & windows), [`ch07/01_main-chapter-code/gpt_instruction_finetuning.py`](https://github.com/ydeven757/llms-from-scratch/blob/main/ch07/01_main-chapter-code/gpt_instruction_finetuning.py) (Instruction fine-tuning), [`pkg/llms_from_scratch/ch04.py`](https://github.com/ydeven757/llms-from-scratch/blob/main/pkg/llms_from_scratch/ch04.py) (Reusable GPT implementation)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_data["Data Pipeline"]
  node_raw_text["Raw text corpora<br/>training data"]
  node_tokenization["Tokenization &amp; windows<br/>data preparation<br/>[ch02.py]"]
  node_bpe_exploration["BPE exploration<br/>chapter example<br/>[bpe_openai_gpt2.py]"]
  node_gutenberg_prep["Gutenberg preparation<br/>dataset builder<br/>[prepare_dataset.py]"]
  node_instruction_data["Instruction responses<br/>JSON dataset"]
end

subgraph group_model["Modeling"]
  node_gpt_package["Reusable GPT implementation<br/>Python package module<br/>[ch04.py]"]
  node_gpt_chapter["Baseline GPT model<br/>chapter entry point<br/>[gpt.py]"]
  node_attention_notebook["Attention foundations<br/>chapter notebook<br/>[ch03.ipynb]"]
  node_architecture_variants["GPT architecture variants<br/>optional experiments"]
end

subgraph group_training["Training &amp; Adaptation"]
  node_pretraining["Scratch pretraining<br/>training loop<br/>[gpt_train.py]"]
  node_generation["Text generation<br/>generation script<br/>[gpt_generate.py]"]
  node_weight_loading["Pretrained weight loading<br/>external-weight boundary<br/>[gpt_download.py]"]
  node_classification["Classification fine-tuning<br/>adaptation entry point"]
  node_instruction_tuning["Instruction fine-tuning<br/>adaptation entry point"]
end

subgraph group_integration["Evaluation &amp; Runtime"]
  node_model_evaluation["LLM evaluation<br/>evaluation examples"]
  node_interactive_uis["Interactive UI demos<br/>optional applications<br/>[app.py]"]
  node_ddp_training["Distributed training<br/>PyTorch DDP example"]
  node_pytorch_runtime{{"Python / PyTorch runtime<br/>execution platform"}}
end

node_raw_text -->|"tokenize"| node_tokenization
node_bpe_exploration -.->|"explores BPE"| node_tokenization
node_gutenberg_prep -->|"prepares corpus"| node_raw_text
node_tokenization -->|"token ID windows"| node_gpt_package
node_attention_notebook -->|"builds toward"| node_gpt_chapter
node_gpt_chapter -.->|"chapter counterpart"| node_gpt_package
node_architecture_variants -.->|"alternative designs"| node_gpt_chapter
node_tokenization -->|"training batches"| node_pretraining
node_gpt_package -->|"model and logits"| node_pretraining
node_weight_loading -.->|"initializes from weights"| node_pretraining
node_pretraining -->|"trained model"| node_generation
node_pretraining -->|"pretrained model"| node_classification
node_pretraining -->|"pretrained model"| node_instruction_tuning
node_instruction_data -->|"supervision"| node_instruction_tuning
node_instruction_tuning -->|"responses"| node_model_evaluation
node_generation -.->|"generation backend"| node_interactive_uis
node_instruction_tuning -.->|"instruction model"| node_interactive_uis
node_pretraining -.->|"scales training loop"| node_ddp_training
node_pytorch_runtime -->|"executes"| node_gpt_package
node_pytorch_runtime -->|"trains on"| node_pretraining

click node_tokenization "https://github.com/ydeven757/llms-from-scratch/blob/main/pkg/llms_from_scratch/ch02.py"
click node_bpe_exploration "https://github.com/ydeven757/llms-from-scratch/blob/main/ch02/02_bonus_bytepair-encoder/bpe_openai_gpt2.py"
click node_gutenberg_prep "https://github.com/ydeven757/llms-from-scratch/blob/main/ch05/03_bonus_pretraining_on_gutenberg/prepare_dataset.py"
click node_instruction_data "https://github.com/ydeven757/llms-from-scratch/blob/main/ch07/01_main-chapter-code/instruction-data-with-response.json"
click node_gpt_package "https://github.com/ydeven757/llms-from-scratch/blob/main/pkg/llms_from_scratch/ch04.py"
click node_gpt_chapter "https://github.com/ydeven757/llms-from-scratch/blob/main/ch04/01_main-chapter-code/gpt.py"
click node_attention_notebook "https://github.com/ydeven757/llms-from-scratch/blob/main/ch03/01_main-chapter-code/ch03.ipynb"
click node_architecture_variants "https://github.com/ydeven757/llms-from-scratch/tree/main/ch04/03_kv-cache"
click node_pretraining "https://github.com/ydeven757/llms-from-scratch/blob/main/ch05/01_main-chapter-code/gpt_train.py"
click node_generation "https://github.com/ydeven757/llms-from-scratch/blob/main/ch05/01_main-chapter-code/gpt_generate.py"
click node_weight_loading "https://github.com/ydeven757/llms-from-scratch/blob/main/ch05/01_main-chapter-code/gpt_download.py"
click node_classification "https://github.com/ydeven757/llms-from-scratch/blob/main/ch06/01_main-chapter-code/gpt_class_finetune.py"
click node_instruction_tuning "https://github.com/ydeven757/llms-from-scratch/blob/main/ch07/01_main-chapter-code/gpt_instruction_finetuning.py"
click node_model_evaluation "https://github.com/ydeven757/llms-from-scratch/tree/main/ch07/03_model-evaluation"
click node_interactive_uis "https://github.com/ydeven757/llms-from-scratch/blob/main/ch07/06_user_interface/app.py"
click node_ddp_training "https://github.com/ydeven757/llms-from-scratch/blob/main/appendix-A/01_main-chapter-code/DDP-script-torchrun.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_raw_text,node_tokenization,node_bpe_exploration,node_gutenberg_prep,node_instruction_data toneBlue
class node_gpt_package,node_gpt_chapter,node_attention_notebook,node_architecture_variants toneAmber
class node_pretraining,node_generation,node_weight_loading,node_classification,node_instruction_tuning toneMint
class node_model_evaluation,node_interactive_uis,node_ddp_training,node_pytorch_runtime toneRose
```

## Components

### Data Pipeline

- **Raw text corpora**: training data
- [Tokenization & windows](https://github.com/ydeven757/llms-from-scratch/blob/main/pkg/llms_from_scratch/ch02.py): data preparation · `pkg/llms_from_scratch/ch02.py`
- [BPE exploration](https://github.com/ydeven757/llms-from-scratch/blob/main/ch02/02_bonus_bytepair-encoder/bpe_openai_gpt2.py): chapter example · `ch02/02_bonus_bytepair-encoder/bpe_openai_gpt2.py`
- [Gutenberg preparation](https://github.com/ydeven757/llms-from-scratch/blob/main/ch05/03_bonus_pretraining_on_gutenberg/prepare_dataset.py): dataset builder · `ch05/03_bonus_pretraining_on_gutenberg/prepare_dataset.py`
- [Instruction responses](https://github.com/ydeven757/llms-from-scratch/blob/main/ch07/01_main-chapter-code/instruction-data-with-response.json): JSON dataset · `ch07/01_main-chapter-code/instruction-data-with-response.json`

### Modeling

- [Reusable GPT implementation](https://github.com/ydeven757/llms-from-scratch/blob/main/pkg/llms_from_scratch/ch04.py): Python package module · Consolidated importable model implementation. · `pkg/llms_from_scratch/ch04.py`
- [Baseline GPT model](https://github.com/ydeven757/llms-from-scratch/blob/main/ch04/01_main-chapter-code/gpt.py): chapter entry point · `ch04/01_main-chapter-code/gpt.py`
- [Attention foundations](https://github.com/ydeven757/llms-from-scratch/blob/main/ch03/01_main-chapter-code/ch03.ipynb): chapter notebook · `ch03/01_main-chapter-code/ch03.ipynb`
- [GPT architecture variants](https://github.com/ydeven757/llms-from-scratch/tree/main/ch04/03_kv-cache): optional experiments · KV cache, GQA, MLA, SWA, MoE, and KV-sharing alternatives. · `ch04/03_kv-cache`

### Training & Adaptation

- [Scratch pretraining](https://github.com/ydeven757/llms-from-scratch/blob/main/ch05/01_main-chapter-code/gpt_train.py): training loop · `ch05/01_main-chapter-code/gpt_train.py`
- [Text generation](https://github.com/ydeven757/llms-from-scratch/blob/main/ch05/01_main-chapter-code/gpt_generate.py): generation script · `ch05/01_main-chapter-code/gpt_generate.py`
- [Pretrained weight loading](https://github.com/ydeven757/llms-from-scratch/blob/main/ch05/01_main-chapter-code/gpt_download.py): external-weight boundary · `ch05/01_main-chapter-code/gpt_download.py`
- [Classification fine-tuning](https://github.com/ydeven757/llms-from-scratch/blob/main/ch06/01_main-chapter-code/gpt_class_finetune.py): adaptation entry point · `ch06/01_main-chapter-code/gpt_class_finetune.py`
- [Instruction fine-tuning](https://github.com/ydeven757/llms-from-scratch/blob/main/ch07/01_main-chapter-code/gpt_instruction_finetuning.py): adaptation entry point · `ch07/01_main-chapter-code/gpt_instruction_finetuning.py`

### Evaluation & Runtime

- [LLM evaluation](https://github.com/ydeven757/llms-from-scratch/tree/main/ch07/03_model-evaluation): evaluation examples · Uses local Ollama and OpenAI API integrations. · `ch07/03_model-evaluation`
- [Interactive UI demos](https://github.com/ydeven757/llms-from-scratch/blob/main/ch07/06_user_interface/app.py): optional applications · `ch07/06_user_interface/app.py`
- [Distributed training](https://github.com/ydeven757/llms-from-scratch/blob/main/appendix-A/01_main-chapter-code/DDP-script-torchrun.py): PyTorch DDP example · `appendix-A/01_main-chapter-code/DDP-script-torchrun.py`
- **Python / PyTorch runtime**: execution platform · Laptop-first execution with optional GPU acceleration.

## Connections

- Raw text corpora → Tokenization & windows: tokenize
- BPE exploration → Tokenization & windows: explores BPE
- Gutenberg preparation → Raw text corpora: prepares corpus
- Tokenization & windows → Reusable GPT implementation: token ID windows
- Attention foundations → Baseline GPT model: builds toward
- Baseline GPT model → Reusable GPT implementation: chapter counterpart
- GPT architecture variants → Baseline GPT model: alternative designs
- Tokenization & windows → Scratch pretraining: training batches
- Reusable GPT implementation → Scratch pretraining: model and logits
- Pretrained weight loading → Scratch pretraining: initializes from weights
- Scratch pretraining → Text generation: trained model
- Scratch pretraining → Classification fine-tuning: pretrained model
- Scratch pretraining → Instruction fine-tuning: pretrained model
- Instruction responses → Instruction fine-tuning: supervision
- Instruction fine-tuning → LLM evaluation: responses
- Text generation → Interactive UI demos: generation backend
- Instruction fine-tuning → Interactive UI demos: instruction model
- Scratch pretraining → Distributed training: scales training loop
- Python / PyTorch runtime → Reusable GPT implementation: executes
- Python / PyTorch runtime → Scratch pretraining: trains on
