y |DSML| nope> <|User|> <|DSML| unknown>"
+ self.assertEqual(self.all_at_once(text), text)
+
+ def test_the_end_of_the_output_inside_a_tag_is_text(self):
+ t = DsmlTranslator()
+ got = t.feed("ok <|DSML| inv") + t.flush()
+ self.assertEqual(got, "ok <|DSML| inv")
+
+ def test_a_value_that_looks_like_a_tag(self):
+ raw = call(("write", [("text", "
bold and < 3", True)]))
+ self.assertIn("
\nbold and < 3\n", self.all_at_once(raw))
+
+ def test_a_missing_closing_tag_is_closed(self):
+ raw = '<|DSML| calls>\n<|DSML| invoke name="f">\n<|DSML| parameter name="a" string="true">x|DSML| invoke>'
+ self.assertEqual(self.all_at_once(raw),
+ "
\n\n\nx\n\n\n\n")
+
+
+class Parser(unittest.TestCase):
+ TOOLS = [WEATHER["function"], {"name": "lookup", "description": "", "parameters": {
+ "type": "object", "properties": {"id": {}}}}]
+
+ def run_parser(self, text, thinking=True, step=7, cls=DsmlOutputParser):
+ p = cls(thinking=thinking, tools=self.TOOLS, stream_tools=True)
+ evs = []
+ for i in range(0, len(text), step):
+ evs += p.feed(text[i:i + step])
+ evs += p.finish("stop")
+ return evs
+
+ def test_reasoning_then_two_calls(self):
+ raw = call(("get_weather", [("city", "Zagreb", True), ("days", "3", False)]), ("lookup", [("id", "123", True)]))
+ for step in (1, 4, 1000):
+ evs = self.run_parser("Think < ok." + raw, step=step)
+ self.assertEqual("".join(e.text for e in evs if e.kind == "reasoning"), "Think < ok.")
+ calls = [e.call for e in evs if e.kind == "tool_call"]
+ self.assertEqual([(c.name, c.arguments) for c in calls],
+ [("get_weather", {"city": "Zagreb", "days": 3}), ("lookup", {"id": "123"})])
+ self.assertEqual("".join(e.text for e in evs if e.kind == "tool_args"),
+ '{"city":"Zagreb","days":3}{"id":"123"}')
+
+ def test_a_string_value_stays_a_string_even_when_the_schema_says_nothing(self):
+ evs = self.run_parser(call(("lookup", [("id", "007", True)])), thinking=False)
+ self.assertEqual([e.call.arguments for e in evs if e.kind == "tool_call"], [{"id": "007"}])
+ evs = self.run_parser(call(("lookup", [("id", "7", False)])), thinking=False)
+ self.assertEqual([e.call.arguments for e in evs if e.kind == "tool_call"], [{"id": 7}])
+
+ def test_a_non_string_value_is_json(self):
+ evs = self.run_parser(call(("lookup", [("id", '{"a": [1, 2]}', False)])), thinking=False)
+ self.assertEqual([e.call.arguments for e in evs if e.kind == "tool_call"], [{"id": {"a": [1, 2]}}])
+
+ def test_content_before_the_call_and_none_after(self):
+ evs = self.run_parser("Checking.\n\n" + call(("lookup", [("id", "x", True)]))[2:], thinking=False)
+ self.assertEqual("".join(e.text for e in evs if e.kind == "content").strip(), "Checking.")
+ self.assertEqual(sum(e.kind == "tool_call" for e in evs), 1)
+
+ def test_a_call_cut_off_by_the_length_limit_is_not_a_call(self):
+ raw = call(("get_weather", [("city", "Zagr", True)]))
+ raw = raw[:raw.index("Zagr") + 4]
+ p = DsmlOutputParser(thinking=False, tools=self.TOOLS, stream_tools=True)
+ evs = p.feed(raw) + p.finish("length")
+ self.assertEqual(sum(e.kind == "tool_call" for e in evs), 0)
+
+ def test_the_plain_parser_is_unchanged(self):
+ p = OutputParser(thinking=False, tools=self.TOOLS)
+ evs = p.feed("
\n\n\n5\n\n\n")
+ self.assertEqual([e.call.arguments for e in evs if e.kind == "tool_call"], [{"id": 5}])
+ self.assertTrue(p.clean)
+
+ def test_clean_counts_a_held_tag(self):
+ p = DsmlOutputParser(thinking=False, tools=self.TOOLS)
+ p.feed("hello <|DS")
+ self.assertFalse(p.clean)
+ p.feed("ML| calls>")
+ self.assertTrue(p.clean)
+
+ def test_forced_opening(self):
+ self.assertEqual(to_dsml_force("
\n\n"),
+ '<|DSML| calls>\n<|DSML| invoke name="get_weather">\n')
+ self.assertEqual(to_dsml_force("\n\n<|DSML| invoke name="')
+ self.assertIsNone(to_dsml_force(None))
+ # the opening and the model's continuation are one call
+ p = DsmlOutputParser(thinking=False, tools=self.TOOLS, stream_tools=True)
+ evs = p.feed(to_dsml_force("\n\n"))
+ evs += p.feed('<|DSML| parameter name="city" string="true">Rome|DSML| parameter>\n|DSML| invoke>\n|DSML| calls>')
+ evs += p.finish("stop")
+ self.assertEqual([(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"],
+ [("get_weather", {"city": "Rome"})])
+
+
+class Api(unittest.TestCase):
+ """Both APIs against a fake engine that replays scripted DeepSeek text."""
+
+ @classmethod
+ def setUpClass(cls):
+ cls.tok = mini_tokenizer()
+
+ def start(self, script):
+ tok = self.tok
+ engine = DsEngine(tok, script)
+ svc = Service(engine, tok, ChatTemplate(TEMPLATE), model_name=default_model_name({"arch": "deepseek41"}))
+ svc.model_arch = "deepseek41"
+ svc.set_family("deepseek41")
+ httpd = serve(svc, port=0)
+ self.addCleanup(httpd.server_close)
+ self.addCleanup(httpd.shutdown)
+ self.addCleanup(frontend.use_family, None)
+ self.engine, self.svc = engine, svc
+ self.base = f"http://127.0.0.1:{httpd.server_address[1]}"
+ return engine
+
+ def post(self, path, body, raw=False):
+ req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),
+ headers={"Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=30) as r:
+ data = r.read().decode()
+ return r.status, (data if raw else json.loads(data))
+ except urllib.error.HTTPError as e:
+ return e.code, json.loads(e.read().decode())
+
+ def prompt(self):
+ return self.tok.decode(self.engine.last_prompt)
+
+ def chat(self, **extra):
+ body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 400, **extra}
+ return self.post("/v1/chat/completions", body)
+
+ # -- thinking --------------------------------------------------------------------------------
+ def test_thinking_by_default(self):
+ self.start("The user greets me.\n\nHello!")
+ status, r = self.chat()
+ self.assertEqual(status, 200, r)
+ self.assertTrue(self.prompt().endswith("<|User|>hi<|Assistant|>"))
+ msg = r["choices"][0]["message"]
+ self.assertEqual(msg["reasoning_content"], "The user greets me.")
+ self.assertEqual(msg["content"].strip(), "Hello!")
+ self.assertEqual(r["choices"][0]["finish_reason"], "stop")
+
+ def test_thinking_off(self):
+ self.start("Hello!")
+ for extra in ({"chat_template_kwargs": {"enable_thinking": False}}, {"reasoning_effort": "none"}):
+ status, r = self.chat(**extra)
+ self.assertEqual(status, 200, r)
+ self.assertTrue(self.prompt().endswith("<|User|>hi<|Assistant|>"), extra)
+ msg = r["choices"][0]["message"]
+ self.assertEqual(msg["content"].strip(), "Hello!")
+ self.assertFalse(msg.get("reasoning_content"))
+
+ def test_the_end_token_is_deepseeks_not_qwens(self):
+ self.start("one<|im_end|>two") # (not a token here: just text, like any other)
+ status, r = self.chat(chat_template_kwargs={"enable_thinking": False})
+ self.assertEqual(r["choices"][0]["message"]["content"], "one<|im_end|>two")
+
+ def test_model_name_and_card_sampling(self):
+ self.start("ok")
+ self.assertEqual(FAMILY_MODEL_NAMES["deepseek41"], "deepseek-v4.1-flash")
+ self.assertEqual(default_model_name({"arch": "deepseek41"}), "deepseek-v4.1-flash")
+ self.assertEqual(model_card_sampling("deepseek41", True), {"temperature": 1.0, "top_p": 1.0})
+ self.chat()
+ self.assertEqual(self.engine.last_sampling.get("temperature"), 1.0)
+
+ # -- effort ------------------------------------------------------------------------------------
+ def test_effort_words(self):
+ self.start("ok")
+ for given, line in (("low", "Reasoning Effort: 50 "), ("medium", "Reasoning Effort: 62 "),
+ ("high", "Reasoning Effort: 75 "), ("max", "Reasoning Effort: 100 "),
+ ("xhigh", "Reasoning Effort: 100 "), (40, "Reasoning Effort: 40 ")):
+ status, r = self.chat(reasoning_effort=given)
+ self.assertEqual(status, 200, (given, r))
+ self.assertIn(line, self.prompt(), given)
+ status, r = self.chat()
+ self.assertIn("Reasoning Effort: 75 ", self.prompt())
+ status, r = self.chat(reasoning_effort="extreme")
+ self.assertEqual(status, 400)
+
+ def test_anthropic_budget_picks_the_effort(self):
+ self.start("ok")
+ status, r = self.post("/v1/messages", {"model": "x", "max_tokens": 300, "thinking": {"type": "enabled", "budget_tokens": 1000},
+ "messages": [{"role": "user", "content": "hi"}]})
+ self.assertEqual(status, 200, r)
+ self.assertIn("Reasoning Effort: 50 ", self.prompt())
+
+ # -- tool calls -------------------------------------------------------------------------------
+ def test_openai_tool_call(self):
+ self.start("Need the weather." + call(("get_weather", [("city", "Zagreb", True), ("days", "2", False)])))
+ status, r = self.chat(tools=[WEATHER])
+ self.assertEqual(status, 200, r)
+ self.assertIn('"name": "get_weather"', self.prompt())
+ ch = r["choices"][0]
+ self.assertEqual(ch["finish_reason"], "tool_calls")
+ tc = ch["message"]["tool_calls"][0]
+ self.assertEqual(tc["function"]["name"], "get_weather")
+ self.assertEqual(json.loads(tc["function"]["arguments"]), {"city": "Zagreb", "days": 2})
+ self.assertEqual(ch["message"]["reasoning_content"], "Need the weather.")
+
+ def test_two_calls_in_one_turn(self):
+ self.start("" + call(("get_weather", [("city", "A", True)]), ("get_weather", [("city", "B", True)])))
+ status, r = self.chat(tools=[WEATHER])
+ names = [json.loads(c["function"]["arguments"])["city"] for c in r["choices"][0]["message"]["tool_calls"]]
+ self.assertEqual(names, ["A", "B"])
+
+ def test_streamed_tool_call(self):
+ self.start("" + call(("get_weather", [("city", "Zagreb", True)])))
+ status, text = self.post("/v1/chat/completions", {"messages": [{"role": "user", "content": "w?"}], "tools": [WEATHER],
+ "stream": True, "max_tokens": 300}, raw=True)
+ self.assertEqual(status, 200)
+ chunks = [json.loads(x[6:]) for x in text.split("\n\n") if x.startswith("data: ") and x != "data: [DONE]"]
+ calls = [tc for c in chunks for tc in c["choices"][0]["delta"].get("tool_calls", [])]
+ self.assertEqual(calls[0]["function"]["name"], "get_weather")
+ self.assertEqual(json.loads("".join(tc["function"].get("arguments", "") for tc in calls)), {"city": "Zagreb"})
+ self.assertEqual([c["choices"][0]["finish_reason"] for c in chunks if c["choices"][0].get("finish_reason")],
+ ["tool_calls"])
+
+ def test_a_tool_result_turn_renders_for_the_model(self):
+ self.start("The weather is sunny.")
+ msgs = [{"role": "user", "content": "weather in Zagreb?"},
+ {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {
+ "name": "get_weather", "arguments": "{\"city\": \"Zagreb\"}"}}]},
+ {"role": "tool", "tool_call_id": "c1", "content": "sunny, 21C"}]
+ status, r = self.post("/v1/chat/completions", {"messages": msgs, "tools": [WEATHER], "max_tokens": 200,
+ "chat_template_kwargs": {"enable_thinking": False}})
+ self.assertEqual(status, 200, r)
+ p = self.prompt()
+ self.assertIn('<|DSML| parameter name="city" string="true">Zagreb|DSML| parameter>', p)
+ self.assertIn("sunny, 21C", p)
+ self.assertEqual(r["choices"][0]["message"]["content"].strip(), "The weather is sunny.")
+
+ def test_forced_tool_choice(self):
+ self.start('<|DSML| parameter name="city" string="true">Rome|DSML| parameter>\n|DSML| invoke>\n|DSML| calls>')
+ status, r = self.chat(tools=[WEATHER], tool_choice={"type": "function", "function": {"name": "get_weather"}},
+ chat_template_kwargs={"enable_thinking": False})
+ self.assertEqual(status, 200, r)
+ self.assertTrue(self.prompt().endswith('<|Assistant|><|DSML| calls>\n<|DSML| invoke name="get_weather">\n'), self.prompt()[-120:])
+ tc = r["choices"][0]["message"]["tool_calls"][0]
+ self.assertEqual((tc["function"]["name"], json.loads(tc["function"]["arguments"])), ("get_weather", {"city": "Rome"}))
+
+ # -- anthropic ---------------------------------------------------------------------------------
+ def test_anthropic_tool_use(self):
+ self.start("Weather needed." + call(("get_weather", [("city", "Oslo", True), ("days", "1", False)])))
+ status, r = self.post("/v1/messages", {"model": "x", "max_tokens": 400,
+ "tools": [{"name": "get_weather", "description": "w", "input_schema":
+ WEATHER["function"]["parameters"]}],
+ "messages": [{"role": "user", "content": "Oslo?"}]})
+ self.assertEqual(status, 200, r)
+ kinds = [b["type"] for b in r["content"]]
+ self.assertEqual(kinds, ["thinking", "tool_use"])
+ self.assertEqual(r["content"][1]["input"], {"city": "Oslo", "days": 1})
+ self.assertEqual(r["stop_reason"], "tool_use")
+
+ def test_anthropic_text_without_thinking(self):
+ self.start("Hello there.")
+ status, r = self.post("/v1/messages", {"model": "x", "max_tokens": 100, "thinking": {"type": "disabled"},
+ "messages": [{"role": "user", "content": "hi"}]})
+ self.assertEqual(status, 200, r)
+ self.assertTrue(self.prompt().endswith("<|Assistant|>"))
+ self.assertEqual([b["type"] for b in r["content"]], ["text"])
+ self.assertEqual(r["content"][0]["text"], "Hello there.")
+ self.assertEqual(r["stop_reason"], "end_turn")
+
+ # -- metrics -----------------------------------------------------------------------------------
+ def test_metrics_use_the_one_answer_speed(self):
+ self.start("Hello, how are you today?")
+ self.chat()
+ status = urllib.request.urlopen(self.base + "/metrics", timeout=10)
+ m = json.loads(status.read().decode())
+ last = m["requests"][-1]
+ # produced tokens over the engine's decode time (10 ms a token in the fake), never over the prompt's time
+ self.assertEqual(last["decode_tok_s"], 100.0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/serve/test_family_name.py b/serve/test_family_name.py
index cd4024ff..44deb841 100644
--- a/serve/test_family_name.py
+++ b/serve/test_family_name.py
@@ -19,11 +19,12 @@ class FamilyName(unittest.TestCase):
def test_per_family(self):
self.assertEqual(default_model_name({"arch": "qwen35moe"}), "qwen3.6-35b-a3b")
self.assertEqual(default_model_name({"arch": "qwen4exp"}), "qwen3.8-flash-next")
+ self.assertEqual(default_model_name({"arch": "deepseek41"}), "deepseek-v4.1-flash")
def test_old_configs(self):
self.assertEqual(default_model_name({}), "qwen3.8-flash-next")
self.assertEqual(default_model_name({"arch": "something-else"}), "qwen3.8-flash-next")
- self.assertEqual(set(FAMILY_MODEL_NAMES), {"qwen4exp", "qwen35moe"})
+ self.assertEqual(set(FAMILY_MODEL_NAMES), {"qwen4exp", "qwen35moe", "deepseek41"})
if __name__ == "__main__":
diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py
index 42a27fed..33452af8 100644
--- a/tools/strata_tokenizer.py
+++ b/tools/strata_tokenizer.py
@@ -66,6 +66,37 @@ QWEN35_PATTERN = (
)
+# The `deepseek-v3` pre-tokenizer (DeepSeek-V3 / V4.1; llama.cpp LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM, the same regex list as
+# JoyAI and Hunyuan-dense). UNLIKE the single-pattern families it is a SEQUENCE: each pattern splits the pieces the
+# one before it left (a span a pattern does not match stays a piece of its own), so digits (runs of 1..3) and CJK
+# runs are cut out before the general word / punctuation / whitespace pattern sees the rest.
+DEEPSEEK3_PATTERNS = (
+ r"\p{N}{1,3}",
+ "[一-龥-ゟ゠-ヿ]+",
+ r"[!\"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~][A-Za-z]+|[^\r\n\p{L}\p{P}\p{S}]?[\p{L}\p{M}]+"
+ r"| ?[\p{P}\p{S}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+",
+)
+
+
+def _sequence_findall(patterns, text: str) -> list[str]:
+ """llama.cpp's unicode_regex_split: the pieces of `text` after each pattern in turn splits every piece into its
+ matches and the unmatched spans between them."""
+ pieces = [text]
+ for pat in patterns:
+ nxt = []
+ for piece in pieces:
+ pos = 0
+ for m in pat.finditer(piece):
+ if m.start() > pos:
+ nxt.append(piece[pos:m.start()])
+ nxt.append(m.group())
+ pos = m.end()
+ if pos < len(piece):
+ nxt.append(piece[pos:])
+ pieces = nxt
+ return pieces
+
+
class Tokenizer:
def __init__(self, tokens: list[str], merges: list[str], token_types: list[int] | None = None,
pre: str = "qwen35", special_ids: dict[str, int] | None = None):
@@ -88,7 +119,12 @@ class Tokenizer:
if parts[0] not in self.ids or parts[1] not in self.ids:
raise ValueError("merge %d names a token outside the vocabulary: %r" % (i, m))
self.ranks[(parts[0], parts[1])] = i
- self._re = regex.compile(QWEN35_PATTERN)
+ if str(pre).startswith("deepseek"):
+ seq = [regex.compile(x) for x in DEEPSEEK3_PATTERNS]
+ self._split = lambda text: _sequence_findall(seq, text)
+ else:
+ self._re = regex.compile(QWEN35_PATTERN)
+ self._split = self._re.findall
# The literals matched directly instead of being run through BPE. GGUF token types: 3 = CONTROL,
# 4 = USER_DEFINED. The two classes behave DIFFERENTLY and llama.cpp's own tokenizer settled which:
@@ -223,7 +259,7 @@ class Tokenizer:
# A piece's ids depend on the piece alone, so repeated pieces (most of a resent conversation) are looked up
# instead of merged again. The ids are the ones _bpe gives: this only skips the work.
cache = self._piece_ids
- for piece in self._re.findall(text):
+ for piece in self._split(text):
got = cache.get(piece)
if got is None:
mapped = "".join(BYTE_TO_UNICODE[b] for b in piece.encode("utf-8"))
@@ -304,6 +340,11 @@ class Tokenizer:
if b is None:
if i < 0 or i >= len(self.tokens):
raise IndexError("token id %d is outside the vocabulary (%d)" % (i, len(self.tokens)))
+ if self.token_types and i < len(self.token_types) and self.token_types[i] in (3, 4):
+ # a special token's string is the literal text (DeepSeek's `<|User|>`, `|DSML|` hold characters outside
+ # the byte alphabet); for Qwen's ASCII specials it is the same bytes the alphabet would give
+ b = cache[i] = self.tokens[i].encode("utf-8")
+ return b
raw = bytearray()
for ch in self.tokens[i]:
v = UNICODE_TO_BYTE.get(ch)