Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

gateway: logprobs reach mimo; mimo's tool-call parse reports its maps

JustVugga6893d040851
diff --git a/c/openai_server.py b/c/openai_server.py
index 39fa1d60..15390b82 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -1010,10 +1010,10 @@ def _parse_arch_tool_calls(reply, tools, tool_reply, track_spans):
"""parse_arch_tool_calls plus the tool-call stage's maps: `(content, tool_calls,
box_map, content_map)`.
- Only the glm/default parser reports maps; the others return None for both. A request
- that opted into the numeric logprobs channel is refused with a named 400 on any other
- architecture, so no reply reaching those branches can carry a logprobs object for a
- map to align."""
+ Only the glm/default and mimo parsers report maps; the others return None for both. A
+ request that opted into the numeric logprobs channel is refused with a named 400 on any
+ other architecture, so no reply reaching those branches can carry a logprobs object for
+ a map to align."""
if ARCH == "deepseek_v4":
return parse_dsv4_tool_calls(reply) + (None, None)
if ARCH == "deepseek_v41":
@@ -1026,7 +1026,7 @@ def _parse_arch_tool_calls(reply, tools, tool_reply, track_spans):
if chat_flavor() in ("qwen36", "qwen38", "qwen3_coder"):
return parse_qwen_tool_calls(reply, tools) + (None, None)
if ARCH == "mimo":
- return parse_mimo_tool_calls(reply, tools) + (None, None)
+ return _parse_mimo_tool_calls(reply, tools, track_spans)
return _parse_tool_calls(reply, tools, track_spans)
@@ -2281,7 +2281,14 @@ MIMO_PARAM_RE = re.compile(r"<parameter=([^>\n]+)>(.*?)</parameter>", re.S)
def parse_mimo_tool_calls(reply, tools=None):
- """MiMo's calls back into OpenAI `tool_calls`.
+ """MiMo's calls back into OpenAI `tool_calls`: `(content, tool_calls)`."""
+ content, calls, _box_map, _content_map = _parse_mimo_tool_calls(reply, tools, False)
+ return content, calls
+
+
+def _parse_mimo_tool_calls(reply, tools, track_spans):
+ """MiMo's calls back into OpenAI `tool_calls`, with the stage's maps: `(content,
+ tool_calls, box_map, content_map)`, both maps None unless `track_spans`.
Parameters are inline (`<parameter=K>V</parameter>`); a value that arrives on its own
lines, Qwen-style, loses exactly one newline on each side. Types come from the declared
@@ -2320,12 +2327,22 @@ def parse_mimo_tool_calls(reply, tools=None):
"function": {"name": name, "arguments": json.dumps(args, ensure_ascii=False)}}
text = reply or ""
- calls = [make_call(m.group(1).strip(), m.group(2)) for m in MIMO_CALL_RE.finditer(text)]
+ matches = list(MIMO_CALL_RE.finditer(text))
+ calls = [make_call(m.group(1).strip(), m.group(2)) for m in matches]
if not calls and tools and ("<tool_call>" in text or "<function=" in text):
sys.stderr.write("[api] mimo tool markers present but no call parsed -- "
"possibly truncated or mangled output\n")
sys.stderr.flush()
- return MIMO_CALL_RE.sub("", text).strip(), calls
+ if not track_spans:
+ return MIMO_CALL_RE.sub("", text).strip(), calls, None, None
+ # The same two deletions as the line above -- every call block, then the surrounding
+ # whitespace -- found as ranges, so logprobs.content can describe the content returned
+ # rather than the raw reply with the call syntax in it.
+ content, box_map = _apply_cuts(text, [(m.start(), m.end()) for m in matches])
+ head = len(content) - len(content.lstrip())
+ kept = len(content.strip())
+ content, step = _apply_cuts(content, [(0, head), (head + kept, len(content))])
+ return content, calls, box_map, _compose_span_maps(box_map, step)
def render_chat_qwen38(messages, enable_thinking=True, reasoning_effort=None, tools=None,
@@ -4925,8 +4942,14 @@ class Engine:
# accepted-but-ignored opt-in is a silently wrong answer rather than an error. Two
# flags, not one -- the numeric logprobs/echo channel (`logprobs=`) and
# pre-tokenized token-id intake (`ids=`) are unrelated capabilities with separate
- # coli_submit_ext keys, set from one arch check only because one engine has both.
- self.supports_logprobs_echo = (arch == "glm")
+ # coli_submit_ext keys. The numeric channel is opened to an engine that keeps the
+ # whole of its contract: a DATA tail on every generated token, and an ECHO frame
+ # for EVERY prompt position (" nan 0" at position 0) unless a pin photo covers the
+ # prefix -- which means never resuming a read-out from a live prefix. colibri.c
+ # (glm) and mimo.c do; the engines that score /v1/brio options but resume
+ # read-outs from a live prefix would answer `echo` with a hole. Token-id intake
+ # is glm's alone: serve_codec.h, which mimo reads its frames with, has no `ids=`.
+ self.supports_logprobs_echo = arch in ("glm", "mimo")
self.supports_tok_ids = (arch == "glm")
child_env = dict(env or os.environ, SNAP=str(model), SERVE="1", SERVE_BATCH="1",
NGEN=str(max_tokens), KV_SLOTS=str(kv_slots))
diff --git a/c/tests/test_brio_api.py b/c/tests/test_brio_api.py
index b29229cf..075748ac 100644
--- a/c/tests/test_brio_api.py
+++ b/c/tests/test_brio_api.py
@@ -12,15 +12,29 @@ must see the value chosen for the field before, and nothing is ever generated.
The fake engine tokenises on whitespace and scores an option by a table, so
every answer here is chosen by the test, not by chance. It records every
call: prompt, max_tokens and pin, which is what the assertions read.
+
+MimoBrioEndToEnd puts the real MiMo engine behind the same server, on the tiny
+fixture (`make mimo mimo-tiny-generate`; skipped without them): the endpoint
+reaches it, every option after the photo reads only its own tokens, the scores
+equal a cold engine's, and chat logprobs pass the gateway's gate.
"""
import json
import math
+import os
+import subprocess
+import sys
+import threading
import unittest
+from pathlib import Path
+from unittest.mock import patch
from urllib.error import HTTPError
from urllib.request import Request, urlopen
-import openai_server
-from openai_server import APIServer
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import mimo_serve_fixture # noqa: E402
+import openai_server # noqa: E402
+from family_registry import family_by_id # noqa: E402
+from openai_server import APIServer # noqa: E402
STATE = "340 lines across 8 files, no tests. CI is green but nothing covers that path."
@@ -287,5 +301,141 @@ class BrioApi(unittest.TestCase):
self.assertIn("quotes", body["error"]["message"])
+class _Recorder:
+ """The real engine, with every call it is given written down: the prompt, the
+ pin, the ACCEPT count and the ECHO positions -- what the saving is read from."""
+
+ def __init__(self, engine):
+ self.engine = engine
+ self.kv_slots = engine.kv_slots
+ self.calls = []
+
+ def generate(self, prompt, *args, on_echo=None, on_accept=None, pin=False, **kwargs):
+ call = {"prompt": prompt, "pin": bool(pin), "echo": [], "accept": None}
+ self.calls.append(call)
+
+ def echo(record):
+ call["echo"].append(record["pos"])
+ if on_echo:
+ on_echo(record)
+
+ def accept(value):
+ call["accept"] = value.get("prompt_tokens")
+ if on_accept:
+ on_accept(value)
+
+ return self.engine.generate(prompt, *args, on_echo=echo, on_accept=accept,
+ pin=pin, **kwargs)
+
+ def __getattr__(self, name):
+ return getattr(self.engine, name)
+
+
+def _cold_option_score(prefix, option):
+ """What one option scores on a fresh engine that reads the whole prompt: the sum
+ of the ECHO log-probabilities past the prefix, from the frames themselves."""
+ env = dict(os.environ, **mimo_serve_fixture.engine_env())
+ p = subprocess.Popen([str(mimo_serve_fixture.ENGINE), "8"], env=env,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL)
+ try:
+ while b"READY" not in p.stdout.readline():
+ pass
+ n_prefix, values = None, []
+ for rid, text in ((1, prefix), (2, prefix + " " + option)):
+ data = text.encode()
+ p.stdin.write(f"SUBMIT {rid} 0 {len(data)} 0 0 1 logprobs=1\n".encode()
+ + data + b"\n")
+ p.stdin.flush()
+ while True:
+ fields = p.stdout.readline().split()
+ if fields[0] == b"ECHO":
+ p.stdout.read(int(fields[2]) + 1)
+ if rid == 2 and int(fields[3]) >= n_prefix and fields[4] != b"nan":
+ values.append(float(fields[4]))
+ elif fields[0] == b"ACCEPT" and rid == 1:
+ n_prefix = int(fields[2])
+ elif fields[0] in (b"DONE", b"ERROR"):
+ break
+ # sum(), as the endpoint adds them: on Python 3.12 it is compensated, and a
+ # plain running total differs from it in the last bits
+ return sum(values), len(values)
+ finally:
+ p.stdin.close()
+ p.wait(timeout=30)
+ p.stdout.close()
+
+
[email protected](mimo_serve_fixture.available(),
+ "mimo is not built or the tiny MiMo fixture is absent "
+ "(make mimo mimo-tiny-generate)")
+class MimoBrioEndToEnd(unittest.TestCase):
+ STATE = ("The release is late, the tests are red and the changelog is empty. "
+ "Two reviewers approved it last week.")
+ OPTIONS = ["ship it", "wait", "wait until the tests pass and the changelog is written"]
+
+ def setUp(self):
+ engine = openai_server.Engine(
+ mimo_serve_fixture.ENGINE, mimo_serve_fixture.served_fixture(), cap=8,
+ env=dict(os.environ, **mimo_serve_fixture.engine_env()),
+ family=family_by_id("mimo"))
+ self.addCleanup(engine.process.stdout.close)
+ self.addCleanup(engine.close)
+ self.engine = _Recorder(engine)
+ self.server = APIServer(("127.0.0.1", 0), self.engine, "mimo-tiny")
+ self.addCleanup(self.server.server_close)
+ self.addCleanup(self.server.shutdown)
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
+ self.base = f"http://127.0.0.1:{self.server.server_port}"
+
+ def post(self, path, body):
+ request = Request(self.base + path, data=json.dumps(body).encode(),
+ headers={"Content-Type": "application/json"})
+ with urlopen(request, timeout=120) as response:
+ return json.loads(response.read())
+
+ def test_options_read_only_their_own_tokens_and_score_like_a_cold_engine(self):
+ out = self.post("/v1/brio", {"model": "mimo-tiny", "state": self.STATE,
+ "question": "What should we do?",
+ "options": self.OPTIONS})
+ self.assertEqual(out["object"], "brio.choice")
+ self.assertIn(out["answer"], self.OPTIONS)
+ self.assertEqual(out["usage"]["completion_tokens"], 0)
+ self.assertAlmostEqual(sum(c["p"] for c in out["choices"]), 1.0, places=9)
+
+ calls = self.engine.calls
+ state, prefix, options = calls[0], calls[1], calls[2:]
+ self.assertTrue(state["pin"] and prefix["pin"])
+ self.assertEqual(len(options), len(self.OPTIONS))
+ # The question resumes from the state's photo, every option from the
+ # question's: each read-out starts exactly where the photo ends and covers
+ # nothing before it. A fallback to a full recompute would read from 0.
+ self.assertEqual(min(prefix["echo"]), state["accept"])
+ for call in options:
+ self.assertEqual(sorted(call["echo"]),
+ list(range(prefix["accept"], call["accept"])),
+ f"{call['prompt']!r} did not resume from the photo")
+ prompt = prefix["prompt"]
+ by_option = {c["option"]: c for c in out["choices"]}
+ for option in self.OPTIONS:
+ total, rows = _cold_option_score(prompt, option)
+ self.assertEqual(by_option[option]["tokens"], rows)
+ self.assertEqual(by_option[option]["logprob"], total,
+ f"{option!r}: the photo scored differently from a cold engine")
+
+ def test_chat_logprobs_reach_the_engine(self):
+ with patch("openai_server.ARCH", "mimo"):
+ out = self.post("/v1/chat/completions", {
+ "model": "mimo-tiny", "max_tokens": 6, "logprobs": True,
+ "top_logprobs": 2, "enable_thinking": False,
+ "messages": [{"role": "user", "content": "Ship it?"}]})
+ choice = out["choices"][0]
+ entries = choice["logprobs"]["content"]
+ self.assertTrue(entries, "no per-token logprobs came back")
+ for entry in entries:
+ self.assertLessEqual(entry["logprob"], 0.0)
+ self.assertEqual(len(entry["top_logprobs"]), 2)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.py
index 589e7289..809d0371 100644
--- a/c/tests/test_openai_server.py
+++ b/c/tests/test_openai_server.py
@@ -1480,6 +1480,27 @@ class StageSpanReportingTest(unittest.TestCase):
self.assertEqual(len(public[1]), 1)
self.assertEqual(public[1][0]["function"]["name"], "weather")
+ def test_the_mimo_parser_maps_the_content_it_returns(self):
+ # The logprobs channel is open on mimo, so its parser has to say which
+ # characters of the reply survive as content: every call block, then the
+ # whitespace around what is left, exactly as the plain parse removes them.
+ tool = {"type": "function", "function": {
+ "name": "weather", "parameters": {"type": "object",
+ "properties": {"city": {"type": "string"},
+ "days": {"type": "integer"}}}}}
+ raw = (" Sure. <tool_call>\n<function=weather>\n<parameter=city>Rome</parameter>\n"
+ "<parameter=days>3</parameter>\n</function>\n</tool_call> then this. ")
+ with patch("openai_server.ARCH", "mimo"):
+ content, calls, box_map, content_map = parse_arch_tool_calls_spans(raw, [tool])
+ public = parse_arch_tool_calls(raw, [tool])
+ self.assertEqual(content, "Sure. then this.")
+ self.assertEqual(json.loads(calls[0]["function"]["arguments"]),
+ {"city": "Rome", "days": 3})
+ self._assert_map_rebuilds(raw, content, content_map)
+ self._assert_map_rebuilds(raw, " Sure. then this. ", box_map)
+ self.assertEqual(public[0], content)
+ self.assertEqual([c["function"] for c in public[1]], [c["function"] for c in calls])
+
def test_the_qwen38_engine_parses_its_own_calls_with_no_flavor_set(self):
# The native arm of the same dispatch: chat_flavor() falls back to ARCH, so a
# qwen38 engine with no flavor recorded still reaches the qwen38 parser.
@@ -6280,6 +6301,32 @@ class LogprobsStageCompositionTest(unittest.TestCase):
self.assertEqual("".join(entry["token"] for entry in entries),
choice["message"]["content"])
+ def test_mimo_tool_call_syntax_is_not_described_as_content(self):
+ # MiMo's call form, through the same three stages on a mimo gateway: the
+ # reasoning and the call block are cut, and the entries join back to the
+ # content the message returns.
+ call = ("<tool_call>\n<function=search>\n<parameter=q>x</parameter>\n"
+ "</function>\n</tool_call>")
+ engine = ScriptedEngine(
+ chunks=("why", "</think>", "before ", call, " after"),
+ records=[(b"why", -0.1, [(1, -0.1)]), (b"</think>", -0.2, [(2, -0.2)]),
+ (b"before ", -0.3, [(3, -0.3)]), (call.encode(), -0.4, [(4, -0.4)]),
+ (b" after", -0.5, [(5, -0.5)])])
+ with patch("openai_server.ARCH", "mimo"):
+ choice = self._chat(engine, enable_thinking=True, tools=[{
+ "type": "function",
+ "function": {"name": "search",
+ "parameters": {"type": "object",
+ "properties": {"q": {"type": "string"}}}}}])
+ entries = choice["logprobs"]["content"]
+ self.assertEqual(choice["message"]["reasoning_content"], "why")
+ self.assertEqual(choice["message"]["content"], "before after")
+ self.assertEqual(len(choice["message"]["tool_calls"]), 1)
+ self.assertEqual([entry["token"] for entry in entries], ["before ", " after"])
+ self.assertEqual([entry["logprob"] for entry in entries], [-0.3, -0.5])
+ self.assertEqual("".join(entry["token"] for entry in entries),
+ choice["message"]["content"])
+
def test_a_plain_chat_turn_describes_every_token(self):
# The control: with no stage cutting anything, nothing is dropped.
choice = self._chat(ScriptedEngine(chunks=("the ", "answer")))
@@ -6521,9 +6568,9 @@ class ClientVisibleEngineFaultCodeTest(unittest.TestCase):
class CapabilitySplitIndependenceTest(unittest.TestCase):
"""`supports_logprobs_echo` and `supports_tok_ids` gate two unrelated SUBMIT extension
- keys and must be settable one without the other. Both are `arch == "glm"` today, so
- nothing short of a double with the two flags set to different values can show the
- split is real rather than cosmetic."""
+ keys and must be settable one without the other. A mimo engine has the first and not
+ the second; the doubles below also set them apart by hand, so the split is shown to be
+ real rather than cosmetic."""
def test_logprobs_is_refused_when_only_token_id_intake_is_available(self):
base = _spawn_test_server(self, ScriptedEngine(supports_logprobs_echo=False,
@@ -6553,6 +6600,17 @@ class CapabilitySplitIndependenceTest(unittest.TestCase):
engine.supports_logprobs_echo = False
self.assertTrue(engine.supports_tok_ids)
+ def test_a_mimo_engine_has_the_numeric_channel_and_not_token_id_intake(self):
+ # mimo.c keeps the channel's whole contract (an ECHO for every prompt position
+ # unless a pin photo covers the prefix); it reads its frames with serve_codec.h,
+ # which has no `ids=`.
+ process = FakeProcess(lambda process, written: None)
+ with patch("openai_server.subprocess.Popen", return_value=process):
+ engine = Engine("mimo", "model", cap=8, family=family_by_id("mimo"))
+ self.addCleanup(engine.close)
+ self.assertTrue(engine.supports_logprobs_echo)
+ self.assertFalse(engine.supports_tok_ids)
+
class ChatFlavorLogprobsGateTest(unittest.TestCase):
"""The logprobs/echo gate is keyed on the engine family (`supports_logprobs_echo`). A chat