How arjun-bhattarai/llms works
Purpose and entry points
This is a PyTorch implementation of a GPT-2-compatible decoder-only LLM, centered on loading GPT-2 weights, continued pretraining, fine-tuning, generation, and evaluation. Operational entry points are scripts/train.py, scripts/evaluate.py, scripts/inference.py, and scripts/prepare_wikitext.py. Exploratory and instructional workflows live in notebooks/.
Model assembly
src/llm/gpt/model.py composes the GPT model from configuration, token/position embeddings, repeated Transformer blocks, final normalization, and vocabulary-logit projection. src/llm/gpt/config.py defines model dimensions compatible with GPT-2 variants. This is the primary boundary between model consumers (training/inference) and model internals.
Transformer and attention core
src/llm/transformer/transformer_block.py implements the residual pre-normalized Transformer layer: causal multi-head self-attention followed by GELU feed-forward processing. src/llm/attention/multi_head_attention.py owns QKV projection, scaled dot-product attention, causal masking, head recombination, and output projection. src/llm/transformer/gelu.py supplies the GPT-style activation.
Text-to-training-data path
src/llm/preprocessing/tokenizer.py and src/llm/preprocessing/bpe.py provide GPT-2-compatible BPE token handling, while src/llm/preprocessing/dataset.py turns token streams into shifted input/target sequences for next-token prediction. Raw corpus preparation is driven by scripts/prepare_wikitext.py; local sample data includes data/the-verdict.txt. The key data boundary is text → token IDs → fixed-context batches.
Pretrained-weight and checkpoint lifecycle
src/llm/weights/gpt2_loader.py maps official GPT-2 tensors into the custom model and validates assignment shapes. gpt_download3.py is the repository-level acquisition utility for GPT-2 assets. src/llm/training/checkpoint.py persists/restores model state, optimizer state, progress, losses, and configuration, enabling continued-pretraining resumption rather than training the 124M model from scratch.
Training, validation, and evaluation
src/llm/training/trainer.py is the optimization orchestrator, integrating device selection, AMP/gradient scaling, AdamW-style training flow, metrics, periodic validation, and checkpointing. Loss masking and next-token cross entropy are in src/llm/training/loss.py; validation/perplexity logic is in src/llm/training/validation.py. scripts/evaluate.py compares baseline and trained checkpoints and writes artifacts under results/evaluation.json and results/generation_samples.txt.
Inference and adaptation paths
src/llm/inference/pipeline.py and src/llm/decoding/sampling.py implement autoregressive prompt generation with context management, temperature, top-k filtering, and multinomial sampling; scripts/inference.py exposes this flow. src/llm/finetuning/classifier.py adds a GPT-based SMS classification path. src/llm/instruction_tuning/instruction_tuner.py formats instruction examples, performs padded/shifted collation with ignored loss positions, and supports supervised instruction tuning over instruction-data.json.
Runtime and external dependencies
The material runtime is Python with PyTorch, optionally CUDA and FP16 AMP. tiktoken is the GPT-2 tokenizer dependency; NumPy/Pandas support data processing. Official OpenAI GPT-2 checkpoints are an external model source. Instruction-response evaluation can call a locally running Ollama service, rather than a hosted LLM API. Outputs and checkpoints are filesystem-based; no web application or server deployment is indicated.
Main entry points: trainer.py Training orchestrator · model.py GPT decoder model · pipeline.py Autoregressive generation · tokenizer.py GPT-2 BPE tokenizer
Components 21
Operational scripts
- WikiText preparation · Prepares raw corpus for tokenization.
scripts/prepare_wikitext.py - Training entry point
scripts/train.py - Evaluation entry point
scripts/evaluate.py - Inference entry point
scripts/inference.py
Data & tokenization
- GPT-2 BPE tokenizer
src/llm/preprocessing/tokenizer.py - BPE implementation
src/llm/preprocessing/bpe.py - Next-token dataset · Builds shifted fixed-context input and target sequences.
src/llm/preprocessing/dataset.py
GPT model core
- GPT-2 configuration
src/llm/gpt/config.py - GPT decoder model · Assembles embeddings, repeated blocks, final normalization, and vocabulary logits.
src/llm/gpt/model.py - Pre-norm Transformer block · Residual causal attention and GELU feed-forward layer.
src/llm/transformer/transformer_block.py - Causal multi-head attention · Projects QKV, masks future tokens, and recombines heads.
src/llm/attention/multi_head_attention.py
Training & weights
- Training orchestrator · Runs AMP/AdamW optimization, validation, metrics, and checkpointing.
src/llm/training/trainer.py - Next-token loss
src/llm/training/loss.py - Validation & perplexity
src/llm/training/validation.py - Checkpoint persistence · Stores model, optimizer, progress, losses, and configuration.
src/llm/training/checkpoint.py - GPT-2 weight loader · Maps official tensors into the custom model with shape validation.
src/llm/weights/gpt2_loader.py - GPT-2 asset download
gpt_download3.py
Generation & adaptation
- Autoregressive generation · Manages prompt context and iterative decoding.
src/llm/inference/pipeline.py - Temperature/top-k sampling
src/llm/decoding/sampling.py - SMS classifier
src/llm/finetuning/classifier.py - Instruction tuner · Formats examples and collates padded shifted targets with ignored positions.
src/llm/instruction_tuning/instruction_tuner.py
Connections 26
- WikiText preparation → GPT-2 BPE tokenizer: prepared text
- GPT-2 BPE tokenizer → BPE implementation: uses
- GPT-2 BPE tokenizer → Next-token dataset: token IDs
- Next-token dataset → Training orchestrator: input/target batches
- GPT-2 configuration → GPT decoder model: dimensions
- GPT decoder model → Pre-norm Transformer block: repeats
- Pre-norm Transformer block → Causal multi-head attention: causal attention
- Training entry point → Training orchestrator: runs
- Training orchestrator → GPT decoder model: optimizes
- Training orchestrator → Next-token loss: computes
- Training orchestrator → Validation & perplexity: periodic validation
- Validation & perplexity → Next-token loss: uses
- Training orchestrator → Checkpoint persistence: save / resume
- GPT-2 asset download → GPT-2 weight loader: GPT-2 assets
- GPT-2 weight loader → GPT decoder model: assigns pretrained weights
- Checkpoint persistence → GPT decoder model: restores state
- Evaluation entry point → Checkpoint persistence: loads baseline and trained states
- Evaluation entry point → Validation & perplexity: evaluates
- Evaluation entry point → Autoregressive generation: writes comparison samples
- Inference entry point → Autoregressive generation: runs
- Autoregressive generation → GPT decoder model: next-token logits
- Autoregressive generation → Temperature/top-k sampling: selects next token
- Autoregressive generation → GPT-2 BPE tokenizer: encode / decode
- SMS classifier → GPT decoder model: adapts
- Instruction tuner → GPT-2 BPE tokenizer: formats and tokenizes
- Instruction tuner → Training orchestrator: supervised batches