KitAI is a production-quality local language model framework built from scratch, combining the best ideas from GPT, Llama, Qwen, DeepSeek, Mistral, Phi, and Gemma architectures. Optimized for consumer GPUs with 6GB VRAM.
KitAI/
├── configs/ # Configuration files
│ ├── default.yaml # Default model config
│ ├── small.yaml # Small model (for 6GB VRAM)
│ ├── medium.yaml # Medium model
│ └── training.yaml # Training-specific config
├── models/ # Model architecture
│ ├── __init__.py
│ ├── config.py # ModelConfig dataclass
│ ├── transformer.py # Main transformer model
│ ├── attention.py # Multi-head + GQA attention
│ ├── layers.py # Transformer blocks
│ ├── embedding.py # Token embeddings + RoPE
│ ├── normalization.py # RMSNorm
│ ├── feed_forward.py # SwiGLU FFN
│ ├── kv_cache.py # KV cache implementation
│ └── output.py # LM head + loss
├── tokenizer/ # BPE tokenizer
│ ├── __init__.py
│ ├── bpe_tokenizer.py # BPE implementation
│ ├── trainer.py # Tokenizer training
│ └── utils.py # Tokenizer utilities
├── training/ # Training pipeline
│ ├── __init__.py
│ ├── dataset.py # Dataset loading & preprocessing
│ ├── trainer.py # Main training loop
│ ├── optimizer.py # Fused AdamW
│ ├── scheduler.py # Cosine LR scheduler with warmup
│ ├── checkpoint.py # Checkpoint saving/loading
│ ├── metrics.py # Training metrics tracking
│ ├── evaluation.py # Evaluation pipeline
│ ├── logger.py # Logging (console + file)
│ ├── validation.py # Validation logic
│ └── resume.py # Resume training from checkpoint
├── datasets/ # Dataset support
│ ├── __init__.py
│ ├── base_dataset.py # Base dataset class
│ ├── text_dataset.py # txt files
│ ├── jsonl_dataset.py # jsonl files
│ ├── parquet_dataset.py # parquet files
│ ├── csv_dataset.py # csv files
│ ├── alpaca_dataset.py # Alpaca format
│ ├── sharegpt_dataset.py # ShareGPT format
│ ├── openai_dataset.py # OpenAI messages format
│ └── packer.py # Sequence packing
├── utils/ # Utilities
│ ├── __init__.py
│ ├── device.py # Device management
│ ├── memory.py # Memory optimization
│ ├── distributed.py # (Future) DDP support
│ ├── seeding.py # Reproducibility
│ └── io_utils.py # File I/O helpers
├── scripts/ # Entry points
│ ├── train.py # Training entry point
│ ├── chat.py # Inference/chat CLI
│ ├── evaluate.py # Evaluation script
│ ├── resume.py # Resume training script
│ ├── tokenize.py # Tokenizer training script
│ └── generate.py # Generation script
├── tests/ # Tests
│ ├── test_attention.py
│ ├── test_layers.py
│ ├── test_tokenizer.py
│ ├── test_training.py
│ └── test_generation.py
├── examples/ # Usage examples
│ └── basic_usage.py
├── requirements.txt
├── setup.py
├── README.md
└── pyproject.toml
- Implements frequency-based rotary embeddings
- Applied to query and key vectors in attention
- Supports
theta=10000.0base frequency - Configurable
rope_thetaparameter
- Pre-Norm architecture (normalize before sublayers)
RMSNorm(x) = x * rms(x) * gammawhererms(x) = sqrt(mean(x^2) + eps)eps = 1e-6for numerical stability
FFN(x) = (swish(xW1) * xV) W2whereswish(x) = x * sigmoid(x)- Hidden dimension:
8/3 * d_model(as in Llama/Mistral) - Supports 3 weight matrices (gate, up, down)
- Number of key-value heads < number of query heads
- Typical ratio:
num_kv_heads = num_attention_heads / 4 - All query heads share KV heads in groups
- Significantly reduces KV cache memory
- Stores keys and values during generation
- Memory-efficient with GQA
- Supports
max_batch_sizeandmax_seq_len dtype = torch.float16for memory efficiency
model:
vocab_size: 32000
d_model: 768
n_layers: 12
n_heads: 12
n_kv_heads: 4
d_ff: 2048
max_seq_len: 2048
dropout: 0.0
activation: swiglu
norm_eps: 1e-6
rope_theta: 10000.0
weight_tying: true
bias: false
init_std: 0.02| Component | Memory (~) |
|---|---|
| Model Parameters | ~1.5 GB |
| Optimizer States | ~3.0 GB |
| Activations + Grads | ~0.8 GB |
| KV Cache | ~0.3 GB |
| Misc (buffers, etc) | ~0.4 GB |
| Total | ~6.0 GB |
Techniques to stay within budget:
- Gradient Checkpointing - Trade compute for memory
- Mixed Precision (AMP) - Use
torch.float16 - Gradient Accumulation - Accumulate over micro-batches
- Activation Checkpointing - Selective layer checkpointing
- Fused AdamW - Memory-efficient optimizer
- Gradient Clipping - For training stability
- Support multiple formats (txt, jsonl, parquet, csv, Alpaca, ShareGPT, OpenAI)
- Automatic sequence packing to
max_seq_len - Efficient shuffling (smart shuffle + buffer)
- Streaming support for large datasets
IterableDatasetfor memory efficiency
- Fused AdamW implementation
- Weight decay support (no decay on bias/layer norms)
betas = (0.9, 0.95),eps = 1e-8- Implements parameter groups for weight decay
- Cosine learning rate decay with linear warmup
- Configurable warmup_steps (recommended: 5-10% of total)
- Configurable min_lr (recommended: 10% of max_lr)
- Supports multiple schedule types (cosine, linear, constant)
- Rich live console dashboard
- Metrics: loss, lr, tokens/sec, GPU%, VRAM, ETA, epoch, step
- Gradient norm monitoring
- TensorBoard-compatible logging
- JSON log file
- Automatic saving every N steps
- Best checkpoint (lowest validation loss)
- Latest checkpoint (resume support)
- Checkpoint averaging (optional)
- Contains: model state, optimizer state, scheduler state, step, epoch
- Train from text corpus
- Support special tokens:
<pad>,<unk>,<bos>,<eos>,<mask> - Configurable vocab size (default: 32000)
- Efficient encoding/decoding
- Vocabulary export/import
- Pre-tokenization (by whitespace + punctuation)
- Merge ranking by frequency
- Byte-level BPE (for universal encoding)
- Regex-based splitting patterns
- Fast inference path (cached merges)
- Interactive CLI with streaming output
- Conversation history management
- System prompt support
- Chat templates (Llama, Mistral, Alpaca)
- Markdown rendering (optional)
- Top-k sampling (
k=40-50) - Top-p (nucleus) sampling (
p=0.9-0.95) - Temperature scaling (
t=0.1-1.5) - Repetition penalty (
1.0-1.2) - Presence penalty (
0.0-0.5) - Frequency penalty (
0.0-0.5) - Stop sequences (customizable)
- Max tokens limit
- Greedy decoding (temperature=0)
- Sampling (stochastic)
- Beam search (future)
- Speculative decoding interface (future-ready)
models/config.py- Model configuration systemmodels/normalization.py- RMSNormmodels/embedding.py- Embeddings + RoPEmodels/attention.py- GQA attentionmodels/feed_forward.py- SwiGLU FFNmodels/kv_cache.py- KV cachemodels/layers.py- Transformer blockmodels/output.py- LM head + lossmodels/transformer.py- Full model assemblyutils/*.py- Utility modules
tokenizer/bpe_tokenizer.py- BPE implementationtokenizer/trainer.py- Tokenizer trainingtokenizer/utils.py- Tokenizer utilities
training/dataset.py- Dataset systemtraining/optimizer.py- Fused AdamWtraining/scheduler.py- LR schedulertraining/checkpoint.py- Checkpoint systemtraining/metrics.py- Metrics trackingtraining/logger.py- Logging systemtraining/evaluation.py- Evaluationtraining/validation.py- Validationtraining/resume.py- Resume trainingtraining/trainer.py- Main trainerdatasets/*.py- Dataset format supportconfigs/*.yaml- Configuration files
scripts/train.py- Training scriptscripts/chat.py- Chat interfacescripts/generate.py- Generation scriptscripts/evaluate.py- Evaluation scriptscripts/resume.py- Resume scriptscripts/tokenize.py- Tokenizer training
tests/test_attention.pytests/test_layers.pytests/test_tokenizer.pytests/test_training.pytests/test_generation.pyexamples/basic_usage.pyrequirements.txt,setup.py,pyproject.toml
torch>=2.0.0
rich>=13.0.0
pyyaml>=6.0
datasets>=2.0.0 (optional, for HuggingFace datasets)
tqdm>=4.65.0
regex>=2023.0.0
tokenizers==0.15.0 (for comparison, not used internally)
numpy>=1.24.0
psutil>=5.9.0 (for system monitoring)
pandas>=2.0.0 (for CSV/Parquet support)
pyarrow>=12.0.0 (for Parquet support)- Mixture of Experts (MoE)
- Vision encoder
- Speech encoder
- Multimodal inputs
- Tool calling
- RAG support
- Function calling
- RLHF pipeline
- LoRA/QLoRA fine-tuning
- Quantization (GPTQ, AWQ)
- Distributed training (FSDP)
This architecture is designed to be modular, extensible, and production-ready from day one.