[Bugfix] Gemma4 parser: classify channel-less output consistently in streaming and non-streaming (#48262)

Signed-off-by: Adhithya Balakrishnan <adhithya.b2004@gmail.com>
Co-authored-by: Ben Browning <56071+bbrowning@users.noreply.github.com>
This commit is contained in:
adhi29
2026-07-14 09:30:16 -04:00
committed by GitHub
co-authored by Ben Browning
parent 32aef44388
commit af453e5647
2 changed files with 123 additions and 24 deletions
+37 -9
View File
@@ -479,19 +479,47 @@ class Gemma4Parser(ParserEngine):
return True
return True
def _prompt_ends_in_open_reasoning(self, prompt_token_ids: Sequence[int]) -> bool:
"""Whether the prompt tail is inside an open ``<|channel>`` block.
Scans backwards: a ``<|channel>`` start token seen before any
closing or turn-boundary token means the block is still open.
"""
start_id = self._reasoning_start_token_id
if start_id is None:
return False
boundary_ids = {
tid
for tid in (
self._reasoning_end_token_id,
self._tool_call_token_id,
self._new_turn_token_id,
self._tool_response_token_id,
)
if tid is not None
}
for tid in reversed(prompt_token_ids):
if tid == start_id:
return True
if tid in boundary_ids:
return False
return False
def adjust_initial_state_from_prompt(self, prompt_token_ids: Sequence[int]) -> None:
"""Pre-initialise the engine to ``REASONING`` when the prompt does
not already end with reasoning concluded.
"""Pre-initialise the engine to ``REASONING`` when the prompt ends
inside an open ``<|channel>`` block.
This covers the post-tool-response continuation case where the chat
template leaves the prompt ending inside an open ``<|channel>``
block (issue #45834). It is also safe in the common new-turn case
where the model itself emits ``<|channel>`` first: the no-op
``(REASONING, THINK_START)`` transition swallows it, and the
``thought\n`` prefix in the first reasoning chunk is stripped by
``_events_to_delta`` as it already is in the default flow.
template leaves the prompt ending with ``<|channel>thought\n``
(issue #45834). A prompt that merely starts a new model turn must
not pre-initialise reasoning: the model may answer directly without
emitting any channel markers, and the non-streaming path classifies
such output as content (issue #48217). When the model does open its
own ``<|channel>``, the ``(CONTENT, THINK_START)`` transition
handles it, and the ``thought\n`` prefix in the first reasoning
chunk is stripped by ``_events_to_delta`` as in the default flow.
"""
if self.is_reasoning_end(list(prompt_token_ids)):
if not self._prompt_ends_in_open_reasoning(prompt_token_ids):
return
self._engine.reset(initial_state=ParserState.REASONING)
# Prevent a later default ``initialize_streaming()`` (e.g. from