# arjun-bhattarai/llms architecture

> Architecture diagram of the GitHub repository arjun-bhattarai/llms, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-09-03). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/arjun-bhattarai/llms
- Repository: https://github.com/arjun-bhattarai/llms

## Overview

#### 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: [`src/llm/training/trainer.py`](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/training/trainer.py) (Training orchestrator), [`src/llm/gpt/model.py`](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/gpt/model.py) (GPT decoder model), [`src/llm/inference/pipeline.py`](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/inference/pipeline.py) (Autoregressive generation), [`src/llm/preprocessing/tokenizer.py`](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/preprocessing/tokenizer.py) (GPT-2 BPE tokenizer)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_entry["Operational scripts"]
  node_prepare["WikiText preparation<br/>script"]
  node_train["Training entry point<br/>script<br/>[train.py]"]
  node_evaluate["Evaluation entry point<br/>script<br/>[evaluate.py]"]
  node_inference_cli["Inference entry point<br/>script<br/>[inference.py]"]
end

subgraph group_data["Data &amp; tokenization"]
  node_tokenizer["GPT-2 BPE tokenizer<br/>tokenization<br/>[tokenizer.py]"]
  node_bpe["BPE implementation<br/>tokenization core<br/>[bpe.py]"]
  node_dataset["Next-token dataset<br/>[dataset.py]"]
end

subgraph group_model["GPT model core"]
  node_gpt_config["GPT-2 configuration<br/>model config<br/>[config.py]"]
  node_gpt_model["GPT decoder model<br/>PyTorch model<br/>[model.py]"]
  node_transformer_block["Pre-norm Transformer block<br/>model layer"]
  node_attention["Causal multi-head attention<br/>attention layer"]
end

subgraph group_lifecycle["Training &amp; weights"]
  node_trainer["Training orchestrator<br/>training runtime<br/>[trainer.py]"]
  node_loss["Next-token loss<br/>loss function<br/>[loss.py]"]
  node_validation["Validation &amp; perplexity<br/>evaluation logic<br/>[validation.py]"]
  node_checkpoint[("Checkpoint persistence<br/>checkpoint store<br/>[checkpoint.py]")]
  node_gpt2_loader["GPT-2 weight loader<br/>weight importer<br/>[gpt2_loader.py]"]
  node_gpt_download["GPT-2 asset download<br/>acquisition utility<br/>[gpt_download3.py]"]
end

subgraph group_serving["Generation &amp; adaptation"]
  node_generation["Autoregressive generation<br/>inference pipeline<br/>[pipeline.py]"]
  node_sampling["Temperature/top-k sampling<br/>decoding<br/>[sampling.py]"]
  node_classifier["SMS classifier<br/>fine-tuning path<br/>[classifier.py]"]
  node_instruction_tuner["Instruction tuner<br/>supervised tuning"]
end

node_prepare -->|"prepared text"| node_tokenizer
node_tokenizer -->|"uses"| node_bpe
node_tokenizer -->|"token IDs"| node_dataset
node_dataset -->|"input/target batches"| node_trainer
node_gpt_config -->|"dimensions"| node_gpt_model
node_gpt_model -->|"repeats"| node_transformer_block
node_transformer_block -->|"causal attention"| node_attention
node_train -->|"runs"| node_trainer
node_trainer -->|"optimizes"| node_gpt_model
node_trainer -->|"computes"| node_loss
node_trainer -->|"periodic validation"| node_validation
node_validation -->|"uses"| node_loss
node_trainer -->|"save / resume"| node_checkpoint
node_gpt_download -->|"GPT-2 assets"| node_gpt2_loader
node_gpt2_loader -->|"assigns pretrained weights"| node_gpt_model
node_checkpoint -->|"restores state"| node_gpt_model
node_evaluate -->|"loads baseline and trained states"| node_checkpoint
node_evaluate -->|"evaluates"| node_validation
node_evaluate -->|"writes comparison samples"| node_generation
node_inference_cli -->|"runs"| node_generation
node_generation -->|"next-token logits"| node_gpt_model
node_generation -->|"selects next token"| node_sampling
node_generation -->|"encode / decode"| node_tokenizer
node_classifier -->|"adapts"| node_gpt_model
node_instruction_tuner -->|"formats and tokenizes"| node_tokenizer
node_instruction_tuner -->|"supervised batches"| node_trainer

click node_prepare "https://github.com/arjun-bhattarai/llms/blob/main/scripts/prepare_wikitext.py"
click node_train "https://github.com/arjun-bhattarai/llms/blob/main/scripts/train.py"
click node_evaluate "https://github.com/arjun-bhattarai/llms/blob/main/scripts/evaluate.py"
click node_inference_cli "https://github.com/arjun-bhattarai/llms/blob/main/scripts/inference.py"
click node_tokenizer "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/preprocessing/tokenizer.py"
click node_bpe "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/preprocessing/bpe.py"
click node_dataset "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/preprocessing/dataset.py"
click node_gpt_config "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/gpt/config.py"
click node_gpt_model "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/gpt/model.py"
click node_transformer_block "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/transformer/transformer_block.py"
click node_attention "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/attention/multi_head_attention.py"
click node_trainer "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/training/trainer.py"
click node_loss "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/training/loss.py"
click node_validation "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/training/validation.py"
click node_checkpoint "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/training/checkpoint.py"
click node_gpt2_loader "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/weights/gpt2_loader.py"
click node_gpt_download "https://github.com/arjun-bhattarai/llms/blob/main/gpt_download3.py"
click node_generation "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/inference/pipeline.py"
click node_sampling "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/decoding/sampling.py"
click node_classifier "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/finetuning/classifier.py"
click node_instruction_tuner "https://github.com/arjun-bhattarai/llms/blob/main/src/llm/instruction_tuning/instruction_tuner.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_prepare,node_train,node_evaluate,node_inference_cli toneBlue
class node_tokenizer,node_bpe,node_dataset toneAmber
class node_gpt_config,node_gpt_model,node_transformer_block,node_attention toneMint
class node_trainer,node_loss,node_validation,node_checkpoint,node_gpt2_loader,node_gpt_download toneRose
class node_generation,node_sampling,node_classifier,node_instruction_tuner toneIndigo
```

## Components

### Operational scripts

- [WikiText preparation](https://github.com/arjun-bhattarai/llms/blob/main/scripts/prepare_wikitext.py): script · Prepares raw corpus for tokenization. · `scripts/prepare_wikitext.py`
- [Training entry point](https://github.com/arjun-bhattarai/llms/blob/main/scripts/train.py): script · `scripts/train.py`
- [Evaluation entry point](https://github.com/arjun-bhattarai/llms/blob/main/scripts/evaluate.py): script · `scripts/evaluate.py`
- [Inference entry point](https://github.com/arjun-bhattarai/llms/blob/main/scripts/inference.py): script · `scripts/inference.py`

### Data & tokenization

- [GPT-2 BPE tokenizer](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/preprocessing/tokenizer.py): tokenization · `src/llm/preprocessing/tokenizer.py`
- [BPE implementation](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/preprocessing/bpe.py): tokenization core · `src/llm/preprocessing/bpe.py`
- [Next-token dataset](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/preprocessing/dataset.py): dataset · Builds shifted fixed-context input and target sequences. · `src/llm/preprocessing/dataset.py`

### GPT model core

- [GPT-2 configuration](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/gpt/config.py): model config · `src/llm/gpt/config.py`
- [GPT decoder model](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/gpt/model.py): PyTorch model · Assembles embeddings, repeated blocks, final normalization, and vocabulary logits. · `src/llm/gpt/model.py`
- [Pre-norm Transformer block](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/transformer/transformer_block.py): model layer · Residual causal attention and GELU feed-forward layer. · `src/llm/transformer/transformer_block.py`
- [Causal multi-head attention](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/attention/multi_head_attention.py): attention layer · Projects QKV, masks future tokens, and recombines heads. · `src/llm/attention/multi_head_attention.py`

### Training & weights

- [Training orchestrator](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/training/trainer.py): training runtime · Runs AMP/AdamW optimization, validation, metrics, and checkpointing. · `src/llm/training/trainer.py`
- [Next-token loss](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/training/loss.py): loss function · `src/llm/training/loss.py`
- [Validation & perplexity](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/training/validation.py): evaluation logic · `src/llm/training/validation.py`
- [Checkpoint persistence](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/training/checkpoint.py): checkpoint store · Stores model, optimizer, progress, losses, and configuration. · `src/llm/training/checkpoint.py`
- [GPT-2 weight loader](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/weights/gpt2_loader.py): weight importer · Maps official tensors into the custom model with shape validation. · `src/llm/weights/gpt2_loader.py`
- [GPT-2 asset download](https://github.com/arjun-bhattarai/llms/blob/main/gpt_download3.py): acquisition utility · `gpt_download3.py`

### Generation & adaptation

- [Autoregressive generation](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/inference/pipeline.py): inference pipeline · Manages prompt context and iterative decoding. · `src/llm/inference/pipeline.py`
- [Temperature/top-k sampling](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/decoding/sampling.py): decoding · `src/llm/decoding/sampling.py`
- [SMS classifier](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/finetuning/classifier.py): fine-tuning path · `src/llm/finetuning/classifier.py`
- [Instruction tuner](https://github.com/arjun-bhattarai/llms/blob/main/src/llm/instruction_tuning/instruction_tuner.py): supervised tuning · Formats examples and collates padded shifted targets with ignored positions. · `src/llm/instruction_tuning/instruction_tuner.py`

## Connections

- 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
