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 lines79808182828384848586878889909192879394959697989910010110210310410510610710810911011111211311482 unmodified lines19719819917820020120220320418218318420520620720820921078 unmodified lines print(f"{q[:40]:40s} -> {r['model']} (budget={r['token_limit']})")```
### CPU-Only (No GPU)### With vLLM Server (Recommended for Production)
If you don't have a GPU, provide pre-computed embeddings directly: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```
```pythonimport numpy as np# Terminal 2: Route queries (connects to the running server)from huggingface_hub import snapshot_downloadimport sys
path = snapshot_download("JiaqiXue/r2-router")sys.path.insert(0, path)
from router import R2Router
router = 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 lines token_knn_*.joblib # Pre-fitted KNN token predictors (6 total)```
### Three Ways to Use### Ways to Use
| Method | GPU? | Description ||--------|------|-------------|| `route_text()` + vLLM server | Yes (server) | Start `vllm serve` once, route from anywhere via HTTP || `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 || `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 lines7891011121312141516171815192017181921222321 unmodified lines454647484950511 unmodified line5354555657585957606162636465666768697071727374757632 unmodified lines10911011111211311411583 unmodified lines1992002011912022032042052062072081 unmodified line2102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462042052472482492502512522 unmodified lines2552562572142152162582592606 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 1: Route from text (auto-embeds with vLLM) # Option B: Remote vLLM server (no local GPU needed for embedding) # Start server: vllm serve Qwen/Qwen3-0.6B --task embed router = R2Router.from_pretrained(path, embed_url="http://localhost:8000") result = router.route_text("What is the capital of France?")
# Option 2: Route from pre-computed embedding # Option C: Pre-computed embedding result = router.route(embedding) # np.ndarray (1024,)
# Option 3: Train from scratch router = R2Router.from_training_data(path, k=80)"""
import os21 unmodified lines model_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 line self.model_names = model_names # {short_name: full_name} self.budgets = budgets # {budget_name: token_limit} self.lambda_val = lambda_val self.embed_url = embed_url # vLLM server URL, e.g. "http://localhost:8000" self._embedder = None
@classmethod def from_pretrained(cls, path: str, lambda_val: float = 0.999) -> "R2Router": def 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 lines model_names=model_names, budgets=config["budgets"], lambda_val=lambda_val, embed_url=embed_url, )
@classmethod83 unmodified lines
def embed(self, queries: Union[str, List[str]]) -> np.ndarray: """ Embed queries using Qwen3-0.6B via vLLM (loaded on first call). 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 line Returns: 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.request
url = 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 LLM except ImportError: raise ImportError( "vLLM is required for text embedding. " "Install with: uv pip install vllm" "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 lines dtype="half", )
if isinstance(queries, str): queries = [queries]
outputs = self._embedder.embed(queries) return np.array([o.outputs.embedding for o in outputs])
README.md+30-7
router.py+53-12