Repository navigation
[Serve] Let multiplexed models fill batches independently - #64595
angryturtlebro wants to merge 9 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request refactors Ray Serve's batching mechanism for multiplexed models by replacing the single-queue sub-batching approach with separate, per-model queues managed dynamically within _LazyBatchQueueWrapper. Idle model-specific queues are automatically cleaned up to conserve resources. A critical race condition was identified in the is_idle() check, where a queue could be prematurely shut down and cancel a background task while it is actively accumulating a batch in wait_for_batch(). A fix is suggested to track the currently accumulating batch and include it in the idle check.
Route multiplexed Serve requests through per-model batch queues so each model can fill its own batch instead of sharing one queue with other model IDs. Preserve the global max_concurrent_batches limit across model queues, and add regression coverage for full per-model batches, concurrency limits, and idle queue cleanup. Signed-off-by: angryturtlebro <[email protected]>
e3f60e2 to
fdedbe0
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit fdedbe0. Configure here.
Signed-off-by: angryturtlebro <[email protected]>
|
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. |
|
Would still like this looked at |
## Description When a single-input batched handler uses `batch_size_fn`, passing its input by keyword leaves no positional argument for `_compute_batch_size` to read. The resulting `IndexError` escapes batch assembly. A local Serve deployment reproduces positional success, keyword timeout, then another positional timeout because the batching task has stopped. Read the first payload value from the existing flattened argument representation, after `self` has already been removed. This preserves successful positional calls and supports a single explicitly supplied input passed by keyword, including keyword-only parameters. Existing multi-input positional calls remain supported. Multi-input keyword calls and variadic keyword (`**kwargs`) handlers are rejected before queueing because their flattened keyword order is not stable across a batch, and omitting a defaulted input is rejected because there is no explicit value to size. These errors affect only the caller and do not stop the batching worker. General callback-error isolation remains outside this change. The tests exercise functions and bound methods, coroutine and streaming handlers, mixed positional/keyword arrivals in both orders, keyword-only signatures, oversized keyword input recovery, omitted defaults, second-keyword-first ordering, variadic keyword signatures, positional multi-input compatibility, and worker survival after invalid requests. The batching guide describes the supported call forms. ## Related work and attribution This addresses the finding already raised in [the review of #59059](#59059 (comment)); it is not a new discovery. Searches for custom sizing and keyword/kwargs fixes found no matching open PR. #66141 fixes callback-error isolation and explicitly excludes keyword compatibility. #64595 restructures per-model queues but leaves this payload extraction unchanged; it touches the same file and may require rebasing. ## Validation macOS arm64, Python 3.12.14, official Ray `3.0.0.dev0` wheel at `39882c660a6d7b579e39d724ce85d9074d6180fb`, with the branch's current Python Serve sources linked into the environment. Because the branch includes newer master changes, the source and wheel revisions are not exact; the focused suite required a runner-local shim for a newer test-fixture helper. ```bash .venv/bin/python - <<'PYTEST' import ray, pytest raise SystemExit(pytest.main([ '--import-mode=importlib', 'python/ray/serve/tests/unit/test_batching.py', '--tb=short', '-q', ])) PYTEST ``` - 15 keyword regressions from the original change fail on the original implementation; seven review-fix cases fail before their respective fixes. - Full batching unit file: **87 passed**, including 26 cases added by this PR. - Real CPU-only local Serve deployment: positional and keyword requests succeed; invalid omitted-default, multi-input-keyword, and variadic-keyword calls return bounded `TypeError`s; a subsequent valid request succeeds and all batching tasks remain alive. - All hooks applicable to the changed files pass; `git diff --check` passes. Vale is excluded for this documentation path and its environment separately failed to compile on this Mac because the C++ `cassert` header was unavailable. - The test runner prints pending-task teardown diagnostics that were already present in the earlier 61-test baseline; the run exits successfully. The local demo logs include the existing batch-size/ongoing-request advisory and Ray shutdown messages. - Independent Astra Low reviews of each exact review-fix diff found no actionable issues in argument mapping, exception propagation, unresolved futures, cancellation, streaming, or worker survival. No GPU performance, full-Ray suite, docs build, or upstream CI result is claimed. --------- Signed-off-by: Jayesh Suyal <[email protected]> Signed-off-by: YashwanthRanjanSingaravel <[email protected]> Co-authored-by: YashwanthRanjanSingaravel <[email protected]>
…exed-batching Signed-off-by: angryturtlebro <[email protected]> # Conflicts: # python/ray/serve/batching.py
Restore master's batch formation logic while retaining current-batch tracking and aggregate queue-length reporting. Use the current batch for idle checks and cancellation, require every queue's batching task to be alive, and snapshot queues in the batch setters. Simplify the tests and add coverage for queue mutation during a setter. Signed-off-by: angryturtlebro <[email protected]>
|
Updated this PR:
Ready for review. |
|
Hi @abrarsheikh I noticed you working on other pr's related to this. Would you be able to take a look or point me in the right direction for this work? Thanks! |
|
@harshit-anyscale @akyang-anyscale |
|
@abrarsheikh Is there anything I need to do for this to get reviewed? Happy to do more work if needed just not sure how to get a reviewer added |
|
@YashwanthRanjanSingaravel @johntaylor-cell could you review this please |
…#67877) ## Description `@serve.batch` forms a batch first and takes a `max_concurrent_batches` permit afterwards. `_process_batches` calls `wait_for_batch()`, then starts a task that waits on the semaphore in `_process_sub_batches` ([`batching.py` L498-L532](https://github.com/ray-project/ray/blob/17e1131/python/ray/serve/batching.py#L498-L532)). While every permit is in use, the loop keeps closing a batch each time `batch_wait_timeout_s` passes, and each of those batches then waits for a permit holding only the requests that arrived in that window. Requests that arrive while the replica is busy are therefore run in many small batches, one after another, instead of together. With `max_batch_size=10`, `batch_wait_timeout_s=0.01`, `max_concurrent_batches=1` and a batch function that takes 0.5 s, one request followed by 10 requests 30 ms apart (script below): | | batch sizes | time for all 11 requests | |---|---|---| | master 17e1131 | `[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]` | 5.53 s | | this PR | `[1, 10]` | 1.02 s | This PR takes the permit in `_process_batches` before calling `wait_for_batch()`, and releases it in `_handle_completed_task`. Requests that arrive while every permit is in use stay in the queue, and the next batch is formed from all of them when a permit is free. `_process_sub_batches` still runs all sub-batches of one batch under one permit. Taking the permit first would make one case slower if nothing else changed: `wait_for_batch()` starts the `batch_wait_timeout_s` timer when it takes the first request from the queue, so a request that waited for a permit would then wait for the timeout again. With `batch_wait_timeout_s=1.0` and a batch function that takes 0.5 s, a lone request arriving 0.2 s into the first batch's run finished 1.81 s after it arrived, against 1.50 s on master. To keep master's timing, each request now records when it was queued (`_SingleRequest.enqueue_time`), and the timeout counts from the first request's arrival. With that change the same request finishes in 1.50 s, as on master, and a request that already waited longer than the timeout goes out with whatever else is queued as soon as a permit is free. The batch wait time metric still measures from when the batch starts forming, as before. If `wait_for_batch()` or starting the batch task raises, or the loop is cancelled while it waits, the permit is released before the exception propagates. A batch task that fails or is cancelled releases its permit in its done callback, because asyncio runs done callbacks for cancelled tasks too, including a task cancelled before it starts. While the queue is empty, the loop now holds one permit as it waits for the first request. That permit becomes the next batch's permit, so no more than `max_concurrent_batches` batches run at once, as before. Holding it while idle delays nothing, because a batch cannot start without a permit. ## Related issues None found. Two open PRs change the same loop: #64040 replaces the semaphore with an `anyio.CapacityLimiter` to add a setter, and #64595 rewrites `_process_batches` for multiplexed queues and acquires the semaphore after `wait_for_batch()`. This PR conflicts with both. With #64595's semaphore shared across queues, a loop that holds a permit while its queue is empty would block the other queues, so that PR would need the acquire placed differently. I can rebase onto either one if it lands first. ## Additional information Tests added to `python/ray/serve/tests/unit/test_batching.py`: - `test_requests_arriving_while_batches_run_form_one_batch`: one request starts a batch that holds the only permit, and 5 more requests arrive 50 ms apart (longer than `batch_wait_timeout_s`). The batch sizes must be `[1, 5]`. On master they are `[1, 1, 1, 1, 1, 1]`. - `test_batch_timeout_counts_time_waiting_for_a_permit`: a request that waited 1.2 s for a permit, with `batch_wait_timeout_s=1.0`, starts less than 0.5 s after the permit is released. It passes on master, and fails if the permit is taken first without the timer change, where the batch starts 1.0 s after the release. The 0.5 s limit leaves room for slow CI machines. Commands, run locally on macOS arm64 with the nightly wheel and `setup-dev.py`: - `pytest python/ray/serve/tests/unit/test_batching.py`: 93 passed. On master 17e1131: 92 passed, and `test_requests_arriving_while_batches_run_form_one_batch` fails. - `pytest python/ray/serve/tests/unit` (without `test_http_util.py`, which does not import in my setup): 273 tests fail on this branch and 274 on master. They are the same tests except for the new one, which fails only on master. Most of them are in `test_deployment_state.py`. - I could not run `python/ray/serve/tests/test_batching.py`. Its first test hangs in my setup on master as well (stopped after 4 minutes), so I am relying on CI for it. - `pre-commit run` on the changed files: passed. <details><summary>Repro script</summary> ```python import asyncio, time from typing import List from ray import serve import ray.serve.context from ray.serve._private.common import DeploymentID, ReplicaID from ray.serve._private.config import DeploymentConfig ray.serve.context._set_internal_replica_context( replica_id=ReplicaID(unique_id="t", deployment_id=DeploymentID(name="t")), servable_object=None, _deployment_config=DeploymentConfig(max_ongoing_requests=100), rank=0, world_size=1) sizes = [] @serve.batch(max_batch_size=10, batch_wait_timeout_s=0.01, max_concurrent_batches=1) async def f(xs: List[int]): sizes.append(len(xs)) await asyncio.sleep(0.5) return xs async def main(): tasks = [asyncio.create_task(f(0))] await asyncio.sleep(0.05) # batch 1 is now executing (0.5 s) for i in range(1, 11): # 10 requests arrive while it runs tasks.append(asyncio.create_task(f(i))) await asyncio.sleep(0.03) await asyncio.gather(*tasks) print("batch sizes:", sizes) t0 = time.perf_counter() asyncio.run(main()) print(f"all 11 requests done in {time.perf_counter() - t0:.2f} s") ``` </details> --------- Signed-off-by: William Guo <[email protected]>
| self.max_concurrent_batches = max_concurrent_batches | ||
| self.handle_batch_func = handle_batch_func | ||
| self.batch_size_fn = batch_size_fn | ||
| self.semaphore = asyncio.Semaphore(max_concurrent_batches) |
There was a problem hiding this comment.
With the default max_concurrent_batches=1, this runs batches for different models one at a time, while master runs them concurrently. 3 models: 3.1s vs 1.1s. Give each queue its own semaphore (semaphore=None in get_queue) so the limit is per model?
There was a problem hiding this comment.
Fixed, each model queue has its own semaphore now, so max_concurrent_batches is per model ID and different models run concurrently again with the default of 1. This is also required after merging master. #67877 takes the permit before forming a batch, so with a shared semaphore an idle model queue would block every other model.
Added test_multiplexed_batch_queues_limit_concurrency_per_model for it, and reverted the max_concurrent_batches=3 I had added to the context-isolation test. The per-model limit is in the batch() docstring and both docs pages.
| """Returns the _BatchQueue for a multiplexed model ID.""" | ||
| queue_key = multiplexed_model_id or "" | ||
| if queue_key not in self._queues: | ||
| self._queues[queue_key] = _BatchQueue( |
There was a problem hiding this comment.
This logs the max_ongoing_requests warning on every model queue creation, so on almost every request when traffic is sparse (20× vs 1× on master with defaults). Log it once from the wrapper?
There was a problem hiding this comment.
Moved this to the wrapper. It checks when it creates its first queue and on later set_max_batch_size calls, and only warns when max_batch_size * max_concurrent_batches is over max_ongoing_requests. Queues the wrapper creates don't log it, so a queue recreated after cleanup doesn't warn again. test_wrapper_warns_about_max_ongoing_requests_once covers multiple model queues, a recreated queue, and the setter with no queues left.
|
|
||
| if self._queue is not None: | ||
| self._queue.set_max_batch_size(new_max_batch_size) | ||
| # Snapshot to avoid iterating a dictionary that queue creation or |
There was a problem hiding this comment.
Nit: this loop and comment are repeated in set_batch_wait_timeout_s, and if not self._queues: _ = self.queue is repeated in _is_batching_task_alive and _get_handling_task_stack. Pull each into a helper?
There was a problem hiding this comment.
Added _queues_or_default() for the repeated default-queue lines and removed the setter loops. The wrapper and its queues share one _BatchConfig now, so a setter updates existing queues, new queues, and a queue being created at the same time. A batch that's already forming keeps the size and timeout it started with. This also fixes the reconfigure race from the limitations section of the description.
There was a problem hiding this comment.
Nice, very useful change that will positively affect performance. I investigated a simpler approach that does not create and destroy queues. It uses one queue and per-model lists, but that required a large edit to this PR, adding significant risk. Totally independent queues seems like the cleanest approach, but the shared semaphore is problematic. I added a related comment inline to help relax this.
Otherwise, there is no e2e test that covers per-model filling. The three multiplex + batching tests in test_multiplex.py pass on master too. Add one with interleaved model IDs that asserts full per-model batches?
I would also like to see a test that covers queue lifecycle, namely a model queue recreated after cleanup. With sparse traffic this is what happens on most requests, and it’s the riskiest lifecycle step. The old loop is cancelled, a new queue is created, and leftover callbacks have to do nothing. A cheap unit test covers it.
And finally, I would like to see a test that that waits for a slot before forming the next batch. This changes behavior for every @serve.batch user, so a unit test should pin it down. For example, with max_concurrent_batches=1, requests that arrive while a batch waits go into the next, fuller batch.
Signed-off-by: angryturtlebro <[email protected]>
Give each model queue its own semaphore so max_concurrent_batches applies per model ID, and log the max_ongoing_requests warning once from the wrapper. Share one batch config and one set of batch metrics across the wrapper's queues, so setters reach queues created at any time and creating a queue stays cheap. Add an e2e test for full per-model batches, and unit tests for queue recreation after cleanup, per-model concurrency, waiting for a permit, cancellation, shared metrics and the setters. Document the per-model concurrency limit. Signed-off-by: angryturtlebro <[email protected]>
|
Thanks for the review @johntaylor-cell! Updated this PR:
Benchmarks All runs go through a single replica with a With 1 s of work per batch (
This PR was faster in every run. On master each model mostly gets batches of 1, and the next shared batch waits for all of the current one's sub-batches. With this PR each model fills and runs its own batches. The sleeps overlap across models, so this shows batching and scheduling, not inference on a shared accelerator. Cost of cleaning up and recreating queues A model's queue is removed once it's idle, so with sequential requests for a model ID this PR creates a new queue for every request. Creating the metric objects was most of that cost, so the wrapper now shares one set across its queues. Metric names and labels didn't change (there's no model-ID label), and the queue-length gauge counts queued requests across all the wrapper's queues, same as master's single queue. One change is that To measure the overhead, the handler does nothing and
Recreating a queue shows up mostly in p99, which is typically 20–35 µs higher with model IDs. A microbenchmark without Serve puts creating and removing a queue at roughly 9 µs per request. The groups of 64 reach the replica spread out, so most of those requests still find their model's queue gone. Queues also stick around while their model has traffic. With 4 models, 16 clients each sending back to back for 10 s with 0.1 s of work per batch, each model kept one queue for all 99 of its batches, and the queues were only removed after traffic stopped. Out of date in the PR description
|
|
|
||
| # Cancel once the request is dequeued into a batch that is still filling. | ||
| await async_wait_for_condition( | ||
| lambda: bool(queue._current_batch), retry_interval_ms=1 |
There was a problem hiding this comment.
On Python 3.10/3.11 this can hang. If the poll fires while the loop is still in its first wait_for with the event already set, wait_for swallows the cancel and await queue._handle_batch_task never returns. I t hung 1 in 160 runs under load. Poll bool(queue._current_batch) and not queue.requests_available_event.is_set() instead?
There was a problem hiding this comment.
Thanks, good catch. Fixed with that poll. I ran it 300 times with every core busy: the old version hung 13 times and the new one passed all 300.
| queue.put(request) | ||
| futures.append(request.future) | ||
|
|
||
| await async_wait_for_condition(lambda: bool(recorded), retry_interval_ms=1) |
There was a problem hiding this comment.
Same race as above. _shut_down_queues can hang if model-a’s loop is still in its first wait_for. Maybe poll len(recorded) >= 2 instead?
There was a problem hiding this comment.
Fixed, it now polls len(recorded) >= 2. Same check: the old version hung 31 times in 300 runs and the new one passed all 300.
| start_times.extend(queue.curr_iteration_start_times.values()) | ||
| return _RuntimeSummaryStatistics(start_times) | ||
|
|
||
| async def _is_batching_task_alive(self) -> bool: |
There was a problem hiding this comment.
These three debug helpers now cover every model queue, but tests only use the default queue, so reverting any of them to default-only still passes. Add a test with two blocked model queues that checks 2 start times, 2 stacks, and _is_batching_task_alive() False after one queue’s loop is cancelled?
There was a problem hiding this comment.
Added test_debug_helpers_cover_every_model_queue with those checks. It fails if I revert any one of the three helpers to default-only.
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| @pytest.mark.parametrize( |
There was a problem hiding this comment.
As a nit, this parametrize list is repeated at line 756; hoist it into a constant like METRIC_ATTRIBUTES?
There was a problem hiding this comment.
Done, both setter tests use BATCH_SETTER_CASES now.
johntaylor-cell
left a comment
There was a problem hiding this comment.
Thanks, everything from my last review is addressed. Please update the PR description as it still describes the shared semaphore, forming a batch before taking a permit, and the reconfigure limitation.
Signed-off-by: angryturtlebro <[email protected]>
|
Thanks again for the review! Made a new commit based on your latest comments and updated the description as requested! |
| task = asyncio.create_task(self._process_batch_inner(func, batch)) | ||
| except BaseException as e: | ||
| self.semaphore.release() | ||
| if isinstance(e, asyncio.CancelledError): |
There was a problem hiding this comment.
Production never cancels this loop while it holds dequeued requests: shutdown() only runs on idle queues, a busy queue stays in queues (so no del), and replica shutdown drains and exits without cancelling user-loop tasks. So this block and both test_cancelled_batch_queue* tests only cover a hypothetical. Drop them?
There was a problem hiding this comment.
Agreed, removed the block and both tests.
| del self._queues[queue_key] | ||
| queue.shutdown() | ||
|
|
||
| def _total_queue_length(self) -> int: |
There was a problem hiding this comment.
The description says serve_batch_queue_length reports queued requests across all queues, but it’s only set while some queue is filling a batch. With one model’s permit busy and 5 requests queued, it reports 0. Also record it on enqueue and after forming a batch?
There was a problem hiding this comment.
Good catch. It's now also recorded after a batch forms, and on enqueue while the queue waits for a permit. test_queue_length_gauge_recorded_on_enqueue_and_after_batch covers your example.
| new_queue.put(request) | ||
| await async_wait_for_condition(lambda: bool(new_queue.tasks), retry_interval_ms=1) | ||
|
|
||
| # A leftover idle notification from the old queue leaves the new one alone. |
There was a problem hiding this comment.
This can’t happen in production. A removed queue has no tasks and its loop dies on the cancel (Queue.get and Semaphore.acquire re-raise), so it never calls _on_idle again. I was wrong to ask for this step, drop these four lines?
There was a problem hiding this comment.
Removed them, along with the blocking request that only that step needed.
Your comment prompted me to check for other code that production never hits, and as a result I dropped the _handle_batch_task is None checks in the debug helpers. @serve.batch always passes a handler, so queues it creates always have a background task.
johntaylor-cell
left a comment
There was a problem hiding this comment.
Thanks, all four addressed. Another pass found a couple more.
Signed-off-by: angryturtlebro <[email protected]>
|
Made it through your new findings! |

Description
This is a follow-up to #59334 for the batching + multiplexing behavior reported in #56633.
#59334 prevents requests for different multiplexed model IDs from being processed in the same user batch, but requests still enter a shared batch queue before being split by model ID. When multiple models receive traffic concurrently, that shared queue can fill with requests for different models, so each model receives only a partial sub-batch.
This PR gives each multiplexed model ID its own batch queue, so each model fills its own batch up to
max_batch_sizeor until its ownbatch_wait_timeout_s. Requests without a model ID use a default queue, as before.Related issues
Related to #56633
Follow-up to #59334
Additional information
How it works
_LazyBatchQueueWrapperkeeps one_BatchQueueper model ID. Each queue has its own semaphore, somax_concurrent_batchesapplies to each model ID._BatchConfig, soset_max_batch_sizeandset_batch_wait_timeout_supdate existing queues, new queues, and a queue being created at the same time. A batch that's already forming keeps the size and timeout it started with.serve_batch_queue_lengthreports the requests still queued across all the wrapper's queues, excluding requests already dequeued into a batch.max_ongoing_requestswarning, when it applies, on its first queue and onset_max_batch_sizecalls. A recreated model queue doesn't log it again.Behavior changes
max_concurrent_batchesnow applies to each model ID. Previously, the sub-batches split from one mixed batch shared a single permit. Now the total across models can exceedmax_concurrent_batches, even at the default of 1. I updated thebatch()docstring and both docs pages to say so.serve_batch_wait_time_msis recorded once per model batch instead of once per shared batch.serve_batch_queue_lengthis also recorded after a batch forms, and on enqueue while the queue waits for a permit. On master it is only recorded while a batch is filling, so it goes stale during that wait. In a microbenchmark with metrics on, this adds about 2 µs of CPU per request for back-to-back sequential requests and for 100-model bursts, and about 0.4 µs for 8-model bursts. Runs with a batch wait or gaps between requests were too noisy to show it._get_curr_iteration_start_timesand_get_handling_task_stackaggregate across queues, and_is_batching_task_aliverequires every queue's task to be alive.Trade-offs and limitations
Related work
set_max_concurrent_batchessetter and replaces the batch queue semaphore with a capacity limiter. With this PR each model queue has its own semaphore, so the setter would store the new value in the shared_BatchConfigfor new queues and update the limit of every existing queue on the event loop. This will need reconciliation if both PRs merge.Testing
Run locally on macOS (Python 3.10, nightly wheel with
setup-dev.py):The new unit tests cover per-model batching and concurrency, idle cleanup including after cancelled requests, queue recreation, shared metrics and the queue-length gauge, the setters, the warning, and the debug helpers.
test_batch_setter_during_queue_construction_is_keptsimulates a setter call during queue creation without starting a thread.test_multiplexed_with_batching_fills_batches_per_model_idintest_multiplex.pysends interleaved requests and checks one full batch of 3 per model; it fails with master'sbatching.py.AI assistance
This PR was developed with AI assistance (Claude Code, with OpenAI Codex as a second reviewer). I reviewed every changed line and ran the tests above locally.