Skip to content
Closed
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
5a21312
add patch for sglang to call dynamo event manager
faradawn Jun 2, 2025
e699408
Merge branch 'main' into sglang-integration-event-manager
faradawn Jun 5, 2025
5dbf090
add default page size to avoid sglang having page size of 1
faradawn Jun 5, 2025
ace979b
Merge branch 'sglang-integration-event-manager' of github.com:faradaw…
faradawn Jun 5, 2025
f61a7c1
remove old patch
faradawn Jun 5, 2025
cfa1cb9
Merge branch 'main' of https://github.com/ai-dynamo/dynamo into sglan…
faradawn Jun 7, 2025
53ea353
1st draft of router
faradawn Jun 10, 2025
3c5781a
Merge branch 'ai-dynamo:main' into sglang-integration-event-manager
faradawn Jun 10, 2025
077ead1
got sglang router graph working
faradawn Jun 13, 2025
7f6f2f1
update sglang router example in readme
faradawn Jun 15, 2025
8507146
fix bindings readme
faradawn Jun 15, 2025
39fd160
update sglang docker commit
faradawn Jun 15, 2025
ab379c6
Merge branch 'main' of https://github.com/faradawn/dynamo into sglang…
faradawn Jun 15, 2025
e5b2cdc
made sglang router example working
faradawn Jun 15, 2025
127eac6
Merge branch 'main' of https://github.com/ai-dynamo/dynamo into sglan…
faradawn Jun 15, 2025
69bb71e
fixing input pasing to sglang
faradawn Jun 15, 2025
aac3b8f
redo frontend small change
faradawn Jun 16, 2025
45e7294
raw sglang frontend
faradawn Jun 16, 2025
29846bf
processing parsing preprocessed errro
faradawn Jun 16, 2025
8f821e1
Merge branch 'main' of https://github.com/ai-dynamo/dynamo into sglan…
faradawn Jun 16, 2025
e55aa27
Merge branch 'ai-dynamo:main' into sglang-integration-event-manager
faradawn Jun 20, 2025
bde922b
Merge branch 'sglang-integration-event-manager' of https://github.com…
faradawn Jun 20, 2025
a818bfb
revert to main branch, frontend and worker working
faradawn Jun 20, 2025
e2817e9
revert readme
faradawn Jun 20, 2025
9e669c7
add kv zmq publisher to worker, it is working
faradawn Jun 21, 2025
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
6 changes: 4 additions & 2 deletions container/Dockerfile.sglang
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,10 @@ RUN if [ "$ARCH" = "arm64" ]; then \

# Install sglang
# Once either 0.4.6post6 or 0.4.7 is released, we can switch back to using the published version
# This commit references a fix to add DP attention based routing along with other perf fixes https://github.com/sgl-project/sglang/pull/6884
ARG SGLANG_COMMIT="f1569876d54dd3b6601f5280f12652e9fbb1375c"
# This commit references multiple perf fixes for DP attention and NIXL https://github.com/sgl-project/sglang/pull/6780
# 6/2(ishan) - moving to ToT for performance purposes
# 6/12(faradawn) - this commit fixes ZMQ KV event publisher inside sglang
ARG SGLANG_COMMIT="777688b8929c877e4e28c2eac208d776abe4c3af"
RUN --mount=type=cache,target=/root/.cache/uv \
git clone https://github.com/sgl-project/sglang.git && \
cd sglang && \
Expand Down
6 changes: 6 additions & 0 deletions examples/sglang/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@ cd /workspace/examples/sglang
dynamo serve graphs.agg:Frontend -f ./configs/agg.yaml
```

#### Aggregated with KV Routing
```bash
cd /workspace/examples/sglang
dynamo serve graphs.agg_router:Frontend -f ./configs/agg_router.yaml
```

#### Disaggregated

As of `sglang==0.4.6.post4`, SGLang uses a mini load balancer to route requests to handle disaggregated serving. The load balancer functions as follows
Expand Down
6 changes: 4 additions & 2 deletions examples/sglang/components/frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from dynamo.sdk import depends, service
from dynamo.sdk.lib.config import ServiceConfig
from dynamo.sdk.lib.image import DYNAMO_IMAGE
from components.kv_router import Router

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -56,11 +57,12 @@ class FrontendConfig(BaseModel):
app=FastAPI(title="LLM Example"),
)
class Frontend:
worker = depends(SGLangWorker)
worker = depends(Router)

def __init__(self):
"""Initialize Frontend service with HTTP server and model configuration."""
frontend_config = FrontendConfig(**ServiceConfig.get_parsed_config("Frontend"))
logger.info("=== Frontend config: %s", frontend_config)
self.frontend_config = frontend_config
self.process = None

Expand All @@ -69,7 +71,7 @@ def __init__(self):
def start_ingress_and_processor(self):
"""Starting dynamo-run based ingress and processor"""
logger.info(
f"Starting HTTP server and processor on port {self.frontend_config.port}"
f"===Starting HTTP server and processor on port {self.frontend_config.port}"
)
dynamo_run_binary = get_dynamo_run_binary()
endpoint = f"dyn://{self.frontend_config.endpoint}"
Expand Down
314 changes: 314 additions & 0 deletions examples/sglang/components/kv_router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,314 @@
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""KV-based router for SGLang workers.

This implementation mirrors the KV router logic used in the vLLM example, but
routes requests to ``SGLangWorker`` instances instead. The key idea is to
compute a *cost* (or *logit*) for each candidate worker using

1. Cache-overlap scores obtained from a ``KvIndexer`` (shared library from
``dynamo.llm``).
2. Runtime metrics (GPU cache usage, prefix-cache hit-rate, request queue
length) aggregated by ``KvMetricsAggregator``.

The router selects the worker with the highest score and streams back the
selected ``worker_id`` together with the estimated prefix-hit ratio so that the
caller can attach this information to the subsequent request.

Both the indexer and the aggregator communicate with workers over ZMQ, which
matches the existing SGLang deployment pattern.
"""

# faradawn hello

from __future__ import annotations

import argparse
import logging
import random
from argparse import Namespace
from typing import AsyncIterator, Tuple

from components.worker import SGLangWorker
from utils.protocol import Tokens

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Import path may break outside examples package

from components.worker import SGLangWorker relies on the current working directory being examples/sglang. Use an absolute import rooted at the project package (e.g. examples.sglang.components.worker) or add .__init__.py files to turn folders into packages.

🤖 Prompt for AI Agents
In examples/sglang/components/kv_router.py around lines 45 to 47, the import
statement uses a relative path that depends on the current working directory,
which can break outside the examples package. Change the import to use an
absolute import rooted at the project package, such as importing SGLangWorker
from examples.sglang.components.worker. Alternatively, ensure all relevant
directories have __init__.py files to make them proper packages and support
relative imports.

from dynamo.llm import (
AggregatedMetrics,
KvIndexer,
KvMetricsAggregator,
OverlapScores,
)
from dynamo.sdk import async_on_start, depends, dynamo_context, endpoint, service
from dynamo.sdk.lib.config import ServiceConfig

class RouterType:
RANDOM = "random"
ROUND_ROBIN = "round-robin"
KV = "kv"
KV_LOAD = "kv-load"

# Type alias for clarity
WorkerId = str

fallback_msg = "Will fallback to random routing."
logger = logging.getLogger(__name__)


def parse_args(service_name: str, prefix: str) -> Namespace:
"""Parse router-specific CLI/ServiceConfig arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--min-workers",
type=int,
default=1,
help="Minimum number of workers required before proceeding",
)
parser.add_argument(
"--model",
type=str,
default="deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
help="Model that is being served",
)
parser.add_argument(
"--block-size",
type=int,
default=64,
help="KV block size",
)
parser.add_argument(
"--custom-router",
type=bool,
default=False,
help="Whether to use custom router or not",
)
parser.add_argument(
"--router",
type=str,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Boolean CLI flag should use action="store_true"

type=bool expects the user to pass an explicit value (--custom-router true), which is error-prone and breaks argparse’s “flag” semantics. Replace with action="store_true" (and drop the default):

-    parser.add_argument(
-        "--custom-router",
-        type=bool,
-        default=False,
-        help="Whether to use custom router or not",
-    )
+    parser.add_argument(
+        "--custom-router",
+        action="store_true",
+        help="Enable custom router",
+    )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"--custom-router",
type=bool,
default=False,
help="Whether to use custom router or not",
)
parser.add_argument(
"--router",
type=str,
parser.add_argument(
"--custom-router",
action="store_true",
help="Enable custom router",
)
parser.add_argument(
"--router",
type=str,
🤖 Prompt for AI Agents
In examples/sglang/components/kv_router.py around lines 90 to 97, the boolean
CLI flag for --custom-router incorrectly uses type=bool, requiring an explicit
value and breaking flag semantics. Change the argument to use
action="store_true" instead and remove the default value to make it a proper
flag that sets the value to True when present.

default=RouterType.KV,
help="The router type",
)

# Merge with service-level configuration
config = ServiceConfig.get_instance()
config_args = config.as_args(service_name, prefix=prefix)
args = parser.parse_args(config_args)
return args


@service(
dynamo={
"namespace": "dynamo",
},
resources={"cpu": "10", "memory": "20Gi"},
workers=1,
)
class Router:
"""Router that decides which ``SGLangWorker`` should execute a request."""

# A dependency is declared so that the runtime ensures workers are launched
worker = depends(SGLangWorker)

def __init__(self):
logger.info("Initializing Custom KV Router for SGLang")
self.args = parse_args(self.__class__.__name__, "")
logger.info("=== Router args: %s", self.args)

# Default metric values when data is unavailable
self.default_metrics = {
"gpu_cache_usage_perc": 0.0,
"num_requests_waiting": 0.0,
"gpu_prefix_cache_hit_rate": 0.0,
}

# ---------------------------------------------------------------------
# Lifecycle hooks
# ---------------------------------------------------------------------

@async_on_start
async def async_init(self):
"""Connect to worker endpoints and initialise ZMQ helpers."""
logger.info("=== starting async init")
self.runtime = dynamo_context["runtime"]

# Client used to fetch current list of worker instance IDs
self.workers_client = (
await self.runtime.namespace("dynamo")
.component("SGLangWorker")
.endpoint("generate")
.client()
)

self.router_type = self.args.router


kv_listener = self.runtime.namespace("dynamo").component("SGLangWorker")
await kv_listener.create_service()

self.indexer = KvIndexer(kv_listener, self.args.block_size)

logger.info("=== created kvIndexer with block size: %s", self.args.block_size)

self.metrics_aggregator = KvMetricsAggregator(kv_listener)
logger.info("KV Router initialised (type=%s)", self.router_type)

# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------

def _cost_function(
self,
scores: OverlapScores | None,
metrics: AggregatedMetrics | None,
token_length: int,
) -> Tuple[WorkerId, float]:
"""Compute the best worker given scores/metrics.

Returns a tuple of ``(worker_id, estimated_prefix_hit_rate)``.
"""
logger.info("=== Cost function called")

worker_scores: dict[WorkerId, float] = {}
if scores:
for worker_id, score in scores.scores.items():
# score is in *blocks*; convert to *tokens* hit-rate
worker_scores[worker_id] = (
score * self.indexer.block_size() / token_length
)
else:
logger.warning("Cannot get KV scores")

worker_metrics: dict[WorkerId, dict[str, float]] = {}
max_waiting = 0.0
if metrics:
for endpoint in metrics.endpoints:
worker_id = endpoint.worker_id
worker_metrics[worker_id] = {
key: getattr(endpoint, key, self.default_metrics[key])
for key in self.default_metrics.keys()
}
max_waiting = max(
max_waiting, worker_metrics[worker_id]["num_requests_waiting"]
)
else:
logger.warning("Cannot get metrics")

# Consider *all* workers, even if metrics/scores missing
worker_ids = self.workers_client.instance_ids()

worker_logits: dict[WorkerId, float] = {}
for worker_id in worker_ids:
score = worker_scores.get(worker_id, 0.0)
metrics_dict = worker_metrics.get(worker_id, self.default_metrics)
gpu_cache_usage = metrics_dict["gpu_cache_usage_perc"]
normalized_waiting = (
metrics_dict["num_requests_waiting"] / max_waiting
if max_waiting > 0 else 0.0
)

# Simple linear combination (higher is better)
worker_logits[worker_id] = 2 * score - gpu_cache_usage - normalized_waiting
logger.info(
"Formula for %s: %.3f = 2.0 * %.3f - %.3f - %.3f",
worker_id,
worker_logits[worker_id],
score,
gpu_cache_usage,
normalized_waiting,
)

if not worker_logits or not any(worker_logits.values()):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Cost function mixes incomparable scales – results may be biased

gpu_cache_usage_perc appears to be a value in [0,100] while score is a fraction 0-1 (after block → token normalisation). Subtracting the raw percentage heavily outweighs the 2×cache-hit bonus, effectively turning the formula into “pick whoever uses 0 % GPU cache”.

Either:

  1. Convert gpu_cache_usage_perc to [0,1] by dividing by 100, or
  2. Rescale all terms/weights based on empirical ranges (e.g. weight hit-rate by 100 as well).

Example fix:

-            gpu_cache_usage = metrics_dict["gpu_cache_usage_perc"]
+            gpu_cache_usage = metrics_dict["gpu_cache_usage_perc"] / 100.0

and revisit the coefficients.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _cost_function(
self,
scores: OverlapScores | None,
metrics: AggregatedMetrics | None,
token_length: int,
) -> Tuple[WorkerId, float]:
"""Compute the best worker given scores/metrics.
Returns a tuple of ``(worker_id, estimated_prefix_hit_rate)``.
"""
logger.info("=== Cost function called")
worker_scores: dict[WorkerId, float] = {}
if scores:
for worker_id, score in scores.scores.items():
# score is in *blocks*; convert to *tokens* hit-rate
worker_scores[worker_id] = (
score * self.indexer.block_size() / token_length
)
else:
logger.warning("Cannot get KV scores")
worker_metrics: dict[WorkerId, dict[str, float]] = {}
max_waiting = 0.0
if metrics:
for endpoint in metrics.endpoints:
worker_id = endpoint.worker_id
worker_metrics[worker_id] = {
key: getattr(endpoint, key, self.default_metrics[key])
for key in self.default_metrics.keys()
}
max_waiting = max(
max_waiting, worker_metrics[worker_id]["num_requests_waiting"]
)
else:
logger.warning("Cannot get metrics")
# Consider *all* workers, even if metrics/scores missing
worker_ids = self.workers_client.instance_ids()
worker_logits: dict[WorkerId, float] = {}
for worker_id in worker_ids:
score = worker_scores.get(worker_id, 0.0)
metrics_dict = worker_metrics.get(worker_id, self.default_metrics)
gpu_cache_usage = metrics_dict["gpu_cache_usage_perc"]
normalized_waiting = (
metrics_dict["num_requests_waiting"] / max_waiting
if max_waiting > 0 else 0.0
)
# Simple linear combination (higher is better)
worker_logits[worker_id] = 2 * score - gpu_cache_usage - normalized_waiting
logger.info(
"Formula for %s: %.3f = 2.0 * %.3f - %.3f - %.3f",
worker_id,
worker_logits[worker_id],
score,
gpu_cache_usage,
normalized_waiting,
)
if not worker_logits or not any(worker_logits.values()):
for worker_id in worker_ids:
score = worker_scores.get(worker_id, 0.0)
metrics_dict = worker_metrics.get(worker_id, self.default_metrics)
- gpu_cache_usage = metrics_dict["gpu_cache_usage_perc"]
+ gpu_cache_usage = metrics_dict["gpu_cache_usage_perc"] / 100.0
normalized_waiting = (
metrics_dict["num_requests_waiting"] / max_waiting
if max_waiting > 0 else 0.0
)
# Simple linear combination (higher is better)
worker_logits[worker_id] = 2 * score - gpu_cache_usage - normalized_waiting
logger.info(
"Formula for %s: %.3f = 2.0 * %.3f - %.3f - %.3f",
worker_id,
worker_logits[worker_id],
score,
gpu_cache_usage,
normalized_waiting,
)
🧰 Tools
🪛 Pylint (3.3.7)

[refactor] 171-171: Too many local variables (18/15)

(R0914)

🤖 Prompt for AI Agents
In examples/sglang/components/kv_router.py between lines 171 and 232, the cost
function subtracts gpu_cache_usage_perc directly, which is on a 0-100 scale,
from score values on a 0-1 scale, causing bias. Fix this by normalizing
gpu_cache_usage_perc to a 0-1 scale by dividing it by 100 before using it in the
formula. After this, revisit and adjust the coefficients in the linear
combination to ensure balanced weighting of all terms.

logger.warning("All worker logits are zero. %s", fallback_msg)
return "", 0.0

max_logit = max(worker_logits.values())
best_workers = [wid for wid, logit in worker_logits.items() if logit == max_logit]
best_worker_id = random.choice(best_workers)

if best_worker_id:
metrics_dict = worker_metrics.get(best_worker_id, self.default_metrics)
logger.info(
"Selected worker: %s, logit: %.3f, Score: %.3f, GPU Cache Hit Rate: %.3f, GPU Cache Usage: %.3f, Requests Waiting: %s",
best_worker_id,
worker_logits[best_worker_id],
worker_scores.get(best_worker_id, 0.0),
metrics_dict["gpu_prefix_cache_hit_rate"],
metrics_dict["gpu_cache_usage_perc"],
metrics_dict["num_requests_waiting"],
)

return best_worker_id, worker_scores.get(best_worker_id, 0.0)

def _get_underloaded_worker(self, metrics: AggregatedMetrics | None) -> Tuple[WorkerId, float]:
"""Pick worker with lowest GPU cache utilisation (KV_LOAD mode)."""
if not metrics:
logger.warning("Cannot get metrics. %s", fallback_msg)
return "", 0.0

kv_load = {
endpoint.worker_id: getattr(endpoint, "gpu_cache_usage_perc", 0.0)
for endpoint in metrics.endpoints
}

if not kv_load or not any(kv_load.values()):
logger.warning("All KV loads are zero. %s", fallback_msg)
return "", 0.0

min_load = min(kv_load.values())
min_load_workers = [wid for wid, load in kv_load.items() if load == min_load]
best_worker_id = random.choice(min_load_workers)

logger.info("Selected worker: %s, KV load: %.3f", best_worker_id, kv_load[best_worker_id])
return best_worker_id, kv_load[best_worker_id]

# ------------------------------------------------------------------
# Public endpoint
# ------------------------------------------------------------------

@endpoint()
async def generate(self, request: Tokens) -> AsyncIterator[Tuple[WorkerId, float]]:
"""Determine the best worker for the given request tokens."""
logger.info("=== Generate called")
# Pull latest metrics snapshot
metrics = await self.metrics_aggregator.get_metrics()

# Fast path for simple load-balancing
if self.router_type == RouterType.KV_LOAD:
try:
yield self._get_underloaded_worker(metrics)
except Exception as e:
logger.exception("Error finding underloaded worker: %s. %s", e, fallback_msg)
yield "", 0.0
return

# Full KV routing logic
lora_id = 0 # LoRA not used in this example
try:
scores = await self.indexer.find_matches_for_request(request.tokens, lora_id)
except Exception as e:
logger.exception("Error finding matches: %s. %s", e, fallback_msg)
yield "", 0.0
return

worker_id, prefix_hit_rate = self._cost_function(scores, metrics, len(request.tokens))

if worker_id:
logger.info(
"Scheduling to worker_id: %s with estimated prefix hit rate: %s",
worker_id,
prefix_hit_rate,
)

yield worker_id, prefix_hit_rate
Loading