-
Notifications
You must be signed in to change notification settings - Fork 814
FEAT: auto batch embedding #4197
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 7 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
281996f
FEAT: support batch embedding
qinxuye d2dbca9
FEAT: auto batch embedding
qinxuye dabb6ce
optimize batch method
qinxuye 473a701
FEAT: abstract func & set env
llyycchhee 67043b9
feat(embedding): modify testcase
llyycchhee 9607ff8
feat(embedding): modify testcase
llyycchhee dba3990
feat(embedding): modify testcase
llyycchhee b1c1efa
feat(embedding): modify by comments
llyycchhee b80ca0d
feat(embedding): modify by comments
llyycchhee 613487d
feat(embedding): adapt py39 asyncio
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| # Copyright 2022-2025 XProbe Inc. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import asyncio | ||
| import inspect | ||
| import logging | ||
| import types | ||
|
|
||
| from xoscar.batch import _ExtensibleWrapper | ||
|
|
||
| from ..constants import XINFERENCE_BATCH_SIZE, XINFERENCE_BATCH_TIMEOUT | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class BatchMixin: | ||
| allow_batch = True | ||
| batch_size = XINFERENCE_BATCH_SIZE | ||
| batch_timeout = XINFERENCE_BATCH_TIMEOUT | ||
|
|
||
| def __init__(self, func: _ExtensibleWrapper): | ||
| self._queue: asyncio.Queue = asyncio.Queue() | ||
| self._func = func | ||
| self._func_name = func.func.__name__ | ||
| setattr(self, self._func_name, types.MethodType(self._wrap_method(), self)) | ||
|
|
||
| self._is_process_batch_running = False | ||
|
|
||
| def _ensure_process_batch_running(self): | ||
| if self._is_process_batch_running: | ||
| return | ||
|
|
||
| # create asyncio task to process batch | ||
| asyncio.create_task(self._process_batch()) | ||
| self._is_process_batch_running = True | ||
|
|
||
| def _get_batch_size(self, *args, **kwargs) -> int: | ||
| raise NotImplementedError | ||
|
|
||
| async def _process_batch(self): | ||
| while True: | ||
| # Wait until at least one item is available | ||
| (first_args, first_kwargs), first_future = await self._queue.get() | ||
|
|
||
| delays = [self._func.delay(*first_args, **first_kwargs)] | ||
| size = self._get_batch_size(*first_args, **first_kwargs) | ||
| futures = [first_future] | ||
|
|
||
| # Try to gather more items into the same batch within a short timeout window | ||
| while size <= self.batch_size: | ||
| try: | ||
| # Wait for a new request for a short time window (e.g. 3ms) | ||
| # This allows batching multiple requests that arrive close in time. | ||
| (args, kwargs), future = await asyncio.wait_for( | ||
| self._queue.get(), timeout=self.batch_timeout | ||
| ) | ||
| size += self._get_batch_size(*args, **kwargs) | ||
| delays.append(self._func.delay(*args, **kwargs)) | ||
| futures.append(future) | ||
| except asyncio.TimeoutError: | ||
| # No new items arrived within the timeout window, | ||
| # stop collecting and start processing the current batch. | ||
| break | ||
|
|
||
| logger.debug("Calling batch %s with %d size", self._func_name, size) | ||
|
|
||
| try: | ||
| results = self._func.batch(*delays) | ||
| if inspect.isawaitable(results): | ||
| results = await results | ||
| except Exception as e: # Handle errors for the entire batch | ||
| for fut in futures: | ||
| fut.set_exception(e) | ||
| else: | ||
| # Ensure the number of results matches the number of input futures | ||
| assert len(results) == len( | ||
| futures | ||
| ), f"#results should be equal to #futures, got {len(results)} and {len(futures)}" | ||
| # Deliver the results to the corresponding waiting callers | ||
| for fut, result in zip(futures, results): | ||
| fut.set_result(result) | ||
|
|
||
| def _wrap_method(self): | ||
|
|
||
| async def _replaced_async_method(model, *args, **kwargs): | ||
| self._ensure_process_batch_running() | ||
| loop = asyncio.get_running_loop() | ||
| fut = loop.create_future() | ||
| await self._queue.put(((args, kwargs), fut)) | ||
| return await fut | ||
|
|
||
| return _replaced_async_method |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.