A ground-up LLM engineering project: tokenizer → architecture → training → scaling laws → inference. Starts at 80M, engineered to scale into 1B+ models with minimal changes. Clean, research-ready code for anyone serious about understanding and building LLMs from first principles.
Python
83
27 commits
updated Jan 29, 2026
A production-grade implementation of a decoder-only transformer language model, built from scratch with modern best practices. This project demonstrates the complete pipeline from raw text to a functioning LLM capable of text generation.
The model was trained on an NVIDIA A100 (80GB) for 10,000 steps (5 hours). Despite the small dataset and short training time, it learned grammar, syntax, and basic world knowledge remarkably well.
Prompt: "Hello, how are"
Hello, how are you doing?
Prompt: "Once upon a time, there was a"
Once upon a time, there was a conflict of the most recently completed , it was a finalizing the most often used to the western Köcorporsen.
(Note: The model is still in early training stages. Hallucinations are expected, but grammar is solid!)
Open in Google Colab - Run the demo notebook directly in your browser!
Or download demo.ipynb and run locally with Jupyter:
jupyter notebook demo.ipynb
There are many "build your own GPT" tutorials out there. So why Mini-LLM?
Most beginner LLM projects suffer from one or more of these issues:
| Feature | Most Tutorials | Mini-LLM |
|---|---|---|
| Position Encoding | Learned positions (doesn't extrapolate) | RoPE (scales to longer sequences) |
| Normalization | LayerNorm | RMSNorm (faster, more stable) |
| Activation | GELU/ReLU | SwiGLU (state-of-the-art) |
| Attention | Standard MHA | Grouped Query Attention (efficient) |
| Tokenization | Character-level | SentencePiece BPE (32K vocab) |
| Precision | FP32 only | BF16/FP16 mixed precision |
| Data Loading | Loads everything into RAM | Memory-mapped (TB-scale ready) |
| Inference | No KV cache | Full KV caching (100x faster) |
| Scaling | Hard-coded | Config-driven (80M → 80B) |
Mini-LLM implements the exact same architecture components as Llama 3, just at a smaller scale. This means:
No installation required - test the trained model on HuggingFace: https://huggingface.co/Ashx098/Mini-LLM
Mini-LLM is an educational yet production-ready implementation of a large language model featuring:
┌─────────────────────────────────────────────────────────────┐
│ Mini-LLM Architecture │
├─────────────────────────────────────────────────────────────┤
│ • Decoder-only Transformer (GPT-style) │
│ • 16 layers × 384 hidden dim × 6 attention heads │
│ • RoPE position embeddings (no learned positions) │
│ • RMSNorm (faster than LayerNorm) │
│ • SwiGLU activation (better than GELU) │
│ • Grouped Query Attention support │
│ • Weight tying (embeddings ↔ output layer) │
└─────────────────────────────────────────────────────────────┘
| Metric | Value |
|---|---|
| Parameters | 50,049,408 |
| Vocabulary Size | 32,000 tokens (BPE) |
| Context Length | 512-2048 tokens |
| Training Data | 361M tokens (~1.4GB text) |
| Training Time | ~2-3 hours (5K steps on A100) |
| Inference Speed | 200-500 tokens/sec (with KV cache) |
# Clone repository
git clone https://github.com/Ashx098/Mini-LLM.git
cd Mini-LLM
# Create virtual environment
python -m venv MiniLLM-env
source MiniLLM-env/bin/activate # On Windows: MiniLLM-env\Scripts\activate
# Install dependencies
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
pip install transformers datasets accelerate tokenizers sentencepiece huggingface_hub tqdm numpy scipy pyyaml tensorboard einops wandb
# 1. Prepare data (if not already done)
python data/prepare_data.py
# 2. Train with test config (quick validation)
python run_train.py --config train/config_test.yaml
# 3. Train with production config
python run_train.py --config train/config.yaml
from inference.generate import Generator
# Load trained model
gen = Generator(
checkpoint_path="out/ckpt.pt",
tokenizer_path="Tokenizer/BPE",
device="cuda"
)
# Generate text
output = gen.generate(
prompt="Once upon a time",
max_new_tokens=50,
temperature=0.8,
top_p=0.95
)
print(output)
Mini-LLM/
├── 📄 README.md # This file
├── 🎮 demo.ipynb # Interactive demo notebook (try it!)
├── 🔧 requirements.txt # Python dependencies
├── 🚀 run_train.py # Training entry point
│
├── 📝 Tokenizer/ # Tokenization module
│ ├── README.md # Tokenizer documentation
│ ├── BPE/ # BPE tokenizer artifacts
│ ├── Unigram/ # Unigram baseline
│ ├── train_spm_bpe.py # Train BPE tokenizer
│ └── convert_to_hf.py # Convert to HuggingFace format
│
├── 💾 data/ # Data processing
│ ├── README.md # Data pipeline documentation
│ ├── raw/ # Raw text sources
│ ├── bin/ # Tokenized binary files
│ └── prepare_data.py # Tokenization script
│
├── 🧠 model/ # Model architecture
│ ├── README.md # Architecture documentation
│ ├── config.py # Model configuration
│ ├── embedding.py # Token embeddings
│ ├── rmsnorm.py # RMS normalization
│ ├── rope.py # Rotary position embeddings
│ ├── attention.py # Multi-head attention
│ ├── mlp.py # SwiGLU feedforward
│ ├── transformer_block.py # Single transformer layer
│ └── transformer.py # Full model
│
├── 🏋️ train/ # Training infrastructure
│ ├── README.md # Training documentation
│ ├── config.yaml # Production training config
│ ├── config_test.yaml # Test/debug config
│ ├── dataloader.py # Memory-mapped data loading
│ ├── optimizer.py # AdamW with weight decay
│ ├── lr_scheduler.py # Cosine LR schedule
│ └── train.py # Main training loop
│
├── 🎯 inference/ # Text generation
│ ├── README.md # Inference documentation
│ ├── sampling.py # Sampling strategies
│ └── generate.py # Generation engine
│
└── 🧪 tests/ # Validation tests
├── model/ # Model component tests
├── tokenizer/ # Tokenizer tests
└── train/ # Training tests
Each module has comprehensive documentation with examples and diagrams:
Loss
│
300│ ●
│ ●
200│ ●●
│ ●●●
100│ ●●●●●
│ ●●●●●●●
50│ ●●●●●●●
│ ●●●●●●
10│_________________________________●●●
0 1000 2000 3000 4000 5000
Steps
After 10 steps (untrained):
Prompt: "Hello world"
Output: "Hello world c c c c c c c c c c"
After 10,000 steps:
Prompt: "Once upon a time"
Output: "Once upon a time, there was a young girl who lived in a small village..."
After 50,000 steps:
Prompt: "Write a Python function to"
Output: "Write a Python function to calculate the factorial of a number:
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)"
Training is controlled via YAML config files. Key parameters:
# Training
batch_size: 16 # Micro-batch size
block_size: 512 # Context length
gradient_accumulation_steps: 4 # Effective batch = 64
max_iters: 5000 # Total training steps
# Learning Rate
learning_rate: 6.0e-4 # Peak LR
min_lr: 6.0e-5 # Minimum LR
warmup_iters: 200 # Warmup steps
# Optimizer
weight_decay: 0.1 # L2 regularization
beta1: 0.9 # Adam beta1
beta2: 0.95 # Adam beta2
grad_clip: 1.0 # Gradient clipping
# System
device: 'cuda' # 'cuda' or 'cpu'
compile: true # Use torch.compile
dtype: 'bfloat16' # 'bfloat16', 'float16', or 'float32'
# Test model components
python tests/model/test_phase2_final.py
# Test dataloader
python tests/train/test_phase3_2.py
# Test optimizer & scheduler
python tests/train/test_phase3_3_4.py
python run_inference.py --prompt "The future of AI is" --temp 0.7
python plot_logs.py
Contributions are welcome! Please:
git checkout -b feature/amazing-feature)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)This project is licensed under the MIT License - see the LICENSE file for details.
Built with ❤️ for the ML community
3 followers · starred Jan 2026
A ground-up LLM engineering project: tokenizer → architecture → training → scaling laws → inference. Starts at 80M, engineered to scale into 1B+ models with minimal changes. Clean, research-ready code for anyone serious about understanding and building LLMs from first principles.
Python
83
27 commits
updated Jan 29, 2026
A production-grade implementation of a decoder-only transformer language model, built from scratch with modern best practices. This project demonstrates the complete pipeline from raw text to a functioning LLM capable of text generation.
The model was trained on an NVIDIA A100 (80GB) for 10,000 steps (5 hours). Despite the small dataset and short training time, it learned grammar, syntax, and basic world knowledge remarkably well.
Prompt: "Hello, how are"
Hello, how are you doing?
Prompt: "Once upon a time, there was a"
Once upon a time, there was a conflict of the most recently completed , it was a finalizing the most often used to the western Köcorporsen.
(Note: The model is still in early training stages. Hallucinations are expected, but grammar is solid!)
Open in Google Colab - Run the demo notebook directly in your browser!
Or download demo.ipynb and run locally with Jupyter:
jupyter notebook demo.ipynb
There are many "build your own GPT" tutorials out there. So why Mini-LLM?
Most beginner LLM projects suffer from one or more of these issues:
| Feature | Most Tutorials | Mini-LLM |
|---|---|---|
| Position Encoding | Learned positions (doesn't extrapolate) | RoPE (scales to longer sequences) |
| Normalization | LayerNorm | RMSNorm (faster, more stable) |
| Activation | GELU/ReLU | SwiGLU (state-of-the-art) |
| Attention | Standard MHA | Grouped Query Attention (efficient) |
| Tokenization | Character-level | SentencePiece BPE (32K vocab) |
| Precision | FP32 only | BF16/FP16 mixed precision |
| Data Loading | Loads everything into RAM | Memory-mapped (TB-scale ready) |
| Inference | No KV cache | Full KV caching (100x faster) |
| Scaling | Hard-coded | Config-driven (80M → 80B) |
Mini-LLM implements the exact same architecture components as Llama 3, just at a smaller scale. This means:
No installation required - test the trained model on HuggingFace: https://huggingface.co/Ashx098/Mini-LLM
Mini-LLM is an educational yet production-ready implementation of a large language model featuring:
┌─────────────────────────────────────────────────────────────┐
│ Mini-LLM Architecture │
├─────────────────────────────────────────────────────────────┤
│ • Decoder-only Transformer (GPT-style) │
│ • 16 layers × 384 hidden dim × 6 attention heads │
│ • RoPE position embeddings (no learned positions) │
│ • RMSNorm (faster than LayerNorm) │
│ • SwiGLU activation (better than GELU) │
│ • Grouped Query Attention support │
│ • Weight tying (embeddings ↔ output layer) │
└─────────────────────────────────────────────────────────────┘
| Metric | Value |
|---|---|
| Parameters | 50,049,408 |
| Vocabulary Size | 32,000 tokens (BPE) |
| Context Length | 512-2048 tokens |
| Training Data | 361M tokens (~1.4GB text) |
| Training Time | ~2-3 hours (5K steps on A100) |
| Inference Speed | 200-500 tokens/sec (with KV cache) |
# Clone repository
git clone https://github.com/Ashx098/Mini-LLM.git
cd Mini-LLM
# Create virtual environment
python -m venv MiniLLM-env
source MiniLLM-env/bin/activate # On Windows: MiniLLM-env\Scripts\activate
# Install dependencies
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
pip install transformers datasets accelerate tokenizers sentencepiece huggingface_hub tqdm numpy scipy pyyaml tensorboard einops wandb
# 1. Prepare data (if not already done)
python data/prepare_data.py
# 2. Train with test config (quick validation)
python run_train.py --config train/config_test.yaml
# 3. Train with production config
python run_train.py --config train/config.yaml
from inference.generate import Generator
# Load trained model
gen = Generator(
checkpoint_path="out/ckpt.pt",
tokenizer_path="Tokenizer/BPE",
device="cuda"
)
# Generate text
output = gen.generate(
prompt="Once upon a time",
max_new_tokens=50,
temperature=0.8,
top_p=0.95
)
print(output)
Mini-LLM/
├── 📄 README.md # This file
├── 🎮 demo.ipynb # Interactive demo notebook (try it!)
├── 🔧 requirements.txt # Python dependencies
├── 🚀 run_train.py # Training entry point
│
├── 📝 Tokenizer/ # Tokenization module
│ ├── README.md # Tokenizer documentation
│ ├── BPE/ # BPE tokenizer artifacts
│ ├── Unigram/ # Unigram baseline
│ ├── train_spm_bpe.py # Train BPE tokenizer
│ └── convert_to_hf.py # Convert to HuggingFace format
│
├── 💾 data/ # Data processing
│ ├── README.md # Data pipeline documentation
│ ├── raw/ # Raw text sources
│ ├── bin/ # Tokenized binary files
│ └── prepare_data.py # Tokenization script
│
├── 🧠 model/ # Model architecture
│ ├── README.md # Architecture documentation
│ ├── config.py # Model configuration
│ ├── embedding.py # Token embeddings
│ ├── rmsnorm.py # RMS normalization
│ ├── rope.py # Rotary position embeddings
│ ├── attention.py # Multi-head attention
│ ├── mlp.py # SwiGLU feedforward
│ ├── transformer_block.py # Single transformer layer
│ └── transformer.py # Full model
│
├── 🏋️ train/ # Training infrastructure
│ ├── README.md # Training documentation
│ ├── config.yaml # Production training config
│ ├── config_test.yaml # Test/debug config
│ ├── dataloader.py # Memory-mapped data loading
│ ├── optimizer.py # AdamW with weight decay
│ ├── lr_scheduler.py # Cosine LR schedule
│ └── train.py # Main training loop
│
├── 🎯 inference/ # Text generation
│ ├── README.md # Inference documentation
│ ├── sampling.py # Sampling strategies
│ └── generate.py # Generation engine
│
└── 🧪 tests/ # Validation tests
├── model/ # Model component tests
├── tokenizer/ # Tokenizer tests
└── train/ # Training tests
Each module has comprehensive documentation with examples and diagrams:
Loss
│
300│ ●
│ ●
200│ ●●
│ ●●●
100│ ●●●●●
│ ●●●●●●●
50│ ●●●●●●●
│ ●●●●●●
10│_________________________________●●●
0 1000 2000 3000 4000 5000
Steps
After 10 steps (untrained):
Prompt: "Hello world"
Output: "Hello world c c c c c c c c c c"
After 10,000 steps:
Prompt: "Once upon a time"
Output: "Once upon a time, there was a young girl who lived in a small village..."
After 50,000 steps:
Prompt: "Write a Python function to"
Output: "Write a Python function to calculate the factorial of a number:
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)"
Training is controlled via YAML config files. Key parameters:
# Training
batch_size: 16 # Micro-batch size
block_size: 512 # Context length
gradient_accumulation_steps: 4 # Effective batch = 64
max_iters: 5000 # Total training steps
# Learning Rate
learning_rate: 6.0e-4 # Peak LR
min_lr: 6.0e-5 # Minimum LR
warmup_iters: 200 # Warmup steps
# Optimizer
weight_decay: 0.1 # L2 regularization
beta1: 0.9 # Adam beta1
beta2: 0.95 # Adam beta2
grad_clip: 1.0 # Gradient clipping
# System
device: 'cuda' # 'cuda' or 'cpu'
compile: true # Use torch.compile
dtype: 'bfloat16' # 'bfloat16', 'float16', or 'float32'
# Test model components
python tests/model/test_phase2_final.py
# Test dataloader
python tests/train/test_phase3_2.py
# Test optimizer & scheduler
python tests/train/test_phase3_3_4.py
python run_inference.py --prompt "The future of AI is" --temp 0.7
python plot_logs.py
Contributions are welcome! Please:
git checkout -b feature/amazing-feature)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)This project is licensed under the MIT License - see the LICENSE file for details.
Built with ❤️ for the ML community
3 followers · starred Jan 2026