Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

18 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MiniGPT — Transformer Language Model in JAX/Flax

A ~20M-parameter GPT-style language model built from scratch using JAX and Flax NNX, trained on the TinyStories dataset. The goal is to implement the full training pipeline — data loading, tokenization, causal attention, and checkpointing — without relying on high-level training wrappers.

Architecture

MiniGPT
├── TokenAndPositionEmbedding        # token embeddings + learned positional embeddings
├── TransformerBlock × 6             # pre-norm: LayerNorm → MHA → residual
│   ├── LayerNorm                    #           LayerNorm → FFN → residual
│   ├── MultiHeadAttention (causal)
│   ├── LayerNorm
│   └── FeedForward  (Linear → GELU → Linear)
└── Linear (output projection)       # logits over GPT-2 vocabulary (50 257 tokens)
Hyperparameter Value
Context length 128
Embedding dim 192
Attention heads 6
FF hidden dim 512
Transformer blocks 6
Vocabulary size 50 257

Pre-norm layout: layer normalisation is applied to the input before each sublayer (attention and feedforward), which stabilises training compared to the original post-norm formulation. The causal mask is a lower-triangular matrix (jnp.tril) passed to nnx.MultiHeadAttention, preventing each position from attending to future tokens.

Stack

Library Role
JAX Accelerated array ops, jit, vmap
Flax NNX Neural network modules and mutable state management
Optax AdamW optimizer + warmup cosine decay LR schedule
Grain Efficient data loading with JAX-friendly fixed-shape batches
tiktoken GPT-2 BPE tokenizer (vocab size 50 257)
Orbax Model checkpoint save/restore
Typer CLI for training and inference

Project Structure

gpt2/
├── architecture.py     # TokenAndPositionEmbedding, TransformerBlock, MiniGPT
├── train.py            # Training loop, optimizer, LR schedule, checkpointing
├── inference.py        # Text generation (greedy + temperature), model loading
├── cli.py              # Typer CLI — train / model-inference commands
├── main.py             # Entry point
├── const.py            # Shared paths and constants (PROJECT_ROOT, DATA_PATH, CHECKPOINT_PATH)
└── process/
    └── load.py         # load_stories, StoryDataset, Grain DataLoader
data/
└── TinyStories-1000.txt   # 1 000-story sample for local development
trained_models/            # saved checkpoints (gitignored)

Quickstart

# CPU (default)
uv sync

# NVIDIA GPU (CUDA 12)
uv sync --extra cuda

# Google TPU
uv sync --extra tpu

JAX selects the best available backend automatically. The training and inference entry points print the active backend and device list at startup so you can confirm what is being used.

CLI Reference

Download the dataset

The repo ships with a 1 000-story sample (data/TinyStories-1000.txt) for quick local runs. To download the full 2M-story dataset from HuggingFace:

uv run python -m gpt2.main download-data

# Save to a custom path
uv run python -m gpt2.main download-data --output data/my-dataset.txt

Train

# Train for 5 epochs on the built-in 1k sample
uv run python -m gpt2.main train 5
# → JAX backend: gpu | devices: [CudaDevice(id=0)]

# Train for 5 epochs with 20 warmup steps
uv run python -m gpt2.main train 5 20

# Train on the full TinyStories dataset
uv run python -m gpt2.main train 5 --data data/TinyStories-train.txt

Inference

# Run inference with the default prompt
uv run python -m gpt2.main model-inference

# Run inference with a custom prompt
uv run python -m gpt2.main model-inference "The little fox"

# Run inference with custom temperature and token count
uv run python -m gpt2.main model-inference "The little fox" --temperature 0.9 --max-tokens 150

Training Details

  • Dataset: TinyStories — short stories for children, easy to overfit and verify coherence on a small compute budget.
  • Loss: cross-entropy on next-token prediction (standard causal language modelling objective).
  • LR schedule: linear warmup → cosine decay (optax.warmup_cosine_decay_schedule, peak lr 3e-4).
  • Optimizer: AdamW with weight decay 0.01.
  • Input/target pair: input = tokens [0 … T-1], target = tokens [1 … T] — the shift is applied batch-wise with jax.vmap.
  • Checkpointing: saved with Orbax PyTreeCheckpointer to trained_models/model_checkpoint.orbax; the directory is created automatically on first save.

Key JAX/Flax Patterns

  • @nnx.jit to compile the training step as a single XLA program
  • nnx.value_and_grad to compute loss and gradients in one forward pass
  • jax.vmap for batched target-sequence construction
  • Fixed-shape batches enforced by Grain (drop_remainder=True) — required by XLA's static shape model
  • SingleDeviceSharding to pin checkpoint restoration explicitly to CPU

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages