Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
127a14a
feat: cherry-pick tokenize/detokenize endpoints and token ID support …
Aphoh Apr 13, 2026
49a2140
feat(sglang): support return_tokens_as_token_ids for token-based logp…
Aphoh Apr 13, 2026
5664bf5
feat: wire up return_tokens_as_token_ids for /v1/completions endpoint
Aphoh Apr 14, 2026
dba0792
Merge origin/main into warnold/sglang-tokens-inout
Aphoh Apr 16, 2026
1fe3151
style: cargo fmt
Aphoh Apr 16, 2026
e8286f9
fix(clippy): collapse nested if-let in local_file_dir
Aphoh Apr 16, 2026
d4f7121
fix(completions): honor return_tokens_as_token_ids in logprob tokens
Aphoh Apr 16, 2026
c62b803
fix(mypy): annotate token_str as str | None in _extract_logprobs
Aphoh Apr 17, 2026
baabe55
feat(sglang): reject logprobs >= 1 unless DYN_SGL_ALLOW_TOP_LOGPROBS set
Aphoh Apr 17, 2026
00553a1
Merge origin/main into warnold/sglang-tokens-inout
Aphoh Apr 17, 2026
7a18d28
Merge origin/main into warnold/sglang-tokens-inout
Aphoh Apr 20, 2026
d013b5c
fix(completions): enable logprobs when logprobs=0 (chosen-token only)
Aphoh Apr 21, 2026
5fc8952
feat(completions): propagate SGLang stop_reason to /v1/completions re…
Aphoh May 1, 2026
ab3eff8
Merge origin/main into warnold/sglang-tokens-inout
Aphoh May 1, 2026
31f7bcb
Merge remote-tracking branch 'origin/main' into warnold/sglang-tokens…
Aphoh May 1, 2026
316b08b
fix(tests): add return_tokens_as_token_ids: None to test fixtures
Aphoh May 1, 2026
6231dab
fix(sglang): trim token logprob branch scope
Aphoh May 2, 2026
f32b200
fix(openai): format top logprobs as token ids
Aphoh May 5, 2026
9f8489f
Merge remote-tracking branch 'origin/main' into warnold/sglang-tokens…
Aphoh May 5, 2026
fd3c9e9
fix(openai): return stop_reason via nvext
Aphoh May 6, 2026
2dc3215
chore(openai): drop vllm logprob changes
Aphoh May 7, 2026
b9d9fa3
Merge remote-tracking branch 'origin/main' into warnold/sglang-tokens…
Aphoh May 7, 2026
0397bef
docs(sglang): link top logprobs upstream fix
Aphoh May 7, 2026
ce704c1
feat(openai): accept token id stop arrays
Aphoh May 7, 2026
4c97a5c
fix(sglang): keep stop reasons in nvext
Aphoh May 7, 2026
eda50cb
test(openai): encode stop input contract
Aphoh May 7, 2026
9de617f
Merge remote-tracking branch 'origin/main' into warnold/sglang-tokens…
Aphoh May 7, 2026
3d5b5f8
fix(openai): update echo choice calls
Aphoh May 7, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions components/src/dynamo/frontend/sglang_prepost.py
Original file line number Diff line number Diff line change
Expand Up @@ -660,24 +660,31 @@ def process_output(self, engine_response: dict[str, Any]) -> dict[str, Any] | No
raw_ids = engine_response.get("token_ids")
token_ids = raw_ids if isinstance(raw_ids, list) else list(raw_ids or [])
finish_reason = engine_response.get("finish_reason")
stop_reason = engine_response.get("stop_reason")

delta_text = self._incremental_decode(token_ids) if token_ids else ""

if self._fast_plain_text:
if delta_text:
return {
choice = {
"index": 0,
"delta": {"role": "assistant", "content": delta_text},
"finish_reason": finish_reason,
"logprobs": None,
}
if stop_reason is not None:
choice["stop_reason"] = stop_reason
return choice
elif finish_reason:
return {
choice = {
"index": 0,
"delta": {},
"finish_reason": finish_reason,
"logprobs": None,
}
if stop_reason is not None:
choice["stop_reason"] = stop_reason
return choice
return None

# -- Reasoning parsing --
Expand Down Expand Up @@ -889,11 +896,14 @@ def process_output(self, engine_response: dict[str, Any]) -> dict[str, Any] | No
effective_finish = "tool_calls"

if has_content or effective_finish:
return {
choice = {
"index": 0,
"delta": delta if has_content else {},
"finish_reason": effective_finish,
"logprobs": None,
}
if stop_reason is not None:
choice["stop_reason"] = stop_reason
return choice

return None
1 change: 1 addition & 0 deletions components/src/dynamo/frontend/sglang_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ def _build_dynamo_preproc(
# (e.g. <|tool_call|>) to detect calls. Mirrors the
# post-processor's _skip_special_tokens logic.
"skip_special_tokens": tool_call_parser is None,
"return_tokens_as_token_ids": request.get("return_tokens_as_token_ids"),
},
"eos_token_ids": [eos_token_id] if eos_token_id is not None else [],
"annotations": [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1465,6 +1465,19 @@ def test_finish_reason_only(self, tokenizer):
assert choice is not None
assert choice["finish_reason"] == "stop"

def test_stop_reason_passthrough(self, tokenizer):
"""Backend stop_reason is included on the emitted choice."""
post = SglangStreamingPostProcessor(
tokenizer=tokenizer, tool_call_parser=None, reasoning_parser=None
)

choice = post.process_output(
{"token_ids": [], "finish_reason": "stop", "stop_reason": "END"}
)

assert choice is not None
assert choice["stop_reason"] == "END"

def test_lookback_trimming(self, tokenizer):
"""Verify _all_token_ids doesn't grow unbounded."""
post = SglangStreamingPostProcessor(
Expand Down
6 changes: 6 additions & 0 deletions components/src/dynamo/sglang/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,12 @@ absolute sequence position where logprob computation starts: `-1` (default) = ou
only (`len(prompt) - 1`), `0` = from prompt start. We set it to 0 when `prompt_logprobs`
is requested.

**Top-logprobs gate**: `logprobs >= 1` (or `prompt_logprobs >= 1`) raises `ValueError`
by default. SGLang's tokenizer manager detokenizes top-k tokens per-position serially,
causing severe latency degradation (O(N) per generated token). Callers must use
`logprobs=0` for chosen-token-only logprobs. Set `DYN_SGL_ALLOW_TOP_LOGPROBS=1` to
override once upstream batches `detokenize_top_logprobs_tokens`.

**Streaming behavior** (`_extract_logprobs`):

Dynamo forces `stream_output=True` (args.py:374), making `output_ids` disjoint per chunk.
Expand Down
147 changes: 107 additions & 40 deletions components/src/dynamo/sglang/request_handlers/llm/decode_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import asyncio
import logging
import os
import time
from typing import Any, AsyncGenerator, Dict, Optional

Expand All @@ -18,6 +19,25 @@
from dynamo.sglang.publisher import DynamoSglangPublisher
from dynamo.sglang.request_handlers.handler_base import BaseWorkerHandler

# Escape hatch: set to "1" (or any truthy value) to allow top_logprobs_num >= 1.
# Default-off because SGLang's tokenizer manager detokenizes top-k tokens
# per-position serially (O(N) per generated token), causing severe latency
# degradation. Flip once upstream batches detokenize_top_logprobs_tokens.
_ALLOW_TOP_LOGPROBS_ENV = "DYN_SGL_ALLOW_TOP_LOGPROBS"

_TOP_LOGPROBS_UNSUPPORTED_MSG = (
"Dynamo's SGLang backend does not currently support logprobs >= 1 due to "
"an O(N) per-position detokenization in the upstream sglang tokenizer "
"manager. Use logprobs=0 for chosen-token logprobs, or set "
"DYN_SGL_ALLOW_TOP_LOGPROBS=1 to override at your own risk. "
"Track the upstream fix at https://github.com/sgl-project/sglang/issues/."
)
Comment thread
Aphoh marked this conversation as resolved.
Resolved


def _top_logprobs_allowed() -> bool:
"""Return True if the DYN_SGL_ALLOW_TOP_LOGPROBS escape hatch is enabled."""
return os.environ.get(_ALLOW_TOP_LOGPROBS_ENV, "").lower() not in ("", "0", "false")


def _extract_media_urls(mm_data: Dict[str, Any], media_key: str) -> list[str] | None:
"""Normalize multimodal URL items from the frontend wire format."""
Expand All @@ -40,6 +60,25 @@ def _extract_media_urls(mm_data: Dict[str, Any], media_key: str) -> list[str] |
return urls or None


def _extract_sglang_stop_reason(finish_reason: Dict[str, Any] | None) -> Any | None:
"""Extract SGLang's matched stop value for Dynamo's stop_reason field."""

if not finish_reason:
return None

matched = finish_reason.get("matched")
if isinstance(matched, bool):
return None
if isinstance(matched, (str, int)):
return matched
if isinstance(matched, list) and all(
isinstance(item, int) and not isinstance(item, bool) for item in matched
):
return matched

return None


class DecodeWorkerHandler(BaseWorkerHandler):
"""Handler for decode workers in both aggregated and disaggregated serving modes."""

Expand Down Expand Up @@ -181,54 +220,58 @@ def _build_logprob_kwargs(request: Dict[str, Any]) -> Dict[str, Any]:
if not output_options:
return kwargs

logprobs_value = output_options.get("logprobs")
if logprobs_value is not None:
allow_top = _top_logprobs_allowed()

def _parse(name: str, value: Any) -> Optional[int]:
try:
parsed = int(logprobs_value)
if parsed < 0:
logging.warning(
f"Invalid logprobs value: {logprobs_value} "
"(must be non-negative), ignoring"
)
else:
kwargs["return_logprob"] = True
kwargs["top_logprobs_num"] = parsed
parsed = int(value)
except (ValueError, TypeError):
logging.warning(
f"Invalid logprobs value: {logprobs_value} "
"(must be integer), ignoring"
f"Invalid {name} value: {value} (must be integer), ignoring"
)
return None
if parsed < 0:
logging.warning(
f"Invalid {name} value: {value} (must be non-negative), ignoring"
)
return None
if parsed >= 1 and not allow_top:
raise ValueError(_TOP_LOGPROBS_UNSUPPORTED_MSG)
return parsed

logprobs_value = output_options.get("logprobs")
if logprobs_value is not None:
parsed = _parse("logprobs", logprobs_value)
if parsed is not None:
kwargs["return_logprob"] = True
kwargs["top_logprobs_num"] = parsed

prompt_logprobs_value = output_options.get("prompt_logprobs")
if prompt_logprobs_value is not None:
try:
parsed = int(prompt_logprobs_value)
if parsed < 0:
logging.warning(
f"Invalid prompt_logprobs value: {prompt_logprobs_value} "
"(must be non-negative), ignoring"
)
else:
kwargs["return_logprob"] = True
# SGLang has a single top_logprobs_num for both prompt
# and output tokens, so take the max of the two.
kwargs["top_logprobs_num"] = max(
kwargs.get("top_logprobs_num", 0), parsed
)
# logprob_start_len=0 computes from prompt start;
# omitting it (or -1) computes output tokens only.
kwargs["logprob_start_len"] = 0
except (ValueError, TypeError):
logging.warning(
f"Invalid prompt_logprobs value: {prompt_logprobs_value} "
"(must be integer), ignoring"
parsed = _parse("prompt_logprobs", prompt_logprobs_value)
if parsed is not None:
kwargs["return_logprob"] = True
# SGLang has a single top_logprobs_num for both prompt
# and output tokens, so take the max of the two.
kwargs["top_logprobs_num"] = max(
kwargs.get("top_logprobs_num", 0), parsed
)
# logprob_start_len=0 computes from prompt start;
# omitting it (or -1) computes output tokens only.
kwargs["logprob_start_len"] = 0

# Belt-and-suspenders: if return_logprob was requested and the gate is
# not open, pin top_logprobs_num=0 so no future code path can flip it on.
if kwargs.get("return_logprob") and not allow_top:
kwargs["top_logprobs_num"] = 0

return kwargs

@staticmethod
def _extract_logprobs(
meta_info: Dict[str, Any], num_output_logprobs_so_far: int
meta_info: Dict[str, Any],
num_output_logprobs_so_far: int,
return_tokens_as_token_ids: bool = False,
) -> tuple:
"""Extract logprobs from SGLang meta_info for new tokens.

Expand Down Expand Up @@ -272,11 +315,17 @@ def _extract_logprobs(
continue
position_list = []
for rank_idx, entry in enumerate(position_entries):
tok_id = entry[1]
token_str = (
f"token_id:{tok_id}"
if return_tokens_as_token_ids
else entry[2]
)
position_list.append(
{
"rank": rank_idx + 1,
"token_id": entry[1],
"token": entry[2],
"token_id": tok_id,
"token": token_str,
"logprob": float(entry[0]),
}
)
Expand Down Expand Up @@ -307,6 +356,11 @@ async def generate(
priority = (request.get("routing") or {}).get("priority")
logprob_kwargs = self._build_logprob_kwargs(request)

output_options = request.get("output_options", {})
return_tokens_as_token_ids = bool(
output_options.get("return_tokens_as_token_ids")
)

lora_path = self._resolve_lora(request)
if lora_path:
logging.debug(f"Request {context.id()} will use LoRA adapter: {lora_path}")
Expand Down Expand Up @@ -351,7 +405,9 @@ async def generate(
)

if not self.use_sglang_tokenizer:
async for out in self._process_token_stream(decode, context):
async for out in self._process_token_stream(
decode, context, return_tokens_as_token_ids
):
yield out
else:
async for out in self._process_text_stream(decode, context):
Expand Down Expand Up @@ -385,7 +441,9 @@ async def generate(
**self._priority_kwargs(priority),
)
if not self.use_sglang_tokenizer:
async for out in self._process_token_stream(agg, context):
async for out in self._process_token_stream(
agg, context, return_tokens_as_token_ids
):
yield out
else:
async for out in self._process_text_stream(agg, context):
Expand All @@ -395,6 +453,7 @@ async def _process_token_stream(
self,
stream_source: AsyncGenerator[Dict[str, Any], None],
context: Context,
return_tokens_as_token_ids: bool = False,
) -> AsyncGenerator[Dict[str, Any], None]:
"""Process token-based stream output.

Expand Down Expand Up @@ -438,6 +497,9 @@ async def _process_token_stream(
out["finish_reason"] = normalize_finish_reason(
finish_reason["type"]
)
stop_reason = _extract_sglang_stop_reason(finish_reason)
if stop_reason is not None:
out["stop_reason"] = stop_reason

# With stream_output=True, output_ids contains only new tokens (disjoint)
output_ids = res.get("output_ids", [])
Expand All @@ -457,7 +519,9 @@ async def _process_token_stream(
top_logprobs,
next_logprobs_total,
) = self._extract_logprobs(
res["meta_info"], output_logprobs_per_choice.get(output_idx, 0)
res["meta_info"],
output_logprobs_per_choice.get(output_idx, 0),
return_tokens_as_token_ids=return_tokens_as_token_ids,
)
output_logprobs_per_choice[output_idx] = next_logprobs_total
if log_probs is not None:
Expand Down Expand Up @@ -544,6 +608,9 @@ async def _process_text_stream(
"delta": {"role": "assistant", "content": delta},
"finish_reason": finish_reason_type,
}
stop_reason = _extract_sglang_stop_reason(finish_reason)
if stop_reason is not None:
choice_data["stop_reason"] = stop_reason

response = {
"id": res["meta_info"]["id"],
Expand Down
Loading
Loading