Vivid86 commited on
Commit
80f8b56
Β·
verified Β·
1 Parent(s): a8e9558

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +140 -0
README.md ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ⚑ MiniTransformer-91M: Custom LLM Built From Scratch
2
+
3
+ [![PyTorch](https://img.shields.io/badge/PyTorch-2.11.0%2Bcu128-EE4C2C?logo=pytorch&logoColor=white)](https://pytorch.org/)
4
+ [![CUDA](https://img.shields.io/badge/CUDA-12.8%20(Blackwell%20sm__120)-76B900?logo=nvidia&logoColor=white)](https://developer.nvidia.com/cuda-toolkit)
5
+ [![Hardware](https://img.shields.io/badge/Hardware-NVIDIA%20GeForce%20RTX%205070-76B900)](https://www.nvidia.com/)
6
+ [![Parameters](https://img.shields.io/badge/Parameters-91.2M-blue)](#model-architecture)
7
+ [![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
8
+
9
+ An end-to-end, production-grade Large Language Model built entirely from ground-up fundamentals in PyTorch β€” featuring a custom Byte-Pair Encoding (BPE) tokenizer, Rotary Position Embeddings (RoPE), SwiGLU feed-forward networks, FlashAttention-powered Scaled Dot-Product Attention (SDPA), KV-Cache inference, and Supervised Fine-Tuning (SFT) for developer code assistance.
10
+
11
+ ---
12
+
13
+ ## πŸ—οΈ Architecture & Specifications
14
+
15
+ | Hyperparameter | Specification | Architectural Rationale |
16
+ | :--- | :--- | :--- |
17
+ | **Total Parameters** | **91,245,312 (~91.2M)** | Right-sized for efficient single-GPU desktop training & high-throughput inference |
18
+ | **Layers (`n_layers`)** | **12 Transformer Blocks** | Deep representation learning with pre-norm RMSNorm stability |
19
+ | **Hidden Dim (`d_model`)** | **768** | Standard projection dimension matching GPT-2 scale |
20
+ | **Attention Heads** | **12 Query / 12 Key-Value** | Multi-Head Self-Attention with FlashAttention SDPA kernel fusion |
21
+ | **Feed-Forward (`d_ff`)** | **2,048 (SwiGLU)** | Swish-Gated Linear Units (LLaMA/Mistral style) for higher non-linear capacity |
22
+ | **Context Window** | **256 tokens** | Sliding causal context with absolute relative distance preserved via RoPE |
23
+ | **Vocabulary Size** | **8,192 tokens** | Custom Byte-Level BPE tokenizer trained on technical & modern literature corpus |
24
+ | **Weight Tying** | **Enabled** | Embedding matrix shared with output language modeling head ($V \times D$) |
25
+ | **Positional Encoding**| **RoPE (Rotary Embeddings)**| Eliminates learnable absolute position embeddings; enables extrapolation & cache alignment |
26
+ | **Normalization** | **RMSNorm ($\epsilon = 10^{-5}$)** | Scaled root-mean-square normalization without mean-centering overhead |
27
+
28
+ ---
29
+
30
+ ## πŸš€ Key Engineering Milestones & Innovations
31
+
32
+ ### 1. Rotary Position Embeddings (RoPE) & Exact KV-Cache Alignment
33
+ Standard RoPE applies complex plane rotations to query and key vectors. In autoregressive KV-cache inference, feeding only the single newest token ($T=1$) naively rotates it at position $0$ instead of absolute step $S$.
34
+ - **Resolved**: Tracked sequential cache index (`start_pos = past_kvs[0][0].shape[2]`) through every block.
35
+ - **Verification**: Verified numerical logit parity between full recomputation and incremental KV-cache with a discrepancy $\le 1.2 \times 10^{-7}$.
36
+
37
+ ### 2. Native CUDA 12.8 & Blackwell RTX 5070 Optimization
38
+ - **Hardware**: NVIDIA GeForce RTX 5070 (12GB VRAM, Compute Capability `sm_120`).
39
+ - **Mixed Precision**: Native `torch.bfloat16` autocast prevents gradient underflow while saving 50% memory bandwidth.
40
+ - **Selective Weight Decay**: 2D weight matrices (linear layers, projections) decayed at $\lambda = 0.1$, while 1D normalization gains ($\gamma$) and biases are exempt.
41
+
42
+ ### 3. Two-Stage Training Curriculum
43
+ 1. **Stage 1 β€” Modern Technical Pre-Training**:
44
+ - 2.66 Million tokens (101 high-density documents across Computer Science, Operating Systems, Algorithms, Physics, and Mathematics).
45
+ - Validation loss dropped from **5.5954 $\rightarrow$ 4.6697**.
46
+ 2. **Stage 2 β€” Code & Developer Supervised Fine-Tuning (SFT)**:
47
+ - 25,022 instruction-response pairs (CodeAlpaca 20k + Alpaca Dialogue).
48
+ - **Response-Only Loss Masking**: User prompts are masked with `ignore_index=-100` so gradients strictly optimize the assistant's solutions.
49
+ - Validation loss dropped from **3.0428 $\rightarrow$ 2.2727**.
50
+
51
+ ---
52
+
53
+ ## πŸ’» Interactive Interfaces
54
+
55
+ ### 🌐 1. Gradio Web Interface (`app.py`)
56
+ Launch the browser UI with real-time typewriter streaming, parameter sliders, and markdown code syntax highlighting:
57
+
58
+ ```powershell
59
+ .venv\Scripts\python.exe app.py
60
+ ```
61
+ Open **`http://127.0.0.1:7860`** in your browser.
62
+
63
+ **Features**:
64
+ - Real-time token streaming powered by generator KV-cache.
65
+ - Dynamic checkpoint switcher (`model_dev_best.pt`, `model_sft_best.pt`, `model_best.pt`).
66
+ - Interactive sliders for Temperature, Top-p Nucleus cutoff, and Repetition Penalty.
67
+ - Clickable 1-click prompt presets for coding and algorithms.
68
+
69
+ ### πŸ“Ÿ 2. Terminal REPL (`chat.py`)
70
+ Chat directly from the command line:
71
+
72
+ ```powershell
73
+ .venv\Scripts\python.exe chat.py --model checkpoints/model_dev_best.pt --temperature 0.6 --penalty 1.15
74
+ ```
75
+
76
+ Live commands inside chat:
77
+ - `/temp 0.5` β€” Adjust sampling temperature
78
+ - `/penalty 1.2` β€” Adjust repetition penalty
79
+ - `/tokens 80` β€” Adjust max generated tokens
80
+ - `/clear` β€” Clear terminal screen
81
+ - `exit` β€” Quit
82
+
83
+ ---
84
+
85
+ ## πŸ› οΈ Project Structure
86
+
87
+ ```text
88
+ llm_from_scratch/
89
+ β”œβ”€β”€ model/
90
+ β”‚ β”œβ”€β”€ config.py # ModelConfig dataclass & parameter calculation
91
+ β”‚ β”œβ”€β”€ transformer.py # MiniTransformer, DecoderLayer, CausalSelfAttention
92
+ β”‚ β”œβ”€β”€ positional_encoding.py # Rotary Position Embedding (RoPE) implementation
93
+ β”‚ β”œβ”€β”€ ffn.py # SwiGLU Feed-Forward Network
94
+ β”‚ └── normalization.py # RMSNorm layer
95
+ β”œβ”€β”€ tokenizer/
96
+ β”‚ β”œβ”€β”€ bpe_tokenizer.py # Byte-Level BPE Tokenizer wrapper
97
+ β”‚ └── train_tokenizer.py # BPE training pipeline (8,192 vocab)
98
+ β”œβ”€β”€ training/
99
+ β”‚ β”œβ”€β”€ training_loop.py # Pre-training loop with BF16 & cosine schedule
100
+ β”‚ β”œβ”€β”€ data_loader_setup.py # Chunking & sliding window dataloader
101
+ β”‚ └── sft_dataset.py # SFT dataset with response-only loss masking (-100)
102
+ β”œβ”€β”€ inference/
103
+ β”‚ β”œβ”€β”€ generate.py # Top-k / Top-p KV-cache sampling
104
+ β”‚ └── generate_stream.py # Streaming generator for web UI
105
+ β”œβ”€β”€ scripts/
106
+ β”‚ β”œβ”€β”€ download_modern_corpus.py # Scrapes 100+ technical articles & algorithms
107
+ β”‚ β”œβ”€β”€ prepare_dev_sft.py # Downloads CodeAlpaca & blends SFT dataset
108
+ β”‚ └── download_alpaca.py # Stanford Alpaca downloader
109
+ β”œβ”€β”€ checkpoints/
110
+ β”‚ β”œβ”€β”€ model_dev_best.pt # Developer SFT Checkpoint (Val Loss: 2.2727)
111
+ β”‚ β”œβ”€β”€ model_sft_best.pt # Conversational SFT Checkpoint
112
+ β”‚ └── model_best.pt # Base Pre-Trained Model (Val Loss: 4.6697)
113
+ β”œβ”€β”€ app.py # Gradio Web Interface
114
+ β”œβ”€β”€ chat.py # Interactive Terminal REPL
115
+ β”œβ”€β”€ train.py # Pre-training execution script
116
+ β”œβ”€β”€ train_sft.py # SFT execution script
117
+ └── requirements.txt # Environment specifications
118
+ ```
119
+
120
+ ---
121
+
122
+ ## πŸ“Š Training Results Summary
123
+
124
+ ```text
125
+ [Pre-Training]
126
+ Corpus: 2,659,709 tokens (101 modern encyclopedic & algorithmic files)
127
+ Vocabulary: 8,192 Byte-Level BPE tokens
128
+ Context Length: 256 tokens | Batch Size: 16 | Hardware: RTX 5070 BF16
129
+ Epoch 1/5: Val Loss = 5.5954
130
+ Epoch 2/5: Val Loss = 5.0667
131
+ Epoch 3/5: Val Loss = 4.7951
132
+ Epoch 4/5: Val Loss = 4.6697 [BEST BASE MODEL]
133
+
134
+ [Code & Developer SFT]
135
+ Dataset: 25,022 pairs (CodeAlpaca 20k + Alpaca Assistant)
136
+ Supervision: Response-Only Loss Masking (-100) | LR: 2.5e-5
137
+ Epoch 1/3: Train Loss = 3.0428 | Val Loss = 2.5424
138
+ Epoch 2/3: Train Loss = 2.2934 | Val Loss = 2.3226
139
+ Epoch 3/3: Train Loss = 2.0401 | Val Loss = 2.2727 [BEST DEV MODEL]
140
+ ```