Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(examples): itemize router costs and validate Cloud fee labels
svonavaa8d14bb6aa4e
diff --git a/examples/train-a-router/QUICKSTART.md b/examples/train-a-router/QUICKSTART.mdindex 9a90764bc..130d08d3e 100644--- a/examples/train-a-router/QUICKSTART.md+++ b/examples/train-a-router/QUICKSTART.md@@ -17,6 +17,8 @@ uv run --frozen python router.py prepare --data data --run my-routerOpen `published-results/explorer/index.html` for the full cost–quality curves.+The [opening comparison table](README.md#1-understand-the-data-and-baseline-sol-808-accuracy-luna-556) separates Sol answers, Luna answers, Laya serving estimates and embedding API fees. Include the router's cost as well as the selected answer; the explorer leaves native hosting unpriced, while the README shows an explicit H100 estimate.+For the **CPU embedding exercise**, install only `--group outcomes`, fetch only `--group core`, and run the following after `prepare`. Then continue at steps 4–5. This uses recorded Laya comparisons; it does not perform LoRA training.```bashdiff --git a/examples/train-a-router/README.md b/examples/train-a-router/README.mdindex 97ddbeff7..3733b9ce4 100644--- a/examples/train-a-router/README.md+++ b/examples/train-a-router/README.md@@ -32,26 +32,32 @@ Repeated questions and identified source/context families stay together. TraininThe main measurements are:- **Answer accuracy:** the percentage of chosen model answers judged correct against the benchmark reference. This measures the answers people receive, rather than whether a router matches an arbitrary “best model” label.-- **Cost per 10,000 requests:** the measured input/output token cost of the selected answers, scaled to a common workload size.+- **Cost per 10,000 requests:** the selected answers' input/output token cost plus the stated router cost, scaled to a common workload size. API charges and hosting estimates are identified separately.- **Savings:** the percentage decrease from always calling Sol.- **Accuracy loss:** always-Sol accuracy minus routed accuracy. For example, 80% becoming 78% is a **2-point loss**; a negative loss means the router did better on these questions.Some questions are answered correctly only by Luna. A good router can therefore occasionally beat always-Sol. The gray random-routing line shows what happens if we choose models without reading the question; a useful router should improve on that tradeoff.-| Method | Answer accuracy | Accuracy loss | Answer cost / 10k | Answer-cost savings |-|---|---:|---:|---:|---:|-| Always Sol | 80.8% | 0.0 points | $70.77 | 0.0% |-| Always Luna | 55.6% | 25.2 points | $12.23 | 82.7% |-| Unchanged Laya | 68.6% | 12.2 points | $41.82 | 40.9% |-| Laya + LoRA | 78.3% | 2.6 points | $56.80 | 19.7% |-| Embedding neighbors | 76.3% | 4.5 points | $53.80 | 24.0% |-| Embedding classifier | 76.8% | 4.0 points | $54.41 | 23.1% |-| LoRA + learned cost | 79.0% | 1.8 points | $57.63 | 18.6% |-| Embedding classifier + learned cost | 79.9% | 0.9 points | $58.16 | 17.8% |-| Text/length + learned cost | 79.0% | 1.8 points | $55.28 | 21.9% |-| Text-predicted task + learned cost | 80.1% | 0.7 points | $58.31 | 17.6% |--All router rows use a rule fixed before final collection: select the highest calibration accuracy under an **80% calibration answer-cost cap** relative to always-Sol. It is an illustrative spending level, not a required quality threshold or a guarantee of 20% test savings. The table reports final-test answer costs; add **$0.81 per 10,000 requests** for the Cloud encoder on embedding routes. For embedding + learned cost, that changes $58.16 to **$58.97**, or **16.7% savings** versus always-Sol at $70.77. Native and application hosting are separate. Every method, both cost variants and all preselected spending levels remain in the full report.+All dollar amounts below are **per 10,000 incoming requests**. Each request gets one answer, from either Sol or Luna. **Subtotals include the embedding API fee or the estimated Laya serving cost.** `≈` marks a hosting estimate; `—` means that model is not used. Application hosting, including the small CPU classifiers and cost predictors, idle capacity, and one-time training/data collection are extra.++| Method | Answer accuracy | Loss (points) | Sol answers | Luna answers | Laya, H100 estimate | Embeddings, Cloud API | Subtotal | Savings |+|---|---:|---:|---:|---:|---:|---:|---:|---:|+| Always Sol | 80.8% | 0.0 | $70.77 | — | — | — | $70.77 | 0.0% |+| Always Luna | 55.6% | 25.2 | — | $12.23 | — | — | $12.23 | 82.7% |+| Unchanged Laya | 68.6% | 12.2 | $36.06 | $5.76 | ≈$1.08 | — | ≈$42.90 | ≈39.4% |+| Laya + LoRA | 78.3% | 2.6 | $54.16 | $2.64 | ≈$1.05 | — | ≈$57.85 | ≈18.2% |+| Embedding neighbors | 76.3% | 4.5 | $50.59 | $3.21 | — | $0.81 | $54.61 | 22.8% |+| Embedding classifier | 76.8% | 4.0 | $51.51 | $2.90 | — | $0.81 | $55.22 | 22.0% |+| LoRA + learned cost | 79.0% | 1.8 | $55.34 | $2.29 | ≈$1.05 | — | ≈$58.68 | ≈17.1% |+| Embedding classifier + learned cost | 79.9% | 0.9 | $56.06 | $2.10 | — | $0.81 | $58.97 | 16.7% |+| Text/length + learned cost | 79.0% | 1.8 | $52.84 | $2.44 | — | — | $55.28 | 21.9% |+| Text-predicted task + learned cost | 80.1% | 0.7 | $56.15 | $2.15 | — | — | $58.31 | 17.6% |++Laya's estimate prices the time actively serving requests on a resident H100; the embedding column uses SIE Cloud's per-request price. These are different deployment choices, not a comparison of both models on identical hardware. [Serving speed and costs](#serving-speed-and-costs) shows the calculation and its limits. Savings use the unrounded subtotal; rounded components can differ from it by a cent.++**Neighbors spend less here because they buy different answers.** They send **49.6%** of requests to Sol, compared with **59.7%** for LoRA. Their answer bill is **$53.80 versus $56.80**, before either router's inference cost, and their accuracy is lower: **76.3% versus 78.3%**. Laya is about 0.4B parameters and Qwen's encoder is 4B, but parameter count alone does not determine the full routing bill.++All router rows use a rule fixed before final collection: select the highest calibration accuracy under an **80% calibration answer-cost cap** relative to always-Sol. It is an illustrative spending level, not a required quality threshold or a guarantee of 20% test savings. The router costs above are added after that selection; they do not change the frozen policies. Every method, both cost variants and all preselected spending levels remain in the full report.The table and default replay use the supplied reference checkpoints. Step 3 also compares a faster training recipe against them. The steps compare different ways to learn the decision; they do not promise that every added model improves every tradeoff. LoRA improves on unchanged Laya. Neighbors provide a simple embedding baseline. Learning request costs improves the embedding classifier at the illustrated spending levels. The inexpensive text controls remain competitive and belong in the comparison.@@ -248,7 +254,7 @@ To try the supplied models directly, fetch `--group weights`, use `--run data/re|---|---:|---:|---:|| Unchanged Laya, resident H100 | 80 ms | 243 ms | $1.08 busy-resource estimate || Adapted Laya, resident H100 | 78 ms | 235 ms | $1.05 busy-resource estimate |-| Adapted Laya, 8-core CPU / 32 GB | 3.98 s | 13.70 s | $6.99 busy-resource estimate |+| Adapted Laya, 8-core CPU / 32 GiB | 3.98 s | 13.70 s | $6.99 busy-resource estimate || SIE Cloud Qwen encoder | 204 ms | 226 ms | $0.81 validated singleton-fee projection || Resident embedding classifier | 0.049 ms | 0.065 ms | Application hosting extra || Classifier + text cost predictors | 2.40 ms | 4.00 ms | Application hosting extra |@@ -257,7 +263,17 @@ Each model measurement uses the same 90 development questions after warmup. TheThe Cloud encoder measurement includes network time and saving the raw response to disk; native model timings are resident-model measurements on the stated Modal hardware. The $0.81 fee projects the final-test question mix; the native busy-resource estimates use the 90-question development timing sample. Model loading and CLI startup are separate. These are sequential single-request measurements, not a throughput benchmark. The learned head adds very little work; deploying the 4B encoder is the larger serving requirement.-The default money comparison uses selected answer token costs. The explorer can add per-request Cloud encoder fees, projected from the ratebook and validated against actual batch and singleton calls. Native hosting, application hosting, idle GPU capacity and one-time training are separate: unpriced costs are never entered as zero. The optional Modal cost estimates price busy resource time only; they are not a production hosting bill. Token prices and workloads can change, so the pinned prices and exact usage are included with the data.+The opening table combines these router estimates with the selected answer costs. The explorer retains the original answer-only curves and can add per-request Cloud encoder fees; it does not insert a native hosting estimate into the frozen evaluation. Its unpriced native and CPU costs remain unknown, not zero.++The cost calculations are:++- **Sol and Luna:** sum each model's token cost only for questions sent to that model, then multiply by `10,000 / 975`. Input, cached-input and cache-write prices follow the saved usage; output tokens already include reasoning tokens, so reasoning is charged once. Multiplying a routing share by the model's overall mean cost would be wrong: routers select different questions, with different answer lengths.+- **Qwen embeddings:** the recorded Cloud rate is **$0.06 per million input tokens**, rounded up per request to a whole **$0.00001 credit**: `ceil(3 × input_tokens / 500)` credits. The 975 test questions total 1,235,875 encoder tokens and **7,910 credits after rounding**: `$0.07910 × 10,000 / 975 = $0.811282`. Both neighbors and classifiers need **one embedding for every incoming request**, whichever answer model is selected. The rate and rounding rule reproduce all 91 saved singleton charges and 245 successful batch charges. The table prices separate live requests, even when the exercise reuses cached vectors; it does not spread the original batch-collection bill across future requests.+- **Laya on H100:** the saved resource rate is **$0.00134388 per second** for an H100, eight CPU cores and 64 GiB RAM. For LoRA, `0.078329 seconds × $0.00134388 × 10,000 = $1.05265`; unchanged Laya uses its measured 0.080407 seconds and costs about $1.08. Each timing already includes **both correctness predictions**, tokenization and the original cost arithmetic. LoRA is merged into the model for inference; this is one adapted router, not an extra model call or a training charge.++The Laya estimate assumes the measured sequential serving time is billable active time. Startup, loading and idle capacity add cost; batching, different hardware or lower precision may change it. The CPU-only LoRA scenario above costs about **$6.99 / 10k**, rather than $1.05. Cloud API pricing and a dedicated server's resource cost should not be interpreted as equal-efficiency measurements. Small CPU heads, learned cost predictors and application hosting are still extra, as are one-time training and answer collection.++The downloaded evidence contains [per-question encoder fees](https://huggingface.co/datasets/superlinked/train-a-router-bbeh/blob/86dd7494a4c2396bc9ffa890f994b9722610b357/fees.json), [answer token usage and prices](https://huggingface.co/datasets/superlinked/train-a-router-bbeh/blob/86dd7494a4c2396bc9ffa890f994b9722610b357/grades/grades-final.json), and [Laya timings and resource rates](https://huggingface.co/datasets/superlinked/train-a-router-bbeh/blob/86dd7494a4c2396bc9ffa890f994b9722610b357/metadata/timing/native-hosting-comparison.json). These are pinned study prices, not a promise about future bills.## What the results establishdiff --git a/examples/train-a-router/embedding/cloud_reader.py b/examples/train-a-router/embedding/cloud_reader.pynew file mode 100644index 000000000..4342ffe4a--- /dev/null+++ b/examples/train-a-router/embedding/cloud_reader.py@@ -0,0 +1,59 @@+"""Accept observed Cloud rounding labels without changing the frozen fee rule."""++from decimal import Decimal+from pathlib import Path++from embedding import collect_features+from embedding import recipes as core++ROUNDING_LABELS = {"ceil-once-per-terminal-event", "ceil-once-per-terminal-event-micro"}+++def check_tokens(root, counts):+ """Validate actual settlement; a rounding label never substitutes for a charge."""+ root = Path(root)+ collection = core.read(root / "collection.json")+ core.require(+ collection["status"] == "complete" and not collection["unknown_charge_batches"],+ "Complete settled features required",+ )+ pricebook = None+ for binding in collection["batch_receipts"]:+ path = root / binding["path"]+ core.require(core.sha(path) == binding["sha256"], "Batch binding changed")+ receipt = core.read(path)+ intent_path = path.parent / "intent.json"+ core.require(core.sha(intent_path) == receipt["intent_sha256"], "Intent changed")+ intent = core.read(intent_path)+ quote = intent["quote"]+ core.require(+ quote["applied_rates"] == [collect_features.RATE]+ and quote["rounding_rule"] in ROUNDING_LABELS+ and quote["minimum_billed_units"] is None,+ "Encoder pricing basis changed",+ )+ core.require(receipt["ids"] == intent["ids"], "Batch IDs changed")+ current = {key: quote[key] for key in ("rate_book_version", "rate_book_sha256")}+ core.require(pricebook is None or pricebook == current, "Pricebook changed across batches")+ pricebook = current+ tokens = sum(counts[item] for item in receipt["ids"])+ core.require(+ receipt["usage"]["input_tokens"] == tokens+ and Decimal(receipt["credits_decimal"]) == collect_features.credits(tokens),+ "Exact token/fee projection differs from observed charge",+ )+ core.require(+ receipt["usage"]["rate_book_version"] == quote["rate_book_version"],+ "Usage/quote pricebook differs",+ )+ return pricebook+++def run(*args, **kwargs):+ """Use the reader check during this sequential CLI collection, then restore it."""+ original = collect_features.check_tokens+ collect_features.check_tokens = check_tokens+ try:+ return collect_features.run(*args, **kwargs)+ finally:+ collect_features.check_tokens = originaldiff --git a/examples/train-a-router/embedding/encode.py b/examples/train-a-router/embedding/encode.pyindex 23703dec0..7d3c461b5 100644--- a/examples/train-a-router/embedding/encode.py+++ b/examples/train-a-router/embedding/encode.py@@ -1,12 +1,13 @@"""Acquire a fresh question-only Qwen feature set and singleton fee validation."""import argparse-from decimal import Decimalimport jsonimport os+from decimal import Decimalfrom pathlib import Path-from embedding import collect_features, recipes as core, selfhost, token_audit, wire+from embedding import cloud_reader, collect_features, selfhost, token_audit, wire+from embedding import recipes as corefrom reader_io import ChangedFileSync, require, sha@@ -20,7 +21,8 @@ def prepare(source, budget, seconds):"format": "bbeh-public-feature-acquisition-v1", "reproduction": True,"source_plan_sha256": source_hash, "n": len(rows), "role_inputs_sha256": input_hashes,"model": core.MODEL, "hf_revision": core.REVISION, "instruction": core.INSTRUCTION,- "source_sha256": {"encode": sha(__file__), "collector": sha(collect_features.__file__),+ "source_sha256": {"encode": sha(__file__), "cloud_reader": sha(cloud_reader.__file__),+ "collector": sha(collect_features.__file__),"wire": sha(wire.__file__), "token_audit": sha(token_audit.__file__)},"budget_usd": str(cap), "collection_seconds": seconds,"singleton_validation_including_warmup": len(collect_features.singleton_rows(rows)),@@ -42,7 +44,7 @@ def execute(source, output, plan):tokenizer = AutoTokenizer.from_pretrained(root, local_files_only=True, trust_remote_code=False)if local:return selfhost.run(source, output, plan, tokenizer, binding)- return collect_features.run(source, output, plan, tokenizer, binding, ChangedFileSync())+ return cloud_reader.run(source, output, plan, tokenizer, binding, ChangedFileSync())def main():diff --git a/examples/train-a-router/test_cloud_reader.py b/examples/train-a-router/test_cloud_reader.pynew file mode 100644index 000000000..6050143b2--- /dev/null+++ b/examples/train-a-router/test_cloud_reader.py@@ -0,0 +1,149 @@+"""Offline Cloud price-label compatibility and unchanged settlement checks."""++import copy+import json+import tempfile+import unittest+from pathlib import Path+from unittest.mock import patch++from embedding import cloud_reader, collect_features, encode+from embedding import recipes as core+from test_public_adapters import source_fixture+++def fixture(root, *, label="ceil-once-per-terminal-event-micro", mutate=None):+ counts = {"first": 166, "second": 167}+ intent = {+ "ids": list(counts),+ "quote": {+ "applied_rates": [copy.deepcopy(collect_features.RATE)],+ "rounding_rule": label,+ "minimum_billed_units": None,+ "rate_book_version": "test-v40",+ "rate_book_sha256": "a" * 64,+ },+ }+ receipt = {+ "ids": list(counts),+ "credits_decimal": "2.000000",+ "usage": {"input_tokens": 333, "rate_book_version": "test-v40"},+ }+ if mutate:+ mutate(intent, receipt)+ directory = root / "000000"+ core.write(directory / "intent.json", intent)+ receipt["intent_sha256"] = core.sha(directory / "intent.json")+ core.write(directory / "receipt.json", receipt)+ core.write(root / "collection.json", {+ "status": "complete", "unknown_charge_batches": [],+ "batch_receipts": [{"path": "000000/receipt.json", "sha256": core.sha(directory / "receipt.json")}],+ })+ return counts+++class CloudReaderTests(unittest.TestCase):+ def test_both_observed_labels_preserve_per_event_rounding_and_raw_receipts(self):+ for label in sorted(cloud_reader.ROUNDING_LABELS):+ with self.subTest(label=label), tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ counts = fixture(root, label=label)+ before = {p.name: p.read_bytes() for p in (root / "000000").iterdir()}+ book = cloud_reader.check_tokens(root, counts)+ self.assertEqual(book, {"rate_book_version": "test-v40", "rate_book_sha256": "a" * 64})+ self.assertEqual(before, {p.name: p.read_bytes() for p in (root / "000000").iterdir()})+ self.assertEqual(collect_features.credits(sum(counts.values())), 2)+ self.assertEqual(sum(collect_features.credits(n) for n in counts.values()), 3)++ def test_changed_rate_unit_minimum_or_label_is_rejected(self):+ changes = {+ "rate": lambda i, r: i["quote"]["applied_rates"][0].update(rate_numerator=4),+ "unit": lambda i, r: i["quote"]["applied_rates"][0].update(unit="output_tokens"),+ "minimum": lambda i, r: i["quote"].update(minimum_billed_units=1),+ "label": lambda i, r: i["quote"].update(rounding_rule="floor-per-request"),+ }+ for name, change in changes.items():+ with self.subTest(name=name), tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ counts = fixture(root, mutate=change)+ with self.assertRaisesRegex(ValueError, "pricing basis"):+ cloud_reader.check_tokens(root, counts)++ def test_fractional_or_per_item_charge_and_wrong_tokens_are_rejected(self):+ changes = {+ "fractional": lambda i, r: r.update(credits_decimal="1.998000"),+ "per_item": lambda i, r: r.update(credits_decimal="3.000000"),+ "tokens": lambda i, r: r["usage"].update(input_tokens=334),+ }+ for name, change in changes.items():+ with self.subTest(name=name), tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ counts = fixture(root, mutate=change)+ with self.assertRaisesRegex(ValueError, "token/fee projection"):+ cloud_reader.check_tokens(root, counts)++ def test_changed_receipt_or_intent_is_rejected(self):+ for name, message in (("receipt.json", "Batch binding"), ("intent.json", "Intent changed")):+ with self.subTest(name=name), tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ counts = fixture(root)+ path = root / "000000" / name+ path.write_bytes(path.read_bytes() + b"\n")+ with self.assertRaisesRegex(ValueError, message):+ cloud_reader.check_tokens(root, counts)++ def test_mismatched_ids_or_book_and_unknown_settlement_are_rejected(self):+ changes = {+ "ids": (lambda i, r: r.update(ids=["first"]), "Batch IDs"),+ "book": (lambda i, r: r["usage"].update(rate_book_version="other"), "Usage/quote"),+ }+ for name, (change, message) in changes.items():+ with self.subTest(name=name), tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ counts = fixture(root, mutate=change)+ with self.assertRaisesRegex(ValueError, message):+ cloud_reader.check_tokens(root, counts)+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ counts = fixture(root)+ collection = core.read(root / "collection.json")+ collection["unknown_charge_batches"] = [{"id": "unresolved"}]+ (root / "collection.json").write_text(json.dumps(collection), encoding="utf-8")+ with self.assertRaisesRegex(ValueError, "Complete settled"):+ cloud_reader.check_tokens(root, counts)++ def test_reader_wraps_only_one_collection_and_restores_checker_on_failure(self):+ original = collect_features.check_tokens+ for failure in (False, True):+ def run(*args, _failure=failure, **kwargs):+ self.assertIs(collect_features.check_tokens, cloud_reader.check_tokens)+ self.assertEqual(args, ("source", "output"))+ self.assertEqual(kwargs, {"marker": 1})+ if _failure:+ raise RuntimeError("fixture failure")+ return {"status": "complete"}++ with self.subTest(failure=failure), patch.object(collect_features, "run", side_effect=run):+ if failure:+ with self.assertRaisesRegex(RuntimeError, "fixture failure"):+ cloud_reader.run("source", "output", marker=1)+ else:+ self.assertEqual(cloud_reader.run("source", "output", marker=1), {"status": "complete"})+ self.assertIs(collect_features.check_tokens, original)++ def test_reader_plan_binds_helper_and_preserves_source_validation(self):+ with tempfile.TemporaryDirectory() as directory:+ source = source_fixture(Path(directory))+ with patch.object(collect_features, "singleton_rows", return_value=[]):+ plan = encode.prepare(source, "1", 60)+ self.assertEqual(plan["source_sha256"]["cloud_reader"], core.sha(cloud_reader.__file__))+ path = source / "question-only/train-inputs.json"+ rows = json.loads(path.read_bytes())+ rows[0]["request"] = "Changed input"+ path.write_text(json.dumps(rows), encoding="utf-8")+ with self.assertRaisesRegex(ValueError, "Input hash changed"):+ encode.prepare(source, "1", 60)+++if __name__ == "__main__":+ unittest.main()