vllm_mlx.prefix_cache¶
Prefix Cache Manager for vllm-mlx.
View the complete module source at #L1-L1039.
API details¶
Each callable below includes its exact signature, type annotations, inputs, defaults, return contract, documented exceptions, implementation source, and parsed docstring sections when the source provides them.
vllm_mlx.prefix_cache
¶
Prefix Cache Manager for vllm-mlx.
Wraps mlx-lm's LRUPromptCache to provide prefix caching functionality, allowing reuse of computed KV cache for common prompt prefixes.
This module provides two implementations: - PrefixCacheManager: Original trie-based LRU cache (for backward compatibility) - BlockAwarePrefixCache: Block-based cache with PagedCacheManager integration
vllm_mlx.prefix_cache.CacheEntry
dataclass
¶
vllm_mlx.prefix_cache.PrefixCacheStats
dataclass
¶
PrefixCacheStats(hits: int = 0, misses: int = 0, tokens_saved: int = 0, total_queries: int = 0, evictions: int = 0)
Statistics for prefix cache performance.
vllm_mlx.prefix_cache.PrefixCacheStats.tokens_saved
class-attribute
instance-attribute
¶
vllm_mlx.prefix_cache.PrefixCacheStats.total_queries
class-attribute
instance-attribute
¶
vllm_mlx.prefix_cache.PrefixCacheStats.evictions
class-attribute
instance-attribute
¶
vllm_mlx.prefix_cache.PrefixCacheStats.hit_rate
property
¶
Calculate cache hit rate.
vllm_mlx.prefix_cache.PrefixCacheStats.to_dict
¶
Convert stats to dictionary.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.PrefixCacheManager
¶
Manages prefix caching for vllm-mlx using a trie-based LRU cache.
This implementation is inspired by mlx-lm's LRUPromptCache but adapted for vllm-mlx's batching architecture.
The cache stores KV states keyed by token sequences, allowing: - Exact match: Full prompt found in cache - Shorter match: Partial prefix found, process remaining tokens - Longer match: Cached prefix longer than request, trim excess
Example
cache_manager = PrefixCacheManager(model, max_entries=100)
Check for cached prefix¶
cache, remaining_tokens = cache_manager.fetch_cache(tokens) if cache: # Use cached KV, only process remaining_tokens pass
After generation, store cache for reuse¶
cache_manager.store_cache(full_tokens, prompt_cache)
Initialize the prefix cache manager.
Parameters:
-
model(Any) –The MLX model (used for cache key identification)
-
max_entries(int, default:100) –Maximum number of cached entries before LRU eviction
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.PrefixCacheManager._lru
instance-attribute
¶
vllm_mlx.prefix_cache.PrefixCacheManager._search
¶
_search(tokens: List[int]) -> Tuple[Optional[List[int]], Optional[List[int]], Optional[List[int]], int]
Search for cached prefix matching tokens.
Returns:
-
Optional[List[int]]–Tuple of (exact, shorter, longer, common_prefix_len)
-
Optional[List[int]]–- exact: Tokens if exact match found
-
Optional[List[int]]–- shorter: Tokens of shorter cached prefix
-
int–- longer: Tokens of longer cached prefix
-
Tuple[Optional[List[int]], Optional[List[int]], Optional[List[int]], int]–- common_prefix_len: Length of common prefix with longer match
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.PrefixCacheManager.fetch_cache
¶
Find cached prefix for the given tokens.
Parameters:
-
tokens(List[int]) –Input token sequence
Returns:
-
Optional[List[Any]]–Tuple of (cache, remaining_tokens)
-
List[int]–- cache: Cached KV state if found, None otherwise
-
Tuple[Optional[List[Any]], List[int]]–- remaining_tokens: Tokens that still need processing
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.PrefixCacheManager.store_cache
¶
Store computed cache for future reuse.
Parameters:
-
tokens(List[int]) –Token sequence that was processed
-
prompt_cache(List[Any]) –The computed KV cache to store
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.PrefixCacheManager._get_cache_entry
¶
_get_cache_entry(tokens: List[int]) -> Optional[CacheEntry]
Get cache entry for given tokens.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.PrefixCacheManager._touch_lru
¶
Move entry to most-recently-used position — O(1) with OrderedDict.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.PrefixCacheManager._evict_lru
¶
Evict least recently used entry — O(1) popitem from OrderedDict.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.PrefixCacheManager._delete_cache
¶
Delete cache entry and clean up empty trie branches.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.PrefixCacheManager._can_trim_cache
¶
Check if cache can be trimmed.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.PrefixCacheManager._trim_cache
¶
Trim cache by removing num_tokens from the end.
vllm_mlx.prefix_cache.PrefixCacheManager.get_stats
¶
vllm_mlx.prefix_cache.PrefixCacheManager.reset_stats
¶
vllm_mlx.prefix_cache.PrefixCacheManager.clear
¶
vllm_mlx.prefix_cache.BlockCacheEntry
dataclass
¶
BlockCacheEntry(block_table: BlockTable, cache_data: List[Any], last_access: float)
Entry mapping a token sequence to cache blocks.
vllm_mlx.prefix_cache.BlockAwarePrefixCache
¶
BlockAwarePrefixCache(model: Any, paged_cache_manager: PagedCacheManager)
Prefix cache that uses PagedCacheManager for block-based storage.
Features: - Block-level prefix sharing (64 tokens per block) - Copy-on-Write for efficient forking - Hash-based deduplication across requests - Reference counting for memory efficiency
This is the recommended cache for production use when memory efficiency for concurrent requests is important.
Example
paged_manager = PagedCacheManager(block_size=64, max_blocks=1000) cache = BlockAwarePrefixCache(model, paged_manager)
Check for cached prefix¶
block_table, remaining_tokens = cache.fetch_cache(request_id, tokens)
After generation, store cache¶
cache.store_cache(request_id, tokens, kv_cache_data)
Clean up when request completes¶
cache.release_cache(request_id)
Initialize block-aware prefix cache.
Parameters:
-
model(Any) –The MLX model (used for identification)
-
paged_cache_manager(PagedCacheManager) –The PagedCacheManager instance for block management
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache.paged_cache
instance-attribute
¶
vllm_mlx.prefix_cache.BlockAwarePrefixCache.block_size
instance-attribute
¶
vllm_mlx.prefix_cache.BlockAwarePrefixCache._prefix_index
instance-attribute
¶
vllm_mlx.prefix_cache.BlockAwarePrefixCache._request_tables
instance-attribute
¶
_request_tables: Dict[str, BlockCacheEntry] = {}
vllm_mlx.prefix_cache.BlockAwarePrefixCache.fetch_cache
¶
fetch_cache(request_id: str, tokens: List[int]) -> Tuple[Optional[BlockTable], List[int]]
Find cached prefix blocks for the given tokens.
Parameters:
-
request_id(str) –Unique request identifier
-
tokens(List[int]) –Input token sequence
Returns:
-
Optional[BlockTable]–Tuple of (block_table, remaining_tokens)
-
List[int]–- block_table: BlockTable if prefix found, None otherwise
-
Tuple[Optional[BlockTable], List[int]]–- remaining_tokens: Tokens that need processing
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache.store_cache
¶
store_cache(request_id: str, tokens: List[int], cache_data: List[Any]) -> Optional[BlockTable]
Store computed cache for future reuse.
This method stores actual tensor data (not references) when cache_data contains extracted states from mlx-lm's KVCache.state property.
Parameters:
-
request_id(str) –Unique request identifier
-
tokens(List[int]) –Token sequence that was processed
-
cache_data(List[Any]) –The computed KV cache to store. Can be: - List of KVCache objects (legacy, stores references) - List of dicts with 'state': (keys, values) tensors (new, stores slices)
Returns:
-
Optional[BlockTable]–BlockTable for the stored cache, or None on failure
Source code in vllm_mlx/prefix_cache.py
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 | |
vllm_mlx.prefix_cache.BlockAwarePrefixCache._extract_block_tensor_slice
¶
_extract_block_tensor_slice(cache_data: List[Dict[str, Any]], start_idx: int, end_idx: int, total_tokens: int) -> Optional[List[Optional[Dict[str, Any]]]]
Extract per-layer cache data for a single block.
Parameters:
-
cache_data(List[Dict[str, Any]]) –List of extracted layer states
-
start_idx(int) –Start token index in the sequence
-
end_idx(int) –End token index in the sequence
-
total_tokens(int) –Total number of tokens covered by cache_data
Returns:
-
Optional[List[Optional[Dict[str, Any]]]]–Per-layer block cache state, or None on failure
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache._cache_state_seq_axis
¶
Return the sequence axis for cache states that support block concat.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache._slice_concat_cache_state
¶
_slice_concat_cache_state(state: Tuple[Any, ...] | List[Any], start_idx: int, end_idx: int) -> Tuple[Any, ...] | List[Any]
Slice a sequence-backed cache state across the token axis.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache._concat_cache_states
¶
_concat_cache_states(states: List[Tuple[Any, ...] | List[Any]], seq_axis: int) -> Optional[Tuple[Any, ...] | List[Any]]
Concatenate state fragments for a sequence-backed cache layer.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache.get_cache_for_generation
¶
Get cache data for generation, applying COW if needed.
Parameters:
-
request_id(str) –Request identifier
Returns:
-
Tuple[Optional[List[Any]], bool]–Tuple of (cache_data, was_copied)
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache.release_cache
¶
Release cache blocks for a completed request.
Parameters:
-
request_id(str) –Request identifier
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache.fork_cache
¶
fork_cache(source_request_id: str, new_request_id: str) -> Optional[BlockTable]
Fork cache from one request to another (COW).
Parameters:
-
source_request_id(str) –Source request ID
-
new_request_id(str) –New request ID
Returns:
-
Optional[BlockTable]–Forked BlockTable, or None if source not found
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache.reconstruct_cache
¶
reconstruct_cache(block_table: BlockTable) -> Optional[List[Any]]
Reconstruct cache objects from stored block tensor data.
Sequence-backed caches are concatenated block-by-block. Recurrent caches such as ArraysCache are restored from the latest sequence boundary snapshot that was actually stored.
Parameters:
-
block_table(BlockTable) –BlockTable containing block IDs to reconstruct from
Returns:
-
Optional[List[Any]]–List of reconstructed KVCache objects (one per layer),
-
Optional[List[Any]]–or None if reconstruction fails
Source code in vllm_mlx/prefix_cache.py
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 | |
vllm_mlx.prefix_cache.BlockAwarePrefixCache._find_best_prefix_match
¶
Find best matching prefix in the index.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache._update_prefix_index
¶
Update prefix index with new token sequence.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache.get_stats
¶
Get cache statistics.
Source code in vllm_mlx/prefix_cache.py
vllm_mlx.prefix_cache.BlockAwarePrefixCache.reset_stats
¶
vllm_mlx.prefix_cache.BlockAwarePrefixCache.clear
¶
Complete contract reference¶
Expand any definition for its exact inputs, annotations, defaults, return contract, directly raised exceptions, source-grounded behavior, and immutable line link. This section includes private and nested definitions that ordinary API generators omit.
vllm_mlx.prefix_cache.CacheEntry · class
Entry in the prefix cache.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
prompt_cache |
List[Any] |
yes |
none |
Required constructor field. |
count |
int |
yes |
none |
Required constructor field. |
Returns
- Constructs:
vllm_mlx.prefix_cache.CacheEntry
Exceptions and behavior
Class CacheEntry declares 0 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheStats · class
vllm_mlx.prefix_cache.PrefixCacheStats(hits: int = 0, misses: int = 0, tokens_saved: int = 0, total_queries: int = 0, evictions: int = 0)
Statistics for prefix cache performance.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
hits |
int |
no |
0 |
Optional constructor field; defaults to 0. |
misses |
int |
no |
0 |
Optional constructor field; defaults to 0. |
tokens_saved |
int |
no |
0 |
Optional constructor field; defaults to 0. |
total_queries |
int |
no |
0 |
Optional constructor field; defaults to 0. |
evictions |
int |
no |
0 |
Optional constructor field; defaults to 0. |
Returns
- Constructs:
vllm_mlx.prefix_cache.PrefixCacheStats
Exceptions and behavior
Class PrefixCacheStats declares 2 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheStats.hit_rate · method
Calculate cache hit rate.
Parameters
This callable has no explicit inputs.
Returns
- Type:
float - Direct return expressions:
0.0;self.hits / self.total_queries
Exceptions and behavior
Method PrefixCacheStats.hit_rate has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheStats.to_dict · method
Convert stats to dictionary.
Parameters
This callable has no explicit inputs.
Returns
- Type:
Dict[str, Any] - Direct return expressions:
{'hits': self.hits, 'misses': self.misses, 'hit_rate': self.hit_rate, 'tokens_saved': self.tokens_saved, 'total_queries…
Exceptions and behavior
Method PrefixCacheStats.to_dict returns {'hits': self.hits, 'misses': self.misses, 'hit_rate': self.hit_rate, 'tokens_saved': self.tokens_saved, 'total_queries….
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager · class
Manages prefix caching for vllm-mlx using a trie-based LRU cache.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model |
Any |
yes |
none |
The MLX model (used for cache key identification) |
max_entries |
int |
no |
100 |
Maximum number of cached entries before LRU eviction |
Returns
- Constructs:
vllm_mlx.prefix_cache.PrefixCacheManager
Exceptions and behavior
Class PrefixCacheManager declares 14 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager.__init__ · method
vllm_mlx.prefix_cache.PrefixCacheManager.__init__(model: Any, max_entries: int = 100) -> not annotated
Initialize the prefix cache manager.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model |
Any |
yes |
none |
The MLX model (used for cache key identification) |
max_entries |
int |
no |
100 |
Maximum number of cached entries before LRU eviction |
Returns
- Type:
not annotated
Exceptions and behavior
Method PrefixCacheManager.__init__ updates self.model, self.model_key, self.max_size, self._cache; calls id, OrderedDict, PrefixCacheStats.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager._search · method
vllm_mlx.prefix_cache.PrefixCacheManager._search(tokens: List[int]) -> Tuple[Optional[List[int]], Optional[List[int]], Optional[List[int]], int]
Search for cached prefix matching tokens.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
List[int] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
Tuple[Optional[List[int]], Optional[List[int]], Optional[List[int]], int] - Direct return expressions:
(None, None, None, 0);(None, list(path), None, 0);(list(tokens), None, None, 0);(None, None, node_path, len(tokens))
Exceptions and behavior
Method PrefixCacheManager._search calls enumerate, list, path.append, stack.pop; has 4 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager.fetch_cache · method
vllm_mlx.prefix_cache.PrefixCacheManager.fetch_cache(tokens: List[int]) -> Tuple[Optional[List[Any]], List[int]]
Find cached prefix for the given tokens.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
List[int] |
yes |
none |
Input token sequence |
Returns
- Type:
Tuple[Optional[List[Any]], List[int]] - Direct return expressions:
(cache_entry.prompt_cache, []);(cache_entry.prompt_cache, remaining);(trimmed_cache, []);(None, tokens)
Exceptions and behavior
Method PrefixCacheManager.fetch_cache updates self.stats.total_queries, self.stats.hits, self.stats.tokens_saved, self.stats.misses; calls tuple, self._search, self._get_cache_entry, len; has 4 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager.store_cache · method
vllm_mlx.prefix_cache.PrefixCacheManager.store_cache(tokens: List[int], prompt_cache: List[Any]) -> None
Store computed cache for future reuse.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
List[int] |
yes |
none |
Token sequence that was processed |
prompt_cache |
List[Any] |
yes |
none |
The computed KV cache to store |
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Method PrefixCacheManager.store_cache calls tuple, self._lru.move_to_end, CacheEntry, len; returns None.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager._get_cache_entry · method
vllm_mlx.prefix_cache.PrefixCacheManager._get_cache_entry(tokens: List[int]) -> Optional[CacheEntry]
Get cache entry for given tokens.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
List[int] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
Optional[CacheEntry] - Direct return expressions:
None;current.get('cache')
Exceptions and behavior
Method PrefixCacheManager._get_cache_entry calls current.get; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager._touch_lru · method
Move entry to most-recently-used position — O(1) with OrderedDict.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens_tuple |
tuple |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None
Exceptions and behavior
Method PrefixCacheManager._touch_lru calls self._lru.move_to_end.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager._evict_lru · method
Evict least recently used entry — O(1) popitem from OrderedDict.
Parameters
This callable has no explicit inputs.
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Method PrefixCacheManager._evict_lru updates self.stats.evictions; calls self._lru.popitem, self._delete_cache, list; returns None.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager._delete_cache · method
Delete cache entry and clean up empty trie branches.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model_key |
Any |
yes |
none |
Required positional or keyword input. |
tokens |
List[int] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Method PrefixCacheManager._delete_cache calls path.append, range, len; returns None.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager._can_trim_cache · method
Check if cache can be trimmed.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
prompt_cache |
List[Any] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
bool - Direct return expressions:
False;trimmable;hasattr(first_cache, 'trim')
Exceptions and behavior
Method PrefixCacheManager._can_trim_cache calls hasattr, first_cache.is_trimmable, logger.debug; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager._trim_cache · method
vllm_mlx.prefix_cache.PrefixCacheManager._trim_cache(prompt_cache: List[Any], num_tokens: int) -> List[Any]
Trim cache by removing num_tokens from the end.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
prompt_cache |
List[Any] |
yes |
none |
Required positional or keyword input. |
num_tokens |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
List[Any] - Direct return expressions:
prompt_cache
Exceptions and behavior
Method PrefixCacheManager._trim_cache calls hasattr, cache.trim; returns prompt_cache.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager.get_stats · method
Get cache statistics.
Parameters
This callable has no explicit inputs.
Returns
- Type:
Dict[str, Any] - Direct return expressions:
self.stats.to_dict()
Exceptions and behavior
Method PrefixCacheManager.get_stats calls self.stats.to_dict; returns self.stats.to_dict().
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager.reset_stats · method
Reset statistics.
Parameters
This callable has no explicit inputs.
Returns
- Type:
None
Exceptions and behavior
Method PrefixCacheManager.reset_stats updates self.stats; calls PrefixCacheStats.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager.clear · method
Clear all cached entries.
Parameters
This callable has no explicit inputs.
Returns
- Type:
None
Exceptions and behavior
Method PrefixCacheManager.clear calls self._cache.clear, self._lru.clear, self.reset_stats.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.PrefixCacheManager.__len__ · method
Return number of cached entries.
Parameters
This callable has no explicit inputs.
Returns
- Type:
int - Direct return expressions:
len(self._lru)
Exceptions and behavior
Method PrefixCacheManager.__len__ calls len; returns len(self._lru).
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockCacheEntry · class
vllm_mlx.prefix_cache.BlockCacheEntry(block_table: BlockTable, cache_data: List[Any], last_access: float)
Entry mapping a token sequence to cache blocks.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
block_table |
BlockTable |
yes |
none |
Required constructor field. |
cache_data |
List[Any] |
yes |
none |
Required constructor field. |
last_access |
float |
yes |
none |
Required constructor field. |
Returns
- Constructs:
vllm_mlx.prefix_cache.BlockCacheEntry
Exceptions and behavior
Class BlockCacheEntry declares 0 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache · class
Prefix cache that uses PagedCacheManager for block-based storage.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model |
Any |
yes |
none |
The MLX model (used for identification) |
paged_cache_manager |
PagedCacheManager |
yes |
none |
The PagedCacheManager instance for block management |
Returns
- Constructs:
vllm_mlx.prefix_cache.BlockAwarePrefixCache
Exceptions and behavior
Class BlockAwarePrefixCache declares 17 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache.__init__ · method
vllm_mlx.prefix_cache.BlockAwarePrefixCache.__init__(model: Any, paged_cache_manager: PagedCacheManager) -> not annotated
Initialize block-aware prefix cache.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model |
Any |
yes |
none |
The MLX model (used for identification) |
paged_cache_manager |
PagedCacheManager |
yes |
none |
The PagedCacheManager instance for block management |
Returns
- Type:
not annotated
Exceptions and behavior
Method BlockAwarePrefixCache.__init__ updates self.model, self.model_key, self.paged_cache, self.block_size; calls id.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache.fetch_cache · method
vllm_mlx.prefix_cache.BlockAwarePrefixCache.fetch_cache(request_id: str, tokens: List[int]) -> Tuple[Optional[BlockTable], List[int]]
Find cached prefix blocks for the given tokens.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_id |
str |
yes |
none |
Unique request identifier |
tokens |
List[int] |
yes |
none |
Input token sequence |
Returns
- Type:
Tuple[Optional[BlockTable], List[int]] - Direct return expressions:
(None, tokens);(block_table, remaining)
Exceptions and behavior
Method BlockAwarePrefixCache.fetch_cache updates self._hits, self._tokens_saved, self._misses; calls self.paged_cache.find_shared_prefix, self.paged_cache.create_block_table, self.paged_cache.increment_ref, self.paged_cache.allocated_blocks.get; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache.store_cache · method
vllm_mlx.prefix_cache.BlockAwarePrefixCache.store_cache(request_id: str, tokens: List[int], cache_data: List[Any]) -> Optional[BlockTable]
Store computed cache for future reuse.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_id |
str |
yes |
none |
Unique request identifier |
tokens |
List[int] |
yes |
none |
Token sequence that was processed |
cache_data |
List[Any] |
yes |
none |
The computed KV cache to store. Can be: - List of KVCache objects (legacy, stores references) - List of dicts with 'state': (keys, values) tensors (new, stores slices) |
Returns
- Type:
Optional[BlockTable] - Direct return expressions:
None;block_table
Exceptions and behavior
Method BlockAwarePrefixCache.store_cache calls isinstance, len, self.paged_cache.get_block_table, self.paged_cache.create_block_table; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache._extract_block_tensor_slice · method
vllm_mlx.prefix_cache.BlockAwarePrefixCache._extract_block_tensor_slice(cache_data: List[Dict[str, Any]], start_idx: int, end_idx: int, total_tokens: int) -> Optional[List[Optional[Dict[str, Any]]]]
Extract per-layer cache data for a single block.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
cache_data |
List[Dict[str, Any]] |
yes |
none |
List of extracted layer states |
start_idx |
int |
yes |
none |
Start token index in the sequence |
end_idx |
int |
yes |
none |
End token index in the sequence |
total_tokens |
int |
yes |
none |
Total number of tokens covered by cache_data |
Returns
- Type:
Optional[List[Optional[Dict[str, Any]]]] - Direct return expressions:
None;block_slices if any((entry is not None for entry in block_slices)) else None
Exceptions and behavior
Method BlockAwarePrefixCache._extract_block_tensor_slice calls block_slices.append, layer_state.get, self._cache_state_seq_axis, self._slice_concat_cache_state; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache._cache_state_seq_axis · method
Return the sequence axis for cache states that support block concat.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
state |
Any |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
Optional[int] - Direct return expressions:
None;2;1
Exceptions and behavior
Method BlockAwarePrefixCache._cache_state_seq_axis calls isinstance, len, hasattr, next; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache._slice_concat_cache_state · method
vllm_mlx.prefix_cache.BlockAwarePrefixCache._slice_concat_cache_state(state: Tuple[Any, ...] | List[Any], start_idx: int, end_idx: int) -> Tuple[Any, ...] | List[Any]
Slice a sequence-backed cache state across the token axis.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
state |
Tuple[Any, ...] \| List[Any] |
yes |
none |
Required positional or keyword input. |
start_idx |
int |
yes |
none |
Required positional or keyword input. |
end_idx |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
Tuple[Any, ...] | List[Any] - Direct return expressions:
tuple(sliced) if isinstance(state, tuple) else sliced
Exceptions and behavior
Method BlockAwarePrefixCache._slice_concat_cache_state calls self._cache_state_seq_axis, ValueError, min, _slice_tensor; can raise ValueError; returns tuple(sliced) if isinstance(state, tuple) else sliced.
Directly raised exceptions: ValueError.
vllm_mlx.prefix_cache.BlockAwarePrefixCache._slice_concat_cache_state._slice_tensor · nested function
vllm_mlx.prefix_cache.BlockAwarePrefixCache._slice_concat_cache_state._slice_tensor(tensor: Any) -> Any
Nested Function BlockAwarePrefixCache._slice_concat_cache_state._slice_tensor calls slice, len, tuple; returns tensor[tuple(slices)].
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tensor |
Any |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
Any - Direct return expressions:
tensor[tuple(slices)]
Exceptions and behavior
Nested Function BlockAwarePrefixCache._slice_concat_cache_state._slice_tensor calls slice, len, tuple; returns tensor[tuple(slices)].
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache._concat_cache_states · method
vllm_mlx.prefix_cache.BlockAwarePrefixCache._concat_cache_states(states: List[Tuple[Any, ...] | List[Any]], seq_axis: int) -> Optional[Tuple[Any, ...] | List[Any]]
Concatenate state fragments for a sequence-backed cache layer.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
states |
List[Tuple[Any, ...] \| List[Any]] |
yes |
none |
Required positional or keyword input. |
seq_axis |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
Optional[Tuple[Any, ...] | List[Any]] - Direct return expressions:
None;tuple(concatenated) if isinstance(states[0], tuple) else concatenated
Exceptions and behavior
Method BlockAwarePrefixCache._concat_cache_states calls len, range, any, concatenated.append; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache.get_cache_for_generation · method
vllm_mlx.prefix_cache.BlockAwarePrefixCache.get_cache_for_generation(request_id: str) -> Tuple[Optional[List[Any]], bool]
Get cache data for generation, applying COW if needed.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_id |
str |
yes |
none |
Request identifier |
Returns
- Type:
Tuple[Optional[List[Any]], bool] - Direct return expressions:
(None, False);(cache_data, was_copied)
Exceptions and behavior
Method BlockAwarePrefixCache.get_cache_for_generation calls self._request_tables.get, self.paged_cache.get_blocks_for_generation, copy.deepcopy, time.time; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache.release_cache · method
Release cache blocks for a completed request.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
request_id |
str |
yes |
none |
Request identifier |
Returns
- Type:
None
Exceptions and behavior
Method BlockAwarePrefixCache.release_cache calls self._request_tables.pop, self.paged_cache.delete_block_table, logger.debug.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache.fork_cache · method
vllm_mlx.prefix_cache.BlockAwarePrefixCache.fork_cache(source_request_id: str, new_request_id: str) -> Optional[BlockTable]
Fork cache from one request to another (COW).
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
source_request_id |
str |
yes |
none |
Source request ID |
new_request_id |
str |
yes |
none |
New request ID |
Returns
- Type:
Optional[BlockTable] - Direct return expressions:
None;forked_table
Exceptions and behavior
Method BlockAwarePrefixCache.fork_cache calls self._request_tables.get, self.paged_cache.fork_block_table, BlockCacheEntry, time.time; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache.reconstruct_cache · method
vllm_mlx.prefix_cache.BlockAwarePrefixCache.reconstruct_cache(block_table: BlockTable) -> Optional[List[Any]]
Reconstruct cache objects from stored block tensor data.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
block_table |
BlockTable |
yes |
none |
BlockTable containing block IDs to reconstruct from |
Returns
- Type:
Optional[List[Any]] - Direct return expressions:
None;reconstructed_caches
Exceptions and behavior
Method BlockAwarePrefixCache.reconstruct_cache calls logger.warning, self.paged_cache.allocated_blocks.get, logger.debug, all_block_data.append; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache._find_best_prefix_match · method
vllm_mlx.prefix_cache.BlockAwarePrefixCache._find_best_prefix_match(tokens: List[int]) -> Optional[Tuple[List[int], List[int]]]
Find best matching prefix in the index.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
List[int] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
Optional[Tuple[List[int], List[int]]] - Direct return expressions:
best_match
Exceptions and behavior
Method BlockAwarePrefixCache._find_best_prefix_match calls range, len, self.paged_cache.compute_block_hash; returns best_match.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache._update_prefix_index · method
vllm_mlx.prefix_cache.BlockAwarePrefixCache._update_prefix_index(tokens: List[int], block_ids: List[int]) -> None
Update prefix index with new token sequence.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
List[int] |
yes |
none |
Required positional or keyword input. |
block_ids |
List[int] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None
Exceptions and behavior
Method BlockAwarePrefixCache._update_prefix_index calls range, len, min, self.paged_cache.compute_block_hash.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache.get_stats · method
Get cache statistics.
Parameters
This callable has no explicit inputs.
Returns
- Type:
Dict[str, Any] - Direct return expressions:
{'hits': self._hits, 'misses': self._misses, 'hit_rate': self._hits / (self._hits + self._misses) if self._hits + self.…
Exceptions and behavior
Method BlockAwarePrefixCache.get_stats calls self.paged_cache.get_memory_usage, len; returns {'hits': self._hits, 'misses': self._misses, 'hit_rate': self._hits / (self._hits + self._misses) if self._hits + self.….
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache.reset_stats · method
Reset statistics.
Parameters
This callable has no explicit inputs.
Returns
- Type:
None
Exceptions and behavior
Method BlockAwarePrefixCache.reset_stats updates self._hits, self._misses, self._tokens_saved; calls self.paged_cache.reset_stats.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache.clear · method
Clear all cached data.
Parameters
This callable has no explicit inputs.
Returns
- Type:
None
Exceptions and behavior
Method BlockAwarePrefixCache.clear calls self._request_tables.clear, self._prefix_index.clear, self.paged_cache.clear, self.reset_stats.
No direct raise statement appears in this definition.
vllm_mlx.prefix_cache.BlockAwarePrefixCache.__len__ · method
Return number of active request entries.
Parameters
This callable has no explicit inputs.
Returns
- Type:
int - Direct return expressions:
len(self._request_tables)
Exceptions and behavior
Method BlockAwarePrefixCache.__len__ calls len; returns len(self._request_tables).
No direct raise statement appears in this definition.
Complete symbol map¶
This map also includes private definitions and nested helpers. The signature column exposes every explicit input even when an internal helper has no dedicated parameter prose.
| Symbol | Kind | Signature and inputs | What it does | Source |
|---|---|---|---|---|
CacheEntry |
class | CacheEntry(prompt_cache: List[Any], count: int) |
Entry in the prefix cache. | #L33-L37 |
PrefixCacheStats |
class | PrefixCacheStats(hits: int = 0, misses: int = 0, tokens_saved: int = 0, total_queries: int = 0, evictions: int = 0) |
Statistics for prefix cache performance. | #L41-L66 |
PrefixCacheStats.hit_rate |
method | PrefixCacheStats.hit_rate() -> float |
Calculate cache hit rate. | #L51-L55 |
PrefixCacheStats.to_dict |
method | PrefixCacheStats.to_dict() -> Dict[str, Any] |
Convert stats to dictionary. | #L57-L66 |
PrefixCacheManager |
class | PrefixCacheManager(model: Any, max_entries: int = 100) |
Manages prefix caching for vllm-mlx using a trie-based LRU cache. | #L69-L355 |
PrefixCacheManager.__init__ |
method | PrefixCacheManager.__init__(model: Any, max_entries: int = 100) -> not annotated |
Initialize the prefix cache manager. | #L94-L115 |
PrefixCacheManager._search |
method | PrefixCacheManager._search(tokens: List[int]) -> Tuple[Optional[List[int]], Optional[List[int]], Optional[List[int]], int] |
Search for cached prefix matching tokens. | #L117-L164 |
PrefixCacheManager.fetch_cache |
method | PrefixCacheManager.fetch_cache(tokens: List[int]) -> Tuple[Optional[List[Any]], List[int]] |
Find cached prefix for the given tokens. | #L166-L221 |
PrefixCacheManager.store_cache |
method | PrefixCacheManager.store_cache(tokens: List[int], prompt_cache: List[Any]) -> None |
Store computed cache for future reuse. | #L223-L258 |
PrefixCacheManager._get_cache_entry |
method | PrefixCacheManager._get_cache_entry(tokens: List[int]) -> Optional[CacheEntry] |
Get cache entry for given tokens. | #L260-L271 |
PrefixCacheManager._touch_lru |
method | PrefixCacheManager._touch_lru(tokens_tuple: tuple) -> None |
Move entry to most-recently-used position — O(1) with OrderedDict. | #L273-L279 |
PrefixCacheManager._evict_lru |
method | PrefixCacheManager._evict_lru() -> None |
Evict least recently used entry — O(1) popitem from OrderedDict. | #L281-L288 |
PrefixCacheManager._delete_cache |
method | PrefixCacheManager._delete_cache(model_key: Any, tokens: List[int]) -> None |
Delete cache entry and clean up empty trie branches. | #L290-L314 |
PrefixCacheManager._can_trim_cache |
method | PrefixCacheManager._can_trim_cache(prompt_cache: List[Any]) -> bool |
Check if cache can be trimmed. | #L316-L330 |
PrefixCacheManager._trim_cache |
method | PrefixCacheManager._trim_cache(prompt_cache: List[Any], num_tokens: int) -> List[Any] |
Trim cache by removing num_tokens from the end. | #L332-L337 |
PrefixCacheManager.get_stats |
method | PrefixCacheManager.get_stats() -> Dict[str, Any] |
Get cache statistics. | #L339-L341 |
PrefixCacheManager.reset_stats |
method | PrefixCacheManager.reset_stats() -> None |
Reset statistics. | #L343-L345 |
PrefixCacheManager.clear |
method | PrefixCacheManager.clear() -> None |
Clear all cached entries. | #L347-L351 |
PrefixCacheManager.__len__ |
method | PrefixCacheManager.__len__() -> int |
Return number of cached entries. | #L353-L355 |
BlockCacheEntry |
class | BlockCacheEntry(block_table: BlockTable, cache_data: List[Any], last_access: float) |
Entry mapping a token sequence to cache blocks. | #L364-L369 |
BlockAwarePrefixCache |
class | BlockAwarePrefixCache(model: Any, paged_cache_manager: PagedCacheManager) |
Prefix cache that uses PagedCacheManager for block-based storage. | #L372-L1039 |
BlockAwarePrefixCache.__init__ |
method | BlockAwarePrefixCache.__init__(model: Any, paged_cache_manager: PagedCacheManager) -> not annotated |
Initialize block-aware prefix cache. | #L399-L426 |
BlockAwarePrefixCache.fetch_cache |
method | BlockAwarePrefixCache.fetch_cache(request_id: str, tokens: List[int]) -> Tuple[Optional[BlockTable], List[int]] |
Find cached prefix blocks for the given tokens. | #L428-L502 |
BlockAwarePrefixCache.store_cache |
method | BlockAwarePrefixCache.store_cache(request_id: str, tokens: List[int], cache_data: List[Any]) -> Optional[BlockTable] |
Store computed cache for future reuse. | #L504-L628 |
BlockAwarePrefixCache._extract_block_tensor_slice |
method | BlockAwarePrefixCache._extract_block_tensor_slice(cache_data: List[Dict[str, Any]], start_idx: int, end_idx: int, total_tokens: int) -> Optional[List[Optional[Dict[str, Any]]]] |
Extract per-layer cache data for a single block. | #L630-L702 |
BlockAwarePrefixCache._cache_state_seq_axis |
method | BlockAwarePrefixCache._cache_state_seq_axis(state: Any) -> Optional[int] |
Return the sequence axis for cache states that support block concat. | #L704-L725 |
BlockAwarePrefixCache._slice_concat_cache_state |
method | BlockAwarePrefixCache._slice_concat_cache_state(state: Tuple[Any, ...] \| List[Any], start_idx: int, end_idx: int) -> Tuple[Any, ...] \| List[Any] |
Slice a sequence-backed cache state across the token axis. | #L727-L751 |
BlockAwarePrefixCache._slice_concat_cache_state._slice_tensor |
nested function | BlockAwarePrefixCache._slice_concat_cache_state._slice_tensor(tensor: Any) -> Any |
Nested Function BlockAwarePrefixCache._slice_concat_cache_state._slice_tensor calls slice, len, tuple; returns tensor[tuple(slices)]. |
#L745-L748 |
BlockAwarePrefixCache._concat_cache_states |
method | BlockAwarePrefixCache._concat_cache_states(states: List[Tuple[Any, ...] \| List[Any]], seq_axis: int) -> Optional[Tuple[Any, ...] \| List[Any]] |
Concatenate state fragments for a sequence-backed cache layer. | #L753-L768 |
BlockAwarePrefixCache.get_cache_for_generation |
method | BlockAwarePrefixCache.get_cache_for_generation(request_id: str) -> Tuple[Optional[List[Any]], bool] |
Get cache data for generation, applying COW if needed. | #L770-L799 |
BlockAwarePrefixCache.release_cache |
method | BlockAwarePrefixCache.release_cache(request_id: str) -> None |
Release cache blocks for a completed request. | #L801-L811 |
BlockAwarePrefixCache.fork_cache |
method | BlockAwarePrefixCache.fork_cache(source_request_id: str, new_request_id: str) -> Optional[BlockTable] |
Fork cache from one request to another (COW). | #L813-L847 |
BlockAwarePrefixCache.reconstruct_cache |
method | BlockAwarePrefixCache.reconstruct_cache(block_table: BlockTable) -> Optional[List[Any]] |
Reconstruct cache objects from stored block tensor data. | #L849-L967 |
BlockAwarePrefixCache._find_best_prefix_match |
method | BlockAwarePrefixCache._find_best_prefix_match(tokens: List[int]) -> Optional[Tuple[List[int], List[int]]] |
Find best matching prefix in the index. | #L969-L992 |
BlockAwarePrefixCache._update_prefix_index |
method | BlockAwarePrefixCache._update_prefix_index(tokens: List[int], block_ids: List[int]) -> None |
Update prefix index with new token sequence. | #L994-L1005 |
BlockAwarePrefixCache.get_stats |
method | BlockAwarePrefixCache.get_stats() -> Dict[str, Any] |
Get cache statistics. | #L1007-L1021 |
BlockAwarePrefixCache.reset_stats |
method | BlockAwarePrefixCache.reset_stats() -> None |
Reset statistics. | #L1023-L1028 |
BlockAwarePrefixCache.clear |
method | BlockAwarePrefixCache.clear() -> None |
Clear all cached data. | #L1030-L1035 |
BlockAwarePrefixCache.__len__ |
method | BlockAwarePrefixCache.__len__() -> int |
Return number of active request entries. | #L1037-L1039 |