Tiny LLM is my personal project: a small large language model built from scratch in PyTorch (😁 I'm still learning). Every layer is written by hand, and the same code can be trained from zero or load real open LLMs (GPT-2, Llama / SmolLM2, Qwen2.5, Pythia) with outputs identical to Hugging Face, fine-tune them with LoRA, and chat with them.
Related projects: a question-answering chatbot built by fine-tuning pre-trained language models here, a context-based question answering model here, and a question answering system built on the original encoder-decoder transformer here.
Note: This is a learning project and does not represent a production-grade solution. The focus is on educational growth and experimentation.
- Introduction
- Quick Start
- Project Structure
- Data
- Background: How LLMs Work
- Model Architecture
- Supported Model Families
- Features of this project
- Explanatory Videos
- Training
- Inference
- Fine Tuning
- Chatbot Interface
- Sanity Check on Simple Data
- Tests
- Contributors
- Contact Us
- About Me
Welcome to the Tiny LLM repository! I built this project to understand large language models by writing one from scratch, taking inspiration from Hugging Face Transformers and from the papers behind today's open models.
This README walks through the whole process: data collection, model architecture, pre-training, fine-tuning (with LoRA), and finally a small chatbot interface to talk with the model.
The code is not tied to one model: a handful of architecture switches let the same implementation load GPT-2, Llama / SmolLM2, Qwen2.5 and Pythia checkpoints, see Supported Model Families.
git clone https://github.com/benisalla/tiny-llm.git
cd tiny-llm
python -m venv .venv && source .venv/bin/activate
pip install -e model/ # the `tiny_llm` package (torch, transformers, numpy, tiktoken)
pip install -r chatbot/requirements.txt
# talk to the model in your browser
streamlit run chatbot/app.pyFree GPU: upload notebooks/train_kaggle_colab.ipynb to Kaggle or Colab and press Run all: it trains, fine-tunes and chats, with no setup.
Docs: architecture · training · inference · testing
No checkpoint yet? The chatbot can load pre-trained small LLMs (GPT-2, SmolLM2, Qwen2.5, Pythia...) straight into our from-scratch architecture (downloaded on first use). Instruct models get a real multi-turn chat.
tiny-llm/
├── model/ # everything about the LLM
│ ├── tiny_llm/ # the python package
│ │ ├── config.py # ModelConfig (architecture switches) + TrainConfig (optimisation)
│ │ ├── norm.py # LayerNorm (GPT-2, Pythia) and RMSNorm (Llama, Qwen2)
│ │ ├── rope.py # rotary position embeddings (Llama, Qwen2, Pythia)
│ │ ├── attention.py # causal self-attention, grouped-query attention, KV cache
│ │ ├── mlp.py # MLP: classic (GELU) or gated (SwiGLU)
│ │ ├── block.py # DBlock = attention + MLP, sequential or parallel residual
│ │ ├── model.py # TinyLLM: embeddings, N blocks, lm_head, generation
│ │ ├── families.py # what changes for each model family + weight name mapping
│ │ ├── pretrained.py # load any supported Hugging Face checkpoint into TinyLLM
│ │ ├── lora.py # LoraLinear, LoraEmbedding, freeze / merge helpers
│ │ ├── tokenizer.py # any HF tokenizer + our special tokens + Q&A prompt format
│ │ ├── data.py # pre-training batches (.bin) and Q&A BatchLoader (.json)
│ │ ├── training.py # lr schedule, loss estimation, the training loop
│ │ ├── checkpoint.py # save / load checkpoints
│ │ ├── generation.py # completion, question answering and chat (streaming)
│ │ └── runtime.py # device, mixed precision, model init, CLI parsing
│ ├── scripts/
│ │ ├── prepare_data.py # .txt files -> train.bin / val.bin / test.bin
│ │ ├── train.py # pre-training
│ │ ├── finetune.py # (LoRA) fine-tuning on question/answer data
│ │ ├── generate.py # text completion from the command line
│ │ ├── ask.py # ask a question to a fine-tuned checkpoint
│ │ ├── make_toy_data.py # small synthetic datasets (arithmetic, reading comprehension)
│ │ ├── eval_toy.py # exact-match accuracy on them
│ │ └── list_families.py # print the supported families table
│ ├── tests/ # pytest suite
│ └── pyproject.toml
├── chatbot/ # a simple interface to use the model
│ ├── engine.py # backend: loads the model, streams answers
│ ├── app.py # frontend: Streamlit chat UI
│ └── tests/
├── notebooks/ # self-contained Kaggle / Colab notebook (free GPU)
│ ├── build_notebook.py # generates it from the package, so it never drifts from the code
│ └── train_kaggle_colab.ipynb
└── docs/ # architecture, training, inference, testing
To train GPT-2, OpenAI needed a substantial corpus of 40 GB of high-quality text. While Common Crawl provided the necessary scale for modern language models, its quality was often inconsistent. Manually curating data from Common Crawl was an option but a costly one. Fortunately, Reddit provided a decentralized curation approach by design, proving to be a crucial innovation for creating the WebText dataset.
The WebText generation process can be summarized as follows:
- Retrieve URLs of all Reddit submissions until December 2017 with a score of 3 or higher.
- Deduplicate retrieved content based on URLs.
- Exclude Wikipedia content, as OpenAI already had a separate Wikipedia dataset.
- Further deduplicate the remaining content using an undisclosed "heuristic" cleaning method, including the removal of non-English web pages.
Neither the resulting corpus nor the source code for its generation was made public, which later inspired Aaron Gokaslan and Vanya Cohen to create the OpenWebText corpus.
OpenWebText2 is an enhanced version of the original OpenWebText corpus, covering all Reddit submissions from 2005 to April 2020, with additional months becoming available after the publication of corresponding PushShift backup files.
Due to resource constraints, we trained our model on only a quarter of the OpenWebText dataset. This limitation in training data was necessary to optimize computational resources while still achieving significant language model performance.
We combined approximately 5 million files from the OpenWebText dataset, roughly equivalent to a quarter of the entire OpenWebText corpus. Subsequently, we performed the following steps:
- We used the GPT-2 tokenizer, also known as "r50k_base", to tokenize the dataset.
import tiktoken
tokenizer = tiktoken.get_encoding("r50k_base")- Following established conventions for dataset splitting, we divided the data into training, validation and test sets (80% / 10% / 10%).
- To optimize data management and efficiency, we stored the token ids as a binary stream (
uint16) in thetrain.bin,val.binandtest.binfiles.
All of this is now one command:
python model/scripts/prepare_data.py --src ./raw_txt --dst ./data/openwebtext --val_ratio 0.1 --test_ratio 0.1Our dataset is currently accessible on Kaggle:
A large language model is trained on one simple task: predict the next token. Given "The capital of France is", it outputs a probability for every token of its vocabulary, and " Paris" should get the highest one. Generating text is just repeating this: pick a token, append it, predict again.
Doing this well on billions of words forces the model to learn grammar, facts and some reasoning, which is why the same network can then answer questions, summarise or chat once it is fine-tuned. Since GPT-2 (2019) almost every open LLM uses the same recipe: a stack of decoder-only transformer blocks trained on large web corpora. The models differ in size, data and a few design choices, not in the core idea.
Small open models are perfect to learn with: they run on a laptop, and Tiny LLM can load all of these:
The original transformer had an encoder and a decoder. LLMs keep only the decoder: masked (causal) self-attention, where each token only looks at the tokens before it, followed by a feed-forward MLP, repeated N times with residual connections and normalisation.
In code (model/tiny_llm/):
| component | module |
|---|---|
| token embeddings (+ learned positions or RoPE) | TinyLLM.transformer.wte / wpe, RotaryEmbedding |
| masked multi-head / grouped-query self-attention, KV cache | CausalSelfAttention |
| feed-forward (GELU or SwiGLU) | MLP |
| pre-norm residual block (x N), sequential or parallel | DBlock |
| LayerNorm / RMSNorm | LayerNorm, RMSNorm |
| final norm + language model head | ln_f, lm_head |
The test suite checks that this implementation produces the same logits and the same greedy generations as Hugging Face for every supported family.
Most small open LLMs are the same decoder-only transformer as GPT-2. They only differ by a few design choices, and each of those choices is one field of ModelConfig. Here is what should be changed for each type of model (defaults = GPT-2):
ModelConfig field |
GPT-2 / DistilGPT2 | Llama (SmolLM2, TinyLlama) | Qwen2 (Qwen2.5) | GPT-NeoX (Pythia) |
|---|---|---|---|---|
norm_type |
layernorm |
rmsnorm |
rmsnorm |
layernorm |
pos_encoding |
learned (position matrix) |
rope |
rope |
rope |
rotary_pct |
- | 1.0 |
1.0 |
0.25 (only a quarter of each head is rotated) |
activation |
gelu_tanh |
silu |
silu |
gelu |
gated_mlp |
False |
True (SwiGLU) |
True (SwiGLU) |
False |
n_kv_head |
= n_head |
fewer (grouped-query attention) | fewer (grouped-query attention) | = n_head |
bias / qkv_bias |
True / True |
False / False |
False / True |
True / True |
parallel_residual |
False |
False |
False |
True |
tie_embeddings |
True |
depends on the checkpoint | depends on the checkpoint | False |
The weights also need to be renamed into our layout (GPT-2 names): for example Llama's separate q_proj, k_proj, v_proj are concatenated into our fused c_attn, and Pythia's per-head interleaved query_key_value is reordered. All of this lives in model/tiny_llm/families.py, one readable block per family (python model/scripts/list_families.py prints its summary).
from tiny_llm import TinyLLM, create_tokenizer, generate_text
name = "HuggingFaceTB/SmolLM2-135M" # or "gpt2", "Qwen/Qwen2.5-0.5B", "EleutherAI/pythia-160m", ...
tokenizer = create_tokenizer(name) # its own tokenizer + our special tokens
model = TinyLLM.from_pretrained(name, tokenizer)
print(generate_text(model, tokenizer, "Once upon a time", max_new_tokens=40))Every script accepts these names too (--init_from HuggingFaceTB/SmolLM2-135M, --pretrained Qwen/Qwen2.5-0.5B), so you can continue pre-training or LoRA fine-tune any of them.
Verified: for each family the tests build a model with Hugging Face, load it into TinyLLM, and check that the logits and the greedy generations (with and without KV cache) are identical.
Adding a new family: write its to_config (read the Hugging Face config) and convert (rename the weights) in families.py and call register(...). If it needs a design choice that doesn't exist yet (e.g. Gemma multiplies the embeddings by sqrt(n_embd)), add a field to ModelConfig and use it in the layer. Not supported yet: RoPE scaling (Llama 3.x), sliding-window attention, q/k norms (Qwen3), mixture of experts.
-
Tiny Scale: small enough to train and run on a laptop, so every step can be understood and tested.
-
Inspired by the best open implementations: design choices follow Hugging Face Transformers and the papers behind GPT-2, Llama, Qwen and Pythia.
-
From scratch, many models: every layer is written by hand, yet GPT-2, Llama/SmolLM2, Qwen2.5 and Pythia checkpoints load into it and give the same outputs as Hugging Face.
-
Fast generation: KV cache, grouped-query attention, top-k / top-p sampling, streaming.
-
LoRA fine-tuning: fine-tune HUGE LLMs by training only small low-rank matrices, then merge them back for free inference.
-
A chatbot interface: a Streamlit app to chat with your model.
I've created explanatory videos to help you understand the intricate link between the architecture and the code, as it might not be immediately obvious.
cd model
# pre-train from scratch (GPT-2 small size by default)
python scripts/train.py --data_dir ./data/openwebtext --init_from scratch
# a small run that fits on a laptop
python scripts/train.py --data_dir ./data/openwebtext --n_layer 4 --n_head 4 --n_embd 256 \
--block_size 256 --batch_size 8 --grad_accum_steps 4
# continue from the last checkpoint
python scripts/train.py --data_dir ./data/openwebtext --init_from resumeEvery field of ModelConfig and TrainConfig is a command-line flag (python scripts/train.py --help). Checkpoints go to ./checkpoints/ckpt.pt whenever the validation loss improves. Mixed precision (bfloat16 / float16) is used automatically on GPU.
python scripts/generate.py --ckpt ./checkpoints/ckpt.pt --prompt "ismail ben alla is the next elon mask because"
python scripts/generate.py --pretrained gpt2 --prompt "Once upon a time" # original GPT-2 weightsFine-tuning data is a JSON list of {"context": ..., "question": ..., "answer": ...} in train.json and val.json. Each sample becomes:
<sost>{context}<ques>{question}<ans>{answer}<eost>
By default the loss is only computed on the answer (--loss_on_answer_only true) and padding is never part of the loss.
cd model
# LoRA fine-tuning of GPT-2 (only the low-rank matrices + token embeddings are trained)
python scripts/finetune.py --init_from gpt2 --data_dir ./data/qa --lora_rank 8 \
--learning_rate 3e-4 --drop_rate 0.1 --max_iters 2000
# LoRA fine-tuning of our own pre-trained model
python scripts/finetune.py --init_from resume --resume_from ./checkpoints/ckpt.pt --data_dir ./data/qa --lora_rank 8
# ask it something
python scripts/ask.py --ckpt ./checkpoints/finetuned.pt \
--context "Ismail Ben Alla built Tiny LLM from scratch in PyTorch." --question "Who built Tiny LLM?"For more details, see the project Fine-Tuning Pretrained GPT-2, where GPT-2 has been fine-tuned specifically for context-question-answer scenarios.
streamlit run chatbot/app.py
# or point it to a specific checkpoint
TINY_LLM_CKPT=model/checkpoints/finetuned.pt streamlit run chatbot/app.py- Weights: one of your checkpoints (
.pt) or any supported pre-trained small LLM (SmolLM2, Qwen2.5, GPT-2, Pythia, or any Hugging Face id of a supported family). - Modes: chat for instruct models (multi-turn, uses the model's own chat template), question answering (with an optional context paragraph) for checkpoints fine-tuned with
finetune.py, text completion for base models. The right mode is picked automatically. - Generation settings: max new tokens, temperature, top-k, top-p. Answers are streamed token by token.
The backend (chatbot/engine.py) has no UI code, so the same ChatEngine can be used from a notebook or behind an API:
from engine import ChatEngine
bot = ChatEngine.from_checkpoint("model/checkpoints/finetuned.pt")
print(bot.reply("Who built Tiny LLM?", context="Ismail Ben Alla built Tiny LLM."))
bot = ChatEngine.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
print(bot.reply("What is the capital of France?")) # -> "The capital of France is Paris."Unit tests prove the code is correct; these two small synthetic tasks prove the model actually learns, in minutes on a CPU.
cd model
python scripts/make_toy_data.py --out ./data/toy
# 1. pre-training from scratch: learn addition, scored on 1,000 problems never seen in training
python scripts/train.py --data_dir ./data/toy/arithmetic --ckpt_name arithmetic.pt \
--n_layer 4 --n_head 4 --n_embd 128 --block_size 32 --batch_size 16 --grad_accum_steps 1 \
--learning_rate 3e-3 --min_lr 3e-4 --warmup_iters 50 --lr_decay_iters 1500 --max_iters 1500 --eval_interval 250
python scripts/eval_toy.py arithmetic --ckpt ./checkpoints/arithmetic.pt --data ./data/toy/arithmetic/test.json
# 2. LoRA fine-tuning: reading comprehension, scored on people / cities / jobs never seen in training
python scripts/eval_toy.py qa --pretrained distilgpt2 --data ./data/toy/qa/val.json # before fine-tuning
python scripts/finetune.py --init_from distilgpt2 --data_dir ./data/toy/qa --lora_rank 8 --learning_rate 1e-3 \
--min_lr 1e-4 --max_iters 300 --warmup_iters 20 --lr_decay_iters 300 --grad_accum_steps 1 --toks_per_batch 2000 \
--eval_interval 100 --ckpt_name qa_finetuned.pt
python scripts/eval_toy.py qa --ckpt ./checkpoints/qa_finetuned.pt --data ./data/toy/qa/val.jsonResults (CPU only, on a shared and heavily loaded machine; exact match, greedy decoding):
| task | setup | before | after | evaluated on |
|---|---|---|---|---|
addition a+b= |
7M-param model from scratch, 1,500 steps (~45 min) | 0% (random) | 30.1% | 1,000 problems never seen in training |
| reading comprehension | LoRA (rank 8) on DistilGPT2, 300 steps | 0% | 40.0% | 100 questions about unseen people, cities and jobs |
| train loss | val loss | |
|---|---|---|
| addition (step 0 → 1,500) | 10.83 → 1.86 | 10.83 → 1.87 |
| reading comprehension (step 0 → 300) | 55.99 → 0.00 | 55.28 → 1.82 (best 1.71 at step 200) |
Reading the numbers honestly:
- Addition: train and val loss stay together, so the model learns the rule, not the pairs. The loss
can't go much below ~1.2 because
aandbare random. Wrong answers are usually close (95+96=→188,7+83=→89), and the loss was still falling: longer training (e.g. the Kaggle notebook on a GPU) raises the accuracy. - Reading comprehension: the base model has never seen the
<sost>…<ques>…<ans>format and just repeats the question; after LoRA it answers in the right format and reads the right fact for 40% of unseen entities. The gap between train (0.00) and val (1.82) loss shows it overfits the 600 training samples: more data, early stopping (best val loss was at step 200) or a larger model would help.
pip install pytest
cd model && pytest # layers, LoRA, model, data, training, scripts end-to-end,
# every family vs Hugging Face (tiny random models, no download), GPT-2 weights
cd ../chatbot && pytest # engine + the Streamlit UI (headless)
pytest -m "not network" # skip tests that download GPT-2 from the Hugging Face Hub
TINY_LLM_TEST_HUB=1 pytest tests/test_hub_models.py # real DistilGPT2, SmolLM2, Pythia, Qwen2.5 (~1.7 GB)Thanks to the team who built this project with me:
For inquiries or suggestions, please contact:
- Project Lead: Ben alla ismail (ismailbenalla52@gmail.com)
- Co-lead: mhaoui Siham (mahouisiham@gmail.com)
🎓 I'm Ismail Ben Alla, and I have a deep passion for neural networks 😍. My mission is to assist neural networks in unraveling the mysteries of our universe.
⛵ I'm an enthusiast when it comes to AI, Deep Learning, and Machine Learning algorithms.
✅ I'm an optimist and a dedicated hard worker, constantly striving to push the boundaries of what's possible.
🌱 I'm committed to continuously learning and staying updated with advanced computer science technologies.
😄 I absolutely love what I do, and I'm excited about the endless possibilities in the world of AI and machine learning!
Let's connect and explore the fascinating world of artificial intelligence together! 🤖🌟









