Skip to content

Commit 88407d1

Browse files
nood-co1ashhart
authored andcommitted
feat(cuda): stop strings on every CUDA engine; ignore_eos and stop checked before a stream opens
- The CUDA server reads `stop` (a string or a list) and cuts the reply token by token: at the first token whose text completes a stop string, the reply's tokens end there, on_tokens returns True, and the match and everything after it are left out. Drafted rounds of many tokens and "draft": false rounds of one therefore give the same content, usage and token_sha. With return_token_ids, the ids listed end at the same token. - The 27B (one GPU and two ranks), and Flash Next and Nemotron on one GPU, stop in the round that holds the match; concurrent streams stop after a later round. GLM, and Flash Next and Nemotron on two ranks, decode on to an end token or the reply limit, and the server returns the reply only up to the match. - Streamed deltas hold back an end that may begin a stop string, as on the Mac (StopPolicy.visible); stop strings match the generated text, reasoning included, before it is split; tool calls are parsed from the cut text. - A non-boolean ignore_eos or a malformed stop is refused with HTTP 400 before any stream bytes (stop_options, as on the Mac). - Where the engine reads ignore_eos (GLM), end tokens inside the reply are text, as on the Mac, and finish_reason is "length" unless a stop string or a tool call ended the reply. - docs/api.md: stop on both backends. (cherry picked from commit 66339f9)
1 parent d448640 commit 88407d1

4 files changed

Lines changed: 392 additions & 12 deletions

File tree

‎src/tensorfold/cuda/reply_text.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import uuid
88
from typing import Any
99

10+
from tensorfold.server.stopping import StopPolicy
1011
from tensorfold.server.tools import parse_glm_tool_call_block
1112

1213
_CALL_OPEN, _CALL_CLOSE = "<tool_call>", "</tool_call>"
@@ -53,6 +54,27 @@ def final(self) -> str:
5354

5455

5556

57+
class StopStrings:
58+
"""A request's ``stop`` strings, decided token by token, so a reply cuts at the same token however its tokens arrive."""
59+
60+
def __init__(self, strings: tuple[str, ...], tok, skip: tuple[int, ...] = ()):
61+
self.strings, self.tok, self.skip = strings, tok, frozenset(skip)
62+
# a new match lies in the last (its UTF-8 length) tokens, plus eight as the Mac's ``StopPolicy`` keeps
63+
self.tail = max((len(s.encode()) for s in strings), default=0) + 8
64+
65+
def hit(self, tokens: list[int]) -> bool:
66+
"""Whether the text through the newest token holds a stop string (earlier tokens were checked already)."""
67+
68+
ids = [t for t in tokens[-self.tail:] if t not in self.skip]
69+
text = self.tok.decode(ids, skip_special_tokens=False)
70+
return any(stop in text for stop in self.strings)
71+
72+
def visible(self, text: str, *, partial: bool = False) -> str:
73+
"""The text before the first match; ``partial`` also holds back an end that may begin one (the Mac's rule)."""
74+
75+
return StopPolicy.visible(self, text, partial=partial)
76+
77+
5678
def hide_tool_calls(text: str, *, finished: bool) -> str:
5779
out: list[str] = []
5880
pos = 0

‎src/tensorfold/cuda/server.py‎

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,12 @@
2020
from tensorfold.server.messages import (_normalize_tool_call_arguments, late_system_role, normalize_messages,
2121
validate_modalities)
2222
from tensorfold.server.request_options import parse_numbers
23+
from tensorfold.server.stopping import stop_options
2324
from tensorfold.server.tool_policy import ToolCallPolicy
2425
from tensorfold.engine.call_gate import CallGate, call_format, generate_gated
2526
from tensorfold.server.tools import active_tool_specs, tool_choice_requires_call
2627

27-
from tensorfold.cuda.reply_text import StreamDecoder, hide_tool_calls, parse_tool_calls
28+
from tensorfold.cuda.reply_text import StopStrings, StreamDecoder, hide_tool_calls, parse_tool_calls
2829
from tensorfold.server.text import split_thinking
2930

3031

@@ -78,6 +79,8 @@ class PreparedRequest:
7879
tools: list[dict[str, Any]]
7980
thinking: bool
8081
sampling: Any # the engine's ``Sampling``, or None for greedy decoding
82+
ignore_eos: bool = False
83+
stop: tuple[str, ...] = ()
8184

8285

8386
def _native_context(model_dir: Path) -> int:
@@ -93,6 +96,8 @@ def _native_context(model_dir: Path) -> int:
9396
class App:
9497
"""Serve one engine with sampling and reply-length defaults for requests that omit them."""
9598

99+
reads_ignore_eos = False # True where the engine reads ``ignore_eos`` itself (``GlmApp``)
100+
96101
def __init__(self, engine, model_dir: Path, served: str, *, default_thinking: bool = False,
97102
sampling: dict[str, Any] | None = None, max_tokens: int = 4096,
98103
context_window: int | None = None):
@@ -166,6 +171,7 @@ def _prepare(self, body: dict[str, Any], chat: bool) -> PreparedRequest:
166171

167172
validate_modalities(body)
168173
ToolCallPolicy(body)
174+
ignore_eos, stop = stop_options(body)
169175
max_tokens = self._requested_tokens(body)
170176
try:
171177
tools = active_tool_specs(body.get("tools"), body.get("tool_choice"))
@@ -193,7 +199,7 @@ def _prepare(self, body: dict[str, Any], chat: bool) -> PreparedRequest:
193199
if not prompt:
194200
raise RequestError("rendered prompt is empty")
195201
# sampling is resolved here, so a malformed control is refused before a stream opens
196-
return PreparedRequest(prompt, max_tokens, tools, thinking, self.sampling_for(body, prompt))
202+
return PreparedRequest(prompt, max_tokens, tools, thinking, self.sampling_for(body, prompt), ignore_eos, stop)
197203

198204
def check(self, body: dict[str, Any], *, prepared: PreparedRequest | None = None) -> str | None:
199205
"""Why the request cannot run, or None; rendered before a stream's headers are sent."""
@@ -257,14 +263,19 @@ def run(self, body: dict[str, Any], chat: bool, emit: Callable[[dict[str, Any]],
257263
tools, thinking = prepared.tools, prepared.thinking
258264
policy = ToolCallPolicy(body)
259265
sampling = prepared.sampling
266+
# end tokens end the reply and stay out of its text, unless it asks ignore_eos of an engine that reads it
267+
ends = () if prepared.ignore_eos and self.reads_ignore_eos else tuple(self.engine.eos)
268+
stops = StopStrings(prepared.stop, self.tok, ends)
260269
out: list[int] = []
261270
sent = {"reasoning": 0, "content": 0}
262-
stopped = {"client": False}
271+
stopped = {"client": False, "stop": False}
263272
failed: list[Exception] = []
264-
stream = StreamDecoder(self.tok, tuple(self.engine.eos))
273+
stream = StreamDecoder(self.tok, ends)
265274

266275
def visible(finished: bool) -> tuple[str, str]:
267276
raw = stream.final() if finished else stream.text
277+
# stop strings match the generated text, reasoning included, before it is split (as on the Mac)
278+
raw = stops.visible(raw, partial=not finished) if stops.strings else raw
268279
if chat and thinking:
269280
reasoning, answer = split_thinking(raw, finished=finished)
270281
else:
@@ -276,10 +287,20 @@ def visible(finished: bool) -> tuple[str, str]:
276287

277288
def on_tokens(new: list[int]) -> bool:
278289
# True stops the engine after this round; engines that finish on both ranks keep calling and get True
279-
if stopped["client"] or failed:
290+
if stopped["client"] or stopped["stop"] or failed:
280291
return True
281292
try:
282-
out.extend(new)
293+
if stops.strings:
294+
kept = []
295+
for token in new: # token by token: the round's width cannot move the cut
296+
kept.append(token)
297+
out.append(token)
298+
if stops.hit(out):
299+
stopped["stop"] = True
300+
break
301+
new = kept
302+
else:
303+
out.extend(new)
283304
stream.add(new)
284305
reasoning, answer = visible(False)
285306
delta: dict[str, Any] = {}
@@ -296,7 +317,7 @@ def on_tokens(new: list[int]) -> bool:
296317
except Exception as exc: # noqa: BLE001 raised after generate returns, never into the engine
297318
failed.append(exc)
298319
return True
299-
return stopped["client"]
320+
return stopped["client"] or stopped["stop"]
300321

301322
draft = body.get("draft", True) is not False
302323
gate = self._call_gate(prompt, tools) if tools and tool_choice_requires_call(body.get("tool_choice")) else None
@@ -318,16 +339,14 @@ def generate(ids: list[int], count: int, feed: Callable[[list[int]], bool]) -> A
318339
final: dict[str, Any] = {}
319340
if len(reasoning) > sent["reasoning"]:
320341
final["reasoning_content"] = reasoning[sent["reasoning"]:]
321-
raw_answer = split_thinking(self.tok.decode([t for t in out if t not in self.engine.eos],
322-
skip_special_tokens=False), finished=True)[1] \
323-
if chat and thinking else self.tok.decode([t for t in out if t not in self.engine.eos],
324-
skip_special_tokens=False)
342+
text = stops.visible(self.tok.decode([t for t in out if t not in ends], skip_special_tokens=False))
343+
raw_answer = split_thinking(text, finished=True)[1] if chat and thinking else text
325344
content, calls = parse_tool_calls(raw_answer, tools, max_calls=policy.max_calls) if tools else (answer, None)
326345
content = policy.content(content) if tools else content
327346
tail = content[sent["content"]:] if content.startswith(answer[:sent["content"]]) else ""
328347
if tail:
329348
final["content"] = tail
330-
finish = "tool_calls" if calls else ("stop" if out and out[-1] in self.engine.eos else "length")
349+
finish = "tool_calls" if calls else ("stop" if stopped["stop"] or (out and out[-1] in ends) else "length")
331350
if body.get("return_token_ids"): # the reply's ids in the "tensorfold" block, for exactness checks
332351
stats = {**(stats or {}), "token_ids": [int(t) for t in out]}
333352
return {"final": final, "calls": calls, "finish": finish, "content": content, "reasoning": reasoning,

‎src/tensorfold/families/glm5_next/cuda/app.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ def render(self, messages, *, tools, enable_thinking, extra=None) -> str:
2323

2424

2525
class GlmApp(App):
26+
reads_ignore_eos = True # ``run`` hands it to the engine's request
27+
2628
def __init__(self, engine, model_dir, served: str, **kwargs: Any) -> None:
2729
super().__init__(engine, model_dir, served, **kwargs)
2830
self.template = ThinkingOffTemplate(self.template)

0 commit comments

Comments
 (0)