-
Notifications
You must be signed in to change notification settings - Fork 6
Add launcher to allow launching worker from router #18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
zhaochenyang20
merged 9 commits into
zhaochenyang20:main
from
dreamyang-liu:feat/launcher
Feb 23, 2026
Merged
Changes from 6 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
f0e7748
Add launcher to allow launching worker from router
dreamyang-liu d815ee7
add example to readme and remove unused cli argument
dreamyang-liu 7023eb8
fix readme
dreamyang-liu 9afe1e4
Fix worker_urls
dreamyang-liu f501d83
fix lint
zhaochenyang20 0cf41be
fix the conflicts between isort and black
zhaochenyang20 37346a1
address comments
dreamyang-liu 4cb19a7
adds mocked port for unit tests
zhaochenyang20 b7052a2
fix conf
zhaochenyang20 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| launcher: | ||
| backend: local | ||
| model: Qwen/Qwen-Image | ||
|
|
||
| num_workers: 2 | ||
| num_gpus_per_worker: 2 | ||
| worker_host: "127.0.0.1" | ||
| worker_base_port: 10090 | ||
|
|
||
| # worker_gpu_ids: ["0,1", "2,3"] # optional: one entry per worker → CUDA_VISIBLE_DEVICES; auto-detected if omitted | ||
| worker_extra_args: "--dit-cpu-offload false --text-encoder-cpu-offload false" | ||
|
dreamyang-liu marked this conversation as resolved.
dreamyang-liu marked this conversation as resolved.
|
||
|
|
||
| wait_timeout: 600 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,13 +6,15 @@ | |
| import argparse | ||
| import asyncio | ||
| import sys | ||
| import threading | ||
|
|
||
| from sglang_diffusion_routing import DiffusionRouter | ||
| from sglang_diffusion_routing.launcher import config as _lcfg | ||
|
|
||
|
|
||
| def _run_router_server( | ||
| args: argparse.Namespace, | ||
| worker_urls: list[str] | None = None, | ||
| router: DiffusionRouter, | ||
| log_prefix: str = "[router]", | ||
| ) -> None: | ||
| try: | ||
|
|
@@ -22,10 +24,7 @@ def _run_router_server( | |
| "uvicorn is required to run router. Install with: pip install uvicorn" | ||
| ) from exc | ||
|
|
||
| worker_urls = list( | ||
| worker_urls if worker_urls is not None else args.worker_urls or [] | ||
| ) | ||
| router = DiffusionRouter(args, verbose=args.verbose) | ||
| worker_urls = list(args.worker_urls or []) | ||
| refresh_tasks = [] | ||
| for url in worker_urls: | ||
| normalized_url = router.normalize_worker_url(url) | ||
|
|
@@ -97,13 +96,48 @@ def _add_router_args(parser: argparse.ArgumentParser) -> None: | |
| parser.add_argument( | ||
| "--log-level", type=str, default="info", help="Uvicorn log level." | ||
| ) | ||
| parser.add_argument( | ||
| "--launcher-config", | ||
| type=str, | ||
| default=None, | ||
| dest="launcher_config", | ||
| help="YAML config for launching router managed workers (see examples/local_launcher.yaml).", | ||
| ) | ||
|
|
||
|
|
||
| def _handle_router(args: argparse.Namespace) -> int: | ||
| _run_router_server( | ||
| args, worker_urls=list(args.worker_urls), log_prefix="[sglang-d-router]" | ||
| ) | ||
| return 0 | ||
| log_prefix = "[sglang-d-router]" | ||
| backend = None | ||
|
|
||
| try: | ||
| router = DiffusionRouter(args, verbose=args.verbose) | ||
|
|
||
| if args.launcher_config is not None: | ||
| launcher_cfg = _lcfg.load_launcher_config(args.launcher_config) | ||
| wait_timeout = launcher_cfg.wait_timeout | ||
|
dreamyang-liu marked this conversation as resolved.
|
||
| backend = _lcfg.create_backend(launcher_cfg) | ||
| backend.launch() | ||
| threading.Thread( | ||
| target=backend.wait_ready_and_register, | ||
| kwargs=dict( | ||
| register_fn=router.register_worker, | ||
| timeout=wait_timeout, | ||
| log_prefix=log_prefix, | ||
| ), | ||
| daemon=True, | ||
| ).start() | ||
|
|
||
| _run_router_server(args, router=router, log_prefix=log_prefix) | ||
| return 0 | ||
| finally: | ||
| try: | ||
| asyncio.run(router.client.aclose()) | ||
| except Exception: | ||
| pass | ||
| if backend is not None: | ||
| print(f"{log_prefix} shutting down managed workers...", flush=True) | ||
| backend.shutdown() | ||
| print(f"{log_prefix} all managed workers terminated.", flush=True) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I left a todo here to refactor. But we can leave it right now. |
||
|
|
||
|
|
||
| def build_parser() -> argparse.ArgumentParser: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| """Launcher backends for spinning up SGLang diffusion workers. | ||
|
|
||
| Supported backends: | ||
| - ``local``: launch workers as local subprocesses. | ||
| """ | ||
|
|
||
| from sglang_diffusion_routing.launcher.backend import ( | ||
| LaunchedWorker, | ||
| LauncherBackend, | ||
| WorkerLaunchResult, | ||
| ) | ||
| from sglang_diffusion_routing.launcher.config import ( | ||
| create_backend, | ||
| load_launcher_config, | ||
| ) | ||
| from sglang_diffusion_routing.launcher.local import LocalLauncher, LocalLauncherConfig | ||
|
|
||
| __all__ = [ | ||
| "LaunchedWorker", | ||
| "LauncherBackend", | ||
| "LocalLauncher", | ||
| "LocalLauncherConfig", | ||
| "WorkerLaunchResult", | ||
| "create_backend", | ||
| "load_launcher_config", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| """Abstract base class and shared data types for launcher backends.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import subprocess | ||
| from abc import ABC, abstractmethod | ||
| from collections.abc import Callable | ||
| from dataclasses import dataclass, field | ||
|
|
||
|
|
||
| @dataclass | ||
| class LaunchedWorker: | ||
| """A worker managed by a launcher backend.""" | ||
|
|
||
| url: str | ||
| process: subprocess.Popen | ||
|
|
||
|
|
||
| @dataclass | ||
| class WorkerLaunchResult: | ||
| """Aggregated result of launching worker subprocesses.""" | ||
|
|
||
| workers: list[LaunchedWorker] = field(default_factory=list) | ||
| all_processes: list[subprocess.Popen] = field(default_factory=list) | ||
|
|
||
| @property | ||
| def urls(self) -> list[str]: | ||
| return [w.url for w in self.workers] | ||
|
|
||
|
|
||
| class LauncherBackend(ABC): | ||
| """Interface for launching and managing SGLang diffusion workers. | ||
|
|
||
| Each backend implements a different deployment strategy (local subprocess, | ||
| Kubernetes, Ray etc.) but exposes the same lifecycle: | ||
| launch → wait_ready_and_register → shutdown. | ||
| """ | ||
|
|
||
| @abstractmethod | ||
| def launch(self) -> list[str]: | ||
| """Launch workers and return their base URLs.""" | ||
|
|
||
| @abstractmethod | ||
| def wait_ready_and_register( | ||
| self, | ||
| register_fn: Callable[[str], None], | ||
| timeout: int, | ||
| log_prefix: str = "[launcher]", | ||
| ) -> None: | ||
| """Wait for workers to become healthy and register each via register_fn. | ||
|
|
||
| Workers are checked concurrently; each is registered as soon as it is | ||
| healthy rather than waiting for all workers to be ready. | ||
| """ | ||
|
|
||
| @abstractmethod | ||
| def shutdown(self) -> None: | ||
| """Terminate or clean up all managed workers.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| """YAML configuration loading and backend factory.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| import yaml | ||
| from omegaconf import DictConfig, OmegaConf | ||
|
|
||
| from sglang_diffusion_routing.launcher.backend import LauncherBackend | ||
| from sglang_diffusion_routing.launcher.local import LocalLauncher, LocalLauncherConfig | ||
|
|
||
| SCHEMA_REGISTRY: dict[str, type] = { | ||
| "local": LocalLauncherConfig, | ||
| } | ||
|
|
||
| BACKEND_REGISTRY: dict[str, type[LauncherBackend]] = { | ||
| "local": LocalLauncher, | ||
| } | ||
|
|
||
|
|
||
| def load_launcher_config(config_path: str) -> DictConfig: | ||
| """Read a YAML config file and return a validated OmegaConf config. | ||
|
|
||
| Steps: | ||
| 1. Parse the YAML and extract the launcher mapping. | ||
| 2. Read the backend key to select the structured schema. | ||
| 3. Merge the YAML values onto the schema defaults. | ||
| """ | ||
| path = Path(config_path) | ||
| if not path.is_file(): | ||
| raise FileNotFoundError(f"Config file not found: {config_path}") | ||
|
|
||
| with path.open() as f: | ||
| raw = yaml.safe_load(f) | ||
|
|
||
| if not isinstance(raw, dict) or "launcher" not in raw: | ||
| raise ValueError( | ||
| f"Config file must contain a top-level 'launcher' key: {config_path}" | ||
| ) | ||
|
|
||
| launcher_raw: dict[str, Any] = raw["launcher"] | ||
| if not isinstance(launcher_raw, dict): | ||
| raise ValueError("'launcher' must be a mapping") | ||
|
|
||
| backend_name = launcher_raw.get("backend", "local") | ||
| schema_cls = SCHEMA_REGISTRY.get(backend_name) | ||
| if schema_cls is None: | ||
| available = ", ".join(sorted(SCHEMA_REGISTRY)) | ||
| raise ValueError( | ||
| f"Unknown launcher backend: {backend_name!r}. " | ||
| f"Available backends: {available}" | ||
| ) | ||
|
|
||
| schema = OmegaConf.structured(schema_cls) | ||
| yaml_cfg = OmegaConf.create(launcher_raw) | ||
| merged: DictConfig = OmegaConf.merge(schema, yaml_cfg) # type: ignore[assignment] | ||
| return merged | ||
|
|
||
|
|
||
| def create_backend(config: DictConfig) -> LauncherBackend: | ||
| """Instantiate a LauncherBackend from a validated config. | ||
|
|
||
| The backend key selects the implementation class from | ||
| BACKEND_REGISTRY. | ||
| """ | ||
| backend_name = config.backend | ||
| cls = BACKEND_REGISTRY.get(backend_name) | ||
| if cls is None: | ||
| available = ", ".join(sorted(BACKEND_REGISTRY)) | ||
| raise ValueError( | ||
| f"Unknown launcher backend: {backend_name!r}. " | ||
| f"Available backends: {available}" | ||
| ) | ||
| return cls(config) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.