Skip to main content

Modular Transformer & Multi-Corpus (English, Arabic, Code) LLM Library

Project description


title: Modular GPT Playground emoji: โšก colorFrom: indigo colorTo: blue sdk: gradio app_file: app.py pinned: false

Modular Transformer Architectures & Multi-Corpus Subword Tokenizer Engine

CI License: MIT

A comprehensive PyTorch implementation of modular Transformer components, attention variants (Multi-Head, Multi-Query, Grouped-Query), positional encodings (Sinusoidal, Learned, RoPE, ALiBi), normalization layers (RMSNorm, LayerNorm), feed-forward networks (SwiGLU, GEGLU), and 7 Subword Tokenization Algorithms across English, Arabic, and Python Code corpora.


๐Ÿš€ Key Features & Modules

  1. Modular Transformer Architecture:

    • Attention Mechanisms: Multi-Head Attention (MHA), Multi-Query Attention (MQA), Grouped-Query Attention (GQA), and Self-Attention.
    • Positional Encodings: Rotary Position Embeddings (RoPE), Attention with Linear Biases (ALiBi), Sinusoidal Encodings, Learned Embeddings, and Absolute Lookups.
    • Feed-Forward Networks: SwiGLU (LLaMA/Mistral) and GEGLU (GPT-2/BERT).
    • Normalization Layers: RMSNorm and LayerNorm.
  2. zahidgpt Python Library:

    • Easily importable Python package (pip install git+https://github.com/Zahid-coder-17/transformers) for text generation and fine-tuning.
  3. FastAPI REST API Server:

    • Production REST API endpoint (python api_server.py) serving /generate and /health for app integrations.
  4. Hugging Face Hub Model Repository:

  5. Subword Tokenizer Engine (From Scratch & Integrated):

    • Character Tokenizer: Fine-grained byte/character representation.
    • Standard BPE Tokenizer: Byte Pair Encoding built from scratch.
    • WordPiece Tokenizer: WordPiece algorithm built from scratch (BERT style with ## subwords).
    • SentencePiece Tokenizer: Unigram/BPE SentencePiece subword integration.
    • Byte-Level BPE Tokenizer: GPT-2 byte-to-unicode byte BPE from scratch.
    • Regex-BPE Tokenizer: GPT-4 style regex splitting pre-tokenization with BPE pair merging.
    • GPT Tokenizer: Full GPT-style Regex Byte-BPE with special token handling (<|endoftext|>).
  6. Multi-Corpus Evaluation (English, Arabic & Code):

    • English Corpus: TinyStories narrative text (roneneldan/TinyStories).
    • Arabic Corpus: Rich Arabic literature and prose corpus.
    • Python Code Corpus: Hugging Face Python Code dataset (flytech/python-codes-25k - 403,441 bytes).

๐Ÿ“Š Subword Tokenizer Multi-Corpus Benchmarks

Corpus Tokenizer Vocab Size Compression Ratio (Bytes / Token) Cross-Entropy Loss Perplexity (PPL) Speed (Tokens / Sec)
Python Code Character 91 1.00 B/tok 3.1470 23.27 261.0 tok/s
Standard BPE 128 1.27 B/tok 3.9970 54.44 328.6 tok/s
WordPiece 145 1.24 B/tok 3.5335 34.24 396.3 tok/s
SentencePiece 128 14.27 B/tok 1.2155 3.37 433.4 tok/s
Byte-Level BPE 256 1.00 B/tok 3.2765 26.48 349.6 tok/s
Regex BPE 256 1.00 B/tok 3.1542 23.43 411.2 tok/s
GPT Tokenizer 256 1.00 B/tok 3.3534 28.60 411.1 tok/s
Arabic Character 43 1.81 B/tok 2.6630 14.34 220.0 tok/s
Standard BPE 128 3.00 B/tok 4.3841 80.17 347.2 tok/s
WordPiece 128 2.19 B/tok 3.2429 25.61 293.4 tok/s
SentencePiece 128 9.80 B/tok 2.2254 9.26 445.1 tok/s
Byte-Level BPE 256 1.00 B/tok 1.9115 6.76 336.3 tok/s
Regex BPE 256 1.00 B/tok 1.8030 6.07 406.0 tok/s
GPT Tokenizer 256 1.00 B/tok 1.8100 6.11 424.6 tok/s

๐Ÿ›๏ธ Model Architecture Matrix (13 Presets)

Configurations supported via the GPT model interface:

# Preset / Target Architecture Attention Position Encoding Normalization Feedforward Description
1 LLaMA-3 Style "mha" / "gqa" "rope" / "sinusoidal" "rms" "swiglu" Default architecture variant
2 Mistral / Mixtral "gqa" "rope" "rms" "swiglu" Grouped-Query Attention ($N_{\text{kv}}=2$)
3 Falcon / PaLM "mqa" "rope" / "sinusoidal" "layer" "swiglu" Multi-Query Attention ($N_{\text{kv}}=1$)
4 GPT-2 "mha" "learned" "layer" "geglu" Standard GPT-2 decoder layout
5 Vaswani Standard (2017) "mha" "sinusoidal" "layer" "geglu" Original Transformer decoder
6 ALiBi Transformer "mha" "alibi" "rms" "swiglu" Linear bias relative positioning
7 RoPE Transformer "mha" "rope" "rms" "swiglu" Rotary positional embeddings
8 Deep RMSNorm + MQA "mqa" "rope" "rms" "swiglu" Reduced KV cache memory layout
9 GQA Balanced "gqa" "sinusoidal" "rms" "geglu" Grouped-Query Attention ($N_{\text{kv}}=4$)
10 Absolute Position GPT "mha" "absolute" "layer" "swiglu" Absolute lookup embeddings
11 Lightweight Compact "mha" "sinusoidal" "rms" "swiglu" 2-layer compact variant ($d_{\text{model}}=256$)
12 Heavy Deep GPT "mha" "sinusoidal" "rms" "swiglu" 6-layer high-capacity variant ($d_{\text{model}}=768$)
13 Bigram Baseline None None None None Non-transformer bigram table lookup

๐Ÿ’ป Quickstart Code Example

import torch
from gpt import GPT
from tokenization.gpt_tokenizer import GPTTokenizer

# Instantiate GPT Tokenizer
tokenizer = GPTTokenizer(vocab_size=256)
tokenizer.fit("def train_gpt_model(text): return GPT(text)")

# Instantiate LLaMA-3 Style Model (MHA + SwiGLU + RMSNorm + Sinusoidal)
model = GPT(
    vocab_size=256,
    d_model=256,
    num_heads=4,
    hidden_dim=1024,
    num_layers=2,
    attention_type="mha",
    normalization_type="rms",
    feedforward_type="swiglu",
    position_encoding="sinusoidal"
)

tokens = torch.tensor([tokenizer.encode("def train_gpt_model(text):")], dtype=torch.long)
logits, loss = model(tokens)
print("Output Logits Shape:", logits.shape)

๐Ÿ› ๏ธ Open-Source API & Fine-Tuning Guide

The zahidgpt library provides complete open-source APIs for Inference, Fine-Tuning, Custom Tokenization, and Hugging Face Hub Integration.

pip install git+https://github.com/Zahid-coder-17/transformers

1. Zero-Setup Inference

from zahidgpt import generate

# Generates text using 17.45M parameter pre-trained weights (auto-downloaded from HF Hub)
print(generate("def fibonacci(", model_type="multicorpus"))
print(generate("Once upon a time", model_type="multicorpus"))
print(generate("ู…ุฑุญุจุง ุจูƒ", model_type="multicorpus"))

2. Fine-Tune on Your Custom Text Dataset

from zahidgpt import finetune

my_dataset = "def custom_function(): return 'Hello World'\n" * 100

# Fine-tune pre-trained model on your dataset in 1 line
model, losses = finetune(
    text_data=my_dataset,
    model_type="multicorpus",
    epochs=10,
    save_path="my_finetuned_model.pth"
)

3. Build Custom Transformer Architectures

from zahidgpt import GPT, TransformerBlock, GPTTokenizer

# Custom 6-layer GQA SwiGLU RoPE transformer
custom_model = GPT(
    vocab_size=512,
    d_model=512,
    num_heads=8,
    hidden_dim=2048,
    num_layers=6,
    attention_type="gqa",
    position_encoding="rope",
    normalization_type="rms",
    feedforward_type="swiglu",
    num_kv_heads=2
)

4. Push & Share Models on Hugging Face Hub

from zahidgpt import push_to_hub, load_from_hub

# Push fine-tuned model weights to Hugging Face
push_to_hub(repo_id="username/my-custom-gpt", checkpoint_path="my_finetuned_model.pth")

# Load model weights from any Hugging Face Hub repository
weight_path = load_from_hub(repo_id="Zahid2005/modular-gpt-multicorpus", filename="gpt_multicorpus.pth")

๐Ÿ“ˆ Trained Model Evaluation Metrics

Evaluation metrics for the trained Modular Transformer model (checkpoints/gpt_character.pth):

Metric Measured Value Description
Model Parameters 2.15M Total trainable parameters
Training Cross-Entropy Loss 0.9375 Final epoch training loss
Validation Cross-Entropy Loss 2.3653 Held-out validation set loss
Validation Perplexity 10.65 $\exp(\text{Validation Loss})$
Next-Token Character Accuracy 43.94% Correct character prediction rate
Inference Latency 4.44 ms/token GPU token generation latency
Inference Throughput 225.44 tokens/sec GPU generation throughput

๐Ÿ“ Repository Structure

transformers/
โ”œโ”€โ”€ assets/
โ”‚   โ”œโ”€โ”€ arabic_tokenizer_comparison.png # Arabic tokenizer benchmark chart
โ”‚   โ”œโ”€โ”€ code_tokenizer_comparison.png   # Python code tokenizer benchmark chart
โ”‚   โ”œโ”€โ”€ loss_curve.png                  # Training loss curve chart
โ”‚   โ”œโ”€โ”€ performance_dashboard.png       # Metrics & performance dashboard
โ”‚   โ””โ”€โ”€ tokenizer_comparison.png        # English tokenizer benchmark chart
โ”œโ”€โ”€ attention/
โ”‚   โ”œโ”€โ”€ gqa.py                          # Grouped-Query Attention
โ”‚   โ”œโ”€โ”€ mha.py                          # Multi-Head Attention
โ”‚   โ”œโ”€โ”€ mqa.py                          # Multi-Query Attention
โ”‚   โ””โ”€โ”€ self_attention.py               # Single-Head Self Attention
โ”œโ”€โ”€ data/
โ”‚   โ”œโ”€โ”€ arabic_input.txt                # Arabic corpus dataset
โ”‚   โ”œโ”€โ”€ code_input.txt                  # Python Code dataset (403,441 bytes from HF)
โ”‚   โ”œโ”€โ”€ download.py                     # TinyStories download script
โ”‚   โ””โ”€โ”€ input.txt                       # TinyStories English corpus
โ”œโ”€โ”€ feedforward/
โ”‚   โ”œโ”€โ”€ geglu.py                        # GELU-Gated Linear Unit
โ”‚   โ””โ”€โ”€ swiglu.py                       # Swish-Gated Linear Unit
โ”œโ”€โ”€ normalization/
โ”‚   โ”œโ”€โ”€ layernorm.py                    # Standard Layer Normalization
โ”‚   โ””โ”€โ”€ rms_norm.py                     # Root Mean Square Normalization
โ”œโ”€โ”€ position/
โ”‚   โ”œโ”€โ”€ alibi.py                        # Attention with Linear Biases
โ”‚   โ”œโ”€โ”€ learnedpe.py                    # Learned Positional Embedding
โ”‚   โ”œโ”€โ”€ rope.py                         # Rotary Position Embedding
โ”‚   โ””โ”€โ”€ sinusodal.py                    # Fixed Sinusoidal Positional Encoding
โ”œโ”€โ”€ tokenization/
โ”‚   โ”œโ”€โ”€ bpe.py                          # BPE, WordPiece (from scratch), SentencePiece
โ”‚   โ”œโ”€โ”€ byte_bpe.py                     # Byte-Level BPE Tokenizer
โ”‚   โ”œโ”€โ”€ character.py                    # Character Tokenizer
โ”‚   โ”œโ”€โ”€ gpt_tokenizer.py                # GPT Tokenizer with special tokens
โ”‚   โ””โ”€โ”€ regex_bpe.py                    # Regex BPE Tokenizer
โ”œโ”€โ”€ utils/
โ”‚   โ”œโ”€โ”€ kv_cache.py                     # Key-Value Cache mechanism
โ”‚   โ””โ”€โ”€ mask.py                         # Causal triangular attention masking
โ”œโ”€โ”€ app.py                              # Gradio interactive Web Application
โ”œโ”€โ”€ compare_arabic_tokenizers.py        # Arabic tokenizer comparison script
โ”œโ”€โ”€ compare_code_tokenizers.py          # Code tokenizer comparison script
โ”œโ”€โ”€ compare_tokenizers.py               # English tokenizer comparison script
โ”œโ”€โ”€ download_expanded_datasets.py       # Hugging Face dataset downloader
โ”œโ”€โ”€ eval_and_visualize.py               # Evaluation dashboard generator
โ”œโ”€โ”€ generate.py                         # Text generation CLI script
โ”œโ”€โ”€ gpt.py                              # Top-level GPT model definition
โ”œโ”€โ”€ run_ablation.py                     # Automated 13-preset ablation benchmark
โ”œโ”€โ”€ test.py                             # Unit test suite
โ”œโ”€โ”€ train.py                            # Model training script
โ”œโ”€โ”€ LICENSE                             # MIT License
โ””โ”€โ”€ README.md                           # Documentation

โšก Distributed Training with DDP (DistributedDataParallel)

The project includes a full PyTorch DDP training implementation (train_multicorpus_ddp.py) that replaces the original single-process train_multicorpus.py.

What is DDP?

DistributedDataParallel (DDP) is PyTorch's recommended strategy for scaling model training across multiple GPUs or machines. Each GPU runs an independent copy of the model (a replica) and processes a different slice of the batch. After every backward pass, DDP uses ring-AllReduce to average the gradients across all replicas so every GPU's weights stay in sync.

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚               DistributedDataParallel (DDP)              โ”‚
โ”‚                                                          โ”‚
โ”‚  GPU 0 (rank 0)    GPU 1 (rank 1)    GPU 2 (rank 2)      โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”‚
โ”‚  โ”‚  GPT model  โ”‚   โ”‚  GPT model  โ”‚   โ”‚  GPT model  โ”‚    โ”‚
โ”‚  โ”‚  replica 0  โ”‚   โ”‚  replica 1  โ”‚   โ”‚  replica 2  โ”‚    โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ”‚
โ”‚         โ”‚  forward + loss  โ”‚                 โ”‚           โ”‚
โ”‚         โ†“                 โ†“                 โ†“           โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
โ”‚  โ”‚     AllReduce  (average gradients across GPUs)     โ”‚  โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚
โ”‚         โ†“                 โ†“                 โ†“           โ”‚
โ”‚    optimizer.step    optimizer.step    optimizer.step    โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚  Checkpoint saved by rank-0 only (no duplicate writes)  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Key Improvements over train_multicorpus.py

Feature train_multicorpus.py train_multicorpus_ddp.py
Multi-GPU support โŒ โœ… DDP
Gradient sync โŒ โœ… AllReduce
Balanced corpus sampling โŒ โœ… Equal 1/3 per language
Duplicate checkpoint writes โŒ โœ… Rank-0 only
UTF-8 safe Arabic printing โŒ โœ…
Mixed-precision AMP โœ… โœ…
Cosine LR warmup โœ… โœ…
Gradient clipping โœ… โœ…

Balanced Corpus Sampling (Critical Fix)

The old script concatenated all corpora and sampled randomly, which means the model saw English ~95% of the time due to the size imbalance:

data/input.txt        โ†’  8,797,812 bytes  (English)
data/code_input.txt   โ†’    415,332 bytes  (Code)
data/arabic_input.txt โ†’      7,686 bytes  (Arabic)  โ† 1145x smaller than English

The new BalancedCorpusSampler keeps each corpus as a separate tensor and draws exactly batch_size / 3 samples from each language per step โ€” regardless of corpus size.

How to Run

Single GPU / CPU (auto-detected):

python train_multicorpus_ddp.py

Multi-GPU on one machine (recommended โ€” uses torchrun):

torchrun --nproc_per_node=2 train_multicorpus_ddp.py   # 2 GPUs
torchrun --nproc_per_node=4 train_multicorpus_ddp.py   # 4 GPUs

Multi-Node (e.g., 2 machines ร— 4 GPUs = 8 GPUs total):

# On node 0 (master)
torchrun --nnodes=2 --nproc_per_node=4 \
         --node_rank=0 --master_addr=<NODE_0_IP> --master_port=29500 \
         train_multicorpus_ddp.py

# On node 1 (worker)
torchrun --nnodes=2 --nproc_per_node=4 \
         --node_rank=1 --master_addr=<NODE_0_IP> --master_port=29500 \
         train_multicorpus_ddp.py

Expected Speedup

Setup Effective Batch Approx. Speedup
1 GPU (baseline) 63 1ร—
2 GPUs 126 ~1.8ร—
4 GPUs 252 ~3.5ร—
8 GPUs 504 ~6.5ร—

Speedup is sub-linear due to AllReduce communication overhead, which decreases as a fraction of total time as model size grows.


๐Ÿ“Š Dataset Size Requirements

For the model to learn all three languages properly, the corpora need to be roughly equal in size and large enough for the model to learn patterns. Recommended minimum sizes:

Corpus Current Size Recommended Minimum Good Target
English (TinyStories) 8.7 MB 8 MB โœ… 8โ€“20 MB
Code (Python) 415 KB 5 MB 8โ€“15 MB
Arabic 7 KB 5 MB 8โ€“15 MB

Arabic needs the most attention โ€” 7 KB is only ~3,500 words, far too little for a character-level model to learn Arabic morphology.

Recommended Arabic Datasets

Recommended Code Datasets


๐Ÿ› ๏ธ Usage Instructions

# Run unit tests
python -m unittest test.py

# Download expanded Hugging Face datasets (Arabic & Python Code)
python download_expanded_datasets.py

# Benchmark tokenizers on English, Arabic, and Code corpora
python compare_tokenizers.py
python compare_arabic_tokenizers.py
python compare_code_tokenizers.py

# Train single-GPU model (original)
python train.py

# Train multi-corpus model with DDP (single GPU / auto-detect)
python train_multicorpus_ddp.py

# Train multi-corpus model with DDP (multi-GPU via torchrun)
torchrun --nproc_per_node=<N> train_multicorpus_ddp.py

# Evaluate model metrics & generate visual dashboard
python eval_and_visualize.py

# Generate text from trained model
python generate.py --prompt "Once upon a time" --max_tokens 300

# Launch Gradio Interactive Web Application
python app.py

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

zahidgpt-0.1.1.tar.gz (31.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

zahidgpt-0.1.1-py3-none-any.whl (29.4 kB view details)

Uploaded Python 3

File details

Details for the file zahidgpt-0.1.1.tar.gz.

File metadata

  • Download URL: zahidgpt-0.1.1.tar.gz
  • Upload date:
  • Size: 31.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for zahidgpt-0.1.1.tar.gz
Algorithm Hash digest
SHA256 69bb232d2de61ab419c465590ae05b651416168b1797674803f9a20a04b21cba
MD5 d07812e4914f45e3e869429ad9427699
BLAKE2b-256 f3f2031fd8522f87de2e51abb2927dd13edd8bab262c2ab271abbc810d5038d9

See more details on using hashes here.

File details

Details for the file zahidgpt-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: zahidgpt-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 29.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for zahidgpt-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e90c380726878f2a467160e5600e939396fac615d76a2351c368617c97ea1b6d
MD5 ae83cd5d03e440de1bdbbdfbc08fbcbd
BLAKE2b-256 c5dcb601ac3562f673174d7dafdf868bc9142b77b7f11acfb0d18d5bf9db2b87

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page