Skip to content

Commit add6f6d

Browse files
authored
[Refactor] detokenizer: Move the incremental decode state and step into incremental_detokenize.py (#47338)
1 parent da4ffac commit add6f6d

5 files changed

Lines changed: 205 additions & 130 deletions

File tree

‎python/sglang/srt/entrypoints/http_server.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -749,7 +749,7 @@ async def health_generate(request: Request) -> Response:
749749

750750
sampling_params = {"max_new_tokens": 1, "temperature": 0.0}
751751
# uuid keeps rids unique across tokenizer workers (a bare time.time() can
752-
# collide and crash the shared DetokenizerManager decode_status).
752+
# collide and crash the shared DetokenizerManager detokenize_state_table).
753753
rid = f"{HEALTH_CHECK_RID_PREFIX}_{uuid.uuid4().hex}"
754754

755755
if _global_state.tokenizer_manager.is_generation:

‎python/sglang/srt/environ.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,9 @@ class Envs:
712712
SGLANG_REQ_RUNNING_TIMEOUT = EnvFloat(-1) # in seconds
713713
# Non-streaming requests flush intermediate outputs every N decoded tokens.
714714
SGLANG_FORCE_STREAM_INTERVAL = EnvInt(50)
715+
# Most per-request states the detokenizer keeps; past it, the oldest is
716+
# evicted. See https://github.com/sgl-project/sglang/issues/2812
717+
SGLANG_DETOKENIZER_MAX_STATES = EnvInt(1 << 16)
715718

716719
# ===================================================================
717720
# Overlap scheduler and pipeline parallelism

‎python/sglang/srt/managers/detokenizer_manager.py‎

Lines changed: 35 additions & 128 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,9 @@
1313
# ==============================================================================
1414
"""DetokenizerManager is a process that detokenizes the token ids."""
1515

16-
import dataclasses
1716
import logging
18-
import os
1917
import signal
20-
from collections import OrderedDict, defaultdict
18+
from collections import defaultdict
2119
from typing import Dict, List, Optional, Tuple, Union
2220

2321
import psutil
@@ -32,6 +30,10 @@
3230
)
3331
from sglang.srt.constants import HEALTH_CHECK_RID_PREFIX
3432
from sglang.srt.environ import envs
33+
from sglang.srt.managers.incremental_detokenize import (
34+
DETOKENIZER_MAX_STATES,
35+
DetokenizeStateTable,
36+
)
3537
from sglang.srt.managers.io_struct import (
3638
BatchEmbeddingOutput,
3739
BatchStrOutput,
@@ -58,45 +60,10 @@
5860
from sglang.srt.utils.network import get_zmq_socket
5961
from sglang.srt.utils.patch_tokenizer import decode_without_hf_kwargs
6062
from sglang.srt.utils.watchdog import Watchdog
61-
from sglang.utils import (
62-
TypeBasedDispatcher,
63-
find_printable_text,
64-
get_exception_traceback,
65-
)
63+
from sglang.utils import TypeBasedDispatcher, get_exception_traceback
6664

6765
logger = logging.getLogger(__name__)
6866

69-
# Maximum number of request states that detokenizer can hold. When exceeded,
70-
# oldest request states will be evicted. Default: 65536 (1<<16).
71-
# For more details, see: https://github.com/sgl-project/sglang/issues/2812
72-
# Use power of 2 values for better memory allocation.
73-
DETOKENIZER_MAX_STATES = int(os.environ.get("SGLANG_DETOKENIZER_MAX_STATES", 1 << 16))
74-
75-
76-
@dataclasses.dataclass
77-
class DecodeStatus:
78-
"""Store the status of incremental decoding."""
79-
80-
decode_ids: List[int]
81-
surr_offset: int
82-
read_offset: int
83-
# Offset that's sent to tokenizer for incremental update.
84-
sent_offset: int = 0
85-
decoded_text: str = ""
86-
decoded_text_len: int = dataclasses.field(default=0, init=False)
87-
decoded_text_chunks: List[str] = dataclasses.field(default_factory=list)
88-
89-
def append_decoded_text(self, text: str):
90-
if text:
91-
self.decoded_text_chunks.append(text)
92-
self.decoded_text_len += len(text)
93-
94-
def get_decoded_text(self) -> str:
95-
if self.decoded_text_chunks:
96-
self.decoded_text += "".join(self.decoded_text_chunks)
97-
self.decoded_text_chunks.clear()
98-
return self.decoded_text
99-
10067

10168
class DetokenizerManager(MultiHttpWorkerDetokenizerMixin):
10269
"""DetokenizerManager is a process that detokenizes the token ids."""
@@ -149,7 +116,9 @@ def init_tokenizer(self, server_args: ServerArgs):
149116
self.vocab_size = getattr(self.tokenizer, "vocab_size", None)
150117

151118
def init_running_status(self, server_args: ServerArgs):
152-
self.decode_status = LimitedCapacityDict(capacity=DETOKENIZER_MAX_STATES)
119+
self.detokenize_state_table = DetokenizeStateTable(
120+
capacity=DETOKENIZER_MAX_STATES
121+
)
153122
self.disable_tokenizer_batch_decode = (
154123
get_serving().disable_tokenizer_batch_decode
155124
)
@@ -226,20 +195,6 @@ def handle_batch_embedding_out(self, recv_obj: BatchEmbeddingOutput):
226195
# If it is embedding model, no detokenization is needed.
227196
return recv_obj
228197

229-
@staticmethod
230-
def _clamp_decode_ids(ids: List[int], vocab_size: Optional[int]) -> List[int]:
231-
"""Map out-of-range token ids to 0 so the tokenizer can decode them.
232-
233-
Multimodal placeholder ids (e.g. Inkling's negative -101/-102, or radix-cache
234-
pad-value hashes) are not real vocab tokens; tiktoken-style backends raise
235-
OverflowError on negative / out-of-range ids. These only appear in the
236-
surrogate-context prefix (before read_offset) and carry no text, and the clamp
237-
is applied identically to surr_ids and read_ids, so the incremental
238-
(read-minus-surr) output text is unchanged.
239-
"""
240-
hi = vocab_size if vocab_size else None
241-
return [t if (0 <= t and (hi is None or t < hi)) else 0 for t in ids]
242-
243198
def _grouped_batch_decode(
244199
self,
245200
ids_list: List[List[int]],
@@ -308,33 +263,22 @@ def _decode_batch_token_id_output(self, recv_obj: BatchTokenIDOutput):
308263
bs = len(recv_obj.rids)
309264
vocab_size = self.vocab_size
310265

311-
# Initialize decode status
266+
# Start or extend each row's state and collect its decode ids.
312267
read_ids, surr_ids = [], []
313268
for i in range(bs):
314-
rid = recv_obj.rids[i]
315-
if rid not in self.decode_status:
316-
s = DecodeStatus(
317-
decode_ids=self._clamp_decode_ids(
318-
recv_obj.decode_ids[i], vocab_size
319-
),
320-
surr_offset=0,
321-
read_offset=recv_obj.read_offsets[i],
322-
)
323-
self.decode_status[rid] = s
324-
else:
325-
s = self.decode_status[rid]
326-
s.decode_ids.extend(
327-
self._clamp_decode_ids(recv_obj.decode_ids[i], vocab_size)
328-
)
329-
330-
read_ids.append(
331-
self.trim_matched_stop(
332-
s.decode_ids[s.surr_offset :],
333-
recv_obj.finished_reasons[i],
334-
recv_obj.no_stop_trim[i],
335-
)
269+
s = self.detokenize_state_table.start_or_extend(
270+
rid=recv_obj.rids[i],
271+
decode_ids=recv_obj.decode_ids[i],
272+
read_offset=recv_obj.read_offsets[i],
273+
vocab_size=vocab_size,
274+
)
275+
row_read_ids, row_surr_ids = s.decode_inputs(
276+
finished_reason=recv_obj.finished_reasons[i],
277+
no_stop_trim=recv_obj.no_stop_trim[i],
278+
trim_matched_stop=self.trim_matched_stop,
336279
)
337-
surr_ids.append(s.decode_ids[s.surr_offset : s.read_offset])
280+
read_ids.append(row_read_ids)
281+
surr_ids.append(row_surr_ids)
338282

339283
# Decode token ids to strings
340284
if not self.disable_tokenizer_batch_decode:
@@ -375,9 +319,8 @@ def _decode_batch_token_id_output(self, recv_obj: BatchTokenIDOutput):
375319
output_strs = []
376320
for i in range(bs):
377321
rid = recv_obj.rids[i]
378-
try:
379-
s = self.decode_status[rid]
380-
except KeyError:
322+
s = self.detokenize_state_table.get(rid)
323+
if s is None:
381324
raise RuntimeError(
382325
f"Decode status not found for request {rid}. "
383326
"It may be due to the request being evicted from the decode status due to memory pressure. "
@@ -386,41 +329,18 @@ def _decode_batch_token_id_output(self, recv_obj: BatchTokenIDOutput):
386329
f"The current value is {DETOKENIZER_MAX_STATES}. "
387330
"For more details, see: https://github.com/sgl-project/sglang/issues/2812"
388331
)
389-
new_text = read_texts[i][len(surr_texts[i]) :]
390-
if recv_obj.finished_reasons[i] is None:
391-
# Streaming. Invariant: sent_offset >= decoded_text_len. The
392-
# gap (`pending`) is "printable but uncommitted" text emitted
393-
# in a prior "�" recovery step; we skip it from this step's
394-
# emission so we don't double-send.
395-
pending = s.sent_offset - s.decoded_text_len
396-
if new_text and not new_text.endswith("�"):
397-
# Clean text: commit to decoded_text and advance offsets.
398-
s.append_decoded_text(new_text)
399-
s.surr_offset = s.read_offset
400-
s.read_offset = len(s.decode_ids)
401-
s.sent_offset = s.decoded_text_len
402-
output_strs.append(new_text[pending:] if pending else new_text)
403-
else:
404-
# Incomplete UTF-8: emit the printable prefix only; do not
405-
# commit (token offsets stay so the next iteration retries
406-
# with more tokens).
407-
printable = find_printable_text(new_text)
408-
s.sent_offset = s.decoded_text_len + len(printable)
409-
output_strs.append(printable[pending:] if pending else printable)
410-
continue
411-
412-
if rid in self.decode_status:
413-
del self.decode_status[rid]
414-
415-
# Finished: materialize once, trim the matched stop, emit the tail.
416-
output_str = self.trim_matched_stop(
417-
s.get_decoded_text() + new_text,
418-
recv_obj.finished_reasons[i],
419-
recv_obj.no_stop_trim[i],
332+
finished_reason = recv_obj.finished_reasons[i]
333+
if finished_reason is not None:
334+
self.detokenize_state_table.release(rid)
335+
output_strs.append(
336+
s.step(
337+
read_text=read_texts[i],
338+
surr_text=surr_texts[i],
339+
finished_reason=finished_reason,
340+
no_stop_trim=recv_obj.no_stop_trim[i],
341+
trim_matched_stop=self.trim_matched_stop,
342+
)
420343
)
421-
incremental_output = output_str[s.sent_offset :]
422-
s.sent_offset = len(output_str)
423-
output_strs.append(incremental_output)
424344

425345
return output_strs
426346

@@ -518,19 +438,6 @@ def is_health_check_request(rid: Optional[str]) -> bool:
518438
return isinstance(rid, str) and rid.startswith(HEALTH_CHECK_RID_PREFIX)
519439

520440

521-
class LimitedCapacityDict(OrderedDict):
522-
def __init__(self, capacity: int, *args, **kwargs):
523-
super().__init__(*args, **kwargs)
524-
self.capacity = capacity
525-
526-
def __setitem__(self, key, value):
527-
if len(self) >= self.capacity:
528-
# Remove the oldest element (first item in the dict)
529-
self.popitem(last=False)
530-
# Set the new item
531-
super().__setitem__(key, value)
532-
533-
534441
def run_detokenizer_process(
535442
server_args: ServerArgs,
536443
port_args: PortArgs,

0 commit comments

Comments
 (0)