Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74425da166 | ||
|
|
1569dc980d | ||
|
|
1d69232253 | ||
|
|
88aa42d40f | ||
|
|
647335489d |
@@ -22,6 +22,7 @@ import json
|
||||
import os
|
||||
|
||||
import sglang as sgl
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
from transformers import AutoTokenizer
|
||||
@@ -52,7 +53,9 @@ TOOLS = [
|
||||
def make_renderer(model: str, enable_thinking: bool | None):
|
||||
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
|
||||
if model.startswith("Qwen/Qwen3.5-"):
|
||||
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
|
||||
return Qwen35Renderer(
|
||||
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
|
||||
)
|
||||
if model == "openai/gpt-oss-20b":
|
||||
return GptOssRenderer(tokenizer)
|
||||
raise ValueError(f"unsupported demo model: {model}")
|
||||
@@ -62,8 +65,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
|
||||
print(f"\n[{label}] {turn}")
|
||||
if parsed.reasoning_content:
|
||||
print(f"reasoning: {parsed.reasoning_content[:240]}")
|
||||
if parsed.tool_calls:
|
||||
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
|
||||
for tc in parsed.tool_calls:
|
||||
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
|
||||
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
|
||||
if parsed.content:
|
||||
print(f"content: {parsed.content}")
|
||||
|
||||
@@ -141,21 +145,33 @@ def main() -> None:
|
||||
if parsed1.reasoning_content:
|
||||
assistant["reasoning_content"] = parsed1.reasoning_content
|
||||
if parsed1.tool_calls:
|
||||
assistant["tool_calls"] = parsed1.tool_calls
|
||||
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
|
||||
assistant["tool_calls"] = [
|
||||
{
|
||||
"id": tc.id or f"call_{idx}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.name,
|
||||
"arguments": tc.arguments
|
||||
if isinstance(tc.arguments, str)
|
||||
else json.dumps(tc.arguments),
|
||||
},
|
||||
}
|
||||
for idx, tc in enumerate(parsed1.tool_calls)
|
||||
]
|
||||
messages.append(assistant)
|
||||
|
||||
if parsed1.tool_calls:
|
||||
new_messages = []
|
||||
for idx, tool_call in enumerate(parsed1.tool_calls):
|
||||
fn = tool_call.get("function") or tool_call
|
||||
tool_args = fn.get("arguments") or {}
|
||||
tool_args = tool_call.arguments or {}
|
||||
if isinstance(tool_args, str):
|
||||
tool_args = json.loads(tool_args)
|
||||
new_messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.get("id", f"call_{idx}"),
|
||||
"name": fn.get("name", "multiply"),
|
||||
"tool_call_id": tool_call.id or f"call_{idx}",
|
||||
"name": tool_call.name or "multiply",
|
||||
"content": json.dumps(
|
||||
{"result": int(tool_args["a"]) * int(tool_args["b"])}
|
||||
),
|
||||
@@ -167,11 +183,14 @@ def main() -> None:
|
||||
]
|
||||
|
||||
# Turn 2: bridge extends prompt_ids + completion1 exactly.
|
||||
bridged_ids = renderer.bridge_to_next_turn(
|
||||
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
|
||||
# extended id stream is on ``.token_ids``.
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
prompt_ids, completion1, new_messages, tools=TOOLS
|
||||
)
|
||||
if bridged_ids is None:
|
||||
if bridged is None:
|
||||
raise RuntimeError("bridge_to_next_turn returned None")
|
||||
bridged_ids = bridged.token_ids
|
||||
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
|
||||
prompt_ids + completion1
|
||||
)
|
||||
|
||||
@@ -44,6 +44,7 @@ from typing import Any
|
||||
|
||||
import httpx
|
||||
from renderers.base import Renderer
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
from transformers import AutoTokenizer
|
||||
@@ -71,7 +72,9 @@ TOOLS = [
|
||||
def make_renderer(model: str, enable_thinking: bool | None) -> Renderer:
|
||||
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
|
||||
if model.startswith("Qwen/Qwen3.5-"):
|
||||
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
|
||||
return Qwen35Renderer(
|
||||
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
|
||||
)
|
||||
if model == "openai/gpt-oss-20b":
|
||||
return GptOssRenderer(tokenizer)
|
||||
raise ValueError(f"unsupported demo model: {model}")
|
||||
@@ -116,8 +119,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
|
||||
print(f"\n[{label}] {turn}")
|
||||
if parsed.reasoning_content:
|
||||
print(f"reasoning: {parsed.reasoning_content[:240]}")
|
||||
if parsed.tool_calls:
|
||||
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
|
||||
for tc in parsed.tool_calls:
|
||||
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
|
||||
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
|
||||
if parsed.content:
|
||||
print(f"content: {parsed.content}")
|
||||
|
||||
@@ -164,21 +168,33 @@ async def run_one(
|
||||
if parsed1.reasoning_content:
|
||||
assistant["reasoning_content"] = parsed1.reasoning_content
|
||||
if parsed1.tool_calls:
|
||||
assistant["tool_calls"] = parsed1.tool_calls
|
||||
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
|
||||
assistant["tool_calls"] = [
|
||||
{
|
||||
"id": tc.id or f"call_{idx}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.name,
|
||||
"arguments": tc.arguments
|
||||
if isinstance(tc.arguments, str)
|
||||
else json.dumps(tc.arguments),
|
||||
},
|
||||
}
|
||||
for idx, tc in enumerate(parsed1.tool_calls)
|
||||
]
|
||||
messages.append(assistant)
|
||||
|
||||
if parsed1.tool_calls:
|
||||
new_messages: list[dict[str, Any]] = []
|
||||
for idx, tool_call in enumerate(parsed1.tool_calls):
|
||||
fn = tool_call.get("function") or tool_call
|
||||
tool_args = fn.get("arguments") or {}
|
||||
tool_args = tool_call.arguments or {}
|
||||
if isinstance(tool_args, str):
|
||||
tool_args = json.loads(tool_args)
|
||||
new_messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.get("id", f"call_{idx}"),
|
||||
"name": fn.get("name", "multiply"),
|
||||
"tool_call_id": tool_call.id or f"call_{idx}",
|
||||
"name": tool_call.name or "multiply",
|
||||
"content": json.dumps(
|
||||
{"result": int(tool_args["a"]) * int(tool_args["b"])}
|
||||
),
|
||||
@@ -190,11 +206,14 @@ async def run_one(
|
||||
]
|
||||
|
||||
# Turn 2: bridge extends prompt_ids + completion1 exactly.
|
||||
bridged_ids = renderer.bridge_to_next_turn(
|
||||
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
|
||||
# extended id stream is on ``.token_ids``.
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
prompt_ids, completion1, new_messages, tools=TOOLS
|
||||
)
|
||||
if bridged_ids is None:
|
||||
if bridged is None:
|
||||
raise RuntimeError("bridge_to_next_turn returned None")
|
||||
bridged_ids = bridged.token_ids
|
||||
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
|
||||
prompt_ids + completion1
|
||||
)
|
||||
|
||||
@@ -22,6 +22,7 @@ import json
|
||||
import os
|
||||
|
||||
import tinker
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
from tinker import types
|
||||
@@ -53,7 +54,9 @@ TOOLS = [
|
||||
def make_renderer(model: str, enable_thinking: bool | None):
|
||||
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
|
||||
if model.startswith("Qwen/Qwen3.5-"):
|
||||
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
|
||||
return Qwen35Renderer(
|
||||
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
|
||||
)
|
||||
if model == "openai/gpt-oss-20b":
|
||||
return GptOssRenderer(tokenizer)
|
||||
raise ValueError(f"unsupported demo model: {model}")
|
||||
@@ -63,8 +66,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
|
||||
print(f"\n[{label}] {turn}")
|
||||
if parsed.reasoning_content:
|
||||
print(f"reasoning: {parsed.reasoning_content[:240]}")
|
||||
if parsed.tool_calls:
|
||||
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
|
||||
for tc in parsed.tool_calls:
|
||||
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
|
||||
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
|
||||
if parsed.content:
|
||||
print(f"content: {parsed.content}")
|
||||
|
||||
@@ -131,21 +135,33 @@ async def main() -> None:
|
||||
if parsed1.reasoning_content:
|
||||
assistant["reasoning_content"] = parsed1.reasoning_content
|
||||
if parsed1.tool_calls:
|
||||
assistant["tool_calls"] = parsed1.tool_calls
|
||||
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
|
||||
assistant["tool_calls"] = [
|
||||
{
|
||||
"id": tc.id or f"call_{idx}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.name,
|
||||
"arguments": tc.arguments
|
||||
if isinstance(tc.arguments, str)
|
||||
else json.dumps(tc.arguments),
|
||||
},
|
||||
}
|
||||
for idx, tc in enumerate(parsed1.tool_calls)
|
||||
]
|
||||
messages.append(assistant)
|
||||
|
||||
if parsed1.tool_calls:
|
||||
new_messages = []
|
||||
for idx, tool_call in enumerate(parsed1.tool_calls):
|
||||
fn = tool_call.get("function") or tool_call
|
||||
tool_args = fn.get("arguments") or {}
|
||||
tool_args = tool_call.arguments or {}
|
||||
if isinstance(tool_args, str):
|
||||
tool_args = json.loads(tool_args)
|
||||
new_messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.get("id", f"call_{idx}"),
|
||||
"name": fn.get("name", "multiply"),
|
||||
"tool_call_id": tool_call.id or f"call_{idx}",
|
||||
"name": tool_call.name or "multiply",
|
||||
"content": json.dumps(
|
||||
{"result": int(tool_args["a"]) * int(tool_args["b"])}
|
||||
),
|
||||
@@ -157,11 +173,14 @@ async def main() -> None:
|
||||
]
|
||||
|
||||
# Turn 2: bridge extends prompt_ids + completion1 exactly.
|
||||
bridged_ids = renderer.bridge_to_next_turn(
|
||||
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
|
||||
# extended id stream is on ``.token_ids``.
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
prompt_ids, completion1, new_messages, tools=TOOLS
|
||||
)
|
||||
if bridged_ids is None:
|
||||
if bridged is None:
|
||||
raise RuntimeError("bridge_to_next_turn returned None")
|
||||
bridged_ids = bridged.token_ids
|
||||
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
|
||||
prompt_ids + completion1
|
||||
)
|
||||
|
||||
@@ -26,6 +26,7 @@ import os
|
||||
import torch
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
|
||||
@@ -55,7 +56,8 @@ TOOLS = [
|
||||
def make_renderer(model: str, enable_thinking: bool | None):
|
||||
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
|
||||
if model.startswith("Qwen/Qwen3.5-"):
|
||||
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking), tokenizer
|
||||
config = Qwen35RendererConfig(enable_thinking=enable_thinking)
|
||||
return Qwen35Renderer(tokenizer, config), tokenizer
|
||||
if model == "openai/gpt-oss-20b":
|
||||
return GptOssRenderer(tokenizer), tokenizer
|
||||
raise ValueError(f"unsupported demo model: {model}")
|
||||
@@ -65,8 +67,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
|
||||
print(f"\n[{label}] {turn}")
|
||||
if parsed.reasoning_content:
|
||||
print(f"reasoning: {parsed.reasoning_content[:240]}")
|
||||
if parsed.tool_calls:
|
||||
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
|
||||
for tc in parsed.tool_calls:
|
||||
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
|
||||
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
|
||||
if parsed.content:
|
||||
print(f"content: {parsed.content}")
|
||||
|
||||
@@ -139,21 +142,33 @@ def main() -> None:
|
||||
if parsed1.reasoning_content:
|
||||
assistant["reasoning_content"] = parsed1.reasoning_content
|
||||
if parsed1.tool_calls:
|
||||
assistant["tool_calls"] = parsed1.tool_calls
|
||||
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
|
||||
assistant["tool_calls"] = [
|
||||
{
|
||||
"id": tc.id or f"call_{idx}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.name,
|
||||
"arguments": tc.arguments
|
||||
if isinstance(tc.arguments, str)
|
||||
else json.dumps(tc.arguments),
|
||||
},
|
||||
}
|
||||
for idx, tc in enumerate(parsed1.tool_calls)
|
||||
]
|
||||
messages.append(assistant)
|
||||
|
||||
if parsed1.tool_calls:
|
||||
new_messages = []
|
||||
for idx, tool_call in enumerate(parsed1.tool_calls):
|
||||
fn = tool_call.get("function") or tool_call
|
||||
tool_args = fn.get("arguments") or {}
|
||||
tool_args = tool_call.arguments or {}
|
||||
if isinstance(tool_args, str):
|
||||
tool_args = json.loads(tool_args)
|
||||
new_messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.get("id", f"call_{idx}"),
|
||||
"name": fn.get("name", "multiply"),
|
||||
"tool_call_id": tool_call.id or f"call_{idx}",
|
||||
"name": tool_call.name or "multiply",
|
||||
"content": json.dumps(
|
||||
{"result": int(tool_args["a"]) * int(tool_args["b"])}
|
||||
),
|
||||
@@ -165,11 +180,14 @@ def main() -> None:
|
||||
]
|
||||
|
||||
# Turn 2: bridge extends prompt_ids + completion1 exactly.
|
||||
bridged_ids = renderer.bridge_to_next_turn(
|
||||
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
|
||||
# extended id stream is on ``.token_ids``.
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
prompt_ids, completion1, new_messages, tools=TOOLS
|
||||
)
|
||||
if bridged_ids is None:
|
||||
if bridged is None:
|
||||
raise RuntimeError("bridge_to_next_turn returned None")
|
||||
bridged_ids = bridged.token_ids
|
||||
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
|
||||
prompt_ids + completion1
|
||||
)
|
||||
|
||||
@@ -21,6 +21,7 @@ import gc
|
||||
import json
|
||||
import os
|
||||
|
||||
from renderers.configs import Qwen35RendererConfig
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
from transformers import AutoTokenizer
|
||||
@@ -52,7 +53,9 @@ TOOLS = [
|
||||
def make_renderer(model: str, enable_thinking: bool | None):
|
||||
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
|
||||
if model.startswith("Qwen/Qwen3.5-"):
|
||||
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
|
||||
return Qwen35Renderer(
|
||||
tokenizer, Qwen35RendererConfig(enable_thinking=enable_thinking)
|
||||
)
|
||||
if model == "openai/gpt-oss-20b":
|
||||
return GptOssRenderer(tokenizer)
|
||||
raise ValueError(f"unsupported demo model: {model}")
|
||||
@@ -62,8 +65,9 @@ def print_parsed(label: str, turn: str, parsed) -> None:
|
||||
print(f"\n[{label}] {turn}")
|
||||
if parsed.reasoning_content:
|
||||
print(f"reasoning: {parsed.reasoning_content[:240]}")
|
||||
if parsed.tool_calls:
|
||||
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
|
||||
for tc in parsed.tool_calls:
|
||||
# ``parse_response`` returns ``ParsedToolCall`` dataclasses, not dicts.
|
||||
print(f"tool_call: {tc.name}({tc.arguments}) [{tc.status.value}]")
|
||||
if parsed.content:
|
||||
print(f"content: {parsed.content}")
|
||||
|
||||
@@ -134,21 +138,33 @@ def main() -> None:
|
||||
if parsed1.reasoning_content:
|
||||
assistant["reasoning_content"] = parsed1.reasoning_content
|
||||
if parsed1.tool_calls:
|
||||
assistant["tool_calls"] = parsed1.tool_calls
|
||||
# Convert the parsed dataclasses back to OpenAI-format tool_calls.
|
||||
assistant["tool_calls"] = [
|
||||
{
|
||||
"id": tc.id or f"call_{idx}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.name,
|
||||
"arguments": tc.arguments
|
||||
if isinstance(tc.arguments, str)
|
||||
else json.dumps(tc.arguments),
|
||||
},
|
||||
}
|
||||
for idx, tc in enumerate(parsed1.tool_calls)
|
||||
]
|
||||
messages.append(assistant)
|
||||
|
||||
if parsed1.tool_calls:
|
||||
new_messages = []
|
||||
for idx, tool_call in enumerate(parsed1.tool_calls):
|
||||
fn = tool_call.get("function") or tool_call
|
||||
tool_args = fn.get("arguments") or {}
|
||||
tool_args = tool_call.arguments or {}
|
||||
if isinstance(tool_args, str):
|
||||
tool_args = json.loads(tool_args)
|
||||
new_messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.get("id", f"call_{idx}"),
|
||||
"name": fn.get("name", "multiply"),
|
||||
"tool_call_id": tool_call.id or f"call_{idx}",
|
||||
"name": tool_call.name or "multiply",
|
||||
"content": json.dumps(
|
||||
{"result": int(tool_args["a"]) * int(tool_args["b"])}
|
||||
),
|
||||
@@ -160,11 +176,14 @@ def main() -> None:
|
||||
]
|
||||
|
||||
# Turn 2: bridge extends prompt_ids + completion1 exactly.
|
||||
bridged_ids = renderer.bridge_to_next_turn(
|
||||
# ``bridge_to_next_turn`` returns a ``RenderedTokens`` (or None); the
|
||||
# extended id stream is on ``.token_ids``.
|
||||
bridged = renderer.bridge_to_next_turn(
|
||||
prompt_ids, completion1, new_messages, tools=TOOLS
|
||||
)
|
||||
if bridged_ids is None:
|
||||
if bridged is None:
|
||||
raise RuntimeError("bridge_to_next_turn returned None")
|
||||
bridged_ids = bridged.token_ids
|
||||
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
|
||||
prompt_ids + completion1
|
||||
)
|
||||
|
||||
+8
-1
@@ -23,7 +23,14 @@ dependencies = [
|
||||
# Used by GptOssRenderer to render and parse harmony tokens. Vendoring
|
||||
# OpenAI's reference implementation keeps us byte-identical with vLLM
|
||||
# (which also uses it) and saves us mirroring a 330-line Jinja template.
|
||||
"openai-harmony>=0.0.8",
|
||||
#
|
||||
# Floor is ``>=0.0.4`` (not the latest 0.0.8) on purpose: every SGLang
|
||||
# release through 0.5.12.post1 hard-pins ``openai-harmony==0.0.4``, so a
|
||||
# higher floor makes ``renderers`` uninstallable alongside SGLang. The
|
||||
# GptOssRenderer renders byte-identically on 0.0.4 (verified token-for-token
|
||||
# against 0.0.8) and ``tests/test_gpt_oss_harmony_parity.py`` passes on it,
|
||||
# so the older harmony is safe.
|
||||
"openai-harmony>=0.0.4",
|
||||
# Crusoe's Rust BPE tokenizer; ~10x faster encode vs HF's tokenizers.
|
||||
# ``load_tokenizer`` patches it in by default for every supported model
|
||||
# except a small denylist (DeepSeek-V3 family). The patch is bracketed
|
||||
|
||||
+38
-12
@@ -1098,8 +1098,7 @@ def _patched_load(model_name_or_path: str, **kwargs):
|
||||
fastokens.patch_transformers()
|
||||
if not _FASTOKENS_ANNOUNCED:
|
||||
logger.info(
|
||||
"fastokens enabled — tokenizers load through the Rust BPE "
|
||||
"fast path (~10x encode speedup)."
|
||||
"fastokens enabled — tokenizers load through the Rust BPE fast path (~10x encode speedup)."
|
||||
)
|
||||
_FASTOKENS_ANNOUNCED = True
|
||||
try:
|
||||
@@ -1169,8 +1168,8 @@ def load_tokenizer(
|
||||
def _populate_registry():
|
||||
if RENDERER_REGISTRY:
|
||||
return
|
||||
from renderers.default import DefaultRenderer
|
||||
from renderers.deepseek_v3 import DeepSeekV3Renderer
|
||||
from renderers.default import DefaultRenderer
|
||||
from renderers.glm5 import GLM5Renderer, GLM51Renderer
|
||||
from renderers.glm45 import GLM45Renderer
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
@@ -1271,8 +1270,7 @@ def create_renderer(
|
||||
cls = RENDERER_REGISTRY.get(config.name)
|
||||
if cls is None:
|
||||
raise ValueError(
|
||||
f"Unknown renderer {config.name!r}. "
|
||||
f"Available: {', '.join(sorted(RENDERER_REGISTRY))}"
|
||||
f"Unknown renderer {config.name!r}. Available: {', '.join(sorted(RENDERER_REGISTRY))}"
|
||||
)
|
||||
return cls(tokenizer, config)
|
||||
|
||||
@@ -1345,7 +1343,7 @@ def build_training_sample(
|
||||
renderer: Renderer,
|
||||
messages: list[Message],
|
||||
*,
|
||||
role_to_mask: Callable[[Message], bool],
|
||||
role_to_mask: Callable[[Message], bool] | None = None,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
content_sft_roles: "set[str] | frozenset[str] | None" = None,
|
||||
) -> tuple[list[int], list[bool]]:
|
||||
@@ -1354,15 +1352,31 @@ def build_training_sample(
|
||||
Single render() call + message_indices → per-token mask.
|
||||
Replaces build_incremental_token_mask (O(N) renders → O(1)).
|
||||
|
||||
When the renderer populates ``rendered.sampled_mask``, the loss mask
|
||||
is the AND of role-based attribution and the sampled signal: only
|
||||
tokens the model would have produced at inference are trainable.
|
||||
This keeps SFT byte-aligned with the RL trajectory mask (where the
|
||||
prompt / completion split achieves the same effect structurally).
|
||||
When ``role_to_mask`` is omitted, ``loss_mask`` is the renderer's
|
||||
``sampled_mask`` directly: every token the model would have
|
||||
produced at inference is trainable, regardless of which message
|
||||
it's attributed to. This is the recommended default for renderer
|
||||
callers — the renderer owns the per-token "is this model output"
|
||||
signal, so role-level filtering becomes a downstream constraint
|
||||
rather than a precondition. (Some role markers — e.g. GLM
|
||||
``<|user|>`` / ``<|observation|>`` after a tool-calling assistant
|
||||
turn — *are* sampled by the model at inference and live inside the
|
||||
next message's span; ``sampled_mask`` captures that, but a
|
||||
naive role filter would mask them out.)
|
||||
|
||||
When ``role_to_mask`` is provided, ``loss_mask`` is the AND of the
|
||||
role-based attribution and the sampled signal: only tokens the
|
||||
model would have produced at inference AND attributed to a
|
||||
trainable role pass through. Useful when the caller needs to
|
||||
restrict training to a specific role (e.g. assistant-only) even on
|
||||
a renderer whose ``sampled_mask`` already covers other roles.
|
||||
|
||||
Renderers that don't populate ``sampled_mask`` (empty list) fall
|
||||
back to attribution-only masking — every token attributed to a
|
||||
trainable role is trained on, including template-injected
|
||||
``<|im_start|>role\\n`` openers.
|
||||
``<|im_start|>role\\n`` openers. In this fallback mode
|
||||
``role_to_mask`` is required; calling without it raises
|
||||
``ValueError``.
|
||||
|
||||
``content_sft_roles`` opts in additional roles for "body-only"
|
||||
supervision: for every message whose role is in this set, tokens
|
||||
@@ -1393,6 +1407,13 @@ def build_training_sample(
|
||||
else:
|
||||
body_roles = frozenset()
|
||||
|
||||
if role_to_mask is None and not has_sampled_info:
|
||||
raise ValueError(
|
||||
"role_to_mask is required when the renderer does not populate "
|
||||
"sampled_mask. Pass an explicit role filter (e.g. "
|
||||
"lambda m: m['role'] == 'assistant') for this renderer."
|
||||
)
|
||||
|
||||
loss_mask: list[bool] = []
|
||||
for k, msg_idx in enumerate(rendered.message_indices):
|
||||
if msg_idx < 0:
|
||||
@@ -1408,6 +1429,11 @@ def build_training_sample(
|
||||
continue
|
||||
if has_sampled_info and not rendered.sampled_mask[k]:
|
||||
loss_mask.append(False)
|
||||
elif role_to_mask is None:
|
||||
# sampled_mask alone gates the loss when no role filter is
|
||||
# supplied. ``sampled_mask[k]`` is True here (handled by the
|
||||
# branch above), so this token is trainable.
|
||||
loss_mask.append(True)
|
||||
else:
|
||||
loss_mask.append(role_to_mask(msg))
|
||||
return rendered.token_ids, loss_mask
|
||||
|
||||
+54
-15
@@ -184,6 +184,22 @@ class GLM45Renderer:
|
||||
role = msg["role"]
|
||||
content = self._visible_text(msg.get("content"))
|
||||
|
||||
# When the previous message is an assistant, this message's
|
||||
# role-opening token (``<|user|>`` / ``<|observation|>``) is
|
||||
# the inference-time stop signal that closes the assistant's
|
||||
# turn (see ``get_stop_token_ids``). Mark it
|
||||
# ``is_sampled=True`` so the loss-mask pipeline trains the
|
||||
# model to emit it after ``</tool_call>`` (instead of
|
||||
# continuing with another ``<tool_call>`` block). The token
|
||||
# stays attributed to this message (msg_idx=i) and remains
|
||||
# ``is_content=False`` — it's a role-marker / scaffold, not
|
||||
# body bytes, so ``content_mask_for_roles({"tool"})`` and
|
||||
# ``content_token_spans_by_role()`` correctly exclude it
|
||||
# from "tool body" views. Byte stream is unchanged.
|
||||
# ``system`` only appears at the start of a GLM conversation,
|
||||
# so its opener is never the closer of an assistant turn.
|
||||
closes_assistant_turn = i > 0 and messages[i - 1]["role"] == "assistant"
|
||||
|
||||
if role == "system":
|
||||
emit_special(self._system, i, is_sampled=False, is_content=False)
|
||||
# ``\n`` is the scaffold separator after the role tag;
|
||||
@@ -193,7 +209,12 @@ class GLM45Renderer:
|
||||
)
|
||||
|
||||
elif role == "user":
|
||||
emit_special(self._user, i, is_sampled=False, is_content=False)
|
||||
emit_special(
|
||||
self._user,
|
||||
i,
|
||||
is_sampled=closes_assistant_turn,
|
||||
is_content=False,
|
||||
)
|
||||
# ``\n`` is scaffold; ``content`` is body; the optional
|
||||
# ``/nothink`` suffix is scaffold the renderer injects
|
||||
# when ``enable_thinking=False``.
|
||||
@@ -362,6 +383,21 @@ class GLM45Renderer:
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
# The opener-token of the first new_message may also serve as
|
||||
# the close of the previous assistant turn (when the model
|
||||
# failed to sample the stop token itself and the bridge has to
|
||||
# synthesize the boundary above). Unlike :meth:`render`, the
|
||||
# bridge emits these with ``is_sampled=False, is_content=False``
|
||||
# — they are template scaffolding for the *next* step's prompt,
|
||||
# not tokens the model produced *in this* step. The RL loss
|
||||
# operates on ``previous_completion_ids`` (what the model
|
||||
# actually sampled this round); bridge tokens belong to the
|
||||
# subsequent prompt and must not be counted as "model output"
|
||||
# by downstream mask consumers. This deliberate disagreement
|
||||
# with ``render()`` reflects the SFT vs RL semantics: render's
|
||||
# masks describe what the model *should* produce given a
|
||||
# complete conversation; bridge's masks describe what it
|
||||
# *actually* produced this step.
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
content = self._visible_text(msg.get("content"))
|
||||
@@ -531,21 +567,24 @@ class GLM45Renderer:
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False. The body bytes
|
||||
# get ``is_content=True``; the ``\n<tool_response>\n`` /
|
||||
# ``\n</tool_response>`` wraps and the ``<|observation|>`` role
|
||||
# tag are scaffold so the SFT mask for tool body never trains
|
||||
# the model to emit them. Single BPE pass over the joined text
|
||||
# preserves boundary merges (the tool body's leading/trailing
|
||||
# chars can merge with the wrap's ``\n``s if the tokenizer would
|
||||
# do so; we route through ``emit_text_segments`` so the
|
||||
# attribution is offset-driven and tokenizer-agnostic).
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
# Tool body bytes get ``is_content=True``; the wraps are
|
||||
# scaffold. The ``<|observation|>`` role tag is scaffold too
|
||||
# (``is_content=False`` so ``content_mask_for_roles({"tool"})``
|
||||
# excludes it). When the previous message is an assistant it
|
||||
# doubles as the inference stop signal for that assistant's
|
||||
# turn — mark it ``is_sampled=True`` so SFT trains the model to
|
||||
# emit it after ``</tool_call>``. The token stays attributed to
|
||||
# this tool message; byte stream is unchanged.
|
||||
prev_role = messages[msg_idx - 1]["role"] if msg_idx > 0 else None
|
||||
closes_assistant_turn = prev_role == "assistant"
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._observation, msg_idx, is_sampled=False, is_content=False)
|
||||
if prev_role != "tool":
|
||||
emit_special(
|
||||
self._observation,
|
||||
msg_idx,
|
||||
is_sampled=closes_assistant_turn,
|
||||
is_content=False,
|
||||
)
|
||||
|
||||
emit_text_segments(
|
||||
[
|
||||
|
||||
+54
-10
@@ -207,12 +207,33 @@ class GLM5Renderer:
|
||||
role = msg["role"]
|
||||
content = self._visible_text(msg.get("content"))
|
||||
|
||||
# When the previous message is an assistant, this message's
|
||||
# role-opening token (``<|user|>`` / ``<|observation|>``) is
|
||||
# the inference-time stop signal that closes the assistant's
|
||||
# turn (see ``get_stop_token_ids``). Mark it
|
||||
# ``is_sampled=True`` so the loss-mask pipeline trains the
|
||||
# model to emit it after ``</tool_call>`` (instead of
|
||||
# continuing with another ``<tool_call>`` block). The token
|
||||
# stays attributed to this message (msg_idx=i) and remains
|
||||
# ``is_content=False`` — it's a role-marker / scaffold, not
|
||||
# body bytes, so ``content_mask_for_roles({"tool"})`` and
|
||||
# ``content_token_spans_by_role()`` correctly exclude it
|
||||
# from "tool body" views. Byte stream is unchanged.
|
||||
# ``system`` only appears at the start of a GLM conversation,
|
||||
# so its opener is never the closer of an assistant turn.
|
||||
closes_assistant_turn = i > 0 and messages[i - 1]["role"] == "assistant"
|
||||
|
||||
if role == "system":
|
||||
emit_special(self._system, i, is_sampled=False, is_content=False)
|
||||
emit_text(content, i, is_sampled=False, is_content=True)
|
||||
|
||||
elif role == "user":
|
||||
emit_special(self._user, i, is_sampled=False, is_content=False)
|
||||
emit_special(
|
||||
self._user,
|
||||
i,
|
||||
is_sampled=closes_assistant_turn,
|
||||
is_content=False,
|
||||
)
|
||||
emit_text(content, i, is_sampled=False, is_content=True)
|
||||
|
||||
elif role == "assistant":
|
||||
@@ -382,6 +403,21 @@ class GLM5Renderer:
|
||||
ext_sampled.append(is_sampled)
|
||||
ext_content.append(is_content)
|
||||
|
||||
# The opener-token of the first new_message may also serve as
|
||||
# the close of the previous assistant turn (when the model
|
||||
# failed to sample the stop token itself and the bridge has to
|
||||
# synthesize the boundary above). Unlike :meth:`render`, the
|
||||
# bridge emits these with ``is_sampled=False, is_content=False``
|
||||
# — they are template scaffolding for the *next* step's prompt,
|
||||
# not tokens the model produced *in this* step. The RL loss
|
||||
# operates on ``previous_completion_ids`` (what the model
|
||||
# actually sampled this round); bridge tokens belong to the
|
||||
# subsequent prompt and must not be counted as "model output"
|
||||
# by downstream mask consumers. This deliberate disagreement
|
||||
# with ``render()`` reflects the SFT vs RL semantics: render's
|
||||
# masks describe what the model *should* produce given a
|
||||
# complete conversation; bridge's masks describe what it
|
||||
# *actually* produced this step.
|
||||
for i, msg in enumerate(new_messages):
|
||||
role = msg.get("role")
|
||||
content = self._visible_text(msg.get("content"))
|
||||
@@ -566,16 +602,24 @@ class GLM5Renderer:
|
||||
emit_text,
|
||||
emit_text_segments,
|
||||
) -> None:
|
||||
# Tool messages are conversation history injected by the runtime
|
||||
# between assistant turns — the model never samples any of these
|
||||
# tokens, so every emission is is_sampled=False. The tool body
|
||||
# bytes get ``is_content=True``; the ``<|observation|>`` /
|
||||
# ``<tool_response>`` wraps are scaffold so the SFT mask for
|
||||
# tool body never trains the model to emit them.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
# Tool body bytes get ``is_content=True``; the wraps are
|
||||
# scaffold. The ``<|observation|>`` role tag is scaffold too
|
||||
# (``is_content=False`` so ``content_mask_for_roles({"tool"})``
|
||||
# excludes it). When the previous message is an assistant it
|
||||
# doubles as the inference stop signal for that assistant's
|
||||
# turn — mark it ``is_sampled=True`` so SFT trains the model to
|
||||
# emit it after ``</tool_call>``. The token stays attributed to
|
||||
# this tool message; byte stream is unchanged.
|
||||
prev_role = messages[msg_idx - 1]["role"] if msg_idx > 0 else None
|
||||
closes_assistant_turn = prev_role == "assistant"
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._observation, msg_idx, is_sampled=False, is_content=False)
|
||||
if prev_role != "tool":
|
||||
emit_special(
|
||||
self._observation,
|
||||
msg_idx,
|
||||
is_sampled=closes_assistant_turn,
|
||||
is_content=False,
|
||||
)
|
||||
|
||||
emit_special(
|
||||
self._tool_response_tok, msg_idx, is_sampled=False, is_content=False
|
||||
|
||||
@@ -430,7 +430,7 @@ class Nemotron3Renderer:
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None, # noqa: ARG002 — args land in a JSON object, schema not needed
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
stop_ids = {self._im_end}
|
||||
if self._endoftext is not None:
|
||||
@@ -443,6 +443,7 @@ class Nemotron3Renderer:
|
||||
think_end_id=self._think_end,
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
|
||||
+16
-10
@@ -65,30 +65,36 @@ def _coerce_arg_value(
|
||||
"""Coerce a raw ``<arg_value>`` body to its declared type.
|
||||
|
||||
Returns ``(value, used_json_fallback)``. The boolean is ``True`` only
|
||||
when ``json.loads`` was attempted and raised, so the caller knows
|
||||
whether to flag ``INVALID_JSON``. Returning a string verbatim
|
||||
because the schema declared ``type: "string"`` is NOT a fallback.
|
||||
when ``json.loads`` was attempted, raised, AND the schema doesn't
|
||||
permit a string. Returning a string verbatim because the schema
|
||||
permits strings is NOT a fallback.
|
||||
|
||||
Rule (matches vLLM / SGLang reference parsers):
|
||||
|
||||
- If the param's declared ``type`` is ``"string"`` (or single-element
|
||||
``["string"]``), return ``text`` verbatim — never ``json.loads``.
|
||||
- Anything else (no schema, non-string scalar, object, array, or
|
||||
union types that include non-string): try ``json.loads`` and fall
|
||||
back to raw ``text`` on parse failure.
|
||||
- Otherwise try ``json.loads``. If that fails, return raw ``text``.
|
||||
The ``used_json_fallback`` flag is ``True`` only when the schema
|
||||
does NOT permit a string — i.e. the fallback is truly suspect.
|
||||
|
||||
Union types that include ``"string"`` alongside other types still
|
||||
attempt ``json.loads`` first so an explicit integer / bool can
|
||||
parse; the string branch only wins as the fallback.
|
||||
Union types (``anyOf``/``oneOf``) that include ``"string"`` alongside
|
||||
other types still attempt ``json.loads`` first so an explicit
|
||||
integer / bool can parse; the string branch wins as fallback, and
|
||||
landing there is expected — not a malformed-JSON signal.
|
||||
"""
|
||||
string_is_allowed = False
|
||||
if param_schema is not None:
|
||||
declared = param_schema.get("type")
|
||||
if declared == "string" or declared == ["string"]:
|
||||
return text, False
|
||||
for branch in param_schema.get("anyOf") or param_schema.get("oneOf") or []:
|
||||
if isinstance(branch, dict) and branch.get("type") == "string":
|
||||
string_is_allowed = True
|
||||
break
|
||||
try:
|
||||
return json.loads(text), False
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
return text, True
|
||||
return text, not string_is_allowed
|
||||
|
||||
|
||||
def _find(ids: list[int], target: int, start: int = 0) -> int:
|
||||
|
||||
@@ -26,7 +26,7 @@ import pytest
|
||||
|
||||
|
||||
# (HuggingFace model name, renderer name). Two JSON-shaped controls
|
||||
# (string types already preserved by the wire format) + four XML-style
|
||||
# (string types already preserved by the wire format) + five XML-style
|
||||
# parsers that rely on the schema to preserve them.
|
||||
_MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"), # hermes JSON — control
|
||||
@@ -35,6 +35,7 @@ _MODELS = [
|
||||
("zai-org/GLM-5", "auto"), # XML
|
||||
("MiniMaxAI/MiniMax-M2.5", "auto"), # XML
|
||||
("poolside/Laguna-XS.2", "auto"), # XML
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"), # XML
|
||||
]
|
||||
|
||||
|
||||
@@ -137,3 +138,75 @@ def test_string_arg_preserves_type(model, renderer_name, renderer, args):
|
||||
assert got == args, (
|
||||
f"{model}: tool-arg type drift — sent {args!r}, parser returned {got!r}"
|
||||
)
|
||||
|
||||
|
||||
# Schemas where ``string`` is one branch of a union (``anyOf`` / ``oneOf``).
|
||||
# These are common in practice — e.g. ``form_input.value: str | bool`` in
|
||||
# Pydantic serialises to ``{"anyOf": [{"type": "string"}, {"type": "boolean"}]}``.
|
||||
# Without the union-aware check, the XML parser's ``json.loads`` falls back
|
||||
# to raw text for bare strings, but flags the call ``INVALID_JSON`` because
|
||||
# no top-level ``type`` key declared a string — silently dropping otherwise
|
||||
# valid tool calls in the renderer client.
|
||||
UNION_WITH_STRING_SCHEMAS = [
|
||||
pytest.param(
|
||||
{"anyOf": [{"type": "string"}, {"type": "boolean"}]},
|
||||
id="anyOf-string-boolean",
|
||||
),
|
||||
pytest.param(
|
||||
{"anyOf": [{"type": "string"}, {"type": "null"}]},
|
||||
id="anyOf-string-null",
|
||||
),
|
||||
pytest.param(
|
||||
{"oneOf": [{"type": "string"}, {"type": "integer"}]},
|
||||
id="oneOf-string-integer",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("param_schema", UNION_WITH_STRING_SCHEMAS)
|
||||
def test_union_with_string_emits_ok_status(
|
||||
model, renderer_name, renderer, param_schema
|
||||
):
|
||||
"""Union schemas containing ``string`` must yield ``status=OK`` when
|
||||
the model emits a bare string. Pre-fix, ``_coerce_arg_value`` flagged
|
||||
this as ``INVALID_JSON`` because the top-level ``type`` key was
|
||||
absent (the string branch was under ``anyOf`` / ``oneOf``)."""
|
||||
from renderers.base import ToolCallParseStatus
|
||||
|
||||
tools = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "f",
|
||||
"description": "Test tool with one union-typed parameter.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"x": param_schema},
|
||||
"required": ["x"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
args = {"x": "abc"}
|
||||
msg = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "functions.f:0",
|
||||
"function": {"name": "f", "arguments": args},
|
||||
}
|
||||
],
|
||||
}
|
||||
completion_ids = _extract_assistant_tokens(renderer, PROMPT, msg, tools=tools)
|
||||
parsed = renderer.parse_response(completion_ids, tools=tools)
|
||||
|
||||
assert parsed.tool_calls, f"{model}: parser returned no tool_calls"
|
||||
tc = parsed.tool_calls[0]
|
||||
assert tc.status == ToolCallParseStatus.OK, (
|
||||
f"{model}: union-with-string schema flagged {tc.status} on bare string"
|
||||
)
|
||||
got = _normalize_args(tc.arguments)
|
||||
assert got == args, (
|
||||
f"{model}: tool-arg drift — sent {args!r}, parser returned {got!r}"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user