TinyStories GPT-124M

A 124.4M-parameter GPT-style decoder-only transformer trained from scratch in PyTorch on TinyStories. No pretrained weights and no external ML framework — attention, MLPs, the training loop, and the tokenization pipeline are all implemented explicitly in roughly 700 lines of Python.

  • Final validation loss: 1.133 (perplexity 3.09) over the full validation set
  • 50,000 optimizer steps, ~3.28B tokens, single RTX 5080 (16 GB)
  • Final model corresponds to training step 50,000

Architecture

Parameters 124.4M (input/output embeddings tied)
Layers 12
d_model / heads / d_head 768 / 12 / 64
Feed-forward 3072 (4×, GELU with tanh approximation)
Context length 1024
Vocabulary 50,257 (GPT-2 BPE via tiktoken)
Position encoding Learned absolute embeddings
Normalization Pre-LayerNorm
Attention F.scaled_dot_product_attention(is_causal=True) → Flash Attention on supported GPUs
Precision bfloat16 mixed precision (no gradient scaler needed)

Training

Dataset TinyStories (469.4M train tokens / 4.72M val tokens)
Steps 50,000
Effective batch 64 sequences (16 micro-batch × 4 grad-accum) × 1024 tokens = 65,536 tokens/step
Tokens seen 3.28B (7 epochs over the training split)
Optimizer AdamW (β₁=0.9, β₂=0.95, ε=1e-8, weight decay 0.1, no decay on biases/LayerNorm)
LR schedule Linear warmup 500 steps → cosine decay 3e-4 → 1e-5
Gradient clipping 1.0
Hardware 1× NVIDIA RTX 5080 16 GB, PyTorch eager mode (Triton unavailable on Windows)
Seed 42

Evaluation

Final model (step 50,000) evaluated in eval mode (dropout off) with bf16 autocast:

Metric Value
Validation loss (exhaustive) 1.1331
Validation perplexity 3.09
Validation tokens 4,723,712 (4,613 non-overlapping 1024-token windows)
Validation loss (training-style, 50 random batches × 16) 1.1483
Train-split loss (200 random batches × 16) 1.0404
Train→val gap +0.093

The exhaustive validation loss covers every token in the validation split with no sampling noise. The small train/validation gap indicates no meaningful overfitting.

Reproduce with scripts/eval_final_loss.py (expects a locally trained checkpoint at checkpoints/step_050000.pt).

Sample generations

Sampling: temperature 0.8, top-k 40, bf16.

Prompt: Once upon a time

Once upon a time, there was a little girl named Lily. She loved to play outside and pick flowers. One day, she found a big squash in her garden. It was so big and round that she couldn't carry it by herself.
Lily's mom saw her struggling and said, "Do you need help, Lily?"
Lily replied, "Yes, please!"
So, her mom helped her pick up the squash and put it in the basket. Lily was so happy that she could finally carry it. She said, "I can carry it! It's my big squash!"
Her mom smiled and said, "Yes, it's a big squash. Good job, Lily!"

Prompt: Once upon a time, there was a small rabbit who lived in the forest.

He was always very curious and wanted to explore the world. One day, he decided to go on a journey and he set off.
He hopped and hopped until he came to a big, green field. In the middle of the field, he saw a big, shiny machine. He had never seen anything like it before and he was very excited.
The rabbit hopped closer and closer to the machine. He wanted to know what it was and why it was there. Suddenly, he heard a voice coming from the machine.
"Hello there," said the voice. "I am a magical machine. I can do lots of things. What would you like me to do?"
The rabbit was very surprised. He had never seen a machine like this before. He thought for a moment and then said, "I want to learn how to do things!"

Files

File Description
model.safetensors Model weights (fp32, 124.4M params)
training_config.json Exact model + training configuration used
eval_results.json Final evaluation metrics and methodology
src/ Model, training loop, data pipeline, tokenizer, generation
main.py CLI: train / generate
scripts/eval_final_loss.py Exhaustive validation-loss evaluation
scripts/qualitative_samples.py Batch sample generation from a .pt checkpoint
scripts/load_pretrained.py Load model.safetensors and generate text
pyproject.toml, uv.lock Python dependencies (managed with uv)

Usage

This is a custom architecture and is not compatible with transformers.AutoModelForCausalLM. Use the included GPT class.

git clone https://huggingface.co/mlvar/tinystories-gpt-124m
cd tinystories-gpt-124m
uv sync
uv pip install torch --torch-backend=auto
uv pip install safetensors
uv run python scripts/load_pretrained.py --prompt "Once upon a time" --max-new-tokens 200

Or from Python:

import json
import torch
from safetensors.torch import load_file

from src.config import ModelConfig
from src.model import GPT
from src.tokenizer import Tokenizer

cfg = json.load(open("training_config.json"))["model"]
cfg.pop("d_head")  # derived at init
model = GPT(ModelConfig(**cfg))
model.load_state_dict(load_file("model.safetensors"))
model.eval().to("cuda")

tokenizer = Tokenizer()
ids = torch.tensor([tokenizer.encode("Once upon a time")], device="cuda")
out = model.generate(ids, max_new_tokens=200, temperature=0.8, top_k=40)
print(tokenizer.decode(out[0].tolist()))

Reproducing training

uv sync
uv pip install torch --torch-backend=auto
uv run python main.py train

The TinyStories dataset (~1.9 GB) is downloaded and tokenized automatically on the first run.

Limitations

  • English-only; trained exclusively on TinyStories (simple children's stories). Out-of-domain prompts will produce poor text.
  • 1024-token context. The reference generate() does not use a KV cache; fine for short samples, slow for long ones.
  • No instruction tuning, RLHF, or safety alignment — not a chatbot, not suitable for production use.
  • Typical small-model artifacts at this loss: occasional character-name drift within a story, mild repetition (especially greedy decoding), and semantic slips.
  • Sampling does not stop at <|endoftext|> (token 50256); the model may roll into a new story. Stop on EOT if a single story is wanted.

Acknowledgements

License

No license has been specified for this repository.

Downloads last month

-

Downloads are not tracked for this model. How to track
Safetensors
Model size
0.1B params
Tensor type
F32
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Dataset used to train mlvar/tinystories-gpt-124m