-
-
Notifications
You must be signed in to change notification settings - Fork 200
[kvoffload] feat: make LMCache connecter work #1589
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 all commits
Commits
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
13 changes: 13 additions & 0 deletions
13
...ite/distributed/kv_transfer/kv_connector/v1/lmcache_integration/lookup_client/__init__.py
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,13 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| from .abstract_client import LookupClientInterface | ||
| from .factory import LookupClientFactory | ||
| from .lmcache_lookup_client import LMCacheLookupClient, LMCacheLookupServer | ||
| from .mooncake_lookup_client import MooncakeLookupClient | ||
|
|
||
| __all__ = [ | ||
| "LookupClientInterface", | ||
| "LookupClientFactory", | ||
| "MooncakeLookupClient", | ||
| "LMCacheLookupClient", | ||
| "LMCacheLookupServer", | ||
| ] |
51 changes: 51 additions & 0 deletions
51
...tributed/kv_transfer/kv_connector/v1/lmcache_integration/lookup_client/abstract_client.py
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,51 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # Standard | ||
| import abc | ||
| from typing import TYPE_CHECKING, Optional, Union | ||
|
|
||
| import torch | ||
|
|
||
| if TYPE_CHECKING: | ||
| pass | ||
|
|
||
|
|
||
| class LookupClientInterface(metaclass=abc.ABCMeta): | ||
| """Abstract interface for lookup clients.""" | ||
|
|
||
| @abc.abstractmethod | ||
| def lookup( | ||
| self, | ||
| token_ids: Union[torch.Tensor, list[int]], | ||
| lookup_id: str, | ||
| request_configs: Optional[dict] = None, | ||
| ) -> Optional[int]: | ||
| """ | ||
| Perform lookup for the given token IDs. | ||
|
|
||
| Args: | ||
| token_ids: The token IDs to lookup | ||
|
|
||
| lookup_id: The lookup ID to associate with the lookup | ||
|
|
||
| request_configs: The configs of the request, | ||
| includes tags and the other configs | ||
|
|
||
| Returns: | ||
| The number of tokens that can be loaded from cache. | ||
| None indicates the lookup/prefetch is in progress. | ||
| """ | ||
| raise NotImplementedError | ||
|
|
||
| @abc.abstractmethod | ||
| def close(self) -> None: | ||
| """Close the lookup client and clean up resources.""" | ||
| raise NotImplementedError | ||
|
|
||
| def supports_producer_reuse(self) -> bool: | ||
| """ | ||
| Return whether this lookup client supports producer KV cache reuse. | ||
|
|
||
| Returns: | ||
| True if producer reuse is supported, False otherwise | ||
| """ | ||
| return False |
151 changes: 151 additions & 0 deletions
151
...dite/distributed/kv_transfer/kv_connector/v1/lmcache_integration/lookup_client/factory.py
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,151 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # Standard | ||
| from typing import TYPE_CHECKING, Optional, Union | ||
|
|
||
| from lmcache.v1.cache_engine import LMCacheEngine | ||
| from lmcache.v1.config import LMCacheEngineConfig | ||
|
|
||
| from aphrodite.logger import init_logger | ||
|
|
||
| from .abstract_client import LookupClientInterface | ||
| from .hit_limit_lookup_client import HitLimitLookupClient | ||
| from .mooncake_lookup_client import MooncakeLookupClient | ||
|
|
||
| if TYPE_CHECKING: | ||
| from aphrodite.config import AphroditeConfig | ||
|
|
||
| from .lmcache_async_lookup_client import LMCacheAsyncLookupServer | ||
| from .lmcache_lookup_client import LMCacheLookupServer | ||
|
|
||
| logger = init_logger(__name__) | ||
|
|
||
|
|
||
| class LookupClientFactory: | ||
| """Factory for creating lookup clients and servers based on configuration.""" | ||
|
|
||
| @staticmethod | ||
| def create_lookup_client( | ||
| aphrodite_config: "AphroditeConfig", | ||
| config: LMCacheEngineConfig, | ||
| ) -> LookupClientInterface: | ||
| """ | ||
| Create a lookup client based on the configuration. | ||
|
|
||
| Args: | ||
| aphrodite_config: The Aphrodite configuration | ||
| config: The LMCache engine configuration | ||
|
|
||
| Returns: | ||
| A lookup client instance | ||
| """ | ||
|
|
||
| # Check if external_lookup_client is configured | ||
| if config.external_lookup_client is not None: | ||
| if config.enable_async_loading: | ||
| raise ValueError( | ||
| "Asynchronous loading is not supported for external lookup clients." | ||
| ) | ||
| client = LookupClientFactory._create_external_lookup_client( | ||
| config.external_lookup_client, aphrodite_config | ||
| ) | ||
| else: | ||
| from .lmcache_async_lookup_client import LMCacheAsyncLookupClient | ||
| from .lmcache_lookup_client import LMCacheLookupClient | ||
|
|
||
| if config.enable_async_loading: | ||
| client = LMCacheAsyncLookupClient(aphrodite_config) | ||
| else: | ||
| client = LMCacheLookupClient(aphrodite_config) | ||
|
|
||
| if config.hit_miss_ratio is not None and 0 <= config.hit_miss_ratio <= 1: | ||
| return HitLimitLookupClient(client, config) | ||
| return client | ||
|
|
||
| @staticmethod | ||
| def create_lookup_server( | ||
| lmcache_engine: LMCacheEngine, | ||
| aphrodite_config: "AphroditeConfig", | ||
| ) -> Optional[Union["LMCacheLookupServer", "LMCacheAsyncLookupServer"]]: | ||
| """ | ||
| Create a lookup server based on the configuration. | ||
|
|
||
| Args: | ||
| lmcache_engine: The LMCache engine instance | ||
| aphrodite_config: The Aphrodite configuration | ||
|
|
||
| Returns: | ||
| A lookup server instance, or None if no server should be created | ||
| """ | ||
| config = lmcache_engine.config | ||
| assert isinstance(config, LMCacheEngineConfig), ( | ||
| "LMCache v1 config is expected for lookup server and client" | ||
| ) | ||
|
|
||
| # Only create the KV lookup API server on worker rank 0 | ||
| # when there are multiple workers and when not using external lookup client | ||
| create_lookup_server_only_on_worker_0_for_mla = config.get_extra_config_value( | ||
| "create_lookup_server_only_on_worker_0_for_mla", | ||
| lmcache_engine.metadata.use_mla, | ||
| ) | ||
|
|
||
| if config.external_lookup_client is None and ( | ||
| not create_lookup_server_only_on_worker_0_for_mla | ||
| or lmcache_engine.metadata.worker_id == 0 | ||
| ): | ||
| from .lmcache_async_lookup_client import LMCacheAsyncLookupServer | ||
| from .lmcache_lookup_client import LMCacheLookupServer | ||
|
|
||
| if config.enable_async_loading: | ||
| return LMCacheAsyncLookupServer(lmcache_engine, aphrodite_config) | ||
| else: | ||
| return LMCacheLookupServer(lmcache_engine, aphrodite_config) | ||
|
|
||
| return None | ||
|
|
||
| @staticmethod | ||
| def _create_external_lookup_client( | ||
| external_lookup_uri: str, | ||
| aphrodite_config: "AphroditeConfig", | ||
| ) -> LookupClientInterface: | ||
| """ | ||
| Create an external lookup client based on the URI format. | ||
|
|
||
| Args: | ||
| external_lookup_uri: URI in format <scheme>://<address> | ||
| aphrodite_config: The Aphrodite configuration | ||
|
|
||
| Returns: | ||
| A lookup client instance | ||
|
|
||
| Raises: | ||
| ValueError: If the URI format is unsupported | ||
| """ | ||
| # Parse URI scheme and address | ||
| if "://" not in external_lookup_uri: | ||
| raise ValueError( | ||
| f"Invalid external lookup client URI format: {external_lookup_uri}. " | ||
| "Expected format: <scheme>://<address>" | ||
| ) | ||
|
|
||
| scheme, address = external_lookup_uri.split("://", 1) | ||
|
|
||
| # Route to appropriate client based on scheme | ||
| if scheme == "mooncakestore": | ||
| return LookupClientFactory._create_mooncake_lookup_client( | ||
| address, aphrodite_config | ||
| ) | ||
| else: | ||
| raise ValueError( | ||
| f"Unsupported external lookup client scheme: {scheme}. " | ||
| "Supported schemes: mooncakestore" | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _create_mooncake_lookup_client( | ||
| master_address: str, | ||
| aphrodite_config: "AphroditeConfig", | ||
| ) -> "MooncakeLookupClient": | ||
| """Create a MooncakeLookupClient instance.""" | ||
| from .mooncake_lookup_client import MooncakeLookupClient | ||
|
|
||
| return MooncakeLookupClient(aphrodite_config, master_address) |
82 changes: 82 additions & 0 deletions
82
.../kv_transfer/kv_connector/v1/lmcache_integration/lookup_client/hit_limit_lookup_client.py
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,82 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # Standard | ||
| from typing import Optional, Union | ||
|
|
||
| # Third Party | ||
| import torch | ||
| from lmcache.v1.config import LMCacheEngineConfig | ||
|
|
||
| # First Party | ||
| from aphrodite.logger import init_logger | ||
|
|
||
| from .abstract_client import LookupClientInterface | ||
|
|
||
| logger = init_logger(__name__) | ||
|
|
||
|
|
||
| """ | ||
| HitLimitLookupClient now is used for test, when lookup is called, cal the cache hit, | ||
| - if the cache hit <= (1 - hit_miss_ratio), direct return the result | ||
| - if the cache hit > (1 - hit_miss_ratio), re-compute the result by hit_miss_ratio | ||
| """ | ||
|
|
||
|
|
||
| class HitLimitLookupClient(LookupClientInterface): | ||
| def __init__( | ||
| self, actual_lookup_client: LookupClientInterface, config: LMCacheEngineConfig | ||
| ): | ||
| assert config.hit_miss_ratio is not None and 0 <= config.hit_miss_ratio <= 1 | ||
| self.actual_lookup_client = actual_lookup_client | ||
| self.hit_ratio_upper = 1 - config.hit_miss_ratio | ||
| self.chunk_size = config.chunk_size | ||
| logger.info( | ||
| f"create HitLimitLookupClient succeed, the hit ratio upper" | ||
| f"is {self.hit_ratio_upper}, chunk size is {self.chunk_size}" | ||
| ) | ||
|
|
||
| def lookup( | ||
| self, | ||
| token_ids: Union[torch.Tensor, list[int]], | ||
| lookup_id: str, | ||
| request_configs: Optional[dict] = None, | ||
| ) -> Optional[int]: | ||
| # get real hit tokens | ||
| result = self.actual_lookup_client.lookup(token_ids, lookup_id, request_configs) | ||
| if result is not None: | ||
| total_tokens_length = len(token_ids) | ||
| assert result <= total_tokens_length | ||
| current_hit_ratio = 0.0 | ||
| if total_tokens_length > 0: | ||
| current_hit_ratio = result / total_tokens_length | ||
| # limit the hit tokens | ||
| if current_hit_ratio > self.hit_ratio_upper: | ||
| origin_result = result | ||
| # align to chunk size | ||
| new_result = ( | ||
| int(total_tokens_length * self.hit_ratio_upper) | ||
| // self.chunk_size | ||
| * self.chunk_size | ||
| ) | ||
| # check again | ||
| result = min(result, new_result) | ||
| logger.debug( | ||
| f"hit ratio upper: {self.hit_ratio_upper} is smaller than " | ||
| f"the real hit ratio {current_hit_ratio}, " | ||
| f"the origin result is {origin_result}, " | ||
| f"the new result is {new_result}, the final result is {result}" | ||
| ) | ||
| return result | ||
|
|
||
| def supports_producer_reuse(self) -> bool: | ||
| return self.actual_lookup_client.supports_producer_reuse() | ||
|
|
||
| def clear_lookup_status(self, lookup_id: str) -> None: | ||
| """Clear lookup status for the given lookup_id. | ||
|
|
||
| Delegates to the wrapped lookup client. | ||
| """ | ||
| if hasattr(self.actual_lookup_client, 'clear_lookup_status'): | ||
| self.actual_lookup_client.clear_lookup_status(lookup_id) | ||
|
|
||
| def close(self) -> None: | ||
| self.actual_lookup_client.close() |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The method name
update_interval_vllm_hit_tokensseems to be a leftover fromvllm, which could be confusing in theaphroditecodebase. While this is inherited from thelmcachedependency, consider aliasing or wrapping this to use a more consistent naming convention (e.g.,update_interval_aphrodite_hit_tokens) if possible, to improve code clarity and maintainability.