Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
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
7 changes: 6 additions & 1 deletion components/src/dynamo/sglang/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ support the current version plus 1 version back (N and N-1). The pattern:
enough surface area to cover what Dynamo actually calls.
4. Each fallback branch in `_compat.py` MUST have a comment noting which SGLang
version it supports and when it can be removed, e.g.:
`# Fallback for sglang <= 0.5.12. Remove when min supported version is 0.5.14+`
`# Fallback for sglang <= 0.5.16. Remove when min supported version is 0.5.18+`
5. When a new SGLang version is released and the old N-1 falls outside the support
window, delete the corresponding fallback branches and polyfills from `_compat.py`.
If `_compat.py` becomes trivial re-exports, inline the imports and delete the file.
Expand Down Expand Up @@ -70,6 +70,11 @@ Worker dispatch (main.py:60-132):
have `max_running_requests`, `dllm_algorithm_config`, or other LLM-specific fields.
Use `getattr()` when accessing fields that may not exist on the stub.

SGLang 0.5.17 makes a resolved `ServerArgs` unconditionally read-only. Apply Dynamo's
post-resolution startup overrides through `_compat.override_server_args()`; control-plane
updates after engine creation should use the tokenizer manager's update API instead of
assigning fields on `server_args`.

**DynamoConfig** combines `DynamoRuntimeConfig` (common flags like `--namespace`,
`--output-modalities`, `--media-output-fs-url`) with `DynamoSGLangConfig` (sglang-specific
flags like `--enable-multimodal`, `--dedicated-mm-encoder`, `--embedding-worker`).
Expand Down
24 changes: 23 additions & 1 deletion components/src/dynamo/sglang/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def ensure_sglang_top_level_exports() -> None:
def ensure_sglang_tensor_image_size() -> None:
"""Allow SGLang's image-token resolver to handle decoded image tensors.

SGLang 0.5.13 through 0.5.16 assume every decoded image exposes the PIL
SGLang 0.5.13 through 0.5.17 assume every decoded image exposes the PIL
``height``/``width`` attributes. Its CUDA JPEG decoder instead returns a
CHW tensor, causing multimodal requests to fall back to retokenization.

Expand Down Expand Up @@ -106,6 +106,27 @@ def resolve_image_token_counts(self: Any, images: list[Any]) -> list[int]:
BaseMultimodalProcessor.resolve_image_token_counts = resolve_image_token_counts


def override_server_args(server_args: Any, source: str, **fields: Any) -> None:
"""Apply a post-resolution SGLang configuration update.

SGLang 0.5.17 makes ``ServerArgs`` unconditionally read-only after
resolution. Both supported CUDA releases expose ``ServerArgs.override`` as
the audited mutation API, so Dynamo must use it instead of assigning fields.
The separately pinned XPU image still uses SGLang 0.5.11, which predates
that API; preserve its legacy assignment behavior until its engine pin is
upgraded.
"""
override = getattr(server_args, "override", None)
if callable(override):
override(source, **fields)
return

# XPU compatibility for SGLang 0.5.11. Remove when the XPU SGLang pin is
# upgraded to 0.5.16+.
for name, value in fields.items():
setattr(server_args, name, value)


@lru_cache(maxsize=32)
def _get_async_generate_supported_kwarg_names(
async_generate: Any,
Expand Down Expand Up @@ -177,5 +198,6 @@ def require_reasoning_kwargs(engine: Any, request: Mapping[str, Any]) -> dict[st
"ensure_sglang_tensor_image_size",
"ensure_sglang_top_level_exports",
"filter_supported_async_generate_kwargs",
"override_server_args",
"require_reasoning_kwargs",
]
13 changes: 11 additions & 2 deletions components/src/dynamo/sglang/init_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from dynamo.common.utils.endpoint_types import parse_endpoint_types
from dynamo.llm import ModelInput, ModelType, WorkerType
from dynamo.runtime import DistributedRuntime
from dynamo.sglang._compat import override_server_args
from dynamo.sglang.args import Config
from dynamo.sglang.health_check import (
SglangDisaggHealthCheckPayload,
Expand Down Expand Up @@ -71,7 +72,11 @@ async def init_decode(
"created before the endpoint existed, so its FPM publisher bound "
"a different IPC path than the relay would subscribe to."
)
server_args.enable_forward_pass_metrics = False
override_server_args(
server_args,
"dynamo.snapshot",
enable_forward_pass_metrics=False,
)
Comment thread
jain-ria marked this conversation as resolved.
Resolved
else:
set_forward_pass_metrics_worker_id(server_args, generate_endpoint)
start_time = time.time()
Expand Down Expand Up @@ -227,7 +232,11 @@ async def init_prefill(
"created before the endpoint existed, so its FPM publisher bound "
"a different IPC path than the relay would subscribe to."
)
server_args.enable_forward_pass_metrics = False
override_server_args(
server_args,
"dynamo.snapshot",
enable_forward_pass_metrics=False,
)
else:
set_forward_pass_metrics_worker_id(server_args, generate_endpoint)
start_time = time.time()
Expand Down
7 changes: 6 additions & 1 deletion components/src/dynamo/sglang/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
)
from dynamo.common.utils.runtime import create_runtime
from dynamo.runtime.logging import configure_dynamo_logging
from dynamo.sglang._compat import override_server_args
from dynamo.sglang.args import parse_args
from dynamo.sglang.init_diffusion import (
init_image_diffusion,
Expand Down Expand Up @@ -44,7 +45,11 @@ async def worker(argv: list[str] | None = None):
if config.server_args.load_format == "gms":
from gpu_memory_service.integrations.sglang import setup_gms

config.server_args.load_format = setup_gms(config.server_args)
override_server_args(
config.server_args,
"dynamo.gms",
load_format=setup_gms(config.server_args),
)
Comment thread
jain-ria marked this conversation as resolved.
Resolved

# Snapshot mode: engine must be created before runtime so CRIU captures no
# NATS/etcd connections.
Expand Down
9 changes: 7 additions & 2 deletions components/src/dynamo/sglang/publisher.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
)
from dynamo.llm import KvEventPublisher, WorkerMetricsPublisher
from dynamo.runtime import Endpoint
from dynamo.sglang._compat import override_server_args
from dynamo.sglang._disagg import SGLANG_WORKER_GROUP_ID_KEY, get_sglang_worker_group_id
from dynamo.sglang.args import Config
from dynamo.sglang.capacity import (
Expand All @@ -49,9 +50,13 @@ def set_forward_pass_metrics_worker_id(

import tempfile

server_args.forward_pass_metrics_worker_id = str(generate_endpoint.connection_id())
ipc_path = tempfile.NamedTemporaryFile(delete=False).name
server_args.forward_pass_metrics_ipc_name = f"ipc://{ipc_path}"
override_server_args(
server_args,
"dynamo.forward_pass_metrics",
forward_pass_metrics_worker_id=str(generate_endpoint.connection_id()),
forward_pass_metrics_ipc_name=f"ipc://{ipc_path}",
)


async def _resolve_multinode_leader_worker_id(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -871,7 +871,9 @@ async def update_weight_version(self, body: dict) -> dict:
if req.abort_all_requests:
self.engine.tokenizer_manager.abort_request(abort_all=True)

self.engine.tokenizer_manager.server_args.weight_version = req.new_version
self.engine.tokenizer_manager._update_weight_version_if_provided(
req.new_version
)
return {
"success": True,
"message": f"Weight version updated to {req.new_version}",
Comment thread
jain-ria marked this conversation as resolved.
Resolved
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,7 @@ def __init__(

# Get bootstrap info using BootstrapManager
self.bootstrap_host, self.bootstrap_port = self._get_bootstrap_info(engine)
self._consume_tasks: set[asyncio.Task[Any]] = set()

logger.info(
f"Multimodal prefill worker handler initialized - bootstrap host: {self.bootstrap_host}, bootstrap port: {self.bootstrap_port}"
Expand Down Expand Up @@ -721,8 +722,56 @@ def _end_bootstrap() -> None:
# Validate and parse request
disagg_request = self._validate_and_parse_disagg_request(disagg_request)

# Generate and return bootstrap info first (like regular SGLang)
bootstrap_room = self._generate_bootstrap_room()
results, tensor_id = await self._start_prefill_generation(
disagg_request, bootstrap_room, context=context
)
consumer_owns_tensor = asyncio.Event()
request_started = asyncio.Event()
task: asyncio.Task[Any] | None = None
try:
task = asyncio.create_task(
self._consume_results(
results,
tensor_id,
context,
consumer_owns_tensor,
request_started,
)
)
self._consume_tasks.add(task)
task.add_done_callback(self._consume_tasks.discard)

started_wait = asyncio.create_task(request_started.wait())
try:
await asyncio.wait(
(task, started_wait),
return_when=asyncio.FIRST_COMPLETED,
)
finally:
if not started_wait.done():
started_wait.cancel()
try:
await started_wait
except asyncio.CancelledError:
pass

# Surface an immediate submission/cancellation failure before
# decode is authorized. Once consumer_owns_tensor is set, the
# consumer's try/finally owns the transferred tensor.
if task.done():
await task
except BaseException:
if not consumer_owns_tensor.is_set():
if task is not None and not task.done():
task.cancel()
if tensor_id is not None:
self.embeddings_processor.release_embeddings(tensor_id)
raise
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

# Do not authorize decode until embeddings have been received and
# the result consumer has advanced SGLang's lazy request iterator.
# Otherwise decode can start waiting before prefill is submitted.
bootstrap_info = {
"bootstrap_host": self.bootstrap_host,
"bootstrap_port": self.bootstrap_port,
Expand All @@ -732,10 +781,7 @@ def _end_bootstrap() -> None:
_end_bootstrap()
yield json.dumps(bootstrap_info)

# Process prefill generation
await self._process_prefill_generation(
disagg_request, bootstrap_room, context=context
)
await task

except Exception as e:
logger.error(f"Error in prefill generation: {e}", exc_info=True)
Expand All @@ -761,13 +807,13 @@ def _validate_and_parse_disagg_request(
)
return disagg_request

async def _process_prefill_generation(
async def _start_prefill_generation(
self,
disagg_request: DisaggSglangMultimodalRequest,
bootstrap_room: int,
context=None,
):
"""Process multimodal input and start prefill generation"""
) -> tuple[AsyncIterator[Any], Optional[int]]:
"""Receive multimodal embeddings and submit the prefill to SGLang."""
# Get the SglangMultimodalRequest from the DisaggSglangMultimodalRequest
request = disagg_request.request
input_ids = request.request.token_ids
Expand All @@ -787,42 +833,92 @@ async def _process_prefill_generation(
context.trace_headers() if context and self.enable_trace else None
)

# Start SGLang prefill generation (like regular SGLang)
with _nvtx.annotate("mm:prefill:engine_async_generate", color="blue"):
gen_params = {
"input_ids": input_ids,
"sampling_params": sampling_params,
"stream": True,
"bootstrap_host": self.bootstrap_host,
"bootstrap_port": self.bootstrap_port,
"bootstrap_room": bootstrap_room,
"external_trace_header": trace_header,
"rid": context.trace_id if context else None,
}

if image_mm_items:
gen_params["image_data"] = image_mm_items
if video_data:
gen_params["video_data"] = video_data

results = await self.engine.async_generate(**gen_params)
try:
Comment thread
jain-ria marked this conversation as resolved.
Resolved
# Start SGLang prefill generation (like regular SGLang)
with _nvtx.annotate("mm:prefill:engine_async_generate", color="blue"):
gen_params = {
"input_ids": input_ids,
"sampling_params": sampling_params,
"stream": True,
"bootstrap_host": self.bootstrap_host,
"bootstrap_port": self.bootstrap_port,
"bootstrap_room": bootstrap_room,
"external_trace_header": trace_header,
"rid": context.trace_id if context else None,
}

if image_mm_items:
gen_params["image_data"] = image_mm_items
if video_data:
gen_params["video_data"] = video_data

results = await self.engine.async_generate(**gen_params)
except BaseException:
if tensor_id is not None:
self.embeddings_processor.release_embeddings(tensor_id)
raise

# Consume results without yielding (prefill doesn't return text, just coordinates)
asyncio.create_task(self._consume_results(results, tensor_id))
return results, tensor_id

async def _consume_results(self, results, tensor_id: Optional[int]):
"""Consume prefill results without returning them (like regular SGLang)"""
async def _consume_results(
self,
results,
tensor_id: Optional[int],
context: Context,
owns_tensor: asyncio.Event,
request_started: asyncio.Event,
) -> None:
"""Consume prefill output while honoring request cancellation."""
released = False
request_id_future: asyncio.Future[str] = asyncio.Future()
Comment thread
jain-ria marked this conversation as resolved.
Resolved
first_result_task: asyncio.Task[Any] | None = None

def process_result(result: dict[str, Any]) -> None:
nonlocal released
if not request_id_future.done():
request_id = result.get("meta_info", {}).get("id")
if request_id:
request_id_future.set_result(request_id)
if tensor_id is not None and not released:
self.embeddings_processor.release_embeddings(tensor_id)
released = True

try:
async for _ in results:
if tensor_id is not None and not released:
self.embeddings_processor.release_embeddings(tensor_id)
released = True
owns_tensor.set()
async with self._cancellation_monitor(request_id_future, context):
first_result_task = asyncio.create_task(anext(results))
# SGLang's stream is a lazy async generator. Give its first
# iteration a scheduler turn before authorizing decode so the
# request reaches TokenizerManager.generate_request.
await asyncio.sleep(0)
Comment thread
jain-ria marked this conversation as resolved.
Resolved
request_started.set()
try:
first_result = await first_result_task
except StopAsyncIteration as e:
raise RuntimeError(
"SGLang prefill stream ended before producing a result"
) from e
process_result(first_result)

async for result in results:
process_result(result)
finally:
if first_result_task is not None:
if not first_result_task.done():
first_result_task.cancel()
try:
await first_result_task
except (asyncio.CancelledError, Exception):
pass
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if tensor_id is not None and not released:
self.embeddings_processor.release_embeddings(tensor_id)

def cleanup(self):
for task in self._consume_tasks:
if not task.done():
task.cancel()
self._consume_tasks.clear()

super().cleanup()
self.engine.shutdown()
logger.info("Multimodal prefill engine shutdown")
6 changes: 4 additions & 2 deletions components/src/dynamo/sglang/snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
SnapshotConfig,
configure_snapshot_capture_env,
)
from dynamo.sglang._compat import override_server_args

from .pause import SGLangEnginePauseController

Expand Down Expand Up @@ -138,15 +139,16 @@ async def prepare_snapshot_engine(
# Enable memory_saver so GPU memory can be released for CRIU.
# When using GMS, weights use VA-stable unmap/remap (no CPU backup); GMS
# forbids enable_weights_cpu_backup. Otherwise use CPU backup for weights.
server_args.enable_memory_saver = True
snapshot_overrides = {"enable_memory_saver": True}
try:
from gpu_memory_service.integrations.sglang import is_gms_active

_using_gms = is_gms_active()
except ImportError:
_using_gms = False
if not _using_gms:
server_args.enable_weights_cpu_backup = True
snapshot_overrides["enable_weights_cpu_backup"] = True
override_server_args(server_args, "dynamo.snapshot", **snapshot_overrides)
Comment thread
jain-ria marked this conversation as resolved.
Resolved

start_time = time.time()
engine = sgl.Engine(server_args=server_args)
Expand Down
Loading
Loading