dknguyen2304/model-router
0
๐ Model Router โ Intelligent AI Gateway Router
An autonomous AI gateway router that intelligently routes incoming API requests to the most appropriate backend model. Built with LoRA fine-tuning on Qwen2.5-0.5B-Instruct + a classification head, achieving 100% routing accuracy with 1.44ms average latency.
โจ Highlights
๐๏ธ Architecture
Input: "Analyze this research paper..."
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Qwen2.5-0.5B-Instruct (LoRA-adapted) โ
โ Target modules: q/k/v/o/gate/up/down โ
โ LoRA rank: 64, alpha: 64 โ
โ Output: Last token hidden state [896] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Classification Head โ
โ Dropout(0.1) โ Linear(896 โ 6) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
Output: "gpt-4-turbo" (probability: 0.92)๐ฏ Supported Routes
๐ Evaluation Results
Per-Class Performance (Test Set: 1,001 samples)
Training Convergence
๐ Quick Start
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
import json
# Load model
base_model = AutoModelForCausalLM.from_pretrained("unsloth/Qwen2.5-0.5B-Instruct")
model = PeftModel.from_pretrained(base_model, "dknguyen2304/model-router")
tokenizer = AutoTokenizer.from_pretrained("unsloth/Qwen2.5-0.5B-Instruct")
# Load classifier head
classifier = torch.nn.Sequential(
torch.nn.Dropout(0.1),
torch.nn.Linear(896, 6)
)
classifier.load_state_dict(torch.load("classifier.pt", map_location="cpu"))
# Label mapping
labels = ["gpt-4-turbo", "gpt-3.5-turbo", "claude-3-opus",
"claude-3-sonnet", "gemini-pro", "mixtral-8x7b"]
# Inference
prompt = "Write a complex recursive algorithm to solve the Tower of Hanoi"
inputs = tokenizer(prompt, return_tensors="pt", max_length=512, truncation=True)
with torch.no_grad():
outputs = model(**inputs, output_hidden_states=True)
hidden = outputs.hidden_states[-1][:, -1, :] # last token
logits = classifier(hidden)
prediction = labels[logits.argmax(dim=-1).item()]
print(f"Route to: {prediction}")๐ Model Files
โโโ adapter_model.safetensors # LoRA adapter weights
โโโ adapter_config.json # PEFT/LoRA configuration
โโโ classifier.pt # Classification head weights
โโโ router_config.json # Router configuration
โโโ label_mapping.json # Label โ ID mappings
โโโ config/
โโโ training_config.yaml # Training hyperparameters
โโโ deepspeed_config.json # DeepSpeed configโ๏ธ Training Details
๐ Pipeline
The model was trained via a fully autonomous 5-stage pipeline:
- Data Generation โ 10,000 synthetic requests with controlled class balance
- LLM-as-Judge Labeling โ Keyword matching (60%) + semantic scoring (40%)
- Distributed Fine-tuning โ DDP training on 8x H200 GPUs
- Evaluation โ Batch inference with latency measurement
- Export โ Production-ready artifacts
โ ๏ธ Limitations & Production Notes
Current Limitations
- Trained on synthetic data โ real-world distribution may differ
- Fixed label set โ only routes to 6 predefined models
- No confidence calibration โ consider adding uncertainty thresholds for production
- Model sensitive to tensor formatting (FP32 vs BFloat16, pad token position)
Production Recommendations
- Fix Tensor Formatting
- Confirm and pin BFloat16 dtype at inference
- Fix padding rules to prevent Classification Head bias toward Label Index 0
- Train on Real Data
- Train additional epochs on real production user prompts
- Synthetic data doesn't cover natural user typing patterns
- Implement Async Support
- Add SSE/Stream support for non-blocking responses
- Handle timeout gracefully when routing to large LLMs
- Timeout Handling
- Large upstream models (DeepSeek, Kimi) may timeout (>30-60s)
- Router must not be synchronous blocking
๐ License
Apache 2.0
๐ Citation
@misc{model-router-2026,
title={Model Router: Intelligent AI Gateway Request Routing via LoRA Fine-tuning},
author={dknguyen2304},
year={2026},
url={https://huggingface.co/dknguyen2304/model-router}
}