diff --git a/docs/inference.md b/docs/inference.md index 125f4e968d7..a78c5deb647 100644 --- a/docs/inference.md +++ b/docs/inference.md @@ -185,8 +185,8 @@ non_cached_tokens = 16 # llm-d only: below this many non-cached prompt "kv-cache-utilization-scorer" = 2.0 ``` -- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`. The only backend supported for single-node (local) deployments. -- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy (multi-node / disaggregated SLURM deployments only). Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay). +- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`. +- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. `uv run router @ router.json` renders their configs and runs both, so it works on one node, on several nodes and under P/D. With in-engine data parallelism on one node, vLLM balances the ranks behind the one engine URL. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay). Both backends support the 2 most important things: - Request routing - KV cache re-use and balanced routing diff --git a/packages/prime-rl-configs/src/prime_rl/configs/components/router.py b/packages/prime-rl-configs/src/prime_rl/configs/components/router.py index ad8af57eb57..b88c5e7b423 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/components/router.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/components/router.py @@ -83,16 +83,14 @@ def validate_scorers(self): return self -# Discriminated on ``type`` so the launch path can pick the router backend. RouterBackendConfig: TypeAlias = Annotated[VllmRouterConfig | LlmdRouterConfig, Field(discriminator="type")] class RouterConfig(ComponentConfig): - """Config of the router process: a vllm-router fronting the engines. The llm-d router has no router process; - the SLURM templates start it.""" + """Config of the router process: a vllm-router, or an llm-d EPP and Envoy, fronting the engines.""" - router: VllmRouterConfig = VllmRouterConfig() - """Settings of the vllm-router backend.""" + router: RouterBackendConfig = VllmRouterConfig() + """Router backend and its settings.""" host: str = "0.0.0.0" """Host the router binds.""" @@ -110,11 +108,15 @@ class RouterConfig(ComponentConfig): """Decode engine URLs of a disaggregated deployment. The launcher passes them at start (``--decode-urls``).""" intra_node_data_parallel_size: int = Field(1, ge=1) - """Data-parallel ranks behind each URL.""" + """Data-parallel ranks behind each URL. Only vllm-router addresses the ranks; llm-d sends to the URL.""" pd_bidirectional_ttl_s: int | None = Field(None, ge=1) """How long the router keeps a session's decode KV blocks for its next prefill. None disables bidirectional KV transfer.""" + decode_port: int | None = Field(None, ge=1, le=65535) + """llm-d P/D only: first port of the decode engines on a node. The pd-sidecar of the engine on + ``decode_port + k`` listens on ``router.decode_sidecar_port + k``, and llm-d routes decode requests to it.""" + prometheus_port: int | None = Field(None, ge=1, le=65535) - """Port of the router's Prometheus metrics endpoint (None = the vllm-router default).""" + """Port of the router's Prometheus metrics endpoint (None = the backend's default).""" diff --git a/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/_supervised.py b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/_supervised.py index fd8b7649b77..e13fd60513e 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/_supervised.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/_supervised.py @@ -118,14 +118,6 @@ def validate_deployment(self): raise ValueError("Must use SLURM for multi-node deployment.") return self - @model_validator(mode="after") - def validate_router_deployment(self): - """The SLURM templates launch the llm-d router (EPP + Envoy) for the engines on dedicated nodes.""" - router = self.inference.router if self.inference is not None else None - if router is not None and router.type == "llm-d" and self.deployment.type == "single_node": - raise ValueError("The llm-d router backend requires a multi-node SLURM deployment.") - return self - @model_validator(mode="after") def validate_weight_broadcast_inference(self): if self.weight_broadcast is not None and self.weight_broadcast.type != "filesystem" and self.inference is None: diff --git a/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/inference.py b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/inference.py index 7bc806a5dd5..0019dfd35e2 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/inference.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/entrypoints/inference.py @@ -21,7 +21,7 @@ prefill_uses_deepep_high_throughput, ) from prime_rl.configs.components.engine.kv_cache import KVCacheOffloadConfig -from prime_rl.configs.components.router import RouterBackendConfig, RouterConfig, VllmRouterConfig +from prime_rl.configs.components.router import LlmdRouterConfig, RouterBackendConfig, RouterConfig, VllmRouterConfig from prime_rl.utils.config import find_package_resource PDRole: TypeAlias = Literal["prefill", "decode"] @@ -69,10 +69,10 @@ def engine_config( ) def router_config(self, local: bool = True, **wired: Any) -> RouterConfig | None: - """The router process's config, or None without a vllm-router. A ``local`` router fronts the one engine + """The router process's config, or None without a router. A ``local`` router fronts the one engine on its host. A router for engines on other nodes binds every interface, and its launcher passes the engine URLs on the command line once it knows the hosts.""" - if not isinstance(self.router, VllmRouterConfig): + if self.router is None: return None host = (self.server.host or "0.0.0.0") if local else "0.0.0.0" worker_host = "localhost" if host == "0.0.0.0" else host @@ -116,9 +116,7 @@ def validate_bidirectional_kv_transfer(self): @model_validator(mode="after") def validate_router_deployment(self): - """The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines.""" - if self.router is not None and self.router.type == "llm-d" and self.deployment.type == "single_node": - raise ValueError("The llm-d router backend requires a multi-node or disaggregated SLURM deployment.") + """Multi-node deployments need a router to front the per-rank engines.""" if self.router is None and self.deployment.type in ("multi_node", "disaggregated"): raise ValueError("Multi-node / disaggregated deployments require a router fronting the per-rank engines.") return self @@ -242,8 +240,11 @@ def router_config(self, local: bool | None = None) -> RouterConfig | None: """The router process's config. The router is ``local`` to a single-node deployment.""" deployment = self.deployment wired: dict[str, Any] = {} - if isinstance(deployment, DisaggregatedInferenceDeploymentConfig) and deployment.bidirectional_kv_transfer: - wired["pd_bidirectional_ttl_s"] = deployment.bidirectional_kv_transfer.effective_router_ttl_s + if isinstance(deployment, DisaggregatedInferenceDeploymentConfig): + if deployment.bidirectional_kv_transfer: + wired["pd_bidirectional_ttl_s"] = deployment.bidirectional_kv_transfer.effective_router_ttl_s + if isinstance(self.router, LlmdRouterConfig): + wired["decode_port"] = deployment.decode_port return super().router_config(deployment.type == "single_node" if local is None else local, **wired) diff --git a/skills/install/SKILL.md b/skills/install/SKILL.md index 9337b00555e..cf9b87373a6 100644 --- a/skills/install/SKILL.md +++ b/skills/install/SKILL.md @@ -105,13 +105,13 @@ Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`. ### llm-d router backend -Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[inference.router] type = "llm-d"`). It needs three native binaries — install once: +Any deployment can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[inference.router] type = "llm-d"`). It needs three native binaries — install once: ```bash bash scripts/install_llmd.sh # builds epp + pd-sidecar from a pinned llm-d-router commit (vendored Go), fetches envoy ``` -Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, so SLURM nodes see them). `epp` is pinned to the commit that includes the `vllmhttp-parser` (PR #1248) so prime-rl's renderer/TITO `/inference/v1/generate` path routes correctly. Override the pin with `LLMD_ROUTER_REF=`. The EPP + Envoy + endpoints configs are rendered from `src/prime_rl/templates/llmd/*.yaml.j2` (included into the SLURM script); only the per-node IPv4 addresses are filled in inline at launch time. +Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, so SLURM nodes see them). `epp` is pinned to the commit that includes the `vllmhttp-parser` (PR #1248) so prime-rl's renderer/TITO `/inference/v1/generate` path routes correctly. Override the pin with `LLMD_ROUTER_REF=`. The router process (`src/prime_rl/components/router.py`) renders the EPP, Envoy and endpoints configs from `router.json` and the engine URLs, and starts `epp` and `envoy` from `third_party/llmd/bin`. ## Key files diff --git a/src/prime_rl/components/router.py b/src/prime_rl/components/router.py index 5209b1d7895..0396a29aaf1 100644 --- a/src/prime_rl/components/router.py +++ b/src/prime_rl/components/router.py @@ -1,21 +1,60 @@ import os import resource +import signal +import socket +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any +from urllib.parse import urlsplit -from prime_rl.configs.components.router import RouterConfig +import yaml + +from prime_rl.configs.components.router import LlmdRouterConfig, RouterConfig, VllmRouterConfig from prime_rl.utils.config import cli +# scripts/install_llmd.sh installs epp, envoy and pd-sidecar here. +LLMD_BIN_DIR = Path(__file__).resolve().parents[3] / "third_party" / "llmd" / "bin" +LLMD_POOL = "prime-rl" +EPP_GRPC_PORT = 9002 +# Not 9003: mooncake_master serves its metrics there and can share the router's node. +EPP_GRPC_HEALTH_PORT = 9013 +EPP_METRICS_PORT = 9090 +ENVOY_ADMIN_PORT = 9901 +# Envoy's default circuit breakers (~1024) reset requests at high inflight concurrency. +UNLIMITED_CIRCUIT_BREAKERS = { + "thresholds": [ + { + "priority": priority, + "max_connections": 100000, + "max_pending_requests": 100000, + "max_requests": 100000, + "max_retries": 1000, + } + for priority in ("DEFAULT", "HIGH") + ] +} -def router_command(config: RouterConfig) -> list[str]: - """The vllm-router command line for ``config``.""" - is_pd = bool(config.prefill_urls or config.decode_urls) - if is_pd: + +def is_disaggregated(config: RouterConfig) -> bool: + """Whether ``config`` routes to prefill and decode engines. Raises for an incomplete set of engine URLs.""" + if config.prefill_urls or config.decode_urls: if config.worker_urls: raise ValueError("Specify either worker_urls or prefill_urls/decode_urls, not both.") if not config.prefill_urls or not config.decode_urls: raise ValueError("Disaggregated routing requires both prefill_urls and decode_urls.") - elif not config.worker_urls: + return True + if not config.worker_urls: raise ValueError("Colocated routing requires at least one entry in worker_urls.") + return False + +def router_command(config: RouterConfig) -> list[str]: + """The vllm-router command line for ``config``.""" + assert isinstance(config.router, VllmRouterConfig) + is_pd = is_disaggregated(config) cmd = [ "vllm-router", "--policy", @@ -57,11 +96,249 @@ def router_command(config: RouterConfig) -> list[str]: return cmd +def _endpoint(name: str, url: str, role: str | None = None, port_offset: int = 0) -> dict[str, Any]: + parts = urlsplit(url) + if parts.hostname is None or parts.port is None: + raise ValueError(f"Engine URL {url!r} needs a host and a port.") + try: + # llm-d's file discovery takes IPv4 addresses only. + address = socket.getaddrinfo(parts.hostname, None, socket.AF_INET)[0][4][0] + except socket.gaierror as e: + raise ValueError(f"Cannot resolve the host of engine URL {url!r} to an IPv4 address: {e}") from e + labels = {"llm-d.ai/pool": LLMD_POOL} + if role is not None: + labels["llm-d.ai/role"] = role + return { + "name": name, + "address": address, + "port": str(parts.port + port_offset), + "namespace": "default", + "labels": labels, + } + + +def llmd_endpoints(config: RouterConfig) -> list[dict[str, Any]]: + """One llm-d endpoint per engine URL. Under P/D, a decode endpoint is the pd-sidecar in front of the engine.""" + llmd = config.router + assert isinstance(llmd, LlmdRouterConfig) + if not is_disaggregated(config): + return [_endpoint(f"backend-{i}", url) for i, url in enumerate(config.worker_urls)] + if config.decode_port is None: + raise ValueError("Disaggregated llm-d routing needs decode_port to find the pd-sidecar of each decode engine.") + sidecar_offset = llmd.decode_sidecar_port - config.decode_port + return [_endpoint(f"prefill-{i}", url, "prefill") for i, url in enumerate(config.prefill_urls)] + [ + _endpoint(f"decode-{i}", url, "decode", sidecar_offset) for i, url in enumerate(config.decode_urls) + ] + + +def _profile(name: str, scorers: dict[str, float], filter_ref: str | None = None) -> dict[str, Any]: + plugins = [{"pluginRef": filter_ref}] if filter_ref else [] + plugins += [{"pluginRef": scorer, "weight": weight} for scorer, weight in scorers.items()] + return {"name": name, "plugins": [*plugins, {"pluginRef": "max-score-picker"}]} + + +def epp_config(config: RouterConfig, endpoints_path: Path) -> dict[str, Any]: + """The llm-d Endpoint Picker config. The vllmhttp parser also parses ``/inference/v1/generate`` (token ids), + so prefix-cache scoring covers the OpenAI and the token-in routes.""" + llmd = config.router + assert isinstance(llmd, LlmdRouterConfig) + plugins: list[dict[str, Any]] = [ + {"name": "file-disc", "type": "file-discovery", "parameters": {"path": str(endpoints_path), "watchFile": True}}, + {"name": "vllmhttp-parser", "type": "vllmhttp-parser"}, + ] + if is_disaggregated(config): + # A request with at least non_cached_tokens uncached prompt tokens runs the prefill profile first. + plugins += [ + { + "name": "pd-decider", + "type": "prefix-based-pd-decider", + "parameters": {"nonCachedTokens": llmd.non_cached_tokens}, + }, + { + "name": "profile-handler", + "type": "disagg-profile-handler", + "parameters": {"deciders": {"prefill": "pd-decider"}}, + }, + {"type": "prefill-filter"}, + {"type": "decode-filter"}, + ] + scorers = [*dict.fromkeys([*llmd.prefill_scorers, *llmd.decode_scorers])] + profiles = [ + _profile("prefill", llmd.prefill_scorers, "prefill-filter"), + _profile("decode", llmd.decode_scorers, "decode-filter"), + ] + handler = [] + else: + scorers = [*llmd.scorers] + profiles = [_profile("default", llmd.scorers)] + handler = [{"type": "single-profile-handler"}] + plugins += [{"type": scorer} for scorer in scorers] + [{"type": "max-score-picker"}] + handler + return { + "apiVersion": "inference.networking.x-k8s.io/v1alpha1", + "kind": "EndpointPickerConfig", + "plugins": plugins, + "schedulingProfiles": profiles, + "requestHandler": {"parser": {"pluginRef": "vllmhttp-parser"}}, + "dataLayer": {"discovery": {"pluginRef": "file-disc"}}, + } + + +def envoy_config(config: RouterConfig) -> dict[str, Any]: + """The Envoy data plane. The EPP picks an endpoint per request (ext_proc) and names it in the + ``x-gateway-destination-endpoint`` header, which the ORIGINAL_DST cluster routes to.""" + route = {"cluster": "backend_cluster", "timeout": "0s", "idle_timeout": "86400s"} + ext_proc = { + "@type": "type.googleapis.com/envoy.extensions.filters.http.ext_proc.v3.ExternalProcessor", + "grpc_service": {"envoy_grpc": {"cluster_name": "epp_cluster"}, "timeout": "10s"}, + "processing_mode": { + "request_header_mode": "SEND", + "response_header_mode": "SEND", + "request_body_mode": "FULL_DUPLEX_STREAMED", + "response_body_mode": "FULL_DUPLEX_STREAMED", + "request_trailer_mode": "SEND", + "response_trailer_mode": "SEND", + }, + "message_timeout": "1000s", + } + connection_manager = { + "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager", + "stat_prefix": "prime_rl", + "codec_type": "AUTO", + "stream_idle_timeout": "0s", + "request_timeout": "0s", + "route_config": { + "virtual_hosts": [ + { + "name": "prime_rl", + "domains": ["*"], + "routes": [ + {"match": {"prefix": "/v1/"}, "route": route}, + {"match": {"prefix": "/inference/v1/"}, "route": route}, + ], + } + ] + }, + "http_filters": [ + {"name": "envoy.filters.http.ext_proc", "typed_config": ext_proc}, + { + "name": "envoy.filters.http.router", + "typed_config": { + "@type": "type.googleapis.com/envoy.extensions.filters.http.router.v3.Router", + "suppress_envoy_headers": True, + }, + }, + ], + } + epp_endpoint = {"endpoint": {"address": {"socket_address": {"address": "127.0.0.1", "port_value": EPP_GRPC_PORT}}}} + return { + "admin": {"address": {"socket_address": {"address": "127.0.0.1", "port_value": ENVOY_ADMIN_PORT}}}, + "static_resources": { + "listeners": [ + { + "name": "prime_rl", + "address": {"socket_address": {"address": config.host, "port_value": config.port}}, + "filter_chains": [ + { + "filters": [ + { + "name": "envoy.filters.network.http_connection_manager", + "typed_config": connection_manager, + } + ] + } + ], + } + ], + "clusters": [ + { + "name": "backend_cluster", + "type": "ORIGINAL_DST", + "lb_policy": "CLUSTER_PROVIDED", + "original_dst_lb_config": { + "use_http_header": True, + "http_header_name": "x-gateway-destination-endpoint", + }, + "connect_timeout": "5s", + "circuit_breakers": UNLIMITED_CIRCUIT_BREAKERS, + }, + { + "name": "epp_cluster", + "type": "STRICT_DNS", + "typed_extension_protocol_options": { + "envoy.extensions.upstreams.http.v3.HttpProtocolOptions": { + "@type": "type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions", + "explicit_http_config": {"http2_protocol_options": {}}, + } + }, + "load_assignment": {"cluster_name": "epp_cluster", "endpoints": [{"lb_endpoints": [epp_endpoint]}]}, + "connect_timeout": "5s", + # ext_proc calls are 1:1 with inflight requests. + "circuit_breakers": UNLIMITED_CIRCUIT_BREAKERS, + }, + ], + }, + } + + +def llmd_commands(config: RouterConfig, config_dir: Path) -> list[list[str]]: + """Write the llm-d configs to ``config_dir`` and return the EPP and Envoy command lines.""" + endpoints_path = config_dir / "endpoints.yaml" + endpoints_path.write_text(yaml.safe_dump({"endpoints": llmd_endpoints(config)}, sort_keys=False)) + (config_dir / "epp.yaml").write_text(yaml.safe_dump(epp_config(config, endpoints_path), sort_keys=False)) + (config_dir / "envoy.yaml").write_text(yaml.safe_dump(envoy_config(config), sort_keys=False)) + epp = [ + "epp", + "--pool-name", + LLMD_POOL, + "--pool-namespace", + "slurm", + "--config-file", + str(config_dir / "epp.yaml"), + "--grpc-port", + str(EPP_GRPC_PORT), + "--grpc-health-port", + str(EPP_GRPC_HEALTH_PORT), + "--metrics-port", + str(config.prometheus_port or EPP_METRICS_PORT), + "--secure-serving=false", + "--metrics-endpoint-auth=false", + "--tracing=false", + ] + return [epp, ["envoy", "-c", str(config_dir / "envoy.yaml")]] + + +def run_llmd(config: RouterConfig) -> int: + """Run the llm-d EPP and Envoy until one of them exits, and return a non-zero exit code: the router is a + service, so any exit is a failure.""" + env = {**os.environ, "PATH": f"{LLMD_BIN_DIR}{os.pathsep}{os.environ.get('PATH', '')}"} + with tempfile.TemporaryDirectory(prefix="prime-rl-llmd-") as config_dir: + processes = [subprocess.Popen(cmd, env=env) for cmd in llmd_commands(config, Path(config_dir))] + + def stop(signum, _frame): + for process in processes: + process.terminate() + for process in processes: + process.wait() + sys.exit(128 + signum) + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGINT, stop) + while (exited := next((p for p in processes if p.poll() is not None), None)) is None: + time.sleep(1) + for process in processes: + process.terminate() + process.wait() + return exited.returncode or 1 + + def main() -> None: - cmd = router_command(cli(RouterConfig)) + config = cli(RouterConfig) # The router holds a socket per in-flight request; a 1024 soft limit runs out at ~500. _, hard_nofile = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (hard_nofile, hard_nofile)) + if isinstance(config.router, LlmdRouterConfig): + sys.exit(run_llmd(config)) + cmd = router_command(config) os.execvp(cmd[0], cmd) diff --git a/src/prime_rl/entrypoints/inference.py b/src/prime_rl/entrypoints/inference.py index 759e992d056..5eca93aaf08 100644 --- a/src/prime_rl/entrypoints/inference.py +++ b/src/prime_rl/entrypoints/inference.py @@ -5,9 +5,7 @@ from threading import Event, Thread from prime_rl.components.engine import setup_engine_process -from prime_rl.components.router import router_command from prime_rl.configs.components.engine.kv_cache import MooncakeKVCacheOffloadConfig -from prime_rl.configs.components.router import RouterConfig from prime_rl.configs.entrypoints.inference import InferenceConfig, InferenceSection from prime_rl.entrypoints.slurm import load_slurm_template, submit_sbatch from prime_rl.utils.admin_token import digest_var @@ -31,6 +29,7 @@ INFERENCE_CONFIG = "inference.json" ENGINE_CONFIG = "engine.json" +ROUTER_CONFIG = "router.json" INFERENCE_SBATCH = "inference.sbatch" @@ -129,12 +128,12 @@ def inference_slurm(config: InferenceConfig): submit_sbatch(script_path, log_message) -def start_router(config: RouterConfig, admin_token_var: str) -> subprocess.Popen: - """Start the vllm-router of ``config``.""" +def start_router(config_path: Path, admin_token_var: str) -> subprocess.Popen: + """Start the router of the config at ``config_path``.""" # The router never calls the engine's admin routes. token_vars = (admin_token_var, digest_var(admin_token_var)) env = {key: value for key, value in os.environ.items() if key not in token_vars} - return subprocess.Popen(router_command(config), env=env) + return subprocess.Popen(["router", "@", config_path.as_posix()], env=env) def inference_local(config: InferenceConfig): @@ -152,8 +151,10 @@ def inference_local(config: InferenceConfig): router_process: subprocess.Popen | None = None router_stopping = Event() if router is not None: + config_dir, _ = prepare_attempt_dirs(config.output_dir) + write_config(config_dir / ROUTER_CONFIG, router) logger.info(f"Starting router on http://{router.host}:{router.port}/v1 (engine on port {engine.server.port})\n") - router_process = start_router(router, engine.server.admin_token_var) + router_process = start_router(config_dir / ROUTER_CONFIG, engine.server.admin_token_var) def watch_router(): router_process.wait() diff --git a/src/prime_rl/templates/_launch_router.sh.j2 b/src/prime_rl/templates/_launch_router.sh.j2 index d35c77b70cc..6e065d028d3 100644 --- a/src/prime_rl/templates/_launch_router.sh.j2 +++ b/src/prime_rl/templates/_launch_router.sh.j2 @@ -1,77 +1,9 @@ {# Shared launch helper for the single global router, included once per template - and called by inference node 0. The router backend (vllm-router vs llm-d - EPP+Envoy) is chosen here via router.type, so the call sites stay - router-agnostic. llm-d endpoint discovery enumerates every inference node: - all nodes for regular mode; for disaggregated mode all prefill nodes across - replicas, then all decode nodes (matching the logical node order in - endpoints.yaml). #} -# launch_router + and called by inference node 0. router.json picks the backend (vllm-router or + llm-d EPP + Envoy); worker_args passes the engine URLs that only the job knows. #} +# launch_router launch_router() { - local mode="$1" worker_args="$2" port="$3" log="$4" -{%- if router.type == "llm-d" %} - echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port" | tee "$log" - export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH" - local LLMD_DIR="$LOG_DIR/inference/llmd" - mkdir -p "$LLMD_DIR" - read -ra HOSTNAMES <<< "$HOSTNAMES_STR" -{%- if is_disaggregated %} -{%- set ep_disaggregated = true %} -{%- set ep_num_prefill = num_prefill_nodes * (num_infer_replicas | default(1)) %} -{%- set ep_num_decode = num_decode_nodes * (num_infer_replicas | default(1)) %} -{%- set ep_dp = dp_per_node %} -{%- set ep_prefill_port = prefill_port %} -{%- set ep_sidecar_port = router.decode_sidecar_port %} - cat > "$LLMD_DIR/epp.yaml" < "$LLMD_DIR/endpoints.yaml" < "$LLMD_DIR/epp.yaml" < "$LLMD_DIR/endpoints.yaml" < "$LLMD_DIR/envoy.yaml" <> "$log" 2>&1 & - envoy -c "$LLMD_DIR/envoy.yaml" >> "$log" 2>&1 & -{%- else %} - local tag="vllm-router"; [ "$mode" = pd ] && tag="vllm-router (PD)" - echo "Starting $tag on $LOCAL_IP:$port" | tee "$log" - # worker_args holds the engine URLs as router flags; router.json holds the rest. + local worker_args="$1" log="$2" + echo "Starting router on $LOCAL_IP" | tee "$log" uv run router @ "$CONFIG_DIR/router.json" $worker_args >> "$log" 2>&1 & -{%- endif %} } diff --git a/src/prime_rl/templates/inference.sbatch.j2 b/src/prime_rl/templates/inference.sbatch.j2 index bb7abc6821d..d5fbe5f4f0b 100755 --- a/src/prime_rl/templates/inference.sbatch.j2 +++ b/src/prime_rl/templates/inference.sbatch.j2 @@ -282,7 +282,7 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH' # Start the single global router on node 0 (external LB across all per-rank endpoints) if [ "$INFER_NODE_RANK" -eq 0 ]; then - launch_router pd "$ROUTER_ARGS" "$ROUTER_PORT" "$LOG_DIR/inference/router.log" + launch_router "$ROUTER_ARGS" "$LOG_DIR/inference/router.log" fi {%- if router.type == "llm-d" %} # pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT @@ -332,7 +332,7 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH' # Start the single global router on node 0 (balances across per-rank endpoints — no intra-node DP header) if [ "$INFER_NODE_RANK" -eq 0 ]; then - launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "$LOG_DIR/inference/router.log" + launch_router "$ROUTER_ARGS" "$LOG_DIR/inference/router.log" fi # External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local), diff --git a/src/prime_rl/templates/llmd/endpoints.yaml.j2 b/src/prime_rl/templates/llmd/endpoints.yaml.j2 deleted file mode 100644 index 1f3bec6214d..00000000000 --- a/src/prime_rl/templates/llmd/endpoints.yaml.j2 +++ /dev/null @@ -1,41 +0,0 @@ -{# llm-d file-discovery endpoints: one entry per DP rank. Rendered (via include) - into the sbatch; the per-node address is the __LLMD_ADDR___ placeholder, - filled with each SLURM host's IPv4 inline in the sbatch (file-discovery rejects - hostnames). Node ordering matches the sbatch's host loop: prefill then decode. - The including sbatch sets ep_* via {% set %}. #} -endpoints: -{%- if ep_disaggregated %} -{%- for node in range(ep_num_prefill) %} -{%- for rank in range(ep_dp) %} - - name: prefill-{{ node }}-rank-{{ rank }} - address: __LLMD_ADDR_{{ node }}__ - port: "{{ ep_prefill_port + rank }}" - namespace: default - labels: - llm-d.ai/pool: prime-rl - llm-d.ai/role: prefill -{%- endfor %} -{%- endfor %} -{%- for node in range(ep_num_decode) %} -{%- for rank in range(ep_dp) %} - - name: decode-{{ node }}-rank-{{ rank }} - address: __LLMD_ADDR_{{ ep_num_prefill + node }}__ - port: "{{ ep_sidecar_port + rank }}" - namespace: default - labels: - llm-d.ai/pool: prime-rl - llm-d.ai/role: decode -{%- endfor %} -{%- endfor %} -{%- else %} -{%- for node in range(ep_num_nodes) %} -{%- for rank in range(ep_dp) %} - - name: backend-{{ node }}-rank-{{ rank }} - address: __LLMD_ADDR_{{ node }}__ - port: "{{ ep_backend_port + rank }}" - namespace: default - labels: - llm-d.ai/pool: prime-rl -{%- endfor %} -{%- endfor %} -{%- endif %} diff --git a/src/prime_rl/templates/llmd/envoy.yaml.j2 b/src/prime_rl/templates/llmd/envoy.yaml.j2 deleted file mode 100644 index 9773d5b59af..00000000000 --- a/src/prime_rl/templates/llmd/envoy.yaml.j2 +++ /dev/null @@ -1,97 +0,0 @@ -{# Envoy data plane: EPP picks the backend (ext_proc) and sets - x-gateway-destination-endpoint; the ORIGINAL_DST cluster routes there. Both - /v1/ (MITO) and /inference/v1/ (TITO) go through the picker. EPP gRPC is on - loopback 9002; the gateway listens on the configured port. #} -admin: - address: { socket_address: { address: 127.0.0.1, port_value: 9901 } } -static_resources: - listeners: - - name: prime_rl - address: { socket_address: { address: 0.0.0.0, port_value: {{ router_port }} } } - filter_chains: - - filters: - - name: envoy.filters.network.http_connection_manager - typed_config: - "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager - stat_prefix: prime_rl - codec_type: AUTO - stream_idle_timeout: 0s - request_timeout: 0s - route_config: - virtual_hosts: - - name: prime_rl - domains: ["*"] - routes: - - match: { prefix: "/v1/" } - route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s } - - match: { prefix: "/inference/v1/" } - route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s } - http_filters: - - name: envoy.filters.http.ext_proc - typed_config: - "@type": type.googleapis.com/envoy.extensions.filters.http.ext_proc.v3.ExternalProcessor - grpc_service: - envoy_grpc: { cluster_name: epp_cluster } - timeout: 10s - processing_mode: - request_header_mode: SEND - response_header_mode: SEND - request_body_mode: FULL_DUPLEX_STREAMED - response_body_mode: FULL_DUPLEX_STREAMED - request_trailer_mode: SEND - response_trailer_mode: SEND - message_timeout: 1000s - - name: envoy.filters.http.router - typed_config: - "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router - suppress_envoy_headers: true - clusters: - - name: backend_cluster - type: ORIGINAL_DST - lb_policy: CLUSTER_PROVIDED - original_dst_lb_config: - use_http_header: true - http_header_name: x-gateway-destination-endpoint - connect_timeout: 5s - # Default circuit breakers (~1024) overflow at high inflight concurrency (>=1536), - # causing "reset reason: overflow" 500s. Raise far above the max concurrent rollouts. - circuit_breakers: - thresholds: - - priority: DEFAULT - max_connections: 100000 - max_pending_requests: 100000 - max_requests: 100000 - max_retries: 1000 - - priority: HIGH - max_connections: 100000 - max_pending_requests: 100000 - max_requests: 100000 - max_retries: 1000 - - name: epp_cluster - type: STRICT_DNS - typed_extension_protocol_options: - envoy.extensions.upstreams.http.v3.HttpProtocolOptions: - "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions - explicit_http_config: - http2_protocol_options: {} - load_assignment: - cluster_name: epp_cluster - endpoints: - - lb_endpoints: - - endpoint: - address: { socket_address: { address: 127.0.0.1, port_value: 9002 } } - connect_timeout: 5s - # ext_proc (EPP) connection pool overflows at high concurrency without this — the - # gRPC ext_proc calls are 1:1 with inflight requests, so cap well above max rollouts. - circuit_breakers: - thresholds: - - priority: DEFAULT - max_connections: 100000 - max_pending_requests: 100000 - max_requests: 100000 - max_retries: 1000 - - priority: HIGH - max_connections: 100000 - max_pending_requests: 100000 - max_requests: 100000 - max_retries: 1000 diff --git a/src/prime_rl/templates/llmd/epp_estimate.yaml.j2 b/src/prime_rl/templates/llmd/epp_estimate.yaml.j2 deleted file mode 100644 index 27f041ff1b7..00000000000 --- a/src/prime_rl/templates/llmd/epp_estimate.yaml.j2 +++ /dev/null @@ -1,34 +0,0 @@ -{# llm-d EPP config: single-pool (non-P/D) routing with approximate prefix-cache - scoring. The vllmhttp parser embeds the OpenAI parser and also handles - /inference/v1/generate (token_ids), so MITO + TITO both get prefix-cache - scoring. Included into the sbatch as a heredoc; $LLMD_DIR is the per-replica - config dir, expanded at launch time. #} -apiVersion: inference.networking.x-k8s.io/v1alpha1 -kind: EndpointPickerConfig -plugins: - - name: file-disc - type: file-discovery - parameters: - path: $LLMD_DIR/endpoints.yaml - watchFile: true - - name: vllmhttp-parser - type: vllmhttp-parser -{%- for scorer in router.scorers %} - - type: {{ scorer }} -{%- endfor %} - - type: max-score-picker - - type: single-profile-handler -schedulingProfiles: - - name: default - plugins: -{%- for scorer, weight in router.scorers.items() %} - - pluginRef: {{ scorer }} - weight: {{ weight }} -{%- endfor %} - - pluginRef: max-score-picker -requestHandler: - parser: - pluginRef: vllmhttp-parser -dataLayer: - discovery: - pluginRef: file-disc diff --git a/src/prime_rl/templates/llmd/epp_pd.yaml.j2 b/src/prime_rl/templates/llmd/epp_pd.yaml.j2 deleted file mode 100644 index 909b531fcdd..00000000000 --- a/src/prime_rl/templates/llmd/epp_pd.yaml.j2 +++ /dev/null @@ -1,56 +0,0 @@ -{# llm-d EPP config: prefill/decode disaggregation. disagg-profile-handler runs - the prefill profile when prefix-based-pd-decider sees >= nonCachedTokens - non-cached prompt tokens, else decode-only. Mirrors the upstream llm-d PD - guide: the prefill profile uses prefill_scorers (prefix + queue/kv) and the - decode profile uses scorers (prefix + active-request); prefill-filter / - decode-filter select endpoints by llm-d.ai/role label. Included into the - sbatch as a heredoc; $LLMD_DIR is the per-replica config dir, expanded at - launch time. #} -apiVersion: inference.networking.x-k8s.io/v1alpha1 -kind: EndpointPickerConfig -plugins: - - name: file-disc - type: file-discovery - parameters: - path: $LLMD_DIR/endpoints.yaml - watchFile: true - - name: vllmhttp-parser - type: vllmhttp-parser - - name: pd-decider - type: prefix-based-pd-decider - parameters: - nonCachedTokens: {{ router.non_cached_tokens }} - - name: profile-handler - type: disagg-profile-handler - parameters: - deciders: - prefill: pd-decider - - type: prefill-filter - - type: decode-filter -{%- for scorer in ((router.prefill_scorers.keys() | list) + (router.decode_scorers.keys() | list)) | unique %} - - type: {{ scorer }} -{%- endfor %} - - type: max-score-picker -schedulingProfiles: - - name: prefill - plugins: - - pluginRef: prefill-filter -{%- for scorer, weight in router.prefill_scorers.items() %} - - pluginRef: {{ scorer }} - weight: {{ weight }} -{%- endfor %} - - pluginRef: max-score-picker - - name: decode - plugins: - - pluginRef: decode-filter -{%- for scorer, weight in router.decode_scorers.items() %} - - pluginRef: {{ scorer }} - weight: {{ weight }} -{%- endfor %} - - pluginRef: max-score-picker -requestHandler: - parser: - pluginRef: vllmhttp-parser -dataLayer: - discovery: - pluginRef: file-disc diff --git a/src/prime_rl/templates/multi_node_rl.sbatch.j2 b/src/prime_rl/templates/multi_node_rl.sbatch.j2 index 21dacac0705..1ef6ba9638e 100644 --- a/src/prime_rl/templates/multi_node_rl.sbatch.j2 +++ b/src/prime_rl/templates/multi_node_rl.sbatch.j2 @@ -392,7 +392,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then # Start the single global router on inference node 0 (PD mode, external LB across all per-rank endpoints) if [ "$INFER_NODE_RANK" -eq 0 ]; then - launch_router pd "$ROUTER_ARGS" "$ROUTER_PORT" "$LOG_DIR/inference/router.log" + launch_router "$ROUTER_ARGS" "$LOG_DIR/inference/router.log" fi {%- if router.type == "llm-d" %} # pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT @@ -435,7 +435,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then {%- else -%} # Start the single global router on inference node 0 (external LB across all per-rank endpoints) if [ "$INFER_NODE_RANK" -eq 0 ]; then - launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "$LOG_DIR/inference/router.log" + launch_router "$ROUTER_ARGS" "$LOG_DIR/inference/router.log" fi # External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d), diff --git a/src/prime_rl/templates/multi_node_sft.sbatch.j2 b/src/prime_rl/templates/multi_node_sft.sbatch.j2 index 13a11da9071..1c47a8913a2 100644 --- a/src/prime_rl/templates/multi_node_sft.sbatch.j2 +++ b/src/prime_rl/templates/multi_node_sft.sbatch.j2 @@ -229,7 +229,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then done if [ "$INFER_NODE_RANK" -eq 0 ]; then - launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "$LOG_DIR/inference/router.log" + launch_router "$ROUTER_ARGS" "$LOG_DIR/inference/router.log" {%- if eval_env_names %} mkdir -p $LOG_DIR/envs/eval diff --git a/tests/unit/test_configs.py b/tests/unit/test_configs.py index cb55c08f14b..f274ce04fc6 100644 --- a/tests/unit/test_configs.py +++ b/tests/unit/test_configs.py @@ -2726,16 +2726,17 @@ def test_rl_trainer_alone_binds_the_nccl_rendezvous_on_multi_node(): def test_sft_inference_takes_its_deployment_from_the_run(): - """The sft launcher starts inference on the run's inference nodes, so llm-d works only on multi-node runs.""" + """The sft launcher starts inference on the run's inference nodes, behind either router backend.""" inference = {"router": {"type": "llm-d"}} multi_node = {"type": "multi_node", "num_train_nodes": 1, "num_infer_nodes": 2} config = SFTConfig.model_validate( {**SFT_INFERENCE_RUN, "inference": inference, "slurm": {}, "deployment": multi_node} ) assert config.placement()["engine"].nodes == 2 - assert "router" not in config.components() - with pytest.raises(ValidationError, match="llm-d router backend requires"): - SFTConfig.model_validate({**SFT_INFERENCE_RUN, "inference": inference}) + assert config.components()["router"].router.type == "llm-d" + assert config.components()["router"].worker_urls == [] + local = SFTConfig.model_validate({**SFT_INFERENCE_RUN, "inference": inference}) + assert local.components()["router"].worker_urls == ["http://localhost:8100"] def test_rl_validates_the_component_configs_it_builds(): diff --git a/tests/unit/test_pd_launch.py b/tests/unit/test_pd_launch.py index b827cdf0cf5..70860c5d3d9 100644 --- a/tests/unit/test_pd_launch.py +++ b/tests/unit/test_pd_launch.py @@ -144,8 +144,8 @@ def test_router_entrypoint_builds_pd_and_colocated_commands(tmp_path: Path): assert cmd[cmd.index("--request-timeout-secs") + 1] == "14400" llmd = InferenceConfig(router={"type": "llm-d"}, deployment={"type": "multi_node"}, slurm={}) - assert llmd.router_config() is None - assert "router" not in llmd.components() + assert llmd.components()["router"] == llmd.router_config() + assert llmd.router_config().router.type == "llm-d" def test_apply_multi_node_dp_env_sets_hybrid_lb_rank_and_head(monkeypatch): diff --git a/tests/unit/test_router_launch.py b/tests/unit/test_router_launch.py index 37a003a1a18..0d92adfbe83 100644 --- a/tests/unit/test_router_launch.py +++ b/tests/unit/test_router_launch.py @@ -1,22 +1,80 @@ +import time from pathlib import Path +import pytest +import yaml from jinja2 import Environment, FileSystemLoader -from prime_rl.components.router import router_command -from prime_rl.configs.components.router import RouterConfig, VllmRouterConfig +from prime_rl.components import router as router_module +from prime_rl.components.router import llmd_commands, router_command, run_llmd +from prime_rl.configs.components.router import LlmdRouterConfig, RouterConfig +from prime_rl.configs.entrypoints.inference import InferenceConfig from prime_rl.configs.entrypoints.rl import RLConfig from prime_rl.utils.config import cli TEMPLATES = Path(__file__).parents[2] / "src" / "prime_rl" / "templates" -def _render(router: VllmRouterConfig) -> str: +def test_multi_node_launchers_start_the_router_from_its_config(): env = Environment(loader=FileSystemLoader(TEMPLATES), keep_trailing_newline=True) - return env.get_template("_launch_router.sh.j2").render(router=router) + script = env.get_template("_launch_router.sh.j2").render() + assert 'uv run router @ "$CONFIG_DIR/router.json" $worker_args' in script -def test_multi_node_launchers_start_the_router_from_its_config(): - assert 'uv run router @ "$CONFIG_DIR/router.json" $worker_args' in _render(VllmRouterConfig()) +def test_llmd_router_runs_epp_and_envoy_from_its_config(tmp_path): + config = RouterConfig( + router=LlmdRouterConfig(scorers={"prefix-cache-scorer": 3.0}), + port=8000, + worker_urls=["http://localhost:8100", "http://127.0.0.1:8101"], + prometheus_port=29000, + ) + epp, envoy = llmd_commands(config, tmp_path) + + endpoints = yaml.safe_load((tmp_path / "endpoints.yaml").read_text())["endpoints"] + assert [(e["name"], e["address"], e["port"]) for e in endpoints] == [ + ("backend-0", "127.0.0.1", "8100"), + ("backend-1", "127.0.0.1", "8101"), + ] + picker = yaml.safe_load((tmp_path / "epp.yaml").read_text()) + assert picker["plugins"][0]["parameters"]["path"] == str(tmp_path / "endpoints.yaml") + assert picker["schedulingProfiles"] == [ + { + "name": "default", + "plugins": [{"pluginRef": "prefix-cache-scorer", "weight": 3.0}, {"pluginRef": "max-score-picker"}], + } + ] + listener = yaml.safe_load((tmp_path / "envoy.yaml").read_text())["static_resources"]["listeners"][0] + assert listener["address"]["socket_address"]["port_value"] == 8000 + assert epp[0] == "epp" and epp[epp.index("--metrics-port") + 1] == "29000" + assert envoy == ["envoy", "-c", str(tmp_path / "envoy.yaml")] + + +def test_llmd_pd_router_sends_decode_requests_to_the_sidecar(tmp_path): + inference = InferenceConfig( + router={"type": "llm-d", "decode_sidecar_port": 8300}, deployment={"type": "disaggregated"}, slurm={} + ) + config = inference.router_config().model_copy( + update={"prefill_urls": ["http://127.0.0.1:8100"], "decode_urls": ["http://127.0.0.1:8201"]} + ) + llmd_commands(config, tmp_path) + endpoints = yaml.safe_load((tmp_path / "endpoints.yaml").read_text())["endpoints"] + assert [(e["name"], e["port"], e["labels"]["llm-d.ai/role"]) for e in endpoints] == [ + ("prefill-0", "8100", "prefill"), + ("decode-0", "8301", "decode"), + ] + profiles = yaml.safe_load((tmp_path / "epp.yaml").read_text())["schedulingProfiles"] + assert [profile["name"] for profile in profiles] == ["prefill", "decode"] + + with pytest.raises(ValueError, match="needs decode_port"): + llmd_commands(config.model_copy(update={"decode_port": None}), tmp_path) + + +@pytest.mark.parametrize("exiting", [["false"], ["true"]]) +def test_llmd_router_fails_when_epp_or_envoy_exits(monkeypatch, tmp_path, exiting): + monkeypatch.setattr(router_module, "llmd_commands", lambda config, config_dir: [["sleep", "60"], exiting]) + start = time.monotonic() + assert run_llmd(RouterConfig(router=LlmdRouterConfig(), worker_urls=["http://127.0.0.1:1"])) == 1 + assert time.monotonic() - start < 10 def test_pd_router_retries_turns_on_connection_errors():