vllm.parser.engine.token_id_scanner
¶
Scan delta token IDs for special tokens and split the stream into pre-lexed terminals and plain text chunks.
Classes:
-
TokenIDScanner–Maps special token IDs in the delta to terminals.
TokenIDScanner
¶
Maps special token IDs in the delta to terminals.
Before text-based lexing happens, the scanner checks each token ID
in the delta against a mapping of {token_id: terminal_name}.
Matched tokens are emitted as PreLexedTerminal items;
everything else is grouped into TextChunk items for the
incremental lexer to process.
When a terminal's text is not yet in delta_text (held back by
the detokenizer), the terminal is deferred until the text arrives
in a subsequent delta.
Methods:
-
reset–Clear mutable state for reuse. Preserves the token text cache.
_join_decoded_text(results)
¶
Join TextChunk and PreLexedTerminal text into one string.
_rebuild_from_anchors(delta_text, results)
¶
Rebuild results from delta_text using terminals as anchors.
When context-dependent decoding creates a mismatch between individually-decoded tokens and delta_text, use PreLexedTerminals as split points and reallocate text from delta_text. If a terminal's text is not found in delta_text, it is deferred to the next scan() call.
Anchors are resolved right-to-left with rfind so that each
anchor binds to the rightmost available occurrence of its
text. This prevents earlier literal lookalikes (e.g. a user
mentioning <tool_call> in prose) from stealing the position
of a real special-token anchor that appears later.
If the same anchor text appears multiple times as real special tokens (not prose), the rightmost-first binding could misalign. In practice this doesn't happen: each special token ID maps to a distinct PreLexedTerminal, and duplicates in prose are resolved by the token-ID filtering layer above.
_recover_holdback_text(delta_text, results)
¶
Recover detokenizer hold-back text not in delta_token_ids.
The detokenizer may flush previously held-back text in
delta_text that has no corresponding token ID in
delta_token_ids. This hold-back text always appears as a
prefix of delta_text.
_resolve_deferred(delta_text, current_token_count=0)
¶
Resolve deferred terminals against new delta_text.
When a previous scan() deferred a terminal (its text hadn't
arrived yet), the next delta's text should contain that terminal's
text. Split delta_text at the terminal boundary: text before
belongs to the previous parser state, the terminal triggers the
state transition, and text after belongs to the new state.
Returns (prefix_items, remaining_text) where prefix_items
are the resolved deferred terminals (with any preceding text)
and remaining_text is the unconsumed portion of delta_text that
should be scanned with the current delta's token IDs.
reset()
¶
Clear mutable state for reuse. Preserves the token text cache.