Repository navigation
[Serve][LLM] Apply replica performance defaults - #66435
Conversation
74c26a6 to
a772a06
Compare
1f82082 to
9a24c15
Compare
a772a06 to
1b0d010
Compare
9a24c15 to
d9a2ee1
Compare
1b0d010 to
d48a9a1
Compare
d48a9a1 to
feb7664
Compare
d9a2ee1 to
39795cf
Compare
feb7664 to
f381235
Compare
39795cf to
0402b44
Compare
Signed-off-by: Seiji Eicher <[email protected]>
f381235 to
641444c
Compare
0402b44 to
2a80546
Compare
Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces default environment variables for Ray Serve LLM replicas, specifically setting 'RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD' and 'RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP' to '0' unless explicitly overridden. It also configures serve handles to pass '_by_reference=False' and adds corresponding unit tests. The review feedback highlights two important issues: first, evaluating 'get_llm_serve_runtime_env()' at the module level in 'DEFAULT_INGRESS_OPTIONS' freezes environment variables at import time and should be handled dynamically; second, a potential 'TypeError' could occur in 'get_llm_serve_runtime_env' if 'env_vars' is explicitly set to 'None' in the runtime environment dictionary.
|
|
||
| DEFAULT_INGRESS_OPTIONS = { | ||
| "max_ongoing_requests": DEFAULT_MAX_ONGOING_REQUESTS, | ||
| "ray_actor_options": {"runtime_env": get_llm_serve_runtime_env()}, |
There was a problem hiding this comment.
Evaluating get_llm_serve_runtime_env() at the module level freezes the environment variable defaults at import time. If a user or test modifies os.environ programmatically after importing this module but before deploying, those changes will not be reflected in the ingress options.\n\nTo fix this, remove "ray_actor_options" from DEFAULT_INGRESS_OPTIONS and populate it dynamically inside get_deployment_options like so:\n\npython\n@classmethod\ndef get_deployment_options(\n cls, llm_configs: Optional[List[LLMConfig]] = None\n) -> Dict[str, Any]:\n options = copy.deepcopy(DEFAULT_INGRESS_OPTIONS)\n options["ray_actor_options"] = {"runtime_env": get_llm_serve_runtime_env()}\n if _all_models_scale_to_zero(llm_configs):\n options.setdefault("autoscaling_config", {})["min_replicas"] = 0\n return options\n
| "ray_actor_options": {"runtime_env": get_llm_serve_runtime_env()}, | |
| # ray_actor_options is populated dynamically in get_deployment_options |
| name: os.environ.get(name, default) | ||
| for name, default in _RAY_SERVE_LLM_REPLICA_ENV_DEFAULTS.items() | ||
| } | ||
| env_vars.update(runtime_env.get("env_vars", {})) |
There was a problem hiding this comment.
If runtime_env explicitly contains "env_vars": None, runtime_env.get("env_vars", {}) will return None instead of {}. This will cause env_vars.update(None) to raise a TypeError. Using runtime_env.get("env_vars") or {} ensures robustness against explicit None values.
| env_vars.update(runtime_env.get("env_vars", {})) | |
| env_vars.update(runtime_env.get("env_vars") or {}) |
## Description Run synchronous deployment methods in a thread pool by default so blocking synchronous I/O does not block the replica event loop. `RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0` retains the legacy behavior for deployments whose shared state is not thread-safe. | Environment variable | `master` | After this PR | | --- | --- | --- | | `RAY_SERVE_RUN_SYNC_IN_THREADPOOL` | OFF | ON | The opt-in warning has been emitted since [#48897](#48897) merged on November 26, 2024—667 days (about 22 months) before this default swap. This provided an extended migration period for users to make synchronous deployment code thread-safe or convert it to `async def`. The documentation now describes thread safety requirements and the opt-out. This default was previously enabled in [#61229](#61229) and reverted in [#61369](#61369). ## Related PRs These default changes are independent and can merge in any order: - [#66432 Enable HAProxy by default on Linux](#66432) - [#66434 Select request body forwarding by router](#66434) - [#66435 Apply Serve LLM replica performance defaults](#66435) ## Tests - `RAY_USE_UVLOOP=0 python -m pytest -q python/ray/serve/tests/test_replica_sync_methods.py`: 9 passed. The executor-introspection cases target the standard asyncio loop used by this Bazel test. - Updated the thread-pool test target description - Pre-commit, including Ruff, Black, Buildifier, mypy, Pyrefly, docs style, and import-order checks ## Duplicate search I searched open Ray PRs for this environment variable and found no active duplicate. ## AI assistance AI assistance was used for implementation and testing. The generated changes and test results require submitter review before the PR is marked ready. Signed-off-by: Seiji Eicher <[email protected]>
| configured_handle = default_handle.options(stream=True) | ||
| configured_handle = default_handle.options( | ||
| stream=True, | ||
| _by_reference=False, |
There was a problem hiding this comment.
nit: add a comment here to explain why
| name: os.environ.get(name, default) | ||
| for name, default in _RAY_SERVE_LLM_REPLICA_ENV_DEFAULTS.items() | ||
| } | ||
| env_vars.update(runtime_env.get("env_vars", {})) |
|
|
||
| DEFAULT_INGRESS_OPTIONS = { | ||
| "max_ongoing_requests": DEFAULT_MAX_ONGOING_REQUESTS, | ||
| "ray_actor_options": {"runtime_env": get_llm_serve_runtime_env()}, |
Signed-off-by: Seiji Eicher <[email protected]>
…eplica-defaults Signed-off-by: Seiji Eicher <[email protected]> # Conflicts: # python/ray/llm/_internal/serve/core/ingress/builder.py
## Description Run synchronous deployment methods in a thread pool by default so blocking synchronous I/O does not block the replica event loop. `RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0` retains the legacy behavior for deployments whose shared state is not thread-safe. | Environment variable | `master` | After this PR | | --- | --- | --- | | `RAY_SERVE_RUN_SYNC_IN_THREADPOOL` | OFF | ON | The opt-in warning has been emitted since [ray-project#48897](ray-project#48897) merged on November 26, 2024—667 days (about 22 months) before this default swap. This provided an extended migration period for users to make synchronous deployment code thread-safe or convert it to `async def`. The documentation now describes thread safety requirements and the opt-out. This default was previously enabled in [ray-project#61229](ray-project#61229) and reverted in [ray-project#61369](ray-project#61369). ## Related PRs These default changes are independent and can merge in any order: - [ray-project#66432 Enable HAProxy by default on Linux](ray-project#66432) - [ray-project#66434 Select request body forwarding by router](ray-project#66434) - [ray-project#66435 Apply Serve LLM replica performance defaults](ray-project#66435) ## Tests - `RAY_USE_UVLOOP=0 python -m pytest -q python/ray/serve/tests/test_replica_sync_methods.py`: 9 passed. The executor-introspection cases target the standard asyncio loop used by this Bazel test. - Updated the thread-pool test target description - Pre-commit, including Ruff, Black, Buildifier, mypy, Pyrefly, docs style, and import-order checks ## Duplicate search I searched open Ray PRs for this environment variable and found no active duplicate. ## AI assistance AI assistance was used for implementation and testing. The generated changes and test results require submitter review before the PR is marked ready. Signed-off-by: Seiji Eicher <[email protected]>
## Description Apply the performance-oriented replica defaults only to the default Ray Serve LLM path. General Serve defaults remain unchanged. | Serve LLM setting | `master` | After this PR | | --- | --- | --- | | OpenAI ingress model-handle transport | `ray.remote` | gRPC | | `RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD` | ON | OFF | | `RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP` | ON | OFF | The same-event-loop defaults are injected into `OpenAiIngress`, the vLLM-backed `LLMServer`, and the direct LLM routers. Explicit `runtime_env.env_vars` values take precedence. Serve LLM's `OpenAiIngress` configures its model deployment handles with `_by_reference=False`, selecting the gRPC transport directly at the point where those handles are created. This avoids changing generic Serve handle construction and does not add a Serve LLM opt-out. gRPC transport was introduced in [ray-project#59908](ray-project#59908). The same-event-loop defaults were previously proposed globally in [ray-project#62156](ray-project#62156); this PR limits them to Serve LLM. ## Related PRs These default changes are independent and can merge in any order: - [ray-project#66432 Enable HAProxy by default on Linux](ray-project#66432) - [ray-project#66434 Select request body forwarding by router](ray-project#66434) - [ray-project#66436 Run sync deployment methods in a thread pool](ray-project#66436) ## Tests - The live GPU reproducer below completed a real OpenAI-compatible request and observed only the consolidated `main` loop on both production replicas - Focused unit tests for LLMServer runtime env defaults and overrides, OpenAI ingress gRPC handles, and router runtime env propagation: 5 passed in 4.22s - The commit hooks passed Ruff, Black, pydoclint, docs style, import order, and the other applicable repository checks ## Local performance benchmark The short-request workload is intentionally framework-heavy while retaining a real vLLM engine. Lower latency is better; higher throughput is better. ```mermaid --- config: themeCSS: | .plot path { stroke-width: 5px !important; stroke-linecap: round; } .legend .markers path { stroke-width: 10px !important; stroke-linecap: round; stroke-dasharray: 0 100; } themeVariables: xyChart: plotColorPalette: "#0072B2, #CC79A7, #009E73, #D55E00" --- xychart-beta title "Effect of consolidating replica event loops" x-axis "Maximum concurrency" [64, 128, 256] y-axis "Requests per second" 0 --> 400 line "This PR: shared main loop" [264.0, 355.9, 368.8] line "Separate user-code thread only" [246.4, 325.8, 318.6] line "Separate router loop only" [255.4, 318.4, 305.7] line "Current default: both separate" [244.1, 302.3, 272.9] ``` Compared with the previous loop defaults, the new defaults increased throughput by 8%, 18%, and 35% at concurrency 64, 128, and 256, respectively. Both individual settings contributed; their relative impact varied with concurrency. The concurrency-256 values are the mean of two runs; the other points are one run each. The chart uses thick series lines and a dot legend with a color-blind-friendly palette in this order: blue, purple, green, and vermilion. | Chart series | `RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD` | `RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP` | | --- | ---: | ---: | | This PR: shared main loop | `0` | `0` | | Separate user-code thread only | `1` | `0` | | Separate router loop only | `0` | `1` | | Current default: both separate | `1` | `1` | ### Benchmark setup | Item | Configuration | | --- | --- | | Hardware | NVIDIA A10G (23 GiB) | | Software | Python 3.12, vLLM 0.29.0, Torch 2.13, HAProxy 2.8.25 | | Model | `Qwen/Qwen3-0.6B` on one vLLM-backed `LLMServer` replica | | Serve topology | One `OpenAiIngress` replica and one `LLMServer` replica; HAProxy was enabled with `RAY_SERVE_ENABLE_HA_PROXY=1` and received requests on port 8000; ingress-to-model handles used gRPC in both cases | | Workload | `vllm bench serve`, OpenAI completions endpoint, random input 32 tokens and output 8 tokens with `--random-range-ratio 0.5`, `--ignore-eos`, and `--temperature 0` | | Load | Infinite offered request rate at maximum concurrency 64, 128, and 256 | | Samples | 256 warmup requests, then 2,048 measured requests per point; deterministic seed `20260928`; 32,768 measured requests and zero failures across all four configurations | | Environment application | Each environment-variable combination was applied to both `OpenAiIngress` and `LLMServer` before their replicas started | As a control, an engine-heavy workload (1,024-token random input, 128-token random output, concurrency 64) delivered approximately 12 requests/s under either setting. This indicates that the difference above is in framework overhead and becomes hidden when model execution dominates. ## Duplicate search I searched open Ray PRs for each environment variable and found no duplicate of this Serve LLM-scoped change. ## AI assistance AI assistance was used for implementation and testing. The generated changes and test results require submitter review before the PR is marked ready. ## Live GPU reproducer The reproducer uses the Python 3.12 `ray[llm]` wheel built from this branch's merge base, then symlinks only `ray/llm` to the checkout. Serve, generated protobufs, and compiled extensions remain from the matching wheel. ```bash uv venv --python 3.12 /tmp/ray-66435-live-venv uv pip install --python /tmp/ray-66435-live-venv/bin/python \ "https://s3-us-west-2.amazonaws.com/ray-wheels/master/98d8084dbf690739ef2921c25918cd49aa1db556/ray-3.0.0.dev0-cp312-cp312-manylinux2014_x86_64.whl[llm]" SITE=/tmp/ray-66435-live-venv/lib/python3.12/site-packages/ray mv "$SITE/llm" "$SITE/llm-wheel" ln -s "$PWD/python/ray/llm" "$SITE/llm" RAY_USAGE_STATS_ENABLED=0 /tmp/ray-66435-live-venv/bin/python - <<'PY' import json import time import openai from prometheus_client.parser import text_string_to_metric_families import requests import ray from ray import serve from ray.serve.llm import LLMConfig, LLMServingArgs, ModelLoadingConfig, build_openai_app MODEL = "Qwen/Qwen3-0.6B" METRICS_URL = "http://127.0.0.1:9999/metrics" METRIC = "ray_serve_event_loop_monitoring_iterations_total" def replica_event_loops(): response = requests.get(METRICS_URL, timeout=5) response.raise_for_status() samples = [ sample for family in text_string_to_metric_families(response.text) for sample in family.samples if sample.name == METRIC and sample.labels.get("component") == "replica" and sample.labels.get("application") == "default" ] actor_to_deployment = { sample.labels["actor_id"]: sample.labels["deployment"] for sample in samples if sample.labels.get("loop_type") == "main" and ( sample.labels["deployment"] == "OpenAiIngress" or sample.labels["deployment"].startswith("LLMServer:") ) } return { deployment: sorted( { sample.labels["loop_type"] for sample in samples if sample.labels["actor_id"] == actor_id } ) for actor_id, deployment in actor_to_deployment.items() } try: ray.init( num_cpus=8, num_gpus=1, include_dashboard=False, _metrics_export_port=9999, _system_config={"metrics_report_interval_ms": 1000}, ) config = LLMConfig( model_loading_config=ModelLoadingConfig(model_id=MODEL, model_source=MODEL), engine_kwargs={ "max_model_len": 1024, "gpu_memory_utilization": 0.5, "enforce_eager": True, }, deployment_config={"num_replicas": 1}, ) serve.run(build_openai_app(LLMServingArgs(llm_configs=[config]))) client = openai.OpenAI( base_url="http://127.0.0.1:8000/v1", api_key="test", timeout=60 ) completion = client.chat.completions.create( model=MODEL, messages=[{"role": "user", "content": "Reply with: loop test passed"}], max_tokens=8, temperature=0, ) print("COMPLETION", completion.choices[0].message.content) deadline = time.time() + 90 while time.time() < deadline: loops = replica_event_loops() if len(loops) == 2: break time.sleep(1) else: raise RuntimeError("Timed out waiting for replica event-loop metrics") # Check three later scrapes so a separate loop cannot be hidden by a # just-created metric that has not reached the exporter yet. for _ in range(3): time.sleep(2) loops = replica_event_loops() assert len(loops) == 2 assert all(loop_types == ["main"] for loop_types in loops.values()) print("REPLICA_EVENT_LOOPS", json.dumps(loops, sort_keys=True)) finally: serve.shutdown() ray.shutdown() PY ``` The script builds the unmodified `build_openai_app` application, starts its real `OpenAiIngress` and vLLM-backed `LLMServer` deployments, sends an OpenAI-compatible completion request, and reads Serve's event-loop heartbeat metrics for those replica actors. Relevant output: ```text Deployment Options: ray_actor_options.runtime_env.env_vars: RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP: '0' RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD: '0' Ingress Options: ray_actor_options.runtime_env.env_vars: RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP: '0' RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD: '0' HTTP Request: POST http://127.0.0.1:8000/v1/chat/completions "HTTP/1.1 200 OK" COMPLETION <think> Okay, the user wants me REPLICA_EVENT_LOOPS {"LLMServer:Qwen--Qwen3-0_6B": ["main"], "OpenAiIngress": ["main"]} ``` The completion request initializes the ingress model handle before metrics are checked. A separate user-code loop or handle-router loop would emit `user_code` or `router` for the same replica actor. Both production replicas emit only `main`, showing that the environment settings take effect and consolidate those loops onto the replica event loop. --------- Signed-off-by: Seiji Eicher <[email protected]>
Description
Apply the performance-oriented replica defaults only to the default Ray Serve LLM path. General Serve defaults remain unchanged.
masterray.remoteRAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREADRAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOPThe same-event-loop defaults are injected into
OpenAiIngress, the vLLM-backedLLMServer, and the direct LLM routers. Explicitruntime_env.env_varsvalues take precedence.Serve LLM's
OpenAiIngressconfigures its model deployment handles with_by_reference=False, selecting the gRPC transport directly at the point where those handles are created. This avoids changing generic Serve handle construction and does not add a Serve LLM opt-out.gRPC transport was introduced in #59908. The same-event-loop defaults were previously proposed globally in #62156; this PR limits them to Serve LLM.
Related PRs
These default changes are independent and can merge in any order:
Tests
mainloop on both production replicasLocal performance benchmark
The short-request workload is intentionally framework-heavy while retaining a real vLLM engine. Lower latency is better; higher throughput is better.
--- config: themeCSS: | .plot path { stroke-width: 5px !important; stroke-linecap: round; } .legend .markers path { stroke-width: 10px !important; stroke-linecap: round; stroke-dasharray: 0 100; } themeVariables: xyChart: plotColorPalette: "#0072B2, #CC79A7, #009E73, #D55E00" --- xychart-beta title "Effect of consolidating replica event loops" x-axis "Maximum concurrency" [64, 128, 256] y-axis "Requests per second" 0 --> 400 line "This PR: shared main loop" [264.0, 355.9, 368.8] line "Separate user-code thread only" [246.4, 325.8, 318.6] line "Separate router loop only" [255.4, 318.4, 305.7] line "Current default: both separate" [244.1, 302.3, 272.9]Compared with the previous loop defaults, the new defaults increased throughput by 8%, 18%, and 35% at concurrency 64, 128, and 256, respectively. Both individual settings contributed; their relative impact varied with concurrency. The concurrency-256 values are the mean of two runs; the other points are one run each.
The chart uses thick series lines and a dot legend with a color-blind-friendly palette in this order: blue, purple, green, and vermilion.
RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREADRAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP00100111Benchmark setup
Qwen/Qwen3-0.6Bon one vLLM-backedLLMServerreplicaOpenAiIngressreplica and oneLLMServerreplica; HAProxy was enabled withRAY_SERVE_ENABLE_HA_PROXY=1and received requests on port 8000; ingress-to-model handles used gRPC in both casesvllm bench serve, OpenAI completions endpoint, random input 32 tokens and output 8 tokens with--random-range-ratio 0.5,--ignore-eos, and--temperature 020260928; 32,768 measured requests and zero failures across all four configurationsOpenAiIngressandLLMServerbefore their replicas startedAs a control, an engine-heavy workload (1,024-token random input, 128-token random output, concurrency 64) delivered approximately 12 requests/s under either setting. This indicates that the difference above is in framework overhead and becomes hidden when model execution dominates.
Duplicate search
I searched open Ray PRs for each environment variable and found no duplicate of this Serve LLM-scoped change.
AI assistance
AI assistance was used for implementation and testing. The generated changes and test results require submitter review before the PR is marked ready.
Live GPU reproducer
The reproducer uses the Python 3.12
ray[llm]wheel built from this branch's merge base, then symlinks onlyray/llmto the checkout. Serve, generated protobufs, and compiled extensions remain from the matching wheel.The script builds the unmodified
build_openai_appapplication, starts its realOpenAiIngressand vLLM-backedLLMServerdeployments, sends an OpenAI-compatible completion request, and reads Serve's event-loop heartbeat metrics for those replica actors.Relevant output:
The completion request initializes the ingress model handle before metrics are checked. A separate user-code loop or handle-router loop would emit
user_codeorrouterfor the same replica actor. Both production replicas emit onlymain, showing that the environment settings take effect and consolidate those loops onto the replica event loop.