Repository navigation
[Serve] Interpret num_replicas and autoscaling bounds as gang counts - #67507
hello-peter-tang wants to merge 10 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces validation to ensure that explicitly set autoscaling bounds (min_replicas, max_replicas, and initial_replicas) are multiples of the gang_size when gang scheduling is configured. The feedback highlights two key issues: a potential TypeError in the validation function if autoscaling_config is None, and a validation bypass in the deployment options method when only one of the configs is updated. Both issues can be resolved using the provided code suggestions.
|
Gang scheduling docs only says |
|
Thanks @GNITOAHC — pushed
microcheck is rerunning on the new head. |
`GangSchedulingAutoscalingPolicy` rounds each scaling decision up to a whole gang, but `AutoscalingState.apply_bounds` clips the decision to `[min_replicas, max_replicas]` without regard to gang size. If a bound is not a multiple of `gang_size`, the clip undoes the rounding: the scheduler then rejects the unaligned scale-up and the deployment fails, or a scale-down never completes and the target flaps every tick. The YAML schema already validates autoscaling bounds against `gang_size`, but the Python API skipped the check whenever `autoscaling_config` was set, so `@serve.deployment(...)` and `Deployment.options(...)` accepted the invalid configuration. Validate only the bounds the user explicitly set (defaults are merged in later and are safe, since decisions are rounded up), at both Python entry points, before `handle_num_replicas_auto()` merges defaults. Signed-off-by: hello-peter-tang <[email protected]>
- Return early when autoscaling_config is None so mypy can narrow the Optional union before indexing it. - Document the autoscaling bound requirement next to the num_replicas requirement and link to the Autoscaling section. Signed-off-by: hello-peter-tang <[email protected]>
f669815 to
1f4f036
Compare
…autoscaling config Fall back to the current config for options left at DEFAULT so that changing only gang scheduling or only autoscaling is still validated against the other. Move the validation into a module-level helper to stop leaking helper names into the locals()-derived user_configured_option_names. Signed-off-by: xiyan.tr <[email protected]>
… configs `handle_num_replicas_auto` merges `AutoscalingConfig.default()` and marks the merged bounds as explicitly set, so validating a deployment's stored config against gang_size treated `min_replicas=1`/`max_replicas=100` as user choices and made later `.options()` calls raise. Skip bounds equal to the autoscaling defaults when the config comes from the deployment, while still validating bounds passed in the current call. Signed-off-by: xiyan.tr <[email protected]>
9fc41b0 to
ded0746
Compare
) ## Description `AutoscalingConfig.target_ongoing_requests` is typed `Optional[PositiveFloat]`, so `None` passes validation, both in `@serve.deployment(autoscaling_config=...)` and as `target_ongoing_requests: null` in a config file. The readers I checked all expect a number: the default policy computes `config.get_target_ongoing_requests() * num_running_replicas` (`autoscaling_policy.py:337`), the config-file override path compares `max_ongoing_requests < get_target_ongoing_requests()` (`application_state.py:2087`), and the autoscaling state sets a gauge to it (`autoscaling_state.py:662`). The first raises a `TypeError` on every controller loop iteration. The `Optional` type and the `None` mapping in `from_proto` date from the rename in #43454, when `None` meant "fall back to `target_num_ongoing_requests_per_replica`". #46392 removed that field and the fallback, so `None` has had no meaning since. The failure is not limited to the misconfigured app. I deployed a healthy app, then an app with `target_ongoing_requests=None`, then a second healthy app, on a local cluster on master. The controller logged 2,217 `TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'` errors in about 4 minutes. The second healthy app never showed up in the controller log, and `serve.status()` did not return before the script was stopped after 4 minutes. This was one run, with the script below. Why one deployment's policy exception stalls the whole loop is a separate question that this PR does not change. Behavior change: `@serve.deployment(autoscaling_config={..., "target_ongoing_requests": None})` now raises `ValidationError` when the class is decorated, instead of being accepted. A `null` in a config file still passes schema parsing, because the schema keeps `autoscaling_config` as a plain dict, and the app fails when it is built, as it already did on master, now with a `ValidationError` from `AutoscalingConfig`. One setup that works today would break: a deployment defined in Python with a custom autoscaling policy that never reads this field. The gauge skips `None`, and the `application_state.py` comparison only runs for config files, so that setup runs with `None` on master. A proto with 0.0, which a client cannot set on purpose because the field must be positive, now gets the default of 2 instead of `None`. A config object that already holds `None` and is restored by unpickling is not revalidated (checked with `cloudpickle`), so it behaves as on master. Changes: - `config.py`: type the field as `PositiveFloat`, so `None` is rejected when an `AutoscalingConfig` is built (when the class is decorated, or when a config-file app is built): `target_ongoing_requests: Input should be a valid number [type=float_type, input_value=None, input_type=NoneType]`. - `_private/config.py`: `from_proto` replaced a 0.0 `target_ongoing_requests`, the proto3 default when the field is not set, with `None`. It now drops the key so the field default (2) applies, the same way the `request_router_config` fields above it are handled. ## Related issues None. I searched issues and PRs for "target_ongoing_requests None", "target_ongoing_requests null" and "autoscaling NoneType" and found no report. Open PRs that edit `serve/config.py` or `_private/config.py` (#67507, #67440, #66855, #66798, #66580, #66512) do not change this field's type or its `from_proto` handling. ## Additional information Tests added to `python/ray/serve/tests/unit/test_config.py`: - `test_target_ongoing_requests_none_rejected`: `AutoscalingConfig(target_ongoing_requests=None)`, and the same value passed through `DeploymentConfig`, raise `ValidationError`. - `test_target_ongoing_requests_proto_default`: a proto without the field gives the default of 2, and a value of 7 survives a proto round trip. Commands, run locally on macOS arm64 with the nightly wheel, `setup-dev.py` and Pydantic 2.14.2: - `pytest python/ray/serve/tests/unit/test_config.py -k target_ongoing`: 3 passed (the two new tests and the existing `test_target_ongoing_requests`). On master 541bd56: the two new tests fail. - `pytest` on `test_config.py`, `test_schema.py`, `test_autoscaling_policy.py`, `test_application_state.py`, `test_deployment_state.py` and `test_autoscaling_metrics_merge.py`, all in `python/ray/serve/tests/unit/`: 751 passed, 12 skipped. - `pre-commit run` on the changed files: passed. <details><summary>Repro script (run on master)</summary> ```python import time, ray from ray import serve from ray.serve.api import _run ray.init(num_cpus=8, include_dashboard=False, log_to_driver=False) @serve.deployment(ray_actor_options={"num_cpus": 0}) class Ok: def __call__(self): return "ok" @serve.deployment(autoscaling_config={"min_replicas": 1, "max_replicas": 3, "target_ongoing_requests": None}, ray_actor_options={"num_cpus": 0}) class Bad: def __call__(self): return "bad" serve.run(Ok.bind(), name="ok1", route_prefix="/ok1") _run(Bad.bind(), name="bad", route_prefix="/bad", _blocking=False) time.sleep(3) _run(Ok.bind(), name="ok2", route_prefix="/ok2", _blocking=False) time.sleep(15) st = serve.status().applications print({k: str(v.status) for k, v in st.items()}) serve.shutdown(); ray.shutdown() ``` </details> Signed-off-by: William Guo <[email protected]>
|
I merged I could not read the failure itself — Could a maintainer re-run |
There was a problem hiding this comment.
thanks for fixing this! i think we should take this opportunity to adjust the gang scheduling API -- when GangSchedulingConfig is set, num_replicas under DeploymentConfig and min_replicas / initial_replicas / max_replicas under AutoscalingConfig should refer to the number of gangs, not the number of serve replicas (# serve replicas = # gangs * gang_size) so that we don't have to worry about unaligned autoscaling bounds. this would be a larger change and would affect serve LLM's DP deployment too.
| ) | ||
|
|
||
|
|
||
| def validate_gang_scheduling_options( |
There was a problem hiding this comment.
serve deploy with YAML skips this, because override_deployment_info never calls .options(). can we validate the bounds under the YAML path and add tests accordingly?
There was a problem hiding this comment.
Added YAML-path validation in override_deployment_info (13b68c8), against the resulting gang and autoscaling configs. New tests in test_application_state.py: test_override_gang_config_rejects_unaligned_code_bounds and test_override_autoscaling_config_rejects_unaligned_yaml_bounds.
| assert f._deployment_config.autoscaling_config.min_replicas == 4 | ||
| assert f._deployment_config.autoscaling_config.max_replicas == 8 | ||
|
|
||
| def test_gang_scheduling_config_decorator_does_not_pollute_option_names(self): |
There was a problem hiding this comment.
why do we need this test? this seems low-signal.
| ``` | ||
|
|
||
| This creates 2 gangs of 4 replicas each resulting in a total of 8 replicas. Partial gang isn't allowed, and therefore `num_replicas` must be a multiple of `gang_size`. | ||
| This creates 2 gangs of 4 replicas each resulting in a total of 8 replicas. Partial gang isn't allowed, and therefore `num_replicas` must be a multiple of `gang_size`. With autoscaling, the autoscaling bounds (`min_replicas`, `max_replicas`, and `initial_replicas`) must also be multiples of `gang_size`; see [Autoscaling](#autoscaling). |
| ): | ||
| f.options(autoscaling_config={"min_replicas": 1}) | ||
|
|
||
| def test_gang_scheduling_config_options_do_not_pollute_option_names(self): |
There was a problem hiding this comment.
don't think we need this
| assert f2._deployment_config.autoscaling_config.min_replicas == 4 | ||
| assert f2._deployment_config.autoscaling_config.max_replicas == 8 | ||
|
|
||
| @pytest.mark.parametrize( |
There was a problem hiding this comment.
do we need all these tests? I'd keep one only if it provides meaningful test coverage + doesn't duplicate coverage with others.
There was a problem hiding this comment.
Collapsed to a single case covering min and max in 13b68c8. Kept the AutoscalingConfig instance test because it exercises the other branch of the validator.
| """Validate that explicitly set autoscaling bounds are multiples of gang_size. | ||
|
|
||
| Bounds left at their defaults are not checked: gang scheduling rounds the | ||
| autoscaler's decisions up to whole gangs, so the defaults are safe. | ||
|
|
||
| Set ``ignore_default_bounds`` when validating a config read back from a | ||
| deployment. ``handle_num_replicas_auto`` merges ``AutoscalingConfig.default()`` | ||
| into that config, which marks the default bounds as explicitly set even | ||
| when the user left them unset. | ||
| """ |
There was a problem hiding this comment.
in general, let's rewrite all docstrings to be shorter and clearer. claude isn't good at writing :(
|
btw microchecks should be publicly available. are you not able to view it? |
Validate autoscaling bounds against the resulting gang config in override_deployment_info, so `serve deploy` with YAML is covered too. Also trims the new docstrings and removes the low-signal tests and the duplicate autoscaling note flagged in review. Signed-off-by: hello-peter-tang <[email protected]>
|
Thanks for the detailed pass. I addressed the concrete items in 13b68c8:
On the larger proposal of making gang counts the unit for |
|
@jeffreywang88 on microchecks being public: I can open https://buildkite.com/ray-project/microcheck/builds/59041, but while signed out I only get the build-level summary — the Build #59041 currently shows 2 failed jobs in 1 failed step (21 steps passed), and the same step was red on the Nov 8 head as well. Locally Could you share the failing step/test name from #59041 when you get a chance? That would tell us whether it's the sharded serve suite hitting existing flakes or something in this change. |
@hello-peter-tang ray/python/ray/serve/config.py Lines 1408 to 1409 in 96600b8 |
|
microcheck failure: |
The pre-commit black hook reformats AutoscalingConfig(min_replicas=3, max_replicas=9) onto a single line, which failed the lint step in CI. Signed-off-by: hello-peter-tang <[email protected]>
|
Found the failing jobs — they weren't serve tests. The two failed jobs were |
When gang scheduling is enabled, DeploymentConfig.num_replicas and the min/initial/max autoscaling bounds now count gangs instead of serve replicas. The controller converts gang counts to replica counts when it computes target replica counts, so the API no longer needs to reject gang-unaligned values. Remove the multiple-of-gang_size validation from the decorator, options, YAML schema, and app override paths, and update DPServer to pass user replica counts through unchanged (defaulting to one DP gang). Signed-off-by: hello-peter-tang <[email protected]>
|
Implemented the gang-count semantics suggested above in 6849c7b: when Also folded in the LLM DP change: @jeffreywang88 @YidaWeng — note this may overlap with #68056 (capacity-adjusted replica alignment); happy to reconcile if that lands first. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 3 potential issues.
Reviewed by Cursor Bugbot for commit 6849c7b. Configure here.
Signed-off-by: hello-peter-tang <[email protected]>
Signed-off-by: hello-peter-tang <[email protected]>
|
premerge #76956 failed on |
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |

Why are these changes needed?
With gang scheduling,
GangSchedulingAutoscalingPolicyrounds the autoscaler's decision up to a whole gang, butapply_bounds()clips to[min_replicas, max_replicas]without regard to gang size. When a bound isn't a multiple ofgang_size, the clip undoes the rounding and the deployment can fail or flap (see #67494):min = max = 3withgang_size = 2: the target is held at 3, rejected by the scheduler on every tick, and the deployment eventually fails withDEPLOY_FAILED.min = 3, max = 4: a scale-down can never stop a partial gang, so the target flaps between 3 and 4.Rather than adding more validation and special-case logic on every entry point (decorator,
.options(), YAML schema,serve deployoverrides), this follows the reviewer's suggestion for the alphaGangSchedulingConfigAPI: make the replica counts themselves gang counts.What is the change?
When
gang_scheduling_configis set,DeploymentConfig.num_replicasandAutoscalingConfig.min_replicas/initial_replicas/max_replicasrefer to the number of gangs, not the number of serve replicas. The total number of replicas is# gang_count * gang_size.DeploymentStateManager.deploycapacity-adjusts the gang count, then multiplies bygang_size.DeploymentAutoscalingStateconverts the initial target and the lower/upper bounds from gangs to replicas before the policy sees them. Autoscaling decisions and contexts remain in replica units, soGangSchedulingAutoscalingPolicystill rounds decisions up to whole gangs.world_sizeis computed asnum_replicas * gang_size(total replicas).gang_sizechecks (and their helpers) are removed from the decorator,Deployment.options(),DeploymentSchema, and theserve deployoverride path. Bounds no longer need to be gang-aligned.serve deploy: stored configs keep gang counts, so the status output shows gang counts as configured.DPServer.get_deployment_optionsno longer multipliesnum_replicasor the autoscaling bounds bydata_parallel_size; the user's values are already gang counts. A deployment withoutnum_replicas/autoscaling still defaults to one DP gang. The DP autoscaling docs already described bounds as numbers of DP groups.Related issue number
Part of #67494
Note: #68056 ("Align capacity-adjusted replica counts with gang size") covers related capacity-adjusted rounding and may overlap; happy to consolidate.
Tests
test_config.py,test_schema.py,test_application_state.py,test_deployment_state.py,test_autoscaling_policy.py: all pass locally (373 + 138 + 267 + 374 passed, one pre-existing environmental failure intest_deployment_info_keeps_markerdue to a running Ray cluster version mismatch).serve deploytests updated to pass gang counts.black(22.10.0),ruff,mypy(serve allowlist), andpyrefly(serve allowlist) clean on the touched files; the only pyrefly diagnostic is a pre-existing protobufFieldDescriptor.labelerror.AI assistance: developed with an AI coding agent; the human submitter reviewed the diff and ran the tests above.