diff --git a/tests/core/distributed_runtime/worker_service_test.cpp b/tests/core/distributed_runtime/worker_service_test.cpp index cb25f1fda5..d3870f4af4 100644 --- a/tests/core/distributed_runtime/worker_service_test.cpp +++ b/tests/core/distributed_runtime/worker_service_test.cpp @@ -51,7 +51,7 @@ class WorkerServiceOutputTest : public ::testing::Test { void collect(const ForwardOutput& source, ForwardOutput& destination) { runtime::Options options; options.backend("llm"); - WorkerService service(options, torch::Device("npu:0"), nullptr); + WorkerService service(options, torch::Device(/*device_string=*/"npu:0")); collect(service, source, destination); } }; @@ -62,7 +62,7 @@ TEST_F(WorkerServiceOutputTest, WaitsForPendingCpuTokenSnapshot) { using namespace std::chrono_literals; runtime::Options options; options.backend("llm").enable_schedule_overlap(true); - WorkerService service(options, torch::Device("npu:0"), nullptr); + WorkerService service(options, torch::Device(/*device_string=*/"npu:0")); Stream producer(torch::Device("npu:0")); ForwardOutput source; source.next_tokens_host = torch::full({1}, -1, torch::kInt64); @@ -402,12 +402,11 @@ void expect_rpc_rejection(runtime::Options options, Response response; CountingClosure done; auto completed = done.get_future(); - // The injected constructor marks the service initialized. A null Worker - // ensures rejected requests cannot accidentally enter model execution. - auto service = initialized ? std::make_unique( - options, torch::Device("npu:0"), nullptr) - : std::make_unique( - options, torch::Device("npu:0")); + auto service = std::make_unique( + options, torch::Device(/*device_string=*/"npu:0")); + if (initialized) { + service->set_worker(/*worker=*/nullptr); + } (service.get()->*rpc)(&controller, &request, &response, &done); EXPECT_EQ(completed.wait_for(std::chrono::seconds(5)), std::future_status::ready); diff --git a/tests/core/framework/block/block_manager_test.cpp b/tests/core/framework/block/block_manager_test.cpp index ac5b902c35..0bcc360694 100644 --- a/tests/core/framework/block/block_manager_test.cpp +++ b/tests/core/framework/block/block_manager_test.cpp @@ -862,15 +862,20 @@ TEST(BlockManagerTest, Basic) { Block& block = blocks[0]; { const Block alias = block; - EXPECT_EQ(alias, block); + EXPECT_EQ(alias.id(), block.id()); EXPECT_EQ(block.ref_count(), 2); } blocks.back() = block; - EXPECT_EQ(blocks.back(), block); + EXPECT_EQ(blocks.back().id(), block.id()); EXPECT_EQ(block.ref_count(), 2); blocks.pop_back(); EXPECT_EQ(block.ref_count(), 1); + { + const Block pinned(block, /*pin_block=*/true); + EXPECT_EQ(block.ref_count(), 2); + EXPECT_EQ(block.unpinned_ref_count(), 1); + } const int32_t id = block.id(); const Block moved = std::move(block); EXPECT_EQ(moved.id(), id); diff --git a/tests/core/framework/block/cache_tier_manager_test.cpp b/tests/core/framework/block/cache_tier_manager_test.cpp index 68caefbeb1..7d4594a6df 100644 --- a/tests/core/framework/block/cache_tier_manager_test.cpp +++ b/tests/core/framework/block/cache_tier_manager_test.cpp @@ -173,31 +173,16 @@ class HostOffloadPageAllocator final : public VmmKVPageAllocator { } } - void trim_kv_cache(const std::string& /*model_id*/, - int32_t /*dp_rank*/) override {} - size_t get_num_available_virt_pages(const std::string& /*model_id*/, int32_t /*dp_rank*/) const override { return max_pages_ - mapped_pages_.size(); } - size_t get_num_inuse_virt_pages(const std::string& /*model_id*/, - int32_t /*dp_rank*/) const override { - return mapped_pages_.size(); - } - size_t get_num_reserved_virt_pages(const std::string& /*model_id*/, - int32_t /*dp_rank*/) const override { - return mapped_pages_.empty() ? 1 : 0; - } int64_t get_virt_page_id(int64_t block_id, size_t block_memory_size) const override { return block_id * static_cast(block_memory_size) / static_cast(page_size()); } size_t page_size() const override { return 64; } - size_t phy_pages_per_virt_page( - const std::string& /*model_id*/) const override { - return 4; - } size_t mapped_pages() const { return mapped_pages_.size(); } size_t mapping_count() const { return mapping_count_; } @@ -2022,6 +2007,9 @@ TEST_F(CacheTierManagerTest, Dsv4ChunkGrowthOffloadsAllCompletedCacheGroups) { Sequence sequence = make_test_sequence(/*index=*/0, tokens); ASSERT_TRUE(pool.allocate(&sequence, kFirstChunkTokens)); + const Block execution_block( + sequence.kv_state().blocks(/*type=*/BlockType::C4).front(), + /*pin_block=*/true); EXPECT_EQ(CacheTierTestPeer::pending_offload_pair_count(pool), 0u); sequence.kv_state().set_kv_cache_tokens_num(kFirstChunkTokens); diff --git a/tests/core/framework/block/composite_block_manager_test.cpp b/tests/core/framework/block/composite_block_manager_test.cpp index 79b581c8e4..c580304a58 100644 --- a/tests/core/framework/block/composite_block_manager_test.cpp +++ b/tests/core/framework/block/composite_block_manager_test.cpp @@ -224,9 +224,6 @@ class TestVmmKVPageAllocator final : public VmmKVPageAllocator { } } - void trim_kv_cache(const std::string& /*model_id*/, - int32_t /*dp_rank*/) override {} - size_t get_num_available_virt_pages(const std::string& /*model_id*/, int32_t dp_rank) const override { if (before_available) { @@ -237,25 +234,15 @@ class TestVmmKVPageAllocator final : public VmmKVPageAllocator { return page_limit > inuse_pages ? page_limit - inuse_pages : 0; } - size_t get_num_inuse_virt_pages(const std::string& /*model_id*/, - int32_t dp_rank) const override { + size_t num_inuse_virt_pages(int32_t dp_rank) const { return allocated_pages_.at(dp_rank).size(); } - size_t get_num_reserved_virt_pages(const std::string& /*model_id*/, - int32_t dp_rank) const override { - return allocated_pages_.at(dp_rank).empty() ? 1 : 0; - } int64_t get_virt_page_id(int64_t block_id, size_t block_memory_size) const override { return block_id * static_cast(block_memory_size) / static_cast(page_size()); } size_t page_size() const override { return 64; } - size_t phy_pages_per_virt_page( - const std::string& /*model_id*/) const override { - return 4; - } - int32_t prealloc_starts = 0; std::vector> allocation_requests; std::vector> released_pages; @@ -1772,8 +1759,7 @@ TEST(CompositeBlockManagerTest, VirtualHistoryPlanningDoesNotMapPages) { leaf, sequence, sequence.kv_state(), /*num_tokens=*/20) .has_value()); EXPECT_FALSE(sequence.kv_state().has_any_blocks()); - EXPECT_EQ( - allocator.get_num_inuse_virt_pages(kHistoryPlanModel, /*dp_rank=*/0), 0u); + EXPECT_EQ(allocator.num_inuse_virt_pages(/*dp_rank=*/0), 0u); const size_t allocation_attempts = allocator.allocation_requests.size(); const HistoryGrowthPlan fits = @@ -1809,16 +1795,12 @@ TEST(CompositeBlockManagerTest, PagedShortageReturnsPagesToInjectedAllocator) { // One page holds four blocks. A five-block request must release its partial // allocation, making the same page capacity available to the next request. EXPECT_TRUE(leaf.allocate(/*num_blocks=*/5).empty()); - EXPECT_EQ( - allocator.get_num_inuse_virt_pages(kInjectedCacheModel, /*dp_rank=*/0), - 0u); + EXPECT_EQ(allocator.num_inuse_virt_pages(/*dp_rank=*/0), 0u); ASSERT_EQ(allocator.released_pages.size(), 1u); std::vector blocks = leaf.allocate(/*num_blocks=*/1); ASSERT_EQ(blocks.size(), 1u); blocks.clear(); - EXPECT_EQ( - allocator.get_num_inuse_virt_pages(kInjectedCacheModel, /*dp_rank=*/0), - 0u); + EXPECT_EQ(allocator.num_inuse_virt_pages(/*dp_rank=*/0), 0u); EXPECT_EQ(allocator.released_pages.size(), 2u); } @@ -1840,9 +1822,7 @@ TEST(CompositeBlockManagerTest, VirtualPrefixRetainsPagesAndReusesBlockIds) { EXPECT_EQ(leaf.num_blocks_in_prefix_cache(), 2u); EXPECT_EQ(leaf.num_used_blocks(), 0u); EXPECT_EQ(leaf.num_free_blocks(), 4u); - EXPECT_EQ( - allocator.get_num_inuse_virt_pages(kPrefixCacheModel, /*dp_rank=*/0), - 1u); + EXPECT_EQ(allocator.num_inuse_virt_pages(/*dp_rank=*/0), 1u); EXPECT_TRUE(allocator.released_pages.empty()); std::vector matched = leaf.allocate_shared(tokens); @@ -1878,8 +1858,7 @@ TEST(CompositeBlockManagerTest, VirtualPrefixEvictsIdleBlocksUnderPressure) { ASSERT_EQ(replacement.size(), 2u); EXPECT_EQ(leaf.num_blocks_in_prefix_cache(), 2u); EXPECT_EQ(leaf.num_used_blocks(), 2u); - EXPECT_EQ( - allocator.get_num_inuse_virt_pages(kPrefixCacheModel, /*dp_rank=*/0), 1u); + EXPECT_EQ(allocator.num_inuse_virt_pages(/*dp_rank=*/0), 1u); EXPECT_TRUE(allocator.released_pages.empty()); std::vector matched = leaf.allocate_shared(tokens); ASSERT_EQ(matched.size(), 2u); @@ -2294,15 +2273,11 @@ TEST(CompositeBlockManagerTest, // must keep its page mapped until its original owner releases it. EXPECT_TRUE(leaf.allocate(/*num_blocks=*/4).empty()); EXPECT_EQ(leaf.num_used_blocks(), 1u); - EXPECT_EQ( - allocator.get_num_inuse_virt_pages(kInjectedCacheModel, /*dp_rank=*/0), - 1u); + EXPECT_EQ(allocator.num_inuse_virt_pages(/*dp_rank=*/0), 1u); EXPECT_TRUE(allocator.released_pages.empty()); held.clear(); EXPECT_EQ(leaf.num_used_blocks(), 0u); - EXPECT_EQ( - allocator.get_num_inuse_virt_pages(kInjectedCacheModel, /*dp_rank=*/0), - 0u); + EXPECT_EQ(allocator.num_inuse_virt_pages(/*dp_rank=*/0), 0u); EXPECT_EQ(allocator.released_pages.size(), 1u); } @@ -2317,9 +2292,7 @@ TEST(CompositeBlockManagerTest, VirtualMemoryRejectsDoubleFreeAfterPageDetach) { const int32_t block_id = blocks.front().id(); blocks.clear(); EXPECT_EQ(leaf.num_used_blocks(), 0u); - EXPECT_EQ( - allocator.get_num_inuse_virt_pages(kInjectedCacheModel, /*dp_rank=*/0), - 0u); + EXPECT_EQ(allocator.num_inuse_virt_pages(/*dp_rank=*/0), 0u); ASSERT_EQ(allocator.released_pages.size(), 1u); // The page-state object is already gone, so the manager must reject a diff --git a/tests/core/kv_cache/storage/vmm_kv_page_allocator_impl_test.cpp b/tests/core/kv_cache/storage/vmm_kv_page_allocator_impl_test.cpp index a15a93e8aa..73c48bde2b 100644 --- a/tests/core/kv_cache/storage/vmm_kv_page_allocator_impl_test.cpp +++ b/tests/core/kv_cache/storage/vmm_kv_page_allocator_impl_test.cpp @@ -259,7 +259,6 @@ TEST(VmmKVPageAllocatorImplTest, mapper.fail_map_call(/*call=*/1); EXPECT_EQ(allocator.alloc_kv_cache_page("model", /*dp_rank=*/1), nullptr); EXPECT_EQ(budget.available_pages("model", /*dp_rank=*/1), 8u); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("model", /*dp_rank=*/1), 0u); auto page = allocator.alloc_kv_cache_page("model", /*dp_rank=*/1); ASSERT_NE(page, nullptr); EXPECT_EQ(page->page_id(), 0); @@ -327,8 +326,6 @@ TEST(VmmKVPageAllocatorImplTest, EXPECT_EQ(second->page_id(), 1); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 0); EXPECT_EQ(allocator.alloc_kv_cache_page("model", /*dp_rank=*/0), nullptr); - EXPECT_EQ(allocator.get_num_free_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("model", /*dp_rank=*/0), 2); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 0); EXPECT_EQ(backend.mapped_offsets(), std::vector({0, 64})); allocator.free_kv_cache_pages("model", /*dp_rank=*/0, {first->page_id()}); @@ -352,8 +349,6 @@ TEST(VmmKVPageAllocatorImplTest, ASSERT_TRUE(allocator.register_model("large", /*num_layers=*/1)); EXPECT_EQ(allocator.get_num_total_virt_pages("large"), kVirtualPages); - EXPECT_EQ(allocator.get_num_free_virt_pages("large", /*dp_rank=*/0), - kVirtualPages); auto first = allocator.alloc_kv_cache_page("large", /*dp_rank=*/0); auto second = allocator.alloc_kv_cache_page("large", /*dp_rank=*/0); @@ -382,8 +377,6 @@ TEST(VmmKVPageAllocatorImplTest, } EXPECT_GT(log_sink.warning_count(), 0u); EXPECT_LE(log_sink.warning_count(), 3u); - EXPECT_EQ(allocator.get_num_free_virt_pages(model_id, /*dp_rank=*/0), 2u); - EXPECT_EQ(allocator.get_num_inuse_virt_pages(model_id, /*dp_rank=*/0), 0u); EXPECT_TRUE(backend.mapped_offsets().empty()); backend.release_pages("weights", /*dp_rank=*/0, 8); @@ -440,41 +433,6 @@ TEST(VmmKVPageAllocatorImplTest, EXPECT_EQ(recycled_one->page_id(), 1); } -TEST(VmmKVPageAllocatorImplTest, - TrimmedVirtualIdsFollowFreshIdsWithoutIncreasingLogicalCapacity) { - FakeKVCachePageResources backend(/*total_pages=*/6, /*dp_size=*/1); - VmmKVPageAllocatorImpl allocator(backend, backend); - allocator.init(/*total_pages=*/6, - /*page_size=*/64, - /*dp_size=*/1, - /*enable_prealloc=*/false); - ASSERT_TRUE(allocator.register_model("model", /*num_layers=*/1)); - auto page = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); - ASSERT_NE(page, nullptr); - allocator.free_kv_cache_pages("model", /*dp_rank=*/0, {page->page_id()}); - EXPECT_EQ(allocator.get_num_available_virt_pages("model", /*dp_rank=*/0), 3); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("model", /*dp_rank=*/0), 1); - - allocator.trim_kv_cache("model", /*dp_rank=*/0); - EXPECT_EQ(allocator.get_num_available_virt_pages("model", /*dp_rank=*/0), 3); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(allocator.get_num_free_virt_pages("model", /*dp_rank=*/0), 3); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 6); - - auto first = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); - auto second = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); - auto recycled = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); - ASSERT_NE(first, nullptr); - ASSERT_NE(second, nullptr); - ASSERT_NE(recycled, nullptr); - EXPECT_EQ(first->page_id(), 1); - EXPECT_EQ(second->page_id(), 2); - EXPECT_EQ(recycled->page_id(), 0); - EXPECT_EQ(allocator.get_num_available_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(allocator.get_num_free_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(allocator.alloc_kv_cache_page("model", /*dp_rank=*/0), nullptr); -} - TEST(VmmKVPageAllocatorImplTest, FailedMappingRestoresVirtualIdAndPhysicalBudgetForRetry) { FakeKVCachePageResources backend(/*total_pages=*/8, /*dp_size=*/1); @@ -487,9 +445,6 @@ TEST(VmmKVPageAllocatorImplTest, backend.fail_map_call(1); EXPECT_EQ(allocator.alloc_kv_cache_page("model", /*dp_rank=*/0), nullptr); - EXPECT_EQ(allocator.get_num_free_virt_pages("model", /*dp_rank=*/0), 2); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("model", /*dp_rank=*/0), 0); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 8); auto retry = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); @@ -497,7 +452,6 @@ TEST(VmmKVPageAllocatorImplTest, EXPECT_EQ(retry->page_id(), 0); EXPECT_EQ(backend.mapped_offsets(), std::vector({0, 0})); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 4); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("model", /*dp_rank=*/0), 1); auto fresh = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); ASSERT_NE(fresh, nullptr); EXPECT_EQ(fresh->page_id(), 1); @@ -525,9 +479,6 @@ TEST(VmmKVPageAllocatorImplTest, auto plan = allocator.begin_suspend("model"); ASSERT_TRUE(plan.has_value()); EXPECT_TRUE(plan->dp_group_page_ids[0].empty()); - EXPECT_EQ(allocator.get_num_free_virt_pages("model", /*dp_rank=*/0), 8); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("model", /*dp_rank=*/0), 0); EXPECT_EQ(backend.map_dp_ranks(), std::vector({0})); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 16); complete_suspend(allocator, backend, "model", *plan); @@ -535,50 +486,47 @@ TEST(VmmKVPageAllocatorImplTest, TEST(VmmKVPageAllocatorImplTest, FailedMixedPreallocationRetriesWholeBatchBeforeRemainingRecycledIds) { - FakeKVCachePageResources backend(/*total_pages=*/20, /*dp_size=*/1); + FakeKVCachePageResources backend(/*total_pages=*/12, /*dp_size=*/1); VmmKVPageAllocatorImpl allocator(backend, backend); - allocator.init(/*total_pages=*/20, + allocator.init(/*total_pages=*/12, /*page_size=*/64, /*dp_size=*/1, - /*enable_prealloc=*/true); - ASSERT_TRUE(allocator.register_model("model", /*num_layers=*/1)); + /*enable_prealloc=*/true, + /*max_reserved_pages=*/2); + const std::string model_id = "model"; + ASSERT_TRUE(allocator.register_model(model_id, /*num_layers=*/1)); std::vector page_ids; - for (size_t index = 0; index < 4; ++index) { - auto page = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); + for (size_t index = 0; index < 5; ++index) { + auto page = allocator.alloc_kv_cache_page(model_id, /*dp_rank=*/0); ASSERT_NE(page, nullptr); page_ids.emplace_back(page->page_id()); } - allocator.free_kv_cache_pages("model", /*dp_rank=*/0, page_ids); - allocator.trim_kv_cache("model", /*dp_rank=*/0); - backend.fail_map_call(5); + allocator.free_kv_cache_pages(model_id, /*dp_rank=*/0, page_ids); + ASSERT_NE(allocator.alloc_kv_cache_page(model_id, /*dp_rank=*/0), nullptr); + ASSERT_NE(allocator.alloc_kv_cache_page(model_id, /*dp_rank=*/0), nullptr); + backend.fail_map_call(/*call=*/6); backend.block_maps(); - allocator.start_prealloc_thread("model"); + allocator.start_prealloc_thread(model_id); EXPECT_TRUE(backend.wait_until_map_started()); backend.release_maps(); - EXPECT_TRUE(backend.wait_until_available_pages(/*dp_rank=*/0, 20)); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(allocator.get_num_free_virt_pages("model", /*dp_rank=*/0), 10); + EXPECT_TRUE( + backend.wait_until_available_pages(/*dp_rank=*/0, /*physical_pages=*/8)); - // The failed batch spans the last fresh IDs and the first recycled IDs. - // Its retry must precede recycled IDs 2 and 3 and retain the entire order. + // Retry must keep the last fresh ID ahead of the recycled IDs. backend.block_maps(); - allocator.start_prealloc_thread("model"); + allocator.start_prealloc_thread(model_id); EXPECT_TRUE(backend.wait_until_map_started()); - auto suspending = std::async(std::launch::async, [&allocator] { - return allocator.begin_suspend("model"); + auto suspending = std::async(std::launch::async, [&allocator, &model_id] { + return allocator.begin_suspend(model_id); }); - EXPECT_TRUE(wait_until_suspended(allocator, "model")); + EXPECT_TRUE(wait_until_suspended(allocator, model_id)); backend.release_maps(); auto plan = suspending.get(); ASSERT_TRUE(plan.has_value()); - EXPECT_EQ(plan->dp_group_page_ids[0], - (std::vector{4, 5, 6, 7, 8, 9, 0, 1})); - EXPECT_EQ( - backend.mapped_offsets(), - (std::vector{0, 64, 128, 192, 256, 320, 384, 448, 512, 576, - 0, 64, 256, 320, 384, 448, 512, 576, 0, 64})); - complete_suspend(allocator, backend, "model", *plan); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 20); + EXPECT_EQ(backend.mapped_offsets(), + (std::vector{0, 64, 128, 192, 256, 320, 128, 320, 128})); + complete_suspend(allocator, backend, model_id, *plan); + EXPECT_EQ(backend.available_pages(model_id, /*dp_rank=*/0), 12); } TEST(VmmKVPageAllocatorImplTest, @@ -627,7 +575,6 @@ TEST(VmmKVPageAllocatorImplTest, EXPECT_FALSE(allocator.is_suspended("model")); for (int32_t dp_rank = 0; dp_rank < 3; ++dp_rank) { EXPECT_EQ(backend.available_pages("model", dp_rank), 4); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("model", dp_rank), 1); } } @@ -643,7 +590,6 @@ TEST(VmmKVPageAllocatorImplTest, EXPECT_EQ(allocator.get_num_available_virt_pages("model", /*dp_rank=*/0), 3); ASSERT_TRUE(backend.try_reserve_pages("weights", /*dp_rank=*/0, 5)); EXPECT_EQ(allocator.get_num_available_virt_pages("model", /*dp_rank=*/0), 1); - EXPECT_EQ(allocator.get_num_free_virt_pages("model", /*dp_rank=*/0), 3); backend.release_pages("weights", /*dp_rank=*/0, 5); EXPECT_EQ(allocator.get_num_available_virt_pages("model", /*dp_rank=*/0), 3); @@ -684,8 +630,6 @@ TEST(VmmKVPageAllocatorImplTest, ZeroReserveUnmapsAndReleasesEveryFreedPage) { allocator.free_kv_cache_pages("model", /*dp_rank=*/0, {page->page_id()}); EXPECT_EQ(backend.unmapped_offsets(), std::vector({0})); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 4); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(allocator.get_num_free_virt_pages("model", /*dp_rank=*/0), 1); auto retry = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); ASSERT_NE(retry, nullptr); EXPECT_EQ(retry->page_id(), page->page_id()); @@ -699,15 +643,22 @@ TEST(VmmKVPageAllocatorImplTest, allocator.init(/*total_pages=*/8, /*page_size=*/64, /*dp_size=*/1, - /*enable_prealloc=*/false); - ASSERT_TRUE(allocator.register_model("first", /*num_layers=*/2)); - ASSERT_TRUE(allocator.register_model("second", /*num_layers=*/2)); - ASSERT_NE(allocator.alloc_kv_cache_page("first", /*dp_rank=*/0), nullptr); - ASSERT_NE(allocator.alloc_kv_cache_page("second", /*dp_rank=*/0), nullptr); - EXPECT_EQ(allocator.alloc_kv_cache_page("first", /*dp_rank=*/0), nullptr); - EXPECT_EQ(allocator.get_num_free_virt_pages("first", /*dp_rank=*/0), 1); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("first", /*dp_rank=*/0), 1); - EXPECT_EQ(backend.available_pages("first", /*dp_rank=*/0), 0); + /*enable_prealloc=*/false, + /*max_reserved_pages=*/0); + const std::string first_model = "first"; + const std::string second_model = "second"; + ASSERT_TRUE(allocator.register_model(first_model, /*num_layers=*/2)); + ASSERT_TRUE(allocator.register_model(second_model, /*num_layers=*/2)); + ASSERT_NE(allocator.alloc_kv_cache_page(first_model, /*dp_rank=*/0), nullptr); + auto second = allocator.alloc_kv_cache_page(second_model, /*dp_rank=*/0); + ASSERT_NE(second, nullptr); + EXPECT_EQ(allocator.alloc_kv_cache_page(first_model, /*dp_rank=*/0), nullptr); + EXPECT_EQ(backend.available_pages(first_model, /*dp_rank=*/0), 0); + allocator.free_kv_cache_pages( + second_model, /*dp_rank=*/0, {second->page_id()}); + auto retry = allocator.alloc_kv_cache_page(first_model, /*dp_rank=*/0); + ASSERT_NE(retry, nullptr); + EXPECT_EQ(retry->page_id(), 1); } TEST(VmmKVPageAllocatorImplTest, DpGroupsReserveIndependentBackendCapacity) { @@ -716,7 +667,8 @@ TEST(VmmKVPageAllocatorImplTest, DpGroupsReserveIndependentBackendCapacity) { allocator.init(/*total_pages=*/8, /*page_size=*/64, /*dp_size=*/2, - /*enable_prealloc=*/false); + /*enable_prealloc=*/false, + /*max_reserved_pages=*/0); ASSERT_TRUE(allocator.register_model("model", /*num_layers=*/2)); ASSERT_NE(allocator.alloc_kv_cache_page("model", /*dp_rank=*/0), nullptr); ASSERT_NE(allocator.alloc_kv_cache_page("model", /*dp_rank=*/0), nullptr); @@ -725,10 +677,8 @@ TEST(VmmKVPageAllocatorImplTest, DpGroupsReserveIndependentBackendCapacity) { EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 0); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/1), 4); allocator.free_kv_cache_pages("model", /*dp_rank=*/1, {page->page_id()}); - allocator.trim_kv_cache("model", /*dp_rank=*/1); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 0); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/1), 8); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("model", /*dp_rank=*/1), 0); } TEST(VmmKVPageAllocatorImplTest, @@ -749,12 +699,7 @@ TEST(VmmKVPageAllocatorImplTest, } EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 0); allocator.free_kv_cache_pages("model", /*dp_rank=*/0, page_ids); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("model", /*dp_rank=*/0), 32); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 16); - allocator.trim_kv_cache("model", /*dp_rank=*/0); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 80); } TEST(VmmKVPageAllocatorImplTest, @@ -780,12 +725,6 @@ TEST(VmmKVPageAllocatorImplTest, EXPECT_EQ(backend.available_pages("awake", /*dp_rank=*/0), 4); allocator.free_kv_cache_pages("sleeping", /*dp_rank=*/0, {page->page_id()}); EXPECT_EQ(backend.available_pages("awake", /*dp_rank=*/0), 4); - EXPECT_EQ(allocator.get_num_free_virt_pages("sleeping", /*dp_rank=*/0), 2); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("sleeping", /*dp_rank=*/0), 0); - allocator.trim_kv_cache("sleeping", /*dp_rank=*/0); - EXPECT_EQ(backend.available_pages("awake", /*dp_rank=*/0), 4); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("sleeping", /*dp_rank=*/0), - 0); } TEST(VmmKVPageAllocatorImplTest, ResumeWaitsForSuspendToDrainPendingMappings) { @@ -865,46 +804,14 @@ TEST(VmmKVPageAllocatorImplTest, FreeWaitsForResumeBeforeRecyclingMappedPage) { free_started.get_future().wait(); EXPECT_EQ(freeing.wait_for(std::chrono::milliseconds(50)), std::future_status::timeout); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("model", /*dp_rank=*/0), 1); allocator.finish_resume("model", /*success=*/true); freeing.get(); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("model", /*dp_rank=*/0), 1); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 4); auto reused = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); ASSERT_NE(reused, nullptr); EXPECT_EQ(reused->page_id(), page->page_id()); } -TEST(VmmKVPageAllocatorImplTest, TrimWaitsForSuspendBeforeReleasingVirtualIds) { - FakeKVCachePageResources backend(/*total_pages=*/8, /*dp_size=*/1); - VmmKVPageAllocatorImpl allocator(backend, backend); - allocator.init(/*total_pages=*/8, - /*page_size=*/64, - /*dp_size=*/1, - /*enable_prealloc=*/false); - ASSERT_TRUE(allocator.register_model("model", /*num_layers=*/2)); - auto page = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); - ASSERT_NE(page, nullptr); - allocator.free_kv_cache_pages("model", /*dp_rank=*/0, {page->page_id()}); - auto plan = allocator.begin_suspend("model"); - ASSERT_TRUE(plan.has_value()); - std::promise trim_started; - auto trimming = std::async(std::launch::async, [&allocator, &trim_started] { - trim_started.set_value(); - allocator.trim_kv_cache("model", /*dp_rank=*/0); - }); - trim_started.get_future().wait(); - EXPECT_EQ(trimming.wait_for(std::chrono::milliseconds(50)), - std::future_status::timeout); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("model", /*dp_rank=*/0), 1); - complete_suspend(allocator, backend, "model", *plan); - trimming.get(); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("model", /*dp_rank=*/0), 0); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 8); - EXPECT_EQ(allocator.get_num_free_virt_pages("model", /*dp_rank=*/0), 2); -} - TEST(VmmKVPageAllocatorImplTest, FailedResumeKeepsPageIdsSuspendedForRetry) { FakeKVCachePageResources backend(/*total_pages=*/8, /*dp_size=*/1); VmmKVPageAllocatorImpl allocator(backend, backend); @@ -929,7 +836,6 @@ TEST(VmmKVPageAllocatorImplTest, FailedResumeKeepsPageIdsSuspendedForRetry) { EXPECT_EQ(retry->dp_group_page_ids, first_resume->dp_group_page_ids); allocator.finish_resume("model", /*success=*/false); allocator.free_kv_cache_pages("model", /*dp_rank=*/0, {page->page_id()}); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("model", /*dp_rank=*/0), 0); EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 8); } @@ -964,105 +870,6 @@ TEST(VmmKVPageAllocatorImplTest, EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 16); } -TEST(VmmKVPageAllocatorImplTest, - UnregisterDrainsExecutingAndQueuedPreallocationBeforeReregister) { - FakeKVCachePageResources backend(/*total_pages=*/32, /*dp_size=*/2); - VmmKVPageAllocatorImpl allocator(backend, backend); - allocator.init(/*total_pages=*/32, - /*page_size=*/64, - /*dp_size=*/2, - /*enable_prealloc=*/true); - ASSERT_TRUE(allocator.register_model("model", /*num_layers=*/1)); - backend.block_maps(); - allocator.start_prealloc_thread("model"); - EXPECT_TRUE(backend.wait_until_map_started()); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 16); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/1), 16); - EXPECT_GT(allocator.get_num_available_virt_pages("model", /*dp_rank=*/0), 0); - std::promise unregister_started; - auto unregistering = - std::async(std::launch::async, [&allocator, &unregister_started] { - unregister_started.set_value(); - return allocator.unregister_model("model"); - }); - unregister_started.get_future().wait(); - EXPECT_TRUE(wait_until_unavailable(allocator, "model")); - EXPECT_EQ(unregistering.wait_for(std::chrono::milliseconds(50)), - std::future_status::timeout); - backend.release_maps(); - ASSERT_TRUE(unregistering.get()); - EXPECT_EQ(backend.map_dp_ranks(), (std::vector{0})); - EXPECT_EQ(backend.unmap_dp_ranks(), (std::vector{0})); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 32); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/1), 32); - - ASSERT_TRUE(allocator.register_model("model", /*num_layers=*/2)); - EXPECT_EQ(allocator.phy_pages_per_virt_page("model"), 4); - EXPECT_EQ(allocator.get_num_total_virt_pages("model"), 8); - auto page = allocator.alloc_kv_cache_page("model", /*dp_rank=*/1); - ASSERT_NE(page, nullptr); - EXPECT_EQ(page->page_id(), 0); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/1), 28); - allocator.free_kv_cache_pages("model", /*dp_rank=*/1, {page->page_id()}); - page.reset(); - EXPECT_TRUE(allocator.unregister_model("model")); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/1), 32); -} - -TEST(VmmKVPageAllocatorImplTest, - UnregisterRejectsLiveAllocationsAndUnfinishedTransitions) { - FakeKVCachePageResources backend(/*total_pages=*/8, /*dp_size=*/1); - VmmKVPageAllocatorImpl allocator(backend, backend); - allocator.init(/*total_pages=*/8, - /*page_size=*/64, - /*dp_size=*/1, - /*enable_prealloc=*/false); - ASSERT_TRUE(allocator.register_model("model", /*num_layers=*/1)); - auto page = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); - ASSERT_NE(page, nullptr); - EXPECT_FALSE(allocator.unregister_model("model")); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 6); - allocator.free_kv_cache_pages("model", /*dp_rank=*/0, {page->page_id()}); - page.reset(); - auto suspend_plan = allocator.begin_suspend("model"); - ASSERT_TRUE(suspend_plan.has_value()); - EXPECT_FALSE(allocator.unregister_model("model")); - complete_suspend(allocator, backend, "model", *suspend_plan); - auto resume_plan = allocator.begin_resume("model"); - ASSERT_TRUE(resume_plan.has_value()); - EXPECT_FALSE(allocator.unregister_model("model")); - allocator.finish_resume("model", /*success=*/false); - EXPECT_TRUE(allocator.unregister_model("model")); - EXPECT_FALSE(allocator.unregister_model("model")); - EXPECT_EQ(backend.available_pages("model", /*dp_rank=*/0), 8); -} - -TEST(VmmKVPageAllocatorImplTest, - UnregisterSuspendedModelDoesNotReleaseItsBudgetTwice) { - FakeKVCachePageResources backend(/*total_pages=*/8, /*dp_size=*/1); - VmmKVPageAllocatorImpl allocator(backend, backend); - allocator.init(/*total_pages=*/8, - /*page_size=*/64, - /*dp_size=*/1, - /*enable_prealloc=*/false); - ASSERT_TRUE(allocator.register_model("model", /*num_layers=*/1)); - ASSERT_TRUE(allocator.register_model("other", /*num_layers=*/1)); - auto page = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); - ASSERT_NE(page, nullptr); - allocator.free_kv_cache_pages("model", /*dp_rank=*/0, {page->page_id()}); - page.reset(); - auto plan = allocator.begin_suspend("model"); - ASSERT_TRUE(plan.has_value()); - complete_suspend(allocator, backend, "model", *plan); - auto other_page = allocator.alloc_kv_cache_page("other", /*dp_rank=*/0); - ASSERT_NE(other_page, nullptr); - EXPECT_TRUE(allocator.unregister_model("model")); - EXPECT_EQ(backend.unmapped_offsets(), (std::vector{0})); - EXPECT_EQ(backend.available_pages("other", /*dp_rank=*/0), 6); - EXPECT_EQ(allocator.get_num_inuse_virt_pages("other", /*dp_rank=*/0), 1); - EXPECT_TRUE(allocator.register_model("model", /*num_layers=*/2)); -} - TEST(VmmKVPageAllocatorImplTest, ShutdownDrainsExecutingAndQueuedPreallocationBeforeBackendTeardown) { FakeKVCachePageResources backend(/*total_pages=*/32, /*dp_size=*/2); @@ -1105,10 +912,8 @@ TEST(VmmKVPageAllocatorImplTest, UsesInjectedPageGeometry) { ASSERT_TRUE(allocator.register_model("model", /*num_layers=*/3)); EXPECT_FALSE(allocator.register_model("model", /*num_layers=*/3)); EXPECT_EQ(allocator.get_num_total_virt_pages("model"), 4); - EXPECT_EQ(allocator.phy_pages_per_virt_page("model"), 6); EXPECT_EQ( allocator.get_virt_page_id(/*block_id=*/7, /*block_memory_size=*/32), 1); - EXPECT_EQ(allocator.get_offset(/*virtual_page_id=*/3), 384); } TEST(VmmKVPageAllocatorImplTest, PreallocationWaitsForEachModelsWorkerRegions) { @@ -1125,7 +930,6 @@ TEST(VmmKVPageAllocatorImplTest, PreallocationWaitsForEachModelsWorkerRegions) { EXPECT_TRUE(backend.wait_until_map_started()); EXPECT_EQ(backend.mapped_model_ids(), std::vector({"first"})); EXPECT_EQ(backend.available_pages("first", /*dp_rank=*/0), 48); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("second", /*dp_rank=*/0), 0); backend.release_maps(); auto first_plan = allocator.begin_suspend("first"); ASSERT_TRUE(first_plan.has_value()); @@ -1147,18 +951,18 @@ TEST(VmmKVPageAllocatorImplTest, PreallocationWaitsForEachModelsWorkerRegions) { EXPECT_EQ(backend.available_pages("second", /*dp_rank=*/0), 64); } -TEST(VmmKVPageAllocatorImplTest, MlaBudgetSurvivesTrimAndSleepWakeup) { +TEST(VmmKVPageAllocatorImplTest, MlaBudgetSurvivesSleepWakeup) { FakeKVCachePageResources backend(/*total_pages=*/36, /*dp_size=*/1); VmmKVPageAllocatorImpl allocator(backend, backend); allocator.init(/*total_pages=*/36, /*page_size=*/2 * 1024 * 1024, /*dp_size=*/1, - /*enable_prealloc=*/false); + /*enable_prealloc=*/false, + /*max_reserved_pages=*/0); ASSERT_TRUE(allocator.register_model("mla", /*num_layers=*/2, /*physical_pages_per_virtual_page=*/18, /*max_virtual_pages=*/2)); - EXPECT_EQ(allocator.phy_pages_per_virt_page("mla"), 18); auto first = allocator.alloc_kv_cache_page("mla", /*dp_rank=*/0); auto second = allocator.alloc_kv_cache_page("mla", /*dp_rank=*/0); ASSERT_NE(first, nullptr); @@ -1166,7 +970,6 @@ TEST(VmmKVPageAllocatorImplTest, MlaBudgetSurvivesTrimAndSleepWakeup) { EXPECT_EQ(backend.available_pages("mla", /*dp_rank=*/0), 0); EXPECT_EQ(allocator.alloc_kv_cache_page("mla", /*dp_rank=*/0), nullptr); allocator.free_kv_cache_pages("mla", /*dp_rank=*/0, {first->page_id()}); - allocator.trim_kv_cache("mla", /*dp_rank=*/0); EXPECT_EQ(backend.available_pages("mla", /*dp_rank=*/0), 18); auto plan = allocator.begin_suspend("mla"); ASSERT_TRUE(plan.has_value()); @@ -1183,7 +986,6 @@ TEST(VmmKVPageAllocatorImplTest, MlaBudgetSurvivesTrimAndSleepWakeup) { allocator.finish_resume("mla", /*success=*/true); EXPECT_EQ(backend.available_pages("mla", /*dp_rank=*/0), 18); allocator.free_kv_cache_pages("mla", /*dp_rank=*/0, {second->page_id()}); - allocator.trim_kv_cache("mla", /*dp_rank=*/0); EXPECT_EQ(backend.available_pages("mla", /*dp_rank=*/0), 36); } @@ -1200,7 +1002,6 @@ TEST(VmmKVPageAllocatorImplTest, MlaShortagePreservesPhysicalBudget) { ASSERT_TRUE(backend.try_reserve_pages("weights", /*dp_rank=*/0, 19)); EXPECT_EQ(allocator.alloc_kv_cache_page("mla", /*dp_rank=*/0), nullptr); EXPECT_EQ(backend.available_pages("mla", /*dp_rank=*/0), 17); - EXPECT_EQ(allocator.get_num_free_virt_pages("mla", /*dp_rank=*/0), 2); backend.release_pages("weights", /*dp_rank=*/0, 1); EXPECT_NE(allocator.alloc_kv_cache_page("mla", /*dp_rank=*/0), nullptr); EXPECT_EQ(backend.available_pages("mla", /*dp_rank=*/0), 0); @@ -1218,7 +1019,6 @@ TEST(VmmKVPageAllocatorImplTest, TensorCapacityLimitsVirtualPageIds) { /*num_layers=*/2, /*physical_pages_per_virtual_page=*/18, /*max_virtual_pages=*/blocks / 128)); - EXPECT_EQ(allocator.get_num_total_virt_pages("mla"), blocks / 128); for (size_t index = 0; index < blocks / 128; ++index) { auto page = allocator.alloc_kv_cache_page("mla", /*dp_rank=*/0); ASSERT_NE(page, nullptr); @@ -1268,10 +1068,7 @@ TEST(VmmKVPageAllocatorImplTest, MlaRetainedPagesKeepPhysicalPageBudget) { ids.emplace_back(page->page_id()); } allocator.free_kv_cache_pages("mla", /*dp_rank=*/0, ids); - EXPECT_EQ(allocator.get_num_reserved_virt_pages("mla", /*dp_rank=*/0), 7); EXPECT_EQ(backend.available_pages("mla", /*dp_rank=*/0), 54); - allocator.trim_kv_cache("mla", /*dp_rank=*/0); - EXPECT_EQ(backend.available_pages("mla", /*dp_rank=*/0), 180); } TEST(VmmKVPageAllocatorImplTest, @@ -1285,24 +1082,22 @@ TEST(VmmKVPageAllocatorImplTest, allocator.init(/*total_pages=*/2 * physical_pages, /*page_size=*/2 * 1024 * 1024, /*dp_size=*/1, - /*enable_prealloc=*/false); + /*enable_prealloc=*/false, + /*max_reserved_pages=*/0); ASSERT_TRUE(allocator.register_model("glm53", /*num_layers=*/78, physical_pages, /*max_virtual_pages=*/2)); - EXPECT_EQ(allocator.phy_pages_per_virt_page("glm53"), 744); ASSERT_TRUE(backend.try_reserve_pages("weights", /*dp_rank=*/0, 1)); auto page = allocator.alloc_kv_cache_page("glm53", /*dp_rank=*/0); ASSERT_NE(page, nullptr); EXPECT_EQ(allocator.alloc_kv_cache_page("glm53", /*dp_rank=*/0), nullptr); EXPECT_EQ(backend.available_pages("glm53", /*dp_rank=*/0), 743); - EXPECT_EQ(allocator.get_num_free_virt_pages("glm53", /*dp_rank=*/0), 1); backend.release_pages("weights", /*dp_rank=*/0, 1); auto second = allocator.alloc_kv_cache_page("glm53", /*dp_rank=*/0); ASSERT_NE(second, nullptr); EXPECT_EQ(backend.available_pages("glm53", /*dp_rank=*/0), 0); allocator.free_kv_cache_pages("glm53", /*dp_rank=*/0, {second->page_id()}); - allocator.trim_kv_cache("glm53", /*dp_rank=*/0); EXPECT_EQ(backend.available_pages("glm53", /*dp_rank=*/0), 744); auto plan = allocator.begin_suspend("glm53"); ASSERT_TRUE(plan.has_value()); @@ -1319,7 +1114,6 @@ TEST(VmmKVPageAllocatorImplTest, allocator.finish_resume("glm53", /*success=*/true); EXPECT_EQ(backend.available_pages("glm53", /*dp_rank=*/0), 744); allocator.free_kv_cache_pages("glm53", /*dp_rank=*/0, {page->page_id()}); - allocator.trim_kv_cache("glm53", /*dp_rank=*/0); EXPECT_EQ(backend.available_pages("glm53", /*dp_rank=*/0), 1488); } @@ -1343,25 +1137,6 @@ TEST(VmmKVPageAllocatorImplDeathTest, "Failed to unmap KV pages for model=model dp_rank=0"); } -TEST(VmmKVPageAllocatorImplDeathTest, - FailedTrimUnmapTerminatesBeforeReleasingBudget) { - FakeKVCachePageResources backend(/*total_pages=*/4, /*dp_size=*/1); - VmmKVPageAllocatorImpl allocator(backend, backend); - allocator.init(/*total_pages=*/4, - /*page_size=*/64, - /*dp_size=*/1, - /*enable_prealloc=*/false); - ASSERT_TRUE(allocator.register_model("model", /*num_layers=*/2)); - auto page = allocator.alloc_kv_cache_page("model", /*dp_rank=*/0); - ASSERT_NE(page, nullptr); - allocator.free_kv_cache_pages("model", /*dp_rank=*/0, {page->page_id()}); - backend.fail_unmap_call(1); - backend.forbid_budget_release(); - - EXPECT_DEATH(allocator.trim_kv_cache("model", /*dp_rank=*/0), - "Failed to unmap KV pages for model=model dp_rank=0"); -} - TEST(VmmKVPageAllocatorImplDeathTest, PartialSuspendUnmapTerminatesBeforeReleasingAnyDpBudget) { FakeKVCachePageResources backend(/*total_pages=*/4, /*dp_size=*/2); diff --git a/tests/core/runtime/schedule_overlap_state_test.cpp b/tests/core/runtime/schedule_overlap_state_test.cpp index 06c80fbf9e..e8656fc80f 100644 --- a/tests/core/runtime/schedule_overlap_state_test.cpp +++ b/tests/core/runtime/schedule_overlap_state_test.cpp @@ -41,21 +41,19 @@ TEST(ScheduleOverlapStateTest, ConsumedOutputRemainsAvailableForContinuation) { /*retain_tokenless_output=*/false); ASSERT_TRUE(state.record(token_output(7), {"request"}, {"sequence"})); - ForwardOutput consumed = state.consume(); + ForwardOutput consumed = state.consume().value(); ASSERT_TRUE(consumed.sample_output.next_tokens.defined()); EXPECT_EQ(consumed.sample_output.next_tokens.item(), 7); EXPECT_TRUE(state.has_tokens()); EXPECT_TRUE(state.prior_output().sample_output.next_tokens.defined()); - EXPECT_EQ(state.request_ids(), (std::vector{"request"})); EXPECT_EQ(state.sample_sequence_ids(), (std::vector{"sequence"})); ASSERT_TRUE( state.record(token_output(9), {"next_request"}, {"next_sequence"})); - consumed = state.consume(); + consumed = state.consume().value(); EXPECT_EQ(consumed.sample_output.next_tokens.item(), 9); EXPECT_EQ(state.prior_output().sample_output.next_tokens.item(), 9); - EXPECT_EQ(state.request_ids(), (std::vector{"next_request"})); EXPECT_EQ(state.sample_sequence_ids(), (std::vector{"next_sequence"})); } @@ -119,7 +117,6 @@ TEST(ScheduleOverlapStateTest, ASSERT_EQ(next_status, std::future_status::ready); ASSERT_TRUE(next_record.get()); EXPECT_EQ(state.prior_output().sample_output.next_tokens.item(), 9); - EXPECT_EQ(state.request_ids(), (std::vector{"next_request"})); EXPECT_EQ(state.sample_sequence_ids(), (std::vector{"next_sequence"})); } @@ -134,11 +131,10 @@ TEST(ScheduleOverlapStateTest, EmptyPublicationClearsPriorContinuation) { ASSERT_TRUE(state.has_tokens()); ASSERT_TRUE(state.record(std::nullopt, {"request"}, {"sequence"})); - const ForwardOutput consumed = state.consume(); + const ForwardOutput consumed = state.consume().value(); EXPECT_FALSE(consumed.sample_output.next_tokens.defined()); EXPECT_FALSE(state.has_tokens()); EXPECT_FALSE(state.prior_output().sample_output.next_tokens.defined()); - EXPECT_TRUE(state.request_ids().empty()); EXPECT_TRUE(state.sample_sequence_ids().empty()); } } @@ -150,7 +146,7 @@ TEST(ScheduleOverlapStateTest, TokenlessMetadataCanBePublishedAndConsumed) { output.json_object_errors.push_back({"sequence", "row mismatch"}); ASSERT_TRUE(state.record(std::move(output), {"request"}, {"sequence"})); - const ForwardOutput consumed = state.consume(); + const ForwardOutput consumed = state.consume().value(); EXPECT_FALSE(consumed.sample_output.next_tokens.defined()); ASSERT_EQ(consumed.json_object_errors.size(), 1U); EXPECT_EQ(state.sample_sequence_ids(), @@ -165,11 +161,10 @@ TEST(ScheduleOverlapStateTest, FiltersOrdinaryTokenlessOutputFromPublication) { output.prepared_token = 11; ASSERT_TRUE(state.record(std::move(output), {"request"}, {"sequence"})); - const ForwardOutput consumed = state.consume(); + const ForwardOutput consumed = state.consume().value(); EXPECT_FALSE(consumed.expert_load_data.defined()); EXPECT_EQ(consumed.prepared_token, -1); EXPECT_FALSE(state.has_tokens()); - EXPECT_TRUE(state.request_ids().empty()); EXPECT_TRUE(state.sample_sequence_ids().empty()); } @@ -181,13 +176,12 @@ TEST(ScheduleOverlapStateTest, RetainsTokenlessOutputWhenRequested) { output.prepared_token = 11; ASSERT_TRUE(state.record(std::move(output), {"request"}, {"sequence"})); - const ForwardOutput consumed = state.consume(); + const ForwardOutput consumed = state.consume().value(); EXPECT_FALSE(consumed.sample_output.next_tokens.defined()); ASSERT_TRUE(consumed.expert_load_data.defined()); EXPECT_TRUE(torch::equal(consumed.expert_load_data, torch::tensor({3, 5}, torch::kInt64))); EXPECT_EQ(consumed.prepared_token, 11); - EXPECT_EQ(state.request_ids(), (std::vector{"request"})); EXPECT_EQ(state.sample_sequence_ids(), (std::vector{"sequence"})); } @@ -201,10 +195,12 @@ TEST(ScheduleOverlapStateTest, RecordAppliesBackpressureUntilConsumed) { return state.record(token_output(2), {}, {}); }); EXPECT_EQ(second_publish.wait_for(50ms), std::future_status::timeout); - EXPECT_EQ(state.consume().sample_output.next_tokens.item(), 1); + EXPECT_EQ(state.consume().value().sample_output.next_tokens.item(), + 1); ASSERT_EQ(second_publish.wait_for(1s), std::future_status::ready); EXPECT_TRUE(second_publish.get()); - EXPECT_EQ(state.consume().sample_output.next_tokens.item(), 2); + EXPECT_EQ(state.consume().value().sample_output.next_tokens.item(), + 2); } TEST(ScheduleOverlapStateTest, ShutdownWakesWaitingConsumerAndProducer) { @@ -215,7 +211,7 @@ TEST(ScheduleOverlapStateTest, ShutdownWakesWaitingConsumerAndProducer) { EXPECT_EQ(consumer.wait_for(50ms), std::future_status::timeout); state.shutdown(); ASSERT_EQ(consumer.wait_for(1s), std::future_status::ready); - EXPECT_FALSE(consumer.get().sample_output.next_tokens.defined()); + EXPECT_FALSE(consumer.get().has_value()); EXPECT_FALSE(state.record(token_output(3), {}, {})); } @@ -231,6 +227,8 @@ TEST(ScheduleOverlapStateTest, ShutdownUnblocksPublicationBackpressure) { state.shutdown(); ASSERT_EQ(second_publish.wait_for(1s), std::future_status::ready); EXPECT_FALSE(second_publish.get()); + EXPECT_EQ(state.consume().value().sample_output.next_tokens.item(), + 1); } TEST(ScheduleOverlapStateTest, @@ -254,7 +252,6 @@ TEST(ScheduleOverlapStateTest, EXPECT_TRUE(state.has_tokens()); EXPECT_EQ(state.prior_output().sample_output.next_tokens.item(), 7); - EXPECT_EQ(state.request_ids(), (std::vector{"prior_request"})); EXPECT_EQ(state.sample_sequence_ids(), (std::vector{"prior_sequence"})); EXPECT_FALSE(weak_owner.expired()); @@ -273,7 +270,7 @@ TEST(ScheduleOverlapStateTest, RetainedInputsOutliveConsumedCopy) { output.retained_inputs.emplace_back(owner); ASSERT_TRUE(state.record(std::move(output), {}, {})); owner.reset(); - ForwardOutput consumed = state.consume(); + ForwardOutput consumed = state.consume().value(); consumed.retained_inputs.clear(); EXPECT_FALSE(weak_owner.expired()); } diff --git a/tests/core/runtime/schedule_overlap_test.cpp b/tests/core/runtime/schedule_overlap_test.cpp index 668959793c..07bb9047af 100644 --- a/tests/core/runtime/schedule_overlap_test.cpp +++ b/tests/core/runtime/schedule_overlap_test.cpp @@ -90,10 +90,11 @@ class OverlapTestWorker final : public WorkerImpl { ContinuationMode continuation_mode = ContinuationMode::DEFAULT_REPLACEMENT, bool speculative_decode = false, - EplbWorkerConfig eplb_config = {}) + EplbWorkerConfig eplb_config = {}, + InstanceRole instance_role = InstanceRole::DEFAULT) : WorkerImpl(parallel_args, torch::Device(torch::kPrivateUse1, /*index=*/0), - options(speculative_decode, eplb_config), + options(speculative_decode, eplb_config, instance_role), /*is_input_release_deferred=*/speculative_decode && parallel_args.dp_size() > 1), outputs_(std::move(outputs)), @@ -159,11 +160,14 @@ class OverlapTestWorker final : public WorkerImpl { private: static runtime::Options options(bool speculative_decode, - EplbWorkerConfig eplb_config) { + EplbWorkerConfig eplb_config, + InstanceRole instance_role) { runtime::Options options; options.enable_schedule_overlap(true); options.enable_speculative_decode(speculative_decode); options.eplb_worker_config(eplb_config); + options.instance_role(instance_role); + options.enable_disagg_pd(instance_role.can_receive_pd_kv()); return options; } @@ -329,7 +333,7 @@ void expect_rejected_json_continuation(torch::Tensor prior_tokens) { EXPECT_EQ(output->json_object_errors.front().sample_sequence_id, "request#0"); EXPECT_EQ(output->json_object_errors.front().message, "prior token violates json_object grammar"); - const ForwardOutput published = worker.get_last_step_result(); + const ForwardOutput published = worker.get_last_step_result().value(); ASSERT_EQ(published.json_object_errors.size(), 1U); EXPECT_EQ(published.json_object_errors.front().sample_sequence_id, "request#0"); @@ -357,6 +361,7 @@ TEST(ScheduleOverlapContinuationTest, auto first = worker.step_async(step_input(/*decode=*/false)); ASSERT_TRUE(std::move(first).get().has_value()); ASSERT_EQ(worker.get_last_step_result() + .value() .sample_output.next_tokens.template item(), 17); @@ -365,6 +370,7 @@ TEST(ScheduleOverlapContinuationTest, ASSERT_TRUE(std::move(second).get().has_value()); EXPECT_EQ(worker.executed_tokens().template item(), 7); ASSERT_EQ(worker.get_last_step_result() + .value() .sample_output.next_tokens.template item(), 23); @@ -372,6 +378,7 @@ TEST(ScheduleOverlapContinuationTest, ASSERT_TRUE(std::move(third).get().has_value()); EXPECT_EQ(worker.executed_tokens().template item(), 23); EXPECT_EQ(worker.get_last_step_result() + .value() .sample_output.next_tokens.template item(), 41); } @@ -517,8 +524,9 @@ TYPED_TEST(ScheduleOverlapTest, EmptyStepClearsPriorContinuation) { empty.token_ids = torch::empty({0}, torch::kInt32); auto idle = worker.step_async(empty); EXPECT_FALSE(std::move(idle).get().has_value()); - EXPECT_FALSE( - worker.get_last_step_result().sample_output.next_tokens.defined()); + EXPECT_FALSE(worker.get_last_step_result() + .value() + .sample_output.next_tokens.defined()); auto next = worker.step_async( step_input(/*decode=*/true, /*token_id=*/-1)); @@ -545,7 +553,7 @@ TYPED_TEST(ScheduleOverlapTest, AddsWarmupAndJsonErrorsToBothResultPaths) { EXPECT_EQ(returned->json_object_errors[0].message, "model error"); EXPECT_EQ(returned->json_object_errors[1].message, "input error"); - const ForwardOutput published = worker.get_last_step_result(); + const ForwardOutput published = worker.get_last_step_result().value(); EXPECT_TRUE(published.is_graph_warmup); ASSERT_EQ(published.json_object_errors.size(), 2U); EXPECT_EQ(published.json_object_errors[0].message, "model error"); @@ -573,7 +581,8 @@ TYPED_TEST(ScheduleOverlapTest, ConstrainedDecodeRejectsUnrelatedPriorResult) { EXPECT_EQ(output->json_object_errors.front().sample_sequence_id, "current#0"); EXPECT_NE(output->json_object_errors.front().message.find("missing"), std::string::npos); - ASSERT_EQ(worker.get_last_step_result().json_object_errors.size(), 1U); + ASSERT_EQ(worker.get_last_step_result().value().json_object_errors.size(), + 1U); } TYPED_TEST(ScheduleOverlapTest, ConstrainedContinuationAdvancesGrammar) { @@ -729,7 +738,8 @@ TYPED_TEST(ScheduleOverlapTest, torch::equal(input.sampling_params.seed_offsets().to(torch::kCPU), torch::tensor({10, 20, 30}, torch::kInt64))); EXPECT_TRUE(torch::equal( - worker.get_last_step_result().sample_output.next_tokens.to(torch::kCPU), + worker.get_last_step_result().value().sample_output.next_tokens.to( + /*device=*/torch::kCPU), output->sample_output.next_tokens.to(torch::kCPU))); } } @@ -761,6 +771,46 @@ TYPED_TEST(ScheduleOverlapTest, NonDriverContinuesWithoutHostConsumption) { EXPECT_EQ(worker.executed_tokens().template item(), 17); } +TYPED_TEST(ScheduleOverlapTest, PdFollowerBindsDeviceOnFreshResultThread) { + const ParallelArgs parallel_args(/*rank=*/1, + /*world_size=*/2, + /*dp_size=*/1, + /*process_group=*/nullptr); + OverlapTestWorker worker( + {token_output(/*token_id=*/17)}, + parallel_args, + OverlapTestWorker::ContinuationMode::DEFAULT_REPLACEMENT, + /*speculative_decode=*/false, + /*eplb_config=*/{}, + /*instance_role=*/InstanceRole::DECODE); + auto step = worker.step_async(step_input(/*decode=*/true)) + .toUnsafeFuture(); + step.wait(/*dur=*/2s); + if (!step.isReady()) { + worker.begin_shutdown(); + } + ASSERT_TRUE(step.isReady()); + const auto submitted = std::move(step).get(); + ASSERT_TRUE(submitted.has_value()); + ASSERT_NE(submitted->ready_event, nullptr); + + auto publication = std::async(std::launch::async, [&worker]() { + auto result = worker.get_last_step_result(); + aclrtContext context = nullptr; + EXPECT_EQ(aclrtGetCurrentContext(&context), ACL_SUCCESS); + EXPECT_NE(context, nullptr); + return result; + }); + const auto status = publication.wait_for(/*timeout=*/2s); + if (status != std::future_status::ready) { + worker.begin_shutdown(); + } + ASSERT_EQ(status, std::future_status::ready); + const auto result = publication.get(); + ASSERT_TRUE(result.has_value()); + EXPECT_FALSE(result->sample_output.next_tokens.defined()); +} + TYPED_TEST(ScheduleOverlapTest, EplbNonDriverPublishesTokenlessMetadataWithFixedPolicy) { ScopedConfigValue eplb(EPLBConfig::get_instance().enable_eplb(), false); @@ -792,7 +842,7 @@ TYPED_TEST(ScheduleOverlapTest, worker.begin_shutdown(); } ASSERT_EQ(publication_status, std::future_status::ready); - const ForwardOutput published = publication.get(); + const ForwardOutput published = publication.get().value(); EXPECT_FALSE(published.sample_output.next_tokens.defined()); ASSERT_TRUE(published.expert_load_data.defined()); EXPECT_TRUE(torch::equal(published.expert_load_data, @@ -825,7 +875,7 @@ TYPED_TEST(ScheduleOverlapTest, DpDriverPublishesWithoutEplb) { worker.begin_shutdown(); } ASSERT_EQ(publication_status, std::future_status::ready); - const ForwardOutput published = publication.get(); + const ForwardOutput published = publication.get().value(); ASSERT_TRUE(published.sample_output.next_tokens.defined()); EXPECT_EQ(published.sample_output.next_tokens.template item(), 17); } @@ -880,7 +930,7 @@ TYPED_TEST(ScheduleOverlapTest, if (publication_status != std::future_status::ready) { worker.begin_shutdown(); } - const ForwardOutput published = publication.get(); + const ForwardOutput published = publication.get().value(); auto second = worker.step_async(step_input(/*decode=*/false)) .toUnsafeFuture() .thenValue([](std::optional output) { diff --git a/tests/core/runtime/worker_shutdown_test.cpp b/tests/core/runtime/worker_shutdown_test.cpp index 028661f7f7..fd8a045661 100644 --- a/tests/core/runtime/worker_shutdown_test.cpp +++ b/tests/core/runtime/worker_shutdown_test.cpp @@ -111,7 +111,7 @@ TEST(WorkerShutdownTest, WakesResultWaitersWithoutPublishingAnOutput) { if (status != std::future_status::ready) { worker.begin_shutdown(); } - EXPECT_FALSE(result.get().sample_output.next_tokens.defined()); + EXPECT_FALSE(result.get().has_value()); worker.drain_pending_execution(); } @@ -119,12 +119,12 @@ TEST(WorkerShutdownTest, DoesNotReturnAnAlreadyConsumedOutputDuringShutdown) { ShutdownTestWorker worker; auto step = worker.step_async(empty_input()); EXPECT_TRUE(std::move(step).get().has_value()); - EXPECT_TRUE( - worker.get_last_step_result().sample_output.next_tokens.defined()); + EXPECT_TRUE(worker.get_last_step_result() + .value() + .sample_output.next_tokens.defined()); worker.begin_shutdown(); - EXPECT_FALSE( - worker.get_last_step_result().sample_output.next_tokens.defined()); + EXPECT_FALSE(worker.get_last_step_result().has_value()); worker.drain_pending_execution(); } diff --git a/tests/core/scheduler/continuous_scheduler_test.cpp b/tests/core/scheduler/continuous_scheduler_test.cpp index 7d79edfd3c..e26bfce7b1 100644 --- a/tests/core/scheduler/continuous_scheduler_test.cpp +++ b/tests/core/scheduler/continuous_scheduler_test.cpp @@ -60,6 +60,10 @@ class ControllableBlockManagerPool final : public BlockManagerPool { explicit ControllableBlockManagerPool(const Options& options) : BlockManagerPool(options, /*dp_size=*/1) {} + void transfer_blocks() override { ++empty_transfer_calls_; } + + size_t empty_transfer_calls() const { return empty_transfer_calls_; } + bool has_pending_async_block_release() const override { return pending_async_release_.load(); } @@ -141,6 +145,7 @@ class ControllableBlockManagerPool final : public BlockManagerPool { } private: + size_t empty_transfer_calls_ = 0; std::atomic pending_async_release_{false}; std::atomic completed_host_copy_{false}; bool host_cache_ = false; @@ -282,7 +287,7 @@ class FakeEngine : public Engine { return std::vector(batch.size()); } const Tokenizer* tokenizer() const { return fake_tokenizer_.get(); } - BlockManagerPool* kv_cache_manager() const override { + ControllableBlockManagerPool* kv_cache_manager() const override { return fake_block_manager_.get(); } const ModelArgs& model_args() const { return model_args_; } @@ -327,7 +332,15 @@ class FakeEngine : public Engine { class PipelinePhaseEngine final : public FakeEngine { public: - PipelinePhaseEngine() : FakeEngine(/*num_blocks=*/128, /*block_size=*/4) {} + explicit PipelinePhaseEngine( + bool enable_linear_attention = false, + int32_t num_blocks = 128, + InstanceRole instance_role = InstanceRole::DEFAULT) + : FakeEngine(num_blocks, + /*block_size=*/4, + /*enable_prefix_cache=*/false, + enable_linear_attention, + instance_role) {} ForwardOutput step(BatchGroup& /*batch*/) override { calls.emplace_back("step"); step_observed_consumed = consumed; @@ -353,6 +366,7 @@ class PipelinePhaseEngine final : public FakeEngine { class TestableContinuousScheduler final : public ContinuousScheduler<> { public: + using ContinuousScheduler<>::prepare_batch; using ContinuousScheduler<>::schedule_request; template @@ -389,10 +403,6 @@ class TestableContinuousScheduler final : public ContinuousScheduler<> { incr_pending_requests(1); } - void notify_after_next_prepare_batch(std::promise& notification) { - prepared_notification_ = ¬ification; - } - void process_batch_output_test() { process_batch_output(running_requests_); } std::vector> get_running_requests() { @@ -425,33 +435,6 @@ class TestableContinuousScheduler final : public ContinuousScheduler<> { pending_step_->batches = BatchGroup(/*dp_size=*/1); pending_step_->batches.front().add(request->sequences().front().get()); } - - void schedule_batch_for_test(std::vector> requests) { - scripted_scheduling_ = true; - scripted_requests_ = std::move(requests); - } - - BatchGroup prepare_batch() override { - if (scripted_scheduling_) { - running_requests_ = std::move(scripted_requests_); - refresh_sequences_from_requests(running_requests_, running_sequences_); - BatchGroup batch(/*dp_size=*/1); - batch.front().add(running_sequences_); - return batch; - } - BatchGroup batch = ContinuousSchedulerBase::prepare_batch(); - std::promise* notification = - std::exchange(prepared_notification_, nullptr); - if (notification != nullptr) { - notification->set_value(); - } - return batch; - } - - private: - bool scripted_scheduling_ = false; - std::vector> scripted_requests_; - std::promise* prepared_notification_ = nullptr; }; class RejectingReadyScheduler final : public ContinuousScheduler<> { @@ -648,22 +631,6 @@ void set_chunk_kv(const std::shared_ptr& request, size_t kv_tokens) { } } -class OverlapDrainEngine final : public FakeEngine { - public: - OverlapDrainEngine() : FakeEngine(32, 4) {} - - std::vector collect_step_outputs( - const BatchGroup& batches) override { - ++completed_batches_; - return std::vector(batches.size()); - } - - size_t completed_batches() const { return completed_batches_; } - - private: - size_t completed_batches_ = 0; -}; - class CancelledOverlapEngine final : public FakeEngine { public: explicit CancelledOverlapEngine(bool linear_state) @@ -718,31 +685,6 @@ class CancelledOverlapEngine final : public FakeEngine { size_t completed_batches_ = 0; }; -class BlockedOverlapScheduler final : public ContinuousScheduler<> { - public: - template - BlockedOverlapScheduler(TargetEngine* engine, - const SchedulerOptions& options, - const std::shared_ptr& request) - : ContinuousScheduler<>(engine, options) { - pending_step_.emplace(); - pending_step_->requests.emplace_back(request); - pending_step_->batches = BatchGroup(1); - pending_step_->batches.front().add(request->sequences().front().get()); - } - - size_t prepare_calls() const { return prepare_calls_; } - - protected: - BatchGroup prepare_batch() override { - ++prepare_calls_; - return BatchGroup(1); - } - - private: - size_t prepare_calls_ = 0; -}; - } // namespace TEST(RequestOutputDispatcherTest, @@ -953,15 +895,16 @@ TEST(ContinuousSchedulerTest, DecodeLinearKeepsIndependentInBatchState) { TEST(ContinuousSchedulerTest, DrainsInflightBatchBeforeRetryingBlockedQueue) { auto request = generate_request_with_prompt_tokens({1, 2, 3, 4}, 4, 30000); - OverlapDrainEngine engine; + PipelinePhaseEngine engine; auto options = create_scheduler_options(1024, 16, 0, 1024, 1); options.enable_schedule_overlap(true); - BlockedOverlapScheduler scheduler(&engine, options, request); + TestableContinuousScheduler scheduler(&engine, options); + scheduler.seed_pending_batch(request); scheduler.step(absl::Seconds(5)); - EXPECT_EQ(scheduler.prepare_calls(), 1u); - EXPECT_EQ(engine.completed_batches(), 1u); + EXPECT_EQ(engine.kv_cache_manager()->empty_transfer_calls(), 1u); + EXPECT_EQ(engine.calls, std::vector{"consume"}); } TEST(ContinuousSchedulerTest, CancelledOverlapRequestReleasesBeforeResult) { @@ -1081,65 +1024,126 @@ TEST(ContinuousSchedulerTest, auto first = generate_request_with_prompt_tokens({1, 2}, 16, 256); auto second = generate_request_with_prompt_tokens({3, 4}, 16, 256); - scheduler.schedule_batch_for_test({first}); + ASSERT_TRUE(scheduler.add_request(first)); scheduler.step(absl::ZeroDuration()); EXPECT_EQ(engine.calls, (std::vector{"step"})); - EXPECT_TRUE(engine.collected_sequences.empty()); - scheduler.schedule_batch_for_test({second}); + first->set_cancel(); + ASSERT_TRUE(scheduler.add_request(second)); scheduler.step(absl::ZeroDuration()); - EXPECT_EQ(engine.calls, + ASSERT_EQ(engine.calls, (std::vector{"step", "step", "consume"})); - ASSERT_EQ(engine.collected_sequences.size(), 1u); EXPECT_EQ(engine.collected_sequences[0], (std::vector{first->sequences().front().get()})); + second->set_cancel(); scheduler.step(absl::ZeroDuration()); - EXPECT_EQ(engine.calls, + ASSERT_EQ(engine.calls, (std::vector{"step", "step", "consume", "consume"})); - ASSERT_EQ(engine.collected_sequences.size(), 2u); EXPECT_EQ(engine.collected_sequences[1], (std::vector{second->sequences().front().get()})); scheduler.step(absl::ZeroDuration()); EXPECT_EQ(engine.calls.size(), 4u); - // Work arriving after a drain starts a fresh first step. - scheduler.schedule_batch_for_test({first}); + auto third = generate_request_with_prompt_tokens( + /*prompt_tokens=*/{5, 6}, /*max_tokens=*/16, /*max_context_len=*/256); + ASSERT_TRUE(scheduler.add_request(third)); scheduler.step(absl::ZeroDuration()); - EXPECT_EQ(engine.calls.back(), "step"); - EXPECT_EQ(engine.calls.size(), 5u); - EXPECT_EQ(engine.collected_sequences.size(), 2u); + EXPECT_EQ( + engine.calls, + (std::vector{"step", "step", "consume", "consume", "step"})); + third->set_cancel(); scheduler.step(absl::ZeroDuration()); - EXPECT_EQ(engine.collected_sequences.size(), 3u); + ASSERT_EQ(engine.collected_sequences.size(), 3u); + EXPECT_EQ(engine.collected_sequences.back(), + (std::vector{third->sequences().front().get()})); } TEST(ContinuousSchedulerTest, OverlapRetainsRequestsUntilPendingStepCompletes) { SchedulerOptions options = create_scheduler_options(64, 4, 0, 64, 1); - options.enable_schedule_overlap(true).disable_log_stats(true); - PipelinePhaseEngine engine; + options.enable_schedule_overlap(/*value=*/true) + .disable_log_stats(/*value=*/true) + .enable_disagg_pd(/*value=*/true) + .instance_role(/*value=*/InstanceRole::DECODE); + PipelinePhaseEngine engine(/*enable_linear_attention=*/true, + /*num_blocks=*/128, + /*instance_role=*/InstanceRole::DECODE); TestableContinuousScheduler scheduler(&engine, options); - auto request = generate_request_with_prompt_tokens({1, 2}, 16, 256); + auto* cache = engine.kv_cache_manager(); + const auto initial_free_blocks = cache->num_free_blocks(); + constexpr int32_t kMaxTokens = 16; + constexpr int32_t kMaxContextLen = 256; + auto request = generate_request_with_prompt_tokens( + /*prompt_token_ids=*/{1, 2}, kMaxTokens, kMaxContextLen); + const auto next_request = generate_request_with_prompt_tokens( + /*prompt_token_ids=*/{3, 4}, kMaxTokens, kMaxContextLen); const std::weak_ptr weak_request = request; Sequence* sequence = request->sequences().front().get(); - bool alive_at_collection = false; + Sequence* next_sequence = next_request->sequences().front().get(); + ASSERT_TRUE(scheduler.add_request(request)); + scheduler.step(absl::ZeroDuration()); + const Slice kv_blocks = + sequence->kv_state().blocks(/*type=*/BlockType::KV); + ASSERT_FALSE(kv_blocks.empty()); + const int32_t kv_id = kv_blocks.front().id(); + const int32_t linear_id = sequence->get_linear_state_slot_id(); + ASSERT_GE(linear_id, 0); engine.on_collect = [&](const BatchGroup& batches) { - const auto retained_request = weak_request.lock(); - alive_at_collection = retained_request != nullptr; - ASSERT_NE(retained_request, nullptr); + EXPECT_FALSE(weak_request.expired()); EXPECT_EQ(batches.front()[0], sequence); - EXPECT_EQ(retained_request->sequences().front().get(), sequence); + ASSERT_TRUE(cache->allocate(next_sequence)); + EXPECT_NE( + next_sequence->kv_state().blocks(/*type=*/BlockType::KV).front().id(), + kv_id); + EXPECT_NE(next_sequence->get_linear_state_slot_id(), linear_id); }; - scheduler.schedule_batch_for_test({request}); - scheduler.step(absl::ZeroDuration()); + request->set_cancel(); request.reset(); - EXPECT_FALSE(weak_request.expired()); - - // Preparing the empty batch releases the running set before collection. scheduler.step(absl::ZeroDuration()); - EXPECT_TRUE(alive_at_collection); + scheduler.wait_for_responses(); EXPECT_TRUE(weak_request.expired()); EXPECT_EQ(engine.calls, (std::vector{"step", "consume"})); + cache->deallocate(next_sequence); + EXPECT_EQ(cache->num_free_blocks(), initial_free_blocks); + + options.priority_strategy(/*value=*/"priority"); + PipelinePhaseEngine pressure_engine(/*enable_linear_attention=*/false, + /*num_blocks=*/4, + /*instance_role=*/InstanceRole::DECODE); + TestableContinuousScheduler pressure_scheduler(&pressure_engine, options); + const auto make_decode_request = [&](const std::vector& prompt) { + auto request = + generate_request_with_prompt_tokens(prompt, kMaxTokens, kMaxContextLen); + make_request_decode_ready(request); + return request; + }; + auto runnable = make_decode_request(/*prompt=*/{1}); + auto waiting = make_decode_request(/*prompt=*/{1, 2, 3}); + auto victim = make_decode_request(/*prompt=*/{3}); + runnable->state().scheduler_param.priority = RequestPriority::HIGH; + victim->state().scheduler_param.priority = RequestPriority::LOW; + ASSERT_TRUE(pressure_scheduler.add_request(runnable)); + ASSERT_TRUE(pressure_scheduler.add_request(waiting)); + ASSERT_TRUE(pressure_scheduler.add_request(victim)); + pressure_scheduler.step(absl::ZeroDuration()); + ASSERT_EQ(pressure_engine.kv_cache_manager()->num_free_blocks().front(), 0u); + + Sequence* waiting_sequence = waiting->sequences().front().get(); + waiting_sequence->kv_state().set_kv_cache_tokens_num( + waiting_sequence->num_tokens()); + waiting_sequence->append_token(Token(/*id=*/4)); + pressure_scheduler.step(absl::ZeroDuration()); + ASSERT_EQ(pressure_engine.calls, + (std::vector{"step", "step", "consume", "consume"})); + EXPECT_EQ(pressure_engine.collected_sequences.back(), + (std::vector{runnable->sequences().front().get()})); + EXPECT_FALSE(victim->preempted()); + + pressure_scheduler.step(absl::ZeroDuration()); + EXPECT_TRUE(victim->preempted()); + EXPECT_EQ(waiting_sequence->kv_state().num_blocks(/*type=*/BlockType::KV), + 2u); } TEST(ContinuousSchedulerTest, ShutdownDrainsForwardBeforeReleasingCacheLease) { @@ -1704,14 +1708,10 @@ TEST(ContinuousSchedulerTest, ASSERT_TRUE(initial_batch.front().empty()); ASSERT_EQ(engine->prefetch_calls(), 1u); - std::promise prepared; - auto preparation_finished = prepared.get_future(); - scheduler.notify_after_next_prepare_batch(prepared); auto scheduled = std::async(std::launch::async, [&scheduler] { return scheduler.schedule_request(absl::Seconds(1)); }); - ASSERT_EQ(preparation_finished.wait_for(std::chrono::seconds(1)), - std::future_status::ready); + ASSERT_TRUE(scheduler.wait_until_armed()); engine->set_prefetch_ready(true); ASSERT_EQ(scheduled.wait_for(std::chrono::milliseconds(100)), diff --git a/tests/core/scheduler/offline_generation_test.cpp b/tests/core/scheduler/offline_generation_test.cpp index 1a96afe00d..41dd8f01ba 100644 --- a/tests/core/scheduler/offline_generation_test.cpp +++ b/tests/core/scheduler/offline_generation_test.cpp @@ -26,6 +26,7 @@ limitations under the License. #include "core/distributed_runtime/engine.h" #include "core/kv_cache/manager/block_manager_pool.h" #include "core/scheduler/continuous_scheduler.h" +#include "core/scheduler/scheduler_notifier_test_peer.h" namespace xllm { namespace { @@ -101,23 +102,9 @@ class OfflineGenerationScheduler final : public ContinuousScheduler<> { pending_step_->batches.front().add(request->sequences().front().get()); } - void notify_after_next_prepare_batch(std::promise& notification) { - prepared_notification_ = ¬ification; + bool wait_until_armed() const { + return SchedulerNotifierTestPeer::wait_until_armed(*notifier_); } - - protected: - BatchGroup prepare_batch() override { - BatchGroup batch = ContinuousSchedulerBase::prepare_batch(); - std::promise* notification = - std::exchange(prepared_notification_, nullptr); - if (notification != nullptr) { - notification->set_value(); - } - return batch; - } - - private: - std::promise* prepared_notification_ = nullptr; }; SchedulerOptions generation_options(bool overlap) { @@ -225,14 +212,10 @@ TEST(OfflineGenerationTest, OverlapWaitsForAdmissionAndResponse) { return true; }; scheduler.incr_pending_requests(/*count=*/1); - std::promise prepared; - std::future preparing = prepared.get_future(); - scheduler.notify_after_next_prepare_batch(prepared); auto generated = std::async(std::launch::async, [&]() { scheduler.generate_with_schedule_overlap(); }); - EXPECT_EQ(preparing.wait_for(std::chrono::seconds(5)), - std::future_status::ready); + EXPECT_TRUE(scheduler.wait_until_armed()); EXPECT_NE(generated.wait_for(std::chrono::seconds(0)), std::future_status::ready); EXPECT_TRUE(scheduler.add_request(request)); diff --git a/tests/core/scheduler/scheduler_policy_test.cpp b/tests/core/scheduler/scheduler_policy_test.cpp index 48cdb50320..59024c1db2 100644 --- a/tests/core/scheduler/scheduler_policy_test.cpp +++ b/tests/core/scheduler/scheduler_policy_test.cpp @@ -1701,7 +1701,7 @@ TEST(SchedulerPolicyTest, UnifiedReclaimsMutuallyBlockedChunksWhenIdle) { .options = options, .min_speculative_tokens_required = 0, .enable_prefix_cache = false, - .has_pending_vmm_batch = pending_release, + .has_pending_kv_batch_ = pending_release, }; const ScheduleBudget initial_budget{ .remaining_token_budget = 32, @@ -2021,7 +2021,7 @@ TEST_P(PendingVmmBatchPolicyTest, RetainsRequestsUntilBatchReleasesBlocks) { .options = options, .min_speculative_tokens_required = 0, .enable_prefix_cache = false, - .has_pending_vmm_batch = true, + .has_pending_kv_batch_ = true, }; const ScheduleBudget initial_budget{ .remaining_token_budget = 1024, @@ -2045,7 +2045,7 @@ TEST_P(PendingVmmBatchPolicyTest, RetainsRequestsUntilBatchReleasesBlocks) { } block_manager_pool.deallocate_without_cache(pending_sequence); - state.has_pending_vmm_batch = false; + state.has_pending_kv_batch_ = false; budget = initial_budget; policy->schedule(state, budget, finished); diff --git a/xllm/core/common/types.h b/xllm/core/common/types.h index 3e30229c0a..cc76976489 100644 --- a/xllm/core/common/types.h +++ b/xllm/core/common/types.h @@ -151,9 +151,13 @@ class InstanceRole { } } - InstanceRole(RoleType role) : role_(role) {} + constexpr InstanceRole(RoleType role) : role_(role) {} bool can_serve_prefill() const { return role_ == PREFILL || role_ == MIX; } operator RoleType() const { return role_; } + + constexpr bool can_receive_pd_kv() const { + return role_ == DECODE || role_ == MIX; + } explicit operator bool() const = delete; bool operator==(InstanceRole rhs) const { return role_ == rhs.role_; } diff --git a/xllm/core/distributed_runtime/llm_engine.cpp b/xllm/core/distributed_runtime/llm_engine.cpp index b741c7fdab..5c2e6d5203 100644 --- a/xllm/core/distributed_runtime/llm_engine.cpp +++ b/xllm/core/distributed_runtime/llm_engine.cpp @@ -527,8 +527,10 @@ std::vector LLMEngine::collect_step_outputs( // because the experts on each worker are different, // and the controller needs the token load of every expert shard. // so we can not skip any worker. - if (eplb_controller_ != nullptr && - eplb_controller_->requires_all_worker_results()) { + if ((options_.enable_disagg_pd() && + options_.instance_role().can_receive_pd_kv()) || + (eplb_controller_ != nullptr && + eplb_controller_->requires_all_worker_results())) { stride = 1; } diff --git a/xllm/core/distributed_runtime/vlm_engine.cpp b/xllm/core/distributed_runtime/vlm_engine.cpp index 72c4ea4124..69dbf83949 100644 --- a/xllm/core/distributed_runtime/vlm_engine.cpp +++ b/xllm/core/distributed_runtime/vlm_engine.cpp @@ -517,7 +517,10 @@ std::vector VLMEngine::collect_step_outputs( // cause the output on other workers is the same as that on driver. // Under data parallelism (DP), we need to get dp_size outputs. // The `stride` means the workers num we can skip. - const uint32_t stride = eplb_controller_ ? 1 : dp_local_size_; + const bool wait_all_ranks = options_.enable_disagg_pd() && + options_.instance_role().can_receive_pd_kv(); + const uint32_t stride = + eplb_controller_ || wait_all_ranks ? 1 : dp_local_size_; auto last_step_results = collect_worker_step_results( worker_clients_, stride, &WorkerClient::get_last_vlm_step_result_async); diff --git a/xllm/core/distributed_runtime/worker_service.cpp b/xllm/core/distributed_runtime/worker_service.cpp index cbd084ccda..0da55629db 100644 --- a/xllm/core/distributed_runtime/worker_service.cpp +++ b/xllm/core/distributed_runtime/worker_service.cpp @@ -328,23 +328,6 @@ WorkerService::WorkerService(runtime::Options options, /*pool_name=*/"WorkerService.request"); } -WorkerService::WorkerService(runtime::Options options, - const torch::Device& device, - std::unique_ptr worker) - : options_(options), - initialized_(true), - device_(device), - worker_(std::move(worker)) { - device_.set_device(); - device_.init_device_context(); - stream_ = device_.get_stream_from_pool(); - threadpool_ = std::make_unique( - /*num_threads=*/4, - /*init_func=*/[this]() mutable { device_.set_device(); }, - /*cpu_binding=*/false, - /*pool_name=*/"WorkerService.request"); -} - WorkerService::~WorkerService() { begin_shutdown(); if (polling_thread_ && polling_thread_->joinable()) { @@ -610,9 +593,14 @@ void WorkerService::GetLastLLMStepResult( return; } auto output = std::move(worker_->get_last_step_result_async()).get(); + if (!output) { + controller->SetFailed( + /*reason=*/"Worker stopped before delivering the step result"); + return; + } ForwardOutput cpu_output; std::vector speculative_token_stats; - if (output.has_value()) { + if (worker_->is_driver() || options_.eplb_worker_config().enabled) { collect_llm_output(*output, cpu_output, speculative_token_stats); } // Embedding-only results are valid completed outputs. @@ -802,9 +790,14 @@ void WorkerService::GetLastVLMStepResult( return; } auto output = std::move(worker_->get_last_step_result_async()).get(); + if (!output) { + controller->SetFailed( + /*reason=*/"Worker stopped before delivering the step result"); + return; + } ForwardOutput cpu_output; std::vector speculative_token_stats; - if (output.has_value()) { + if (worker_->is_driver() || options_.eplb_worker_config().enabled) { collect_vlm_output(*output, cpu_output, speculative_token_stats); } // Embedding-only results are valid completed outputs. diff --git a/xllm/core/distributed_runtime/worker_service.h b/xllm/core/distributed_runtime/worker_service.h index 2a1fddd0bb..046e06166f 100644 --- a/xllm/core/distributed_runtime/worker_service.h +++ b/xllm/core/distributed_runtime/worker_service.h @@ -15,6 +15,7 @@ limitations under the License. #pragma once +#include #include #include @@ -27,9 +28,6 @@ namespace xllm { class WorkerService : public proto::DistributeWorker { public: WorkerService(runtime::Options options, const torch::Device& device); - WorkerService(runtime::Options options, - const torch::Device& device, - std::unique_ptr worker); virtual ~WorkerService(); @@ -194,7 +192,7 @@ class WorkerService : public proto::DistributeWorker { // runtime options runtime::Options options_; - bool initialized_; + std::atomic initialized_; Device device_; diff --git a/xllm/core/framework/request/sequence_kv_state.cpp b/xllm/core/framework/request/sequence_kv_state.cpp index 41eb63dd30..e8bce26544 100644 --- a/xllm/core/framework/request/sequence_kv_state.cpp +++ b/xllm/core/framework/request/sequence_kv_state.cpp @@ -25,13 +25,6 @@ limitations under the License. namespace xllm { namespace { -// Empty block list returned by read views when a BlockType is absent from the -// map. Static so the returned Slice / reference stays valid. -const std::vector& empty_blocks() { - static const std::vector kEmpty; - return kEmpty; -} - void try_replace_unique_blocks(std::vector&& matched_shared_blocks, uint32_t* num_owned_shared_blocks, std::vector* owned_blocks) { @@ -179,7 +172,7 @@ void KVCacheState::incr_kv_cache_tokens_num_up_to(size_t new_target) { Slice KVCacheState::blocks(const CachePartitionId& id) const { const auto it = composite_blocks_.find(id); - return it == composite_blocks_.end() ? Slice(empty_blocks()) + return it == composite_blocks_.end() ? Slice() : Slice(it->second); } @@ -510,7 +503,6 @@ void KVCacheState::reset() { restore_tokens_.clear(); num_owned_shared_blocks_.clear(); num_cached_blocks_.clear(); - pushed_local_block_count_ = 0; for (auto& [type, blocks] : composite_blocks_) { Block::release(std::move(blocks)); } diff --git a/xllm/core/framework/request/sequence_kv_state.h b/xllm/core/framework/request/sequence_kv_state.h index 473e9f5328..bc8f04ac10 100644 --- a/xllm/core/framework/request/sequence_kv_state.h +++ b/xllm/core/framework/request/sequence_kv_state.h @@ -19,6 +19,7 @@ limitations under the License. #include #include #include +#include #include #include @@ -99,6 +100,16 @@ class KVCacheState { std::vector* mutable_blocks(BlockType type); // Number of blocks held under `type`. size_t num_blocks(BlockType type) const; + auto block_groups(std::optional excluded_type) const { + const CachePartitionId* excluded_partition = + excluded_type ? &partition_id(*excluded_type) : nullptr; + return composite_blocks_ | + std::views::filter([excluded_partition](const auto& group) { + return excluded_partition == nullptr || + group.first != *excluded_partition; + }) | + std::views::values; + } // True if the sequence holds any cache-bearing blocks (KV / SWA / C4 / C128). // Excludes EMBEDDING, which is a per-sequence resource, not token cache. Used // to decide whether an allocation that started from an empty sequence should @@ -190,13 +201,6 @@ class KVCacheState { void set_transfer_kv_info(TransferKVInfo&& info); std::optional& transfer_kv_info(); - uint32_t pushed_local_block_count() const { - return pushed_local_block_count_; - } - void set_pushed_local_block_count(uint32_t n) { - pushed_local_block_count_ = n; - } - size_t next_transfer_block_idx() const; void advance_transfer_block_idx(size_t idx); @@ -253,10 +257,6 @@ class KVCacheState { // Pre-grow cache insert cursor per partition. See num_cached_blocks() above. std::map num_cached_blocks_; - - // Number of local KV blocks already pushed to the decode instance. - // Used for incremental push in chunked prefill + PD disagg mode. - uint32_t pushed_local_block_count_ = 0; }; } // namespace xllm diff --git a/xllm/core/kv_cache/block/block.cpp b/xllm/core/kv_cache/block/block.cpp index 54b04f85d9..50927b317a 100644 --- a/xllm/core/kv_cache/block/block.cpp +++ b/xllm/core/kv_cache/block/block.cpp @@ -75,35 +75,33 @@ void Block::release(std::vector blocks) { } Block::Block(int32_t id, BlockManager* manager) - : id_(id), ref_count_(new std::atomic(1)), manager_(manager) { - // get the block size from the manager - size_ = manager_ == nullptr ? 0 : manager_->block_size(); -} + : id_(id), + size_(manager == nullptr ? 0 + : static_cast(manager->block_size())), + pin_block_(false), + ref_count_(new std::atomic{/*desired=*/1}), + manager_(manager) {} -Block::~Block() { - // decrease reference count - dec_ref_count(); -} +Block::~Block() { dec_ref_count(); } -// copy constructor -Block::Block(const Block& other) +Block::Block(const Block& other, bool pin_block) : id_(other.id_), size_(other.size_), + pin_block_(pin_block || other.pin_block_), ref_count_(other.ref_count_), manager_(other.manager_) { memcpy(hash_value_, other.hash_value_, XXH3_128BITS_HASH_VALUE_LEN); - // increase reference count inc_ref_count(); } -// copy assignment Block& Block::operator=(const Block& other) { if (this != &other) { dec_ref_count(); id_ = other.id_; size_ = other.size_; + pin_block_ = other.pin_block_; manager_ = other.manager_; ref_count_ = other.ref_count_; @@ -117,11 +115,11 @@ Block& Block::operator=(const Block& other) { Block::Block(Block&& other) noexcept : id_(other.id_), size_(other.size_), + pin_block_(other.pin_block_), ref_count_(other.ref_count_), manager_(other.manager_) { memcpy(hash_value_, other.hash_value_, XXH3_128BITS_HASH_VALUE_LEN); - // reset other without adjusting the reference count other.id_ = -1; other.size_ = 0; other.ref_count_ = nullptr; @@ -134,6 +132,7 @@ Block& Block::operator=(Block&& other) noexcept { id_ = other.id_; size_ = other.size_; + pin_block_ = other.pin_block_; manager_ = other.manager_; ref_count_ = other.ref_count_; @@ -151,7 +150,7 @@ Block& Block::operator=(Block&& other) noexcept { void Block::inc_ref_count() { if (ref_count_ != nullptr) { // Another alias appearing only needs atomicity, not ordering, so relaxed. - ref_count_->fetch_add(1, std::memory_order_relaxed); + ref_count_->fetch_add(ref_count_delta(), std::memory_order_relaxed); } } @@ -161,12 +160,11 @@ void Block::dec_ref_count() { } // acq_rel pairs the releasing decrements with the acquiring final one, so the // thread that drives the count to zero observes all prior alias writes before - // it frees. fetch_sub returns the previous value; == 1 means we just hit - // zero. - if (ref_count_->fetch_sub(1, std::memory_order_acq_rel) == 1) { - // release the reference count memory + // it frees. + const uint64_t prior = + ref_count_->fetch_sub(ref_count_delta(), std::memory_order_acq_rel); + if (static_cast(prior) == 1) { delete ref_count_; - // return the block id to the manager if (manager_ != nullptr) { manager_->free(id_); } diff --git a/xllm/core/kv_cache/block/block.h b/xllm/core/kv_cache/block/block.h index e853ccacab..bd363ae7ca 100644 --- a/xllm/core/kv_cache/block/block.h +++ b/xllm/core/kv_cache/block/block.h @@ -123,10 +123,10 @@ class Block final { public: ~Block(); - Block() = default; + Block() noexcept : size_(0), pin_block_(false), hash_value_{} {} Block(int32_t id, BlockManager* allocator); - Block(const Block& other); + Block(const Block& other, bool pin_block = false); Block& operator=(const Block& other); Block(Block&& other) noexcept; @@ -137,25 +137,23 @@ class Block final { // still uses the ordinary destructor, which only drops a cache reference. static void release(std::vector blocks); - // get the block id constexpr int32_t id() const { return id_; } - // get the block size constexpr uint32_t size() const { return size_; } - // get the reference count, 0 if the block is invalid after move uint32_t ref_count() const { - return ref_count_ == nullptr ? 0 - : ref_count_->load(std::memory_order_acquire); + return static_cast(load_packed_ref_counts()); + } + + uint32_t unpinned_ref_count() const { + const uint64_t counts = load_packed_ref_counts(); + return static_cast(counts) - static_cast(counts >> 32); } - // check if the block is shared bool is_shared() const { return ref_count() > 1; } - // check if the block is valid bool is_valid() const { return id_ >= 0 && ref_count_ != nullptr; } - // owner manager that allocated this block. BlockManager* manager() const { return manager_; } // Reassign this block's owning manager. Used by concurrency wrappers (e.g. @@ -168,36 +166,33 @@ class Block final { // for recording the hash value of the current block and previous blocks. // hash_value_ = Hash(current_block, Hash(pre_block)). const uint8_t* get_immutable_hash_value() const { return hash_value_; } - uint8_t* get_mutable_hash_value() { return hash_value_; } void set_hash_value(const uint8_t* hash_value) { memcpy(hash_value_, hash_value, XXH3_128BITS_HASH_VALUE_LEN); } - constexpr uint32_t get_hash_value_len() const { - return XXH3_128BITS_HASH_VALUE_LEN; + private: + uint64_t load_packed_ref_counts() const { + return ref_count_ == nullptr ? 0 + : ref_count_->load(std::memory_order_acquire); } - private: - // increase reference count - void inc_ref_count(); + uint64_t ref_count_delta() const { + return 1 + (static_cast(pin_block_) << 32); + } - // decrease reference count + void inc_ref_count(); void dec_ref_count(); - // block id int32_t id_ = -1; - // block size - uint32_t size_ = 0; + uint32_t size_ : 31; + bool pin_block_ : 1; - // reference count, shared across Block aliases of the same physical block. - // Atomic because aliases are copied/destroyed across threads outside the - // owning BlockManager's lock (e.g. disagg-PD scheduler match vs. prefill - // threadpool sequence teardown), so inc/dec must not race. - std::atomic* ref_count_ = nullptr; + // Aliases change both counts atomically outside the manager's lock. + // Total references occupy the low half and pins occupy the high half. + std::atomic* ref_count_ = nullptr; - // manager that manages this block BlockManager* manager_ = nullptr; uint8_t hash_value_[XXH3_128BITS_HASH_VALUE_LEN]; @@ -212,6 +207,7 @@ class KVCacheBlockLease final { std::vector blocks, std::vector> retained_leases = {}, std::shared_ptr producer = {}); + KVCacheBlockLease(KVCacheBlockLease&&) noexcept = default; ~KVCacheBlockLease(); const std::shared_ptr& prefix_producer() const { @@ -229,9 +225,4 @@ class KVCacheBlockLease final { std::vector> retained_leases_; }; -// equal operator, mainly used for testing -inline constexpr bool operator==(const Block& lhs, const Block& rhs) { - return lhs.id() == rhs.id(); -} - } // namespace xllm diff --git a/xllm/core/kv_cache/block/linear_state_block_manager.cpp b/xllm/core/kv_cache/block/linear_state_block_manager.cpp index c1c697e807..d4bfc5871c 100644 --- a/xllm/core/kv_cache/block/linear_state_block_manager.cpp +++ b/xllm/core/kv_cache/block/linear_state_block_manager.cpp @@ -41,8 +41,9 @@ RecurrentStateGrowthPlan LinearStateBlockManager::plan_state_growth( CHECK(blocks.empty() || blocks.back().is_valid()); RecurrentLiveSlot live_slot = RecurrentLiveSlot::ABSENT; if (!blocks.empty()) { - live_slot = blocks.back().is_shared() ? RecurrentLiveSlot::SHARED - : RecurrentLiveSlot::PRIVATE; + live_slot = blocks.back().unpinned_ref_count() > 1 + ? RecurrentLiveSlot::SHARED + : RecurrentLiveSlot::PRIVATE; } return RecurrentStateGrowthPlan( block_size(), diff --git a/xllm/core/kv_cache/prefix/host_prefix_cache.cpp b/xllm/core/kv_cache/prefix/host_prefix_cache.cpp index 8d4624936c..b62898c048 100644 --- a/xllm/core/kv_cache/prefix/host_prefix_cache.cpp +++ b/xllm/core/kv_cache/prefix/host_prefix_cache.cpp @@ -798,7 +798,7 @@ void HostPrefixCache::save(Sequence* sequence) { for (size_t i = 0; i < comparable_blocks; ++i) { Block& hbm_block = (*hbm_blocks)[i]; Block& host_block = (*host_blocks)[i]; - if (hbm_block.ref_count() != expected_hbm_refs || + if (hbm_block.unpinned_ref_count() != expected_hbm_refs || host_block.ref_count() != 1) { continue; } diff --git a/xllm/core/kv_cache/storage/vmm_kv_page_allocator.h b/xllm/core/kv_cache/storage/vmm_kv_page_allocator.h index bd903717ef..8cd4bfa47c 100644 --- a/xllm/core/kv_cache/storage/vmm_kv_page_allocator.h +++ b/xllm/core/kv_cache/storage/vmm_kv_page_allocator.h @@ -42,20 +42,14 @@ class VmmKVPageAllocator { const std::string& model_id, int32_t dp_rank, const std::vector& virtual_page_ids) = 0; - virtual void trim_kv_cache(const std::string& model_id, int32_t dp_rank) = 0; // Includes resident reserve pages and currently budgeted growth. This is // a scheduling hint; alloc_kv_cache_page performs the actual reservation. virtual size_t get_num_available_virt_pages(const std::string& model_id, int32_t dp_rank) const = 0; - virtual size_t get_num_inuse_virt_pages(const std::string& model_id, - int32_t dp_rank) const = 0; - virtual size_t get_num_reserved_virt_pages(const std::string& model_id, - int32_t dp_rank) const = 0; virtual int64_t get_virt_page_id(int64_t block_id, size_t block_memory_size) const = 0; virtual size_t page_size() const = 0; - virtual size_t phy_pages_per_virt_page(const std::string& model_id) const = 0; }; } // namespace xllm diff --git a/xllm/core/kv_cache/storage/vmm_kv_page_allocator_impl.cpp b/xllm/core/kv_cache/storage/vmm_kv_page_allocator_impl.cpp index 418cb8d2fc..d354e0491d 100644 --- a/xllm/core/kv_cache/storage/vmm_kv_page_allocator_impl.cpp +++ b/xllm/core/kv_cache/storage/vmm_kv_page_allocator_impl.cpp @@ -130,7 +130,6 @@ bool VmmKVPageAllocatorImpl::register_model( return false; } ModelState& state = it->second; - state.num_layers = num_layers; const size_t symmetric_pages = 2 * static_cast(num_layers); state.phy_pages_per_virt_page = physical_pages_per_virtual_page == 0 ? symmetric_pages @@ -164,60 +163,12 @@ bool VmmKVPageAllocatorImpl::register_model( return true; } -bool VmmKVPageAllocatorImpl::unregister_model(const std::string& model_id) { - std::unique_lock lock(mtx_); - auto it = model_states_.find(model_id); - if (it == model_states_.end()) { - return false; - } - ModelState& state = it->second; - const auto has_allocated_pages = [&state] { - return std::any_of(state.dp_group_pages.begin(), - state.dp_group_pages.end(), - [](const DpGroupPages& pages) { - return !pages.allocated_virt_page_list.empty(); - }); - }; - if (state.unregistering || state.transition != ModelTransition::IDLE || - state.transition_waiters > 0 || has_allocated_pages()) { - LOG(ERROR) << "Cannot unregister active KV cache model " << model_id; - return false; - } - state.unregistering = true; - cond_.notify_all(); - cond_.wait(lock, [&state] { return state.pending_map_ops == 0; }); - // A synchronous allocation already mapping when cleanup began can finish - // with a live page. Keep its state available for the owner to recycle it. - if (has_allocated_pages()) { - state.unregistering = false; - cond_.notify_all(); - return false; - } - const bool mapped = state.kv_cache_mapped; - const auto plan = snapshot_pages(state); - lock.unlock(); - if (mapped) { - unmap_pages(model_id, plan); - for (int32_t dp_rank = 0; dp_rank < dp_size_; ++dp_rank) { - page_budget_.release_pages(model_id, - dp_rank, - plan.dp_group_page_ids[dp_rank].size() * - plan.physical_pages_per_virtual_page); - } - } - lock.lock(); - model_states_.erase(model_id); - return true; -} - void VmmKVPageAllocatorImpl::start_prealloc_thread( const std::string& model_id) { std::lock_guard lock(mtx_); CHECK(initialized_) << "VmmKVPageAllocatorImpl not initialized"; CHECK(!shutting_down_) << "VmmKVPageAllocatorImpl is shutting down"; ModelState& state = get_model_state(model_id); - CHECK(!state.unregistering) - << "Cannot preallocate for unregistering model " << model_id; state.ready_for_preallocation = true; if (!enable_prealloc_) { return; @@ -322,7 +273,7 @@ void VmmKVPageAllocatorImpl::free_kv_cache_pages( << "KV page " << page_id << " is not allocated for model " << model_id; } pages.num_free_virt_pages += virtual_page_ids.size(); - if (!state.kv_cache_mapped) { + if (state.suspended) { pages.recycle_free_virt_pages(virtual_page_ids); return; } @@ -350,34 +301,6 @@ void VmmKVPageAllocatorImpl::free_kv_cache_pages( cond_.notify_all(); } -void VmmKVPageAllocatorImpl::trim_kv_cache(const std::string& model_id, - int32_t dp_rank) { - std::unique_lock lock(mtx_); - validate_dp_rank(dp_rank); - ModelState& state = get_model_state(model_id); - wait_for_model_transition(state, lock); - auto& pages = state.dp_group_pages[dp_rank]; - std::vector pages_to_unmap(pages.reserved_virt_page_list.begin(), - pages.reserved_virt_page_list.end()); - pages.reserved_virt_page_list.clear(); - if (!state.kv_cache_mapped) { - pages.recycle_free_virt_pages(pages_to_unmap); - return; - } - if (pages_to_unmap.empty()) { - return; - } - ++state.pending_map_ops; - lock.unlock(); - unmap_virtual_pages(model_id, dp_rank, pages_to_unmap); - lock.lock(); - pages.recycle_free_virt_pages(pages_to_unmap); - page_budget_.release_pages( - model_id, dp_rank, pages_to_unmap.size() * state.phy_pages_per_virt_page); - --state.pending_map_ops; - cond_.notify_all(); -} - std::optional VmmKVPageAllocatorImpl::begin_suspend( const std::string& model_id) { std::unique_lock lock(mtx_); @@ -397,7 +320,6 @@ void VmmKVPageAllocatorImpl::finish_suspend(const std::string& model_id) { std::lock_guard lock(mtx_); ModelState& state = get_model_state(model_id); CHECK(state.transition == ModelTransition::SUSPENDING); - state.kv_cache_mapped = false; state.transition = ModelTransition::IDLE; cond_.notify_all(); } @@ -421,7 +343,6 @@ void VmmKVPageAllocatorImpl::finish_resume(const std::string& model_id, ModelState& state = get_model_state(model_id); CHECK(state.transition == ModelTransition::RESUMING); state.suspended = !success; - state.kv_cache_mapped = success; state.transition = ModelTransition::IDLE; cond_.notify_all(); } @@ -471,7 +392,7 @@ size_t VmmKVPageAllocatorImpl::get_num_available_virt_pages( std::lock_guard lock(mtx_); validate_dp_rank(dp_rank); const ModelState& state = get_model_state(model_id); - if (shutting_down_ || state.unregistering || state.suspended || + if (shutting_down_ || state.suspended || state.transition != ModelTransition::IDLE) { return 0; } @@ -483,34 +404,6 @@ size_t VmmKVPageAllocatorImpl::get_num_available_virt_pages( return pages.reserved_virt_page_list.size() + growth; } -size_t VmmKVPageAllocatorImpl::get_num_free_virt_pages( - const std::string& model_id, - int32_t dp_rank) const { - std::lock_guard lock(mtx_); - validate_dp_rank(dp_rank); - return get_model_state(model_id).dp_group_pages[dp_rank].num_free_virt_pages; -} - -size_t VmmKVPageAllocatorImpl::get_num_inuse_virt_pages( - const std::string& model_id, - int32_t dp_rank) const { - std::lock_guard lock(mtx_); - validate_dp_rank(dp_rank); - const ModelState& state = get_model_state(model_id); - return state.num_total_virt_pages - - state.dp_group_pages[dp_rank].num_free_virt_pages; -} - -size_t VmmKVPageAllocatorImpl::get_num_reserved_virt_pages( - const std::string& model_id, - int32_t dp_rank) const { - std::lock_guard lock(mtx_); - validate_dp_rank(dp_rank); - return get_model_state(model_id) - .dp_group_pages[dp_rank] - .reserved_virt_page_list.size(); -} - size_t VmmKVPageAllocatorImpl::get_num_total_virt_pages( const std::string& model_id) const { std::lock_guard lock(mtx_); @@ -540,17 +433,6 @@ int64_t VmmKVPageAllocatorImpl::get_offset(int64_t virtual_page_id) const { return virtual_page_id * static_cast(page_size_); } -int64_t VmmKVPageAllocatorImpl::num_layers(const std::string& model_id) const { - std::lock_guard lock(mtx_); - return get_model_state(model_id).num_layers; -} - -size_t VmmKVPageAllocatorImpl::phy_pages_per_virt_page( - const std::string& model_id) const { - std::lock_guard lock(mtx_); - return get_model_state(model_id).phy_pages_per_virt_page; -} - VmmKVPageAllocatorImpl::ModelState& VmmKVPageAllocatorImpl::get_model_state( const std::string& model_id) { auto it = model_states_.find(model_id); @@ -568,15 +450,10 @@ VmmKVPageAllocatorImpl::get_model_state(const std::string& model_id) const { void VmmKVPageAllocatorImpl::wait_for_model_transition( ModelState& state, std::unique_lock& lock) { - CHECK(!shutting_down_) << "VmmKVPageAllocatorImpl is shutting down"; - CHECK(!state.unregistering) << "KV cache model is unregistering"; - ++state.transition_waiters; cond_.wait(lock, [this, &state] { return shutting_down_ || state.transition == ModelTransition::IDLE; }); - --state.transition_waiters; CHECK(!shutting_down_) << "VmmKVPageAllocatorImpl is shutting down"; - CHECK(!state.unregistering) << "KV cache model is unregistering"; } KVCacheMappingPlan VmmKVPageAllocatorImpl::snapshot_pages( @@ -680,8 +557,8 @@ void VmmKVPageAllocatorImpl::prealloc_worker() { prealloc_needed_ = false; batches.reserve(model_states_.size() * static_cast(dp_size_)); for (auto& [model_id, state] : model_states_) { - if (!state.ready_for_preallocation || state.unregistering || - state.suspended || state.transition != ModelTransition::IDLE) { + if (!state.ready_for_preallocation || state.suspended || + state.transition != ModelTransition::IDLE) { continue; } for (int32_t dp_rank = 0; dp_rank < dp_size_; ++dp_rank) { @@ -722,7 +599,7 @@ void VmmKVPageAllocatorImpl::prealloc_worker() { { std::lock_guard lock(mtx_); ModelState& state = get_model_state(batch.model_id); - if (state.unregistering || state.suspended || !prealloc_running_) { + if (state.suspended || !prealloc_running_) { auto& pages = state.dp_group_pages[batch.dp_rank]; pages.restore_free_virt_pages(batch.virtual_page_ids); page_budget_.release_pages( diff --git a/xllm/core/kv_cache/storage/vmm_kv_page_allocator_impl.h b/xllm/core/kv_cache/storage/vmm_kv_page_allocator_impl.h index 7c630e7869..5aa0f1db35 100644 --- a/xllm/core/kv_cache/storage/vmm_kv_page_allocator_impl.h +++ b/xllm/core/kv_cache/storage/vmm_kv_page_allocator_impl.h @@ -66,10 +66,6 @@ class VmmKVPageAllocatorImpl final : public VmmKVPageAllocator { int64_t num_layers, size_t physical_pages_per_virtual_page = 0, size_t max_virtual_pages = 0); - // The caller must stop model operations and destroy every page-state user - // first. Refuses live allocations or an unfinished residency transition. - // Drains preallocation, releases resident reserves, then forgets the model. - bool unregister_model(const std::string& model_id); // Stops and joins background allocation before budget and mapping resources // disappear. No caller may start further allocator operations after shutdown // begins. @@ -83,7 +79,6 @@ class VmmKVPageAllocatorImpl final : public VmmKVPageAllocator { const std::string& model_id, int32_t dp_rank, const std::vector& virtual_page_ids) override; - void trim_kv_cache(const std::string& model_id, int32_t dp_rank) override; // begin_* freezes allocation, recycling and preallocation until finish_*. // Suspend also drains every reserved or executing mapping batch before @@ -100,19 +95,10 @@ class VmmKVPageAllocatorImpl final : public VmmKVPageAllocator { size_t get_num_available_virt_pages(const std::string& model_id, int32_t dp_rank) const override; - size_t get_num_free_virt_pages(const std::string& model_id, - int32_t dp_rank) const; - size_t get_num_inuse_virt_pages(const std::string& model_id, - int32_t dp_rank) const override; - size_t get_num_reserved_virt_pages(const std::string& model_id, - int32_t dp_rank) const override; size_t get_num_total_virt_pages(const std::string& model_id) const; int64_t get_virt_page_id(int64_t block_id, size_t block_memory_size) const override; - int64_t get_offset(int64_t virtual_page_id) const; size_t page_size() const override { return page_size_; } - int64_t num_layers(const std::string& model_id) const; - size_t phy_pages_per_virt_page(const std::string& model_id) const override; private: static constexpr size_t kMinReservedPages = 8; @@ -144,17 +130,13 @@ class VmmKVPageAllocatorImpl final : public VmmKVPageAllocator { }; struct ModelState { - int64_t num_layers = 0; size_t num_total_virt_pages = 0; size_t phy_pages_per_virt_page = 0; size_t min_reserved_pages = kMinReservedPages; size_t max_reserved_pages = kMaxReservedPages; bool ready_for_preallocation = false; - bool unregistering = false; bool suspended = false; - bool kv_cache_mapped = true; ModelTransition transition = ModelTransition::IDLE; - size_t transition_waiters = 0; size_t pending_map_ops = 0; std::vector dp_group_pages; }; @@ -171,6 +153,7 @@ class VmmKVPageAllocatorImpl final : public VmmKVPageAllocator { std::unique_lock& lock); KVCacheMappingPlan snapshot_pages(const ModelState& state) const; void validate_dp_rank(int32_t dp_rank) const; + int64_t get_offset(int64_t virtual_page_id) const; bool map_virtual_pages(const std::string& model_id, int32_t dp_rank, const std::vector& virtual_page_ids, diff --git a/xllm/core/runtime/schedule_overlap.cpp b/xllm/core/runtime/schedule_overlap.cpp index 87fb2f7e68..6709f1da98 100644 --- a/xllm/core/runtime/schedule_overlap.cpp +++ b/xllm/core/runtime/schedule_overlap.cpp @@ -21,6 +21,7 @@ limitations under the License. #include #include +#include "core/platform/device.h" #include "core/runtime/json_object_decode_adapter.h" #include "core/runtime/vlm_forward_params.h" #include "core/runtime/worker_impl.h" @@ -33,11 +34,17 @@ limitations under the License. namespace xllm { ScheduleOverlap::ScheduleOverlap(bool is_driver, - bool enable_eplb, - bool retire_unconsumed_inputs) - : state_(/*publish_to_host=*/is_driver || enable_eplb, - /*retain_tokenless_output=*/enable_eplb, - retire_unconsumed_inputs) {} + const runtime::Options& options, + bool is_input_release_deferred) + : publish_output_(is_driver || options.eplb_worker_config().enabled), + wait_worker_completion_(options.enable_schedule_overlap() && + options.enable_disagg_pd() && + options.instance_role().can_receive_pd_kv()), + state_(/*publish_to_host=*/publish_output_ || wait_worker_completion_, + /*retain_tokenless_output=*/options.eplb_worker_config().enabled || + wait_worker_completion_, + /*retire_unconsumed_inputs=*/options.enable_schedule_overlap() || + is_input_release_deferred) {} template std::optional ScheduleOverlap::execute_impl(WorkerImpl& worker, @@ -51,28 +58,29 @@ std::optional ScheduleOverlap::execute_impl(WorkerImpl& worker, torch::Tensor sampling_rows; auto output = worker.step_for_schedule_overlap( input, [&]() { sampling_rows = prepare_sampling_impl(worker, input); }); - if (sampling_rows.defined()) { - if (output.has_value()) { + if (wait_worker_completion_ && !output.has_value()) { + output.emplace(); + } + if (output.has_value()) { + if (sampling_rows.defined()) { // Keep the pinned H2D source alive through this output's completion. output->retained_inputs.emplace_back( std::make_shared(std::move(sampling_rows))); - } else { - CHECK_EQ(worker.compute_stream_->synchronize(), 0); } - } - // Composite workers may return retained inputs without an output event. The - // completion boundary must cover the full worker step before ownership is - // transferred to the overlap state. - if (output.has_value() && output->ready_event == nullptr && - (!output->retained_inputs.empty() || prior_tokens_owner != nullptr)) { - output->ready_event = worker.compute_stream_->record_event_or_sync(); - } - if (prior_tokens_owner != nullptr) { - if (output.has_value() && output->ready_event != nullptr) { + // MTP's output event can precede its prelaunched draft on the compute + // stream. + if ((wait_worker_completion_ && + worker.options().enable_speculative_decode()) || + (output->ready_event == nullptr && + (wait_worker_completion_ || !output->retained_inputs.empty() || + prior_tokens_owner != nullptr))) { + output->ready_event = worker.compute_stream_->record_event_or_sync(); + } + if (output->ready_event != nullptr && prior_tokens_owner != nullptr) { output->retained_inputs.emplace_back(std::move(prior_tokens_owner)); - } else { - CHECK_EQ(worker.compute_stream_->synchronize(), 0); } + } else if (sampling_rows.defined() || prior_tokens_owner != nullptr) { + CHECK_EQ(worker.compute_stream_->synchronize(), 0); } worker.observe_execution_memory(input.input_params.meta.is_graph_warmup); complete_step_impl(input, *worker.compute_stream_, output); @@ -194,7 +202,19 @@ std::optional ScheduleOverlap::execute(WorkerImpl& worker, return execute_impl(worker, input); } -ForwardOutput ScheduleOverlap::consume() { return state_.consume(); } +std::optional ScheduleOverlap::consume(const Device& device) { + auto output = state_.consume(); + if (!output || publish_output_) { + return output; + } + if (output->ready_event != nullptr) { + // Worker.async starts on a different host thread from the producer. + device.set_device(); + CHECK(output->ready_event->synchronize()) + << "failed to retire overlap KV cache access"; + } + return ForwardOutput{}; +} void ScheduleOverlap::shutdown() { state_.shutdown(); } diff --git a/xllm/core/runtime/schedule_overlap.h b/xllm/core/runtime/schedule_overlap.h index 2a9c49b4d0..ef1412e634 100644 --- a/xllm/core/runtime/schedule_overlap.h +++ b/xllm/core/runtime/schedule_overlap.h @@ -21,18 +21,23 @@ limitations under the License. namespace xllm { +class Device; class Stream; class WorkerImpl; class VlmForwardInput; +namespace runtime { +struct Options; +} // namespace runtime + // Coordinates one overlap step on the worker's FIFO execution thread. It owns // continuation provenance, stream dependencies and host publication while the // worker supplies model execution capabilities. class ScheduleOverlap final { public: ScheduleOverlap(bool is_driver, - bool enable_eplb, - bool retire_unconsumed_inputs); + const runtime::Options& options, + bool is_input_release_deferred); // Runs the complete overlap protocol using the worker's current execution // resources and model-specific hooks. @@ -42,7 +47,7 @@ class ScheduleOverlap final { VlmForwardInput& input); // May be called by the host consumer concurrently with the execution thread. - ForwardOutput consume(); + std::optional consume(const Device& device); void shutdown(); private: @@ -61,6 +66,8 @@ class ScheduleOverlap final { const ForwardOutput& prior_output, bool use_graph_decode_input); + const bool publish_output_; + const bool wait_worker_completion_; ScheduleOverlapState state_; }; diff --git a/xllm/core/runtime/schedule_overlap_state.cpp b/xllm/core/runtime/schedule_overlap_state.cpp index 0d6fb25279..de182cc85f 100644 --- a/xllm/core/runtime/schedule_overlap_state.cpp +++ b/xllm/core/runtime/schedule_overlap_state.cpp @@ -114,13 +114,15 @@ bool ScheduleOverlapState::record( return true; } -ForwardOutput ScheduleOverlapState::consume() { +std::optional ScheduleOverlapState::consume() { CHECK(publish_to_host_) << "overlap output has no host consumer"; std::unique_lock lock(mutex_); condition_.wait(lock, [this] { return pending_ || shutting_down_; }); - ForwardOutput output = - pending_ && has_output() ? prior_output_ : ForwardOutput(); + if (!pending_) { + return std::nullopt; + } + ForwardOutput output = has_output() ? prior_output_ : ForwardOutput(); pending_ = false; condition_.notify_all(); return output; diff --git a/xllm/core/runtime/schedule_overlap_state.h b/xllm/core/runtime/schedule_overlap_state.h index 208f8ef168..58b02a5392 100644 --- a/xllm/core/runtime/schedule_overlap_state.h +++ b/xllm/core/runtime/schedule_overlap_state.h @@ -53,7 +53,7 @@ class ScheduleOverlapState final { // Only valid for host-visible ranks. Waits for publication or shutdown and // consumes the publication flag. Returns a copy when relevant to the caller. // The cached prior output is retained for the next overlapped device step. - ForwardOutput consume(); + std::optional consume(); // Wakes blocked producer and consumer calls. Cached device state is kept // intact so destruction can drain already submitted work safely. @@ -62,7 +62,6 @@ class ScheduleOverlapState final { // These accessors are for the single producer thread that executes the next // overlapped step. They borrow state owned by this object. const ForwardOutput& prior_output() const { return prior_output_; } - const std::vector& request_ids() const { return request_ids_; } const std::vector& sample_sequence_ids() const { return sample_sequence_ids_; } diff --git a/xllm/core/runtime/worker_impl.cpp b/xllm/core/runtime/worker_impl.cpp index 9f8bdae5ff..3e124eb415 100644 --- a/xllm/core/runtime/worker_impl.cpp +++ b/xllm/core/runtime/worker_impl.cpp @@ -231,10 +231,7 @@ WorkerImpl::WorkerImpl(const ParallelArgs& parallel_args, : options_(options), driver_(parallel_args.rank() == 0), dp_driver_(is_dp_driver(parallel_args)), - schedule_overlap_( - is_driver(), - options.eplb_worker_config().enabled, - options.enable_schedule_overlap() || is_input_release_deferred), + schedule_overlap_(is_driver(), options, is_input_release_deferred), device_(device), parallel_args_(parallel_args) { parallel_args_.eplb_worker_config(options_.eplb_worker_config()); @@ -1135,8 +1132,8 @@ folly::SemiFuture> WorkerImpl::step_async_impl( return future; } -ForwardOutput WorkerImpl::get_last_step_result() { - return schedule_overlap_.consume(); +std::optional WorkerImpl::get_last_step_result() { + return schedule_overlap_.consume(device_); } folly::SemiFuture WorkerImpl::process_group_test_async() { diff --git a/xllm/core/runtime/worker_impl.h b/xllm/core/runtime/worker_impl.h index 3f48223b25..3cb1544644 100644 --- a/xllm/core/runtime/worker_impl.h +++ b/xllm/core/runtime/worker_impl.h @@ -285,7 +285,7 @@ class WorkerImpl { return options_.enable_schedule_overlap_; } - virtual ForwardOutput get_last_step_result(); + virtual std::optional get_last_step_result(); bool is_driver() const { return driver_ || dp_driver_; } diff --git a/xllm/core/scheduler/continuous_scheduler.cpp b/xllm/core/scheduler/continuous_scheduler.cpp index 399960df78..9018494963 100644 --- a/xllm/core/scheduler/continuous_scheduler.cpp +++ b/xllm/core/scheduler/continuous_scheduler.cpp @@ -26,6 +26,7 @@ limitations under the License. #include #include #include +#include #include #include "core/common/metrics.h" @@ -39,6 +40,7 @@ limitations under the License. #include "core/framework/request/priority_comparator.h" #include "core/framework/request/request.h" #include "core/framework/request/sequence.h" +#include "core/kv_cache/block/block.h" #include "core/scheduler/request_priority_queue.h" #include "core/scheduler/scheduler_policy.h" #include "core/util/timer.h" @@ -397,6 +399,9 @@ BatchGroup ContinuousSchedulerBase::prepare_batch() { // Strategy-driven scheduling policy_->schedule(state, budget, finished); + if (pending_step_ && requires_pd_kv_retirement()) { + pending_step_->drain_next_batch_ = budget.preemption_deferred_; + } // Finalize if (!finished.empty()) { @@ -443,8 +448,9 @@ SchedulerState ContinuousSchedulerBase::make_state() { [this](const std::shared_ptr& request) { release_failed_request(request); }, - .has_pending_vmm_batch = - kv_cache_manager_->uses_virtual_memory() && pending_step_.has_value(), + .has_pending_kv_batch_ = pending_step_.has_value() && + (kv_cache_manager_->uses_virtual_memory() || + requires_pd_kv_retirement()), }; } @@ -532,7 +538,39 @@ bool ContinuousSchedulerBase::step_with_schedule_overlap( return false; } + std::optional cache_block_lease; if (!cur_batch_all_empty) { + if (requires_pd_kv_retirement()) { + // BatchState already retains the VMM KV blocks used by its forward plan. + const std::optional excluded_type = + KVCacheConfig::get_instance().enable_vmm_kvcache() + ? std::optional{/*value=*/BlockType::KV} + : std::nullopt; + size_t block_count = 0; + for (Sequence* sequence : running_sequences_) { + for (const auto& group : + sequence->kv_state().block_groups(excluded_type)) { + block_count += group.size(); + } + } + + std::vector blocks; + blocks.reserve(block_count); + for (Sequence* sequence : running_sequences_) { + for (const auto& group : + sequence->kv_state().block_groups(excluded_type)) { + for (const Block& block : group) { + if (!block.is_valid()) { + continue; + } + blocks.emplace_back(block, /*pin_block=*/true); + } + } + } + if (!blocks.empty()) { + cache_block_lease.emplace(std::move(blocks)); + } + } step_callback_(batch); } @@ -552,12 +590,25 @@ bool ContinuousSchedulerBase::step_with_schedule_overlap( // Reuse the retired request vector's capacity across steady-state steps. pending_step_->batches = std::move(batch); pending_step_->requests = running_requests_; + if (cache_block_lease) { + pending_step_->cache_block_lease_.emplace(std::move(*cache_block_lease)); + } + if (pending_step_->drain_next_batch_) { + // A partial batch must not renew the deferral into the next round. + complete_pending_step(); + pending_step_.reset(); + } return true; } +bool ContinuousSchedulerBase::requires_pd_kv_retirement() const { + const auto role = options_.instance_role(); + return options_.enable_disagg_pd() && role && role->can_receive_pd_kv(); +} + void ContinuousSchedulerBase::complete_pending_step() { - CHECK(pending_step_.has_value()); result_callback_(pending_step_->batches); + pending_step_->cache_block_lease_.reset(); process_batch_output(pending_step_->requests); } diff --git a/xllm/core/scheduler/continuous_scheduler.h b/xllm/core/scheduler/continuous_scheduler.h index bcf3d796f6..1b42d67ba2 100644 --- a/xllm/core/scheduler/continuous_scheduler.h +++ b/xllm/core/scheduler/continuous_scheduler.h @@ -42,6 +42,7 @@ limitations under the License. #include "core/framework/request/priority_comparator.h" #include "core/framework/request/request.h" #include "core/framework/request/sequence.h" +#include "core/kv_cache/block/block.h" #include "core/kv_cache/manager/kv_cache_manager.h" #include "core/scheduler/kv_cache_prefetcher.h" #include "core/scheduler/profile/profile_manager.h" @@ -205,10 +206,6 @@ class ContinuousSchedulerBase : public Scheduler { // token budget for each running sequence std::vector running_sequences_budgets_; - // preemptible requests that hold cache slots, sorted by priority from high to - // low. - std::deque> preemptable_requests_; - std::shared_ptr cancel_request_queue_; std::unique_ptr output_dispatcher_; @@ -243,8 +240,7 @@ class ContinuousSchedulerBase : public Scheduler { int32_t min_speculative_tokens_required_ = 0; - // build a batch of requests from the priority queue - virtual BatchGroup prepare_batch(); + BatchGroup prepare_batch(); // tokenizer std::unique_ptr tokenizer_; @@ -257,6 +253,8 @@ class ContinuousSchedulerBase : public Scheduler { // Keep requests alive until their non-owning Batch views are destroyed. std::vector> requests; BatchGroup batches; + std::optional cache_block_lease_; + bool drain_next_batch_ = false; }; std::optional pending_step_; @@ -277,6 +275,7 @@ class ContinuousSchedulerBase : public Scheduler { bool step_with_schedule_overlap(const absl::Duration& timeout); void complete_pending_step(); + bool requires_pd_kv_retirement() const; void refresh_sequences_from_requests( const std::vector>& requests, diff --git a/xllm/core/scheduler/scheduler_policy.cpp b/xllm/core/scheduler/scheduler_policy.cpp index 63f3a32248..4bb080a57a 100644 --- a/xllm/core/scheduler/scheduler_policy.cpp +++ b/xllm/core/scheduler/scheduler_policy.cpp @@ -697,7 +697,7 @@ void SchedulerPolicy::allocate_shared_blocks_for(Sequence* seq, bool SchedulerPolicy::has_pending_block_release( const SchedulerState& state) const { - return state.has_pending_vmm_batch || + return state.has_pending_kv_batch_ || state.kv_cache_manager->has_pending_async_block_release(); } @@ -892,6 +892,7 @@ void SchedulerPolicy::schedule_decode_from_queue( // pages released by a sequence. Let that owner finish before preempting // another request. if (has_pending_block_release(state)) { + budget.preemption_deferred_ = true; return; } diff --git a/xllm/core/scheduler/scheduler_policy.h b/xllm/core/scheduler/scheduler_policy.h index 30eb4c58ac..277f240f60 100644 --- a/xllm/core/scheduler/scheduler_policy.h +++ b/xllm/core/scheduler/scheduler_policy.h @@ -73,9 +73,7 @@ struct SchedulerState { bool enable_prefix_cache; std::function&)> release_failed_request = {}; - // A submitted VMM batch can still hold pages after its sequences release - // their aliases. Drain it before treating an allocation failure as final. - bool has_pending_vmm_batch = false; + bool has_pending_kv_batch_ = false; }; // ScheduleBudget tracks the remaining resources for the current scheduling @@ -95,6 +93,7 @@ struct ScheduleBudget { // A real allocation failure stops further prefill growth in this round. // The next round retries after already scheduled work can release memory. bool kv_allocation_deferred = false; + bool preemption_deferred_ = false; }; inline bool budget_exhausted(const ScheduleBudget& budget) { diff --git a/xllm/core/scheduler/unified_policy.cpp b/xllm/core/scheduler/unified_policy.cpp index c7bdf7c9f8..b49b8f7c57 100644 --- a/xllm/core/scheduler/unified_policy.cpp +++ b/xllm/core/scheduler/unified_policy.cpp @@ -352,6 +352,7 @@ void UnifiedPolicy::schedule_from_unified_queue( continue; } if (has_pending_block_release(state)) { + budget.preemption_deferred_ = true; break; }