Run frontier MoE models on hardware you already own β pure C, zero deps, experts streamed from disk. Tiny engine, immense model. π¦
C
brio: default normalize to sum; warn when mean mixes option token counts
Taras Zubar8298d713a3f8
diff --git a/c/openai_server.py b/c/openai_server.pyindex 488aefce..dcdbc80a 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -4490,7 +4490,7 @@ class APIHandler(BaseHTTPRequestHandler):if not isinstance(text, str) or not text.strip():raise APIError(400, f"`questions[{i}].question` must be a non-empty string.","questions")- per = entry.get("normalize", body.get("normalize", "mean"))+ per = entry.get("normalize", body.get("normalize", "sum"))if per not in ("mean", "sum"):raise APIError(400, "`normalize` must be \"mean\" or \"sum\".", "normalize")questions.append((text, self._brio_options(entry.get("options"),@@ -4537,7 +4537,13 @@ class APIHandler(BaseHTTPRequestHandler):raise APIError(400, "Provide `state`, `messages` or `question`.", "state")if not state and form != "options":raise APIError(400, f"`{form}` needs a `state` (or `messages`) to decide on.", "state")- normalize = body.get("normalize", "mean")+ # "sum" (the joint log-probability of the option as a continuation)+ # is the default: "mean" compares per-token averages, which silently+ # favors multi-token options whenever the menu mixes token counts β+ # e.g. DENY (2 tokens) beating ALLOW (1) on every safe change in a+ # 30-case benchmark. "mean" stays available for menus whose options+ # tokenize to the same length, and warns when they do not.+ normalize = body.get("normalize", "sum")if normalize not in ("mean", "sum"):raise APIError(400, "`normalize` must be \"mean\" or \"sum\".", "normalize")# Lo slot si sceglie dallo STATO, non dalla domanda: mille domande@@ -4606,6 +4612,15 @@ class APIHandler(BaseHTTPRequestHandler):raise APIError(502, "The engine returned no log probabilities for the ""options.", None, "engine_error", "server_error")key = "mean_logprob" if norm == "mean" else "logprob"+ if norm == "mean":+ token_counts = {entry["tokens"] for entry in scored if entry["tokens"]}+ if len(token_counts) > 1:+ counts = ", ".join(f"{entry['option']}={entry['tokens']}"+ for entry in scored)+ print(f"[brio] WARNING: normalize=mean with unequal option "+ f"token counts ({counts}) β per-token averages favor "+ f"multi-token options; consider normalize=sum",+ file=sys.stderr)top = max(entry[key] for entry in scored)weights = [math.exp(entry[key] - top) for entry in scored]total_weight = sum(weights) or 1.0diff --git a/c/tests/test_brio_api.py b/c/tests/test_brio_api.pyindex ec2aea9c..9a2f76b8 100644--- a/c/tests/test_brio_api.py+++ b/c/tests/test_brio_api.py@@ -146,7 +146,7 @@ class BrioApi(unittest.TestCase):self.assertEqual(out["object"], "brio.answers")self.assertEqual([a["answer"] for a in out["answers"]],["request changes", "yes", "high"])- self.assertEqual([a["normalize"] for a in out["answers"]], ["mean", "mean", "sum"])+ self.assertEqual([a["normalize"] for a in out["answers"]], ["sum", "sum", "sum"])for answer in out["answers"]:self.assertAlmostEqual(sum(c["p"] for c in answer["choices"]), 1.0, places=6)self.assertGreaterEqual(answer["entropy"], 0.0)@@ -164,6 +164,38 @@ class BrioApi(unittest.TestCase):self.assertEqual(out["usage"]["read_tokens"],sum(c["tokens"] for a in out["answers"] for c in a["choices"]))+ def test_default_normalize_is_sum(self):+ # The default was "mean", whose per-token averages silently favor+ # multi-token options on any menu that mixes token counts; "sum" is+ # the joint log-probability and the only safe default.+ self.serve({"merge": -3.0, "close": -4.0})+ out = self.post({"model": "test-model", "state": STATE,+ "question": "What should the reviewer do?",+ "options": ["merge", "close"]})+ self.assertEqual(out["normalize"], "sum")++ def test_mean_with_unequal_option_token_counts_warns(self):+ import contextlib+ import io+ self.serve({"merge": -3.0, "request changes": -0.2})+ stderr = io.StringIO()+ with contextlib.redirect_stderr(stderr):+ self.post({"model": "test-model", "state": STATE,+ "question": "What should the reviewer do?",+ "options": ["merge", "request changes"],+ "normalize": "mean"})+ self.assertIn("unequal option token counts", stderr.getvalue())+ self.assertIn("merge=1", stderr.getvalue())+ # Equal token counts stay quiet β mean is valid there. (The [api]+ # request log also lands on stderr; only the bias warning matters.)+ self.serve({"yes": -0.1, "no": -2.0})+ stderr = io.StringIO()+ with contextlib.redirect_stderr(stderr):+ self.post({"model": "test-model", "state": STATE,+ "question": "Ship it?", "options": ["yes", "no"],+ "normalize": "mean"})+ self.assertNotIn("unequal option token counts", stderr.getvalue())+# ---- schema: a JSON object filled one cell at a time --------------------def test_schema_fills_cells_in_order_and_each_cell_sees_the_ones_before(self):self.serve({"merge": -3.0, "request changes": -0.2, "close": -4.0,diff --git a/docs/brio.md b/docs/brio.mdindex 89a0ae73..d9557cc0 100644--- a/docs/brio.md+++ b/docs/brio.md@@ -77,7 +77,7 @@ POST /v1/brio| `state` | one of | the text to decide on || `messages` | one of | a chat history used as the context instead of `state` || `question` | optional | what to ask about the state |-| `normalize` | optional | `mean` (default) or `sum`, see below |+| `normalize` | optional | `sum` (default) or `mean`, see below || `cache_slot` | optional | forced KV slot; by default derived from `state` |The reply:@@ -87,7 +87,7 @@ The reply:"object": "brio.choice","answer": "request changes","entropy": 0.121,- "normalize": "mean",+ "normalize": "sum","choices": [{"option": "request changes", "p": 0.974, "logprob": -0.252, "mean_logprob": -0.126, "tokens": 2},{"option": "merge", "p": 0.023, "logprob": -4.007, "mean_logprob": -4.007, "tokens": 1},