mirror of
https://github.com/PaddlePaddle/FastDeploy.git
synced 2026-04-24 01:29:57 +08:00
7707be8384
* [Feature][KVCache] Support cache manager v1 architecture Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Update cache manager and related modules Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: update cache_manager and related modules Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: add node to evictable set in complete_swap_to_device When a node transitions from SWAP_TO_DEVICE to DEVICE via complete_swap_to_device, it was not being added to the _evictable_device set. This caused nodes with ref_count=0 to become "orphaned" - not appearing in any evictable set despite having cache_status=DEVICE. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: update cache manager v1 and related modules - Add new cache_manager.py with cache management functionality - Add radix_tree.py for prefix caching - Update block_pool.py and metadata.py - Update request.py and resource_manager_v1.py for scheduling - Update gpu_model_runner.py for GPU model execution Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(cache): add cache controller v1 implementation - Add CacheController class for cache management - Update config.py with cache related configurations - Refactor gpu_model_runner.py for improved cache handling * feat(cache_manager): update cache manager v1 * fix(cache_manager): 修复 swap_cache H2D/D2H 方向的 block_ids 逻辑并清理 ForwardMeta ## Motivation 修复 swap_cache_optimized.cu 中 H2D 方向时 src/dst block_ids 使用错误的问题, 并清理 ForwardMeta 中已废弃的 cache_controller 字段。 ## Modifications - fix: swap_cache_optimized.cu 中根据 D2H 模板参数正确选取 src/dst block_ids, 修复 H2D 方向 src/dst 倒置 bug(同时修复 SwapCachePerLayerImpl 和 SwapCacheAllLayersBatchImpl) - refactor: cache_manager/v1/__init__.py 将 LayerSwapTimeoutError 导入从 cache_controller 改为 cache_utils(正确来源) - refactor: ForwardMeta 移除废弃的 cache_controller 字段 - refactor: gpu_model_runner.py 移除对应的 cache_controller 赋值语句 - test: 新增 tests/cache_manager/v1/test_swap_cache_ops.py 单元测试 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(cache_manager): refactor cache manager v1 and optimize swap ops ## Motivation 对 cache manager v1 进行重构和优化,精简代码结构,提升可维护性。 ## Modifications - 重构 transfer_manager.py,大幅精简代码逻辑 - 优化 swap_cache_optimized.cu GPU 算子实现 - 调整 cache_manager.py、cache_controller.py 逻辑,修复 free_device_blocks 方法缺失问题 - 更新 block_pool.py、cache_utils.py、metadata.py、radix_tree.py - 精简 gpu_model_runner.py、forward_meta.py、attention.py 中相关调用 - 更新对应单元测试(test_cache_controller、test_swap_cache_ops、test_transfer_manager) - 调整 config.py 中相关配置项 * [KVCache][MTP] 支持 cache_manager_v1 下的 MTP KV Cache 初始化及多模态 hash ## Motivation 在 enable_cache_manager_v1 路径下,MTP(speculative decode)的 KV Cache 需要由 CacheController 统一管理,以复用 swap/transfer 能力,同时修复多模态场景下 block hash 未携带 multimodal extra_keys 的问题。 ## Modifications - `cache_controller.py` - 新增 `initialize_mtp_kv_cache`:通过 CacheController 初始化 MTP KV Cache, 并将其注册到 cache_kvs_map,使 transfer_manager 自动覆盖 MTP 层 - `initialize_host_cache` 中的 num_layers 改为包含 MTP 额外 cache 层数,保证 Host Cache 也为 MTP 分配足够空间 - `_free_gpu_cache` 改名为 `free_gpu_cache`(对外可调用) - `cache_utils.py` - 新增 `get_block_hash_extra_keys`:提取单个 block 内的多模态 hash 信息, 对齐 PrefixCacheManager 的 multimodal extra_keys 逻辑 - `get_request_block_hasher` 中在 hash_block_tokens 时携带 extra_keys, 修复多模态场景 prefix cache 命中率不准的问题 - `spec_decode/mtp.py` - `update_mtp_block_num` 新增 `skip_cache_init` 参数,避免 v1 cache manager 路径下重复初始化 MTP KV Cache - `gpu_model_runner.py` - `initialize_kv_cache(v1)` 路径:在主模型 cache 初始化后,调用 `cache_controller.initialize_mtp_kv_cache` 完成 MTP cache 创建 - `clear_cache` / `wakeup` / `reset` 等路径:respect `enable_cache_manager_v1` 标志,跳过重复的 proposer.initialize_kv_cache 调用 ## Usage or Command ```bash # 启动支持 MTP + cache_manager_v1 的推理服务(示例) bash run.sh ``` * fix(cache_manager): multi-GPU fix, mm hash boundary fix, and remove batch ops 1. Fix CuPy stream/event creation for multi-GPU: wrap all stream operations with cp.cuda.Device(device_id) context to ensure streams/events are bound to the correct device, preventing cross-device errors in multi-GPU setups. 2. Remove cudaSetDevice from SwapCacheAllLayers (handled by cupy context now). 3. Remove swap_cache_all_layers_batch op: simplified the implementation by removing the batch upload variant; all-layer transfers now use the standard swap_cache_all_layers with cupy device context. 4. Fix mm hash boundary comparison in get_block_hash_extra_keys: change strict less-than (<) to less-than-or-equal (<=) so that multimodal items ending exactly at block start are correctly excluded. 5. Extract config fields to KVCacheBase: model_config, cache_config, quant_config, parallel_config are now set in the base class __init__ to avoid duplication in CacheController and CacheManager subclasses. 6. Translate metadata.py docstrings from Chinese to English for broader contributor accessibility. 7. Add test_cache_utils.py: comprehensive unit tests for get_block_hash_extra_keys covering all boundary and overlap scenarios. 8. Expand test suite: test_request.py cache fields tests, test_radix_tree.py backup candidate tests, test_transfer_manager.py and test_cache_manager.py multi-GPU and concurrent operation tests. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [BugFix][KVCache] fix List import and move write_policy normalization to CacheManager ## Motivation 修复两处问题: 1. `fastdeploy/engine/request.py` 中 `List` 未导入导致 pre-commit F821 报错 2. `write_policy` 归一化逻辑(`write_through` → `write_through_selective`)不应放在 `FDConfig`,移至 `CacheManager.__init__` 中,使其只影响 Cache Manager V1 的内部逻辑 ## Modifications - `fastdeploy/engine/request.py`: 在 `typing` 导入中补充 `List`,删除重复的 `CacheSwapMetadata` TYPE_CHECKING 导入,修复 F821/F811 - `fastdeploy/config.py`: 删除 `write_policy` 归一化逻辑 - `fastdeploy/cache_manager/v1/cache_manager.py`: 将归一化逻辑移入 `CacheManager.__init__` Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [BugFix][KVCache] fix pre-commit code style issues ## Motivation 修复 CI pre-commit 代码风格检查失败问题。 ## Modifications - `fastdeploy/engine/common_engine.py`: black 格式化 - `fastdeploy/worker/worker_process.py`: black 格式化 + isort 修复 - `fastdeploy/cache_manager/v1/storage/__init__.py`: isort 修复 - `fastdeploy/worker/gpu_worker.py`: isort 修复 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [Feature][KVCache] update cache_manager_v1 modules ## Motivation 更新 Cache Manager V1 相关模块,完善版权信息、改进模块结构与可维护性。 ## Modifications - `fastdeploy/cache_manager/v1/` 系列模块:补充版权 header,优化代码结构 - `fastdeploy/config.py`:配置项更新 - `fastdeploy/engine/sched/resource_manager_v1.py`:调度相关更新 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [Feature][KVCache] add BatchRequest.from_tasks and refactor worker task parsing ## Motivation 将 worker_process 中重复的 task 解析逻辑收敛到 BatchRequest,减少代码冗余,提升可维护性。 ## Modifications - `fastdeploy/engine/request.py`:新增 `BatchRequest.from_tasks()` 类方法,统一将 task_queue 任务分类为推理请求和控制请求 - `fastdeploy/worker/worker_process.py`:使用 `BatchRequest.from_tasks()` 替代内联解析逻辑,并修复重复的 control_reqs 处理块 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [Feature][KVCache] add NUMA affinity for host cache and skip swap cache tests ## Motivation 优化 Host cache 内存分配的 NUMA 亲和性,减少跨 NUMA 访问延迟; 同时跳过 swap cache ops 测试(当前环境不支持)。 ## Modifications - `fastdeploy/cache_manager/v1/cache_controller.py`: - 新增 `_get_numa_node_for_gpu()` 方法,通过 nvidia-smi 或 sysfs 获取 GPU 对应的 NUMA 节点 - 新增 `_bind_to_closest_numa_node()` 方法,绑定当前线程到 GPU 最近的 NUMA 节点 - 在 `initialize_host_cache()` 中调用 NUMA 绑定,优化 H2D 传输性能 - `tests/cache_manager/v1/test_swap_cache_ops.py`:跳过所有测试类(`TestSwapCacheAllLayersCorrectness`、`TestSwapCacheAllLayersPerformance`、`TestSwapCacheRandomBlockIndices`) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [BugFix][KVCache] fix unittest failures for cache_manager_v1 三个单测因接口变更或 Mock 方式问题导致失败,需修复。 - tests/distributed/chunked_moe.py:`setup_model_runner` 使用 `__new__` 跳过 `__init__`,补加 `enable_cache_manager_v1 = False`,修复 `AttributeError` - tests/engine/test_resource_manager.py:`PrefixCacheManager` 为局部导入,`patch` 路径改为定义位置 `fastdeploy.cache_manager.prefix_cache_manager.PrefixCacheManager` - tests/v1/test_resource_manager_v1.py:`_trigger_preempt` 第四参数已由 `list` 改为 `BatchRequest`,更新测试传参和断言 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [BugFix][KVCache] remove debug logging code ## Modifications - fastdeploy/engine/request.py:删除调试用 logger 及 prompt_hashes 中的 debug 日志 - fastdeploy/worker/worker_process.py:删除 __main__ 中的调试 import 和 print 语句 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [BugFix][KVCache] fix cupy device id caching and pickle for _match_result ## Motivation 修复两个 bug: 1. `transfer_manager.py` 中每次调用 `cp.cuda.runtime.getDevice()` 存在隐患,应在初始化时缓存为实例变量,保证后续操作使用一致的设备 ID。 2. `request.py` 的 `__getstate__` 未跳过 `_match_result`,该字段包含 BlockNode 树的父子循环引用,pickle 时会触发 `RecursionError`;同时补充 `__setstate__` 确保 unpickle 后字段恢复为安全默认值。 ## Modifications - `transfer_manager.py`:初始化时调用 `cp.cuda.runtime.getDevice()` 并缓存到 `self._cupy_device_id`,后续 `with cp.cuda.Device(...)` 和日志均使用该缓存值。 - `request.py`: - `__getstate__` 中将 `_match_result` 加入跳过集合 `_SKIP_KEYS`,避免循环引用导致 pickle 失败。 - 新增 `__setstate__`,unpickle 后将 `_block_hasher` 和 `_match_result` 恢复为 `None`。 ## Usage or Command * fix(test): fix unit test errors for _trigger_preempt and wakeup with MTP - Use BatchRequest instead of list in test_trigger_preempt_records_tasks - Add missing enable_cache_manager_v1 attr in TestSleepWakeupBehavior._make_runner Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [BugFix][KVCache] fix gpu_free_block_list returning wrong block IDs ## Motivation `gpu_free_block_list` 的兼容 property 中误用了 `list(range(N))`, 将 `available_blocks()` 的返回值当作整数传给 `range()`, 导致返回 `[0, 1, ..., N-1]` 的假列表,而非真实的空闲 block ID。 ## Modifications - `cache_manager/v1/cache_manager.py`:将 `list(range(self._device_pool.available_blocks()))` 改为 `list(self._device_pool.available_blocks())` Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [BugFix][KVCache] 修复 gpu_free_block_list 返回 int 导致 TypeError ## Motivation gpu_free_block_list 属性中调用 BlockPool.available_blocks(), 该方法返回 int(空闲块数量),用 list() 包装 int 会触发 TypeError: 'int' object is not iterable。 ## Modifications 将 list(self._device_pool.available_blocks()) 改为 list(self._device_pool._free_blocks),直接返回空闲块索引列表。 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [KVCache][CacheManager] 适配 V1 CacheManager 的 pause/sleep/free_cache 操作 ## Motivation V1 CacheManager 引入了新的 reset_cache() 接口,pause 和 sleep 操作需要适配, 同时 free_cache 需要支持可选的 clear_storage 参数。 ## Modifications - cache_controller.py: free_cache 新增 clear_storage 参数(默认 False), 仅当 clear_storage=True 时才调用 _clear_storage(),避免不必要的 storage 清空 - common_engine.py: pause 和 sleep 操作中,当 ENABLE_V1_KVCACHE_MANAGER 时 使用 cache_manager.reset_cache() 替代旧的 reset() 和 pause_transfer 逻辑 - gpu_model_runner.py: sleep 时仅在非 V1 cache manager 下执行 MTP cache 清除 ## Usage or Command # 启动服务(V1 CacheManager) python -m fastdeploy.entrypoints.openai.api_server \ --enable-v1-kvcache-manager \ ... * [BugFix][KVCache] fix missing enable_cache_manager_v1 in test mocks and remove unused select_blocks_for_backup - Remove unused `select_blocks_for_backup` method from radix_tree.py - Fix `match_prefix` default param `skip_storage=True` and log order in cache_manager.py - Sync test_gpu_model_runner.py with upstream/develop (add TestInsertTasksV1SplitwiseSuffix) - Add `enable_cache_manager_v1=False` to all mock runners to fix AttributeError in CI Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [BugFix][KVCache] simplify _free_blocks in ResourceManagerV1 for non-v1 path Remove redundant prefix_caching branch in else path; always call recycle_gpu_blocks with full block_tables for non-cache-manager-v1 case. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * [KVCache][Optimization][BugFix] fix and optimize block_pool, cache_manager, transfer_manager, request ## Motivation 修复 cache_manager v1 中若干代码质量问题,提升性能并消除潜在的类型不一致 Bug。 ## Modifications 1. **block_pool.py**:`BlockPool.allocate` 将逐个 pop 循环替换为切片 + 批量 set.update,消除 Python 循环开销,O(n) → O(k)(C 层批量操作) 2. **cache_manager.py**:`match_prefix` 在 prefix caching 关闭时提前 return 前写入空 `MatchResult()`,避免调用方解引用 `_match_result=None` 崩溃 3. **transfer_manager.py**:`_build_device_layer_indices` 在 `_cache_kvs_map` 为空时也重置四个层索引列表,防止残留旧 tensor 被 swap 算子使用 4. **request.py**:`BatchRequest.append_swap_metadata` / `append_evict_metadata` 构造 `CacheSwapMetadata` 时将 `src_type`/`dst_type` 从字符串改为 `CacheLevel` 枚举,与字段类型声明一致;补充 `CacheLevel` 导入;`match_result` 属性返回类型标注修正为 `Optional[MatchResult]` 5. **resource_manager_v1.py**:`_allocate_gpu_blocks` 日志从 `INFO` 降级为 `DEBUG`,消除高频调度路径的日志噪音 6. **tests/engine/test_request.py**:同步更新 `src_type`/`dst_type` 断言为 `CacheLevel` 枚举值,补充 `CacheLevel` 导入 ## Usage or Command 单元测试: ```bash source .venv/py310/bin/activate cd baidu/FastDeploy python -m pytest tests/cache_manager/v1/test_cache_manager.py -v python -m pytest tests/cache_manager/v1/test_transfer_manager.py -v python -m pytest tests/engine/test_request.py -v ``` * [BugFix][KVCache] Fix BlockPool.allocate returns all blocks when num_blocks=0 ## Motivation 当 `allocate(num_blocks=0)` 被调用时,Python 负索引陷阱导致严重错误: `-0 == 0`,所以 `self._free_blocks[-0:]` 等价于 `self._free_blocks[0:]`, 会返回并清空整个空闲块列表,而非返回空列表。 ## Modifications 在 `BlockPool.allocate` 中增加对 `num_blocks == 0` 的提前判断,直接返回 `[]`, 避免触发 Python 负索引陷阱。 ## Usage or Command ```bash # 运行相关单元测试验证修复 python -m pytest tests/cache_manager/v1/test_cache_manager.py -vv -s ``` * [KVCache][Test] add unit tests for cache_manager v1 modules ## Motivation 补全 cache_manager/v1 各模块的单测覆盖,确保核心方法有完整的测试保障。 ## Modifications 新增/补充以下测试文件,全部 326 个用例通过: - tests/cache_manager/v1/test_block_pool.py(新建) 覆盖 BlockPool.get_metadata/set_metadata/resize、DeviceBlockPool/HostBlockPool - tests/cache_manager/v1/test_metadata.py(新建) 覆盖 BlockNode、RadixTreeStats、MatchResult、CacheSwapMetadata、AsyncTaskHandler - tests/cache_manager/v1/test_cache_utils.py(补充) 新增 hash_block_tokens、get_request_block_hasher、LayerDoneCounter 时间追踪及内部辅助方法 - tests/cache_manager/v1/test_radix_tree.py(补充) 新增 TestCompleteSwapToDevice 专项测试类(6 个用例) - tests/cache_manager/v1/test_cache_manager.py(补充) 新增 offload_to_host、load_from_host、pending backup 系列、prepare_prefetch_metadata - tests/cache_manager/v1/test_transfer_manager.py(补充) 新增 _swap_single_layer 校验路径、sync_input/output_stream、record_input_stream_event ## Usage or Command ```bash # 运行所有新增单测 source .venv/py310/bin/activate python -m pytest tests/cache_manager/v1/test_block_pool.py \ tests/cache_manager/v1/test_metadata.py \ tests/cache_manager/v1/test_cache_utils.py \ tests/cache_manager/v1/test_radix_tree.py \ tests/cache_manager/v1/test_cache_manager.py \ tests/cache_manager/v1/test_transfer_manager.py -v # 期望结果:326 passed ``` --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Jiang-Jia-Jun <163579578+Jiang-Jia-Jun@users.noreply.github.com>
935 lines
36 KiB
Python
935 lines
36 KiB
Python
"""
|
|
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
|
|
Unit tests for CacheManager class.
|
|
|
|
Tests cover:
|
|
- Block allocation (device/host)
|
|
- Block release (device/host)
|
|
- Resource checking (can_allocate_*)
|
|
- Free block counting (num_free_*_blocks)
|
|
- Reset functionality
|
|
- Request lifecycle management with RadixTree integration
|
|
- Multi-method workflow tests
|
|
"""
|
|
|
|
import unittest
|
|
from dataclasses import dataclass, field
|
|
from typing import List
|
|
|
|
from utils import get_default_test_fd_config
|
|
|
|
|
|
def create_cache_manager(
|
|
total_block_num: int = 100,
|
|
num_cpu_blocks: int = 50,
|
|
block_size: int = 64,
|
|
enable_prefix_caching: bool = True,
|
|
):
|
|
"""Helper to create CacheManager with test config."""
|
|
from fastdeploy.cache_manager.v1.cache_manager import CacheManager
|
|
|
|
config = get_default_test_fd_config()
|
|
config.cache_config.total_block_num = total_block_num
|
|
config.cache_config.num_cpu_blocks = num_cpu_blocks
|
|
config.cache_config.block_size = block_size
|
|
config.cache_config.enable_prefix_caching = enable_prefix_caching
|
|
|
|
return CacheManager(config)
|
|
|
|
|
|
@dataclass
|
|
class MockMatchResult:
|
|
"""Mock MatchResult for testing."""
|
|
|
|
device_nodes: List = field(default_factory=list)
|
|
host_nodes: List = field(default_factory=list)
|
|
storage_nodes: List = field(default_factory=list)
|
|
uncached_block_ids: List = field(default_factory=list)
|
|
|
|
@property
|
|
def matched_device_nums(self) -> int:
|
|
return len(self.device_nodes)
|
|
|
|
@property
|
|
def matched_host_nums(self) -> int:
|
|
return len(self.host_nodes)
|
|
|
|
@property
|
|
def matched_storage_nums(self) -> int:
|
|
return len(self.storage_nodes)
|
|
|
|
@property
|
|
def total_matched_blocks(self) -> int:
|
|
return self.matched_device_nums + self.matched_host_nums + self.matched_storage_nums
|
|
|
|
@property
|
|
def device_block_ids(self) -> List[int]:
|
|
return [node.block_id for node in self.device_nodes]
|
|
|
|
|
|
@dataclass
|
|
class MockRequest:
|
|
"""Mock Request for testing CacheManager."""
|
|
|
|
request_id: str
|
|
prompt_hashes: List[str]
|
|
block_tables: List[int] = field(default_factory=list)
|
|
match_result: MockMatchResult = field(default_factory=MockMatchResult)
|
|
cache_evict_metadata: List = field(default_factory=list)
|
|
cache_swap_metadata: List = field(default_factory=list)
|
|
|
|
|
|
class TestCacheManagerAllocation(unittest.TestCase):
|
|
"""Test CacheManager block allocation functionality."""
|
|
|
|
def test_allocate_device_blocks_with_request(self):
|
|
"""Test device block allocation with mock request."""
|
|
cache_manager = create_cache_manager()
|
|
request = MockRequest(
|
|
request_id="test_req_1",
|
|
prompt_hashes=["h1", "h2", "h3", "h4", "h5"],
|
|
block_tables=[],
|
|
)
|
|
|
|
allocated = cache_manager.allocate_device_blocks(request, 5)
|
|
|
|
self.assertIsNotNone(allocated)
|
|
self.assertEqual(len(allocated), 5)
|
|
self.assertEqual(cache_manager.num_free_device_blocks, 95)
|
|
|
|
def test_allocate_device_blocks_insufficient(self):
|
|
"""Test device block allocation when not enough blocks after eviction."""
|
|
cache_manager = create_cache_manager()
|
|
# Exhaust device blocks
|
|
for _ in range(10):
|
|
cache_manager.allocate_device_blocks(MockRequest(request_id="req", prompt_hashes=[], block_tables=[]), 10)
|
|
|
|
# Next allocation should fail (no evictable blocks and no free blocks)
|
|
request = MockRequest(request_id="test", prompt_hashes=["h1"], block_tables=[])
|
|
result = cache_manager.allocate_device_blocks(request, 10)
|
|
self.assertEqual(result, [])
|
|
|
|
def test_allocate_host_blocks_success(self):
|
|
"""Test successful host block allocation."""
|
|
cache_manager = create_cache_manager()
|
|
allocated = cache_manager.allocate_host_blocks(10)
|
|
|
|
self.assertIsNotNone(allocated)
|
|
self.assertEqual(len(allocated), 10)
|
|
self.assertEqual(cache_manager.num_free_host_blocks, 40)
|
|
|
|
def test_allocate_host_blocks_insufficient(self):
|
|
"""Test host block allocation returns empty when not enough blocks."""
|
|
cache_manager = create_cache_manager(num_cpu_blocks=5)
|
|
allocated = cache_manager.allocate_host_blocks(10)
|
|
|
|
self.assertEqual(allocated, [])
|
|
|
|
|
|
class TestCacheManagerRelease(unittest.TestCase):
|
|
"""Test CacheManager block release functionality."""
|
|
|
|
def test_free_device_blocks(self):
|
|
"""Test freeing device blocks."""
|
|
cache_manager = create_cache_manager()
|
|
request = MockRequest(request_id="req", prompt_hashes=[], block_tables=[])
|
|
allocated = cache_manager.allocate_device_blocks(request, 10)
|
|
initial_free = cache_manager.num_free_device_blocks
|
|
|
|
cache_manager.free_device_blocks(allocated)
|
|
|
|
self.assertEqual(cache_manager.num_free_device_blocks, initial_free + 10)
|
|
|
|
def test_free_host_blocks(self):
|
|
"""Test freeing host blocks."""
|
|
cache_manager = create_cache_manager()
|
|
allocated = cache_manager.allocate_host_blocks(10)
|
|
initial_free = cache_manager.num_free_host_blocks
|
|
|
|
cache_manager.free_host_blocks(allocated)
|
|
|
|
self.assertEqual(cache_manager.num_free_host_blocks, initial_free + 10)
|
|
|
|
def test_free_all_device_blocks(self):
|
|
"""Test freeing all device blocks."""
|
|
cache_manager = create_cache_manager()
|
|
req = MockRequest(request_id="req", prompt_hashes=[], block_tables=[])
|
|
cache_manager.allocate_device_blocks(req, 50)
|
|
|
|
freed = cache_manager.free_all_device_blocks()
|
|
|
|
self.assertEqual(freed, 50)
|
|
self.assertEqual(cache_manager.num_free_device_blocks, 100)
|
|
|
|
def test_free_all_host_blocks(self):
|
|
"""Test freeing all host blocks."""
|
|
cache_manager = create_cache_manager()
|
|
cache_manager.allocate_host_blocks(25)
|
|
|
|
freed = cache_manager.free_all_host_blocks()
|
|
|
|
self.assertEqual(freed, 25)
|
|
self.assertEqual(cache_manager.num_free_host_blocks, 50)
|
|
|
|
|
|
class TestCacheManagerReset(unittest.TestCase):
|
|
"""Test CacheManager reset functionality."""
|
|
|
|
def test_reset_cache(self):
|
|
"""Test cache reset functionality."""
|
|
cache_manager = create_cache_manager()
|
|
req = MockRequest(request_id="req", prompt_hashes=[], block_tables=[])
|
|
cache_manager.allocate_device_blocks(req, 50)
|
|
cache_manager.allocate_host_blocks(25)
|
|
|
|
result = cache_manager.reset_cache()
|
|
|
|
self.assertTrue(result)
|
|
self.assertEqual(cache_manager.num_free_device_blocks, 100)
|
|
self.assertEqual(cache_manager.num_free_host_blocks, 50)
|
|
|
|
|
|
class TestCacheManagerResize(unittest.TestCase):
|
|
"""Test CacheManager resize functionality."""
|
|
|
|
def test_resize_device_pool_expand(self):
|
|
"""Test expanding device pool."""
|
|
cache_manager = create_cache_manager(total_block_num=100)
|
|
|
|
result = cache_manager.resize_device_pool(150)
|
|
|
|
self.assertTrue(result)
|
|
self.assertEqual(cache_manager.num_gpu_blocks, 150)
|
|
self.assertEqual(cache_manager.num_free_device_blocks, 150)
|
|
|
|
def test_resize_device_pool_shrink_with_used_blocks(self):
|
|
"""Test shrinking device pool fails when used blocks exceed new size."""
|
|
cache_manager = create_cache_manager(total_block_num=100)
|
|
req = MockRequest(request_id="req", prompt_hashes=[], block_tables=[])
|
|
cache_manager.allocate_device_blocks(req, 60)
|
|
|
|
result = cache_manager.resize_device_pool(50)
|
|
|
|
self.assertFalse(result)
|
|
self.assertEqual(cache_manager.num_gpu_blocks, 100)
|
|
|
|
def test_resize_device_pool_allocate_after_expand(self):
|
|
"""Test allocating blocks after expanding pool."""
|
|
cache_manager = create_cache_manager(total_block_num=100)
|
|
cache_manager.resize_device_pool(150)
|
|
|
|
req = MockRequest(request_id="req", prompt_hashes=[], block_tables=[])
|
|
allocated = cache_manager.allocate_device_blocks(req, 120)
|
|
|
|
self.assertIsNotNone(allocated)
|
|
self.assertEqual(len(allocated), 120)
|
|
|
|
|
|
class TestCacheManagerWorkflow(unittest.TestCase):
|
|
"""Test CacheManager multi-method workflow scenarios."""
|
|
|
|
def test_request_lifecycle_full(self):
|
|
"""Test complete request lifecycle: match -> allocate -> finish."""
|
|
cache_manager = create_cache_manager()
|
|
|
|
# Step 1: Request comes in, match prefix (no existing cache)
|
|
request1 = MockRequest(
|
|
request_id="req_1",
|
|
prompt_hashes=["hash1", "hash2", "hash3"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(request1)
|
|
|
|
self.assertEqual(request1.match_result.total_matched_blocks, 0)
|
|
|
|
# Step 2: Allocate blocks for the request
|
|
allocated = cache_manager.allocate_device_blocks(request1, 3)
|
|
self.assertIsNotNone(allocated)
|
|
self.assertEqual(len(allocated), 3)
|
|
|
|
# Step 3: Request finishes, cache the blocks
|
|
request1.block_tables = allocated
|
|
cache_manager.request_finish(request1)
|
|
|
|
# Verify blocks are cached
|
|
self.assertEqual(cache_manager.num_free_device_blocks, 97)
|
|
|
|
def test_request_lifecycle_with_prefix_reuse(self):
|
|
"""Test request reusing cached prefix."""
|
|
cache_manager = create_cache_manager()
|
|
|
|
# First request: insert [h1, h2, h3]
|
|
req1 = MockRequest(
|
|
request_id="req_1",
|
|
prompt_hashes=["h1", "h2", "h3"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req1)
|
|
allocated1 = cache_manager.allocate_device_blocks(req1, 3)
|
|
req1.block_tables = allocated1
|
|
cache_manager.request_finish(req1)
|
|
|
|
# Second request: same prefix [h1, h2], then new [h4]
|
|
req2 = MockRequest(
|
|
request_id="req_2",
|
|
prompt_hashes=["h1", "h2", "h4"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req2)
|
|
|
|
# Should match h1, h2 (result stored in _match_result)
|
|
self.assertEqual(req2._match_result.matched_device_nums, 2)
|
|
self.assertEqual(req2._match_result.matched_host_nums, 0)
|
|
|
|
# Allocate only for h4 (1 new block needed)
|
|
allocated2 = cache_manager.allocate_device_blocks(req2, 1)
|
|
self.assertIsNotNone(allocated2)
|
|
|
|
matched_ids = req2._match_result.device_block_ids
|
|
req2.block_tables = matched_ids + allocated2
|
|
cache_manager.request_finish(req2)
|
|
|
|
def test_shared_prefix_multiple_requests(self):
|
|
"""Test multiple requests sharing prefix."""
|
|
cache_manager = create_cache_manager()
|
|
|
|
# Insert base prefix [A, B]
|
|
req1 = MockRequest(
|
|
request_id="req_1",
|
|
prompt_hashes=["A", "B", "C1"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req1)
|
|
allocated1 = cache_manager.allocate_device_blocks(req1, 3)
|
|
req1.block_tables = allocated1
|
|
cache_manager.request_finish(req1)
|
|
|
|
# Check radix tree state
|
|
stats = cache_manager.radix_tree.get_stats()
|
|
self.assertEqual(stats.node_count, 4) # root + A + B + C1
|
|
|
|
# Second request with different suffix
|
|
req2 = MockRequest(
|
|
request_id="req_2",
|
|
prompt_hashes=["A", "B", "C2"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req2)
|
|
self.assertEqual(req2._match_result.matched_device_nums, 2) # A, B
|
|
|
|
allocated2 = cache_manager.allocate_device_blocks(req2, 1)
|
|
req2.block_tables = req2._match_result.device_block_ids + allocated2
|
|
cache_manager.request_finish(req2)
|
|
|
|
stats = cache_manager.radix_tree.get_stats()
|
|
self.assertEqual(stats.node_count, 5) # root + A + B + C1 + C2
|
|
|
|
def test_eviction_workflow(self):
|
|
"""Test eviction when device memory is full."""
|
|
cache_manager = create_cache_manager(num_cpu_blocks=50)
|
|
|
|
# Exhaust device memory
|
|
requests = []
|
|
for i in range(10):
|
|
req = MockRequest(
|
|
request_id=f"req_{i}",
|
|
prompt_hashes=[f"h{i}_{j}" for j in range(10)],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req)
|
|
allocated = cache_manager.allocate_device_blocks(req, 10)
|
|
req.block_tables = allocated
|
|
cache_manager.request_finish(req)
|
|
requests.append(req)
|
|
|
|
self.assertEqual(cache_manager.num_free_device_blocks, 0)
|
|
|
|
# Verify evictable blocks exist
|
|
stats = cache_manager.radix_tree.get_stats()
|
|
self.assertEqual(stats.evictable_device_count, 100)
|
|
|
|
# New request should trigger eviction
|
|
new_req = MockRequest(
|
|
request_id="new_req",
|
|
prompt_hashes=["new1", "new2", "new3"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(new_req)
|
|
allocated = cache_manager.allocate_device_blocks(new_req, 3)
|
|
|
|
self.assertIsNotNone(allocated)
|
|
self.assertEqual(len(allocated), 3)
|
|
|
|
def test_host_cache_eviction_workflow(self):
|
|
"""Test device -> host eviction workflow when memory is full."""
|
|
cache_manager = create_cache_manager(num_cpu_blocks=30)
|
|
|
|
# Exhaust device memory with different hashes (no prefix sharing)
|
|
for i in range(10):
|
|
req = MockRequest(
|
|
request_id=f"req_{i}",
|
|
prompt_hashes=[f"h{i}_{j}" for j in range(10)],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req)
|
|
allocated = cache_manager.allocate_device_blocks(req, 10)
|
|
req.block_tables = allocated
|
|
cache_manager.request_finish(req)
|
|
|
|
# Device should be full
|
|
self.assertEqual(cache_manager.num_free_device_blocks, 0)
|
|
|
|
# New request should still work (eviction should occur)
|
|
new_req = MockRequest(
|
|
request_id="new_req",
|
|
prompt_hashes=["new1", "new2", "new3"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(new_req)
|
|
allocated = cache_manager.allocate_device_blocks(new_req, 3)
|
|
|
|
self.assertIsNotNone(allocated)
|
|
self.assertEqual(len(allocated), 3)
|
|
|
|
|
|
class TestCacheManagerRadixTreeIntegration(unittest.TestCase):
|
|
"""Test CacheManager RadixTree integration."""
|
|
|
|
def test_match_prefix_updates_ref_count(self):
|
|
"""Test that match_prefix increments ref count."""
|
|
cache_manager = create_cache_manager()
|
|
|
|
# Insert some blocks
|
|
req1 = MockRequest(
|
|
request_id="req_1",
|
|
prompt_hashes=["h1", "h2"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req1)
|
|
allocated1 = cache_manager.allocate_device_blocks(req1, 2)
|
|
req1.block_tables = allocated1
|
|
cache_manager.request_finish(req1)
|
|
|
|
# Check initial evictable count (should be 2 after finish)
|
|
stats1 = cache_manager.radix_tree.get_stats()
|
|
self.assertEqual(stats1.evictable_device_count, 2)
|
|
|
|
# Match same prefix - should increment ref
|
|
req2 = MockRequest(
|
|
request_id="req_2",
|
|
prompt_hashes=["h1", "h2"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req2)
|
|
|
|
# Ref count should be incremented, nodes not evictable
|
|
stats2 = cache_manager.radix_tree.get_stats()
|
|
self.assertEqual(stats2.evictable_device_count, 0)
|
|
|
|
def test_insert_and_find_prefix(self):
|
|
"""Test inserting blocks and finding prefix."""
|
|
cache_manager = create_cache_manager()
|
|
|
|
# Insert blocks
|
|
req1 = MockRequest(
|
|
request_id="req_1",
|
|
prompt_hashes=["hash_a", "hash_b", "hash_c"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req1)
|
|
allocated = cache_manager.allocate_device_blocks(req1, 3)
|
|
req1.block_tables = allocated
|
|
cache_manager.request_finish(req1)
|
|
|
|
# Find prefix
|
|
req2 = MockRequest(
|
|
request_id="req_2",
|
|
prompt_hashes=["hash_a", "hash_b"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req2)
|
|
|
|
self.assertEqual(req2._match_result.matched_device_nums, 2)
|
|
# Block IDs depend on allocation order; verify count and that they are valid ints
|
|
block_ids = req2._match_result.device_block_ids
|
|
self.assertEqual(len(block_ids), 2)
|
|
self.assertTrue(all(isinstance(bid, int) for bid in block_ids))
|
|
|
|
|
|
class TestCacheManagerWithDisabledPrefixCaching(unittest.TestCase):
|
|
"""Test CacheManager with prefix caching disabled."""
|
|
|
|
def test_radix_tree_none_when_disabled(self):
|
|
"""Test radix_tree is None when prefix caching disabled."""
|
|
cache_manager = create_cache_manager(enable_prefix_caching=False)
|
|
self.assertIsNone(cache_manager.radix_tree)
|
|
|
|
def test_allocation_works_without_prefix_caching(self):
|
|
"""Test block allocation still works without prefix caching."""
|
|
cache_manager = create_cache_manager(enable_prefix_caching=False)
|
|
req = MockRequest(request_id="req", prompt_hashes=[], block_tables=[])
|
|
allocated = cache_manager.allocate_device_blocks(req, 10)
|
|
|
|
self.assertIsNotNone(allocated)
|
|
self.assertEqual(len(allocated), 10)
|
|
|
|
|
|
class TestCacheManagerWithNoHostCache(unittest.TestCase):
|
|
"""Test CacheManager with no host cache."""
|
|
|
|
def test_host_cache_disabled(self):
|
|
"""Test host cache is disabled."""
|
|
cache_manager = create_cache_manager(num_cpu_blocks=0)
|
|
self.assertFalse(cache_manager.enable_host_cache)
|
|
|
|
def test_no_free_host_blocks(self):
|
|
"""Test no free host blocks when disabled."""
|
|
cache_manager = create_cache_manager(num_cpu_blocks=0)
|
|
self.assertEqual(cache_manager.num_free_host_blocks, 0)
|
|
|
|
|
|
class TestCacheManagerProperties(unittest.TestCase):
|
|
"""Test CacheManager properties."""
|
|
|
|
def test_device_pool_property(self):
|
|
"""Test device_pool property returns correct pool."""
|
|
from fastdeploy.cache_manager.v1.block_pool import DeviceBlockPool
|
|
|
|
cache_manager = create_cache_manager()
|
|
self.assertIsInstance(cache_manager.device_pool, DeviceBlockPool)
|
|
|
|
def test_host_pool_property(self):
|
|
"""Test host_pool property returns correct pool."""
|
|
from fastdeploy.cache_manager.v1.block_pool import HostBlockPool
|
|
|
|
cache_manager = create_cache_manager()
|
|
self.assertIsInstance(cache_manager.host_pool, HostBlockPool)
|
|
|
|
def test_radix_tree_property(self):
|
|
"""Test radix_tree property returns correct tree."""
|
|
from fastdeploy.cache_manager.v1.radix_tree import RadixTree
|
|
|
|
cache_manager = create_cache_manager()
|
|
self.assertIsInstance(cache_manager.radix_tree, RadixTree)
|
|
|
|
|
|
class TestCacheManagerStats(unittest.TestCase):
|
|
"""Test CacheManager statistics methods."""
|
|
|
|
def test_get_stats(self):
|
|
"""Test get_stats returns correct structure."""
|
|
cache_manager = create_cache_manager()
|
|
stats = cache_manager.get_stats()
|
|
|
|
self.assertIn("initialized", stats)
|
|
self.assertIn("num_gpu_blocks", stats)
|
|
self.assertIn("num_cpu_blocks", stats)
|
|
self.assertIn("block_size", stats)
|
|
self.assertIn("device_pool", stats)
|
|
self.assertIn("host_pool", stats)
|
|
self.assertIn("num_free_device_blocks", stats)
|
|
self.assertIn("num_free_host_blocks", stats)
|
|
self.assertIn("radix_tree", stats)
|
|
|
|
self.assertTrue(stats["initialized"])
|
|
self.assertEqual(stats["num_gpu_blocks"], 100)
|
|
self.assertEqual(stats["num_cpu_blocks"], 50)
|
|
|
|
def test_get_memory_usage(self):
|
|
"""Test get_memory_usage returns correct structure."""
|
|
cache_manager = create_cache_manager()
|
|
usage = cache_manager.get_memory_usage()
|
|
|
|
self.assertIn("device", usage)
|
|
self.assertIn("host", usage)
|
|
self.assertIn("total_blocks", usage["device"])
|
|
self.assertIn("used_blocks", usage["device"])
|
|
self.assertIn("free_blocks", usage["device"])
|
|
self.assertIn("usage_percent", usage["device"])
|
|
|
|
|
|
class TestCacheManagerEdgeCases(unittest.TestCase):
|
|
"""Test CacheManager edge cases."""
|
|
|
|
def test_empty_prompt_hashes(self):
|
|
"""Test request with empty prompt hashes."""
|
|
cache_manager = create_cache_manager()
|
|
req = MockRequest(request_id="req", prompt_hashes=[], block_tables=[])
|
|
|
|
cache_manager.match_prefix(req)
|
|
self.assertEqual(req.match_result.total_matched_blocks, 0)
|
|
|
|
allocated = cache_manager.allocate_device_blocks(req, 0)
|
|
self.assertEqual(allocated, [])
|
|
|
|
def test_allocation_with_matched_host_blocks(self):
|
|
"""Test allocation when host cache has matched blocks."""
|
|
cache_manager = create_cache_manager(num_cpu_blocks=50)
|
|
|
|
# Insert blocks and evict some to host
|
|
req1 = MockRequest(
|
|
request_id="req_1",
|
|
prompt_hashes=["h1", "h2", "h3"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req1)
|
|
allocated1 = cache_manager.allocate_device_blocks(req1, 3)
|
|
req1.block_tables = allocated1
|
|
cache_manager.request_finish(req1)
|
|
|
|
# Exhaust device, evict to host
|
|
for i in range(10):
|
|
req = MockRequest(
|
|
request_id=f"req_{i}",
|
|
prompt_hashes=[f"other_{i}_{j}" for j in range(10)],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req)
|
|
allocated = cache_manager.allocate_device_blocks(req, 10)
|
|
req.block_tables = allocated
|
|
cache_manager.request_finish(req)
|
|
|
|
# Now request h1, h2 - should find them in host cache
|
|
req2 = MockRequest(
|
|
request_id="req_2",
|
|
prompt_hashes=["h1", "h2"],
|
|
block_tables=[],
|
|
)
|
|
cache_manager.match_prefix(req2)
|
|
|
|
# After device is full, h1 and h2 may be evicted to host (write_through policy)
|
|
# Total matched should be non-negative regardless of eviction policy
|
|
total_matched = req2._match_result.total_matched_blocks
|
|
self.assertGreaterEqual(total_matched, 0)
|
|
# If found in host, matched_host_nums > 0
|
|
if req2._match_result.matched_host_nums > 0:
|
|
self.assertGreater(req2._match_result.matched_host_nums, 0)
|
|
|
|
|
|
class TestCacheManagerCanAllocate(unittest.TestCase):
|
|
"""Test CacheManager can_allocate_* methods."""
|
|
|
|
def test_can_allocate_device_blocks_enough(self):
|
|
"""Test can_allocate_device_blocks returns True when enough free blocks."""
|
|
cache_manager = create_cache_manager(total_block_num=100)
|
|
self.assertTrue(cache_manager.can_allocate_device_blocks(50))
|
|
|
|
def test_can_allocate_device_blocks_exact(self):
|
|
"""Test can_allocate_device_blocks returns True for exact count."""
|
|
cache_manager = create_cache_manager(total_block_num=100)
|
|
self.assertTrue(cache_manager.can_allocate_device_blocks(100))
|
|
|
|
def test_can_allocate_device_blocks_too_many(self):
|
|
"""Test can_allocate_device_blocks returns False when not enough blocks."""
|
|
cache_manager = create_cache_manager(total_block_num=100, enable_prefix_caching=False)
|
|
self.assertFalse(cache_manager.can_allocate_device_blocks(101))
|
|
|
|
def test_can_allocate_host_blocks_enough(self):
|
|
"""Test can_allocate_host_blocks returns True when enough free blocks."""
|
|
cache_manager = create_cache_manager(num_cpu_blocks=50)
|
|
self.assertTrue(cache_manager.can_allocate_host_blocks(30))
|
|
|
|
def test_can_allocate_host_blocks_too_many(self):
|
|
"""Test can_allocate_host_blocks returns False when not enough blocks."""
|
|
cache_manager = create_cache_manager(num_cpu_blocks=10, enable_prefix_caching=False)
|
|
self.assertFalse(cache_manager.can_allocate_host_blocks(20))
|
|
|
|
def test_can_allocate_gpu_blocks_alias(self):
|
|
"""Test can_allocate_gpu_blocks is alias for can_allocate_device_blocks."""
|
|
cache_manager = create_cache_manager(total_block_num=100)
|
|
self.assertEqual(
|
|
cache_manager.can_allocate_device_blocks(50),
|
|
cache_manager.can_allocate_gpu_blocks(50),
|
|
)
|
|
|
|
|
|
class TestCacheManagerLegacyMethods(unittest.TestCase):
|
|
"""Test CacheManager legacy compatibility methods."""
|
|
|
|
def test_allocate_gpu_blocks_alias(self):
|
|
"""Test allocate_gpu_blocks delegates to allocate_device_blocks."""
|
|
cache_manager = create_cache_manager()
|
|
req = MockRequest(request_id="req", prompt_hashes=[], block_tables=[])
|
|
allocated = cache_manager.allocate_gpu_blocks(req, 5)
|
|
|
|
self.assertIsNotNone(allocated)
|
|
self.assertEqual(len(allocated), 5)
|
|
|
|
def test_gpu_free_block_list_property(self):
|
|
"""Test gpu_free_block_list returns a list."""
|
|
cache_manager = create_cache_manager(total_block_num=100)
|
|
free_list = cache_manager.gpu_free_block_list
|
|
self.assertIsInstance(free_list, list)
|
|
|
|
def test_available_gpu_resource_full(self):
|
|
"""Test available_gpu_resource is 1.0 when no blocks used."""
|
|
cache_manager = create_cache_manager(total_block_num=100)
|
|
self.assertAlmostEqual(cache_manager.available_gpu_resource, 1.0)
|
|
|
|
def test_available_gpu_resource_after_allocation(self):
|
|
"""Test available_gpu_resource decreases after allocation."""
|
|
cache_manager = create_cache_manager(total_block_num=100, enable_prefix_caching=False)
|
|
req = MockRequest(request_id="req", prompt_hashes=[], block_tables=[])
|
|
cache_manager.allocate_device_blocks(req, 50)
|
|
self.assertAlmostEqual(cache_manager.available_gpu_resource, 0.5)
|
|
|
|
def test_update_cache_config(self):
|
|
"""Test update_cache_config resizes device pool when total_block_num changes."""
|
|
cache_manager = create_cache_manager(total_block_num=100)
|
|
|
|
new_cfg = cache_manager.cache_config
|
|
new_cfg.total_block_num = 150
|
|
cache_manager.update_cache_config(new_cfg)
|
|
|
|
self.assertEqual(cache_manager.num_gpu_blocks, 150)
|
|
|
|
|
|
class TestCacheManagerStorageScheduler(unittest.TestCase):
|
|
"""Test CacheManager storage_scheduler property."""
|
|
|
|
def test_storage_scheduler_none_by_default(self):
|
|
"""Test storage_scheduler is None when not configured."""
|
|
cache_manager = create_cache_manager()
|
|
# Default config has no storage backend, so scheduler should be None
|
|
# (behavior depends on create_storage_scheduler implementation)
|
|
# Just verify it's accessible without error
|
|
_ = cache_manager.storage_scheduler
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# offload_to_host
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestCacheManagerOffloadToHost(unittest.TestCase):
|
|
"""Tests for CacheManager.offload_to_host."""
|
|
|
|
def test_offload_frees_device_blocks(self):
|
|
"""After offload, device blocks should be released."""
|
|
cm = create_cache_manager(total_block_num=20, num_cpu_blocks=20)
|
|
device_blocks = cm._device_pool.allocate(4)
|
|
self.assertIsNotNone(device_blocks)
|
|
free_before = cm.num_free_device_blocks
|
|
|
|
success = cm.offload_to_host(device_blocks)
|
|
|
|
self.assertTrue(success)
|
|
self.assertEqual(cm.num_free_device_blocks, free_before + 4)
|
|
|
|
def test_offload_allocates_host_blocks(self):
|
|
"""After offload, host blocks should be consumed."""
|
|
cm = create_cache_manager(total_block_num=20, num_cpu_blocks=20)
|
|
device_blocks = cm._device_pool.allocate(3)
|
|
free_host_before = cm.num_free_host_blocks
|
|
|
|
cm.offload_to_host(device_blocks)
|
|
|
|
self.assertEqual(cm.num_free_host_blocks, free_host_before - 3)
|
|
|
|
def test_offload_fails_when_no_host_blocks(self):
|
|
"""Offload should return False when host pool is exhausted."""
|
|
cm = create_cache_manager(total_block_num=20, num_cpu_blocks=0)
|
|
device_blocks = cm._device_pool.allocate(2)
|
|
|
|
success = cm.offload_to_host(device_blocks)
|
|
self.assertFalse(success)
|
|
|
|
def test_offload_copies_device_metadata_to_host(self):
|
|
"""Metadata on device blocks should be copied to host blocks."""
|
|
from fastdeploy.cache_manager.v1.metadata import CacheBlockMetadata
|
|
|
|
cm = create_cache_manager(total_block_num=20, num_cpu_blocks=20)
|
|
device_blocks = cm._device_pool.allocate(1)
|
|
block_id = device_blocks[0]
|
|
meta = CacheBlockMetadata(block_id=block_id, device_id=0, block_size=64, ref_count=5)
|
|
cm._device_pool.set_metadata(block_id, meta)
|
|
|
|
cm.offload_to_host(device_blocks)
|
|
|
|
# Find the newly used host block (last used)
|
|
used_host = list(cm._host_pool._used_blocks)
|
|
self.assertEqual(len(used_host), 1)
|
|
host_meta = cm._host_pool.get_metadata(used_host[0])
|
|
self.assertIsNotNone(host_meta)
|
|
self.assertEqual(host_meta.ref_count, 5)
|
|
|
|
def test_offload_empty_list_returns_true(self):
|
|
"""Offloading empty list succeeds."""
|
|
cm = create_cache_manager()
|
|
success = cm.offload_to_host([])
|
|
self.assertTrue(success)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# load_from_host
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestCacheManagerLoadFromHost(unittest.TestCase):
|
|
"""Tests for CacheManager.load_from_host."""
|
|
|
|
def test_load_frees_host_blocks(self):
|
|
"""After loading, host blocks should be released."""
|
|
cm = create_cache_manager(total_block_num=20, num_cpu_blocks=20)
|
|
host_blocks = cm._host_pool.allocate(4)
|
|
free_before = cm.num_free_host_blocks
|
|
|
|
success = cm.load_from_host(host_blocks)
|
|
|
|
self.assertTrue(success)
|
|
self.assertEqual(cm.num_free_host_blocks, free_before + 4)
|
|
|
|
def test_load_allocates_device_blocks(self):
|
|
"""After loading, device blocks should be consumed."""
|
|
cm = create_cache_manager(total_block_num=20, num_cpu_blocks=20)
|
|
host_blocks = cm._host_pool.allocate(3)
|
|
free_device_before = cm.num_free_device_blocks
|
|
|
|
cm.load_from_host(host_blocks)
|
|
|
|
self.assertEqual(cm.num_free_device_blocks, free_device_before - 3)
|
|
|
|
def test_load_fails_when_no_device_blocks(self):
|
|
"""Load should return False when device pool is exhausted."""
|
|
cm = create_cache_manager(total_block_num=2, num_cpu_blocks=20)
|
|
# Fill up device
|
|
cm._device_pool.allocate(2)
|
|
host_blocks = cm._host_pool.allocate(2)
|
|
|
|
success = cm.load_from_host(host_blocks)
|
|
self.assertFalse(success)
|
|
|
|
def test_load_empty_list_returns_true(self):
|
|
"""Loading empty list succeeds."""
|
|
cm = create_cache_manager()
|
|
success = cm.load_from_host([])
|
|
self.assertTrue(success)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# get_pending_backup_count / check_and_add_pending_backup /
|
|
# issue_pending_backup_to_batch_request
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestCacheManagerPendingBackup(unittest.TestCase):
|
|
"""Tests for write_through_selective backup methods."""
|
|
|
|
def _create_write_through_cm(self, threshold: int = 1):
|
|
from fastdeploy.cache_manager.v1.cache_manager import CacheManager
|
|
|
|
config = get_default_test_fd_config()
|
|
config.cache_config.total_block_num = 50
|
|
config.cache_config.num_cpu_blocks = 50
|
|
config.cache_config.block_size = 64
|
|
config.cache_config.enable_prefix_caching = True
|
|
config.cache_config.write_policy = "write_through_selective"
|
|
config.cache_config.write_through_threshold = threshold
|
|
return CacheManager(config)
|
|
|
|
def test_get_pending_backup_count_initially_zero(self):
|
|
cm = self._create_write_through_cm()
|
|
self.assertEqual(cm.get_pending_backup_count(), 0)
|
|
|
|
def test_issue_pending_backup_returns_none_when_empty(self):
|
|
cm = self._create_write_through_cm()
|
|
result = cm.issue_pending_backup_to_batch_request()
|
|
self.assertIsNone(result)
|
|
|
|
def test_check_and_add_pending_backup_does_nothing_without_prefix_caching(self):
|
|
"""When prefix caching is off, check_and_add_pending_backup is a no-op."""
|
|
cm = create_cache_manager(enable_prefix_caching=False)
|
|
cm.check_and_add_pending_backup() # should not raise
|
|
self.assertEqual(cm.get_pending_backup_count(), 0)
|
|
|
|
def test_check_and_add_pending_backup_does_nothing_without_host_cache(self):
|
|
"""Without host cache, check_and_add_pending_backup is a no-op."""
|
|
cm = self._create_write_through_cm()
|
|
cm.enable_host_cache = False
|
|
cm.check_and_add_pending_backup()
|
|
self.assertEqual(cm.get_pending_backup_count(), 0)
|
|
|
|
def test_check_and_add_pending_backup_adds_candidates(self):
|
|
"""After inserting nodes that meet threshold, backup should be queued."""
|
|
cm = self._create_write_through_cm(threshold=1)
|
|
rt = cm._radix_tree
|
|
|
|
# Insert nodes and decrement so they become evictable
|
|
nodes, _ = rt.insert([("h1", 0), ("h2", 1), ("h3", 2)])
|
|
# Simulate hit_count meeting threshold (threshold=1, default hit_count=1)
|
|
cm._device_pool.allocate(3) # Ensure enough device blocks consumed
|
|
rt.decrement_ref_nodes(nodes)
|
|
|
|
cm.check_and_add_pending_backup()
|
|
# Should have added at least something if there are candidates
|
|
# (may be 0 if no candidates qualify; just ensure no exception)
|
|
count = cm.get_pending_backup_count()
|
|
self.assertGreaterEqual(count, 0)
|
|
|
|
def test_issue_pending_backup_clears_queue(self):
|
|
"""After issuing, the pending backup queue should be empty."""
|
|
cm = self._create_write_through_cm(threshold=1)
|
|
rt = cm._radix_tree
|
|
|
|
nodes, _ = rt.insert([("h1", 0)])
|
|
cm._device_pool.allocate(1)
|
|
rt.decrement_ref_nodes(nodes)
|
|
cm.check_and_add_pending_backup()
|
|
|
|
cm.issue_pending_backup_to_batch_request()
|
|
self.assertEqual(cm.get_pending_backup_count(), 0)
|
|
|
|
def test_issue_returns_none_when_host_cache_disabled(self):
|
|
"""If host cache is not enabled, issue returns None and clears queue."""
|
|
cm = self._create_write_through_cm()
|
|
# Manually add a fake pending entry
|
|
cm._pending_backup.append(([], []))
|
|
cm.enable_host_cache = False
|
|
result = cm.issue_pending_backup_to_batch_request()
|
|
self.assertIsNone(result)
|
|
self.assertEqual(cm.get_pending_backup_count(), 0)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# prepare_prefetch_metadata
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestCacheManagerPreparePrefetchMetadata(unittest.TestCase):
|
|
"""Tests for CacheManager.prepare_prefetch_metadata."""
|
|
|
|
def test_empty_hashes_returns_none(self):
|
|
cm = create_cache_manager()
|
|
result = cm.prepare_prefetch_metadata([])
|
|
self.assertIsNone(result)
|
|
|
|
def test_returns_nodes_when_host_blocks_available(self):
|
|
cm = create_cache_manager(num_cpu_blocks=20)
|
|
hashes = ["hash_a", "hash_b"]
|
|
result = cm.prepare_prefetch_metadata(hashes)
|
|
# Should return a list (possibly empty if no host blocks or tree reuse)
|
|
self.assertIsInstance(result, list)
|
|
|
|
def test_returns_empty_when_insufficient_host_blocks(self):
|
|
cm = create_cache_manager(total_block_num=20, num_cpu_blocks=0)
|
|
result = cm.prepare_prefetch_metadata(["h1", "h2"])
|
|
# With no host blocks, should return empty or None
|
|
self.assertFalse(result) # None or []
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|