CoolFace
Modelpublic

dknguyen2304/model-router

sourceHugging Faceapache-2.0updated 6mo agoView on Hugging Face
0likes
Model Card

๐Ÿš€ 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

MetricValue
Routing Accuracy100%
Macro F11.0
Avg Latency1.44ms
P50 Latency0.62ms
Base ModelQwen2.5-0.5B-Instruct
Training8x NVIDIA H200 GPUs (DDP)

๐Ÿ—๏ธ 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

RouteUse Case
gpt-4-turboComplex reasoning, advanced coding, creative writing, long context analysis
gpt-3.5-turboSimple QA, basic summarization, casual conversation, quick translation
claude-3-opusDeep research synthesis, long document analysis, nuanced analysis
claude-3-sonnetBalanced analysis, code assistance, general writing, data interpretation
gemini-proMultimodal content, factual QA, web-grounded generation, visual reasoning
mixtral-8x7bFast inference, code generation, roleplay, instruction following

๐Ÿ“Š Evaluation Results

Per-Class Performance (Test Set: 1,001 samples)

Backend ModelPrecisionRecallF1Support
gpt-4-turbo1.001.001.00149
gpt-3.5-turbo1.001.001.00711
claude-3-opus1.001.001.0049
claude-3-sonnet1.001.001.0056
gemini-pro1.001.001.0013
mixtral-8x7b1.001.001.0023

Training Convergence

EpochTrain LossEval Accuracy
11.010876.8%
20.2813100.0%
30.0602100.0%
10~0.0100.0%

๐Ÿš€ Quick Start

python
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

ParameterValue
Base Modelunsloth/Qwen2.5-0.5B-Instruct
LoRA Rank (r)64
LoRA Alpha64
LoRA Dropout0.1
Target Modulesqproj, kproj, vproj, oproj, gateproj, upproj, down_proj
Learning Rate1e-3
Batch Size8 per GPU ร— 8 GPUs ร— 4 grad accum = 256 effective
Epochs10
Max Seq Length512
OptimizerAdamW
SchedulerCosine with warmup (5%)
PrecisionBF16
Hardware8x NVIDIA H200 (143 GB each)
Training Data10,000 synthetic samples (80/10/10 split)
Total Steps350

๐Ÿ”„ Pipeline

The model was trained via a fully autonomous 5-stage pipeline:

  1. 1.Data Generation โ€” 10,000 synthetic requests with controlled class balance
  2. 2.LLM-as-Judge Labeling โ€” Keyword matching (60%) + semantic scoring (40%)
  3. 3.Distributed Fine-tuning โ€” DDP training on 8x H200 GPUs
  4. 4.Evaluation โ€” Batch inference with latency measurement
  5. 5.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

  1. 1.Fix Tensor Formatting
  2. 2.Confirm and pin BFloat16 dtype at inference
  3. 3.Fix padding rules to prevent Classification Head bias toward Label Index 0
  1. 1.Train on Real Data
  2. 2.Train additional epochs on real production user prompts
  3. 3.Synthetic data doesn't cover natural user typing patterns
  1. 1.Implement Async Support
  2. 2.Add SSE/Stream support for non-blocking responses
  3. 3.Handle timeout gracefully when routing to large LLMs
  1. 1.Timeout Handling
  2. 2.Large upstream models (DeepSeek, Kimi) may timeout (>30-60s)
  3. 3.Router must not be synchronous blocking

๐Ÿ“œ License

Apache 2.0

๐Ÿ“– Citation

bibtex
@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}
}