before_code
stringlengths
30
149k
reviewer_comment
stringlengths
16
20.6k
after_code
stringlengths
30
163k
diff_context
stringlengths
0
22.4k
file_path
stringlengths
6
155
comment_line
int64
0
26
language
stringclasses
19 values
quality_score
float64
0.07
1
comment_type
stringclasses
9 values
comment_length
int64
16
20.6k
before_lines
int64
2
4.61k
after_lines
int64
2
4.4k
is_negative
bool
2 classes
pr_title
stringlengths
7
140
pr_number
int64
18
61.2k
repo_name
stringclasses
29 values
repo_stars
int64
321
56k
repo_language
stringclasses
14 values
reviewer_username
stringclasses
378 values
author_username
stringclasses
739 values
user
stringlengths
361
200k
assistant
stringlengths
16
20.6k
system
stringclasses
1 value
# receive tensors for start, end in zip(reordered_starts, reordered_ends, strict=False): ret_mask[start:end] = True # set the mask # receive metadata metadata_dict = self.broadcast_object_fn( None, self...
I'm not sure about this. Why are we not allocating from the memory allocator?
if self.metadata.is_first_rank(): # Broadcast total chunk count chunk_count = len(reordered_chunks) self.broadcast_object_fn(chunk_count, self.metadata.first_rank) # Broadcast each chunk's data for key, memory_obj, start, end in reordered_chunks: ...
@@ -864,6 +850,215 @@ def close(self) -> None: logger.info("LMCacheEngine closed.") + def _process_tokens_internal( + self, + tokens, + mask, + reordered_keys, + reordered_memory_objs, + reordered_starts, + reordered_ends, + ret_mask, + ): + ...
lmcache/v1/cache_engine.py
26
Python
0.357
question
77
51
51
false
[VLLM|CacheEngine]support only save on rank 0 for DS MLA
1,128
LMCache/LMCache
4,864
Python
YaoJiayi
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/cache_engine.py PR Title: [VLLM|CacheEngine]support only save on rank 0 for DS MLA BEFORE CODE: # receive tensors for start, end in zip(reordered_starts, reordered_ends, strict=False): ret_mask[sta...
I'm not sure about this. Why are we not allocating from the memory allocator?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
else: # NOTE: key should always be in the lookup cache once # we support it. location = self.storage_manager.contains(key) if location is None: # TODO(Jiayi): Need to refactor P2P as a storage backend to ...
@YaoJiayi This method is abstracted from `retrieve` method without modify any content.
@_lmcache_nvtx_annotate def health( self, ) -> int: """ Check the health of the cache engine. return: 0 if healthy, otherwise the error code """ return 0 if self.memory_allocator.memcheck() else -1 def close(self) -> None: """Close the cache engin...
@@ -874,6 +842,186 @@ def close(self) -> None: logger.info("LMCacheEngine closed.") + def _process_tokens_internal(
lmcache/v1/cache_engine.py
26
Python
0.357
refactor
87
51
51
false
[VLLM|CacheEngine]support only save on rank 0 for DS MLA
1,128
LMCache/LMCache
4,864
Python
maobaolong
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/cache_engine.py PR Title: [VLLM|CacheEngine]support only save on rank 0 for DS MLA BEFORE CODE: else: # NOTE: key should always be in the lookup cache once # we support it. location = self....
@YaoJiayi This method is abstracted from `retrieve` method without modify any content.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
MemoryObjs from the StorageBackends and convert them into GPU KV caches by GPUConnectors specialized for the serving engine. It also supports prefetching the KV caches from the StorageBackends. It relies on the StorageBackends to manage the requests of prefetching and real retrieval and avoid the c...
Curious why we pass these communication related functions as init arguments.
class LMCacheEngine: """The main class for the cache engine. When storing the KV caches into the cache engine, it takes GPU KV caches from the serving engine and convert them into MemoryObjs that resides in the CPU. The MemoryObjs are then being stored into the StorageBackends in an asynchronous m...
@@ -74,13 +76,25 @@ def __init__( memory_allocator: MemoryAllocatorInterface, token_database: TokenDatabase, gpu_connector: GPUConnectorInterface, + broadcast_fn: Callable[[torch.Tensor, int], None],
lmcache/v1/cache_engine.py
26
Python
0.214
nitpick
76
51
51
false
[VLLM|CacheEngine]support only save on rank 0 for DS MLA
1,128
LMCache/LMCache
4,864
Python
YaoJiayi
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/cache_engine.py PR Title: [VLLM|CacheEngine]support only save on rank 0 for DS MLA BEFORE CODE: MemoryObjs from the StorageBackends and convert them into GPU KV caches by GPUConnectors specialized for the serving engine. It also support...
Curious why we pass these communication related functions as init arguments.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
) self.broadcast_fn(tensor, self.metadata.first_rank) # Create temporary memory object (key not needed for other ranks) memory_obj = TensorMemoryObj(raw_data=tensor, metadata=metadata) reordered_chunks.append((None, memory_obj, start, end)...
Raising a performance concern here: are other ranks waiting for this pice transfer? If so, this on-gpu broadcast seems to be redundant. A better approach would be using an on-cpu shared memory broadcast or unifying all local lmcache workers into a single process. We can postpone handling this though.
reordered_chunks: List of tuples containing [key, memory object, start, end] ret_mask: Boolean mask indicating which positions have been processed Side Effects: - On first rank: * Broadcasts chunk count and each chunk's combined metadata * Broadcasts tensor data ...
@@ -879,6 +847,186 @@ def close(self) -> None: logger.info("LMCacheEngine closed.") + def _process_tokens_internal( + self, + tokens, + mask, + ret_mask, + ) -> List[Tuple[CacheEngineKey, MemoryObj, int, int]]: + """Process tokens and populate the reordered lists. +...
lmcache/v1/cache_engine.py
26
Python
0.643
performance
304
51
51
false
[VLLM|CacheEngine]support only save on rank 0 for DS MLA
1,128
LMCache/LMCache
4,864
Python
YaoJiayi
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/cache_engine.py PR Title: [VLLM|CacheEngine]support only save on rank 0 for DS MLA BEFORE CODE: ) self.broadcast_fn(tensor, self.metadata.first_rank) # Create temporary memory object (key not needed f...
Raising a performance concern here: are other ranks waiting for this pice transfer? If so, this on-gpu broadcast seems to be redundant. A better approach would be using an on-cpu shared memory broadcast or unifying all local lmcache workers into a single process. We can postpone handling this though.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
Check for external KV cache hit. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request Returns: the number of tokens that can be loaded from the external KV ...
As there are two place similar, suggest to abstract a method
Args: layer_name (str): the name of the layer. kv_layer (torch.Tensor): the paged KV buffer of the current layer in vLLM. attn_metadata (AttentionMetadata): the attention metadata. **kwargs: additional arguments for the save operation. """...
@@ -777,6 +791,12 @@ def get_num_new_matched_tokens( token_ids, request.mm_hashes, request.mm_positions ) + tags = None + if request.sampling_params.extra_args is not None:
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.214
refactor
60
51
51
false
[CacheEngine] Support separate cache key by user through lmcache tags
1,200
LMCache/LMCache
4,864
Python
maobaolong
xshwu-ai
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: [CacheEngine] Support separate cache key by user through lmcache tags BEFORE CODE: Check for external KV cache hit. Args: request (Request): the request object. num_...
As there are two place similar, suggest to abstract a method
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
@dataclass(order=True) class CacheEngineKey: fmt: str model_name: str world_size: int worker_id: int chunk_hash: int tags: OrderedDict = None def __hash__(self): return hash( ( self.fmt, self.model_name, self.world_size, ...
Is it necessary to add an addition check `and len(tags) == 0`
torch.float8_e4m3fn: "fp8_e4m3", torch.float8_e5m2: "fp8_e5m2", } STR_DTYPE_TO_TORCH_DTYPE = {v: k for k, v in TORCH_DTYPE_TO_STR_DTYPE.items()} @dataclass(order=True) class CacheEngineKey: fmt: str model_name: str world_size: int worker_id: int chunk_hash: int tags: Optional[OrderedD...
@@ -78,10 +79,14 @@ def __hash__(self): ) def to_string(self): - return ( + s = ( f"{self.fmt}@{self.model_name}@{self.world_size}" f"@{self.worker_id}@{self.chunk_hash}" ) + if self.tags is not None:
lmcache/utils.py
26
Python
0.357
suggestion
61
51
51
false
[CacheEngine] Support separate cache key by user through lmcache tags
1,200
LMCache/LMCache
4,864
Python
maobaolong
xshwu-ai
Review this pull request change. Language: Python File: lmcache/utils.py PR Title: [CacheEngine] Support separate cache key by user through lmcache tags BEFORE CODE: @dataclass(order=True) class CacheEngineKey: fmt: str model_name: str world_size: int worker_id: int chunk_hash: int tags: Ord...
Is it necessary to add an addition check `and len(tags) == 0`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# Request id req_id: str # Total prompt token length prompt_len: int # The token ids that has been scheduled so far token_ids: list[int] # The block ids that has been allocated so far # NOTE: allocated blocks could be more than the number of tokens # FIXME: need to check whether t...
Optional[OrderDict]? @hickeyma do you know why linter cannot detect this?
def extract_tags( config: LMCacheEngineConfig, sampling_params: SamplingParams ) -> OrderedDict: tags = None tag_keys = None if config.extra_config is not None and isinstance(config.extra_config, dict): tag_keys = config.extra_config.get("tag_keys") if sampling_params.extra_args is not Non...
@@ -101,6 +112,8 @@ class RequestTracker: # Multimodal hashes and positions mm_hashes: Optional[list[str]] = None mm_positions: Optional[list["PlaceholderRange"]] = None + # The request tags + tags: OrderedDict = None
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.214
question
73
51
51
false
[CacheEngine] Support separate cache key by user through lmcache tags
1,200
LMCache/LMCache
4,864
Python
YaoJiayi
xshwu-ai
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: [CacheEngine] Support separate cache key by user through lmcache tags BEFORE CODE: # Request id req_id: str # Total prompt token length prompt_len: int # The token ids that has been sc...
Optional[OrderDict]? @hickeyma do you know why linter cannot detect this?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
@dataclass class SaveSpec: # Skip already saved tokens skip_leading_tokens: int # Whether the scheduler allow us to save the tokens can_save: bool @dataclass class DisaggSpec: req_id: str receiver_info: NixlReceiverInfo is_last_prefill: bool = False num_transferred_tokens: int = 0 t...
if we have more than one tags, init in here is inflexible
@dataclass class SaveSpec: # Skip already saved tokens skip_leading_tokens: int # Whether the scheduler allow us to save the tokens can_save: bool @dataclass class DisaggSpec: req_id: str receiver_info: NixlReceiverInfo is_last_prefill: bool = False num_transferred_tokens: int = 0 t...
@@ -89,6 +90,16 @@ class DisaggSpec: tmp_disagg_tracker: dict[str, DisaggSpec] = {} +def extract_tags(sampling_params: SamplingParams) -> OrderedDict: + tags = None + if sampling_params.extra_args is not None: + if kv_transfer_params := sampling_params.extra_args.get("kv_transfer_params"): + ...
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.214
nitpick
57
51
51
false
[CacheEngine] Support separate cache key by user through lmcache tags
1,200
LMCache/LMCache
4,864
Python
chunxiaozheng
xshwu-ai
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: [CacheEngine] Support separate cache key by user through lmcache tags BEFORE CODE: @dataclass class SaveSpec: # Skip already saved tokens skip_leading_tokens: int # Whether the scheduler allow ...
if we have more than one tags, init in here is inflexible
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# TODO(Serapheim): there's a chance we don't want the local # CPU cache in front of ours. Let's experiment and potentially # change that in the future. storage_backends[str(weka_backend)] = weka_backend if config.gds_path is not None: gds_backend = GdsBackend(config, loop, me...
`is_normal_backend` sounds a bit weird. why not use `isinstance` instead, such as ``` if isinstance(backend, LocalCPUBackend): ... else: ... ```
# TODO(Serapheim): there's a chance we don't want the local # CPU cache in front of ours. Let's experiment and potentially # change that in the future. storage_backends[str(weka_backend)] = weka_backend if config.gds_path is not None: gds_backend = GdsBackend(config, loop, me...
@@ -103,4 +103,25 @@ def CreateStorageBackends( backend_name = str(remote_backend) storage_backends[backend_name] = remote_backend - return storage_backends + # Only wrap if audit is enabled in config + if config.extra_config is not None and config.extra_config.get( + "audit_backend_...
lmcache/v1/storage_backend/__init__.py
26
Python
0.786
suggestion
157
37
37
false
Introduce audit_backend to record audit log of backend
1,205
LMCache/LMCache
4,864
Python
chunxiaozheng
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/__init__.py PR Title: Introduce audit_backend to record audit log of backend BEFORE CODE: # TODO(Serapheim): there's a chance we don't want the local # CPU cache in front of ours. Let's experiment and potentially ...
`is_normal_backend` sounds a bit weird. why not use `isinstance` instead, such as ``` if isinstance(backend, LocalCPUBackend): ... else: ... ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
async def move(req: MoveRequest): try: event_id = "Move" + str(uuid.uuid4()) msg = MoveMsg( event_id=event_id, old_position=req.old_position, new_position=req.new_position, tokens=req.tokens, copy=req.cop...
Why dictionary here? Maybe add a simple comment here?
async def move(req: MoveRequest): try: event_id = "Move" + str(uuid.uuid4()) msg = MoveMsg( event_id=event_id, old_position=req.old_position, new_position=req.new_position, tokens=req.tokens, copy=req.cop...
@@ -222,19 +222,21 @@ class HealthRequest(BaseModel): class HealthResponse(BaseModel): event_id: str - alive: bool + error_codes: dict[int, int]
lmcache/v1/api_server/__main__.py
26
Python
0.214
question
53
51
51
false
[Controller] Introduce health check by controller
1,219
LMCache/LMCache
4,864
Python
YaoJiayi
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/api_server/__main__.py PR Title: [Controller] Introduce health check by controller BEFORE CODE: async def move(req: MoveRequest): try: event_id = "Move" + str(uuid.uuid4()) msg = MoveMsg( event_id=...
Why dictionary here? Maybe add a simple comment here?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
:param dst_device: the device where the blocking retrieved KV is stored, could be either "cpu", "cuda", or "cuda:0", "cuda:1", etc. :raise: RuntimeError if the device is not valid """ try: torch.device(dst_device) except RuntimeError: raise ...
How about we introduce a new method `get_listener(self) -> Optional[StorageBackendListener]` so that we don't need to use `hasattr` here. Can do something like: ```python if listener := self.get_listener(): listener.on_evict(self, keys) ```
:param dst_device: the device where the blocking retrieved KV is stored, could be either "cpu", "cuda", or "cuda:0", "cuda:1", etc. :raise: RuntimeError if the device is not valid """ try: torch.device(dst_device) except RuntimeError: raise ...
@@ -31,6 +32,20 @@ def __init__( raise self.dst_device = dst_device + self._listener: Optional[StorageBackendListener] = None + + def set_listener(self, listener: StorageBackendListener): + """ + Set the listener to receive events. + """ + self._listener = l...
lmcache/v1/storage_backend/abstract_backend.py
26
Python
0.857
suggestion
251
51
51
false
[Bugfix] Fix lookup server registration bug #1189
1,237
LMCache/LMCache
4,864
Python
ApostaC
chickeyton
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/abstract_backend.py PR Title: [Bugfix] Fix lookup server registration bug #1189 BEFORE CODE: :param dst_device: the device where the blocking retrieved KV is stored, could be either "cpu", "cuda", or "cuda:0", "c...
How about we introduce a new method `get_listener(self) -> Optional[StorageBackendListener]` so that we don't need to use `hasattr` here. Can do something like: ```python if listener := self.get_listener(): listener.on_evict(self, keys) ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from lmcache.utils import ( CacheEngineKey, _lmcache_nvtx_annotate, start_loop_in_thread_with_exceptions, ) from lmcache.v1.config import LMCacheEngineConfig from lmcache.v1.lookup_server import LookupServerInterface from lmcache.v1.memory_management import ( MemoryAllocatorInterface, MemoryFormat, ...
Let's try not to make `StorageManager` inherit from `StorageBackendListener`. Alternatively, we can define a new sub class of `StorageBackendListener` (e.g., something like `EvictionListener`) that holds the reference to the storage manager object. When the `on_evict` function of the `EvictionListener` is called, i...
from lmcache.v1.lookup_server import LookupServerInterface from lmcache.v1.memory_management import ( MemoryAllocatorInterface, MemoryFormat, MemoryObj, ) from lmcache.v1.storage_backend import CreateStorageBackends from lmcache.v1.storage_backend.abstract_backend import ( AllocatorBackendInterface, ...
@@ -42,7 +43,7 @@ # TODO: extend this class to implement caching policies and eviction policies -class StorageManager: +class StorageManager(StorageBackendListener):
lmcache/v1/storage_backend/storage_manager.py
26
Python
0.643
suggestion
492
51
51
false
[Bugfix] Fix lookup server registration bug #1189
1,237
LMCache/LMCache
4,864
Python
ApostaC
chickeyton
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/storage_manager.py PR Title: [Bugfix] Fix lookup server registration bug #1189 BEFORE CODE: from lmcache.utils import ( CacheEngineKey, _lmcache_nvtx_annotate, start_loop_in_thread_with_exceptions, ) from lmcache.v1.confi...
Let's try not to make `StorageManager` inherit from `StorageBackendListener`. Alternatively, we can define a new sub class of `StorageBackendListener` (e.g., something like `EvictionListener`) that holds the reference to the storage manager object. When the `on_evict` function of the `EvictionListener` is called, i...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def __hash__(self): if self.tags is None: return hash( ( self.fmt, self.model_name, self.world_size, self.worker_id, self.chunk_hash, ) ) return...
Hey @sdimitro , I thought you fixed some problems regarding the chunk hash format in #1299. Can you quickly check the code here? I think we need this modification since the `from_string ` are using something like `int(chunk_hash, 16)`. But just wanted to double check
def __post_init__(self): tags = None if self.request_configs is not None: for k, v in self.request_configs.items(): if k.startswith("lmcache.tag."): if tags is None: tags = {} tags[k[len("lmcache.tag.") :]] =...
@@ -106,7 +106,7 @@ def __hash__(self): def to_string(self): s = ( f"{self.fmt}@{self.model_name}@{self.world_size}" - f"@{self.worker_id}@{self.chunk_hash}" + f"@{self.worker_id}@{hex(self.chunk_hash)}"
lmcache/utils.py
26
Python
0.571
style
270
51
51
false
[Bugfix] Fix lookup server registration bug #1189
1,237
LMCache/LMCache
4,864
Python
ApostaC
chickeyton
Review this pull request change. Language: Python File: lmcache/utils.py PR Title: [Bugfix] Fix lookup server registration bug #1189 BEFORE CODE: def __hash__(self): if self.tags is None: return hash( ( self.fmt, self.model_name, ...
Hey @sdimitro , I thought you fixed some problems regarding the chunk hash format in #1299. Can you quickly check the code here? I think we need this modification since the `from_string ` are using something like `int(chunk_hash, 16)`. But just wanted to double check
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self.storage_manager = storage_manager def on_evict( self, backend: StorageBackendInterface, keys: List[CacheEngineKey] ): """ remove keys from lookup server only if they don't exist in local backends. :param StorageBackendInterface backend: ...
Rather than defining an internal class, we can have this class defined in `storage_backend_listener.py`.
self, backend: StorageBackendInterface, keys: List[CacheEngineKey] ): """ remove keys from lookup server only if they don't exist in local backends. :param StorageBackendInterface backend: The backend that evicted the keys. :param List[CacheEngineKey]...
@@ -47,6 +48,34 @@ class StorageManager: The StorageManager is responsible for managing the storage backends. """ + class _BackendListener(StorageBackendListener): + def __init__(self, storage_manager: "StorageManager"): + self.storage_manager = storage_manager + + def on_evict( ...
lmcache/v1/storage_backend/storage_manager.py
26
Python
0.5
suggestion
104
51
51
false
[Bugfix] Fix lookup server registration bug #1189
1,237
LMCache/LMCache
4,864
Python
ApostaC
chickeyton
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/storage_manager.py PR Title: [Bugfix] Fix lookup server registration bug #1189 BEFORE CODE: self.storage_manager = storage_manager def on_evict( self, backend: StorageBackendInterface, keys: List[Cach...
Rather than defining an internal class, we can have this class defined in `storage_backend_listener.py`.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
return hash( ( self.fmt, self.model_name, self.world_size, self.worker_id, self.chunk_hash, self.layer_id, ) ) return hash( ...
@Shaoting-Feng @sammshen Hey folks, can you take a look here to make sure that this change won't impact other functionalities like PD disaggregation?
return hash( ( self.fmt, self.model_name, self.world_size, self.worker_id, self.chunk_hash, self.layer_id, ) ) return hash( ...
@@ -244,7 +244,7 @@ def __hash__(self): def to_string(self): s = ( f"{self.fmt}@{self.model_name}@{self.world_size}" - f"@{self.worker_id}@{self.chunk_hash}@{self.layer_id}" + f"@{self.worker_id}@{hex(self.chunk_hash)}@{self.layer_id}"
lmcache/utils.py
26
Python
0.429
question
149
51
51
false
[Bugfix] Fix lookup server registration bug #1189
1,237
LMCache/LMCache
4,864
Python
ApostaC
chickeyton
Review this pull request change. Language: Python File: lmcache/utils.py PR Title: [Bugfix] Fix lookup server registration bug #1189 BEFORE CODE: return hash( ( self.fmt, self.model_name, self.world_size, sel...
@Shaoting-Feng @sammshen Hey folks, can you take a look here to make sure that this change won't impact other functionalities like PD disaggregation?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
""" Check if the remote server contains the key Input: key: a string Returns: True if the cache engine contains the key, False otherwise """ raise NotImplementedError @abc.abstractmethod async def get(self, key: CacheEngineKey) -> Option...
This seems duplicated with L209
""" Check if the remote server contains the key Input: key: a string Returns: True if the cache engine contains the key, False otherwise """ raise NotImplementedError @abc.abstractmethod def exists_sync(self, key: CacheEngineKey) -> bool...
@@ -130,6 +130,24 @@ async def get(self, key: CacheEngineKey) -> Optional[MemoryObj]: """ raise NotImplementedError + async def batched_get(
lmcache/v1/storage_backend/connector/base_connector.py
26
Python
0.071
refactor
32
51
51
false
perf(mooncakestore connector): optimize get/put with zero-copy operations
1,269
LMCache/LMCache
4,864
Python
maobaolong
xiaguan
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/base_connector.py PR Title: perf(mooncakestore connector): optimize get/put with zero-copy operations BEFORE CODE: """ Check if the remote server contains the key Input: key: a string ...
This seems duplicated with L209
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
extra_config.get( "metadata_server", MooncakeStoreConfig.DEFAULT_METADATA_SERVER ), ), global_segment_size=file_config.get( "global_segment_size", extra_config.get( "global_segment_size", ...
You have to override this `support_batched_get` method and return true for mooncake
def _unregister_cpu_buffer(self): """Unregister CPU buffer.""" if self.registered_buffer_ptr is not None: result = self.store.unregister_buffer(self.registered_buffer_ptr) if result == 0: logger.info(f"Unregistered buffer: {hex(self.registered_buffer_ptr)}") ...
@@ -139,11 +334,277 @@ def __init__( self.loop = loop self.local_cpu_backend = local_cpu_backend + self.metadata = metadata + self.registered_buffer_ptr = None + + # Initialize ReplicateConfig + self.replica_config = ReplicateConfig() + self.replica_config.replica_...
lmcache/v1/storage_backend/connector/mooncakestore_connector.py
26
Python
0.357
performance
83
51
51
false
perf(mooncakestore connector): optimize get/put with zero-copy operations
1,269
LMCache/LMCache
4,864
Python
maobaolong
xiaguan
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/mooncakestore_connector.py PR Title: perf(mooncakestore connector): optimize get/put with zero-copy operations BEFORE CODE: extra_config.get( "metadata_server", MooncakeStoreConfig.DEFAU...
You have to override this `support_batched_get` method and return true for mooncake
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
except ValueError as e: logger.error("Configuration loading failed: %s", e) raise except Exception as exc: logger.error("An error occurred while loading the configuration: %s", exc) raise self.loop = loop self.local_cpu_backend = local_cp...
The log has been printed in parent class `RemoteConnector`, is the `init_chunk_meta` method need to override here?
except ValueError as e: logger.error("Configuration loading failed: %s", e) raise except Exception as exc: logger.error("An error occurred while loading the configuration: %s", exc) raise self.loop = loop self.local_cpu_backend = local_cp...
@@ -152,33 +166,232 @@ def __init__( self.loop = loop self.local_cpu_backend = local_cpu_backend + self.registered_buffer_ptr = None + + # Initialize ReplicateConfig + self.replica_config = ReplicateConfig() + self.replica_config.replica_num = 1 + + # Set preferred...
lmcache/v1/storage_backend/connector/mooncakestore_connector.py
26
Python
0.5
question
114
51
51
false
perf(mooncakestore connector): optimize get/put with zero-copy operations
1,269
LMCache/LMCache
4,864
Python
chunxiaozheng
xiaguan
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/mooncakestore_connector.py PR Title: perf(mooncakestore connector): optimize get/put with zero-copy operations BEFORE CODE: except ValueError as e: logger.error("Configuration loading failed: %s", e) ...
The log has been printed in parent class `RemoteConnector`, is the `init_chunk_meta` method need to override here?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
n_read, ) except Exception as exc: logger.error(f"Reshape failed for key {keys[i]}: {exc}") memory_objs[i].ref_count_down() return results except Exception as exc: logger.error(f"batch_g...
If we sallow this exception, the vllm will generate wrong output.
logger.error(f"Reshape failed for key {keys[i]}: {exc}") memory_objs[i].ref_count_down() return results except Exception as exc: logger.error(f"batch_get_into threw exception: {str(exc)}") # Release any buffers we successfully allocat...
@@ -152,33 +166,232 @@ def __init__( self.loop = loop self.local_cpu_backend = local_cpu_backend + self.registered_buffer_ptr = None + + # Initialize ReplicateConfig + self.replica_config = ReplicateConfig() + self.replica_config.replica_num = 1 + + # Set preferred...
lmcache/v1/storage_backend/connector/mooncakestore_connector.py
26
Python
0.357
bug
65
51
51
false
perf(mooncakestore connector): optimize get/put with zero-copy operations
1,269
LMCache/LMCache
4,864
Python
maobaolong
xiaguan
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/mooncakestore_connector.py PR Title: perf(mooncakestore connector): optimize get/put with zero-copy operations BEFORE CODE: n_read, ) except Exception as exc: ...
If we sallow this exception, the vllm will generate wrong output.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
memory_objs[i].ref_count_down() return [None] * len(keys) async def _batch_get_buffer( self, keys: List[CacheEngineKey] ) -> List[Optional[MemoryObj]]: """ Batch get using batch_get_buffer when metadata is stored remotely. This is used when save_chunk...
This is another place for silent error handling.
async def _batch_get_buffer( self, keys: List[CacheEngineKey] ) -> List[Optional[MemoryObj]]: """ Batch get using batch_get_buffer when metadata is stored remotely. This is used when save_chunk_meta=True (metadata stored with data). """ key_strs = [key.to_string()...
@@ -152,33 +166,232 @@ def __init__( self.loop = loop self.local_cpu_backend = local_cpu_backend + self.registered_buffer_ptr = None + + # Initialize ReplicateConfig + self.replica_config = ReplicateConfig() + self.replica_config.replica_num = 1 + + # Set preferred...
lmcache/v1/storage_backend/connector/mooncakestore_connector.py
26
Python
0.214
suggestion
49
51
51
false
perf(mooncakestore connector): optimize get/put with zero-copy operations
1,269
LMCache/LMCache
4,864
Python
maobaolong
xiaguan
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/mooncakestore_connector.py PR Title: perf(mooncakestore connector): optimize get/put with zero-copy operations BEFORE CODE: memory_objs[i].ref_count_down() return [None] * len(keys) async d...
This is another place for silent error handling.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# Check metadata handling mode to match get behavior if self.save_chunk_meta: # Use put_parts with metadata stored remotely await self._put_with_metadata(key_str, memory_obj) else: # Use put_from without metadata (zero-copy) await self._put_without...
I guess we need to raise the exception so that caller can aware and handling.
await self._put_with_metadata(key_str, memory_obj) else: # Use put_from without metadata (zero-copy) await self._put_without_metadata(key_str, memory_obj) async def _put_without_metadata(self, key_str: str, memory_obj: MemoryObj): """ Zero-copy put using ...
@@ -213,19 +426,69 @@ async def get(self, key: CacheEngineKey) -> Optional[MemoryObj]: return None async def put(self, key: CacheEngineKey, memory_obj: MemoryObj): - # Please use a function like `memory_obj.to_meta()`. - kv_bytes = memory_obj.byte_array - kv_shape = memory_obj.g...
lmcache/v1/storage_backend/connector/mooncakestore_connector.py
26
Python
0.357
suggestion
77
51
51
false
perf(mooncakestore connector): optimize get/put with zero-copy operations
1,269
LMCache/LMCache
4,864
Python
maobaolong
xiaguan
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/mooncakestore_connector.py PR Title: perf(mooncakestore connector): optimize get/put with zero-copy operations BEFORE CODE: # Check metadata handling mode to match get behavior if self.save_chunk_meta: ...
I guess we need to raise the exception so that caller can aware and handling.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self.worker_id, self.chunk_hash, layer_id, ) ) return keys def get_first_layer(self) -> "LayerCacheEngineKey": """Return the key for the first layer""" key = LayerCacheEngineKey( self.fmt, ...
Why there is a 16 here? @sdimitro
"%".join([f"{k}={v}" for k, v in self.tags.items()]), ) ) def to_string(self): s = ( f"{self.fmt}@{self.model_name}@{self.world_size}" f"@{self.worker_id}@{self.chunk_hash}" ) if self.tags is not None and len(self.tags) != 0: ...
@@ -124,7 +124,7 @@ def from_string(s): if len(parts) != 5: raise ValueError(f"Invalid key string: {s}") return CacheEngineKey( - parts[0], parts[1], int(parts[2]), int(parts[3]), int(parts[4]) + parts[0], parts[1], int(parts[2]), int(parts[3]), int(parts[4], 16)
lmcache/utils.py
26
Python
0.071
question
34
51
51
false
Misc Upstreaming
1,299
LMCache/LMCache
4,864
Python
maobaolong
sdimitro
Review this pull request change. Language: Python File: lmcache/utils.py PR Title: Misc Upstreaming BEFORE CODE: self.worker_id, self.chunk_hash, layer_id, ) ) return keys def get_first_layer(self) -> "LayerCacheEng...
Why there is a 16 here? @sdimitro
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
super().__init__(dst_device) self.config = config self.loop = loop self.memory_allocator = memory_allocator self.dst_device = dst_device assert config.weka_path is not None, ( "Need to specify weka_path for WekaGdsBackend" ) self.weka_path = ...
Can you explain why you use threadpool instead of `asyncio` ?
super().__init__(dst_device) self.config = config self.loop = loop self.memory_allocator = memory_allocator self.dst_device = dst_device assert config.weka_path is not None, ( "Need to specify weka_path for WekaGdsBackend" ) self.weka_path = ...
@@ -153,14 +153,14 @@ def __init__( self.put_tasks: set[CacheEngineKey] = set() self.rand = random.Random(self.dst_device) + thread_count = config.gds_io_threads or 4 + self._thread_pool = ThreadPoolExecutor(
lmcache/v1/storage_backend/weka_gds_backend.py
26
Python
0.571
question
61
51
51
false
Misc Upstreaming
1,299
LMCache/LMCache
4,864
Python
maobaolong
sdimitro
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/weka_gds_backend.py PR Title: Misc Upstreaming BEFORE CODE: super().__init__(dst_device) self.config = config self.loop = loop self.memory_allocator = memory_allocator self.dst_device = dst_de...
Can you explain why you use threadpool instead of `asyncio` ?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
"nixl_peer_host": {"type": Optional[str], "default": None, "env_converter": str}, "nixl_peer_init_port": { "type": Optional[list[int]], "default": None, "env_converter": _to_int_list, }, "nixl_peer_alloc_port": { "type": Optional[list[int]], "default": None, ...
It's better to make this as an extra config?
"nixl_peer_host": {"type": Optional[str], "default": None, "env_converter": str}, "nixl_peer_init_port": { "type": Optional[list[int]], "default": None, "env_converter": _to_int_list, }, "nixl_peer_alloc_port": { "type": Optional[list[int]], "default": None, ...
@@ -185,6 +185,11 @@ def _to_int_list( "default": None, "env_converter": int, }, + "gds_io_threads": { + "type": Optional[int], + "default": None, + "env_converter": int, + },
lmcache/v1/config.py
26
Python
0.143
question
44
51
51
false
Misc Upstreaming
1,299
LMCache/LMCache
4,864
Python
YaoJiayi
sdimitro
Review this pull request change. Language: Python File: lmcache/v1/config.py PR Title: Misc Upstreaming BEFORE CODE: "nixl_peer_host": {"type": Optional[str], "default": None, "env_converter": str}, "nixl_peer_init_port": { "type": Optional[list[int]], "default": None, "env_converter...
It's better to make this as an extra config?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
memory_obj.ref_count_down() return None return memory_obj def _load_bytes_from_disk_with_allocation( self, key: CacheEngineKey, path: str, dtype: torch.dtype, shape: torch.Size, ) -> Optional[MemoryObj]: """ Load byte array...
@sdimitro Sorry, can you remind me how does this memory allocator behave?
) memory_obj.ref_count_down() return None return memory_obj def _load_bytes_from_disk_with_allocation( self, key: CacheEngineKey, path: str, dtype: torch.dtype, shape: torch.Size, ) -> Optional[MemoryObj]: """ ...
@@ -445,6 +445,81 @@ def _load_bytes_from_disk( return None return memory_obj + def _load_bytes_from_disk_with_allocation( + self, + key: CacheEngineKey, + path: str, + dtype: torch.dtype, + shape: torch.Size, + ) -> Optional[MemoryObj]: + """ + ...
lmcache/v1/storage_backend/weka_gds_backend.py
26
Python
0.357
question
73
51
51
false
Misc Upstreaming
1,299
LMCache/LMCache
4,864
Python
YaoJiayi
sdimitro
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/weka_gds_backend.py PR Title: Misc Upstreaming BEFORE CODE: memory_obj.ref_count_down() return None return memory_obj def _load_bytes_from_disk_with_allocation( self, key: CacheEng...
@sdimitro Sorry, can you remind me how does this memory allocator behave?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
""" # TODO(Jiayi): Consider adding write-back here. memory_obj = self.local_cpu_backend.allocate(shape, dtype, fmt) assert memory_obj is not None, "Memory allocation failed during disk load." buffer = memory_obj.byte_array size = len(buffer) fblock_aligned = si...
this path needs the same try exacept right?
start_time = time.time() size = len(buffer) fblock_aligned = size % self.os_disk_bs == 0 if not fblock_aligned and self.use_odirect: logger.warning( "Cannot use O_DIRECT for this file, " "size is not aligned to disk block size." ) ...
@@ -590,8 +590,13 @@ def load_bytes_from_disk( start_time = time.time() if not fblock_aligned or not self.use_odirect: - with open(path, "rb") as f: - f.readinto(buffer) + try: + with open(path, "rb") as f: + f.readinto(buffer) +...
lmcache/v1/storage_backend/local_disk_backend.py
26
Python
0.071
question
44
42
34
false
[Fix] EngineCore shutdown when some .pt files was lost
1,314
LMCache/LMCache
4,864
Python
sammshen
fourierr
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/local_disk_backend.py PR Title: [Fix] EngineCore shutdown when some .pt files was lost BEFORE CODE: """ # TODO(Jiayi): Consider adding write-back here. memory_obj = self.local_cpu_backend.allocate(shape, dtyp...
this path needs the same try exacept right?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
}, "extra_config": { "type": Optional[dict], "default": None, "env_converter": lambda x: json.loads(x) if x else None, }, "save_unfull_chunk": { "type": bool, "default": True, "env_converter": lambda x: x.lower() in ["true", "1"], }, "blocking_time...
what do you think about rename lmcache_metrics_api_server? we already have api server for cache controller
"type": Optional[dict], "default": None, "env_converter": lambda x: json.loads(x) if x else None, }, "save_unfull_chunk": { "type": bool, "default": True, "env_converter": lambda x: x.lower() in ["true", "1"], }, "blocking_timeout_secs": {"type": int, "def...
@@ -217,6 +217,16 @@ def _to_int_list( "default": "LRU", "env_converter": str, }, + "cache_engine_internal_api_server_enabled": {
lmcache/v1/config.py
26
Python
0.429
performance
110
51
51
false
Lmcache internal api server for metrics export
1,318
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/config.py PR Title: Lmcache internal api server for metrics export BEFORE CODE: }, "extra_config": { "type": Optional[dict], "default": None, "env_converter": lambda x: json.loads(x) if x else None, }, "save_u...
what do you think about rename lmcache_metrics_api_server? we already have api server for cache controller
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# Create lookup client using factory self.lookup_client = LookupClientFactory.create_lookup_client( vllm_config, config ) self._unfinished_requests: dict[str, Request] = {} self._lookup_requests_in_step: list[str] = [] else: ...
Shall we put `vllm_config.speculative_config` here like the first four arguments?
class LMCacheConnectorV1Impl: def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, parent: KVConnectorBase_V1, ): self._parent = parent self.kv_role = vllm_config.kv_transfer_config.kv_role config = lmcache_get_config() self.con...
@@ -520,6 +537,7 @@ def __init__( vllm_config.cache_config, vllm_config.scheduler_config, config, + vllm_config,
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.357
question
81
51
51
false
Support addon num_mtp_layers from num_nextn_predict_layers
1,320
LMCache/LMCache
4,864
Python
Shaoting-Feng
maobaolong
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: Support addon num_mtp_layers from num_nextn_predict_layers BEFORE CODE: # Create lookup client using factory self.lookup_client = LookupClientFactory.create_lookup_client( ...
Shall we put `vllm_config.speculative_config` here like the first four arguments?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
VLLM_PARALLEL_CONFIG: Optional[ParallelConfig] = None VLLM_SCHEDULER_CONFIG: Optional[SchedulerConfig] = None def _init_lmcache_engine( lmcache_config: LMCacheEngineConfig, vllm_config: "VllmConfig", ) -> Optional[LMCacheEngine]: """Initialize the LMCache engine by the given model config and parallel ...
sorry, I don't quite understand why are we turning these unto tuples? for exaple, integration tests are failing right now because of: ```text (EngineCore_0 pid=143) kv_dtype = get_kv_cache_torch_dtype(cache_config.cache_dtype, model_config.dtype) --   | (EngineCore_0 pid=143) ...
`LMCACHE_CONFIG_FILE` to load the configuration file. If that environment variable is not set, this function will return None. :param lmcache_config: The LMCache configuration. :type lmcache_config: LMCacheEngineConfig :param vllm_config: The vLLM configuration. :type vllm_config: VllmConfig ...
@@ -412,6 +417,11 @@ def init_lmcache_engine( if LMCacheEngineBuilder.get(ENGINE_NAME) is not None: return None + model_config = (vllm_config.model_config,)
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
1
bug
726
51
51
false
Support addon num_mtp_layers from num_nextn_predict_layers
1,320
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: Support addon num_mtp_layers from num_nextn_predict_layers BEFORE CODE: VLLM_PARALLEL_CONFIG: Optional[ParallelConfig] = None VLLM_SCHEDULER_CONFIG: Optional[SchedulerConfig] = None def _init_lmcache_engi...
sorry, I don't quite understand why are we turning these unto tuples? for exaple, integration tests are failing right now because of: ```text (EngineCore_0 pid=143) kv_dtype = get_kv_cache_torch_dtype(cache_config.cache_dtype, model_config.dtype) --   | (EngineCore_0 pid=143) ...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
" \033[33mAverage generation throughput (per request): " f"\033[32m{average_generation_speed_per_request:.4f} " "tokens/req/s\033[0m\n" ) print(f" \033[33mAverage TTFT: \033[32m{average_ttft:.4f}s\033[0m\n") print(f"Time range: {start_time} - {end_time} ({...
The `qps` here is to match the process summary to the various qps values in the run script. It is best to rename the `total_requests / total_time` to something like `real_qps` to avoid overwrite.
" \033[33mOutput tokens per second: " f"\033[32m{average_generation_speed:.4f} tokens/s\033[0m\n" ) print( " \033[33mAverage generation throughput (per request): " f"\033[32m{average_generation_speed_per_request:.4f} " "tokens/req/s\033[0m\n...
@@ -521,10 +524,9 @@ def summary(self, start_time: float, end_time: float) -> pd.DataFrame: pending_queries = len([s for s in self.sessions if s.has_unfinished_request]) start_time = max(self.start_time, start_time) end_time = min(end_time, df["finish_time"].max()) - qps = self.workloa...
benchmarks/multi-round-qa/multi-round-qa.py
26
Python
0.571
suggestion
195
51
51
false
[Bugfix][Enhancement] Improve multi-round-qa.py and data_preprocessing.py scripts
1,321
LMCache/LMCache
4,864
Python
Shaoting-Feng
1saac-k
Review this pull request change. Language: Python File: benchmarks/multi-round-qa/multi-round-qa.py PR Title: [Bugfix][Enhancement] Improve multi-round-qa.py and data_preprocessing.py scripts BEFORE CODE: " \033[33mAverage generation throughput (per request): " f"\033[32m{average_generation...
The `qps` here is to match the process summary to the various qps values in the run script. It is best to rename the `total_requests / total_time` to something like `real_qps` to avoid overwrite.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
""" Allocate a memory object of shape and dtype evict if necessary. Storage manager should always call local_cpu_backend.allocate() to get memory objects regardless of whether local_cpu is True or False """ logger.debug( f"Allocating memory in local cp...
Here's a bit weird. Why does the local CPU backend need to handle `CuFileMemoryAllocator`? This should be for gds backend only. IIUC, the storage manager should have the correct "allocator backend" to allocate and evict the memory objects. The allocator backend should be gds backend when using gds, which will handle...
self.lmcache_worker.put_msg( KVEvictMsg(self.instance_id, key.worker_id, key.chunk_hash, str(self)) ) # NOTE (Jiayi): This `return True` might not accurately reflect # whether the key is removed from the actual memory because # other backends might still (...
@@ -263,8 +264,10 @@ def allocate( if memory_obj is not None or not eviction: return memory_obj - assert isinstance(self.memory_allocator, MixedMemoryAllocator) or isinstance( - self.memory_allocator, NixlCPUMemoryAllocator + assert ( + isinstance(self.memory_...
lmcache/v1/storage_backend/local_cpu_backend.py
26
Python
0.786
suggestion
381
51
51
false
[Bugfix] Add KV Cache format in gds backend
1,324
LMCache/LMCache
4,864
Python
ApostaC
muma378
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/local_cpu_backend.py PR Title: [Bugfix] Add KV Cache format in gds backend BEFORE CODE: """ Allocate a memory object of shape and dtype evict if necessary. Storage manager should always call local_cpu_...
Here's a bit weird. Why does the local CPU backend need to handle `CuFileMemoryAllocator`? This should be for gds backend only. IIUC, the storage manager should have the correct "allocator backend" to allocate and evict the memory objects. The allocator backend should be gds backend when using gds, which will handle...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
event_manager=self.event_manager, lmcache_worker=self.lmcache_worker, lookup_server=self.lookup_server, ) # HACK: remove this in the future # NOTE (Jiayi): This is currently used to support # dropping the kv cache from the buffer in PD backend ...
if this is hard coded from the metadata, can we move all of this into the GdsBackend and its allocator? it will be able to pack and unpack from there as well
# HACK: remove this in the future # NOTE (Jiayi): This is currently used to support # dropping the kv cache from the buffer in PD backend # at decoder. self.remove_after_retrieve = config.enable_pd and config.pd_role == "receiver" self.use_layerwise = config.use_layerwi...
@@ -152,11 +152,14 @@ def __init__( self.use_layerwise = config.use_layerwise self.num_layers = metadata.kv_shape[0] + self.fmt = MemoryFormat.KV_2LTD
lmcache/v1/cache_engine.py
26
Python
0.429
suggestion
157
51
51
false
[Bugfix] Add KV Cache format in gds backend
1,324
LMCache/LMCache
4,864
Python
sammshen
muma378
Review this pull request change. Language: Python File: lmcache/v1/cache_engine.py PR Title: [Bugfix] Add KV Cache format in gds backend BEFORE CODE: event_manager=self.event_manager, lmcache_worker=self.lmcache_worker, lookup_server=self.lookup_server, ) # HACK:...
if this is hard coded from the metadata, can we move all of this into the GdsBackend and its allocator? it will be able to pack and unpack from there as well
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
"type": Optional[str], "default": None, "env_converter": str, }, "nixl_enable_gc": { "type": bool, "default": False, "env_converter": lambda x: x.lower() in ["true", "1"], }, "nixl_backends": { "type": Optional[list[str]], "default": None, ...
can we make the default UCX like nixl originally does since you are currently passing None into the consturctor if this is unspecified
}, "nixl_role": {"type": Optional[str], "default": None, "env_converter": str}, "nixl_receiver_host": { "type": Optional[str], "default": None, "env_converter": str, }, "nixl_receiver_port": { "type": Optional[int], "default": None, "env_converter": in...
@@ -158,6 +169,11 @@ def _to_int_list( "default": False, "env_converter": lambda x: x.lower() in ["true", "1"], }, + "nixl_backends": {
lmcache/v1/config.py
26
Python
0.357
suggestion
134
51
51
false
[Misc] Allow passing nixl backends when creating nixl_agent in nixl_connector_v3
1,343
LMCache/LMCache
4,864
Python
sammshen
jinqinn
Review this pull request change. Language: Python File: lmcache/v1/config.py PR Title: [Misc] Allow passing nixl backends when creating nixl_agent in nixl_connector_v3 BEFORE CODE: "type": Optional[str], "default": None, "env_converter": str, }, "nixl_enable_gc": { "type": bo...
can we make the default UCX like nixl originally does since you are currently passing None into the consturctor if this is unspecified
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
""" self.nixl_config = nixl_config self.side_channel = side_channel if nixl_config.buffer_size > NixlPipe.TRANSFER_BUFFER_SIZE: assert nixl_config.buffer_size % NixlPipe.TRANSFER_BUFFER_SIZE == 0, ( f"Buffer size must be a multiple of {NixlPipe.TRANSFER_BUFFE...
or just don't pass in None here
""" self.nixl_config = nixl_config self.side_channel = side_channel if nixl_config.buffer_size > NixlPipe.TRANSFER_BUFFER_SIZE: assert nixl_config.buffer_size % NixlPipe.TRANSFER_BUFFER_SIZE == 0, ( f"Buffer size must be a multiple of {NixlPipe.TRANSFER_BUFFE...
@@ -235,7 +235,12 @@ def __init__( # allocator (should be initialized after self._buffer) self._allocator = NixlBufferAllocator(self) - self._agent = nixl_agent(str(nixl_config.role) + str(nixl_config.buffer_device)) + self._agent = nixl_agent(
lmcache/v1/storage_backend/connector/nixl_connector_v2.py
26
Python
0.071
suggestion
31
51
51
false
[Misc] Allow passing nixl backends when creating nixl_agent in nixl_connector_v3
1,343
LMCache/LMCache
4,864
Python
sammshen
jinqinn
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/nixl_connector_v2.py PR Title: [Misc] Allow passing nixl backends when creating nixl_agent in nixl_connector_v3 BEFORE CODE: """ self.nixl_config = nixl_config self.side_channel = side_channel ...
or just don't pass in None here
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self.use_hot = config.local_cpu self.lookup_server = lookup_server self.memory_allocator = memory_allocator self.lmcache_worker = lmcache_worker self.instance_id = config.lmcache_instance_id self.cpu_lock = threading.Lock() self.stream = torch.cuda.Stream() ...
this is to distinguish between workers right?
self.memory_allocator = memory_allocator self.lmcache_worker = lmcache_worker self.instance_id = config.lmcache_instance_id self.cpu_lock = threading.Lock() self.stream = torch.cuda.Stream() self.stats_monitor = LMCStatsMonitor.GetOrCreate() self.layerwise = co...
@@ -67,6 +69,21 @@ def __init__( # assumption: only one request is looked up at a time # (only one worker per cache engine) self.keys_in_request: List[CacheEngineKey] = [] + self._setup_metrics() + + def _setup_metrics(self): + Gauge( + "lmcache:local_cpu_hot_cache...
lmcache/v1/storage_backend/local_cpu_backend.py
26
Python
0.071
question
46
51
51
false
Add metrics to LocalCPUBackend by lambda
1,344
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/local_cpu_backend.py PR Title: Add metrics to LocalCPUBackend by lambda BEFORE CODE: self.use_hot = config.local_cpu self.lookup_server = lookup_server self.memory_allocator = memory_allocator self.lmc...
this is to distinguish between workers right?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
@staticmethod def unregister_all_metrics(): collectors = list(REGISTRY._collector_to_names.keys()) for collector in collectors: try: REGISTRY.unregister(collector) except KeyError: pass class PrometheusLogger: _gauge_cls = prometheus_...
sorry where is this supposed to be called?
remote_cache_usage_bytes=self.remote_cache_usage_bytes, local_storage_usage_bytes=self.local_storage_usage_bytes, active_memory_objs_count=self.active_memory_objs_count, pinned_memory_objs_count=self.pinned_memory_objs_count, time_to_retrieve=time_to_retrieve,...
@@ -396,6 +397,15 @@ def GetOrCreate() -> "LMCStatsMonitor": def DestroyInstance(): LMCStatsMonitor._instance = None + @staticmethod + def unregister_all_metrics():
lmcache/observability.py
26
Python
0.071
question
43
51
51
false
Add metrics to LocalCPUBackend by lambda
1,344
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/observability.py PR Title: Add metrics to LocalCPUBackend by lambda BEFORE CODE: @staticmethod def unregister_all_metrics(): collectors = list(REGISTRY._collector_to_names.keys()) for collector in collectors: try: ...
sorry where is this supposed to be called?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self.cache_policy = get_cache_policy(config.cache_policy) self.hot_cache = self.cache_policy.init_mutable_mapping() self.use_hot = config.local_cpu self.lookup_server = lookup_server self.memory_allocator = memory_allocator self.lmcache_worker = lmcache_worker se...
Sorry, I'm not so familiar with the Prometheus python SDK. If we create gauges here, can they be automatically exposed to the prometheus metric endpoint?
self.use_hot = config.local_cpu self.lookup_server = lookup_server self.memory_allocator = memory_allocator self.lmcache_worker = lmcache_worker self.instance_id = config.lmcache_instance_id self.cpu_lock = threading.Lock() self.stream = torch.cuda.Stream() ...
@@ -67,6 +69,21 @@ def __init__( # assumption: only one request is looked up at a time # (only one worker per cache engine) self.keys_in_request: List[CacheEngineKey] = [] + self._setup_metrics() + + def _setup_metrics(self): + Gauge(
lmcache/v1/storage_backend/local_cpu_backend.py
26
Python
0.357
question
153
51
51
false
Add metrics to LocalCPUBackend by lambda
1,344
LMCache/LMCache
4,864
Python
ApostaC
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/local_cpu_backend.py PR Title: Add metrics to LocalCPUBackend by lambda BEFORE CODE: self.cache_policy = get_cache_policy(config.cache_policy) self.hot_cache = self.cache_policy.init_mutable_mapping() self.us...
Sorry, I'm not so familiar with the Prometheus python SDK. If we create gauges here, can they be automatically exposed to the prometheus metric endpoint?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self.cache_policy = get_cache_policy(config.cache_policy) self.hot_cache = self.cache_policy.init_mutable_mapping() self.use_hot = config.local_cpu self.lookup_server = lookup_server self.memory_allocator = memory_allocator self.lmcache_worker = lmcache_worker se...
Also, is it possible to add a helper function in `PrometheusLogger` for other modules to register metrics? The goal of such a helper function is to make sure that the metric labels (right now include `model_id` and `worker_id`) can be correctly added. (See the function `PrometheusLogger._metadata_to_labels`)
self.use_hot = config.local_cpu self.lookup_server = lookup_server self.memory_allocator = memory_allocator self.lmcache_worker = lmcache_worker self.instance_id = config.lmcache_instance_id self.cpu_lock = threading.Lock() self.stream = torch.cuda.Stream() ...
@@ -67,6 +69,21 @@ def __init__( # assumption: only one request is looked up at a time # (only one worker per cache engine) self.keys_in_request: List[CacheEngineKey] = [] + self._setup_metrics() + + def _setup_metrics(self): + Gauge(
lmcache/v1/storage_backend/local_cpu_backend.py
26
Python
0.571
refactor
312
51
51
false
Add metrics to LocalCPUBackend by lambda
1,344
LMCache/LMCache
4,864
Python
ApostaC
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/local_cpu_backend.py PR Title: Add metrics to LocalCPUBackend by lambda BEFORE CODE: self.cache_policy = get_cache_policy(config.cache_policy) self.hot_cache = self.cache_policy.init_mutable_mapping() self.us...
Also, is it possible to add a helper function in `PrometheusLogger` for other modules to register metrics? The goal of such a helper function is to make sure that the metric labels (right now include `model_id` and `worker_id`) can be correctly added. (See the function `PrometheusLogger._metadata_to_labels`)
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
_instance = None @staticmethod def GetOrCreate(metadata: LMCacheEngineMetadata) -> "PrometheusLogger": if PrometheusLogger._instance is None: PrometheusLogger._instance = PrometheusLogger(metadata) # assert PrometheusLogger._instance.metadata == metadata, \ # "Promet...
`GetInstanceIfCreate` sounds a little bit weird (I'm okay with it though) Proposing some alternatives: - `GetInstanceIfExists` - `GetInstanceOrNone` - `MaybeGetInstance`
_instance = None @staticmethod def GetOrCreate(metadata: LMCacheEngineMetadata) -> "PrometheusLogger": if PrometheusLogger._instance is None: PrometheusLogger._instance = PrometheusLogger(metadata) # assert PrometheusLogger._instance.metadata == metadata, \ # "Promet...
@@ -910,6 +938,14 @@ def GetInstance() -> "PrometheusLogger": ) return PrometheusLogger._instance + @staticmethod + def GetInstanceIfCreate() -> Optional["PrometheusLogger"]:
lmcache/observability.py
26
Python
0.5
suggestion
177
51
51
false
Add metrics to LocalCPUBackend by lambda
1,344
LMCache/LMCache
4,864
Python
ApostaC
maobaolong
Review this pull request change. Language: Python File: lmcache/observability.py PR Title: Add metrics to LocalCPUBackend by lambda BEFORE CODE: _instance = None @staticmethod def GetOrCreate(metadata: LMCacheEngineMetadata) -> "PrometheusLogger": if PrometheusLogger._instance is None: ...
`GetInstanceIfCreate` sounds a little bit weird (I'm okay with it though) Proposing some alternatives: - `GetInstanceIfExists` - `GetInstanceOrNone` - `MaybeGetInstance`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
): return 0 self._requests_priority[request.request_id] = request.priority token_ids = request.prompt_token_ids # If the request has multimodal hashes, apply them to the token ids if request.mm_hashes: # TODO(Jiayi): Optimize this token_ids ...
QQ: is `request.priority` already stable enough in vLLM?
#################### @_lmcache_nvtx_annotate def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> Optional[int]: """ Check for external KV cache hit. Args: request (Request): the request object. ...
@@ -1008,6 +1022,8 @@ def get_num_new_matched_tokens( ): return 0 + self._requests_priority[request.request_id] = request.priority
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.357
question
56
51
51
false
Priority based storing -- only store kv cache for high priority requests
1,368
LMCache/LMCache
4,864
Python
ApostaC
FerdinandZhong
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: Priority based storing -- only store kv cache for high priority requests BEFORE CODE: ): return 0 self._requests_priority[request.request_id] = request.priority token_i...
QQ: is `request.priority` already stable enough in vLLM?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# Disagg spec for the request disagg_spec: Optional[DisaggSpec] = None # Multimodal hashes and positions mm_hashes: Optional[list[str]] = None mm_positions: Optional[list["PlaceholderRange"]] = None # The configs of the request, includes tags and other configs request_configs: Optional[di...
Why do we need to put the skip_save flag in the request tracker? This class is meant to save the request states, such as token ids/block ids/number of cached tokens. An alternative way is to check the priority in `build_connector_meta` and directly calculate and pass the `skip_save` flag in the `build_connector_meta...
# FIXME: need to check whether the block ids will be changed after # preemption allocated_block_ids: list[int] # The number of tokens that has been saved num_saved_tokens: int = 0 # Disagg spec for the request disagg_spec: Optional[DisaggSpec] = None # Multimodal hashes and pos...
@@ -135,13 +135,18 @@ class RequestTracker: # Whether the request is in decode phase is_decode_phase = False + # Whether the request cache should be saved + skip_save: bool = False + @_lmcache_nvtx_annotate @staticmethod def from_new_request( lmcache_config: LMCacheEngineConfig...
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.571
performance
332
51
51
false
Priority based storing -- only store kv cache for high priority requests
1,368
LMCache/LMCache
4,864
Python
ApostaC
FerdinandZhong
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: Priority based storing -- only store kv cache for high priority requests BEFORE CODE: # Disagg spec for the request disagg_spec: Optional[DisaggSpec] = None # Multimodal hashes and positions ...
Why do we need to put the skip_save flag in the request tracker? This class is meant to save the request states, such as token ids/block ids/number of cached tokens. An alternative way is to check the priority in `build_connector_meta` and directly calculate and pass the `skip_save` flag in the `build_connector_meta...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
""" Check for external KV cache hit. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request Returns: the number of tokens that can be loaded from the ...
The `request.priority` is not exists in vllm `0.8.5`, so this PR make LMCache break backward-compatible. @ApostaC @FerdinandZhong @yoo-kumaneko
#################### @_lmcache_nvtx_annotate def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> Optional[int]: """ Check for external KV cache hit. Args: request (Request): the request object. ...
@@ -1036,6 +1044,8 @@ def get_num_new_matched_tokens( ): return 0 + self._requests_priority[request.request_id] = request.priority
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.5
performance
147
51
51
false
Priority based storing -- only store kv cache for high priority requests
1,368
LMCache/LMCache
4,864
Python
maobaolong
FerdinandZhong
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: Priority based storing -- only store kv cache for high priority requests BEFORE CODE: """ Check for external KV cache hit. Args: request (Request): the request object. ...
The `request.priority` is not exists in vllm `0.8.5`, so this PR make LMCache break backward-compatible. @ApostaC @FerdinandZhong @yoo-kumaneko
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# Whether the scheduler allow us to load the tokens can_load: bool @dataclass class SaveSpec: # Skip already saved tokens skip_leading_tokens: int # Whether the scheduler allow us to save the tokens can_save: bool @dataclass class DisaggSpec: req_id: str receiver_info: NixlReceiverIn...
This is better than set a `tag_keys` into confiig.👍
@dataclass class SaveSpec: # Skip already saved tokens skip_leading_tokens: int # Whether the scheduler allow us to save the tokens can_save: bool @dataclass class DisaggSpec: req_id: str receiver_info: NixlReceiverInfo is_last_prefill: bool = False num_transferred_tokens: int = 0 t...
@@ -91,21 +91,16 @@ class DisaggSpec: tmp_disagg_tracker: dict[str, DisaggSpec] = {} -def extract_tags( - config: LMCacheEngineConfig, sampling_params: SamplingParams -) -> OrderedDict: - tags = None - tag_keys = None - if config.extra_config is not None and isinstance(config.extra_config, dict): - ...
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.429
suggestion
52
51
51
false
[refact] use request_configs replace tags
1,377
LMCache/LMCache
4,864
Python
maobaolong
chunxiaozheng
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: [refact] use request_configs replace tags BEFORE CODE: # Whether the scheduler allow us to load the tokens can_load: bool @dataclass class SaveSpec: # Skip already saved tokens skip_leadin...
This is better than set a `tag_keys` into confiig.👍
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# Whether to discard partial chunks self._discard_partial_chunks = ( vllm_config.kv_transfer_config.get_from_extra_config( "discard_partial_chunks", False ) or not config.save_unfull_chunk ) self._lmcache_chunk_size = config.chunk_siz...
nice, now we can also debug the scheduler independently
# Whether to discard partial chunks self._discard_partial_chunks = ( vllm_config.kv_transfer_config.get_from_extra_config( "discard_partial_chunks", False ) or not config.save_unfull_chunk ) self._lmcache_chunk_size = config.chunk_siz...
@@ -610,6 +612,9 @@ def __init__( self.force_skip_save = bool(os.environ.get("LMCACHE_FORCE_SKIP_SAVE", False)) + self.api_server = InternalAPIServer(self)
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.357
bug
55
51
51
false
Improve internal api server to support multiple lmcache server
1,387
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: Improve internal api server to support multiple lmcache server BEFORE CODE: # Whether to discard partial chunks self._discard_partial_chunks = ( vllm_config.kv_transfer_config.g...
nice, now we can also debug the scheduler independently
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# request_id -> full_token_ids self._request_trackers: dict[str, RequestTracker] = {} # Whether to discard partial chunks self._discard_partial_chunks = ( vllm_config.kv_transfer_config.get_from_extra_config( "discard_partial_chunks", False ) ...
nit: can you write a small comment here that activation of API server for this worker / scheduler connector component is decided inside the constructor or else it looks like we always create the `api_server`
# request_id -> full_token_ids self._request_trackers: dict[str, RequestTracker] = {} # Whether to discard partial chunks self._discard_partial_chunks = ( vllm_config.kv_transfer_config.get_from_extra_config( "discard_partial_chunks", False ) ...
@@ -610,6 +612,9 @@ def __init__( self.force_skip_save = bool(os.environ.get("LMCACHE_FORCE_SKIP_SAVE", False))
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.571
nitpick
207
51
51
false
Improve internal api server to support multiple lmcache server
1,387
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: Improve internal api server to support multiple lmcache server BEFORE CODE: # request_id -> full_token_ids self._request_trackers: dict[str, RequestTracker] = {} # Whether to disca...
nit: can you write a small comment here that activation of API server for this worker / scheduler connector component is decided inside the constructor or else it looks like we always create the `api_server`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# SPDX-License-Identifier: Apache-2.0 # Standard from dataclasses import dataclass from enum import IntEnum, auto import struct MAX_KEY_LENGTH = 150 class Constants(IntEnum): CLIENT_PUT = auto() CLIENT_GET = auto() CLIENT_EXIST = auto() CLIENT_LIST = auto() SERVER_SUCCESS = 200 SERVER_FAIL =...
I know this isn't part of this PR but do you mind breaking this out into 2 enums: - ClientCommands - ServerReturnCodes As it currently stands, the enum is just a catchall for constants which is not good practice.
# SPDX-License-Identifier: Apache-2.0 # Standard from dataclasses import dataclass from enum import IntEnum, auto import struct MAX_KEY_LENGTH = 150 class ClientCommand(IntEnum): PUT = auto() GET = auto() EXIST = auto() LIST = auto() class ServerReturnCode(IntEnum): # keep the same as HTTP stat...
@@ -1,16 +1,17 @@ # SPDX-License-Identifier: Apache-2.0 # Standard from dataclasses import dataclass +from enum import IntEnum, auto import struct MAX_KEY_LENGTH = 150 -class Constants: - CLIENT_PUT = 1 - CLIENT_GET = 2 - CLIENT_EXIST = 3 - CLIENT_LIST = 4 +class Constants(IntEnum): + CLIENT_P...
lmcache/protocol.py
17
Python
0.429
suggestion
219
42
42
false
use enum auto instead of number literal
1,390
LMCache/LMCache
4,864
Python
hickeyma
mengbingrock
Review this pull request change. Language: Python File: lmcache/protocol.py PR Title: use enum auto instead of number literal BEFORE CODE: # SPDX-License-Identifier: Apache-2.0 # Standard from dataclasses import dataclass from enum import IntEnum, auto import struct MAX_KEY_LENGTH = 150 class Constants(IntEnum):...
I know this isn't part of this PR but do you mind breaking this out into 2 enums: - ClientCommands - ServerReturnCodes As it currently stands, the enum is just a catchall for constants which is not good practice.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# Standard from collections import deque from contextlib import nullcontext from dataclasses import dataclass from enum import Enum, auto from typing import List, Optional, Tuple, Union import abc import ctypes import math import threading # Third Party import sortedcontainers import torch # First Party from lmcache....
Its probably better to start with `0` like current value.
# Standard from collections import deque from contextlib import nullcontext from dataclasses import dataclass from enum import Enum, auto from typing import Any, List, Optional, Tuple, Union import abc import ctypes import math import threading # Third Party import sortedcontainers import torch # First Party from lmc...
@@ -24,26 +24,26 @@ class MemoryFormat(Enum): - UNDEFINED = 0 + UNDEFINED = auto()
lmcache/v1/memory_management.py
26
Python
0.429
suggestion
57
51
51
false
use enum auto instead of number literal
1,390
LMCache/LMCache
4,864
Python
hickeyma
mengbingrock
Review this pull request change. Language: Python File: lmcache/v1/memory_management.py PR Title: use enum auto instead of number literal BEFORE CODE: # Standard from collections import deque from contextlib import nullcontext from dataclasses import dataclass from enum import Enum, auto from typing import List, Op...
Its probably better to start with `0` like current value.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from dataclasses import dataclass from enum import Enum, auto from typing import List, Optional, Tuple, Union import abc import ctypes import math import threading # Third Party import sortedcontainers import torch # First Party from lmcache.logging import init_logger from lmcache.observability import LMCStatsMonitor...
Comments should probably retain the specific value and not `auto()`
from dataclasses import dataclass from enum import Enum, auto from typing import Any, List, Optional, Tuple, Union import abc import ctypes import math import threading # Third Party import sortedcontainers import torch # First Party from lmcache.logging import init_logger from lmcache.observability import LMCStatsMo...
@@ -24,26 +24,26 @@ class MemoryFormat(Enum): - UNDEFINED = 0 + UNDEFINED = auto() """[2, num_layers, num_tokens, hidden_dim] """ - # KV_BLOB = 1 - KV_2LTD = 1 + # KV_BLOB = auto()
lmcache/v1/memory_management.py
26
Python
0.429
suggestion
67
51
51
false
use enum auto instead of number literal
1,390
LMCache/LMCache
4,864
Python
hickeyma
mengbingrock
Review this pull request change. Language: Python File: lmcache/v1/memory_management.py PR Title: use enum auto instead of number literal BEFORE CODE: from dataclasses import dataclass from enum import Enum, auto from typing import List, Optional, Tuple, Union import abc import ctypes import math import threading ...
Comments should probably retain the specific value and not `auto()`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import ctypes import math import threading # Third Party import sortedcontainers import torch # First Party from lmcache.logging import init_logger from lmcache.observability import LMCStatsMonitor from lmcache.utils import _lmcache_nvtx_annotate import lmcache.c_ops as lmc_ops logger = init_logger(__name__) class...
Leave comment with specific value and not auto()
import ctypes import math import threading # Third Party import sortedcontainers import torch # First Party from lmcache.logging import init_logger from lmcache.observability import LMCStatsMonitor from lmcache.utils import _lmcache_nvtx_annotate import lmcache.c_ops as lmc_ops logger = init_logger(__name__) class...
@@ -28,22 +28,22 @@ class MemoryFormat(Enum): """[2, num_layers, num_tokens, hidden_dim] """ # KV_BLOB = 1 - KV_2LTD = 1 + KV_2LTD = auto() """[num_tokens, 2, hidden_dim] """ - # LAYER_KV_BLOB = 2 - KV_T2D = 2 + # LAYER_KV_BLOB = auto()
lmcache/v1/memory_management.py
26
Python
0.071
suggestion
48
51
51
false
use enum auto instead of number literal
1,390
LMCache/LMCache
4,864
Python
hickeyma
mengbingrock
Review this pull request change. Language: Python File: lmcache/v1/memory_management.py PR Title: use enum auto instead of number literal BEFORE CODE: import ctypes import math import threading # Third Party import sortedcontainers import torch # First Party from lmcache.logging import init_logger from lmcache.ob...
Leave comment with specific value and not auto()
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# SPDX-License-Identifier: Apache-2.0 # Standard from dataclasses import dataclass from enum import IntEnum, auto from typing import Optional import struct # Third Party import torch # First Party from lmcache.utils import CacheEngineKey from lmcache.v1.memory_management import MemoryFormat MAX_KEY_LENGTH = 150 cl...
Sorry but I didn't mean to add `s` at end; do you mind changing to `ClientCommand`?
# SPDX-License-Identifier: Apache-2.0 # Standard from dataclasses import dataclass from enum import IntEnum, auto from typing import Optional import struct # Third Party import torch # First Party from lmcache.utils import CacheEngineKey from lmcache.v1.memory_management import MemoryFormat MAX_KEY_LENGTH = 150 cl...
@@ -14,15 +15,17 @@ MAX_KEY_LENGTH = 150 -class Constants: - CLIENT_PUT = 1 - CLIENT_GET = 2 - CLIENT_EXIST = 3 - CLIENT_LIST = 4 - CLIENT_HEALTH = 5 +class ClientCommands(IntEnum):
lmcache/v1/protocol.py
18
Python
0.357
question
83
43
43
false
use enum auto instead of number literal
1,390
LMCache/LMCache
4,864
Python
hickeyma
mengbingrock
Review this pull request change. Language: Python File: lmcache/v1/protocol.py PR Title: use enum auto instead of number literal BEFORE CODE: # SPDX-License-Identifier: Apache-2.0 # Standard from dataclasses import dataclass from enum import IntEnum, auto from typing import Optional import struct # Third Party imp...
Sorry but I didn't mean to add `s` at end; do you mind changing to `ClientCommand`?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# SPDX-License-Identifier: Apache-2.0 # Standard from dataclasses import dataclass from enum import IntEnum, auto from typing import Optional import struct # Third Party import torch # First Party from lmcache.utils import CacheEngineKey from lmcache.v1.memory_management import MemoryFormat MAX_KEY_LENGTH = 150 cl...
Sorry but I didn't mean to add `s` at end; do you mind changing to `ServerReturnCode`?
# SPDX-License-Identifier: Apache-2.0 # Standard from dataclasses import dataclass from enum import IntEnum, auto from typing import Optional import struct # Third Party import torch # First Party from lmcache.utils import CacheEngineKey from lmcache.v1.memory_management import MemoryFormat MAX_KEY_LENGTH = 150 cl...
@@ -14,15 +15,17 @@ MAX_KEY_LENGTH = 150 -class Constants: - CLIENT_PUT = 1 - CLIENT_GET = 2 - CLIENT_EXIST = 3 - CLIENT_LIST = 4 - CLIENT_HEALTH = 5 +class ClientCommands(IntEnum): + PUT = auto() + GET = auto() + EXIST = auto() + LIST = auto() + HEALTH = auto() - SERVER_SUCCESS ...
lmcache/v1/protocol.py
26
Python
0.357
question
86
51
51
false
use enum auto instead of number literal
1,390
LMCache/LMCache
4,864
Python
hickeyma
mengbingrock
Review this pull request change. Language: Python File: lmcache/v1/protocol.py PR Title: use enum auto instead of number literal BEFORE CODE: # SPDX-License-Identifier: Apache-2.0 # Standard from dataclasses import dataclass from enum import IntEnum, auto from typing import Optional import struct # Third Party imp...
Sorry but I didn't mean to add `s` at end; do you mind changing to `ServerReturnCode`?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
_CONFIG_DEFINITIONS: dict[str, dict[str, Any]] = { # Basic configurations "chunk_size": {"type": int, "default": 256, "env_converter": int}, "local_cpu": { "type": bool, "default": True, "env_converter": lambda x: x.lower() in ["true", "1"], }, "max_local_cpu_size": {"type": ...
@Shaoting-Feng As this code duplicated so much time, would you like to abstract this into a `bool_converter` ? You can referent to `_to_int_list`
"chunk_size": {"type": int, "default": 256, "env_converter": int}, "local_cpu": { "type": bool, "default": True, "env_converter": lambda x: x if isinstance(x, bool) else str(x).lower() in ["true", "1"], }, "max_local_cpu_size": {"type": float, "default": 5.0, "env...
@@ -78,12 +78,16 @@ def _to_int_list( "use_layerwise": { "type": bool, "default": False, - "env_converter": lambda x: x.lower() in ["true", "1"], + "env_converter": lambda x: x
lmcache/v1/config.py
26
Python
0.5
refactor
148
51
51
false
[Bugfix][PD] Fix config setting
1,391
LMCache/LMCache
4,864
Python
maobaolong
Shaoting-Feng
Review this pull request change. Language: Python File: lmcache/v1/config.py PR Title: [Bugfix][PD] Fix config setting BEFORE CODE: _CONFIG_DEFINITIONS: dict[str, dict[str, Any]] = { # Basic configurations "chunk_size": {"type": int, "default": 256, "env_converter": int}, "local_cpu": { "type": ...
@Shaoting-Feng As this code duplicated so much time, would you like to abstract this into a `bool_converter` ? You can referent to `_to_int_list`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from lmcache.v1.rpc_utils import get_zmq_rpc_path_lmcache if TYPE_CHECKING: # Third Party from vllm.config import VllmConfig logger = init_logger(__name__) class LMCacheLookupClient(LookupClientInterface): """ ZMQ-based lookup client that communicates with a lookup server. Related extra_config:...
Suggest to abstract this `use_mla` to `utils.py` and modified the duplicated code also
from lmcache.v1.lookup_client.abstract_client import LookupClientInterface from lmcache.v1.rpc_utils import get_zmq_rpc_path_lmcache if TYPE_CHECKING: # Third Party from vllm.config import VllmConfig logger = init_logger(__name__) class LMCacheLookupClient(LookupClientInterface): """ ZMQ-based looku...
@@ -39,11 +39,17 @@ def __init__(self, vllm_config: "VllmConfig", config: LMCacheEngineConfig): "lmcache_rpc_port", 0 ) self.tensor_parallel_size = vllm_config.parallel_config.tensor_parallel_size + use_mla = (
lmcache/v1/lookup_client/lmcache_lookup_client.py
26
Python
0.429
refactor
86
51
51
false
[bugfix][#1357] Unified the default value if use mla
1,394
LMCache/LMCache
4,864
Python
maobaolong
chunxiaozheng
Review this pull request change. Language: Python File: lmcache/v1/lookup_client/lmcache_lookup_client.py PR Title: [bugfix][#1357] Unified the default value if use mla BEFORE CODE: from lmcache.v1.rpc_utils import get_zmq_rpc_path_lmcache if TYPE_CHECKING: # Third Party from vllm.config import VllmConfig ...
Suggest to abstract this `use_mla` to `utils.py` and modified the duplicated code also
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from lmcache.v1.lookup_client.lmcache_lookup_client import ( LMCacheLookupClient, ) return LMCacheLookupClient(vllm_config, config) @staticmethod def create_lookup_server( lmcache_engine: LMCacheEngine, vllm_config: "VllmConfig", ) -> Opt...
Suggest to abstract a util method `get_extra_config_value(config, default_value)`, this can helps to reduce changes line a lot.
from lmcache.v1.lookup_client.lmcache_lookup_client import ( LMCacheLookupClient, ) return LMCacheLookupClient(vllm_config, config) @staticmethod def create_lookup_server( lmcache_engine: LMCacheEngine, vllm_config: "VllmConfig", ) -> Opt...
@@ -72,11 +72,14 @@ def create_lookup_server( # 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 = (
lmcache/v1/lookup_client/factory.py
26
Python
0.571
refactor
127
51
51
false
[bugfix][#1357] Unified the default value if use mla
1,394
LMCache/LMCache
4,864
Python
maobaolong
chunxiaozheng
Review this pull request change. Language: Python File: lmcache/v1/lookup_client/factory.py PR Title: [bugfix][#1357] Unified the default value if use mla BEFORE CODE: from lmcache.v1.lookup_client.lmcache_lookup_client import ( LMCacheLookupClient, ) return LMCa...
Suggest to abstract a util method `get_extra_config_value(config, default_value)`, this can helps to reduce changes line a lot.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from lmcache.v1.storage_backend.connector.nixl_utils import ( get_correct_nixl_device, ) corrected_device = get_correct_nixl_device( config.nixl_buffer_device, metadata.worker_id, ) ...
nit: ```python config.get_extra_config_value("save_only_first_rank") and metadata.use_mla ``` works here since None is falsy metadata.use_mla and metadata.use_mla just looks weird
dtype=torch.uint8, device=corrected_device, ) nixl_cpu_mem_allocator = NixlCPUMemoryAllocator() nixl_cpu_mem_allocator.init_nixl_memory_allocator( buffer, torch.Size(metadata.kv_shape), ...
@@ -1201,13 +1197,10 @@ def _Create_memory_allocator( return CuFileMemoryAllocator(config.cufile_buffer_size * 1024**2) max_local_cpu_size = config.max_local_cpu_size - save_only_first_rank_default = True if metadata.use_mla else False + # save_only_first_rank only works when use m...
lmcache/v1/cache_engine.py
26
Python
0.786
nitpick
188
51
51
false
[bugfix][#1357] Unified the default value if use mla
1,394
LMCache/LMCache
4,864
Python
sammshen
chunxiaozheng
Review this pull request change. Language: Python File: lmcache/v1/cache_engine.py PR Title: [bugfix][#1357] Unified the default value if use mla BEFORE CODE: from lmcache.v1.storage_backend.connector.nixl_utils import ( get_correct_nixl_device, ) ...
nit: ```python config.get_extra_config_value("save_only_first_rank") and metadata.use_mla ``` works here since None is falsy metadata.use_mla and metadata.use_mla just looks weird
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
if path.is_file(): files = [path] elif path.is_dir(): # Recursively find all .py and .sh files for ext in ["*.py", "*.sh"]: files.extend(path.rglob(ext)) for file in files: self._launch_plugin(file) def _should_skip_plugin(sel...
nit: ```python logger.info(f"worker {self.worker_id} is skipping plugin {file}, which is only for worker ID {plugin_worker_id}") ```
if path.is_file(): files = [path] elif path.is_dir(): # Recursively find all .py and .sh files for ext in ["*.py", "*.sh"]: files.extend(path.rglob(ext)) for file in files: self._launch_plugin(file) def _should_skip_plugin(sel...
@@ -0,0 +1,148 @@ +# SPDX-License-Identifier: Apache-2.0 +# Standard +from pathlib import Path +import atexit +import os +import subprocess +import threading + +# First Party +from lmcache.logging import init_logger + +logger = init_logger(__name__) + + +class PluginLauncher: + def __init__(self, config, role, worke...
lmcache/v1/plugin/plugin_launcher.py
26
Python
0.714
nitpick
136
51
51
false
[feat] Introduce a plugin framework
1,401
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/plugin/plugin_launcher.py PR Title: [feat] Introduce a plugin framework BEFORE CODE: if path.is_file(): files = [path] elif path.is_dir(): # Recursively find all .py and .sh files for ext in ["*.py...
nit: ```python logger.info(f"worker {self.worker_id} is skipping plugin {file}, which is only for worker ID {plugin_worker_id}") ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# SPDX-License-Identifier: Apache-2.0 # Standard from typing import List, Optional, Tuple, no_type_check import asyncio import os import struct # Third Party from redis.asyncio import from_url as redis_from_url from redis.asyncio.sentinel import Sentinel import redis # First Party from lmcache.logging import init_log...
Main Change #2: I had to change redis to batched and async in order to encounter cpu memory pressure. this is not the main purpose of the PR
# SPDX-License-Identifier: Apache-2.0 # Standard from typing import List, Optional, Tuple, no_type_check import asyncio import inspect import os # Third Party import redis # First Party from lmcache.logging import init_logger from lmcache.utils import CacheEngineKey from lmcache.v1.memory_management import MemoryObj ...
lmcache/v1/storage_backend/connector/redis_connector.py
1
Python
0.571
performance
140
26
26
false
[patch]: busy loop on local cpu full
1,429
LMCache/LMCache
4,864
Python
sammshen
sammshen
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/redis_connector.py PR Title: [patch]: busy loop on local cpu full BEFORE CODE: # SPDX-License-Identifier: Apache-2.0 # Standard from typing import List, Optional, Tuple, no_type_check import asyncio import os import struct ...
Main Change #2: I had to change redis to batched and async in order to encounter cpu memory pressure. this is not the main purpose of the PR
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self.lookup_server = lookup_server self.lmcache_worker = lmcache_worker self.instance_id = config.lmcache_instance_id self.worker_id = metadata.worker_id self.nixl_offload_stream = torch.cuda.Stream() @_lmcache_nvtx_annotate def allocate( self, shape: t...
This line causes problems. Some allocator backends don't have `busy_loop` and will cause runtime error
self.lookup_server = lookup_server self.lmcache_worker = lmcache_worker self.instance_id = config.lmcache_instance_id self.worker_id = metadata.worker_id self.nixl_offload_stream = torch.cuda.Stream() @_lmcache_nvtx_annotate def allocate( self, shape: t...
@@ -103,14 +103,17 @@ def allocate( dtype: torch.dtype, fmt: MemoryFormat = MemoryFormat.KV_2LTD, eviction=True, + busy_loop=True, ) -> Optional[MemoryObj]: """ Allocate memory object with memory allocator. Use LRU evictor if eviction is enabled. ...
lmcache/v1/storage_backend/storage_manager.py
26
Python
0.714
suggestion
103
51
51
false
[patch]: busy loop on local cpu full
1,429
LMCache/LMCache
4,864
Python
ApostaC
sammshen
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/storage_manager.py PR Title: [patch]: busy loop on local cpu full BEFORE CODE: self.lookup_server = lookup_server self.lmcache_worker = lmcache_worker self.instance_id = config.lmcache_instance_id sel...
This line causes problems. Some allocator backends don't have `busy_loop` and will cause runtime error
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
if mla is enabled, default is 0; - if mla_lookup_server_worker_id < 0, start lookup server on all workers - if mla_lookup server_worker_id >= 0, start lookup server on the given worker """ def __init__( self, vllm_config: "VllmConfig", ): metadata, config = c...
The loop for range is not suitable for `self.mla_lookup_server_worker_id >= 0` i guess, Would you like to generate a list and add all rank into it? You can loop by use that list instead of the `range(rank)`, maybe this can make code clearer than before, WDYT?
- mla_lookup_server_worker_id: is a flag to control whether to create lookup server only on one worker. if mla is not enabled, default is -1; if mla is enabled, default is 0; - if mla_lookup_server_worker_id < 0, start lookup server on all workers - if mla_lookup server_worke...
@@ -47,17 +51,17 @@ def __init__( "lmcache_rpc_port", 0 ) self.tensor_parallel_size = vllm_config.parallel_config.tensor_parallel_size - use_mla = mla_enabled(vllm_config.model_config) - self.create_lookup_server_only_on_worker_0_for_mla = ( - config.get_extra_con...
lmcache/v1/lookup_client/lmcache_async_lookup_client.py
26
Python
0.643
question
260
51
51
false
support start lookup server on other rank
1,466
LMCache/LMCache
4,864
Python
maobaolong
chunxiaozheng
Review this pull request change. Language: Python File: lmcache/v1/lookup_client/lmcache_async_lookup_client.py PR Title: support start lookup server on other rank BEFORE CODE: if mla is enabled, default is 0; - if mla_lookup_server_worker_id < 0, start lookup server on all workers - if mla_...
The loop for range is not suitable for `self.mla_lookup_server_worker_id >= 0` i guess, Would you like to generate a list and add all rank into it? You can loop by use that list instead of the `range(rank)`, maybe this can make code clearer than before, WDYT?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
local_cpu_backend, dst_device, lmcache_worker, lookup_server, ) backend_name = str(local_disk_backend) storage_backends[backend_name] = local_disk_backend if config.weka_path is not None: weka_backend = WekaGdsBackend(config, loop, me...
Can we make this a single if instead of if-else? ``` if xxx: create_dynamix_backends(xxx) ```
lmcache_worker, lookup_server, ) backend_name = str(local_disk_backend) storage_backends[backend_name] = local_disk_backend if config.weka_path is not None: weka_backend = WekaGdsBackend(config, loop, memory_allocator, dst_device) # TODO(Serapheim): ...
@@ -198,17 +198,20 @@ def CreateStorageBackends( backend_name = str(remote_backend) storage_backends[backend_name] = remote_backend - # Create dynamic backends from configuration - create_dynamic_backends( - config, - metadata, - loop, - memory_allocator, - l...
lmcache/v1/storage_backend/__init__.py
26
Python
0.643
question
99
51
51
false
[Bugfix][PD] Fix nixl initialization problem
1,494
LMCache/LMCache
4,864
Python
YaoJiayi
Shaoting-Feng
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/__init__.py PR Title: [Bugfix][PD] Fix nixl initialization problem BEFORE CODE: local_cpu_backend, dst_device, lmcache_worker, lookup_server, ) backend_name = str(local...
Can we make this a single if instead of if-else? ``` if xxx: create_dynamix_backends(xxx) ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# change that in the future. storage_backends[str(weka_backend)] = weka_backend if config.gds_path is not None: gds_backend = GdsBackend(config, loop, memory_allocator, dst_device) storage_backends[str(gds_backend)] = gds_backend if config.remote_url is not None: remote_b...
Using a placeholder like `pass` is ok in test code but not here. I think the code below is cleaner and is easier to understand the logic. ```suggestion if not config.enable_nixl or config.local_cpu: # Create dynamic backends from configuration create_dynamic_backends( config, ...
if config.gds_path is not None: gds_backend = GdsBackend(config, loop, memory_allocator, dst_device) storage_backends[str(gds_backend)] = gds_backend if config.remote_url is not None: remote_backend = RemoteBackend( config, metadata, loop, local_cpu_backend, dst_device, looku...
@@ -198,17 +198,20 @@ def CreateStorageBackends( backend_name = str(remote_backend) storage_backends[backend_name] = remote_backend - # Create dynamic backends from configuration - create_dynamic_backends( - config, - metadata, - loop, - memory_allocator, - l...
lmcache/v1/storage_backend/__init__.py
26
Python
0.929
suggestion
520
50
46
false
[Bugfix][PD] Fix nixl initialization problem
1,494
LMCache/LMCache
4,864
Python
hickeyma
Shaoting-Feng
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/__init__.py PR Title: [Bugfix][PD] Fix nixl initialization problem BEFORE CODE: # change that in the future. storage_backends[str(weka_backend)] = weka_backend if config.gds_path is not None: gds_backend =...
Using a placeholder like `pass` is ok in test code but not here. I think the code below is cleaner and is easier to understand the logic. ```suggestion if not config.enable_nixl or config.local_cpu: # Create dynamic backends from configuration create_dynamic_backends( config, ...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
) self.use_layerwise = config.use_layerwise self.num_layers = metadata.kv_shape[0] if self.use_layerwise: if config.enable_blending: self.fmt = MemoryFormat.KV_2TD else: self.fmt = MemoryFormat.KV_T2D # NOTE(ApostaC): ...
caught by integration tests ! :) ```text (EngineCore_0 pid=67) File "/opt/venv/lib/python3.12/site-packages/lmcache/v1/cache_engine.py", line 173, in __init__ --   | (EngineCore_0 pid=67) self.force_store_wait = config.extra_config.get("force_store_wait", False)   | (EngineCore_0 pid=67) ...
) self.use_layerwise = config.use_layerwise self.num_layers = metadata.kv_shape[0] if self.use_layerwise: if config.enable_blending: self.fmt = MemoryFormat.KV_2TD else: self.fmt = MemoryFormat.KV_T2D # NOTE(ApostaC): ...
@@ -169,6 +169,12 @@ def __init__( self.post_inited = False + # Whether to force store to wait if no CPU buffer is available + self.force_store_wait = ( + config.extra_config and \ + config.extra_config.get("force_store_wait", False + ) +
lmcache/v1/cache_engine.py
26
Python
1
performance
580
51
51
false
[Misc][Core] add extra config `force_store_wait` to make sure store does not skip any requests
1,499
LMCache/LMCache
4,864
Python
sammshen
ApostaC
Review this pull request change. Language: Python File: lmcache/v1/cache_engine.py PR Title: [Misc][Core] add extra config `force_store_wait` to make sure store does not skip any requests BEFORE CODE: ) self.use_layerwise = config.use_layerwise self.num_layers = metadata.kv_shape[0] ...
caught by integration tests ! :) ```text (EngineCore_0 pid=67) File "/opt/venv/lib/python3.12/site-packages/lmcache/v1/cache_engine.py", line 173, in __init__ --   | (EngineCore_0 pid=67) self.force_store_wait = config.extra_config.get("force_store_wait", False)   | (EngineCore_0 pid=67) ...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
raise ValueError(f"No adapter found for URL: {self.context.url}") def CreateConnector( url: str, loop: asyncio.AbstractEventLoop, local_cpu_backend: LocalCPUBackend, config: Optional[LMCacheEngineConfig] = None, metadata: Optional[LMCacheEngineMetadata] = None, ) -> InstrumentedRemoteConn...
`benchmark` --> `mock`? Because its a mock connector that can be used for bench marking.
raise ValueError(f"No adapter found for URL: {self.context.url}") def CreateConnector( url: str, loop: asyncio.AbstractEventLoop, local_cpu_backend: LocalCPUBackend, config: Optional[LMCacheEngineConfig] = None, metadata: Optional[LMCacheEngineMetadata] = None, ) -> InstrumentedRemoteConn...
@@ -219,6 +219,7 @@ def CreateConnector( - audit://host:port[?verify=true|false] - fs://[host:port]/path - s3://[bucket].s3express-[az_id].[region].amazonaws.com" + - benchmark://[capacity]/?peeking_latency=[ms]&read_throughput=[GB/s]&write_throughput=[GB/s]
lmcache/v1/storage_backend/connector/__init__.py
26
Python
0.429
suggestion
88
51
51
false
[Feat]: Mock Connector
1,500
LMCache/LMCache
4,864
Python
hickeyma
sammshen
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/__init__.py PR Title: [Feat]: Mock Connector BEFORE CODE: raise ValueError(f"No adapter found for URL: {self.context.url}") def CreateConnector( url: str, loop: asyncio.AbstractEventLoop, local_cpu_ba...
`benchmark` --> `mock`? Because its a mock connector that can be used for bench marking.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) self.plugin_processes.append(proc) logger.info(f"Launched plugin: {file} with {interpreter}") # Start thread to capture output continuo...
Error reading plugin file {file}: {e} --> Error reading interpreter from plugin file {file} - using default interpreters: {e}
env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) self.plugin_processes.append(proc) logger.info(f"Launched plugin: {file} with {interpreter}") # Start thread to capture output continuo...
@@ -109,22 +110,32 @@ def _launch_plugin(self, file: Path): def _get_interpreter(self, file: Path) -> str: """Get interpreter from first line comment""" + interpreters = [] try: with open(file, "r", encoding="utf-8") as f: first_line = f.readline().strip() ...
lmcache/v1/plugin/plugin_launcher.py
26
Python
0.5
suggestion
125
51
51
false
[Improvement][PluginFramework] Add default interpreter from plugin script
1,504
LMCache/LMCache
4,864
Python
hickeyma
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/plugin/plugin_launcher.py PR Title: [Improvement][PluginFramework] Add default interpreter from plugin script BEFORE CODE: env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, tex...
Error reading plugin file {file}: {e} --> Error reading interpreter from plugin file {file} - using default interpreters: {e}
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
).start() except Exception as e: logger.error(f"Failed to launch plugin {file}: {e}") def _get_interpreter(self, file: Path) -> str: """Get interpreter from first line comment""" interpreters = [] try: with open(file, "r", encoding="utf-8") as f: ...
```suggestion else: raise ValueError(f"Plugin type {file.suffix} not supported ") ```
).start() except Exception as e: logger.error(f"Failed to launch plugin {file}: {e}") def _get_interpreter(self, file: Path) -> str: """Get interpreter from first line comment""" interpreters = [] try: with open(file, "r", encoding="utf-8") as f: ...
@@ -109,22 +110,32 @@ def _launch_plugin(self, file: Path): def _get_interpreter(self, file: Path) -> str: """Get interpreter from first line comment""" + interpreters = [] try: with open(file, "r", encoding="utf-8") as f: first_line = f.readline().strip() ...
lmcache/v1/plugin/plugin_launcher.py
26
Python
0.857
suggestion
116
51
51
false
[Improvement][PluginFramework] Add default interpreter from plugin script
1,504
LMCache/LMCache
4,864
Python
hickeyma
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/plugin/plugin_launcher.py PR Title: [Improvement][PluginFramework] Add default interpreter from plugin script BEFORE CODE: ).start() except Exception as e: logger.error(f"Failed to launch plugin {file}: {e}") def...
```suggestion else: raise ValueError(f"Plugin type {file.suffix} not supported ") ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def _get_interpreter(self, file: Path) -> str: """Get interpreter from first line comment""" interpreters = [] try: with open(file, "r", encoding="utf-8") as f: first_line = f.readline().strip() if first_line.startswith("#!"): ...
resolved_interp --> resolved_interpreter
def _get_interpreter(self, file: Path) -> str: """Get interpreter from first line comment""" interpreters = [] try: with open(file, "r", encoding="utf-8") as f: first_line = f.readline().strip() if first_line.startswith("#!"): ...
@@ -109,22 +110,32 @@ def _launch_plugin(self, file: Path): def _get_interpreter(self, file: Path) -> str: """Get interpreter from first line comment""" + interpreters = [] try: with open(file, "r", encoding="utf-8") as f: first_line = f.readline().strip() ...
lmcache/v1/plugin/plugin_launcher.py
26
Python
0.071
suggestion
40
51
51
false
[Improvement][PluginFramework] Add default interpreter from plugin script
1,504
LMCache/LMCache
4,864
Python
hickeyma
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/plugin/plugin_launcher.py PR Title: [Improvement][PluginFramework] Add default interpreter from plugin script BEFORE CODE: def _get_interpreter(self, file: Path) -> str: """Get interpreter from first line comment""" interpreters...
resolved_interp --> resolved_interpreter
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def relative_time(df, start_time): """ Relative time to the start of the benchmark. """ df["request_start"] = df["request_start"] - start_time df["request_end"] = df["request_end"] - start_time df["ttft_time"] = df["request_start"] + df["ttft"] def visualize_results(warmup_df, benchmark_df):...
nit: can we change the "Request TTFT" to "Request first token"?
def relative_time(df, start_time): """ Relative time to the start of the benchmark. """ df["request_start"] = df["request_start"] - start_time df["request_end"] = df["request_end"] - start_time df["ttft_time"] = df["request_start"] + df["ttft"] def visualize_results(warmup_df, benchmark_df):...
@@ -242,6 +312,55 @@ def repeat_prompts(prompts, repeat_count, mode: str): ) +def relative_time(df, start_time): + """ + Relative time to the start of the benchmark. + """ + df["request_start"] = df["request_start"] - start_time + df["request_end"] = df["request_end"] - start_time + df["t...
benchmarks/long_doc_qa/long_doc_qa.py
26
Python
0.286
question
63
51
51
false
[Benchmark] Add completions and visualization to long doc qa
1,519
LMCache/LMCache
4,864
Python
ApostaC
sammshen
Review this pull request change. Language: Python File: benchmarks/long_doc_qa/long_doc_qa.py PR Title: [Benchmark] Add completions and visualization to long doc qa BEFORE CODE: def relative_time(df, start_time): """ Relative time to the start of the benchmark. """ df["request_start"] = df["reques...
nit: can we change the "Request TTFT" to "Request first token"?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Adapted from # https://github.com/vllm-project/vllm/blob/main/benchmarks/benchmark_long_document_qa_throughput.py """ Commandline arguments: --num-documents: The number of documents to sample prompts from. ...
Is this still the default method?
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Adapted from # https://github.com/vllm-project/vllm/blob/main/benchmarks/benchmark_long_document_qa_throughput.py """ Commandline arguments: --num-documents: The number of documents to sample prompts from. ...
@@ -17,11 +17,10 @@ (Optional, default: 2) --repeat-mode: The mode to repeat prompts. The supported modes are: - - 'random': shuffle the prompts randomly. (Default) - - 'tile': the entire prompt list is repeated in sequence. (Potentially - lowest cache hit) + ...
benchmarks/long_doc_qa/long_doc_qa.py
20
Python
0.071
question
33
45
45
false
[Benchmark]: Benchmarking Recommendation + Documentation
1,534
LMCache/LMCache
4,864
Python
Shaoting-Feng
sammshen
Review this pull request change. Language: Python File: benchmarks/long_doc_qa/long_doc_qa.py PR Title: [Benchmark]: Benchmarking Recommendation + Documentation BEFORE CODE: # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Adapted from # https://github.com...
Is this still the default method?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
if actual_latency_gain < args.expected_latency_gain: sys.exit( f"ERROR: latency gain {actual_latency_gain:.2f}× < expected " f"{args.expected_latency_gain:.2f}×" ) def create_argument_parser(): parser = argparse.ArgumentParser( description="B...
Could you please also add this field to `LMCache/.buildkite/configs/xx.yaml`? I know this is not ideal but currently the comprehensive tests use a lot of default values in the `long_doc_qa.py`.
if actual_latency_gain < args.expected_latency_gain: sys.exit( f"ERROR: latency gain {actual_latency_gain:.2f}× < expected " f"{args.expected_latency_gain:.2f}×" ) def create_argument_parser(): parser = argparse.ArgumentParser( description="B...
@@ -500,7 +518,7 @@ def create_argument_parser(): parser.add_argument( "--num-documents", type=int, - default=8, + default=20,
benchmarks/long_doc_qa/long_doc_qa.py
26
Python
0.571
performance
193
51
51
false
[Benchmark]: Benchmarking Recommendation + Documentation
1,534
LMCache/LMCache
4,864
Python
Shaoting-Feng
sammshen
Review this pull request change. Language: Python File: benchmarks/long_doc_qa/long_doc_qa.py PR Title: [Benchmark]: Benchmarking Recommendation + Documentation BEFORE CODE: if actual_latency_gain < args.expected_latency_gain: sys.exit( f"ERROR: latency gain {actual_latency_gain:...
Could you please also add this field to `LMCache/.buildkite/configs/xx.yaml`? I know this is not ideal but currently the comprehensive tests use a lot of default values in the `long_doc_qa.py`.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self.worker_id, self.chunk_hash, ) ) return hash( ( self.fmt, self.model_name, self.world_size, self.worker_id, self.chunk_hash, "%".joi...
Does this string concat can be avoid if we just use self.tags equals other.tags?
self.worker_id, self.chunk_hash, ) ) return hash( ( self.fmt, self.model_name, self.world_size, self.worker_id, self.chunk_hash, "%".joi...
@@ -126,6 +126,32 @@ def __hash__(self): ) ) + def __eq__(self, other): + if not isinstance(other, CacheEngineKey): + return False + + if type(self) is CacheEngineKey and type(other) is not CacheEngineKey: + return False + + self_tags_str = ( + ...
lmcache/utils.py
26
Python
0.286
question
80
51
51
false
[bugfix] fix not hit in LocalCpuBackend
1,545
LMCache/LMCache
4,864
Python
maobaolong
chunxiaozheng
Review this pull request change. Language: Python File: lmcache/utils.py PR Title: [bugfix] fix not hit in LocalCpuBackend BEFORE CODE: self.worker_id, self.chunk_hash, ) ) return hash( ( self.fmt, ...
Does this string concat can be avoid if we just use self.tags equals other.tags?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
with self.key_lock: for key in keys: metadata = self.key_dict.get(key.chunk_hash) if metadata is None: obj_list.append(None) continue dtype = metadata.dtype shape = metadata.shape ...
file_indices could also use a generic name
with self.key_lock: for key in keys: metadata = self.key_dict.get(key.chunk_hash) if metadata is None: obj_list.append(None) continue dtype = metadata.dtype shape = metadata.shape ...
@@ -357,7 +437,7 @@ async def file_to_gpu( if not mem_indices: return obj_list - handle = self.agent.get_file_to_gpu_handle(mem_indices, file_indices) + handle = self.agent.get_storage_to_mem_handle(mem_indices, file_indices)
lmcache/v1/storage_backend/nixl_storage_backend.py
26
Python
0.143
suggestion
42
51
51
false
[Core] Support NIXL storage obj backend
1,557
LMCache/LMCache
4,864
Python
jgoldsch12
tshmilnvidia
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/nixl_storage_backend.py PR Title: [Core] Support NIXL storage obj backend BEFORE CODE: with self.key_lock: for key in keys: metadata = self.key_dict.get(key.chunk_hash) if metadata ...
file_indices could also use a generic name
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
Args: req_meta (ReqMeta): the request metadata. """ self.requests.append(req_meta) class LMCacheConnectorV1Impl: def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, parent: KVConnectorBase_V1, ): self._parent = paren...
the `LMCacheEngineConfig` is not a single instance, other `LMCacheEngineConfig` object does not have the configs from vllm when they are inited in other position, I am not sure if this will cause any inconsistency issues.
Args: req_meta (ReqMeta): the request metadata. """ self.requests.append(req_meta) class LMCacheConnectorV1Impl: def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, parent: KVConnectorBase_V1, ): self._parent = paren...
@@ -547,7 +547,24 @@ def __init__( assert isinstance(config, LMCacheEngineConfig), ( "LMCache v1 configuration is should be passed for vLLM v1." ) + # Put the leading with "lmcache." and matched configs from + # vllm extra_config to the config + kv_connector_extra_con...
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.643
performance
221
51
51
false
[Improve] Support pass through the lmcache config from vllm extra config
1,568
LMCache/LMCache
4,864
Python
chunxiaozheng
maobaolong
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: [Improve] Support pass through the lmcache config from vllm extra config BEFORE CODE: Args: req_meta (ReqMeta): the request metadata. """ self.requests.append(req_meta) ...
the `LMCacheEngineConfig` is not a single instance, other `LMCacheEngineConfig` object does not have the configs from vllm when they are inited in other position, I am not sure if this will cause any inconsistency issues.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
class LMCacheConnectorV1Impl: def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, parent: KVConnectorBase_V1, ): self._parent = parent self.kv_role = vllm_config.kv_transfer_config.kv_role self.worker_count = vllm_config.parallel_config...
nit: the validation happens with `hasattr()` and not with with the function `validate_and_set_config_value()`
class LMCacheConnectorV1Impl: def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, parent: KVConnectorBase_V1, ): self._parent = parent self.kv_role = vllm_config.kv_transfer_config.kv_role self.worker_count = vllm_config.parallel_config...
@@ -547,7 +547,24 @@ def __init__( assert isinstance(config, LMCacheEngineConfig), ( "LMCache v1 configuration is should be passed for vLLM v1." ) + # Put the leading with "lmcache." and matched configs from + # vllm extra_config to the config + kv_connector_extra_con...
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.5
nitpick
109
51
51
false
[Improve] Support pass through the lmcache config from vllm extra config
1,568
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: [Improve] Support pass through the lmcache config from vllm extra config BEFORE CODE: class LMCacheConnectorV1Impl: def __init__( self, vllm_config: "VllmConfig", role: KVConne...
nit: the validation happens with `hasattr()` and not with with the function `validate_and_set_config_value()`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def mock_up_broadcast_object_fn(a: Any, i: int) -> None: raise NotImplementedError("Calling invalid broadcast object function") #### Python equivalents of CPP CUDA functions #### def alloc_pinned_numa_ptr(size: int) -> torch.Tensor: # Create a 1D uint8 CPU tensor in pinned memory, as uint8 == 1 byte # R...
I like this idea of having the same set of C functions implemented in Python for non-CUDA platforms. Can we separate those to a new source file so that we can import it as: ``` if torch.cuda.is_available(): import lmcache.c_ops as lmc_ops else: import lmcache.mockup_ops as lmc_ops # could have differe...
# SPDX-License-Identifier: Apache-2.0 # Future from __future__ import annotations # Standard from dataclasses import dataclass from typing import TYPE_CHECKING, Any, List, Optional, Tuple import asyncio import hashlib import threading import traceback try: # Third Party from nvtx import annotate # type: igno...
@@ -384,3 +384,26 @@ def mock_up_broadcast_fn(t: torch.Tensor, i: int) -> None: def mock_up_broadcast_object_fn(a: Any, i: int) -> None: raise NotImplementedError("Calling invalid broadcast object function") + + +#### Python equivalents of CPP CUDA functions #### +def alloc_pinned_numa_ptr(size: int) -> torch....
lmcache/utils.py
26
Python
1
performance
438
27
387
false
[Test]: Enable unit tests to run on non-CUDA environment
1,575
LMCache/LMCache
4,864
Python
ApostaC
hickeyma
Review this pull request change. Language: Python File: lmcache/utils.py PR Title: [Test]: Enable unit tests to run on non-CUDA environment BEFORE CODE: def mock_up_broadcast_object_fn(a: Any, i: int) -> None: raise NotImplementedError("Calling invalid broadcast object function") #### Python equivalents of C...
I like this idea of having the same set of C functions implemented in Python for non-CUDA platforms. Can we separate those to a new source file so that we can import it as: ``` if torch.cuda.is_available(): import lmcache.c_ops as lmc_ops else: import lmcache.mockup_ops as lmc_ops # could have differe...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
request: "Request", num_computed_tokens: int, ) -> Optional[int]: """ Check for external KV cache hit. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request ...
Can we have a helper function called `extract_mm_features` that returns `Optional[Tuple[mm_hashes, mm_positions]]`? So the code will be like: ```python if mm_features := extract_mm_features(request): token_ids = torch.tensor(request.prompt_token_ids) mm_hashes, mm_positions = mm_features apply_mm_ha...
def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> Optional[int]: """ Check for external KV cache hit. Args: request (Request): the request object. num_computed_tokens (int): the number of locally ...
@@ -1055,23 +1058,27 @@ def get_num_new_matched_tokens( token_ids = request.prompt_token_ids # If the request has multimodal hashes, apply them to the token ids - if request.mm_features: + if request.mm_features or request.mm_hashes:
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.857
refactor
349
51
51
false
[Core] Add backward compatibility with vllm
1,583
LMCache/LMCache
4,864
Python
ApostaC
Shaoting-Feng
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: [Core] Add backward compatibility with vllm BEFORE CODE: request: "Request", num_computed_tokens: int, ) -> Optional[int]: """ Check for external KV cache hit. A...
Can we have a helper function called `extract_mm_features` that returns `Optional[Tuple[mm_hashes, mm_positions]]`? So the code will be like: ```python if mm_features := extract_mm_features(request): token_ids = torch.tensor(request.prompt_token_ids) mm_hashes, mm_positions = mm_features apply_mm_ha...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
num_computed_tokens: int, ) -> Optional[int]: """ Check for external KV cache hit. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request Returns: the...
```suggestion mm_hashes, mm_positions = extract_mm_features(request) if mm_hashes and mm_positions: ```
################### # Scheduler side APIs #################### @_lmcache_nvtx_annotate def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> Optional[int]: """ Check for external KV cache hit. Args: ...
@@ -1055,23 +1052,17 @@ def get_num_new_matched_tokens( token_ids = request.prompt_token_ids # If the request has multimodal hashes, apply them to the token ids - if request.mm_features: + mm_features = extract_mm_features(request) + if mm_features[0] != [] and mm_features[1] !=...
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.786
refactor
122
51
51
false
[Core] Add backward compatibility with vllm
1,583
LMCache/LMCache
4,864
Python
ApostaC
Shaoting-Feng
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: [Core] Add backward compatibility with vllm BEFORE CODE: num_computed_tokens: int, ) -> Optional[int]: """ Check for external KV cache hit. Args: request (Re...
```suggestion mm_hashes, mm_positions = extract_mm_features(request) if mm_hashes and mm_positions: ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
echo \"Model ${model} is available on ${port}\" "; then echo "OpenAI API server did not start" docker logs $cid return 1 fi } run_lmcache_vllmopenai_container() { local docker="$1" local vllm="$2" local cfg_name="$3" LOGFILE="/tmp/build_${BUILD_ID}_${cfg_name}.lo...
We can also mount the entire config directory so that it doesn’t have to be only for the MLA test.
echo \"Model ${model} is available on ${port}\" "; then echo "OpenAI API server did not start" docker logs $cid return 1 fi } run_lmcache_vllmopenai_container() { local docker="$1" local vllm="$2" local cfg_name="$3" LOGFILE="/tmp/build_${BUILD_ID}_${cfg_name}.lo...
@@ -111,16 +111,18 @@ run_lmcache_vllmopenai_container() { local cfg_name="$3" LOGFILE="/tmp/build_${BUILD_ID}_${cfg_name}.log" - # Pick the GPU with the largest free memory - source "$ORIG_DIR/.buildkite/scripts/pick-free-gpu.sh" "" + # Pick the GPUs based on config + gpu_count=$(yq -r '.docker...
.buildkite/scripts/vllm-integration-tests.sh
26
Shell
0.214
suggestion
98
51
51
false
Update vLLM options for MLA test
1,588
LMCache/LMCache
4,864
Python
Shaoting-Feng
yoo-kumaneko
Review this pull request change. Language: Shell File: .buildkite/scripts/vllm-integration-tests.sh PR Title: Update vLLM options for MLA test BEFORE CODE: echo \"Model ${model} is available on ${port}\" "; then echo "OpenAI API server did not start" docker logs $cid return 1 ...
We can also mount the entire config directory so that it doesn’t have to be only for the MLA test.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
assert len(self.kv_caches) > 0 kvcaches = list(self.kv_caches.values()) attn_metadata = forward_context.attn_metadata if attn_metadata is None: logger.debug("In connector.start_load_kv, but the attn_metadata is None") return assert self.lmcache_engine is...
Using `kvcaches[0][0].device` looks messy. Can we have a `self.device` somewhere?
"""Get vLLM version information. Returns: str: vLLM version string """ return VLLM_VERSION @_lmcache_nvtx_annotate def _init_kv_caches_from_forward_context(self, forward_context: "ForwardContext"): for layer_name in forward_context.no_compile_layers: ...
@@ -822,7 +840,7 @@ def start_load_kv(self, forward_context: "ForwardContext", **kwargs) -> None: tokens = request.token_ids # TODO: have a pre-allocated buffer to hold the slot_mappings - slot_mapping = request.slot_mapping.cuda() + slot_mapping = request.slot_mapping....
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.357
performance
81
51
51
false
Add XPU support to LMCache for CPU/disk offloading
1,593
LMCache/LMCache
4,864
Python
YaoJiayi
zhenwei-intel
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: Add XPU support to LMCache for CPU/disk offloading BEFORE CODE: assert len(self.kv_caches) > 0 kvcaches = list(self.kv_caches.values()) attn_metadata = forward_context.attn_metadata...
Using `kvcaches[0][0].device` looks messy. Can we have a `self.device` somewhere?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
) # Third Party from vllm.attention.backends.flashmla import FlashMLAMetadata from vllm.attention.backends.mla.common import MLACommonMetadata from vllm.config import ( CacheConfig, ModelConfig, ParallelConfig, SchedulerConfig, ) from vllm.sequence import IntermediateTensors from vllm.utils import ...
Would be great if you make this device check by vLLM way: ``` from vllm.platforms import current_platform if current_platform.is_cuda_alike(): ```
) # Third Party from vllm.attention.backends.flashmla import FlashMLAMetadata from vllm.attention.backends.mla.common import MLACommonMetadata from vllm.config import ( CacheConfig, ModelConfig, ParallelConfig, SchedulerConfig, ) from vllm.platforms import current_platform from vllm.sequence import...
@@ -49,7 +49,8 @@ logger = init_logger(__name__) -LMCACHE_CUDA_STREAM = torch.cuda.Stream() +if torch.cuda.is_available():
lmcache/integration/vllm/vllm_adapter.py
26
Python
0.714
suggestion
146
51
51
false
Add XPU support to LMCache for CPU/disk offloading
1,593
LMCache/LMCache
4,864
Python
KuntaiDu
zhenwei-intel
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_adapter.py PR Title: Add XPU support to LMCache for CPU/disk offloading BEFORE CODE: ) # Third Party from vllm.attention.backends.flashmla import FlashMLAMetadata from vllm.attention.backends.mla.common import MLACommonMetada...
Would be great if you make this device check by vLLM way: ``` from vllm.platforms import current_platform if current_platform.is_cuda_alike(): ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
kvcaches = list(self.kv_caches.values()) attn_metadata = forward_context.attn_metadata if attn_metadata is None: logger.debug("In connector.start_load_kv, but the attn_metadata is None") return assert self.lmcache_engine is not None self.lmcache_engine....
this should not be the cause of the performance degradation. `.cuda()` should call `.to()` under the hood
assert len(self.kv_caches) > 0 kvcaches = list(self.kv_caches.values()) attn_metadata = forward_context.attn_metadata if attn_metadata is None: logger.debug("In connector.start_load_kv, but the attn_metadata is None") return assert self.lmcache_engine is...
@@ -863,7 +884,7 @@ def start_load_kv(self, forward_context: "ForwardContext", **kwargs) -> None: tokens = request.token_ids # TODO: have a pre-allocated buffer to hold the slot_mappings - slot_mapping = request.slot_mapping.cuda() + slot_mapping = request.slot_mapping....
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.714
performance
105
51
51
false
Add XPU support to LMCache for CPU/disk offloading
1,593
LMCache/LMCache
4,864
Python
sammshen
zhenwei-intel
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: Add XPU support to LMCache for CPU/disk offloading BEFORE CODE: kvcaches = list(self.kv_caches.values()) attn_metadata = forward_context.attn_metadata if attn_metadata is None: ...
this should not be the cause of the performance degradation. `.cuda()` should call `.to()` under the hood
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def _get_file_path( self, key: CacheEngineKey, generate_tmp_path=False ) -> Tuple[Path, Optional[Path]]: """Get file path and tmp path for the given key""" # If there's only one path, use it directly if len(self.base_paths) == 1: base_path = self.base_paths[0] ...
This method didn't need the second value of the tuple which returned by `_get_file_path `
def _get_base_path(self, key: CacheEngineKey) -> Path: """Get file base path for the given key""" if len(self.base_paths) == 1: base_path = self.base_paths[0] else: # Calculate hash value and modulo to select path hash_val = abs(key.chunk_hash) ...
@@ -69,21 +82,28 @@ def _get_file_path(self, key: CacheEngineKey) -> Path: base_path = self.base_paths[idx] key_path = key.to_string().replace("/", "-") + ".data" - return base_path / key_path + data_path = base_path / key_path + tmp_path = None + if generate_tmp_path...
lmcache/v1/storage_backend/connector/fs_connector.py
26
Python
0.357
suggestion
89
51
51
false
support tmp path in FSConnector
1,603
LMCache/LMCache
4,864
Python
maobaolong
chunxiaozheng
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/fs_connector.py PR Title: support tmp path in FSConnector BEFORE CODE: def _get_file_path( self, key: CacheEngineKey, generate_tmp_path=False ) -> Tuple[Path, Optional[Path]]: """Get file path and tm...
This method didn't need the second value of the tuple which returned by `_get_file_path `
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
) else: user_session = UserSession(user_config, self.use_sharegpt) self.sessions.append(user_session) return user_session def _remove_finished_sessions(self): sessions_to_remove = [s for s in self.sessions if s.finished] if len(sessions_to_remove) > 0...
In my opinion, we should not add this additional condition. We use this script to benchmark different engines. If an engine performs poorly and requests finish slowly, adding this condition will cause the QPS to decrease, making the workload lighter than for an engine that performs well. This would result in an unfair ...
def _create_user_session(self): self.user_id += 1 user_config = UserConfig.new_user_config(self.user_id, self.workload_config) if self.use_sharegpt: user_session = UserSession( user_config, self.use_sharegpt, self.sharegpt_data[self.user_id] ) ...
@@ -426,7 +426,8 @@ def step(self, timestamp: float, executor: RequestExecutor): if self.start_time is None: self.start_time = timestamp - if timestamp - self.last_user_join > self.gap_between_users: + # New user session only joins when meets time interval and active user count is ...
benchmarks/multi_round_qa/multi-round-qa.py
26
Python
0.5
performance
331
51
51
false
[Benchmark] configure user stacking at high qps in multi-round-qa
1,609
LMCache/LMCache
4,864
Python
Shaoting-Feng
yuezhu1
Review this pull request change. Language: Python File: benchmarks/multi_round_qa/multi-round-qa.py PR Title: [Benchmark] configure user stacking at high qps in multi-round-qa BEFORE CODE: ) else: user_session = UserSession(user_config, self.use_sharegpt) self.sessions.append...
In my opinion, we should not add this additional condition. We use this script to benchmark different engines. If an engine performs poorly and requests finish slowly, adding this condition will cause the QPS to decrease, making the workload lighter than for an engine that performs well. This would result in an unfair ...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
send_path: str, done_event: threading.Event, ): """ Upload a file to S3. """ headers = HttpHeaders() headers.add("Host", self.s3_endpoint) req = HttpRequest("PUT", self._format_safe_path(key_str), headers) done = {"err": None, "status": None}...
Why do we have a `_put` and another `put`?
headers.add("Host", self.s3_endpoint) req = HttpRequest("PUT", self._format_safe_path(key_str), headers) done = {"err": None, "status": None} def on_done(error=None, status_code=None, **kwargs): done["err"] = error done["status"] = status_code if d...
@@ -464,7 +542,7 @@ def on_done(error=None, status_code=None, **kwargs): on_done=on_done, ) - async def put(self, key: CacheEngineKey, memory_obj: MemoryObj): + async def _put(self, key: CacheEngineKey, memory_obj: MemoryObj):
lmcache/v1/storage_backend/connector/s3_connector.py
26
Python
0.214
question
42
51
51
false
[feat]: working async s3
1,614
LMCache/LMCache
4,864
Python
YaoJiayi
sammshen
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/s3_connector.py PR Title: [feat]: working async s3 BEFORE CODE: send_path: str, done_event: threading.Event, ): """ Upload a file to S3. """ headers = HttpHeaders() ...
Why do we have a `_put` and another `put`?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
priority=Priorities.PREFETCH, ) async def list(self) -> List[str]: raise NotImplementedError def support_ping(self) -> bool: return False # TODO(Jiayi): This needs to be implemented. async def ping(self) -> int: raise NotImplementedError def support_ba...
We can move the mhm-related cleanup code to the memory allocator
# SPDX-License-Identifier: Apache-2.0 # Standard from enum import IntEnum, auto from functools import partial from typing import List, Optional from urllib.parse import quote as url_quote import asyncio import ctypes import mmap import os import tempfile # Third Party from awscrt import auth, io, s3 from awscrt.http i...
@@ -514,6 +659,12 @@ def support_batched_get(self) -> bool: return True async def close(self): - for shm in self.shms: - shm.close() - shm.unlink() + await self.pq_executor.shutdown(wait=True) + # let python GC clean up mmap inodes + for mm in self.adhoc...
lmcache/v1/storage_backend/connector/s3_connector.py
26
Python
0.429
suggestion
64
27
654
false
[feat]: working async s3
1,614
LMCache/LMCache
4,864
Python
YaoJiayi
sammshen
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/s3_connector.py PR Title: [feat]: working async s3 BEFORE CODE: priority=Priorities.PREFETCH, ) async def list(self) -> List[str]: raise NotImplementedError def support_ping(self) -> bo...
We can move the mhm-related cleanup code to the memory allocator
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
hash_buf, offset_buf, lookup_id_buf, request_configs_buf, ] else: tokens_buf = self.encoder.encode(token_ids) msg_buf = [ tokens_buf, lookup_id_buf, request_configs...
why don't we set socket timeouts once at initiatialization?
for start, end, key in self.token_database.process_tokens( token_ids, make_key=False ): hashes.append(key) offsets.append(end - start) hash_buf = self.encoder.encode(hashes) offset_buf = self.encoder.encode(offsets) ...
@@ -128,16 +129,71 @@ def lookup( request_configs_buf, ] - for i in range(ranks): - self.sockets[i].send_multipart(msg_buf, copy=False) - results = [] - # TODO(Jiayi): we can use zmq poll to optimize a bit + max_retries = self.config.lookup_max_re...
lmcache/v1/lookup_client/lmcache_lookup_client.py
26
Python
0.214
question
60
51
51
false
[Improve] Add timeout for lookup client
1,615
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/lookup_client/lmcache_lookup_client.py PR Title: [Improve] Add timeout for lookup client BEFORE CODE: hash_buf, offset_buf, lookup_id_buf, request_configs_buf, ] el...
why don't we set socket timeouts once at initiatialization?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def preprocess_attention_qk(self, q: torch.Tensor, k: torch.Tensor, attn_layer): """ Qwen3-specific Q/K preprocessing - apply q_norm and k_norm Args: q: Query tensor k: Key tensor attn_layer: Attention layer Returns: tuple: (processe...
Can this function be fused with rotary embedding kernel?
# SPDX-License-Identifier: Apache-2.0 # First Party from lmcache.v1.compute.models.base import LMCBaseModel class LMCQwen3Model(LMCBaseModel): def _process_qkv(self, q, k, v, layer): """Process QKV tensors for Qwen3 model with q_norm and k_norm layers.""" # Qwen3 has q_norm and k_norm layers ...
@@ -0,0 +1,75 @@ +# SPDX-License-Identifier: Apache-2.0 +# Third Party +import torch + +# Local +from .base import LMCBaseModel + +# TODO(Jiayi): A few things need to be tested/supported: +# TP, PP, Multimodal + + +class LMCQwen3Model(LMCBaseModel): + """LMC Qwen3 model implementation, inheriting from base model cla...
lmcache/v1/compute/models/qwen3.py
26
Python
0.286
question
56
29
25
false
[Model] Add Qwen3 model support for CacheBlend
1,633
LMCache/LMCache
4,864
Python
YaoJiayi
junl666
Review this pull request change. Language: Python File: lmcache/v1/compute/models/qwen3.py PR Title: [Model] Add Qwen3 model support for CacheBlend BEFORE CODE: def preprocess_attention_qk(self, q: torch.Tensor, k: torch.Tensor, attn_layer): """ Qwen3-specific Q/K preprocessing - apply q_norm a...
Can this function be fused with rotary embedding kernel?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
k: torch.Tensor, v: torch.Tensor, residual: torch.Tensor, layer_id: int, attn_output: Optional[torch.Tensor], attn_metadata: LMCAttnMetadata, ): logger.debug(f"Blender is processing KV for layer {layer_id}") old_k, old_v = self.gpu_connector.get_kv(lay...
Is it a good idea to move the `rotary_emb` into `preprocess_attention_qk`
k: torch.Tensor, v: torch.Tensor, residual: torch.Tensor, layer_id: int, attn_output: Optional[torch.Tensor], attn_metadata: LMCAttnMetadata, ): logger.debug(f"Blender is processing KV for layer {layer_id}") old_k, old_v = self.gpu_connector.get_kv(lay...
@@ -83,6 +83,10 @@ def process_qkv( ) layer = self.layerwise_model.vllm_model.model.layers[layer_id] attn_layer = layer.self_attn + + # Use model-specific Q/K preprocessing method + q, k = self.layerwise_model.preprocess_attention_qk(q, k, attn_layer) + q, k = attn_...
lmcache/v1/compute/blend/blender.py
26
Python
0.429
suggestion
73
51
51
false
[Model] Add Qwen3 model support for CacheBlend
1,633
LMCache/LMCache
4,864
Python
YaoJiayi
junl666
Review this pull request change. Language: Python File: lmcache/v1/compute/blend/blender.py PR Title: [Model] Add Qwen3 model support for CacheBlend BEFORE CODE: k: torch.Tensor, v: torch.Tensor, residual: torch.Tensor, layer_id: int, attn_output: Optional[torch.Tensor], ...
Is it a good idea to move the `rotary_emb` into `preprocess_attention_qk`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# First Party from lmcache.config import LMCacheEngineMetadata from lmcache.utils import CacheEngineKey from lmcache.v1.config import LMCacheEngineConfig from lmcache.v1.lookup_server import LookupServerInterface from lmcache.v1.memory_management import ( MemoryAllocatorInterface, MemoryFormat, MemoryObj, )...
Let's not include this for the default `StorageBackendInterface` since those parameters are pretty tightly coupled to each backend's implementation. How about we create a base class for all the dynamic loading storage backend? Something like: ```python class ExternalStorageBackend(StorageBackendInterface): # I'm ...
# First Party from lmcache.config import LMCacheEngineMetadata from lmcache.utils import CacheEngineKey from lmcache.v1.config import LMCacheEngineConfig from lmcache.v1.memory_management import ( MemoryAllocatorInterface, MemoryFormat, MemoryObj, ) if TYPE_CHECKING: # First Party from lmcache.v1.s...
@@ -10,18 +11,28 @@ from lmcache.config import LMCacheEngineMetadata from lmcache.utils import CacheEngineKey from lmcache.v1.config import LMCacheEngineConfig +from lmcache.v1.lookup_server import LookupServerInterface from lmcache.v1.memory_management import ( MemoryAllocatorInterface, MemoryFormat, ...
lmcache/v1/storage_backend/abstract_backend.py
26
Python
0.857
performance
878
51
51
false
[Backend][BugFix]: Refactor StorageBackendInterface constructor to enable dynamic loading
1,636
LMCache/LMCache
4,864
Python
ApostaC
hickeyma
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/abstract_backend.py PR Title: [Backend][BugFix]: Refactor StorageBackendInterface constructor to enable dynamic loading BEFORE CODE: # First Party from lmcache.config import LMCacheEngineMetadata from lmcache.utils import CacheEngine...
Let's not include this for the default `StorageBackendInterface` since those parameters are pretty tightly coupled to each backend's implementation. How about we create a base class for all the dynamic loading storage backend? Something like: ```python class ExternalStorageBackend(StorageBackendInterface): # I'm ...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
module_path = config.extra_config.get( f"external_backend.{backend_name}.module_path" ) class_name = config.extra_config.get( f"external_backend.{backend_name}.class_name" ) if not module_path or not class_name: ...
@hickeyma As this PR modified this, and as the lmc_external_log_backend is a demonstrate project for `external backend framework`, would you like to modify the https://github.com/opendataio/lmc_external_log_backend/blob/main/lmc_external_log_backend/lmc_external_log_backend.py also?
f"external_backend.{backend_name}.module_path" ) class_name = config.extra_config.get( f"external_backend.{backend_name}.class_name" ) if not module_path or not class_name: logger.warning( f"Backend {bac...
@@ -79,12 +79,12 @@ def create_dynamic_backends( # Create the backend instance backend_instance = backend_class(
lmcache/v1/storage_backend/__init__.py
26
Python
0.571
question
283
51
51
false
[Backend][BugFix]: Refactor StorageBackendInterface constructor to enable dynamic loading
1,636
LMCache/LMCache
4,864
Python
maobaolong
hickeyma
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/__init__.py PR Title: [Backend][BugFix]: Refactor StorageBackendInterface constructor to enable dynamic loading BEFORE CODE: module_path = config.extra_config.get( f"external_backend.{backend_name}.module_...
@hickeyma As this PR modified this, and as the lmc_external_log_backend is a demonstrate project for `external backend framework`, would you like to modify the https://github.com/opendataio/lmc_external_log_backend/blob/main/lmc_external_log_backend/lmc_external_log_backend.py also?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def insert_put_task(self, key: CacheEngineKey): with self.put_lock: self.put_tasks.append(key) def exists_in_put_tasks(self, key: CacheEngineKey) -> bool: with self.put_lock: return key in self.put_tasks def close(self): # Gracefully shut down the executor ...
Why these changes are necessary? @hickeyma
def insert_put_task(self, key: CacheEngineKey): with self.put_lock: self.put_tasks.append(key) def exists_in_put_tasks(self, key: CacheEngineKey) -> bool: with self.put_lock: return key in self.put_tasks def close(self): # Gracefully shut down the executor ...
@@ -101,7 +101,7 @@ def __init__( dst_device: str = "cuda", lmcache_worker: Optional["LMCacheWorker"] = None, ): - super().__init__(dst_device)
lmcache/v1/storage_backend/local_disk_backend.py
26
Python
0.143
question
44
51
51
false
[Backend][BugFix]: Refactor StorageBackendInterface constructor to enable dynamic loading
1,636
LMCache/LMCache
4,864
Python
maobaolong
hickeyma
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/local_disk_backend.py PR Title: [Backend][BugFix]: Refactor StorageBackendInterface constructor to enable dynamic loading BEFORE CODE: def insert_put_task(self, key: CacheEngineKey): with self.put_lock: self.p...
Why these changes are necessary? @hickeyma
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
metadata: Optional[LMCacheEngineMetadata] = None, ) -> MemoryAllocatorInterface: cpu_size = config.max_local_cpu_size if metadata is not None: # save_only_first_rank only works when use mla save_only_first_rank = ( config.get_extra_config_value("save_...
we should not always override the cpu size right, only in the save_only_first_rank case maybe
def initialize_allocator( self, config: LMCacheEngineConfig, metadata: Optional[LMCacheEngineMetadata] = None, ) -> MemoryAllocatorInterface: cpu_size = config.max_local_cpu_size if metadata is not None: # save_only_first_rank only works when use mla ...
@@ -266,17 +319,18 @@ def initialize_allocator( if save_only_first_rank and metadata.is_first_rank(): # Only the first rank will save the cache, - # so we need to set it lager than other ranks - cpu_size = ( - config.extra_config.get("firs...
lmcache/v1/storage_backend/local_cpu_backend.py
26
Python
0.286
suggestion
93
51
51
false
Support adjust the effective memory by system available memory and reserve size
1,708
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/local_cpu_backend.py PR Title: Support adjust the effective memory by system available memory and reserve size BEFORE CODE: metadata: Optional[LMCacheEngineMetadata] = None, ) -> MemoryAllocatorInterface: cpu_size...
we should not always override the cpu size right, only in the save_only_first_rank case maybe
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
The effective CPU memory size in GB """ save_only_first_rank = ( metadata is not None and config.get_extra_config_value("save_only_first_rank", metadata.use_mla) and metadata.use_mla ) if not save_only_first_rank: # Do not adju...
`effective_cpu_size` may be 0, should an exception or assert be thrown in this situation?
The effective CPU memory size in GB """ save_only_first_rank = ( metadata is not None and config.get_extra_config_value("save_only_first_rank", metadata.use_mla) and metadata.use_mla ) if not save_only_first_rank: # Do not adju...
@@ -250,6 +250,61 @@ def remove(self, key: CacheEngineKey, force: bool = True) -> bool: # other backends might still (temporarily) hold the memory object. return True + def _calculate_effective_cpu_size( + self, + configured_cpu_size: float, + config: LMCacheEngineConfig, + ...
lmcache/v1/storage_backend/local_cpu_backend.py
26
Python
0.571
question
89
51
51
false
Support adjust the effective memory by system available memory and reserve size
1,708
LMCache/LMCache
4,864
Python
chunxiaozheng
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/local_cpu_backend.py PR Title: Support adjust the effective memory by system available memory and reserve size BEFORE CODE: The effective CPU memory size in GB """ save_only_first_rank = ( met...
`effective_cpu_size` may be 0, should an exception or assert be thrown in this situation?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
keys=keys, memory_objs=memory_objs, location=location, ) return num_tokens @_lmcache_nvtx_annotate def lookup_unpin(self, lookup_ids: list[str]) -> None: for lookup_id in lookup_ids: if lookup_id in self.lookup_pins: self....
hi @maobaolong, why delete the broadcast here?
keys=keys, memory_objs=memory_objs, location=location, ) return num_tokens @_lmcache_nvtx_annotate def lookup_unpin(self, lookup_ids: list[str]) -> None: for lookup_id in lookup_ids: if lookup_id in self.lookup_pins: self....
@@ -980,11 +980,9 @@ def clear( if self.save_only_first_rank: if self.metadata.is_first_rank(): num_removed = self._clear(tokens, locations, request_configs) - self.broadcast_object_fn(num_removed, self.metadata.first_rank)
lmcache/v1/cache_engine.py
26
Python
0.214
question
46
51
51
false
[core]Add cache/clear api to internal_api_server
1,711
LMCache/LMCache
4,864
Python
chunxiaozheng
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/cache_engine.py PR Title: [core]Add cache/clear api to internal_api_server BEFORE CODE: keys=keys, memory_objs=memory_objs, location=location, ) return num_tokens @_lmcache_nvtx_annotate ...
hi @maobaolong, why delete the broadcast here?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# TODO(Jiayi): we can use zmq poll to optimize a bit for i in range(ranks): resp = self.sockets[i].recv() result = int.from_bytes(resp, "big") results.append(result) except zmq.Again: logger.error(f"Timeout occurred for rank {i...
need to consult req_status before
results = [] try: for i in range(ranks): self.sockets[i].send_multipart(msg_buf, copy=False) # TODO(Jiayi): we can use zmq poll to optimize a bit for i in range(ranks): resp = self.sockets[i].recv() result = int.from_by...
@@ -163,7 +173,13 @@ def lookup( # NOTE: it is possible that the number of hit tokens is different # across TP ranks, so we can use the minimum value as the # number of hit tokens.
lmcache/v1/lookup_client/lmcache_lookup_client.py
26
Python
0.071
suggestion
33
51
51
false
[Core] Remove `lookup_id` and use `req_id` instead
1,729
LMCache/LMCache
4,864
Python
sammshen
YaoJiayi
Review this pull request change. Language: Python File: lmcache/v1/lookup_client/lmcache_lookup_client.py PR Title: [Core] Remove `lookup_id` and use `req_id` instead BEFORE CODE: # TODO(Jiayi): we can use zmq poll to optimize a bit for i in range(ranks): resp = self.sockets...
need to consult req_status before
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# TODO: extend this class to implement caching policies and eviction policies class StorageManager: """ The StorageManager is responsible for managing the storage backends. """ def __init__( self, config: LMCacheEngineConfig, metadata: LMCacheEngineMetadata, event_manage...
can we create a helper ```python is_cuda_worker(metadata): return metadata.role != "scheduler" and torch.cuda.is_available() ```
# TODO: extend this class to implement caching policies and eviction policies class StorageManager: """ The StorageManager is responsible for managing the storage backends. """ def __init__( self, config: LMCacheEngineConfig, metadata: LMCacheEngineMetadata, event_manage...
@@ -195,7 +195,10 @@ def __init__( ) self.thread.start() - if torch.cuda.is_available(): + # For scheduler role, always use CPU device + if metadata.role == "scheduler":
lmcache/v1/storage_backend/storage_manager.py
26
Python
0.714
refactor
139
51
51
false
Add a LMCacheBypassLookupClient to support lookup without communicate to any worker
1,733
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/storage_manager.py PR Title: Add a LMCacheBypassLookupClient to support lookup without communicate to any worker BEFORE CODE: # TODO: extend this class to implement caching policies and eviction policies class StorageManager: """...
can we create a helper ```python is_cuda_worker(metadata): return metadata.role != "scheduler" and torch.cuda.is_available() ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
args=(self.loop,), name="storage-manger-event-loop", ) self.thread.start() # For scheduler role, always use CPU device if is_cuda_worker(metadata): dst_device = "cuda" else: dst_device = "cpu" self.storage_backends: Ordered...
super nit (sorry): ```python self.allocator_backend = None if metadata.role != "scheduler": self.allocator_backend = self._get_allocator_backend(config) ```
args=(self.loop,), name="storage-manger-event-loop", ) self.thread.start() # For scheduler role, always use CPU device if is_cuda_worker(metadata): dst_device = "cuda" else: dst_device = "cpu" self.storage_backends: Ordered...
@@ -214,7 +215,11 @@ def __init__( self.enable_pd = config.enable_pd - self.allocator_backend = self._get_allocator_backend(config) + self.allocator_backend = (
lmcache/v1/storage_backend/storage_manager.py
26
Python
0.714
nitpick
171
51
51
false
Add a LMCacheBypassLookupClient to support lookup without communicate to any worker
1,733
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/storage_manager.py PR Title: Add a LMCacheBypassLookupClient to support lookup without communicate to any worker BEFORE CODE: args=(self.loop,), name="storage-manger-event-loop", ) self.thread....
super nit (sorry): ```python self.allocator_backend = None if metadata.role != "scheduler": self.allocator_backend = self._get_allocator_backend(config) ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
use_gpu=use_gpu, chunk_size=chunk_size, dtype=kv_dtype, device=device, ) tpg = get_tp_group() else: vllm_gpu_connector = VLLMPagedMemGPUConnectorV2( hidden_dim_size, num_layer, use_gpu=use...
super nit (sorry): ```python if role == "scheduler" and lmcache_config.enable_scheduler_bypass_lookup: assert ( engine.save_only_first_rank or lmcache_config.get_extra_config_value( "remote_enable_mla_worker_id_as0", metadata.use_mla ) ) ```
use_gpu=use_gpu, chunk_size=chunk_size, dtype=kv_dtype, device=device, ) tpg = get_tp_group() else: vllm_gpu_connector = VLLMPagedMemGPUConnectorV2( hidden_dim_size, num_layer, use_gpu=use...
@@ -553,7 +560,19 @@ def _init_lmcache_engine( tpg.broadcast, tpg.broadcast_object, ) - + assert (
lmcache/integration/vllm/vllm_v1_adapter.py
26
Python
0.857
performance
317
51
51
false
Add a LMCacheBypassLookupClient to support lookup without communicate to any worker
1,733
LMCache/LMCache
4,864
Python
sammshen
maobaolong
Review this pull request change. Language: Python File: lmcache/integration/vllm/vllm_v1_adapter.py PR Title: Add a LMCacheBypassLookupClient to support lookup without communicate to any worker BEFORE CODE: use_gpu=use_gpu, chunk_size=chunk_size, dtype=kv_dtype, ...
super nit (sorry): ```python if role == "scheduler" and lmcache_config.enable_scheduler_bypass_lookup: assert ( engine.save_only_first_rank or lmcache_config.get_extra_config_value( "remote_enable_mla_worker_id_as0", metadata.use_mla ) ) ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
# Deserialize metadata and allocate memory metadata = RemoteMetadata.deserialize(md_buffer) memory_obj = self.local_cpu_backend.allocate( metadata.shape, metadata.dtype, metadata.fmt ) else: ...
It will be graceful if you could care about the tail chunk case.
# Deserialize metadata and allocate memory metadata = RemoteMetadata.deserialize(md_buffer) memory_obj = self.local_cpu_backend.allocate( metadata.shape, metadata.dtype, metadata.fmt ) else: ...
@@ -142,13 +156,25 @@ async def get(self, key: CacheEngineKey) -> Optional[MemoryObj]: # Read the actual data into allocated memory buffer = memory_obj.byte_array - num_read = await f.readinto(buffer) if self.save_chunk_meta: + num_r...
lmcache/v1/storage_backend/connector/fs_connector.py
26
Python
0.286
suggestion
64
51
51
false
[FSConnector] support read ahead in FSConnector
1,771
LMCache/LMCache
4,864
Python
maobaolong
chunxiaozheng
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/connector/fs_connector.py PR Title: [FSConnector] support read ahead in FSConnector BEFORE CODE: # Deserialize metadata and allocate memory metadata = RemoteMetadata.deserialize(md_buffer) ...
It will be graceful if you could care about the tail chunk case.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
keys = [] for chunk_info in chunk_info_iterator: assert isinstance(chunk_info[2], CacheEngineKey) chunk_info_list.append(chunk_info) keys.append(chunk_info[2]) batched_contains_res = self.storage_manager.batched...
thanks for cleaning up the prev_end logic
continue return res else: chunk_info_list = [] keys = [] for chunk_info in chunk_info_iterator: assert isinstance(chunk_info[2], CacheEngineKey) chunk_info_list.append(chunk_in...
@@ -713,29 +711,44 @@ def lookup( found = True if found: if pin: + assert lookup_id is not None, ( + "lookup_id is required when pin is True" + ) ...
lmcache/v1/cache_engine.py
26
Python
0.071
suggestion
41
51
51
false
[core] add batched_contains interface
1,778
LMCache/LMCache
4,864
Python
sammshen
chunxiaozheng
Review this pull request change. Language: Python File: lmcache/v1/cache_engine.py PR Title: [core] add batched_contains interface BEFORE CODE: keys = [] for chunk_info in chunk_info_iterator: assert isinstance(chunk_info[2], CacheEngineKey) ch...
thanks for cleaning up the prev_end logic
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def layerwise_batched_get( self, keys: List[List[CacheEngineKey]], location: Optional[str] = None, ) -> Generator[Future, None, None]: """ Non-blocking function to get the memory objects into the storages in a layerwise manner. Do not store if the same obj...
Thanks for the fix @DongDongJu . instead of checking for if the serializer is None here, can we always intialize it (not only in the async codepath). Layerwise codepath also needs async serializer because multiple layers loading at once shoudl ensure that we don't deadlock the cpu as well
def layerwise_batched_get( self, keys: List[List[CacheEngineKey]], location: Optional[str] = None, ) -> Generator[Future, None, None]: """ Non-blocking function to get the memory objects into the storages in a layerwise manner. Do not store if the same obj...
@@ -436,20 +437,15 @@ def layerwise_batched_get( """ if location is None: location = "LocalCPUBackend" - for keys_multi_chunk in keys: # Retrieve all chunks for one layer backend = self.storage_backends[location] # TODO(Jiayi): need to make ...
lmcache/v1/storage_backend/storage_manager.py
26
Python
0.643
bug
289
51
51
false
Guarded the async serializer usage so we only wrap the backend load c…
1,795
LMCache/LMCache
4,864
Python
sammshen
DongDongJu
Review this pull request change. Language: Python File: lmcache/v1/storage_backend/storage_manager.py PR Title: Guarded the async serializer usage so we only wrap the backend load c… BEFORE CODE: def layerwise_batched_get( self, keys: List[List[CacheEngineKey]], location: Optional[str] =...
Thanks for the fix @DongDongJu . instead of checking for if the serializer is None here, can we always intialize it (not only in the async codepath). Layerwise codepath also needs async serializer because multiple layers loading at once shoudl ensure that we don't deadlock the cpu as well
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.