Repository navigation
[serve] Take the max_concurrent_batches permit before forming a batch - #67877
Conversation
_process_batches formed a batch and then waited for a semaphore permit in the batch task. While every permit was in use, the loop kept closing a batch each batch_wait_timeout_s, so requests arriving at a busy replica ran as many small batches one after another. Take the permit before wait_for_batch() and release it when the batch task completes, so those requests stay queued and form one batch. Count batch_wait_timeout_s from the first request's arrival, so a request that waited for a permit does not wait for the timeout again. Signed-off-by: William Guo <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request updates Ray Serve's batching mechanism to acquire the concurrency semaphore before forming a batch, rather than during sub-batch processing. This allows requests arriving while all permits are in use to join a single batch, and ensures that batch timeouts account for the time requests spend waiting for a permit. A review comment correctly identifies a potential semaphore leak if a synchronous exception occurs during batch splitting or task creation, and suggests wrapping the entire block in a try-except block to safely release the permit.
| await self.semaphore.acquire() | ||
| try: | ||
| batch, _ = await self.wait_for_batch() | ||
| except BaseException: | ||
| self.semaphore.release() | ||
| raise | ||
|
|
||
| # Split batch by multiplexed_model_id to ensure requests for different | ||
| # models are processed in separate batches. This is necessary when using | ||
| # model multiplexing with batching, as a single batch containing requests | ||
| # for different models would not work correctly. | ||
| sub_batches = self._split_batch_by_model_id(batch) | ||
|
|
||
| # Process all sub-batches together under a single semaphore permit. | ||
| # Process all sub-batches together under the permit taken above. | ||
| # This ensures sub-batches from the same original batch run concurrently | ||
| # rather than being serialized by the semaphore. | ||
| # rather than being serialized by the semaphore. The permit is released | ||
| # in _handle_completed_task. | ||
| promise = self._process_sub_batches(func, sub_batches) | ||
| task = asyncio.create_task(promise) | ||
| self.tasks.add(task) |
There was a problem hiding this comment.
If a synchronous exception is raised during batch splitting or task creation (e.g., in _split_batch_by_model_id or _process_sub_batches), the semaphore permit acquired at line 513 will be leaked because the try...except BaseException block only wraps wait_for_batch(). Wrapping the entire sequence of operations from wait_for_batch up to adding the task to self.tasks ensures that the semaphore is safely released if any unexpected exception occurs before the task's done callback is registered.
| await self.semaphore.acquire() | |
| try: | |
| batch, _ = await self.wait_for_batch() | |
| except BaseException: | |
| self.semaphore.release() | |
| raise | |
| # Split batch by multiplexed_model_id to ensure requests for different | |
| # models are processed in separate batches. This is necessary when using | |
| # model multiplexing with batching, as a single batch containing requests | |
| # for different models would not work correctly. | |
| sub_batches = self._split_batch_by_model_id(batch) | |
| # Process all sub-batches together under a single semaphore permit. | |
| # Process all sub-batches together under the permit taken above. | |
| # This ensures sub-batches from the same original batch run concurrently | |
| # rather than being serialized by the semaphore. | |
| # rather than being serialized by the semaphore. The permit is released | |
| # in _handle_completed_task. | |
| promise = self._process_sub_batches(func, sub_batches) | |
| task = asyncio.create_task(promise) | |
| self.tasks.add(task) | |
| await self.semaphore.acquire() | |
| try: | |
| batch, _ = await self.wait_for_batch() | |
| # Split batch by multiplexed_model_id to ensure requests for different | |
| # models are processed in separate batches. This is necessary when using | |
| # model multiplexing with batching, as a single batch containing requests | |
| # for different models would not work correctly. | |
| sub_batches = self._split_batch_by_model_id(batch) | |
| # Process all sub-batches together under the permit taken above. | |
| # This ensures sub-batches from the same original batch run concurrently | |
| # rather than being serialized by the semaphore. The permit is released | |
| # in _handle_completed_task. | |
| promise = self._process_sub_batches(func, sub_batches) | |
| task = asyncio.create_task(promise) | |
| self.tasks.add(task) | |
| except BaseException: | |
| self.semaphore.release() | |
| raise |
There was a problem hiding this comment.
Done in 2ddc36c. The try block now covers wait_for_batch(), the split by model ID, building the coroutine and asyncio.create_task(). If any of them raises, the except BaseException releases the permit and re-raises. Each batch gets one task, which runs all of its sub-batches under the one permit. Once create_task() returns, that task owns the permit, and its done callback _handle_completed_task releases it. The callback is registered a few lines later, outside the try, with no await in between, so the permit is released once on either path.
Signed-off-by: William Guo <[email protected]>
The test used a 1 ms wait_for as a proxy for "t1's batch has formed". On Windows the asyncio clock ticks every 15.6 ms, so that timer fires on the next loop iteration. Since ray-project#67877 frees the batch permit in a done callback, the loop is a few iterations behind and t2 joins t1's batch. Wait for t1's batch to start instead. Signed-off-by: john.taylor <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
) The test used a 1 ms wait_for as a proxy for "t1's batch has formed". On Windows the asyncio clock ticks every 15.6 ms, so that timer fires on the next loop iteration. Since #67877 frees the batch permit in a done callback, the loop is a few iterations behind and t2 joins t1's batch. Wait for t1's batch to start instead. Signed-off-by: john.taylor <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Description
@serve.batchforms a batch first and takes amax_concurrent_batchespermit afterwards._process_batchescallswait_for_batch(), then starts a task that waits on the semaphore in_process_sub_batches(batching.pyL498-L532). While every permit is in use, the loop keeps closing a batch each timebatch_wait_timeout_spasses, 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=1and a batch function that takes 0.5 s, one request followed by 10 requests 30 ms apart (script below):[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1][1, 10]This PR takes the permit in
_process_batchesbefore callingwait_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_batchesstill 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 thebatch_wait_timeout_stimer when it takes the first request from the queue, so a request that waited for a permit would then wait for the timeout again. Withbatch_wait_timeout_s=1.0and 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 thanmax_concurrent_batchesbatches 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.CapacityLimiterto add a setter, and #64595 rewrites_process_batchesfor multiplexed queues and acquires the semaphore afterwait_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 thanbatch_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, withbatch_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, andtest_requests_arriving_while_batches_run_form_one_batchfails.pytest python/ray/serve/tests/unit(withouttest_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 intest_deployment_state.py.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 runon the changed files: passed.Repro script