Text Classification
Scikit-learn
Joblib
English
llm-routing
model-selection
budget-optimization
nearest-neighbor
Run this model with HF Jobs
Run JiaqiXue/R2-Router-RouterArena on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/JiaqiXue/R2-Router-RouterArena. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/JiaqiXue/R2-Router-RouterArena on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use JiaqiXue/R2-Router-RouterArena with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Scikit-learn
How to use JiaqiXue/R2-Router-RouterArena with Scikit-learn:
from huggingface_hub import hf_hub_download import joblib model = joblib.load( hf_hub_download("JiaqiXue/R2-Router-RouterArena", "sklearn_model.joblib") ) # only load pickle files from sources you trust # read more about it here https://skops.readthedocs.io/en/stable/persistence.html - Notebooks
- Google Colab
- Kaggle
Add vLLM server mode: start once, route from anywhere
Browse files78 unmodified lines798081828384858687888990919282 unmodified lines17517617717817918018118218318418518618778 unmodified linesprint(f"{q[:40]:40s} -> {r['model']} (budget={r['token_limit']})")```### CPU-Only (No GPU)If you don't have a GPU, provide pre-computed embeddings directly:```pythonimport numpy as npfrom router import R2Routerrouter = R2Router.from_pretrained(path)# Your own 1024-dim embedding (e.g., from an API or pre-computed)82 unmodified linestoken_knn_*.joblib # Pre-fitted KNN token predictors (6 total)```### Three Ways to Use| Method | GPU? | Description ||--------|------|-------------|| `router.route_text(query)` | Yes | End-to-end: auto-embeds with vLLM, then routes || `router.route(embedding)` | No | Route from pre-computed 1024-dim embedding || `R2Router.from_training_data(path)` | No | Train your own KNN with custom hyperparameters |## Training Details78 unmodified lines79808182838485868788899091929394959697989910010110210310410510610710810911011111211311482 unmodified lines19719819920020120220320420520620720820921078 unmodified linesprint(f"{q[:40]:40s} -> {r['model']} (budget={r['token_limit']})")```### With vLLM Server (Recommended for Production)Start the embedding server once, then route from any process without reloading the model:```bash# Terminal 1: Start vLLM embedding server (runs once, stays alive)uv pip install vllmvllm serve Qwen/Qwen3-0.6B --task embed --port 8000``````python# Terminal 2: Route queries (connects to the running server)from huggingface_hub import snapshot_downloadimport syspath = snapshot_download("JiaqiXue/r2-router")sys.path.insert(0, path)from router import R2Routerrouter = R2Router.from_pretrained(path, embed_url="http://localhost:8000")result = router.route_text("What is the capital of France?")print(f"Model: {result['model_full_name']}, Budget: {result['token_limit']}")```### CPU-Only (No GPU)If you don't have a GPU, provide pre-computed embeddings directly:```pythonrouter = R2Router.from_pretrained(path)# Your own 1024-dim embedding (e.g., from an API or pre-computed)82 unmodified linestoken_knn_*.joblib # Pre-fitted KNN token predictors (6 total)```### Ways to Use| Method | GPU? | Description ||--------|------|-------------|| `route_text()` + vLLM server | Yes (server) | Start `vllm serve` once, route from anywhere via HTTP || `route_text()` + local vLLM | Yes (local) | Auto-loads Qwen3-0.6B on first call, caches it || `route(embedding)` | No | Route from pre-computed 1024-dim embedding || `from_training_data(path)` | No | Train your own KNN with custom hyperparameters |## Training Details
6 unmodified lines7891011121314151617181920212221 unmodified lines4445464748491 unmodified line5152535455565758596061626364656632 unmodified lines9910010110210310483 unmodified lines1881891901911921931941 unmodified line1961971981992002012022032042052062072082 unmodified lines2112122132142152162172182196 unmodified linesUsage:from router import R2Routerrouter = R2Router.from_pretrained(path)# Option 1: Route from text (auto-embeds with vLLM)result = router.route_text("What is the capital of France?")# Option 2: Route from pre-computed embeddingresult = router.route(embedding) # np.ndarray (1024,)# Option 3: Train from scratchrouter = R2Router.from_training_data(path, k=80)"""import os21 unmodified linesmodel_names: Dict[str, str],budgets: Dict[str, int],lambda_val: float = 0.999,):self.quality_knns = quality_knns # {model: {budget: KNN}}self.token_knns = token_knns # {model: KNN}1 unmodified lineself.model_names = model_names # {short_name: full_name}self.budgets = budgets # {budget_name: token_limit}self.lambda_val = lambda_valself._embedder = None@classmethoddef from_pretrained(cls, path: str, lambda_val: float = 0.999) -> "R2Router":"""Load pre-trained KNN checkpoints.Args:path: Local directory or HuggingFace repo ID (e.g., "JiaqiXue/r2-router")lambda_val: Cost-accuracy tradeoff (higher = more cost-sensitive)"""if not os.path.isdir(path):path = cls._download_from_hf(path)32 unmodified linesmodel_names=model_names,budgets=config["budgets"],lambda_val=lambda_val,)@classmethod83 unmodified linesdef embed(self, queries: Union[str, List[str]]) -> np.ndarray:"""Embed queries using Qwen3-0.6B via vLLM (loaded on first call).Args:queries: Single query string or list of queries1 unmodified lineReturns:numpy array of shape (N, 1024)"""if self._embedder is None:try:from vllm import LLMexcept ImportError:raise ImportError("vLLM is required for text embedding. ""Install with: uv pip install vllm")self._embedder = LLM(model="Qwen/Qwen3-0.6B",2 unmodified linesdtype="half",)if isinstance(queries, str):queries = [queries]outputs = self._embedder.embed(queries)return np.array([o.outputs.embedding for o in outputs])6 unmodified lines789101112131415161718192021222321 unmodified lines454647484950511 unmodified line53545556575859606162636465666768697071727374757632 unmodified lines10911011111211311411583 unmodified lines1992002012022032042052062072081 unmodified line2102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522 unmodified lines2552562572582592606 unmodified linesUsage:from router import R2Router# Option A: Local vLLM (loads Qwen3-0.6B on first call)router = R2Router.from_pretrained(path)result = router.route_text("What is the capital of France?")# Option B: Remote vLLM server (no local GPU needed for embedding)# Start server: vllm serve Qwen/Qwen3-0.6B --task embedrouter = R2Router.from_pretrained(path, embed_url="http://localhost:8000")result = router.route_text("What is the capital of France?")# Option C: Pre-computed embeddingresult = router.route(embedding) # np.ndarray (1024,)"""import os21 unmodified linesmodel_names: Dict[str, str],budgets: Dict[str, int],lambda_val: float = 0.999,embed_url: Optional[str] = None,):self.quality_knns = quality_knns # {model: {budget: KNN}}self.token_knns = token_knns # {model: KNN}1 unmodified lineself.model_names = model_names # {short_name: full_name}self.budgets = budgets # {budget_name: token_limit}self.lambda_val = lambda_valself.embed_url = embed_url # vLLM server URL, e.g. "http://localhost:8000"self._embedder = None@classmethoddef from_pretrained(cls,path: str,lambda_val: float = 0.999,embed_url: Optional[str] = None,) -> "R2Router":"""Load pre-trained KNN checkpoints.Args:path: Local directory or HuggingFace repo ID (e.g., "JiaqiXue/r2-router")lambda_val: Cost-accuracy tradeoff (higher = more cost-sensitive)embed_url: vLLM server URL for embedding (e.g., "http://localhost:8000").If None, loads Qwen3-0.6B locally on first route_text() call."""if not os.path.isdir(path):path = cls._download_from_hf(path)32 unmodified linesmodel_names=model_names,budgets=config["budgets"],lambda_val=lambda_val,embed_url=embed_url,)@classmethod83 unmodified linesdef embed(self, queries: Union[str, List[str]]) -> np.ndarray:"""Embed queries using Qwen3-0.6B.If embed_url is set, uses a remote vLLM server (OpenAI-compatible API).Otherwise, loads Qwen3-0.6B locally via vLLM (on first call).Args:queries: Single query string or list of queries1 unmodified lineReturns:numpy array of shape (N, 1024)"""if isinstance(queries, str):queries = [queries]if self.embed_url:return self._embed_remote(queries)return self._embed_local(queries)def _embed_remote(self, queries: List[str]) -> np.ndarray:"""Embed via a running vLLM server (OpenAI-compatible embeddings API)."""import urllib.requesturl = self.embed_url.rstrip("/") + "/v1/embeddings"payload = json.dumps({"model": "Qwen/Qwen3-0.6B","input": queries,}).encode()req = urllib.request.Request(url, data=payload,headers={"Content-Type": "application/json"},)with urllib.request.urlopen(req) as resp:result = json.loads(resp.read())embeddings = [item["embedding"] for item in sorted(result["data"], key=lambda x: x["index"])]return np.array(embeddings)def _embed_local(self, queries: List[str]) -> np.ndarray:"""Embed by loading Qwen3-0.6B locally via vLLM."""if self._embedder is None:try:from vllm import LLMexcept ImportError:raise ImportError("vLLM is required for local embedding. ""Install with: uv pip install vllm\n""Or start a vLLM server and pass embed_url to from_pretrained().")self._embedder = LLM(model="Qwen/Qwen3-0.6B",2 unmodified linesdtype="half",)outputs = self._embedder.embed(queries)return np.array([o.outputs.embedding for o in outputs])
README.md+30-7
router.py+53-12