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
vLLM-based route_text(), uv install guide, complete runnable examples
Browse files32 unmodified lines3334353637383739404142434445464047484950444546515253544 unmodified lines5960615758596061626364656667686263646566676874697071777872737475767778798081808182838485868788898586879091899293949596919798999410010110210310410510610796979810810911011111253 unmodified lines1661671681581691701711722 unmodified lines17517617716717817916917018018118218318418518618732 unmodified lines
### Installation
We recommend using [uv](https://docs.astral.sh/uv/) for fast, reliable environment setup:
```bashpip install scikit-learn numpy joblib huggingface_hub torch transformers>=4.51# Install uv (if not already installed)curl -LsSf https://astral.sh/uv/install.sh | sh
# Create environment and install dependenciesuv venv .venv && source .venv/bin/activateuv pip install scikit-learn numpy joblib huggingface_hub vllm```
### Complete Example### Complete Example (GPU)
```pythonfrom huggingface_hub import snapshot_downloadimport sys, torchimport numpy as npfrom transformers import AutoModel, AutoTokenizerimport sys
# 1. Download routerpath = snapshot_download("JiaqiXue/r2-router")4 unmodified lines# 2. Load pre-trained KNN checkpointsrouter = R2Router.from_pretrained(path)
# 3. Embed your query with Qwen3-0.6B (1024-dim)tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")model = AutoModel.from_pretrained("Qwen/Qwen3-0.6B")
query = "What is the capital of France?"inputs = tokenizer(query, return_tensors="pt", padding=True, truncation=True)with torch.no_grad(): output = model(**inputs)embedding = output.last_hidden_state.mean(dim=1).squeeze().numpy()
# 4. Route!result = router.route(embedding)# 3. Route a query (auto-embeds with Qwen3-0.6B via vLLM)result = router.route_text("What is the capital of France?")print(f"Model: {result['model_full_name']}")print(f"Token Budget: {result['token_limit']}")print(f"Predicted Quality: {result['predicted_quality']:.3f}")```
### Train from Scratch`route_text()` automatically loads Qwen3-0.6B via vLLM on first call and caches it. Batch routing is also supported:
```pythonfrom huggingface_hub import snapshot_downloadimport sysqueries = [ "What is the capital of France?", "Write a Python function to sort a list", "Translate 'hello' to Japanese",]results = router.route_text(queries)for q, r in zip(queries, results): print(f"{q[:40]:40s} -> {r['model']} (budget={r['token_limit']})")```
path = snapshot_download("JiaqiXue/r2-router")sys.path.insert(0, path)### CPU-Only (No GPU)
If you don't have a GPU, provide pre-computed embeddings directly:
```pythonimport numpy as npfrom router import R2Router
# Train KNN from the provided sub_10 training data (custom hyperparameters)router = R2Router.from_training_data(path, k=80)```router = R2Router.from_pretrained(path)
### Alternative: vLLM Embeddings (Faster for Batches)# Your own 1024-dim embedding (e.g., from an API or pre-computed)embedding = np.random.randn(1024) # replace with real embeddingresult = router.route(embedding)```
For GPU-accelerated batch embedding:### Train from Scratch
```pythonfrom vllm import LLMfrom huggingface_hub import snapshot_downloadimport sys
path = snapshot_download("JiaqiXue/r2-router")sys.path.insert(0, path)
from router import R2Router
llm = LLM(model="Qwen/Qwen3-0.6B", runner="pooling")outputs = llm.embed(["What is the capital of France?"])embedding = outputs[0].outputs.embedding# Train KNN with custom hyperparametersrouter = R2Router.from_training_data(path, k=80, lambda_val=0.999)```
## Architecture53 unmodified lines
```config.json # Router configuration (models, budgets, prices, hyperparams)router.py # Self-contained inference coderouter.py # Self-contained inference code (embed + route)training_data/ embeddings.npy # Sub_10 training embeddings (809 x 1024) labels.json # Per-(model, budget) accuracy & token labels2 unmodified lines token_knn_*.joblib # Pre-fitted KNN token predictors (6 total)```
### Two Ways to Use### Three Ways to Use
1. **Load checkpoints** (`from_pretrained`): Directly load pre-fitted KNN models. No training needed.2. **Train from data** (`from_training_data`): Use the provided training embeddings and labels to fit your own KNN with custom hyperparameters (e.g., different K, distance metric).| 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 Details
5 unmodified lines678910912131011121314151617181920212228 unmodified lines515253545556571 unmodified line596061556263645865666776 unmodified lines14414514614114714814936 unmodified lines18618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124219 unmodified lines2622632642092652662675 unmodified lines
Usage: from router import R2Router router = R2Router.from_pretrained("jqxue1999/r2-router") result = router.route(embedding) # embedding: np.ndarray (1024,)
# Or train from scratch: router = R2Router.from_training_data("jqxue1999/r2-router") router = 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 embedding result = router.route(embedding) # np.ndarray (1024,)
# Option 3: Train from scratch router = R2Router.from_training_data(path, k=80)"""
import os28 unmodified lines self.model_names = model_names # {short_name: full_name} self.budgets = budgets # {budget_name: token_limit} self.lambda_val = lambda_val self._embedder = None
@classmethod def from_pretrained(cls, path: str, lambda_val: float = 0.999) -> "R2Router":1 unmodified line Load pre-trained KNN checkpoints.
Args: path: Local directory or HuggingFace repo ID (e.g., "jqxue1999/r2-router") path: Local directory or HuggingFace repo ID (e.g., "JiaqiXue/r2-router") lambda_val: Cost-accuracy tradeoff (higher = more cost-sensitive) """ # If HF repo ID, download first if not os.path.isdir(path): path = cls._download_from_hf(path)
76 unmodified lines knn.fit(X_train[valid], acc[valid]) quality_knns[model_name][budget_name] = knn
# Token predictor (use concise budget's output_tokens) if "concise" in model_labels and "output_tokens" in model_labels["concise"]: tok = np.array([x if x is not None else np.nan for x in model_labels["concise"]["output_tokens"]]) valid = ~np.isnan(tok)36 unmodified lines "Install with: pip install huggingface_hub" )
def 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 queries
Returns: numpy array of shape (N, 1024) """ 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" ) self._embedder = LLM( model="Qwen/Qwen3-0.6B", runner="pooling", trust_remote_code=True, dtype="half", )
if isinstance(queries, str): queries = [queries]
outputs = self._embedder.embed(queries) return np.array([o.outputs.embedding for o in outputs])
def route_text( self, query: Union[str, List[str]], lambda_val: Optional[float] = None, ) -> Union[Dict, List[Dict]]: """ Route text query(ies) end-to-end: embed with Qwen3-0.6B, then route.
Args: query: Single query string or list of queries lambda_val: Override default lambda
Returns: Routing decision dict (single) or list of dicts (batch) """ embeddings = self.embed(query) if isinstance(query, str): return self.route(embeddings[0], lambda_val) return self.route_batch(embeddings, lambda_val)
def route( self, embedding: np.ndarray,19 unmodified lines for mn in self.quality_knns: price = self.model_prices.get(mn, 0)
# Predict output tokens if mn in self.token_knns: tok = max(1.0, float(self.token_knns[mn].predict(embedding)[0])) else:README.md+49-35
router.py+63-8