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 lines33343536373839404142434445464748494 unmodified lines5455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010153 unmodified lines1551561571581591601612 unmodified lines16416516616716816917017117217332 unmodified lines### Installation```bashpip install scikit-learn numpy joblib huggingface_hub torch transformers>=4.51```### Complete Example```pythonfrom huggingface_hub import snapshot_downloadimport sys, torchimport numpy as npfrom transformers import AutoModel, AutoTokenizer# 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)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```pythonfrom huggingface_hub import snapshot_downloadimport syspath = snapshot_download("JiaqiXue/r2-router")sys.path.insert(0, path)from router import R2Router# Train KNN from the provided sub_10 training data (custom hyperparameters)router = R2Router.from_training_data(path, k=80)```### Alternative: vLLM Embeddings (Faster for Batches)For GPU-accelerated batch embedding:```pythonfrom vllm import LLMllm = LLM(model="Qwen/Qwen3-0.6B", runner="pooling")outputs = llm.embed(["What is the capital of France?"])embedding = outputs[0].outputs.embedding```## Architecture53 unmodified lines```config.json # Router configuration (models, budgets, prices, hyperparams)router.py # Self-contained inference codetraining_data/embeddings.npy # Sub_10 training embeddings (809 x 1024)labels.json # Per-(model, budget) accuracy & token labels2 unmodified linestoken_knn_*.joblib # Pre-fitted KNN token predictors (6 total)```### Two Ways to Use1. **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).## Training Details32 unmodified lines333435363738394041424344454647484950515253544 unmodified lines596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111253 unmodified lines1661671681691701711722 unmodified lines17517617717817918018118218318418518618732 unmodified lines### InstallationWe recommend using [uv](https://docs.astral.sh/uv/) for fast, reliable environment setup:```bash# 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 (GPU)```pythonfrom huggingface_hub import snapshot_downloadimport sys# 1. Download routerpath = snapshot_download("JiaqiXue/r2-router")4 unmodified lines# 2. Load pre-trained KNN checkpointsrouter = R2Router.from_pretrained(path)# 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}")````route_text()` automatically loads Qwen3-0.6B via vLLM on first call and caches it. Batch routing is also supported:```pythonqueries = ["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']})")```### 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)embedding = np.random.randn(1024) # replace with real embeddingresult = router.route(embedding)```### Train from Scratch```pythonfrom huggingface_hub import snapshot_downloadimport syspath = snapshot_download("JiaqiXue/r2-router")sys.path.insert(0, path)from router import R2Router# 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 code (embed + route)training_data/embeddings.npy # Sub_10 training embeddings (809 x 1024)labels.json # Per-(model, budget) accuracy & token labels2 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 Details
5 unmodified lines67891011121314151628 unmodified lines4546474849501 unmodified line5253545556575859606176 unmodified lines13813914014114214314436 unmodified lines18118218318418518619 unmodified lines2062072082092102112125 unmodified linesUsage:from router import R2Routerrouter = 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")"""import os28 unmodified linesself.model_names = model_names # {short_name: full_name}self.budgets = budgets # {budget_name: token_limit}self.lambda_val = lambda_val@classmethoddef from_pretrained(cls, path: str, lambda_val: float = 0.999) -> "R2Router":1 unmodified lineLoad pre-trained KNN checkpoints.Args:path: Local directory or HuggingFace repo ID (e.g., "jqxue1999/r2-router")lambda_val: Cost-accuracy tradeoff (higher = more cost-sensitive)"""# If HF repo ID, download firstif not os.path.isdir(path):path = cls._download_from_hf(path)76 unmodified linesknn.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 route(self,embedding: np.ndarray,19 unmodified linesfor mn in self.quality_knns:price = self.model_prices.get(mn, 0)# Predict output tokensif mn in self.token_knns:tok = max(1.0, float(self.token_knns[mn].predict(embedding)[0]))else:5 unmodified lines67891011121314151617181920212228 unmodified lines515253545556571 unmodified line59606162636465666776 unmodified lines14414514614714814936 unmodified lines18618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124219 unmodified lines2622632642652662675 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 os28 unmodified linesself.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":1 unmodified lineLoad 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)76 unmodified linesknn.fit(X_train[valid], acc[valid])quality_knns[model_name][budget_name] = knnif "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 queriesReturns: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",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 querieslambda_val: Override default lambdaReturns: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 linesfor mn in self.quality_knns:price = self.model_prices.get(mn, 0)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