vllm_mlx.memory_cache¶
Memory-aware prefix cache for vllm-mlx.
View the complete module source at #L1-L1463.
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.memory_cache
¶
Memory-aware prefix cache for vllm-mlx.
This module provides a prefix cache implementation that tracks memory usage and evicts entries based on memory pressure rather than entry count.
Key features: - Automatic memory limit detection based on available system RAM - Accurate memory tracking for MLX array caches - LRU eviction triggered by memory thresholds - No unnecessary deep copies (MLX arrays are immutable)
Example
config = MemoryCacheConfig(max_memory_percent=0.25) cache = MemoryAwarePrefixCache(model, config)
Fetch returns reference (no copy) - safe because MLX arrays are immutable¶
kv_cache, remaining = cache.fetch(tokens)
Store tracks memory automatically¶
cache.store(tokens, kv_cache)
vllm_mlx.memory_cache.MemoryCacheConfig
dataclass
¶
MemoryCacheConfig(max_memory_mb: int | None = None, max_memory_percent: float = _DEFAULT_MEMORY_PERCENT, max_entries: int = 1000, enable_memory_tracking: bool = True, kv_quantize: bool = False, kv_bits: int = 8, kv_group_size: int = 64, kv_min_quantize_tokens: int = 256, min_prefix_tokens: int = 128)
Configuration for memory-aware prefix cache.
Attributes:
-
max_memory_mb(int | None) –Maximum memory in MB. If None, auto-detects.
-
max_memory_percent(float) –Fraction of available RAM to use (0.0-1.0).
-
max_entries(int) –Hard limit on number of entries (safety net).
-
enable_memory_tracking(bool) –Whether to track per-entry memory.
-
kv_quantize(bool) –Whether to quantize KV cache layers for reduced memory.
-
kv_bits(int) –Number of bits for KV cache quantization.
-
kv_group_size(int) –Group size for KV cache quantization.
-
kv_min_quantize_tokens(int) –Minimum sequence length for quantization to apply.
-
min_prefix_tokens(int) –Minimum cached prefix length eligible for reuse.
vllm_mlx.memory_cache.MemoryCacheConfig.max_memory_mb
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.MemoryCacheConfig.max_memory_percent
class-attribute
instance-attribute
¶
max_memory_percent: float = _DEFAULT_MEMORY_PERCENT
vllm_mlx.memory_cache.MemoryCacheConfig.max_entries
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.MemoryCacheConfig.enable_memory_tracking
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.MemoryCacheConfig.kv_quantize
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.MemoryCacheConfig.kv_bits
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.MemoryCacheConfig.kv_group_size
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.MemoryCacheConfig.kv_min_quantize_tokens
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.MemoryCacheConfig.min_prefix_tokens
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.MemoryCacheConfig.__post_init__
¶
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.MemoryCacheConfig.compute_memory_limit
¶
Compute the memory limit in bytes.
Returns:
-
int–Memory limit in bytes.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.CacheStats
dataclass
¶
CacheStats(hits: int = 0, misses: int = 0, evictions: int = 0, tokens_saved: int = 0, current_memory_bytes: int = 0, max_memory_bytes: int = 0, entry_count: int = 0)
Statistics for cache performance monitoring.
vllm_mlx.memory_cache.CacheStats.tokens_saved
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.CacheStats.current_memory_bytes
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.CacheStats.max_memory_bytes
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.CacheStats.entry_count
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache.CacheStats.hit_rate
property
¶
Return successful lookups divided by all completed lookups.
vllm_mlx.memory_cache.CacheStats.memory_utilization
property
¶
Return the fraction of the configured memory budget in use.
vllm_mlx.memory_cache.CacheStats.to_dict
¶
Return rounded cache counters and memory values for APIs and logs.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache._CacheEntry
dataclass
¶
Internal cache entry with memory tracking.
vllm_mlx.memory_cache._CacheEntry.create
classmethod
¶
create(tokens: list[int], cache: list[Any]) -> _CacheEntry
Create a cache entry with memory estimation.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache._QuantizedCacheWrapper
¶
Lightweight wrapper storing quantized KV arrays + original cache metadata.
Unlike QuantizedKVCache, this preserves enough info to reconstruct
the original cache type (KVCache, RotatingKVCache, etc.) on dequantize.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache._QuantizedCacheWrapper.__slots__
class-attribute
instance-attribute
¶
vllm_mlx.memory_cache._QuantizedCacheWrapper.keys
instance-attribute
¶
vllm_mlx.memory_cache._QuantizedCacheWrapper.values
instance-attribute
¶
vllm_mlx.memory_cache._QuantizedCacheWrapper.group_size
instance-attribute
¶
vllm_mlx.memory_cache.MemoryAwarePrefixCache
¶
MemoryAwarePrefixCache(model: Any, config: MemoryCacheConfig | None = None)
Prefix cache with memory-based eviction.
This cache tracks memory usage per entry and evicts based on memory pressure rather than entry count. It uses LRU (Least Recently Used) ordering for eviction decisions.
Key design decisions: - No deep copies on fetch: MLX arrays are immutable, so sharing is safe - Memory tracking per entry: Accurate accounting for eviction - Auto-detection of available RAM: Adapts to different systems - OrderedDict for O(1) LRU operations
Thread Safety
This class is NOT thread-safe. Use external locking if needed.
Initialize the memory-aware prefix cache.
Parameters:
-
model(Any) –The MLX model (used for identification).
-
config(MemoryCacheConfig | None, default:None) –Cache configuration. Uses defaults if None.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.MemoryAwarePrefixCache._config
instance-attribute
¶
_config = config or MemoryCacheConfig()
vllm_mlx.memory_cache.MemoryAwarePrefixCache._model_fingerprint
instance-attribute
¶
_model_fingerprint = _compute_model_fingerprint(model)
vllm_mlx.memory_cache.MemoryAwarePrefixCache._entries
instance-attribute
¶
_entries: OrderedDict[tuple[int, ...], _CacheEntry] = OrderedDict()
vllm_mlx.memory_cache.MemoryAwarePrefixCache._sorted_keys
instance-attribute
¶
vllm_mlx.memory_cache.MemoryAwarePrefixCache._max_memory
instance-attribute
¶
vllm_mlx.memory_cache.MemoryAwarePrefixCache._current_memory
instance-attribute
¶
vllm_mlx.memory_cache.MemoryAwarePrefixCache._memory_lock
instance-attribute
¶
vllm_mlx.memory_cache.MemoryAwarePrefixCache._stats
instance-attribute
¶
_stats = CacheStats(max_memory_bytes=self._max_memory)
vllm_mlx.memory_cache.MemoryAwarePrefixCache._last_match_type
instance-attribute
¶
vllm_mlx.memory_cache.MemoryAwarePrefixCache.memory_usage_mb
property
¶
Current memory usage in MB.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.memory_limit_mb
property
¶
Memory limit in MB.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.fetch
¶
Find cached KV state for the given tokens.
This method searches for exact matches, prefix matches, supersequence matches, and longest-common-prefix (LCP) matches. Uses a sorted key index for O(log N) lookup instead of scanning all entries.
Returns the cached KV state directly (no copy) since MLX arrays are immutable and safe to share.
Parameters:
-
tokens(list[int]) –Input token sequence.
Returns:
-
list[Any] | None–Tuple of (cache, remaining_tokens):
-
list[int]–- cache: Cached KV state if found, None otherwise
-
tuple[list[Any] | None, list[int]]–- remaining_tokens: Tokens that still need processing
Source code in vllm_mlx/memory_cache.py
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 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 968 969 970 971 972 973 974 975 976 977 | |
vllm_mlx.memory_cache.MemoryAwarePrefixCache.store
¶
Store KV cache for future reuse.
This method stores the cache reference directly (no copy) and tracks memory usage. If memory limit is exceeded, LRU entries are evicted until there's room.
Parameters:
-
tokens(list[int]) –Token sequence that was processed.
-
cache(list[Any]) –The computed KV cache to store.
-
evict_prefixes(bool, default:True) –If True, evict existing entries whose token sequence is a strict prefix of
tokens. Set to False when storing prompt+output entries to preserve prompt-only entries created by prompt_cache_save (those are the entries that future requests will actually match).
Returns:
-
bool–True if stored successfully, False if rejected.
Source code in vllm_mlx/memory_cache.py
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 | |
vllm_mlx.memory_cache.MemoryAwarePrefixCache._remove_from_sorted
¶
Remove a key from the sorted index using bisect for O(log N).
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.MemoryAwarePrefixCache._evict_lru
¶
Evict the least recently used entry.
If an SSD tier is attached, the entry is spilled to disk instead of being discarded.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.MemoryAwarePrefixCache.remove
¶
Remove a specific cache entry.
Parameters:
-
tokens(list[int]) –Token sequence to remove.
Returns:
-
bool–True if entry was found and removed.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.MemoryAwarePrefixCache.clear
¶
Clear all cached entries.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.MemoryAwarePrefixCache.get_stats
¶
vllm_mlx.memory_cache.MemoryAwarePrefixCache.reset_stats
¶
Reset statistics while preserving cache contents.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.MemoryAwarePrefixCache.try_reserve_memory
¶
Tentatively reserve cache memory for an upcoming promotion.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.MemoryAwarePrefixCache.release_reserved_memory
¶
Release memory previously reserved by try_reserve_memory().
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.MemoryAwarePrefixCache.__len__
¶
vllm_mlx.memory_cache.MemoryAwarePrefixCache.__contains__
¶
vllm_mlx.memory_cache.MemoryAwarePrefixCache.set_ssd_tier
¶
Attach an SSD cache tier for eviction spilling.
When set, evicted entries are spilled to SSD instead of discarded.
Parameters:
-
ssd_tier–An SSDCacheTier instance (or None to disable).
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.MemoryAwarePrefixCache.check_ssd
¶
Check if tokens have an SSD cache hit (without reading data).
Returns metadata dict with 'match_type' ('exact' or 'prefix') if found in SSD tier, None if not found. For prefix matches, the dict also includes 'matched_tokens' (the count of tokens the SSD entry covers).
This is a fast synchronous call (SQLite lookup only). The actual data read happens via the scheduler handoff.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.MemoryAwarePrefixCache.save_to_disk
¶
Save all cache entries to disk using mlx_lm's safetensors format.
Directory layout::
cache_dir/
index.json # token keys + metadata per entry
entry_0.safetensors # KV arrays for entry 0
entry_1.safetensors
...
Returns True if at least one entry was saved.
Source code in vllm_mlx/memory_cache.py
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 | |
vllm_mlx.memory_cache.MemoryAwarePrefixCache.load_from_disk
¶
Load cache entries from disk.
Returns the number of entries successfully loaded.
Source code in vllm_mlx/memory_cache.py
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 | |
vllm_mlx.memory_cache._get_available_memory
¶
Get available system memory in bytes.
Returns:
-
int–Available memory in bytes, or 0 if detection fails.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache._array_memory
¶
Estimate array memory from shape+dtype without triggering lazy eval.
Accessing .nbytes on a lazy MLX array forces evaluation of the entire computation graph, causing a VRAM spike. This function uses shape and dtype metadata (which are always available without eval) to compute the same value.
Parameters:
-
arr–An MLX array or similar object.
Returns:
-
int–Estimated memory in bytes.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache._nested_array_memory
¶
Sum _array_memory over an arbitrarily nested state structure.
Cache state payloads are not always a flat (keys, values) pair:
CacheList yields a list of sub-cache states and PoolingCache yields
(buf_kv, buf_gate, pooled) with possible None members. Unpacking
those as two values raised, was swallowed, and the entry was accounted as
zero bytes — so the dashboard showed 0% cache memory and, far worse, the
byte-based LRU eviction never fired for such models.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache.estimate_kv_cache_memory
¶
Estimate memory usage of a KV cache in bytes.
This function inspects MLX arrays in the cache and calculates their total memory footprint using shape+dtype metadata to avoid triggering lazy evaluation (which would cause a VRAM spike).
Parameters:
-
cache(list[Any]) –List of layer cache objects, each containing keys/values tensors.
Returns:
-
int–Estimated memory usage in bytes.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache._is_cache_layer_trimmable
¶
Return whether a cache layer can safely be rewound for partial reuse.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache._trim_cache_offset
¶
Create copies of cache layers with the last trim_by positions removed.
This is used when returning a cached KV state to the scheduler so that the last N positions are "freed" and the model will recompute them on the next forward pass (preventing duplicate KV entries).
For plain KVCache: reduces offset (surplus data beyond offset is harmless
since merge slices to keys[:, :, :offset, :]).
For RotatingKVCache: actually trims the circular buffer — reducing offset
alone breaks size() / _temporal_order invariants.
Supports KVCache, RotatingKVCache, and _QuantizedCacheWrapper.
Source code in vllm_mlx/memory_cache.py
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 | |
vllm_mlx.memory_cache._needs_kv_trim
¶
Check if a cache layer has oversized KV arrays (duck-typed, no MLX import).
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache._trim_to_offset
¶
Trim KV arrays to their actual used size (offset) before storage.
KV arrays are often pre-allocated larger than needed (e.g. 4096 slots
when only 100 are used). This slices them down to offset and
evaluates the result so the original large buffer can be freed.
Parameters:
-
cache(list[Any]) –List of cache layer objects (KVCache or other types).
Returns:
-
list[Any]–New list with KVCache layers trimmed to their offset.
-
list[Any]–Non-KVCache layers are passed through unchanged.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache._quantize_cache
¶
Quantize KV cache layers to reduce memory.
Only plain KVCache layers are quantized. RotatingKVCache (sliding window) is left as-is because its internal _idx/rotation state is tightly coupled with update_and_fetch logic and cannot survive quantize/dequantize roundtrip. RotatingKVCache is typically small (max_size=1024) so skipping it is fine.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache._dequantize_cache
¶
Dequantize _QuantizedCacheWrapper layers and copy non-quantized layers.
All layers are copied (never returned by reference) so that the model's
update_and_fetch mutations don't corrupt the stored cache entry.
Source code in vllm_mlx/memory_cache.py
vllm_mlx.memory_cache._compute_model_fingerprint
¶
Compute a fingerprint from model architecture for cache compatibility.
Used to reject disk-persisted caches created by a different model or a different quantisation of the same model. The fingerprint is a short hex digest of (num_layers, hidden_size, vocab_size, num_kv_heads, head_dim) — lightweight and deterministic.
Source code in vllm_mlx/memory_cache.py
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.memory_cache._get_available_memory · function
Get available system memory in bytes.
Parameters
This callable has no explicit inputs.
Returns
- Type:
int - Direct return expressions:
psutil.virtual_memory().available;0
Exceptions and behavior
Function _get_available_memory calls psutil.virtual_memory, logger.warning; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._array_memory · function
Estimate array memory from shape+dtype without triggering lazy eval.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
arr |
not annotated |
yes |
none |
An MLX array or similar object. |
Returns
- Type:
int - Direct return expressions:
math.prod(arr.shape) * dtype.size;arr.nbytes;0
Exceptions and behavior
Function _array_memory calls hasattr, math.prod; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._nested_array_memory · function
Sum _array_memory over an arbitrarily nested state structure.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
value |
Any |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
int - Direct return expressions:
0;sum((_nested_array_memory(v) for v in value));_array_memory(value)
Exceptions and behavior
Function _nested_array_memory calls isinstance, sum, _nested_array_memory, _array_memory; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.estimate_kv_cache_memory · function
Estimate memory usage of a KV cache in bytes.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
cache |
list[Any] |
yes |
none |
List of layer cache objects, each containing keys/values tensors. |
Returns
- Type:
int - Direct return expressions:
0;total_bytes
Exceptions and behavior
Function estimate_kv_cache_memory calls isinstance, _array_memory, hasattr, getattr; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryCacheConfig · class
vllm_mlx.memory_cache.MemoryCacheConfig(max_memory_mb: int | None = None, max_memory_percent: float = _DEFAULT_MEMORY_PERCENT, max_entries: int = 1000, enable_memory_tracking: bool = True, kv_quantize: bool = False, kv_bits: int = 8, kv_group_size: int = 64, kv_min_quantize_tokens: int = 256, min_prefix_tokens: int = 128)
Configuration for memory-aware prefix cache.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
max_memory_mb |
int \| None |
no |
None |
Optional constructor field; defaults to None. |
max_memory_percent |
float |
no |
_DEFAULT_MEMORY_PERCENT |
Optional constructor field; defaults to _DEFAULT_MEMORY_PERCENT. |
max_entries |
int |
no |
1000 |
Optional constructor field; defaults to 1000. |
enable_memory_tracking |
bool |
no |
True |
Optional constructor field; defaults to True. |
kv_quantize |
bool |
no |
False |
Optional constructor field; defaults to False. |
kv_bits |
int |
no |
8 |
Optional constructor field; defaults to 8. |
kv_group_size |
int |
no |
64 |
Optional constructor field; defaults to 64. |
kv_min_quantize_tokens |
int |
no |
256 |
Optional constructor field; defaults to 256. |
min_prefix_tokens |
int |
no |
128 |
Optional constructor field; defaults to 128. |
Returns
- Constructs:
vllm_mlx.memory_cache.MemoryCacheConfig
Exceptions and behavior
Class MemoryCacheConfig declares 2 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryCacheConfig.__post_init__ · method
Method MemoryCacheConfig.__post_init__ calls ValueError; can raise ValueError.
Parameters
This callable has no explicit inputs.
Returns
- Type:
None
Exceptions and behavior
Method MemoryCacheConfig.__post_init__ calls ValueError; can raise ValueError.
Directly raised exceptions: ValueError.
vllm_mlx.memory_cache.MemoryCacheConfig.compute_memory_limit · method
Compute the memory limit in bytes.
Parameters
This callable has no explicit inputs.
Returns
- Type:
int - Direct return expressions:
self.max_memory_mb * _BYTES_PER_MB;max(limit, _MIN_MEMORY_BYTES);int(fallback_total * self.max_memory_percent)
Exceptions and behavior
Method MemoryCacheConfig.compute_memory_limit calls _get_available_memory, int, max; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.CacheStats · class
vllm_mlx.memory_cache.CacheStats(hits: int = 0, misses: int = 0, evictions: int = 0, tokens_saved: int = 0, current_memory_bytes: int = 0, max_memory_bytes: int = 0, entry_count: int = 0)
Statistics for cache performance monitoring.
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. |
evictions |
int |
no |
0 |
Optional constructor field; defaults to 0. |
tokens_saved |
int |
no |
0 |
Optional constructor field; defaults to 0. |
current_memory_bytes |
int |
no |
0 |
Optional constructor field; defaults to 0. |
max_memory_bytes |
int |
no |
0 |
Optional constructor field; defaults to 0. |
entry_count |
int |
no |
0 |
Optional constructor field; defaults to 0. |
Returns
- Constructs:
vllm_mlx.memory_cache.CacheStats
Exceptions and behavior
Class CacheStats declares 3 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.CacheStats.hit_rate · method
Return successful lookups divided by all completed lookups.
Parameters
This callable has no explicit inputs.
Returns
- Type:
float - Direct return expressions:
self.hits / total if total > 0 else 0.0
Exceptions and behavior
Method CacheStats.hit_rate returns self.hits / total if total > 0 else 0.0.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.CacheStats.memory_utilization · method
Return the fraction of the configured memory budget in use.
Parameters
This callable has no explicit inputs.
Returns
- Type:
float - Direct return expressions:
0.0;self.current_memory_bytes / self.max_memory_bytes
Exceptions and behavior
Method CacheStats.memory_utilization has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.CacheStats.to_dict · method
Return rounded cache counters and memory values for APIs and logs.
Parameters
This callable has no explicit inputs.
Returns
- Type:
dict[str, Any] - Direct return expressions:
{'hits': self.hits, 'misses': self.misses, 'hit_rate': round(self.hit_rate, 4), 'evictions': self.evictions, 'tokens_sa…
Exceptions and behavior
Method CacheStats.to_dict calls round; returns {'hits': self.hits, 'misses': self.misses, 'hit_rate': round(self.hit_rate, 4), 'evictions': self.evictions, 'tokens_sa….
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._CacheEntry · class
Internal cache entry with memory tracking.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
tuple[int, ...] |
yes |
none |
Required constructor field. |
cache |
list[Any] |
yes |
none |
Required constructor field. |
memory_bytes |
int |
yes |
none |
Required constructor field. |
Returns
- Constructs:
vllm_mlx.memory_cache._CacheEntry
Exceptions and behavior
Class _CacheEntry declares 1 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._CacheEntry.create · method
Create a cache entry with memory estimation.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
list[int] |
yes |
none |
Required positional or keyword input. |
cache |
list[Any] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
_CacheEntry - Direct return expressions:
cls(tokens=tuple(tokens), cache=cache, memory_bytes=memory)
Exceptions and behavior
Method _CacheEntry.create calls estimate_kv_cache_memory, cls, tuple; returns cls(tokens=tuple(tokens), cache=cache, memory_bytes=memory).
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._is_cache_layer_trimmable · function
Return whether a cache layer can safely be rewound for partial reuse.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
layer_cache |
Any |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
bool - Direct return expressions:
False;hasattr(layer_cache, 'offset') and hasattr(layer_cache, 'keys');bool(is_trimmable())
Exceptions and behavior
Function _is_cache_layer_trimmable calls isinstance, hasattr, getattr, callable; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._trim_cache_offset · function
Create copies of cache layers with the last trim_by positions removed.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
cache |
list[Any] |
yes |
none |
Required positional or keyword input. |
trim_by |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list[Any] - Direct return expressions:
trimmed
Exceptions and behavior
Function _trim_cache_offset calls isinstance, _QuantizedCacheWrapper.__new__, max, trimmed.append; returns trimmed.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._needs_kv_trim · function
Check if a cache layer has oversized KV arrays (duck-typed, no MLX import).
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
layer |
Any |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
bool - Direct return expressions:
False;0 < offset < shape[2]
Exceptions and behavior
Function _needs_kv_trim calls getattr, isinstance, len; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._trim_to_offset · function
Trim KV arrays to their actual used size (offset) before storage.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
cache |
list[Any] |
yes |
none |
List of cache layer objects (KVCache or other types). |
Returns
- Type:
list[Any] - Direct return expressions:
cache;trimmed
Exceptions and behavior
Function _trim_to_offset calls any, _needs_kv_trim, isinstance, trimmed.append; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._QuantizedCacheWrapper · class
Lightweight wrapper storing quantized KV arrays + original cache metadata.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
layer |
Any |
yes |
none |
Required positional or keyword input. |
bits |
int |
yes |
none |
Required positional or keyword input. |
group_size |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Constructs:
vllm_mlx.memory_cache._QuantizedCacheWrapper
Exceptions and behavior
Class _QuantizedCacheWrapper declares 1 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._QuantizedCacheWrapper.__init__ · method
vllm_mlx.memory_cache._QuantizedCacheWrapper.__init__(layer: Any, bits: int, group_size: int) -> not annotated
Method _QuantizedCacheWrapper.__init__ updates self.keys, self.values, self.offset, self.bits; calls mx.quantize, type, hasattr, getattr.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
layer |
Any |
yes |
none |
Required positional or keyword input. |
bits |
int |
yes |
none |
Required positional or keyword input. |
group_size |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
not annotated
Exceptions and behavior
Method _QuantizedCacheWrapper.__init__ updates self.keys, self.values, self.offset, self.bits; calls mx.quantize, type, hasattr, getattr.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._quantize_cache · function
vllm_mlx.memory_cache._quantize_cache(cache: list[Any], bits: int = 8, group_size: int = 64) -> list[Any]
Quantize KV cache layers to reduce memory.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
cache |
list[Any] |
yes |
none |
Required positional or keyword input. |
bits |
int |
no |
8 |
Optional positional or keyword input; defaults to 8. |
group_size |
int |
no |
64 |
Optional positional or keyword input; defaults to 64. |
Returns
- Type:
list[Any] - Direct return expressions:
quantized
Exceptions and behavior
Function _quantize_cache calls type, getattr, quantized.append, _QuantizedCacheWrapper; returns quantized.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._dequantize_cache · function
Dequantize _QuantizedCacheWrapper layers and copy non-quantized layers.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
cache |
list[Any] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
list[Any] - Direct return expressions:
result
Exceptions and behavior
Function _dequantize_cache calls isinstance, orig_cls.__new__, mx.dequantize, hasattr; returns result.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache._compute_model_fingerprint · function
Compute a fingerprint from model architecture for cache compatibility.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model |
Any |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
str - Direct return expressions:
fingerprint
Exceptions and behavior
Function _compute_model_fingerprint calls getattr, parts.append, hashlib.sha256('|'.join(parts).encode()).hexdigest, hashlib.sha256; returns fingerprint.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache · class
Prefix cache with memory-based eviction.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model |
Any |
yes |
none |
The MLX model (used for identification). |
config |
MemoryCacheConfig \| None |
no |
None |
Cache configuration. Uses defaults if None. |
Returns
- Constructs:
vllm_mlx.memory_cache.MemoryAwarePrefixCache
Exceptions and behavior
Class MemoryAwarePrefixCache declares 19 direct member(s).
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.__init__ · method
vllm_mlx.memory_cache.MemoryAwarePrefixCache.__init__(model: Any, config: MemoryCacheConfig | None = None) -> None
Initialize the memory-aware prefix cache.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
model |
Any |
yes |
none |
The MLX model (used for identification). |
config |
MemoryCacheConfig \| None |
no |
None |
Cache configuration. Uses defaults if None. |
Returns
- Type:
None
Exceptions and behavior
Method MemoryAwarePrefixCache.__init__ updates self._model_id, self._config, self._model_fingerprint, self._entries; calls id, MemoryCacheConfig, _compute_model_fingerprint, OrderedDict.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.fetch · method
vllm_mlx.memory_cache.MemoryAwarePrefixCache.fetch(tokens: list[int]) -> tuple[list[Any] | None, list[int]]
Find cached KV state for the given tokens.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
list[int] |
yes |
none |
Input token sequence. |
Returns
- Type:
tuple[list[Any] | None, list[int]] - Direct return expressions:
(None, tokens);(cache_out, []);(trimmed_cache, []);(cache_out, remaining);(trimmed_cache, remaining)
Exceptions and behavior
Method MemoryAwarePrefixCache.fetch updates self._stats.misses, self._last_match_type, self._stats.hits, self._stats.tokens_saved; calls len, tuple, self._entries.move_to_end, _dequantize_cache; has 5 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.store · method
vllm_mlx.memory_cache.MemoryAwarePrefixCache.store(tokens: list[int], cache: list[Any], evict_prefixes: bool = True) -> bool
Store KV cache for future reuse.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
list[int] |
yes |
none |
Token sequence that was processed. |
cache |
list[Any] |
yes |
none |
The computed KV cache to store. |
evict_prefixes |
bool |
no |
True |
If True, evict existing entries whose token sequence is a strict prefix of tokens. Set to False when storing prompt+output entries to preserve prompt-only entries created by prompt_cache_save (those are the entries that future requests will actually match). |
Returns
- Type:
bool - Direct return expressions:
False;True
Exceptions and behavior
Method MemoryAwarePrefixCache.store updates self._current_memory, self._stats.evictions, self._stats.entry_count, self._stats.current_memory_bytes; calls len, logger.debug, tuple, self._entries.move_to_end; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache._remove_from_sorted · method
Remove a key from the sorted index using bisect for O(log N).
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
key |
tuple[int, ...] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None
Exceptions and behavior
Method MemoryAwarePrefixCache._remove_from_sorted calls bisect.bisect_left, len, self._sorted_keys.pop.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache._evict_lru · method
Evict the least recently used entry.
Parameters
This callable has no explicit inputs.
Returns
- Type:
None - Direct return expressions:
None
Exceptions and behavior
Method MemoryAwarePrefixCache._evict_lru updates self._current_memory, self._stats.evictions, self._stats.entry_count, self._stats.current_memory_bytes; calls self._entries.popitem, self._remove_from_sorted, len, self._ssd_tier.enqueue_spill; returns None.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.remove · method
Remove a specific cache entry.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
list[int] |
yes |
none |
Token sequence to remove. |
Returns
- Type:
bool - Direct return expressions:
True;False
Exceptions and behavior
Method MemoryAwarePrefixCache.remove updates self._current_memory, self._stats.entry_count, self._stats.current_memory_bytes; calls tuple, self._entries.pop, self._remove_from_sorted, len; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.clear · method
Clear all cached entries.
Parameters
This callable has no explicit inputs.
Returns
- Type:
None
Exceptions and behavior
Method MemoryAwarePrefixCache.clear updates self._current_memory, self._stats; calls self._entries.clear, self._sorted_keys.clear, CacheStats, logger.debug.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.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 MemoryAwarePrefixCache.get_stats calls self._stats.to_dict; returns self._stats.to_dict().
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.reset_stats · method
Reset statistics while preserving cache contents.
Parameters
This callable has no explicit inputs.
Returns
- Type:
None
Exceptions and behavior
Method MemoryAwarePrefixCache.reset_stats updates self._stats; calls CacheStats, len.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.memory_usage_mb · method
Current memory usage in MB.
Parameters
This callable has no explicit inputs.
Returns
- Type:
float - Direct return expressions:
self._current_memory / _BYTES_PER_MB
Exceptions and behavior
Method MemoryAwarePrefixCache.memory_usage_mb returns self._current_memory / _BYTES_PER_MB.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.memory_limit_mb · method
Memory limit in MB.
Parameters
This callable has no explicit inputs.
Returns
- Type:
float - Direct return expressions:
self._max_memory / _BYTES_PER_MB
Exceptions and behavior
Method MemoryAwarePrefixCache.memory_limit_mb returns self._max_memory / _BYTES_PER_MB.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.try_reserve_memory · method
Tentatively reserve cache memory for an upcoming promotion.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
nbytes |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
bool - Direct return expressions:
False;True
Exceptions and behavior
Method MemoryAwarePrefixCache.try_reserve_memory updates self._current_memory, self._stats.current_memory_bytes; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.release_reserved_memory · method
Release memory previously reserved by try_reserve_memory().
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
nbytes |
int |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
None
Exceptions and behavior
Method MemoryAwarePrefixCache.release_reserved_memory updates self._current_memory, self._stats.current_memory_bytes; calls max.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.__len__ · method
Return number of cached entries.
Parameters
This callable has no explicit inputs.
Returns
- Type:
int - Direct return expressions:
len(self._entries)
Exceptions and behavior
Method MemoryAwarePrefixCache.__len__ calls len; returns len(self._entries).
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.__contains__ · method
Check if tokens are cached.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
list[int] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
bool - Direct return expressions:
tuple(tokens) in self._entries
Exceptions and behavior
Method MemoryAwarePrefixCache.__contains__ calls tuple; returns tuple(tokens) in self._entries.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.set_ssd_tier · method
Attach an SSD cache tier for eviction spilling.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
ssd_tier |
not annotated |
yes |
none |
An SSDCacheTier instance (or None to disable). |
Returns
- Type:
None
Exceptions and behavior
Method MemoryAwarePrefixCache.set_ssd_tier updates self._ssd_tier; calls logger.info.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.check_ssd · method
Check if tokens have an SSD cache hit (without reading data).
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
tokens |
list[int] |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
dict | None - Direct return expressions:
None;candidate;prefix
Exceptions and behavior
Method MemoryAwarePrefixCache.check_ssd calls tuple, self._ssd_tier.lookup_ssd, len, self._ssd_tier.lookup_ssd_prefix; has 3 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.save_to_disk · method
Save all cache entries to disk using mlx_lm's safetensors format.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
cache_dir |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
bool - Direct return expressions:
False;saved > 0
Exceptions and behavior
Method MemoryAwarePrefixCache.save_to_disk calls logger.info, _time.monotonic, os.makedirs, logger.warning; has 2 explicit return paths.
No direct raise statement appears in this definition.
vllm_mlx.memory_cache.MemoryAwarePrefixCache.load_from_disk · method
Load cache entries from disk.
Parameters
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
cache_dir |
str |
yes |
none |
Required positional or keyword input. |
Returns
- Type:
int - Direct return expressions:
0;loaded
Exceptions and behavior
Method MemoryAwarePrefixCache.load_from_disk updates self._current_memory, self._stats.entry_count, self._stats.current_memory_bytes; calls os.path.join, os.path.exists, logger.info, _time.monotonic; has 2 explicit return paths.
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 |
|---|---|---|---|---|
_get_available_memory |
function | _get_available_memory() -> int |
Get available system memory in bytes. | #L47-L63 |
_array_memory |
function | _array_memory(arr) -> int |
Estimate array memory from shape+dtype without triggering lazy eval. | #L66-L88 |
_nested_array_memory |
function | _nested_array_memory(value: Any) -> int |
Sum _array_memory over an arbitrarily nested state structure. |
#L91-L105 |
estimate_kv_cache_memory |
function | estimate_kv_cache_memory(cache: list[Any]) -> int |
Estimate memory usage of a KV cache in bytes. | #L108-L162 |
MemoryCacheConfig |
class | MemoryCacheConfig(max_memory_mb: int \| None = None, max_memory_percent: float = _DEFAULT_MEMORY_PERCENT, max_entries: int = 1000, enable_memory_tracking: bool = True, kv_quantize: bool = False, kv_bits: int = 8, kv_group_size: int = 64, kv_min_quantize_tokens: int = 256, min_prefix_tokens: int = 128) |
Configuration for memory-aware prefix cache. | #L166-L225 |
MemoryCacheConfig.__post_init__ |
method | MemoryCacheConfig.__post_init__() -> None |
Method MemoryCacheConfig.__post_init__ calls ValueError; can raise ValueError. |
#L192-L206 |
MemoryCacheConfig.compute_memory_limit |
method | MemoryCacheConfig.compute_memory_limit() -> int |
Compute the memory limit in bytes. | #L208-L225 |
CacheStats |
class | CacheStats(hits: int = 0, misses: int = 0, evictions: int = 0, tokens_saved: int = 0, current_memory_bytes: int = 0, max_memory_bytes: int = 0, entry_count: int = 0) |
Statistics for cache performance monitoring. | #L229-L268 |
CacheStats.hit_rate |
method | CacheStats.hit_rate() -> float |
Return successful lookups divided by all completed lookups. | #L241-L245 |
CacheStats.memory_utilization |
method | CacheStats.memory_utilization() -> float |
Return the fraction of the configured memory budget in use. | #L248-L253 |
CacheStats.to_dict |
method | CacheStats.to_dict() -> dict[str, Any] |
Return rounded cache counters and memory values for APIs and logs. | #L255-L268 |
_CacheEntry |
class | _CacheEntry(tokens: tuple[int, ...], cache: list[Any], memory_bytes: int) |
Internal cache entry with memory tracking. | #L272-L287 |
_CacheEntry.create |
method | _CacheEntry.create(tokens: list[int], cache: list[Any]) -> _CacheEntry |
Create a cache entry with memory estimation. | #L280-L287 |
_is_cache_layer_trimmable |
function | _is_cache_layer_trimmable(layer_cache: Any) -> bool |
Return whether a cache layer can safely be rewound for partial reuse. | #L290-L314 |
_trim_cache_offset |
function | _trim_cache_offset(cache: list[Any], trim_by: int) -> list[Any] |
Create copies of cache layers with the last trim_by positions removed. |
#L317-L481 |
_needs_kv_trim |
function | _needs_kv_trim(layer: Any) -> bool |
Check if a cache layer has oversized KV arrays (duck-typed, no MLX import). | #L484-L495 |
_trim_to_offset |
function | _trim_to_offset(cache: list[Any]) -> list[Any] |
Trim KV arrays to their actual used size (offset) before storage. | #L498-L538 |
_QuantizedCacheWrapper |
class | _QuantizedCacheWrapper(layer: Any, bits: int, group_size: int) |
Lightweight wrapper storing quantized KV arrays + original cache metadata. | #L541-L571 |
_QuantizedCacheWrapper.__init__ |
method | _QuantizedCacheWrapper.__init__(layer: Any, bits: int, group_size: int) -> not annotated |
Method _QuantizedCacheWrapper.__init__ updates self.keys, self.values, self.offset, self.bits; calls mx.quantize, type, hasattr, getattr. |
#L558-L571 |
_quantize_cache |
function | _quantize_cache(cache: list[Any], bits: int = 8, group_size: int = 64) -> list[Any] |
Quantize KV cache layers to reduce memory. | #L574-L590 |
_dequantize_cache |
function | _dequantize_cache(cache: list[Any]) -> list[Any] |
Dequantize _QuantizedCacheWrapper layers and copy non-quantized layers. | #L593-L645 |
_compute_model_fingerprint |
function | _compute_model_fingerprint(model: Any) -> str |
Compute a fingerprint from model architecture for cache compatibility. | #L648-L682 |
MemoryAwarePrefixCache |
class | MemoryAwarePrefixCache(model: Any, config: MemoryCacheConfig \| None = None) |
Prefix cache with memory-based eviction. | #L685-L1463 |
MemoryAwarePrefixCache.__init__ |
method | MemoryAwarePrefixCache.__init__(model: Any, config: MemoryCacheConfig \| None = None) -> None |
Initialize the memory-aware prefix cache. | #L703-L746 |
MemoryAwarePrefixCache.fetch |
method | MemoryAwarePrefixCache.fetch(tokens: list[int]) -> tuple[list[Any] \| None, list[int]] |
Find cached KV state for the given tokens. | #L748-L977 |
MemoryAwarePrefixCache.store |
method | MemoryAwarePrefixCache.store(tokens: list[int], cache: list[Any], evict_prefixes: bool = True) -> bool |
Store KV cache for future reuse. | #L979-L1092 |
MemoryAwarePrefixCache._remove_from_sorted |
method | MemoryAwarePrefixCache._remove_from_sorted(key: tuple[int, ...]) -> None |
Remove a key from the sorted index using bisect for O(log N). | #L1094-L1098 |
MemoryAwarePrefixCache._evict_lru |
method | MemoryAwarePrefixCache._evict_lru() -> None |
Evict the least recently used entry. | #L1100-L1126 |
MemoryAwarePrefixCache.remove |
method | MemoryAwarePrefixCache.remove(tokens: list[int]) -> bool |
Remove a specific cache entry. | #L1128-L1147 |
MemoryAwarePrefixCache.clear |
method | MemoryAwarePrefixCache.clear() -> None |
Clear all cached entries. | #L1149-L1156 |
MemoryAwarePrefixCache.get_stats |
method | MemoryAwarePrefixCache.get_stats() -> dict[str, Any] |
Get cache statistics. | #L1158-L1160 |
MemoryAwarePrefixCache.reset_stats |
method | MemoryAwarePrefixCache.reset_stats() -> None |
Reset statistics while preserving cache contents. | #L1162-L1169 |
MemoryAwarePrefixCache.memory_usage_mb |
method | MemoryAwarePrefixCache.memory_usage_mb() -> float |
Current memory usage in MB. | #L1172-L1174 |
MemoryAwarePrefixCache.memory_limit_mb |
method | MemoryAwarePrefixCache.memory_limit_mb() -> float |
Memory limit in MB. | #L1177-L1179 |
MemoryAwarePrefixCache.try_reserve_memory |
method | MemoryAwarePrefixCache.try_reserve_memory(nbytes: int) -> bool |
Tentatively reserve cache memory for an upcoming promotion. | #L1181-L1188 |
MemoryAwarePrefixCache.release_reserved_memory |
method | MemoryAwarePrefixCache.release_reserved_memory(nbytes: int) -> None |
Release memory previously reserved by try_reserve_memory(). | #L1190-L1194 |
MemoryAwarePrefixCache.__len__ |
method | MemoryAwarePrefixCache.__len__() -> int |
Return number of cached entries. | #L1196-L1198 |
MemoryAwarePrefixCache.__contains__ |
method | MemoryAwarePrefixCache.__contains__(tokens: list[int]) -> bool |
Check if tokens are cached. | #L1200-L1202 |
MemoryAwarePrefixCache.set_ssd_tier |
method | MemoryAwarePrefixCache.set_ssd_tier(ssd_tier) -> None |
Attach an SSD cache tier for eviction spilling. | #L1204-L1214 |
MemoryAwarePrefixCache.check_ssd |
method | MemoryAwarePrefixCache.check_ssd(tokens: list[int]) -> dict \| None |
Check if tokens have an SSD cache hit (without reading data). | #L1216-L1249 |
MemoryAwarePrefixCache.save_to_disk |
method | MemoryAwarePrefixCache.save_to_disk(cache_dir: str) -> bool |
Save all cache entries to disk using mlx_lm's safetensors format. | #L1255-L1346 |
MemoryAwarePrefixCache.load_from_disk |
method | MemoryAwarePrefixCache.load_from_disk(cache_dir: str) -> int |
Load cache entries from disk. | #L1348-L1463 |