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
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
-
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.
-
zahidgptPython Library:- Easily importable Python package (
pip install git+https://github.com/Zahid-coder-17/transformers) for text generation and fine-tuning.
- Easily importable Python package (
-
FastAPI REST API Server:
- Production REST API endpoint (
python api_server.py) serving/generateand/healthfor app integrations.
- Production REST API endpoint (
-
Hugging Face Hub Model Repository:
- Pre-trained 17.45M parameter DDP multi-corpus model hosted live at
Zahid2005/modular-gpt-multicorpus.
- Pre-trained 17.45M parameter DDP multi-corpus model hosted live at
-
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|>).
-
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).
- English Corpus: TinyStories narrative text (
๐ 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
wikimedia/wikipediaโarsubset (~800 MB, use a slice of 5โ10 MB)oscar-corpus/OSCAR-2301โarsubset (very large, sample freely)cc100โarsubset (~6 GB, sample 10 MB)
Recommended Code Datasets
flytech/python-codes-25kโ already used, expand to full downloadcodeparrot/github-codeโ filter for Python, sample 10โ15 MBbigcode/the-stackโ Python subset
๐ ๏ธ 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
69bb232d2de61ab419c465590ae05b651416168b1797674803f9a20a04b21cba
|
|
| MD5 |
d07812e4914f45e3e869429ad9427699
|
|
| BLAKE2b-256 |
f3f2031fd8522f87de2e51abb2927dd13edd8bab262c2ab271abbc810d5038d9
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e90c380726878f2a467160e5600e939396fac615d76a2351c368617c97ea1b6d
|
|
| MD5 |
ae83cd5d03e440de1bdbbdfbc08fbcbd
|
|
| BLAKE2b-256 |
c5dcb601ac3562f673174d7dafdf868bc9142b77b7f11acfb0d18d5bf9db2b87
|