[Perf] Eliminate full-history reasoning scans for structured outputs (#55223)

Signed-off-by: sfeng33 <4florafeng@gmail.com>
Signed-off-by: Flora Feng <4florafeng@gmail.com>
Co-authored-by: Wentao Ye <44945378+yewentao256@users.noreply.github.com>
This commit is contained in:
Flora Feng
2026-09-08 14:07:16 -07:00
committed by GitHub
co-authored by Wentao Ye
parent 73f61d12aa
commit 29f46ac475
8 changed files with 475 additions and 42 deletions
+15
View File
@@ -219,6 +219,21 @@ class Parser:
"""
return self.is_reasoning_end(input_ids)
def find_reasoning_end_offset(self, token_ids: Sequence[int]) -> int | None:
"""
Locate the token that ends reasoning within one window of tokens.
Args:
token_ids: The tokens to examine.
Returns:
The offset within ``token_ids`` of the last reasoning token, or
``None`` when reasoning does not end in this window. Parsers that
cannot answer from a window alone always return ``None``; callers
fall back to :meth:`is_reasoning_end_streaming`.
"""
return None
@abstractmethod
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
"""
+7
View File
@@ -65,6 +65,9 @@ class ParserEngineReasoningAdapter(ReasoningParser):
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
return self._parser_engine.is_reasoning_end(list(input_ids))
def find_reasoning_end_offset(self, token_ids: Sequence[int]) -> int | None:
return self._parser_engine.find_reasoning_end_offset(token_ids)
def adjust_initial_state_from_prompt(self, prompt_token_ids: Sequence[int]) -> None:
self._parser_engine.adjust_initial_state_from_prompt(prompt_token_ids)
@@ -108,6 +111,10 @@ class ParserEngineReasoningAdapter(ReasoningParser):
def reasoning_end_str(self) -> str | None:
return self._parser_engine.reasoning_end_str
@property
def reasoning_end_token_ids(self) -> frozenset[int]:
return self._parser_engine.reasoning_end_token_ids
def adjust_request(
self,
request: ChatCompletionRequest | ResponsesRequest,
+39
View File
@@ -152,6 +152,9 @@ class ParserEngine(Parser):
for token in parser_engine_config.turn_boundary_tokens
if (token_id := vocab.get(token)) is not None
)
self._reasoning_end_token_ids: frozenset[int] = (
self._derive_reasoning_end_token_ids(parser_engine_config, vocab)
)
@property
def reasoning_start_str(self) -> str | None:
@@ -608,6 +611,42 @@ class ParserEngine(Parser):
# ── Reasoning state queries ───────────────────────────────────────
@staticmethod
def _derive_reasoning_end_token_ids(
config: ParserEngineConfig, vocab: dict[str, int]
) -> frozenset[int]:
end_terminals: dict[str, ParserState] = {}
for (state, terminal), transition in config.transitions.items():
if state != ParserState.REASONING:
continue
if EventType.REASONING_END in transition.events:
end_terminals.setdefault(terminal, transition.next_state)
elif transition.next_state != ParserState.REASONING:
return frozenset()
token_ids: set[int] = set()
for terminal, next_state in end_terminals.items():
text = config.token_id_terminals.get(terminal)
token_id = vocab.get(text) if text is not None else None
if token_id is not None:
token_ids.add(token_id)
elif next_state == ParserState.CONTENT:
return frozenset()
return frozenset(token_ids)
@property
def reasoning_end_token_ids(self) -> frozenset[int]:
return self._reasoning_end_token_ids
def find_reasoning_end_offset(self, token_ids: Sequence[int]) -> int | None:
end_ids = self._reasoning_end_token_ids
if not end_ids:
return None
for offset, token_id in enumerate(token_ids):
if token_id in end_ids:
return offset
return None
def is_reasoning_end(self, input_ids: list[int]) -> bool:
end_id = self._reasoning_end_token_id
start_id = self._reasoning_start_token_id
+71 -42
View File
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.parser.engine.adapters import ParserEngineReasoningAdapter
from vllm.reasoning import ReasoningParserManager
from vllm.tokenizers import cached_tokenizer_from_config
from vllm.utils.import_utils import LazyLoader
@@ -291,40 +292,43 @@ class StructuredOutputManager:
apply_bitmask = self.should_fill_bitmask(request)
reasoner = None if apply_bitmask else self._get_reasoner(request)
detect_reasoning_end = reasoner is not None
simulated_buf: list[int] | None = None
history_len = 0
state_advancements = 0
post_reasoning_end_in_window = False
req_tokens = scheduled_spec_decode_tokens.get(req_id, ())
# Locate the reasoning-end marker in the draft window once.
# Rejected-draft padding (-1) is trailing, so the window is
# cut there and the reasoner never sees a placeholder.
window_start = len(request.all_token_ids)
reasoning_end_index: int | None = None
if reasoner is not None and req_tokens:
window = req_tokens
if -1 in window:
window = window[: window.index(-1)]
reasoning_end_index = self._find_reasoning_end_index(
reasoner,
request.all_token_ids,
window_start,
window,
delta_appended=False,
)
for i, token in enumerate(req_tokens):
self._fill_bitmasks(((grammar, cumulative_index, apply_bitmask),))
advance_grammar = apply_bitmask
if token == -1:
apply_bitmask = False
advance_grammar = False
elif (
detect_reasoning_end
and reasoner is not None
and not apply_bitmask
):
if simulated_buf is None:
history = list(request.all_token_ids)
history_len = len(history)
simulated_buf = history + list(req_tokens)
simulated = simulated_buf[: history_len + i + 1]
if reasoner.is_reasoning_end_streaming(simulated, [token]):
# Reasoning ended mid-window. Constrain the rest
# of the window via bitmask. Skip grammar advance
# through the marker (it is reasoning content);
# try to advance through subsequent drafts so the
# next bitmask row reflects the post-advance state,
# but tolerate rejection since those drafts predate
# the bitmask and are not guaranteed valid.
apply_bitmask = True
advance_grammar = False
post_reasoning_end_in_window = True
elif not apply_bitmask and window_start + i == reasoning_end_index:
# Reasoning ended mid-window. Constrain the rest
# of the window via bitmask. Skip grammar advance
# through the marker (it is reasoning content);
# try to advance through subsequent drafts so the
# next bitmask row reflects the post-advance state,
# but tolerate rejection since those drafts predate
# the bitmask and are not guaranteed valid.
apply_bitmask = True
advance_grammar = False
post_reasoning_end_in_window = True
if advance_grammar and not grammar.is_terminated():
if post_reasoning_end_in_window:
accepted = bool(grammar.validate_tokens([token]))
@@ -431,21 +435,24 @@ class StructuredOutputManager:
# The tokens were already appended this step, so the step window
# starts exactly len(new_token_ids) from the end.
start = len(all_token_ids) - len(new_token_ids)
delta_ids: Iterable[int] = new_token_ids
delta_ids: Sequence[int] = new_token_ids
else:
# Draft-validation callers arrive here after update_from_output
# has already persisted any boundary found this step, so this
# window only needs to cover tokens not examined yet.
delta_from = request.num_computed_tokens - request.num_output_placeholders
start = (
delta_from
if delta_from >= 0
else max(len(all_token_ids) + delta_from, 0)
)
delta_ids = itertools.islice(all_token_ids, start, None)
if reasoner.is_reasoning_end_streaming(all_token_ids, delta_ids):
delta_ids = all_token_ids[start:]
end_index = self._find_reasoning_end_index(
reasoner, all_token_ids, start, delta_ids, delta_appended=True
)
if end_index is not None:
structured_req.reasoning_ended = True
# Record the boundary so the scheduler can exclude reasoning tokens.
end_index = self._find_reasoning_end_index(reasoner, all_token_ids, start)
structured_req.reasoning_end_token_index = end_index
return True
@@ -453,24 +460,46 @@ class StructuredOutputManager:
@staticmethod
def _find_reasoning_end_index(
reasoner: "ReasoningParser", all_token_ids: Sequence[int], start: int
) -> int:
"""Locates the last reasoning token within ``all_token_ids[start:]``.
reasoner: "ReasoningParser",
all_token_ids: Sequence[int],
start: int,
delta_ids: Sequence[int],
*,
delta_appended: bool,
) -> int | None:
"""Locates the token that ends reasoning within ``delta_ids``.
``delta_ids`` occupy positions ``start..``; ``delta_appended`` says
whether they are already in ``all_token_ids`` (accepted tokens) or
not (speculative drafts).
Legacy parsers are probed one token at a time. Accepted tokens get a
whole-delta check as well, and a marker seen only that way reports
the final token. Drafts skip it: some predicates are order-sensitive
over a multi-token window and would miss the marker.
Returns:
The absolute index of the token at which
``is_reasoning_end_streaming`` first fires. Falls back to the
final index when no single token triggers the detection (e.g.
a multi-token marker only recognized on the full delta), which
conservatively treats the whole step as reasoning content.
Absolute index of the last reasoning token, or ``None``.
"""
if (
isinstance(reasoner, ParserEngineReasoningAdapter)
and reasoner.reasoning_end_token_ids
):
offset = reasoner.find_reasoning_end_offset(delta_ids)
return None if offset is None else start + offset
if delta_appended and not reasoner.is_reasoning_end_streaming(
all_token_ids, delta_ids
):
return None
prefix = list(itertools.islice(all_token_ids, start))
for idx in range(start, len(all_token_ids)):
token = all_token_ids[idx]
for offset, token in enumerate(delta_ids):
prefix.append(token)
if reasoner.is_reasoning_end_streaming(prefix, [token]):
return idx
return len(all_token_ids) - 1
return start + offset
if delta_appended:
return len(all_token_ids) - 1
return None
def trim_reasoning_for_advance(
self, request: "Request", new_token_ids: list[int]