diff --git a/docs/src/content/docs/en/dev_guide/code_arch.md b/docs/src/content/docs/en/dev_guide/code_arch.md index 1b7efcfa67..23e3322479 100644 --- a/docs/src/content/docs/en/dev_guide/code_arch.md +++ b/docs/src/content/docs/en/dev_guide/code_arch.md @@ -14,7 +14,7 @@ immediate callees before exploring platform-specific implementations. | 1 | [`xllm/xllm.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/xllm.cpp): `main()`, `run()` | How are configuration, the master, and the HTTP service connected? | | 2 | [`chat_service_impl.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/api_service/chat_service_impl.cpp): `ChatServiceImpl::process_async_impl()` | How do chat messages become an internal request with an output callback? | | 3 | [`llm_master.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/distributed_runtime/llm_master.cpp): `LLMMaster::handle_request()`, `run()` | How does a request enter the scheduler, and what drives the scheduling loop? | -| 4 | [`continuous_scheduler.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/scheduler/continuous_scheduler.cpp): `ContinuousSchedulerBase::step()` | How is one batch scheduled, executed, and processed? | +| 4 | [`continuous_scheduler.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/scheduler/continuous_scheduler.cpp): `ContinuousScheduler::step()` | How is one batch scheduled, executed, and processed? | | 5 | [`llm_engine.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/distributed_runtime/llm_engine.cpp): `LLMEngine::step()` | How does a batch reach the workers, and how are their results collected? | | 6 | [`llm_worker_impl.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/runtime/llm_worker_impl.cpp): `LLMWorkerImpl::step_internal()` | Where do model execution, logits, and token sampling happen? | @@ -380,7 +380,7 @@ POST /v1/chat/completions -> HTTP route / APIService / ChatServiceImpl -> LLMMaster / LLMRequestFactory messages -> chat template -> prompt -> token IDs -> Request - -> ContinuousSchedulerBase / SchedulerPolicy + -> ContinuousScheduler / SchedulerPolicy choose sequences and token budgets -> BatchGroup -> LLMEngine build inputs -> dispatch to worker ranks @@ -406,7 +406,7 @@ POST /v1/chat/completions applies the chat template, tokenizes and validates the prompt, and creates request/sequence state. The master then calls `scheduler_->add_request()`. -3. **Choose work for the next step.** `ContinuousSchedulerBase` manages the +3. **Choose work for the next step.** `ContinuousScheduler` manages the request queues and execution loop. [`scheduler_policy.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/scheduler/scheduler_policy.cpp) contains the batch-assembly policies: `PrefillFirstPolicy`, diff --git a/docs/src/content/docs/zh/dev_guide/code_arch.md b/docs/src/content/docs/zh/dev_guide/code_arch.md index a927fbdbe2..070e6a3769 100644 --- a/docs/src/content/docs/zh/dev_guide/code_arch.md +++ b/docs/src/content/docs/zh/dev_guide/code_arch.md @@ -13,7 +13,7 @@ title: "代码架构与请求流程" | 1 | [`xllm/xllm.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/xllm.cpp):`main()`、`run()` | 配置、master 和 HTTP 服务如何连接起来? | | 2 | [`chat_service_impl.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/api_service/chat_service_impl.cpp):`ChatServiceImpl::process_async_impl()` | 聊天消息如何转换为内部请求,并绑定输出回调? | | 3 | [`llm_master.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/distributed_runtime/llm_master.cpp):`LLMMaster::handle_request()`、`run()` | 请求如何进入调度器?谁在驱动调度循环? | -| 4 | [`continuous_scheduler.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/scheduler/continuous_scheduler.cpp):`ContinuousSchedulerBase::step()` | 一轮批次如何被调度、执行并处理结果? | +| 4 | [`continuous_scheduler.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/scheduler/continuous_scheduler.cpp):`ContinuousScheduler::step()` | 一轮批次如何被调度、执行并处理结果? | | 5 | [`llm_engine.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/distributed_runtime/llm_engine.cpp):`LLMEngine::step()` | 批次如何发送到各个 worker,执行结果如何汇总? | | 6 | [`llm_worker_impl.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/runtime/llm_worker_impl.cpp):`LLMWorkerImpl::step_internal()` | 模型执行、logits 计算和 token 采样发生在哪里? | @@ -322,7 +322,7 @@ POST /v1/chat/completions -> HTTP route / APIService / ChatServiceImpl -> LLMMaster / LLMRequestFactory messages -> chat template -> prompt -> token IDs -> Request - -> ContinuousSchedulerBase / SchedulerPolicy + -> ContinuousScheduler / SchedulerPolicy choose sequences and token budgets -> BatchGroup -> LLMEngine build inputs -> dispatch to worker ranks @@ -345,7 +345,7 @@ POST /v1/chat/completions 应用聊天模板,对提示词分词并校验,创建请求和序列状态。随后 master 调用 `scheduler_->add_request()` 将请求加入调度器。 -3. **选择下一轮执行的工作。** `ContinuousSchedulerBase` 管理请求队列和执行循环。 +3. **选择下一轮执行的工作。** `ContinuousScheduler` 管理请求队列和执行循环。 [`scheduler_policy.cpp`](https://github.com/xLLM-AI/xllm/blob/main/xllm/core/scheduler/scheduler_policy.cpp) 中的 `PrefillFirstPolicy`、`DecodeFirstPolicy` 和 `UnifiedPolicy` 负责组批, 考虑 token/序列预算与缓存容量。想了解哪些请求会一起执行,应继续阅读策略文件; diff --git a/tests/core/framework/parallel_state/mlu_cp_capability_test.cpp b/tests/core/framework/parallel_state/mlu_cp_capability_test.cpp index bb131041f2..fe4cb729d2 100644 --- a/tests/core/framework/parallel_state/mlu_cp_capability_test.cpp +++ b/tests/core/framework/parallel_state/mlu_cp_capability_test.cpp @@ -43,8 +43,10 @@ TEST(MluCpCapabilityTest, AcceptsOrthogonalDeepseekV4TargetAndSuffix) { /*engine_type=*/EngineType::LLM, /*model_type=*/"deepseek_v4") .has_value()); - EXPECT_FALSE(validate_context_parallel_config(options, - /*engine_type=*/EngineType::SSM, + Options suffix_decode_options = options; + suffix_decode_options.num_speculative_tokens(/*value=*/2); + EXPECT_FALSE(validate_context_parallel_config(suffix_decode_options, + /*engine_type=*/EngineType::LLM, /*model_type=*/"deepseek_v4") .has_value()); } @@ -105,9 +107,10 @@ TEST(MluCpCapabilityTest, RejectsUnsupportedTopologyAndAcceptsMtp) { .has_value()); Options mtp_options = make_cp_options(kWorldSize); - mtp_options.speculative_algorithm("MTP"); + mtp_options.speculative_algorithm(/*value=*/"MTP") + .num_speculative_tokens(/*value=*/2); EXPECT_FALSE(validate_context_parallel_config(mtp_options, - /*engine_type=*/EngineType::SSM, + /*engine_type=*/EngineType::LLM, /*model_type=*/"glm_moe_dsa") .has_value()); diff --git a/tests/core/framework/parallel_state/npu_cp_capability_test.cpp b/tests/core/framework/parallel_state/npu_cp_capability_test.cpp index 84ac6efbc1..69888bba22 100644 --- a/tests/core/framework/parallel_state/npu_cp_capability_test.cpp +++ b/tests/core/framework/parallel_state/npu_cp_capability_test.cpp @@ -235,27 +235,23 @@ TEST(NpuCpCapabilityTest, PythonCpPreservesQwenAndRestrictsGlm) { .ep_size(16) .instance_role(InstanceRole::PREFILL) .enable_graph(false) - .speculative_algorithm("MTP"); + .speculative_algorithm(/*value=*/"MTP") + .num_speculative_tokens(/*value=*/2); EXPECT_FALSE(validate_context_parallel_config(options, /*engine_type=*/EngineType::LLM, /*model_type=*/"qwen3") .has_value()); EXPECT_FALSE(validate_context_parallel_config(options, - /*engine_type=*/EngineType::SSM, - /*model_type=*/"qwen3") - .has_value()); - EXPECT_FALSE(validate_context_parallel_config(options, - /*engine_type=*/EngineType::SSM, + /*engine_type=*/EngineType::LLM, /*model_type=*/"glm_moe_dsa") .has_value()); - options.speculative_algorithm("DSpark"); - EXPECT_NE(validate_context_parallel_config(options, - /*engine_type=*/EngineType::SSM, - /*model_type=*/"glm_moe_dsa") - .value_or("") - .find("aux-hidden-capture"), - std::string::npos); + options.speculative_algorithm(/*value=*/"DSpark") + .draft_model_path(/*value=*/"/tmp/draft"); + EXPECT_TRUE(validate_context_parallel_config(options, + /*engine_type=*/EngineType::LLM, + /*model_type=*/"glm_moe_dsa") + .has_value()); options.cp_size(1).instance_role(InstanceRole::DECODE).enable_disagg_pd(true); EXPECT_FALSE(validate_context_parallel_config(options, @@ -361,12 +357,19 @@ TEST(NpuCpCapabilityTest, PythonGlm5NextCapabilityGate) { /*model_type=*/"glm5_next") .has_value()); - EXPECT_NE( - validate_context_parallel_config( - options, /*engine_type=*/EngineType::SSM, /*model_type=*/"glm5_next") - .value_or(/*default_value=*/"") - .find(/*str=*/"target-side speculative verification"), - std::string::npos); + options.speculative_algorithm(/*value=*/"MTP") + .num_speculative_tokens(/*value=*/2) + .draft_model_path(/*value=*/"/tmp/draft"); + EXPECT_EQ( + validate_context_parallel_config(options, + /*engine_type=*/EngineType::LLM, + /*model_type=*/"glm5_next"), + std::optional{ + /*value=*/ + "Python GLM-5 Next CP does not support target-side speculative " + "verification; run speculation on a cp_size=1 Decode instance"}); + + options.num_speculative_tokens(/*value=*/0).draft_model_path(std::nullopt); execution_config.python_graph_backend("inductor"); EXPECT_NE( @@ -498,11 +501,12 @@ TEST(NpuCpCapabilityTest, PythonGlmMtpSupportsCpWithDecodeAclGraph) { .cp_size(2) .dp_size(1) .ep_size(1) - .instance_role(InstanceRole::DEFAULT) - .enable_graph(true) - .speculative_algorithm("MTP"); + .instance_role(/*value=*/InstanceRole::DEFAULT) + .enable_graph(/*value=*/true) + .speculative_algorithm(/*value=*/"MTP") + .num_speculative_tokens(/*value=*/2); EXPECT_FALSE(validate_context_parallel_config(options, - /*engine_type=*/EngineType::SSM, + /*engine_type=*/EngineType::LLM, /*model_type=*/"glm_moe_dsa") .has_value()); @@ -511,7 +515,7 @@ TEST(NpuCpCapabilityTest, PythonGlmMtpSupportsCpWithDecodeAclGraph) { options.instance_role(InstanceRole::PREFILL).enable_disagg_pd(true); parallel_config.kv_split_size(0); EXPECT_FALSE(validate_context_parallel_config(options, - /*engine_type=*/EngineType::SSM, + /*engine_type=*/EngineType::LLM, /*model_type=*/"glm_moe_dsa") .has_value()); } diff --git a/tests/core/scheduler/continuous_scheduler_test.cpp b/tests/core/scheduler/continuous_scheduler_test.cpp index 7d79edfd3c..c393da1e96 100644 --- a/tests/core/scheduler/continuous_scheduler_test.cpp +++ b/tests/core/scheduler/continuous_scheduler_test.cpp @@ -31,10 +31,10 @@ #include "core/framework/config/speculative_config.h" #include "core/kv_cache/manager/block_manager_pool.h" #include "core/scheduler/dit_scheduler.h" +#include "core/scheduler/fake_scheduling_engine_test_utils.h" #include "core/scheduler/request_output_dispatcher.h" #include "core/scheduler/scheduler_notifier_test_peer.h" #include "core/util/tensor_helper.h" -#include "distributed_runtime/engine.h" #include "scheduler_factory.h" #include "util/utils.h" @@ -154,27 +154,6 @@ class ControllableBlockManagerPool final : public BlockManagerPool { pending_; }; -class FakeTokenizer : public Tokenizer { - public: - bool encode(const std::string_view& text, - std::vector* ids, - bool add_special_tokens = true) const { - NOT_IMPLEMENTED(); - } - std::string decode(const Slice& ids, - bool skip_special_tokens) const { - return ""; - } - std::optional token_to_id(const std::string_view& token) const { - NOT_IMPLEMENTED(); - } - std::string id_to_token(int32_t id) const { NOT_IMPLEMENTED(); } - size_t vocab_size() const { NOT_IMPLEMENTED(); } - std::unique_ptr clone() const { - return std::make_unique(); - } -}; - class ResponseGate final { public: void wait_until_released() { @@ -253,7 +232,7 @@ class SpeculativeStatsLogCapture final : public google::LogSink { std::string messages_; }; -class FakeEngine : public Engine { +class FakeEngine : public FakeSchedulingEngine { public: FakeEngine(int32_t num_blocks, int32_t block_size, @@ -273,56 +252,46 @@ class FakeEngine : public Engine { opt.linear_state_num_slots_ = num_blocks + 2; } opt.enable_prefix_cache(enable_prefix_cache); - fake_tokenizer_ = std::make_unique(); - fake_block_manager_ = std::make_unique(opt); + auto pool = std::make_unique(opt); + controllable_pool_ = pool.get(); + block_manager_ = std::move(pool); } - virtual ForwardOutput step(BatchGroup& /*batch*/) { return {}; } - virtual std::vector collect_step_outputs( - const BatchGroup& batch) { + + std::vector collect_step_outputs( + const BatchGroup& batch) override { return std::vector(batch.size()); } - const Tokenizer* tokenizer() const { return fake_tokenizer_.get(); } - BlockManagerPool* kv_cache_manager() const override { - return fake_block_manager_.get(); - } - const ModelArgs& model_args() const { return model_args_; } - const TokenizerArgs& tokenizer_args() const { NOT_IMPLEMENTED(); } - bool init() override { return true; } void set_prefetch_ready(bool ready) { - fake_block_manager_->set_prefetch_ready(ready); + controllable_pool_->set_prefetch_ready(ready); } void set_pending_async_release(bool pending) { - fake_block_manager_->set_pending_async_release(pending); + controllable_pool_->set_pending_async_release(pending); } void set_uses_virtual_memory(bool enabled) { - fake_block_manager_->set_uses_virtual_memory(enabled); + controllable_pool_->set_uses_virtual_memory(enabled); } void set_storage_prefetch_enabled(bool enabled) { - fake_block_manager_->set_storage_prefetch_enabled(enabled); + controllable_pool_->set_storage_prefetch_enabled(enabled); } void set_host_cache_enabled(bool enabled) { - fake_block_manager_->set_host_cache_enabled(enabled); + controllable_pool_->set_host_cache_enabled(enabled); } - void complete_host_copy() { fake_block_manager_->complete_host_copy(); } + void complete_host_copy() { controllable_pool_->complete_host_copy(); } - size_t prefetch_calls() const { - return fake_block_manager_->prefetch_calls(); - } + size_t prefetch_calls() const { return controllable_pool_->prefetch_calls(); } size_t prefetch_pipeline_calls() const { - return fake_block_manager_->prefetch_pipeline_calls(); + return controllable_pool_->prefetch_pipeline_calls(); } private: - std::unique_ptr fake_tokenizer_; - std::unique_ptr fake_block_manager_; - ModelArgs model_args_; + ControllableBlockManagerPool* controllable_pool_ = nullptr; }; class PipelinePhaseEngine final : public FakeEngine { @@ -351,116 +320,9 @@ class PipelinePhaseEngine final : public FakeEngine { bool step_observed_consumed = false; }; -class TestableContinuousScheduler final : public ContinuousScheduler<> { - public: - using ContinuousScheduler<>::schedule_request; - - template - TestableContinuousScheduler(TargetEngine* engine, const Options& options) - : ContinuousScheduler<>(engine, - options, - /*model_residency_coordinator=*/nullptr, - /*distributed_worker_manager=*/nullptr) {} - - void drain_prefetch_for_test() { - if (kv_cache_prefetcher_) { - kv_cache_prefetcher_->drain(); - } - } - - uint64_t wakeup_generation() const { - return notifier_->snapshot().generation; - } - - bool wait_for_wakeup(uint64_t observed_generation) { - notifier_->wait_for(observed_generation, std::chrono::seconds(5)); - return notifier_->snapshot().generation != observed_generation; - } - - bool wait_until_armed() const { - return SchedulerNotifierTestPeer::wait_until_armed(*notifier_); - } - - void stop_scheduling() { notifier_->request_stop(); } - - void enqueue_decode_restore(const std::shared_ptr& request) { - decode_restore_waiting_.emplace_back( - DecodeRestoreEntry{request, absl::Now()}); - 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() { - return running_requests_; - } - - std::vector get_running_sequences_budgets() { - return running_sequences_budgets_; - } - - ProfileManager& profile_manager_for_test() { return *profile_manager_; } - - void reject_stream(const std::shared_ptr& request) { - output_dispatcher_->process_stream_request(request); - output_dispatcher_->wait_completion(); - } - - void reject_streams(const std::vector>& requests) { - std::vector> request_copy = requests; - output_dispatcher_->batch_process_stream_requests(request_copy); - output_dispatcher_->wait_completion(); - } - - size_t scheduler_queue_size() { return request_queue_.size(); } - - void wait_for_responses() { output_dispatcher_->wait_completion(); } - void seed_pending_batch(const std::shared_ptr& request) { - pending_step_.emplace(); - pending_step_->requests.emplace_back(request); - 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<> { +class RejectingReadyScheduler final : public TestableContinuousScheduler { public: - RejectingReadyScheduler(FakeEngine* engine, const Options& options) - : ContinuousScheduler<>(engine, - options, - /*model_residency_coordinator=*/nullptr, - /*distributed_worker_manager=*/nullptr) {} + using TestableContinuousScheduler::TestableContinuousScheduler; protected: bool enqueue_ready_request(std::shared_ptr /*request*/) override { @@ -684,7 +546,8 @@ class CancelledOverlapEngine final : public FakeEngine { output.outputs.emplace_back(std::move(sample)); EXPECT_FALSE(sequence->cancelled()); } - batch.process_sample_output(output, BatchOutputAction::RESERVE_PENDING); + batch.process_sample_output( + output, /*action=*/BatchOutputAction::RESERVE_PENDING); } return {}; } @@ -718,31 +581,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, @@ -951,16 +789,15 @@ TEST(ContinuousSchedulerTest, DecodeLinearKeepsIndependentInBatchState) { second_sequence->get_linear_state_slot_id()); } -TEST(ContinuousSchedulerTest, DrainsInflightBatchBeforeRetryingBlockedQueue) { +TEST(ContinuousSchedulerTest, DrainsInflightBatchWhenQueueIsEmpty) { auto request = generate_request_with_prompt_tokens({1, 2, 3, 4}, 4, 30000); OverlapDrainEngine engine; auto options = create_scheduler_options(1024, 16, 0, 1024, 1); options.enable_schedule_overlap(true); - BlockedOverlapScheduler scheduler(&engine, options, request); - - scheduler.step(absl::Seconds(5)); + TestableContinuousScheduler scheduler(&engine, options); + scheduler.seed_pending_batch(request); - EXPECT_EQ(scheduler.prepare_calls(), 1u); + scheduler.step(absl::ZeroDuration()); EXPECT_EQ(engine.completed_batches(), 1u); } @@ -1081,12 +918,13 @@ 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, (std::vector{"step", "step", "consume"})); @@ -1094,6 +932,7 @@ TEST(ContinuousSchedulerTest, EXPECT_EQ(engine.collected_sequences[0], (std::vector{first->sequences().front().get()})); + second->set_cancel(); scheduler.step(absl::ZeroDuration()); EXPECT_EQ(engine.calls, (std::vector{"step", "step", "consume", "consume"})); @@ -1104,11 +943,14 @@ TEST(ContinuousSchedulerTest, 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); + third->set_cancel(); scheduler.step(absl::ZeroDuration()); EXPECT_EQ(engine.collected_sequences.size(), 3u); } @@ -1130,13 +972,14 @@ TEST(ContinuousSchedulerTest, OverlapRetainsRequestsUntilPendingStepCompletes) { EXPECT_EQ(retained_request->sequences().front().get(), sequence); }; - scheduler.schedule_batch_for_test({request}); + ASSERT_TRUE(scheduler.add_request(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()); + scheduler.wait_for_responses(); EXPECT_TRUE(alive_at_collection); EXPECT_TRUE(weak_request.expired()); EXPECT_EQ(engine.calls, (std::vector{"step", "consume"})); @@ -1189,7 +1032,7 @@ TEST(ContinuousSchedulerTest, CopyProfileUsesSchedulerModelId) { .enable_in_batch_prefix_cache(false); FakeEngine engine(/*num_blocks=*/8, /*block_size=*/128); TestableContinuousScheduler scheduler(&engine, options); - ProfileManager& profile_manager = scheduler.profile_manager_for_test(); + ProfileManager& profile_manager = *scheduler.get_profile_manager(); EXPECT_DOUBLE_EQ(profile_manager.predict_copy_blocks_time(2), known_model ? 1.2 : 2.0); @@ -1704,14 +1547,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)), @@ -1986,39 +1825,6 @@ TEST(ContinuousSchedulerTest, EXPECT_EQ(scheduler->get_waiting_requests_num(), 0u); } -TEST(ContinuousSchedulerFactoryTest, ChunkedPrefillCreatesContinuousScheduler) { - SchedulerOptions opt = create_scheduler_options(10000, 256, 0, 1024, 1); - opt.enable_chunked_prefill() = true; - - auto engine = std::make_unique(32, 32); - auto scheduler = - create_continuous_scheduler(engine.get(), - opt, - /*distributed_worker_manager=*/nullptr, - /*model_residency_coordinator=*/nullptr); - - // All non-PD paths now create ContinuousScheduler with BatchMode routing. - EXPECT_NE(dynamic_cast*>(scheduler.get()), - nullptr); -} - -TEST(ContinuousSchedulerFactoryTest, - ChunkedPrefillWithSPAndSpeculativeCreatesContinuousScheduler) { - SchedulerOptions opt = create_scheduler_options(10000, 256, 4, 1024, 1); - opt.enable_chunked_prefill() = true; - - auto engine = std::make_unique(32, 32); - auto scheduler = - create_continuous_scheduler(engine.get(), - opt, - /*distributed_worker_manager=*/nullptr, - /*model_residency_coordinator=*/nullptr); - - // All non-PD paths now create ContinuousScheduler with BatchMode routing. - EXPECT_NE(dynamic_cast*>(scheduler.get()), - nullptr); -} - TEST(ContinuousSchedulerFactoryTest, ChunkedPrefillWithSPDoesNotBuildMixedBatch) { SchedulerOptions opt = create_scheduler_options(8, 8, 0, 4, 1); @@ -2063,7 +1869,7 @@ TEST(SchedulerFactoryTest, PDChunkedPrefillUsesPD) { opt.enable_disagg_pd() = true; opt.enable_chunked_prefill() = true; - EXPECT_EQ(select_scheduler_kind(opt), SchedulerKind::PD); + EXPECT_EQ(select_scheduler_kind(opt), SchedulerKind::DISAGG_PD); } TEST(BlockManagerPoolTest, AllocateFailureRollsBackSharedPrefixBlocks) { diff --git a/tests/core/scheduler/fake_scheduling_engine_test_utils.h b/tests/core/scheduler/fake_scheduling_engine_test_utils.h new file mode 100644 index 0000000000..93e80a8c07 --- /dev/null +++ b/tests/core/scheduler/fake_scheduling_engine_test_utils.h @@ -0,0 +1,155 @@ +/* Copyright 2026 The xLLM Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://github.com/xLLM-AI/xllm/blob/main/LICENSE + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#pragma once + +#include +#include +#include +#include +#include + +#include "core/framework/batch/batch_group.h" +#include "core/framework/model/model_args.h" +#include "core/framework/tokenizer/tokenizer.h" +#include "core/kv_cache/manager/block_manager_pool.h" +#include "core/runtime/forward_params.h" +#include "core/scheduler/continuous_scheduler.h" +#include "core/scheduler/profile/profile_manager.h" +#include "core/scheduler/scheduler_callbacks.h" +#include "core/scheduler/scheduler_notifier_test_peer.h" + +namespace xllm { + +class FakeSchedulingTokenizer : public Tokenizer { + public: + std::unique_ptr clone() const override { + return std::make_unique(); + } +}; + +class FakeSchedulingEngine { + public: + virtual ~FakeSchedulingEngine() = default; + + explicit FakeSchedulingEngine( + std::unique_ptr block_manager = nullptr) + : tokenizer_(std::make_unique()), + block_manager_(std::move(block_manager)) {} + + virtual ForwardOutput step(BatchGroup& /*batch*/) { return {}; } + virtual std::vector collect_step_outputs( + const BatchGroup& /*batch*/) { + return {}; + } + const Tokenizer* tokenizer() const { return tokenizer_.get(); } + BlockManagerPool* kv_cache_manager() const { return block_manager_.get(); } + const ModelArgs& model_args() const { return model_args_; } + + protected: + std::unique_ptr tokenizer_; + std::unique_ptr block_manager_; + ModelArgs model_args_; +}; + +class TestableContinuousScheduler : public ContinuousScheduler { + public: + using ContinuousScheduler::prepare_batch; + using ContinuousScheduler::schedule_request; + + TestableContinuousScheduler(FakeSchedulingEngine* engine, + const Options& options) + : ContinuousScheduler(engine->kv_cache_manager(), + &engine->model_args(), + engine->tokenizer(), + make_scheduler_callbacks(engine), + options, + /*model_residency_coordinator=*/nullptr, + /*distributed_worker_manager=*/nullptr) {} + + void drain_prefetch_for_test() { + if (kv_cache_prefetcher_) { + kv_cache_prefetcher_->drain(); + } + } + + ProfileManager* get_profile_manager() { return profile_manager_.get(); } + + bool in_batch_prefix_cache_enabled() const { + return enable_in_batch_prefix_cache_; + } + + uint64_t wakeup_generation() const { + return notifier_->snapshot().generation; + } + + bool wait_for_wakeup(uint64_t observed_generation) { + notifier_->wait_for(observed_generation, std::chrono::seconds{5}); + return notifier_->snapshot().generation != observed_generation; + } + + bool wait_until_armed() const { + return SchedulerNotifierTestPeer::wait_until_armed(*notifier_); + } + + void stop_scheduling() { notifier_->request_stop(); } + + void enqueue_decode_restore(const std::shared_ptr& request) { + decode_restore_waiting_.emplace_back( + DecodeRestoreEntry{request, absl::Now()}); + incr_pending_requests(/*count=*/1); + } + + void process_batch_output_test() { process_batch_output(running_requests_); } + + std::vector> get_running_requests() const { + return running_requests_; + } + + std::vector get_running_sequences_budgets() const { + return running_sequences_budgets_; + } + + void reject_stream(const std::shared_ptr& request) { + output_dispatcher_->process_stream_request(request); + output_dispatcher_->wait_completion(); + } + + void reject_streams(const std::vector>& requests) { + std::vector> request_copy = requests; + output_dispatcher_->batch_process_stream_requests(request_copy); + output_dispatcher_->wait_completion(); + } + + size_t scheduler_queue_size() { return request_queue_.size(); } + + void wait_for_responses() { output_dispatcher_->wait_completion(); } + void seed_pending_batch(const std::shared_ptr& request) { + pending_step_.emplace(); + pending_step_->requests.emplace_back(request); + pending_step_->batches = BatchGroup(/*dp_size=*/1); + pending_step_->batches.front().add(request->sequences().front().get()); + } +}; + +inline ProfileManager make_profile_manager(FakeSchedulingEngine& engine, + ProfileManager::Options options) { + return ProfileManager(engine.kv_cache_manager(), + &engine.model_args(), + options, + make_scheduler_callbacks(&engine)); +} + +} // namespace xllm diff --git a/tests/core/scheduler/offline_generation_test.cpp b/tests/core/scheduler/offline_generation_test.cpp index 1a96afe00d..c4c3bc40c4 100644 --- a/tests/core/scheduler/offline_generation_test.cpp +++ b/tests/core/scheduler/offline_generation_test.cpp @@ -23,21 +23,14 @@ limitations under the License. #include #include -#include "core/distributed_runtime/engine.h" #include "core/kv_cache/manager/block_manager_pool.h" #include "core/scheduler/continuous_scheduler.h" +#include "core/scheduler/fake_scheduling_engine_test_utils.h" namespace xllm { namespace { -class TestTokenizer final : public Tokenizer { - public: - std::unique_ptr clone() const override { - return std::make_unique(); - } -}; - -class FiniteGenerationEngine final : public Engine { +class FiniteGenerationEngine final : public FakeSchedulingEngine { public: explicit FiniteGenerationEngine(bool overlap) : overlap_(overlap) { BlockManagerPool::Options options; @@ -45,11 +38,10 @@ class FiniteGenerationEngine final : public Engine { .block_size(4) .max_seqs_per_batch(1) .enable_prefix_cache(false); - kv_cache_manager_ = std::make_unique(options); - tokenizer_ = std::make_unique(); + block_manager_ = std::make_unique(options); } - ForwardOutput step(BatchGroup& batches) { + ForwardOutput step(BatchGroup& batches) override { ++submitted_; if (overlap_ && submitted_ > completed_ + 2) { throw std::logic_error("Pending generation results were not collected"); @@ -66,7 +58,7 @@ class FiniteGenerationEngine final : public Engine { } std::vector collect_step_outputs( - const BatchGroup& batches) { + const BatchGroup& batches) override { ++completed_; for (const Batch& batch : batches) { for (Sequence* sequence : batch.get_sequences()) { @@ -88,38 +80,6 @@ class FiniteGenerationEngine final : public Engine { size_t completed_ = 0; }; -class OfflineGenerationScheduler final : public ContinuousScheduler<> { - public: - OfflineGenerationScheduler(FiniteGenerationEngine* engine, - const SchedulerOptions& options) - : ContinuousScheduler<>(engine, options) {} - - void seed_pending_batch(const std::shared_ptr& request) { - pending_step_.emplace(); - pending_step_->requests.emplace_back(request); - pending_step_->batches = BatchGroup(/*dp_size=*/1); - pending_step_->batches.front().add(request->sequences().front().get()); - } - - void notify_after_next_prepare_batch(std::promise& notification) { - prepared_notification_ = ¬ification; - } - - 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) { SchedulerOptions options; options.max_tokens_per_batch(64) @@ -162,7 +122,7 @@ std::shared_ptr make_request(int32_t max_tokens, bool overlap) { TEST(OfflineGenerationTest, OverlapCommitsFinalTokensAndCanRunAgain) { SchedulerOptions options = generation_options(/*overlap=*/true); FiniteGenerationEngine engine(/*overlap=*/true); - OfflineGenerationScheduler scheduler(&engine, options); + TestableContinuousScheduler scheduler(&engine, options); const auto initial_free_blocks = engine.kv_cache_manager()->num_free_blocks(); scheduler.generate_with_schedule_overlap(); @@ -195,7 +155,7 @@ TEST(OfflineGenerationTest, OverlapCommitsFinalTokensAndCanRunAgain) { TEST(OfflineGenerationTest, OverlapDrainsPreviouslySubmittedWork) { SchedulerOptions options = generation_options(/*overlap=*/true); FiniteGenerationEngine engine(/*overlap=*/true); - OfflineGenerationScheduler scheduler(&engine, options); + TestableContinuousScheduler scheduler(&engine, options); auto request = make_request(/*max_tokens=*/1, /*overlap=*/true); request->set_cancel(); const std::weak_ptr retained_request = request; @@ -213,7 +173,7 @@ TEST(OfflineGenerationTest, OverlapDrainsPreviouslySubmittedWork) { TEST(OfflineGenerationTest, OverlapWaitsForAdmissionAndResponse) { SchedulerOptions options = generation_options(/*overlap=*/true); FiniteGenerationEngine engine(/*overlap=*/true); - OfflineGenerationScheduler scheduler(&engine, options); + TestableContinuousScheduler scheduler(&engine, options); auto request = make_request(/*max_tokens=*/1, /*overlap=*/true); std::promise callback_started; std::future callback = callback_started.get_future(); @@ -225,14 +185,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)); @@ -249,7 +205,7 @@ TEST(OfflineGenerationTest, OverlapWaitsForAdmissionAndResponse) { TEST(OfflineGenerationTest, LegacyGenerationKeepsSynchronousOutput) { SchedulerOptions options = generation_options(/*overlap=*/false); FiniteGenerationEngine engine(/*overlap=*/false); - OfflineGenerationScheduler scheduler(&engine, options); + TestableContinuousScheduler scheduler(&engine, options); auto request = make_request(/*max_tokens=*/3, /*overlap=*/false); std::vector outputs; outputs.reserve(1); diff --git a/tests/core/scheduler/pd_scheduler_test.cpp b/tests/core/scheduler/pd_scheduler_test.cpp index 8668c3fb2d..595258bc0e 100644 --- a/tests/core/scheduler/pd_scheduler_test.cpp +++ b/tests/core/scheduler/pd_scheduler_test.cpp @@ -50,10 +50,10 @@ limitations under the License. #include "core/kv_cache/block/block_manager_impl.h" #include "core/kv_cache/manager/block_manager_pool.h" #include "core/kv_cache/transfer/kv_transfer_completion.h" -#include "core/platform/device.h" +#include "core/scheduler/continuous_scheduler.h" +#include "core/scheduler/fake_scheduling_engine_test_utils.h" #include "core/util/scope_guard.h" #include "distributed_runtime/distributed_worker_manager.h" -#include "distributed_runtime/engine.h" #include "distributed_runtime/kv_transfer_coordinator.h" #include "framework/model/model_args.h" #include "framework/request/request.h" @@ -194,7 +194,7 @@ class PrefetchBlockManagerPool final : public BlockManagerPool { std::atomic prefetch_pipeline_calls_{0}; }; -class FakeEngine final : public Engine { +class FakeEngine final : public FakeSchedulingEngine { public: FakeEngine(int32_t num_blocks, int32_t block_size, @@ -210,16 +210,19 @@ class FakeEngine final : public Engine { .num_embedding_blocks(embedding_blocks == 0 ? num_blocks : embedding_blocks); tokenizer_ = std::make_unique(); - block_manager_ = - std::make_unique(options, dp_size); + auto pool = std::make_unique(options, dp_size); + prefetch_pool_ = pool.get(); + block_manager_ = std::move(pool); } - std::function forward; + StepCallback forward_; + + PrefetchBlockManagerPool* prefetch_pool_ = nullptr; std::function complete_forward; ForwardOutput step(BatchGroup& batch) { - if (forward) { - return forward(batch); + if (forward_) { + return forward_(batch); } NOT_IMPLEMENTED(); } @@ -231,24 +234,12 @@ class FakeEngine final : public Engine { return std::vector(batch.size()); } - const Tokenizer* tokenizer() const override { return tokenizer_.get(); } - - BlockManagerPool* kv_cache_manager() const override { - return block_manager_.get(); - } - - const ModelArgs& model_args() const override { return model_args_; } - - const TokenizerArgs& tokenizer_args() const override { NOT_IMPLEMENTED(); } - - bool init() override { return true; } - void set_storage_prefetch_enabled(bool enabled) { - block_manager_->set_storage_prefetch_enabled(enabled); + prefetch_pool_->set_storage_prefetch_enabled(enabled); } size_t prefetch_pipeline_calls() const { - return block_manager_->prefetch_pipeline_calls(); + return prefetch_pool_->prefetch_pipeline_calls(); } void set_tokenizer(std::unique_ptr tokenizer) { @@ -256,35 +247,27 @@ class FakeEngine final : public Engine { } void set_release_callback(std::function callback) { - block_manager_->on_release = std::move(callback); + prefetch_pool_->on_release = std::move(callback); } - - private: - std::unique_ptr tokenizer_; - std::unique_ptr block_manager_; - ModelArgs model_args_; -}; - -class TestPDServiceImpl final : public PDServiceImpl { - public: - using PDServiceImpl::generate_request; - using PDServiceImpl::PDServiceImpl; }; class TestPDScheduler final : public PDScheduler { public: + using ContinuousScheduler::prepare_batch; + using ContinuousScheduler::schedule_request; + using PDScheduler::drain_request_releases; using PDScheduler::enqueue_request_block_release; - using PDScheduler::prepare_batch; - template TestPDScheduler( - TargetEngine* engine, + FakeEngine* engine, const Options& options, std::shared_ptr transfer_coordinator = nullptr) - : PDScheduler(engine, + : PDScheduler(engine->kv_cache_manager(), + &engine->model_args(), + engine->tokenizer(), + make_scheduler_callbacks(engine), options, - SkipRuntimeStart{}, /*distributed_worker_manager=*/nullptr, /*model_residency_coordinator=*/nullptr, std::move(transfer_coordinator)) {} @@ -388,10 +371,10 @@ class TestPDScheduler final : public PDScheduler { } void start_idle_runtime() { - server_name_ = "PDShutdownTest"; + server_name_ = "DisaggPDShutdownTest"; auto server = ServerRegistry::get_instance().register_server(server_name_); - auto service = std::make_shared(); - CHECK(server->start(service, "127.0.0.1:0", "PDShutdownTest")); + auto service = std::make_shared(this); + ASSERT_TRUE(server->start(service, /*addr=*/"127.0.0.1:0", server_name_)); rpc_server_thread_ = std::make_unique( [server, service = std::move(service)] { server->run(); }); dispatch_thread_ = std::make_unique( @@ -412,6 +395,11 @@ class TestPDScheduler final : public PDScheduler { return req_to_channel_map_.contains(req_id); } + std::shared_ptr reserved_request(const std::string& id) { + std::lock_guard lock(received_request_map_mutex_); + return received_request_map_.at(id); + } + bool reservations_empty() { std::lock_guard lock(received_request_map_mutex_); return received_request_map_.empty() && @@ -462,7 +450,7 @@ class TestPDScheduler final : public PDScheduler { void cache_prefill_blocks_for_test(Request* request) { for (auto& sequence : request->sequences()) { - kv_cache_manager_->publish_prefix(sequence.get()); + kv_cache_manager()->publish_prefix(sequence.get()); } } @@ -783,6 +771,7 @@ TEST(PDSchedulerShutdownTest, StopsListenerAndWakesIdleDispatchBeforeJoining) { ASSERT_EXIT( { alarm(5); + XServiceClientTestPeer::set_initialized(/*initialized=*/true); FakeEngine engine(/*num_blocks=*/32, /*block_size=*/16); PDScheduler::Options options = make_options(); { @@ -1455,11 +1444,14 @@ TEST(PDSchedulerTest, DecodeBuildsMinimumLengthLogitsBias) { FakeEngine engine(/*num_blocks=*/8, /*block_size=*/2); PDScheduler::Options options = make_decode_options(); TestPDScheduler scheduler(&engine, options); - TestPDServiceImpl service(&scheduler, &engine); + PDServiceImpl service(&scheduler); for (const uint32_t minimum : {0u, 3u}) { SCOPED_TRACE(minimum); - proto::DisaggRequest wire_request; - wire_request.set_req_id("decode-min-tokens"); + proto::DisaggRequests wire_requests; + const std::string request_id = + "decode-min-tokens-" + std::to_string(minimum); + auto& wire_request = *wire_requests.add_reqs(); + wire_request.set_req_id(request_id); wire_request.add_prompt_tokens(1); wire_request.set_seq_capacity(16); wire_request.set_n(1); @@ -1471,8 +1463,11 @@ TEST(PDSchedulerTest, DecodeBuildsMinimumLengthLogitsBias) { wire_request.set_repetition_penalty(1.0f); wire_request.set_eos_token_id(7); wire_request.add_all_stop_token_ids(7); - auto request = service.generate_request(wire_request); - ASSERT_NE(request, nullptr); + proto::DisaggResponses responses; + service.decode_recv_new_requests(&wire_requests, &responses); + ASSERT_EQ(responses.resps_size(), 1); + ASSERT_EQ(responses.resps(/*index=*/0).status_code(), 200); + const auto request = scheduler.reserved_request(request_id); EXPECT_EQ(request->state().sampling_param.min_tokens, minimum); SamplingInputBuilder builder; @@ -1538,8 +1533,9 @@ TEST(PDSchedulerTest, DecodeOutputCallbacksOutliveRpcService) { TestPDScheduler scheduler(&engine, make_decode_options()); std::shared_ptr request; { - auto rpc_service = std::make_unique(&scheduler, &engine); - proto::DisaggRequest wire_request; + PDServiceImpl rpc_service(&scheduler); + proto::DisaggRequests wire_requests; + auto& wire_request = *wire_requests.add_reqs(); wire_request.set_req_id("retained"); wire_request.set_service_req_id("service-retained"); wire_request.set_source_xservice_addr(address); @@ -1552,8 +1548,11 @@ TEST(PDSchedulerTest, DecodeOutputCallbacksOutliveRpcService) { wire_request.set_vocab_size(8); wire_request.set_repetition_penalty(1.0f); wire_request.set_eos_token_id(7); - request = rpc_service->generate_request(wire_request); - ASSERT_NE(request, nullptr); + proto::DisaggResponses responses; + rpc_service.decode_recv_new_requests(&wire_requests, &responses); + ASSERT_EQ(responses.resps_size(), 1); + ASSERT_EQ(responses.resps(/*index=*/0).status_code(), 200); + request = scheduler.reserved_request(wire_request.req_id()); } // Queued outputs retain the request after its RPC service is destroyed. @@ -1586,7 +1585,7 @@ TEST(PDSchedulerTest, DecodeRejectsMalformedMetadataBeforeKvAllocation) { TestPDScheduler scheduler(&engine, make_options()); PDServiceOptions options; options.enable_response_formatting = true; - PDServiceImpl service(&scheduler, &engine, options); + PDServiceImpl service(&scheduler, options); for (int32_t invalid_field = 0; invalid_field < 4; ++invalid_field) { proto::DisaggRequests requests; auto* request = requests.add_reqs(); @@ -1782,7 +1781,8 @@ TEST(PDSchedulerTest, TemporaryDecodeBlockPressureIsNotPermanent) { BlockManagerPool* block_manager = engine.kv_cache_manager(); std::shared_ptr holder = make_request({1, 2, 3, 4, 5, 6}); ASSERT_TRUE(block_manager->try_allocate(holder->sequences()[0].get())); - std::shared_ptr request = make_request({7, 8}); + std::shared_ptr request = + make_request(/*prompt_tokens=*/{3, 4, 5, 6, 7, 8}); Sequence* sequence = request->sequences()[0].get(); EXPECT_FALSE(scheduler.try_allocate(sequence)); @@ -2506,7 +2506,7 @@ TEST_P(ChunkReservationTest, folly::Promise> push; std::promise started; auto entered = started.get_future(); - engine.forward = [&](BatchGroup& batch) { + engine.forward_ = [&](BatchGroup& batch) { KVTransferCompletion completion(push.getSemiFuture(), {local->request_id()}); started.set_value(); @@ -2623,21 +2623,6 @@ TEST(PDSchedulerTest, MtpExhaustionRollsBackKvReservation) { namespace xllm { namespace { -class OutputTokenizer final : public Tokenizer { - public: - std::unique_ptr clone() const override { - return std::make_unique(); - } - std::string decode(const Slice& ids, - bool /*skip_special_tokens*/) const override { - std::string text; - for (int32_t id : ids) { - text += static_cast(id); - } - return text; - } -}; - TEST(PDSchedulerTest, PrefillEmitsNoSuccessfulOutputInEitherProtocol) { for (const bool http : {false, true}) { for (const bool stream : {false, true}) { @@ -2659,7 +2644,7 @@ TEST(PDSchedulerTest, PrefillEmitsNoSuccessfulOutputInEitherProtocol) { return std::vector(outputs.size(), true); }; finish_prefill(request->sequences()[0].get()); - OutputTokenizer tokenizer; + FakeTokenizer tokenizer; RequestOutputDispatcher dispatcher(&tokenizer, /*num_response_handling_threads=*/4, /*enable_service_routing=*/true, @@ -2680,7 +2665,7 @@ TEST(PDSchedulerTest, PrefillEmitsNoSuccessfulOutputInEitherProtocol) { TEST(PDSchedulerTest, ServiceOutputBatchesRequestsAndMapsPartialAcknowledgements) { for (const bool stream : {false, true}) { - OutputTokenizer tokenizer; + FakeTokenizer tokenizer; std::vector cancelled; RequestOutputDispatcher dispatcher( &tokenizer, @@ -2746,7 +2731,7 @@ TEST(PDSchedulerTest, DecodeEmitsFirstTokenAsynchronouslyBeforeAnyDecodeStep) { SCOPED_TRACE("overlap=" + std::to_string(overlap) + ", batched=" + std::to_string(batched)); FakeEngine engine(/*num_blocks=*/8, /*block_size=*/2); - engine.set_tokenizer(std::make_unique()); + engine.set_tokenizer(std::make_unique()); auto options = make_decode_options(); options.enable_schedule_overlap(overlap).enable_service_routing(batched); TestPDScheduler scheduler(&engine, options); @@ -2864,7 +2849,7 @@ TEST(PDSchedulerTest, DecodeEmitsFirstTokenAsynchronouslyBeforeAnyDecodeStep) { TEST(PDSchedulerTest, DecodeTerminatesFirstTokenWithoutQueueingDecodeWork) { for (const bool stream : {false, true}) { FakeEngine engine(/*num_blocks=*/8, /*block_size=*/2); - engine.set_tokenizer(std::make_unique()); + engine.set_tokenizer(std::make_unique()); TestPDScheduler scheduler(&engine, make_decode_options()); auto request = make_request({65, 66}, "req", @@ -2901,7 +2886,7 @@ TEST(PDSchedulerTest, DecodeTerminatesFirstTokenWithoutQueueingDecodeWork) { TEST(PDSchedulerTest, FullDecodeQueueFailsAfterFirstTokenAndReleasesKv) { FakeEngine engine(/*num_blocks=*/8, /*block_size=*/2); - engine.set_tokenizer(std::make_unique()); + engine.set_tokenizer(std::make_unique()); auto options = make_decode_options(); options.request_queue_size(1); TestPDScheduler scheduler(&engine, options); @@ -2961,7 +2946,7 @@ TEST(RequestOutputDispatcherTest, StreamingUsageCountsPreparedPromptTokens) { outputs.insert(outputs.end(), batch.begin(), batch.end()); return std::vector(batch.size(), true); }; - OutputTokenizer tokenizer; + FakeTokenizer tokenizer; RequestOutputDispatcher dispatcher(&tokenizer, /*num_response_handling_threads=*/4, batch_response, diff --git a/tests/core/scheduler/profile/profile_graph_warmup_test.cpp b/tests/core/scheduler/profile/profile_graph_warmup_test.cpp index 177de960dc..3414aeef6c 100644 --- a/tests/core/scheduler/profile/profile_graph_warmup_test.cpp +++ b/tests/core/scheduler/profile/profile_graph_warmup_test.cpp @@ -24,7 +24,6 @@ limitations under the License. #include #include "core/common/options.h" -#include "core/distributed_runtime/engine.h" #include "core/framework/config/disagg_pd_config.h" #include "core/framework/config/execution_config.h" #include "core/framework/config/kv_cache_config.h" @@ -37,6 +36,7 @@ limitations under the License. #include "core/framework/request/stopping_checker.h" #include "core/framework/sampling/sampling_params.h" #include "core/kv_cache/manager/block_manager_pool.h" +#include "core/scheduler/scheduler_callbacks.h" #include "platform/platform.h" #include "runtime/decode_graph_bucket.h" #include "scheduler/profile/decode_graph_warmup_plan.h" @@ -144,7 +144,7 @@ DecodeGraphWarmupConfig make_decode_graph_warmup_config( return warmup_config; } -class RecordingProfileEngine final : public Engine { +class RecordingProfileEngine final { public: explicit RecordingProfileEngine(bool overlap = false, int32_t dp_size = 1, @@ -152,9 +152,7 @@ class RecordingProfileEngine final : public Engine { InstanceRole role = InstanceRole::DEFAULT, int32_t num_speculative_tokens = 0, bool enable_prefix_cache = false) - : overlap_(overlap), - linear_attention_(linear_attention), - num_speculative_tokens_(num_speculative_tokens) { + : overlap_(overlap), linear_attention_(linear_attention) { BlockManagerPool::Options options; options.num_blocks(/*num_blocks=*/64) .block_size(/*block_size=*/4) @@ -229,11 +227,9 @@ class RecordingProfileEngine final : public Engine { return std::vector(batches.size()); } - BlockManagerPool* kv_cache_manager() const override { - return block_manager_.get(); - } + BlockManagerPool* kv_cache_manager() const { return block_manager_.get(); } - const ModelArgs& model_args() const override { return model_args_; } + const ModelArgs& model_args() const { return model_args_; } void set_max_context_len(int32_t max_context_len) { model_args_.max_position_embeddings(max_context_len); @@ -267,7 +263,6 @@ class RecordingProfileEngine final : public Engine { bool all_requests_marked_ = true; bool overlap_ = false; bool linear_attention_ = false; - int32_t num_speculative_tokens_ = 0; int32_t pending_steps_ = 0; std::vector observed_batches_; std::vector observed_token_lengths_; @@ -325,7 +320,10 @@ TEST_P(LinearProfileGraphWarmupTest, PrefillWarmupDoesNotSplitIntoChunks) { /*linear_attention=*/true, InstanceRole::PREFILL, std::get<1>(GetParam())); - ProfileManager profile_manager(&engine, options(InstanceRole::PREFILL)); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + options(/*role=*/InstanceRole::PREFILL), + make_scheduler_callbacks(&engine)); EXPECT_EQ(engine.prefill_batches(), (std::vector>{{10}})); @@ -347,7 +345,10 @@ TEST_P(LinearProfileGraphWarmupTest, profile_options.dp_size(3) .enable_dp_fair_token_budget(true) .max_tokens_per_chunk_for_prefill(-1); - ProfileManager profile_manager(&engine, profile_options); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + profile_options, + make_scheduler_callbacks(&engine)); EXPECT_EQ(engine.prefill_batches(), (std::vector>{{10}})); } @@ -366,7 +367,10 @@ TEST_P(LinearProfileGraphWarmupTest, PrefillUsesInjectedFairBudget) { .enable_dp_fair_token_budget(true) .enable_chunked_prefill(chunked) .max_tokens_per_chunk_for_prefill(6); - ProfileManager profile_manager(&engine, profile_options); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + profile_options, + make_scheduler_callbacks(&engine)); const int32_t expected_tokens = chunked ? 6 : 10; EXPECT_EQ(engine.prefill_batches(), (std::vector>{{expected_tokens}})); @@ -380,8 +384,11 @@ TEST_P(LinearProfileGraphWarmupTest, PrefillRespectsSequenceLimit) { /*linear_attention=*/true, InstanceRole::PREFILL, std::get<1>(GetParam())); - ProfileManager profile_manager(&engine, - options(InstanceRole::PREFILL, 10, 2)); + ProfileManager profile_manager( + engine.kv_cache_manager(), + &engine.model_args(), + options(/*role=*/InstanceRole::PREFILL, /*sequence_budget=*/2), + make_scheduler_callbacks(&engine)); EXPECT_EQ(engine.prefill_batches(), (std::vector>{{10}})); @@ -396,7 +403,10 @@ TEST_P(LinearProfileGraphWarmupTest, EagerWarmupAcceptsMoreThanOneCheckpoint) { std::get<1>(GetParam())); ProfileManager::Options profile_options = options(InstanceRole::PREFILL); profile_options.enable_graph(false); - ProfileManager profile_manager(&engine, profile_options); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + profile_options, + make_scheduler_callbacks(&engine)); EXPECT_EQ(engine.prefill_batches(), (std::vector>{{10}})); EXPECT_EQ(engine.kv_cache_manager()->num_used_blocks(), @@ -413,7 +423,10 @@ TEST_P(LinearProfileGraphWarmupTest, std::get<1>(GetParam())); ProfileManager::Options profile_options = options(InstanceRole::PREFILL); profile_options.disable_graph_warmup(true); - ProfileManager profile_manager(&engine, profile_options); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + profile_options, + make_scheduler_callbacks(&engine)); profile_manager.run_request(10, 3); profile_manager.run_request(8, 0); EXPECT_EQ(engine.prefill_batches(), @@ -430,7 +443,10 @@ TEST_P(LinearProfileGraphWarmupTest, UnifiedWarmupSeedsDecodeSlots) { InstanceRole::DEFAULT, std::get<1>(GetParam()), /*enable_prefix_cache=*/true); - ProfileManager profile_manager(&engine, options(InstanceRole::DEFAULT)); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + options(/*role=*/InstanceRole::DEFAULT), + make_scheduler_callbacks(&engine)); EXPECT_EQ(engine.prefill_batches(), (std::vector>{{10}})); @@ -449,7 +465,10 @@ TEST_P(LinearProfileGraphWarmupTest, DecodeOnlyWarmupAllocatesWorkingSlots) { /*linear_attention=*/true, InstanceRole::DECODE, std::get<1>(GetParam())); - ProfileManager profile_manager(&engine, options(InstanceRole::DECODE)); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + options(/*role=*/InstanceRole::DECODE), + make_scheduler_callbacks(&engine)); EXPECT_TRUE(engine.prefill_batches().empty()); EXPECT_GT(engine.decode_sequences(), 0); @@ -753,27 +772,6 @@ TEST(GraphWarmupTest, DecodeRoleUsesDecodeOnlyPlan) { GraphWarmupPlan::DECODE_ONLY); } -TEST(GraphWarmupTest, FormatsWarmupProgress) { - const std::string progress = graph_warmup_progress( - /*completed=*/3, /*total=*/8, /*token_bucket=*/8, /*latency_ms=*/12.5); - - EXPECT_EQ(progress, - "Graph warmup progress: [########------------] 3/8 37.5%, " - "token_bucket=8, latency=12.50 ms"); -} - -TEST(GraphWarmupTest, FormatsCompletedWarmupProgress) { - const std::string progress = graph_warmup_progress( - /*completed=*/8, - /*total=*/8, - /*token_bucket=*/64, - /*latency_ms=*/100.0); - - EXPECT_EQ(progress, - "Graph warmup progress: [####################] 8/8 100.0%, " - "token_bucket=64, latency=100.00 ms"); -} - TEST(GraphWarmupTest, InjectsBootstrapEmbeddingWhenSpeculativeEnabled) { Sequence sequence = make_sequence(/*index=*/0, /*tokens=*/{1, 2, 3}); @@ -866,8 +864,13 @@ TEST(GraphWarmupTest, PresetDpRankControlsBlockAllocation) { TEST(GraphWarmupTest, MarksOrdinaryProfileRequestsAsSyntheticLoad) { RecordingProfileEngine engine; ProfileManager::Options options; - options.max_tokens_per_batch(4).max_seqs_per_batch(1).dp_size(1); - ProfileManager profile_manager(&engine, options); + options.max_tokens_per_batch(/*value=*/4) + .max_seqs_per_batch(/*value=*/1) + .dp_size(/*value=*/1); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + options, + make_scheduler_callbacks(&engine)); engine.reset_profile_markers(); profile_manager.run_request(/*token_length=*/4, /*prefix_length=*/0); @@ -887,7 +890,10 @@ TEST(GraphWarmupTest, DecodeProfileUsesConfiguredSpeculativeGeometry) { .dp_size(1) .instance_role(InstanceRole::DECODE) .decode_graph_warmup_config(engine_options.decode_graph_warmup_config()); - ProfileManager profile_manager(&engine, options); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + options, + make_scheduler_callbacks(&engine)); profile_manager.profile_decode_step_time(/*token_length=*/5, /*batch_size=*/1, @@ -980,7 +986,10 @@ TEST(GraphWarmupTest, OrdinaryStepsWarmBucketsAndDrainBeforeReleasingKv) { /*num_speculative_tokens=*/0, /*enable_no_padding=*/false, /*max_graph_batch_size=*/4)); - ProfileManager profile_manager(&engine, options); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + options, + make_scheduler_callbacks(&engine)); EXPECT_EQ(engine.observed_batches(), (std::vector{4, 2, 1})); EXPECT_EQ(engine.pending_steps(), 0); EXPECT_EQ(engine.kv_cache_manager()->num_used_blocks(), used_blocks); @@ -1180,7 +1189,10 @@ TEST(GraphWarmupTest, PythonNoPaddingWarmsEverySequenceCount) { no_padding, /*max_graph_batch_size=*/4)); - ProfileManager profile_manager(&engine, options); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + options, + make_scheduler_callbacks(&engine)); std::vector expected = {4, 3, 2, 1}; if (!no_padding) { @@ -1220,7 +1232,10 @@ TEST(GraphWarmupTest, VmmUsesOrdinaryEagerWarmup) { .enable_profile_step_time(false) .instance_role(InstanceRole::DEFAULT); - ProfileManager profile_manager(&engine, options); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + options, + make_scheduler_callbacks(&engine)); EXPECT_EQ(engine.observed_batches(), (std::vector{1})); EXPECT_EQ(engine.observed_token_lengths(), (std::vector{16})); @@ -1250,7 +1265,10 @@ TEST(GraphWarmupTest, VmmDecodeOnlySkipsEagerWarmup) { .enable_profile_step_time(false) .instance_role(InstanceRole::DECODE); - ProfileManager profile_manager(&engine, options); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + options, + make_scheduler_callbacks(&engine)); EXPECT_TRUE(engine.observed_batches().empty()); EXPECT_EQ(engine.pending_steps(), 0); @@ -1279,7 +1297,10 @@ TEST(GraphWarmupTest, VmmGraphWarmupCanBeDisabled) { .enable_profile_step_time(false) .instance_role(InstanceRole::DEFAULT); - ProfileManager profile_manager(&engine, options); + ProfileManager profile_manager(engine.kv_cache_manager(), + &engine.model_args(), + options, + make_scheduler_callbacks(&engine)); EXPECT_TRUE(engine.observed_batches().empty()); EXPECT_EQ(engine.pending_steps(), 0); diff --git a/tests/core/scheduler/scheduler_policy_test.cpp b/tests/core/scheduler/scheduler_policy_test.cpp index 48cdb50320..b36678a8c4 100644 --- a/tests/core/scheduler/scheduler_policy_test.cpp +++ b/tests/core/scheduler/scheduler_policy_test.cpp @@ -42,6 +42,7 @@ limitations under the License. #include "core/framework/config/speculative_config.h" #include "core/kv_cache/layout/static_kv_layout.h" #include "core/kv_cache/manager/block_manager_pool.h" +#include "core/scheduler/fake_scheduling_engine_test_utils.h" #include "core/scheduler/request_output_dispatcher.h" #include "distributed_runtime/engine.h" #include "framework/model/model_args.h" @@ -72,7 +73,7 @@ class FakeTokenizer : public Tokenizer { } }; -class FakeEngine : public Engine { +class FakeEngine : public FakeSchedulingEngine { public: FakeEngine(int32_t num_blocks, int32_t block_size, @@ -95,14 +96,14 @@ class FakeEngine : public Engine { opt.linear_state_chunk_stride(linear_state_chunk_stride); model_args_.layer_types({"linear_attention"}); } - fake_tokenizer_ = std::make_unique(); - fake_block_manager_ = std::make_unique(opt, dp_size); + tokenizer_ = std::make_unique(); + block_manager_ = std::make_unique(opt, dp_size); } explicit FakeEngine(std::unique_ptr block_manager) - : fake_tokenizer_(std::make_unique()), - fake_block_manager_(std::move(block_manager)) { - const auto snapshot = fake_block_manager_->capacity_snapshot(/*dp_rank=*/0); + : FakeSchedulingEngine(std::move(block_manager)) { + tokenizer_ = std::make_unique(); + const auto snapshot = block_manager_->capacity_snapshot(/*dp_rank=*/0); if (snapshot && std::ranges::any_of( snapshot->partitions, [](const CachePartitionCapacity& partition) { @@ -111,24 +112,6 @@ class FakeEngine : public Engine { model_args_.layer_types({"linear_attention"}); } } - - virtual ForwardOutput step(BatchGroup& /*batch*/) { return {}; } - virtual std::vector collect_step_outputs( - const BatchGroup& /*batch*/) { - NOT_IMPLEMENTED(); - } - const Tokenizer* tokenizer() const { return fake_tokenizer_.get(); } - BlockManagerPool* kv_cache_manager() const override { - return fake_block_manager_.get(); - } - const ModelArgs& model_args() const override { return model_args_; } - const TokenizerArgs& tokenizer_args() const { NOT_IMPLEMENTED(); } - bool init() override { return true; } - - private: - std::unique_ptr fake_tokenizer_; - std::unique_ptr fake_block_manager_; - ModelArgs model_args_; }; class StaleCapacityBlockManagerPool final : public BlockManagerPool { @@ -633,30 +616,6 @@ void update_requests(std::vector> requests) { } } -class TestableContinuousScheduler final : public ContinuousScheduler<> { - public: - template - TestableContinuousScheduler(TargetEngine* engine, const Options& options) - : ContinuousScheduler<>(engine, - options, - /*model_residency_coordinator=*/nullptr, - /*distributed_worker_manager=*/nullptr) {} - - BatchGroup prepare_batch_test() { return prepare_batch(); } - - std::vector> get_running_requests() { - return running_requests_; - } - - std::vector get_running_sequences_budgets() { - return running_sequences_budgets_; - } - - ProfileManager* get_profile_manager() { return profile_manager_.get(); } - - void wait_for_responses() { output_dispatcher_->wait_completion(); } -}; - } // namespace TEST(SchedulerWarmupTest, ForwardsInstanceModeToProfileManager) { @@ -664,9 +623,9 @@ TEST(SchedulerWarmupTest, ForwardsInstanceModeToProfileManager) { class WarmupEngine final : public FakeEngine { public: WarmupEngine() : FakeEngine(/*num_blocks=*/64, /*block_size=*/4) { - warmup_args_.vocab_size(128).max_position_embeddings(16); + model_args_.vocab_size(/*value=*/128) + .max_position_embeddings(/*value=*/16); } - const ModelArgs& model_args() const override { return warmup_args_; } ForwardOutput step(BatchGroup& /*batch*/) override { ++steps_; return {}; @@ -674,7 +633,6 @@ TEST(SchedulerWarmupTest, ForwardsInstanceModeToProfileManager) { int32_t steps() const { return steps_; } private: - ModelArgs warmup_args_; int32_t steps_ = 0; }; for (const bool graph : {false, true}) { @@ -828,7 +786,7 @@ TEST(SchedulerPolicyTest, PrioritySettingsOverrideConflictingGlobals) { std::shared_ptr request = timed_request; ASSERT_TRUE(scheduler.add_request(request)); - scheduler.prepare_batch_test(); + scheduler.prepare_batch(); EXPECT_EQ(request->urgency(), expected_urgency); EXPECT_EQ(request->is_starved(), expected_starved); @@ -929,7 +887,7 @@ TEST(SchedulerPolicyTest, AdmissionThresholdOverridesConflictingGlobal) { ASSERT_TRUE(scheduler.add_request(request)); } - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); EXPECT_EQ(batches.front().size(), threshold == 0.5 ? 1u : 2u); @@ -963,7 +921,6 @@ TEST(SchedulerPolicyTest, AddNewRequestBase) { std::make_unique(num_blocks[idx], block_size[idx]); auto scheduler = std::make_unique(engine.get(), opt); - EXPECT_TRUE(scheduler != nullptr); EXPECT_EQ(scheduler->get_instance_info().kv_split_size, kv_split_size[idx]); // create requests @@ -973,7 +930,7 @@ TEST(SchedulerPolicyTest, AddNewRequestBase) { scheduler->add_request(req); } - auto batch = scheduler->prepare_batch_test(); + auto batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); const std::vector& allowed_max_tokens = batch[0].get_allowed_max_tokens(); @@ -1022,7 +979,7 @@ TEST(SchedulerPolicyTest, PrefillBudgetUsesInjectedFairAndChunkSwitches) { request->sequences().front()->set_dp_rank(0); ASSERT_TRUE(scheduler.add_request(request)); } - auto batches = scheduler.prepare_batch_test(); + auto batches = scheduler.prepare_batch(); size_t scheduled_tokens = 0; for (const Batch& batch : batches) { for (const uint32_t tokens : batch.get_allowed_max_tokens()) { @@ -1069,7 +1026,7 @@ TEST(SchedulerPolicyTest, NonChunkedPrefillAssignsDpBeforeFairBudget) { scheduler->add_request(requests[0]); scheduler->add_request(requests[1]); - BatchGroup batches = scheduler->prepare_batch_test(); + BatchGroup batches = scheduler->prepare_batch(); EXPECT_GE(requests[0]->sequences()[0]->dp_rank(), 0); EXPECT_LT(requests[0]->sequences()[0]->dp_rank(), kDpSize); @@ -1112,7 +1069,7 @@ TEST(SchedulerPolicyTest, UnifiedPrefixHitIncludesScheduledSuffixCapacity) { generate_request({kPromptTokens}, {1}, std::nullopt, std::nullopt, 10000); scheduler->add_request(requests[0]); - BatchGroup batches = scheduler->prepare_batch_test(); + BatchGroup batches = scheduler->prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches[0].size(), 1u); Sequence* hit_sequence = requests[0]->sequences()[0].get(); @@ -1211,7 +1168,7 @@ TEST(SchedulerPolicyTest, LinearSchedulingPreservesReadSourceAcrossPolicies) { size_t cached_tokens = 0; int32_t previous_output_id = -1; for (const size_t expected_tokens : {256, 256, 256, 9}) { - auto batches = scheduler.prepare_batch_test(); + auto batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); EXPECT_EQ(batches.front().get_allowed_max_tokens().front(), @@ -1258,7 +1215,7 @@ TEST(SchedulerPolicyTest, DecodeFirstSkipsRedistributionForLinearModels) { scheduler.add_request(requests.front()); size_t cached_tokens = 0; for (const size_t expected_tokens : {4u, 4u, 4u, 1u}) { - auto batches = scheduler.prepare_batch_test(); + auto batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); EXPECT_EQ(batches.front().get_allowed_max_tokens().front(), @@ -1318,7 +1275,7 @@ TEST(SchedulerPolicyTest, DecodeQueuePlansColdBestOfCandidatesAsPrefill) { first->kv_state().set_kv_cache_tokens_num(7); first->append_token(Token(/*id=*/1)); scheduler.add_request(request); - auto batches = scheduler.prepare_batch_test(); + auto batches = scheduler.prepare_batch(); ASSERT_EQ(request->sequences().size(), 2u); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 2u); @@ -1387,7 +1344,7 @@ TEST(SchedulerPolicyTest, LinearLatencySchedulingRespectsRemainingTokenBudget) { scheduler.add_request(request); } - auto batches = scheduler.prepare_batch_test(); + auto batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 2u); @@ -1403,7 +1360,7 @@ TEST(SchedulerPolicyTest, LinearLatencySchedulingRespectsRemainingTokenBudget) { .set_kv_cache_tokens_num( batches.front().get_allowed_max_tokens()[sequence_index]); } - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 2u); const uint32_t expected_first_tokens = @@ -1553,7 +1510,8 @@ TEST(SchedulerPolicyTest, UnifiedRetryRefreshesHostRestoreBeforeChunkSizing) { auto profile_engine = std::make_unique(512, 128); ProfileManager::Options profile_options; profile_options.max_tokens_per_batch(16384).max_seqs_per_batch(16); - ProfileManager profile_manager(profile_engine.get(), profile_options); + ProfileManager profile_manager = + make_profile_manager(*profile_engine, profile_options); std::vector> requests = generate_request({static_cast(kPromptTokens), @@ -1662,7 +1620,8 @@ TEST(SchedulerPolicyTest, UnifiedReclaimsMutuallyBlockedChunksWhenIdle) { BlockManagerPool* pool = engine.kv_cache_manager(); ProfileManager::Options profile_options; profile_options.max_tokens_per_batch(32).max_seqs_per_batch(2); - ProfileManager profile_manager(&engine, profile_options); + ProfileManager profile_manager = + make_profile_manager(engine, profile_options); auto requests = generate_request({96, 96}, {16, 16}, std::nullopt, @@ -1853,7 +1812,8 @@ TEST_P(AsyncBlockReleasePolicyTest, WaitsWithoutPreemptionThenRetries) { FakeEngine profile_engine(256, 128); ProfileManager::Options profile_options; profile_options.max_tokens_per_batch(1024).max_seqs_per_batch(16); - ProfileManager profile_manager(&profile_engine, profile_options); + ProfileManager profile_manager = + make_profile_manager(profile_engine, profile_options); auto requests = generate_request(std::vector(request_count, 128), std::vector(request_count, 16), std::nullopt, @@ -1973,7 +1933,8 @@ TEST_P(PendingVmmBatchPolicyTest, RetainsRequestsUntilBatchReleasesBlocks) { FakeEngine profile_engine(256, 128); ProfileManager::Options profile_options; profile_options.max_tokens_per_batch(1024).max_seqs_per_batch(16); - ProfileManager profile_manager(&profile_engine, profile_options); + ProfileManager profile_manager = + make_profile_manager(profile_engine, profile_options); auto requests = generate_request(std::vector(request_count, 128), std::vector(request_count, 16), std::nullopt, @@ -2078,7 +2039,8 @@ TEST(SchedulerPolicyTest, DefersWhileAsyncBlockReleaseIsPending) { auto profile_engine = std::make_unique(256, 128); ProfileManager::Options profile_options; profile_options.max_tokens_per_batch(16384).max_seqs_per_batch(16); - ProfileManager profile_manager(profile_engine.get(), profile_options); + ProfileManager profile_manager = + make_profile_manager(*profile_engine, profile_options); std::vector> requests = generate_request( {32000}, {2}, std::nullopt, std::nullopt, /*max_context_len=*/40000); @@ -2661,7 +2623,6 @@ TEST(SchedulerPolicyTest, ResourceNotEnough) { auto engine = std::make_unique(16, 16); auto scheduler = std::make_unique(engine.get(), opt); - EXPECT_TRUE(scheduler != nullptr); // request prompt len: 100 auto requests = @@ -2669,7 +2630,7 @@ TEST(SchedulerPolicyTest, ResourceNotEnough) { scheduler->add_request(requests[0]); scheduler->add_request(requests[1]); - auto batch = scheduler->prepare_batch_test(); + auto batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 1); // can not schedule the second. } @@ -2679,14 +2640,13 @@ TEST(SchedulerPolicyTest, ResourceNotEnough) { SchedulerOptions opt = create_scheduler_options(1000, 256, 0, 1024, 1); // free block slot: 1 auto engine = std::make_unique(2, 8); + std::optional callback_status; auto scheduler = std::make_unique(engine.get(), opt); - EXPECT_TRUE(scheduler != nullptr); // request prompt len: 1000 auto requests = generate_request( {1, 1000}, {1, 100}, std::nullopt, std::nullopt, 10000); - std::optional callback_status; requests[1]->state().output_func = [&](const RequestOutput& output) { callback_status = output.status; return true; @@ -2694,7 +2654,7 @@ TEST(SchedulerPolicyTest, ResourceNotEnough) { scheduler->add_request(requests[0]); scheduler->add_request(requests[1]); - auto batch = scheduler->prepare_batch_test(); + auto batch = scheduler->prepare_batch(); scheduler->wait_for_responses(); ASSERT_EQ(batch.size(), 1u); EXPECT_EQ(batch[0].size(), 1u); @@ -2718,7 +2678,6 @@ TEST(SchedulerPolicyTest, NormalSchedule) { auto engine = std::make_unique(block_num, block_size); auto scheduler = std::make_unique(engine.get(), opt); - EXPECT_TRUE(scheduler != nullptr); // 1. schedule some new prefill requests auto requests = generate_request( @@ -2737,7 +2696,7 @@ TEST(SchedulerPolicyTest, NormalSchedule) { update_requests(requests); // 2. schedule decoding requests - batch = scheduler->prepare_batch_test(); + batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 3); update_requests(requests); @@ -2748,7 +2707,7 @@ TEST(SchedulerPolicyTest, NormalSchedule) { for (auto req : requests1) { scheduler->add_request(req); } - batch = scheduler->prepare_batch_test(); + batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 5); update_requests(requests); @@ -2762,7 +2721,7 @@ TEST(SchedulerPolicyTest, NormalSchedule) { for (auto req : requests2) { scheduler->add_request(req); } - batch = scheduler->prepare_batch_test(); + batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 6); const std::vector& allowed_max_tokens = @@ -2781,7 +2740,7 @@ TEST(SchedulerPolicyTest, NormalSchedule) { for (auto req : requests3) { scheduler->add_request(req); } - batch = scheduler->prepare_batch_test(); + batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 7); const std::vector& allowed_max_tokens1 = @@ -2805,7 +2764,6 @@ TEST(SchedulerPolicyTest, PreemptSchedule) { auto engine = std::make_unique(block_num, block_size); auto scheduler = std::make_unique(engine.get(), opt); - EXPECT_TRUE(scheduler != nullptr); std::vector> running_requests; @@ -2817,12 +2775,12 @@ TEST(SchedulerPolicyTest, PreemptSchedule) { for (auto req : requests) { scheduler->add_request(req); } - auto batch = scheduler->prepare_batch_test(); + auto batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 2); update_requests(running_requests); - batch = scheduler->prepare_batch_test(); + batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 2); update_requests(running_requests); @@ -2830,7 +2788,7 @@ TEST(SchedulerPolicyTest, PreemptSchedule) { BlockManagerPool* block_manager_pool = engine->kv_cache_manager(); int free_blocks_before_preempt = util::max(block_manager_pool->num_free_blocks()); - batch = scheduler->prepare_batch_test(); + batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 1); int free_blocks_after_preempt = @@ -2847,7 +2805,7 @@ TEST(SchedulerPolicyTest, PreemptSchedule) { // it just like a new prefill request. // Continue to run, the new prefill request will not preempt // request in running_queue. - batch = scheduler->prepare_batch_test(); + batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 1); } @@ -2866,7 +2824,6 @@ TEST(SchedulerPolicyTest, PrioritySchedule) { auto engine = std::make_unique(block_num, block_size); auto scheduler = std::make_unique(engine.get(), opt); - EXPECT_TRUE(scheduler != nullptr); std::vector> running_requests; @@ -2879,7 +2836,7 @@ TEST(SchedulerPolicyTest, PrioritySchedule) { for (auto req : requests) { scheduler->add_request(req); } - auto batch = scheduler->prepare_batch_test(); + auto batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 2); EXPECT_TRUE(scheduler->get_running_requests().size() == 2); @@ -2898,7 +2855,7 @@ TEST(SchedulerPolicyTest, PrioritySchedule) { std::vector{1}, 30000); // use 1 blocks scheduler->add_request(new_requests[0]); - batch = scheduler->prepare_batch_test(); + batch = scheduler->prepare_batch(); // check there are 3 running requests owing to decode-maximal EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 3); @@ -2906,7 +2863,7 @@ TEST(SchedulerPolicyTest, PrioritySchedule) { running_requests.push_back(new_requests[0]); update_requests(running_requests); // preemption happens, only HIGH and NORMAL decode requests - batch = scheduler->prepare_batch_test(); + batch = scheduler->prepare_batch(); EXPECT_TRUE(batch.size() == 1); EXPECT_TRUE(batch[0].size() == 2); EXPECT_TRUE(scheduler->get_running_requests().size() == 2); @@ -2937,7 +2894,6 @@ TEST(SchedulerPolicyTest, LatencySchedule) { auto engine = std::make_unique(block_num, block_size); auto scheduler = std::make_unique(engine.get(), opt); - EXPECT_TRUE(scheduler != nullptr); // manually created profile data for y=0.5x^2+10x std::vector> created_profile_data = { @@ -2961,7 +2917,7 @@ TEST(SchedulerPolicyTest, LatencySchedule) { for (auto req : requests) { scheduler->add_request(req); } - auto batch = scheduler->prepare_batch_test(); + auto batch = scheduler->prepare_batch(); EXPECT_EQ(batch.size(), 1); EXPECT_EQ(batch[0].size(), 3); EXPECT_EQ(scheduler->get_running_requests().size(), 3); @@ -2972,7 +2928,7 @@ TEST(SchedulerPolicyTest, LatencySchedule) { auto new_requests = generate_request( {10}, {10}, std::nullopt, std::nullopt, 30000); // use 1 blocks scheduler->add_request(new_requests[0]); - batch = scheduler->prepare_batch_test(); + batch = scheduler->prepare_batch(); auto running_sequences_budgets = scheduler->get_running_sequences_budgets(); EXPECT_EQ(batch.size(), 1); @@ -3020,7 +2976,7 @@ TEST(SchedulerPolicyTest, FullFootprintAdmissionGate) { scheduler->add_request(requests[0]); scheduler->add_request(requests[1]); - auto batch = scheduler->prepare_batch_test(); + auto batch = scheduler->prepare_batch(); ASSERT_EQ(batch.size(), 1); // Only A admitted. B blocked: after A uses 1 block, available=8-1=7 < 8. EXPECT_EQ(batch[0].size(), 1); @@ -3056,7 +3012,7 @@ TEST(SchedulerPolicyTest, FullFootprintAdmitsBothWhenFits) { scheduler->add_request(requests[0]); scheduler->add_request(requests[1]); - auto batch = scheduler->prepare_batch_test(); + auto batch = scheduler->prepare_batch(); ASSERT_EQ(batch.size(), 1); EXPECT_EQ(batch[0].size(), 2); // Both admitted. } @@ -3088,7 +3044,7 @@ TEST(SchedulerPolicyTest, SharedArenaAdmissionReservesFullAndLinearResources) { ASSERT_TRUE(scheduler.add_request(requests[0])); ASSERT_TRUE(scheduler.add_request(requests[1])); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); EXPECT_EQ(batches.front().size(), 1u); @@ -3166,7 +3122,7 @@ TEST(SchedulerPolicyTest, StaleCapacityReservesFullPromptBeforeFirstChunk) { // A completed request can free physical pages before the next advisory // snapshot. The first chunk must probe the real allocator and retain // the full three-block prompt reservation without advancing computation. - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); Sequence* sequence = request->sequences().front().get(); @@ -3236,7 +3192,7 @@ TEST(SchedulerPolicyTest, StaleCapacityDefersFailedFullPromptReservation) { // Another owner temporarily holds the pages. Failed admission must leave // the request queued and return without retrying within the same round. for (size_t attempt = 0; attempt < 2; ++attempt) { - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); EXPECT_TRUE(batches.front().empty()); @@ -3252,7 +3208,7 @@ TEST(SchedulerPolicyTest, StaleCapacityDefersFailedFullPromptReservation) { } pool->deallocate(blocker.get()); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); @@ -3307,7 +3263,7 @@ TEST(SchedulerPolicyTest, PersistentPrefillAllocationFailureUnblocksFollower) { constexpr size_t kRetryLimit = 4096; for (size_t attempt = 0; attempt < kRetryLimit; ++attempt) { pool->set_fail_on_attempt(pool->allocation_attempts() + 1); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_TRUE(batches.front().empty()); } @@ -3320,7 +3276,7 @@ TEST(SchedulerPolicyTest, PersistentPrefillAllocationFailureUnblocksFollower) { EXPECT_EQ(pool->num_free_blocks(), initial_free_blocks); pool->set_fail_on_attempt(/*attempt=*/0); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); EXPECT_EQ(batches.front()[0], requests.back()->sequences().front().get()); @@ -3370,7 +3326,7 @@ TEST(SchedulerPolicyTest, SuccessfulPrefillResetsAllocationFailureWindow) { sequence->kv_state().set_kv_cache_tokens_num(computed_tokens); for (size_t attempt = 0; attempt < kFailuresBeforeRecovery; ++attempt) { pool->set_fail_on_attempt(pool->allocation_attempts() + 1); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_TRUE(batches.front().empty()); } @@ -3378,7 +3334,7 @@ TEST(SchedulerPolicyTest, SuccessfulPrefillResetsAllocationFailureWindow) { ASSERT_FALSE(callback_status.has_value()); pool->set_fail_on_attempt(/*attempt=*/0); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); EXPECT_EQ(batches.front()[0], sequence); @@ -3423,7 +3379,7 @@ TEST(SchedulerPolicyTest, TransientDecodeAllocationFailurePreservesRequest) { return true; }; ASSERT_TRUE(scheduler.add_request(request)); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); Sequence* sequence = request->sequences().front().get(); @@ -3439,7 +3395,7 @@ TEST(SchedulerPolicyTest, TransientDecodeAllocationFailurePreservesRequest) { // The first decode token crosses the four-token block boundary. A // transient mapping failure must not discard the completed prompt. - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); EXPECT_TRUE(batches.front().empty()); @@ -3454,7 +3410,7 @@ TEST(SchedulerPolicyTest, TransientDecodeAllocationFailurePreservesRequest) { EXPECT_EQ(pool->num_free_blocks(), free_blocks_before); EXPECT_EQ(pool->allocation_attempts(), successful_allocations + 1); - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); @@ -3496,7 +3452,7 @@ TEST(SchedulerPolicyTest, DecodeAllocationFailureDefersNewPrefill) { for (auto& request : requests) { ASSERT_TRUE(scheduler.add_request(request)); } - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 2u); update_requests(requests); @@ -3516,7 +3472,7 @@ TEST(SchedulerPolicyTest, DecodeAllocationFailureDefersNewPrefill) { // The first decode grows successfully; the second mapping fails. Keep the // successful decode, but do not spend more memory on a new prefill. - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); @@ -3534,7 +3490,7 @@ TEST(SchedulerPolicyTest, DecodeAllocationFailureDefersNewPrefill) { // waiting prefill alongside both existing decodes on the next pass. progressing->kv_state().set_kv_cache_tokens_num(5); progressing->append_token(Token(1)); - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 3u); @@ -3575,7 +3531,7 @@ TEST(SchedulerPolicyTest, ChunkAllocationFailureDefersOtherPrefillQueue) { auto chunked = generate_request({12}, {4}, std::nullopt, std::nullopt, 64)[0]; ASSERT_TRUE(scheduler.add_request(chunked)); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); Sequence* sequence = chunked->sequences().front().get(); @@ -3595,7 +3551,7 @@ TEST(SchedulerPolicyTest, ChunkAllocationFailureDefersOtherPrefillQueue) { // A blocked continuation must not trigger another allocation through the // separate fresh-prefill queue, or discard its already computed prefix. - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); EXPECT_TRUE(batches.front().empty()); @@ -3610,7 +3566,7 @@ TEST(SchedulerPolicyTest, ChunkAllocationFailureDefersOtherPrefillQueue) { pool->deallocate(holder.get()); for (const size_t completed_tokens : {4u, 8u}) { sequence->kv_state().set_kv_cache_tokens_num(completed_tokens); - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); EXPECT_EQ(batches.front()[0], sequence); @@ -3619,7 +3575,7 @@ TEST(SchedulerPolicyTest, ChunkAllocationFailureDefersOtherPrefillQueue) { } sequence->kv_state().set_kv_cache_tokens_num(12); sequence->append_token(Token(1)); - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); bool fresh_scheduled = false; @@ -3662,7 +3618,7 @@ TEST(SchedulerPolicyTest, StaticCapacityRejectsDecodeBeyondArena) { return true; }; ASSERT_TRUE(scheduler.add_request(request)); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); Sequence* sequence = request->sequences().front().get(); @@ -3672,7 +3628,7 @@ TEST(SchedulerPolicyTest, StaticCapacityRejectsDecodeBeyondArena) { // Padding leaves two usable blocks. The next decode token needs a third // block, which cannot fit even after all other owners release memory. - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); EXPECT_TRUE(batches.front().empty()); @@ -3711,7 +3667,7 @@ TEST(SchedulerPolicyTest, IdleChunkContinuationExceedsUtilizationThreshold) { return true; }; ASSERT_TRUE(scheduler.add_request(request)); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); EXPECT_EQ(batches.front().get_allowed_max_tokens(), @@ -3726,7 +3682,7 @@ TEST(SchedulerPolicyTest, IdleChunkContinuationExceedsUtilizationThreshold) { // No decode or other executable request can lower utilization. The // continuation must be allowed to allocate its last prompt block. - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); @@ -3779,7 +3735,7 @@ TEST(SchedulerPolicyTest, StaticCapacityRejectsPromptWithoutReservation) { // Ten prompt blocks exceed the configured nine-block arena. This is a // permanent size limit, so no physical reservation should be attempted. - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); EXPECT_TRUE(batches.front().empty()); @@ -3826,7 +3782,7 @@ TEST(SchedulerPolicyTest, StaticCapacityRejectsBestOfWithoutReservation) { }; ASSERT_TRUE(scheduler.add_request(request)); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); EXPECT_TRUE(batches.front().empty()); @@ -3871,7 +3827,7 @@ TEST(SchedulerPolicyTest, StaticCapacityRejectsPromptWithActiveRequest) { std::shared_ptr& active = requests[0]; std::shared_ptr& oversized = requests[1]; ASSERT_TRUE(scheduler.add_request(active)); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); Sequence* active_sequence = active->sequences().front().get(); @@ -3886,7 +3842,7 @@ TEST(SchedulerPolicyTest, StaticCapacityRejectsPromptWithActiveRequest) { }; ASSERT_TRUE(scheduler.add_request(oversized)); - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); @@ -3933,7 +3889,7 @@ TEST(SchedulerPolicyTest, BestOfAllocationFailureKeepsSuccessfulSequence) { "best-of-fresh", "best-of-fresh", "", std::move(request_state), ""); ASSERT_TRUE(scheduler.add_request(request)); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); @@ -3951,7 +3907,7 @@ TEST(SchedulerPolicyTest, BestOfAllocationFailureKeepsSuccessfulSequence) { first->kv_state().blocks(BlockType::KV).front().id(); first->kv_state().set_kv_cache_tokens_num(4); - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 2u); EXPECT_EQ(batches.front()[0], first); @@ -4002,7 +3958,7 @@ TEST(SchedulerPolicyTest, BestOfAllocationFailurePreservesExistingChunk) { ASSERT_EQ(first->kv_state().num_blocks(BlockType::KV), 1u); ASSERT_TRUE(scheduler.add_request(request)); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); @@ -4049,8 +4005,8 @@ TEST(SchedulerPolicyTest, BestOfPartialAdmissionReleasesPrefixUsage) { pool->publish_prefix(cached_sequence); pool->deallocate(cached_request.get()); - TestableContinuousScheduler scheduler(&engine, options); std::optional cancelled_response; + TestableContinuousScheduler scheduler(&engine, options); RequestState request_state = generate_request({12}, {4}, std::nullopt, std::nullopt, 64)[0] ->state() @@ -4067,7 +4023,7 @@ TEST(SchedulerPolicyTest, BestOfPartialAdmissionReleasesPrefixUsage) { ASSERT_TRUE(scheduler.add_request(request)); const std::vector used_blocks_before = pool->num_used_blocks(); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 1u); @@ -4084,7 +4040,7 @@ TEST(SchedulerPolicyTest, BestOfPartialAdmissionReleasesPrefixUsage) { first->kv_state().blocks(BlockType::KV).back().id(); first->kv_state().set_kv_cache_tokens_num(8); - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); ASSERT_EQ(batches.size(), 1u); ASSERT_EQ(batches.front().size(), 2u); EXPECT_EQ(batches.front()[0], first); @@ -4096,7 +4052,7 @@ TEST(SchedulerPolicyTest, BestOfPartialAdmissionReleasesPrefixUsage) { EXPECT_EQ(pool->allocation_attempts(), 4u); request->set_cancel(); - batches = scheduler.prepare_batch_test(); + batches = scheduler.prepare_batch(); scheduler.wait_for_responses(); ASSERT_EQ(batches.size(), 1u); EXPECT_TRUE(batches.front().empty()); diff --git a/xllm/api_service/CMakeLists.txt b/xllm/api_service/CMakeLists.txt index c3cce612c0..382c5a4cae 100644 --- a/xllm/api_service/CMakeLists.txt +++ b/xllm/api_service/CMakeLists.txt @@ -66,7 +66,6 @@ cc_library( non_stream_call.h multipart_form_data.h service_impl_factory.h - serving_mode.h stream_call.h models_service_impl.h mm_service_utils.h diff --git a/xllm/api_service/api_service.cpp b/xllm/api_service/api_service.cpp index 600a4deacf..0ac8efdcf3 100644 --- a/xllm/api_service/api_service.cpp +++ b/xllm/api_service/api_service.cpp @@ -37,7 +37,6 @@ limitations under the License. #include "api_service/request_id.h" #include "api_service/rpc_request_metrics.h" #include "api_service/service_impl_factory.h" -#include "api_service/serving_mode.h" #include "call.h" #include "chat.pb.h" #include "common.pb.h" @@ -535,7 +534,7 @@ void APIService::register_chat_completions_handler() { ctrl, request, response, - ChatJsonParser::get(ServingMode::VLM), + ChatJsonParser::get(/*engine_type=*/EngineType::VLM), default_model_, system_fingerprint_); }; @@ -550,7 +549,7 @@ void APIService::register_chat_completions_handler() { ctrl, request, response, - ChatJsonParser::get(ServingMode::LLM), + ChatJsonParser::get(/*engine_type=*/EngineType::LLM), default_model_, system_fingerprint_); }; diff --git a/xllm/api_service/api_service_benchmark.cpp b/xllm/api_service/api_service_benchmark.cpp index 1cf199862c..6c1d72c8a3 100644 --- a/xllm/api_service/api_service_benchmark.cpp +++ b/xllm/api_service/api_service_benchmark.cpp @@ -73,7 +73,6 @@ limitations under the License. #include "api_service/chat_json_parser.h" #include "api_service/chat_request_decoder.h" #include "api_service/completion_json_parser.h" -#include "api_service/serving_mode.h" #include "chat.pb.h" #include "completion.pb.h" #include "core/framework/request/request_output.h" @@ -88,7 +87,7 @@ namespace { // local resolves to the deprecated one. Sinking the value into a non-const // parameter first selects the supported overload. template -inline BENCHMARK_ALWAYS_INLINE void do_not_optimize(T value) { +[[gnu::always_inline]] inline void do_not_optimize(T value) { benchmark::DoNotOptimize(value); } @@ -260,7 +259,8 @@ void BM_ApiService_CompletionJsonToProto(benchmark::State& state) { void BM_ApiService_ChatJsonToProto(benchmark::State& state) { const std::string body = make_chat_json(static_cast(state.range(0))); - const ChatJsonParser& parser = ChatJsonParser::get(ServingMode::LLM); + const ChatJsonParser& parser = + ChatJsonParser::get(/*engine_type=*/EngineType::LLM); proto::ChatRequest request; for (auto _ : state) { @@ -279,8 +279,9 @@ void BM_ApiService_ChatJsonToProto(benchmark::State& state) { // the decoder has to carve out, plus chat_template_kwargs. void BM_ApiService_ChatToolsJsonToProto(benchmark::State& state) { const std::string body = - make_chat_tools_json(static_cast(state.range(0))); - const ChatJsonParser& parser = ChatJsonParser::get(ServingMode::LLM); + make_chat_tools_json(static_cast(state.range(/*pos=*/0))); + const ChatJsonParser& parser = + ChatJsonParser::get(/*engine_type=*/EngineType::LLM); proto::ChatRequest request; for (auto _ : state) { @@ -366,7 +367,8 @@ void BM_ApiService_CompletionJson2PbOnly(benchmark::State& state) { void BM_ApiService_ChatPreprocessOnly(benchmark::State& state) { const std::string body = make_chat_json(static_cast(state.range(0))); - const ChatJsonParser& parser = ChatJsonParser::get(ServingMode::LLM); + const ChatJsonParser& parser = + ChatJsonParser::get(/*engine_type=*/EngineType::LLM); for (auto _ : state) { auto [status, processed_json] = parser.preprocess(body); @@ -379,7 +381,8 @@ void BM_ApiService_ChatPreprocessOnly(benchmark::State& state) { void BM_ApiService_ChatJsonToMessageOnly(benchmark::State& state) { const std::string body = make_chat_json(static_cast(state.range(0))); - const ChatJsonParser& parser = ChatJsonParser::get(ServingMode::LLM); + const ChatJsonParser& parser = + ChatJsonParser::get(/*engine_type=*/EngineType::LLM); auto [status, processed_json] = parser.preprocess(body); if (!status.ok()) { state.SkipWithError("failed to preprocess the benchmark body"); @@ -407,7 +410,8 @@ void BM_ApiService_ChatJsonToMessageOnly(benchmark::State& state) { // the bodies here carry no such field, so this measures the fast path only. void BM_ApiService_ChatJson2PbOnly(benchmark::State& state) { const std::string body = make_chat_json(static_cast(state.range(0))); - const ChatJsonParser& parser = ChatJsonParser::get(ServingMode::LLM); + const ChatJsonParser& parser = + ChatJsonParser::get(/*engine_type=*/EngineType::LLM); auto [status, processed_json] = parser.preprocess(body); if (!status.ok()) { state.SkipWithError("failed to preprocess the benchmark body"); diff --git a/xllm/api_service/chat_json_parser.cpp b/xllm/api_service/chat_json_parser.cpp index 665d1fbadb..5a9f2eb87d 100644 --- a/xllm/api_service/chat_json_parser.cpp +++ b/xllm/api_service/chat_json_parser.cpp @@ -73,8 +73,8 @@ Status normalize_tool_choice(nlohmann::json* json, bool* modified) { } // namespace -const ChatJsonParser& ChatJsonParser::get(ServingMode mode) { - if (mode == ServingMode::VLM) { +const ChatJsonParser& ChatJsonParser::get(EngineType engine_type) { + if (engine_type == EngineType::VLM) { static const VlmChatJsonParser k_vlm_parser; return k_vlm_parser; } diff --git a/xllm/api_service/chat_json_parser.h b/xllm/api_service/chat_json_parser.h index 04260d008e..33a030b97f 100644 --- a/xllm/api_service/chat_json_parser.h +++ b/xllm/api_service/chat_json_parser.h @@ -18,7 +18,6 @@ limitations under the License. #include #include -#include "api_service/serving_mode.h" #include "core/common/types.h" namespace xllm { @@ -33,11 +32,8 @@ class ChatJsonParser { [[nodiscard]] virtual std::pair preprocess( std::string json_str) const = 0; - // Returns the singleton parser for the given serving mode. - // LLM → LlmChatJsonParser, VLM → VlmChatJsonParser. - static const ChatJsonParser& get(ServingMode mode); + static const ChatJsonParser& get(EngineType engine_type); - // Returns the Anthropic protocol parser (separate from serving mode). static const ChatJsonParser& anthropic(); }; diff --git a/xllm/api_service/generation_master.h b/xllm/api_service/generation_master.h index c3009ca1d1..12b8481385 100644 --- a/xllm/api_service/generation_master.h +++ b/xllm/api_service/generation_master.h @@ -109,12 +109,6 @@ class GenerationMaster final { }); } - bool handle_rpc_response(const RequestOutput& output) const { - return visit([&](const auto& master) { - return master->handle_rpc_response(output); - }); - } - private: Masters master_; }; diff --git a/xllm/api_service/service_impl_factory.cpp b/xllm/api_service/service_impl_factory.cpp index edb5298608..4dfbfc5f8f 100644 --- a/xllm/api_service/service_impl_factory.cpp +++ b/xllm/api_service/service_impl_factory.cpp @@ -21,7 +21,6 @@ limitations under the License. #include #include "api_service.h" -#include "api_service/serving_mode.h" #include "core/common/global_flags.h" #include "core/distributed_runtime/dit_master.h" #include "core/distributed_runtime/llm_master.h" @@ -39,8 +38,8 @@ void ServiceImplFactory::create( using InitFn = std::function&)>; - static const std::unordered_map kRegistry = { - {static_cast(ServingMode::LLM), + static const std::unordered_map kRegistry = { + {EngineType::LLM, [](APIService* self, Master* master, const std::vector& models) { @@ -66,7 +65,7 @@ void ServiceImplFactory::create( llm_master, models, self->master_manager_); } }}, - {static_cast(ServingMode::VLM), + {EngineType::VLM, [](APIService* self, Master* master, const std::vector& models) { @@ -92,7 +91,7 @@ void ServiceImplFactory::create( std::make_unique( vlm_master, models, SpeechToTextTask::TRANSLATE); }}, - {static_cast(ServingMode::DIT), + {EngineType::DIT, [](APIService* self, Master* master, const std::vector& models) { @@ -109,8 +108,8 @@ void ServiceImplFactory::create( }}, }; - ServingMode mode = to_serving_mode(master->options().backend()); - auto it = kRegistry.find(static_cast(mode)); + const EngineType mode(master->options().backend()); + auto it = kRegistry.find(mode); if (it != kRegistry.end()) { it->second(service, master, model_names); } else { diff --git a/xllm/api_service/serving_mode.h b/xllm/api_service/serving_mode.h deleted file mode 100644 index acb55bb547..0000000000 --- a/xllm/api_service/serving_mode.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright 2025-2026 The xLLM Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - https://github.com/xLLM-AI/xllm/blob/main/LICENSE - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#pragma once - -#include -#include - -#include "core/common/types.h" - -namespace xllm { - -// Service-layer abstraction of the active serving pipeline. -// Unlike EngineType (which includes engine-internal variants such as SSM), -// ServingMode only exposes the distinctions that matter to the API surface. -enum class ServingMode : int8_t { - LLM = 0, - VLM = 1, - DIT = 2, -}; - -// Maps an engine-layer EngineType to its corresponding ServingMode. -// SSM (speculative decoding) serves the same API as LLM. VLMSSM is the -// speculative variant of VLM and keeps the VLM API surface. -inline ServingMode to_serving_mode(EngineType engine_type) { - switch (static_cast(engine_type)) { - case EngineType::VLM: - case EngineType::VLMSSM: - return ServingMode::VLM; - case EngineType::DIT: - return ServingMode::DIT; - default: - return ServingMode::LLM; - } -} - -inline ServingMode to_serving_mode(const std::string& backend) { - return to_serving_mode(EngineType(backend)); -} - -} // namespace xllm diff --git a/xllm/core/common/types.h b/xllm/core/common/types.h index 3e30229c0a..809b5628e4 100644 --- a/xllm/core/common/types.h +++ b/xllm/core/common/types.h @@ -33,10 +33,8 @@ class EngineType { public: enum Value : int8_t { LLM = 0, - SSM = 1, VLM = 2, DIT = 3, - VLMSSM = 5, INVALID = -1, }; @@ -44,12 +42,8 @@ class EngineType { EngineType(const std::string& str) { if (str == "LLM" || str == "llm") { value_ = LLM; - } else if (str == "SSM" || str == "ssm") { - value_ = SSM; } else if (str == "VLM" || str == "vlm") { value_ = VLM; - } else if (str == "VLMSSM" || str == "vlmssm") { - value_ = VLMSSM; } else if (str == "DIT" || str == "dit") { value_ = DIT; } else { @@ -70,12 +64,8 @@ class EngineType { constexpr const char* to_string() const { if (this->value_ == LLM) { return "LLM"; - } else if (this->value_ == SSM) { - return "SSM"; } else if (this->value_ == VLM) { return "VLM"; - } else if (this->value_ == VLMSSM) { - return "VLMSSM"; } else if (this->value_ == DIT) { return "DIT"; } diff --git a/xllm/core/disaggregation/pd_scheduler.cpp b/xllm/core/disaggregation/pd_scheduler.cpp index f85121110e..eb04017cc3 100644 --- a/xllm/core/disaggregation/pd_scheduler.cpp +++ b/xllm/core/disaggregation/pd_scheduler.cpp @@ -22,6 +22,7 @@ limitations under the License. #include #include +#include #include #include #include @@ -34,12 +35,13 @@ limitations under the License. #include "core/framework/config/disagg_pd_config.h" #include "core/framework/config/service_config.h" #include "core/framework/config/speculative_config.h" +#include "core/framework/model/model_args.h" #include "core/kv_cache/manager/kv_cache_manager.h" #include "core/kv_cache/transfer/pd_topology_guard.h" +#include "core/scheduler/profile/profile_manager.h" #include "core/util/scope_guard.h" #include "core/util/tensor_codec.h" #include "disagg_pd.pb.h" -#include "distributed_runtime/engine.h" #include "distributed_runtime/xservice_client.h" #include "framework/request/request.h" #include "framework/request/request_state.h" @@ -261,7 +263,7 @@ void PDScheduler::register_instance_info(const std::string& server_name) { void PDScheduler::profile_ttft() { LOG(INFO) << "Start profiling TTFT."; // get the maximum prefill token length - auto& model_args = engine_->model_args(); + auto& model_args = *model_args_; int32_t max_context_len = model_args.max_position_embeddings(); if (!options_.enable_chunked_prefill()) { max_context_len = @@ -283,14 +285,15 @@ void PDScheduler::profile_ttft() { void PDScheduler::profile_tpot() { LOG(INFO) << "Start profiling TPOT."; // get the maximum token length - auto& model_args = engine_->model_args(); + auto& model_args = *model_args_; int32_t max_context_len = model_args.max_position_embeddings(); if (!options_.enable_chunked_prefill()) { max_context_len = std::min(max_context_len, options_.max_tokens_per_batch()); } - const size_t resource_capacity = kv_cache_manager_->admission_capacity(0); + const size_t resource_capacity = + kv_cache_manager_->admission_capacity(/*dp_rank=*/0); int32_t block_size = kv_cache_manager_->block_size(); int32_t max_seqs_per_batch = options_.max_seqs_per_batch(); const size_t request_units = kv_cache_manager_->sequence_resource_units( @@ -322,8 +325,7 @@ void PDScheduler::profile_tpot() { } void PDScheduler::start_rpc_server(PDServiceOptions response_options) { - auto service = - std::make_unique(this, engine_, std::move(response_options)); + auto service = std::make_unique(this, std::move(response_options)); const int32_t port = ::xllm::DisaggPDConfig::get_instance().disagg_pd_port(); auto rpc_server = ServerRegistry::get_instance().register_server(server_name_); @@ -334,7 +336,7 @@ void PDScheduler::start_rpc_server(PDServiceOptions response_options) { } void PDScheduler::step(const absl::Duration& timeout) { - ContinuousSchedulerBase::step(timeout); + ContinuousScheduler::step(timeout); // Send first generation token to decode instance. // Always check (not gated on last_step_prefill_) because chunked prefill // mode does not set that flag and a chunked prefill may complete at any step. @@ -346,7 +348,7 @@ void PDScheduler::step(const absl::Duration& timeout) { } size_t PDScheduler::num_queued_requests() const { - return ContinuousSchedulerBase::num_queued_requests() + + return ContinuousScheduler::num_queued_requests() + pending_dispatch_requests_; } @@ -372,7 +374,7 @@ bool PDScheduler::enqueue_dispatched_request(std::shared_ptr request) { { std::lock_guard lock(request_admission_mutex_); CHECK_GT(pending_dispatch_requests_, 0u); - queued = ContinuousSchedulerBase::enqueue_ready_request(request); + queued = ContinuousScheduler::enqueue_ready_request(request); --pending_dispatch_requests_; } if (!queued) { @@ -792,7 +794,7 @@ void PDScheduler::prefill_send_first_generation() { group->add_ids(static_cast(block.id())); } } - if (has_linear_attention_layers(engine_->model_args())) { + if (has_linear_attention_layers(*model_args_)) { const int32_t linear_state_id = sequence->get_linear_state_slot_id(); CHECK_GE(linear_state_id, 0) << "Prefill did not allocate a linear-state slot."; @@ -1254,6 +1256,27 @@ void PDScheduler::restore_disaggregated_latency( } } +void PDScheduler::start_runtime(PDServiceOptions response_options) { + CHECK(distributed_worker_manager_ != nullptr) + << "Disaggregated PD requires a distributed worker manager."; + CHECK(kv_transfer_coordinator_ != nullptr) + << "Disaggregated PD requires a KV cache transfer coordinator."; + dispatch_thread_ = + std::make_unique(&PDScheduler::dispatch_requests, this); + server_name_.append(std::to_string(options_.server_idx())); + rpc_server_thread_ = std::make_unique( + [this, response_options = std::move(response_options)]() mutable { + start_rpc_server(std::move(response_options)); + }); + initialize_rpc_server(server_name_); + register_instance_info(server_name_); + if (!options_.disable_ttft_profiling() && + options_.instance_role().value() == InstanceRole::MIX) { + profile_ttft(); + profile_tpot(); + } +} + bool PDScheduler::try_allocate(Sequence* sequence) { // When the KV Cache usage reaches the threshold, prefill requests will no // longer be scheduled to avoid frequent preemption. diff --git a/xllm/core/disaggregation/pd_scheduler.h b/xllm/core/disaggregation/pd_scheduler.h index b3685bb4d0..66aeef7987 100644 --- a/xllm/core/disaggregation/pd_scheduler.h +++ b/xllm/core/disaggregation/pd_scheduler.h @@ -17,7 +17,6 @@ limitations under the License. #include -#include #include #include #include @@ -26,7 +25,6 @@ limitations under the License. #include #include #include -#include #include #include @@ -52,53 +50,9 @@ bool is_permanent_rejection(int32_t status_code); bool has_rank_preserving_kv_groups(const proto::DisaggResponse& response); -class PDScheduler : public ContinuousScheduler<> { +class PDScheduler : public ContinuousScheduler { public: - // Skips dispatch and RPC startup. Unit tests construct through this so they - // do not block in initialize_rpc_server. - struct SkipRuntimeStart {}; - - template - requires requires(TargetEngine* engine, BatchGroup& batch) { - static_cast(engine); - { engine->step(batch) } -> std::same_as; - { - engine->collect_step_outputs(batch) - } -> std::same_as>; - } - PDScheduler( - TargetEngine* engine, - const Options& options, - std::shared_ptr distributed_worker_manager, - std::shared_ptr model_residency_coordinator = - nullptr, - std::shared_ptr kv_transfer_coordinator = nullptr, - PDServiceOptions response_options = {}) - : PDScheduler(engine, - options, - SkipRuntimeStart{}, - std::move(distributed_worker_manager), - std::move(model_residency_coordinator), - std::move(kv_transfer_coordinator)) { - CHECK(distributed_worker_manager_ != nullptr) - << "Disaggregated PD requires a distributed worker manager."; - CHECK(kv_transfer_coordinator_ != nullptr) - << "Disaggregated PD requires a KV cache transfer coordinator."; - dispatch_thread_ = - std::make_unique(&PDScheduler::dispatch_requests, this); - server_name_.append(std::to_string(options_.server_idx())); - rpc_server_thread_ = std::make_unique( - [this, response_options = std::move(response_options)]() mutable { - start_rpc_server(std::move(response_options)); - }); - initialize_rpc_server(server_name_); - register_instance_info(server_name_); - if (!options_.disable_ttft_profiling() && - options_.instance_role().value() == InstanceRole::MIX) { - profile_ttft(); - profile_tpot(); - } - } + void start_runtime(PDServiceOptions response_options); ~PDScheduler() override; @@ -176,28 +130,23 @@ class PDScheduler : public ContinuousScheduler<> { const int32_t dp_size, const int32_t src_kv_split_size); - protected: - template - requires requires(TargetEngine* engine, BatchGroup& batch) { - static_cast(engine); - { engine->step(batch) } -> std::same_as; - { - engine->collect_step_outputs(batch) - } -> std::same_as>; - } PDScheduler( - TargetEngine* engine, + KVCacheManager* kv_cache_manager, + const ModelArgs* model_args, + const Tokenizer* tokenizer, + SchedulerCallbacks callbacks, const Options& options, - SkipRuntimeStart, - std::shared_ptr distributed_worker_manager = - nullptr, + std::shared_ptr distributed_worker_manager, std::shared_ptr model_residency_coordinator = nullptr, std::shared_ptr kv_transfer_coordinator = nullptr) - : ContinuousScheduler<>(engine, - options, - std::move(model_residency_coordinator), - std::move(distributed_worker_manager)), + : ContinuousScheduler(kv_cache_manager, + model_args, + tokenizer, + std::move(callbacks), + options, + std::move(model_residency_coordinator), + std::move(distributed_worker_manager)), kv_transfer_coordinator_(std::move(kv_transfer_coordinator)), server_name_("PDServer") { if (!options_.instance_role().has_value()) { @@ -205,6 +154,7 @@ class PDScheduler : public ContinuousScheduler<> { } } + protected: void release_failed_request(const std::shared_ptr& request) override; std::future enqueue_request_block_release( diff --git a/xllm/core/disaggregation/pd_service.cpp b/xllm/core/disaggregation/pd_service.cpp index 965c83e589..3ac58bad4d 100644 --- a/xllm/core/disaggregation/pd_service.cpp +++ b/xllm/core/disaggregation/pd_service.cpp @@ -22,12 +22,9 @@ limitations under the License. namespace xllm { -PDService::PDService(PDScheduler* scheduler, - Engine* engine, - PDServiceOptions response_options) +PDService::PDService(PDScheduler* scheduler, PDServiceOptions response_options) : pd_service_impl_( std::make_unique(scheduler, - engine, std::move(response_options))) {} void PDService::ReleaseReservation( diff --git a/xllm/core/disaggregation/pd_service.h b/xllm/core/disaggregation/pd_service.h index 747ec4d547..3a03a40afb 100644 --- a/xllm/core/disaggregation/pd_service.h +++ b/xllm/core/disaggregation/pd_service.h @@ -26,9 +26,7 @@ namespace xllm { class PDService : public proto::DisaggPDService { public: explicit PDService(PDScheduler* scheduler, - Engine* engine, PDServiceOptions response_options = {}); - PDService() = default; ~PDService() override = default; // for decode recv prefill request diff --git a/xllm/core/disaggregation/pd_service_impl.cpp b/xllm/core/disaggregation/pd_service_impl.cpp index 43190a254c..49f8852957 100644 --- a/xllm/core/disaggregation/pd_service_impl.cpp +++ b/xllm/core/disaggregation/pd_service_impl.cpp @@ -25,15 +25,14 @@ limitations under the License. #include "api_service/openai_json.h" #include "common/options.h" #include "common/types.h" -#include "core/common/types.h" #include "core/disaggregation/pd_kv_response.h" #include "core/disaggregation/pd_request_converter.h" #include "core/disaggregation/pd_response.h" #include "core/disaggregation/pd_scheduler.h" #include "core/distributed_runtime/distributed_vmm_coordinator.h" -#include "core/distributed_runtime/engine.h" #include "core/framework/config/kv_cache_config.h" #include "core/framework/constrained/json_object_grammar.h" +#include "core/framework/model/model_args.h" #include "core/framework/request/request_output.h" #include "core/kv_cache/manager/kv_cache_manager.h" #include "core/util/tensor_codec.h" @@ -57,13 +56,9 @@ PDServiceOptions make_pd_service_options(const Options& options, } PDServiceImpl::PDServiceImpl(PDScheduler* scheduler, - Engine* engine, PDServiceOptions response_options) - : scheduler_(scheduler), - engine_(engine), - response_options_(std::move(response_options)), - xservice_client_(XServiceClient::get_instance()), - kv_cache_manager_(engine->kv_cache_manager()) { + : scheduler_(scheduler), response_options_(std::move(response_options)) { + xservice_client_ = XServiceClient::get_instance(); if (!xservice_client_->initialize_done()) { LOG(FATAL) << "XServiceClient not init."; return; @@ -77,13 +72,14 @@ std::shared_ptr PDServiceImpl::get_json_object_grammar( std::shared_ptr& grammar = reasoning_enabled ? json_reasoning_grammar_ : json_object_grammar_; if (grammar == nullptr) { - grammar = JsonObjectGrammar::create_from_tokenizer( - *engine_->tokenizer(), - engine_->model_args().eos_token_id(), - engine_->model_args().stop_token_ids(), - engine_->model_args().vocab_size(), - reasoning_enabled, - error); + const ModelArgs* model_args = scheduler_->model_args(); + grammar = + JsonObjectGrammar::create_from_tokenizer(*scheduler_->tokenizer(), + model_args->eos_token_id(), + model_args->stop_token_ids(), + model_args->vocab_size(), + reasoning_enabled, + error); } return grammar; } @@ -202,20 +198,17 @@ void PDServiceImpl::release_reservation( : proto::ReleaseReservationResponse::NOT_WAITING); } -bool PDServiceImpl::append_virtual_kv_offsets( - int32_t dp_rank, - const std::string& request_id, - const std::vector& block_ids, - proto::DisaggResponse* response) { - if (kv_cache_manager_ == nullptr || - !kv_cache_manager_->uses_virtual_memory() || block_ids.empty()) { - return true; - } +namespace { +bool append_virtual_kv_offsets(int32_t dp_rank, + const std::string& model_id, + const std::string& request_id, + const std::vector& block_ids, + proto::DisaggResponse* response) { std::vector layer_offsets; const bool offsets_available = DistributedVmmCoordinator::get_instance().get_virtual_kv_offsets( - dp_rank, kv_cache_manager_->model_id(), block_ids, layer_offsets); + dp_rank, model_id, block_ids, layer_offsets); if (!offsets_available) { LOG(ERROR) << "Failed to get VirtualMemory offsets for request " << request_id; @@ -248,11 +241,17 @@ bool PDServiceImpl::append_virtual_kv_offsets( return true; } +} // namespace + void PDServiceImpl::decode_recv_new_requests( const proto::DisaggRequests* request, proto::DisaggResponses* response) { response->mutable_resps()->Reserve(response->resps_size() + request->reqs_size()); + const KVCacheManager* kv_cache_manager = scheduler_->kv_cache_manager(); + const bool has_linear_attention_layers = + ::xllm::has_linear_attention_layers(*scheduler_->model_args()); + const bool enable_vmm_kvcache = kv_cache_manager->uses_virtual_memory(); for (const auto& req : request->reqs()) { auto* resp = response->add_resps(); resp->set_req_id(req.req_id()); @@ -292,12 +291,12 @@ void PDServiceImpl::decode_recv_new_requests( std::vector virtual_memory_block_ids; append_pd_kv_transfer_groups( sequence->kv_state(), - has_linear_attention_layers(engine_->model_args()), + has_linear_attention_layers, resp, - kv_cache_manager_ != nullptr && kv_cache_manager_->uses_virtual_memory() - ? &virtual_memory_block_ids - : nullptr); - if (!append_virtual_kv_offsets(sequence->dp_rank(), + enable_vmm_kvcache ? &virtual_memory_block_ids : nullptr); + if (!virtual_memory_block_ids.empty() && + !append_virtual_kv_offsets(sequence->dp_rank(), + kv_cache_manager->model_id(), req.req_id(), virtual_memory_block_ids, resp)) { diff --git a/xllm/core/disaggregation/pd_service_impl.h b/xllm/core/disaggregation/pd_service_impl.h index ecd4d0369a..8d62a85ee2 100644 --- a/xllm/core/disaggregation/pd_service_impl.h +++ b/xllm/core/disaggregation/pd_service_impl.h @@ -28,8 +28,6 @@ limitations under the License. namespace xllm { -class KVCacheManager; -class Engine; class Request; class Sequence; class PDScheduler; @@ -47,31 +45,28 @@ struct PDServiceOptions { PDServiceOptions make_pd_service_options(const Options& options, const ModelArgs& model_args); -class PDServiceImpl { +class PDServiceImpl final { public: explicit PDServiceImpl(PDScheduler* scheduler, - Engine* engine, PDServiceOptions response_options = {}); - virtual ~PDServiceImpl() = default; + void decode_recv_new_requests(const proto::DisaggRequests* request, + proto::DisaggResponses* response); - virtual void decode_recv_new_requests(const proto::DisaggRequests* request, - proto::DisaggResponses* response); - - virtual void decode_recv_first_generation( + void decode_recv_first_generation( const proto::DisaggGenerationsRequests* request, proto::Status* response, const BinaryPayload& attachment = {}); - virtual void link_instance(const proto::InstanceClusterInfo* request, - proto::Status* response); + void link_instance(const proto::InstanceClusterInfo* request, + proto::Status* response); - virtual void unlink_instance(const proto::InstanceClusterInfo* request, - proto::Status* response); + void unlink_instance(const proto::InstanceClusterInfo* request, + proto::Status* response); void release_reservation(const proto::ReleaseReservationRequest* request, proto::ReleaseReservationResponse* response); - protected: + private: std::shared_ptr generate_request(const proto::DisaggRequest& req); std::shared_ptr get_json_object_grammar( @@ -79,22 +74,11 @@ class PDServiceImpl { std::string* error); PDScheduler* scheduler_; // not owned - Engine* engine_; // not owned const PDServiceOptions response_options_; XServiceClient* xservice_client_ = nullptr; std::mutex json_object_grammar_mutex_; std::shared_ptr json_object_grammar_; std::shared_ptr json_reasoning_grammar_; - - private: - bool append_virtual_kv_offsets(int32_t dp_rank, - const std::string& request_id, - const std::vector& block_ids, - proto::DisaggResponse* response); - - // Not owned. The initialized engine and its cache manager outlive this - // service. - const KVCacheManager* const kv_cache_manager_; }; } // namespace xllm diff --git a/xllm/core/distributed_runtime/CMakeLists.txt b/xllm/core/distributed_runtime/CMakeLists.txt index 06958f716f..9d8cc5859a 100644 --- a/xllm/core/distributed_runtime/CMakeLists.txt +++ b/xllm/core/distributed_runtime/CMakeLists.txt @@ -41,7 +41,6 @@ cc_library( dit_engine.h llm_engine.h vlm_engine.h - speculative_engine.h distributed_worker_manager.h remote_worker.h worker_server.h @@ -52,20 +51,18 @@ cc_library( kv_transfer_coordinator.h xservice_client.h model_residency_coordinator.h - kv_capacity_planner.h worker_step_dispatch.h SRCS + engine.cpp dit_engine.cpp llm_engine.cpp vlm_engine.cpp - speculative_engine.cpp distributed_worker_manager.cpp kv_transfer_coordinator.cpp remote_worker.cpp worker_server.cpp xservice_client.cpp model_residency_coordinator.cpp - kv_capacity_planner.cpp DEPS :common :worker_service diff --git a/xllm/core/distributed_runtime/dit_engine.cpp b/xllm/core/distributed_runtime/dit_engine.cpp index a1d1cf4846..0043792384 100644 --- a/xllm/core/distributed_runtime/dit_engine.cpp +++ b/xllm/core/distributed_runtime/dit_engine.cpp @@ -26,6 +26,7 @@ limitations under the License. #include "core/common/metrics.h" #include "core/framework/config/execution_config.h" #include "core/platform/device.h" +#include "core/runtime/worker_client.h" #include "framework/parallel_state/parallel_args.h" #include "framework/parallel_state/parallel_state.h" #include "runtime/worker.h" @@ -33,11 +34,7 @@ limitations under the License. #include "util/timer.h" namespace xllm { -DiTEngine::DiTEngine( - const runtime::Options& options, - std::shared_ptr distributed_worker_manager) - : options_(options), - distributed_worker_manager_(std::move(distributed_worker_manager)) { +DiTEngine::DiTEngine(const runtime::Options& options) : Engine(options) { auto master_node_addr = options.master_node_addr().value_or(""); CHECK(!master_node_addr.empty()) << " DIT need to set master node addr, Please set --master_node_addr."; @@ -53,20 +50,11 @@ DiTEngine::DiTEngine( } // setup all workers and create worker clients in nnode_rank=0 engine side. - setup_workers(options); - worker_clients_num_ = worker_clients_.size(); + setup_workers(); forward_input_factory_ = std::make_unique(); } -void DiTEngine::setup_workers(const runtime::Options& options) { - if (!distributed_worker_manager_) { - distributed_worker_manager_ = - std::make_shared(options); - } - worker_clients_ = distributed_worker_manager_->get_worker_clients(); -} - bool DiTEngine::init() { if (!init_model()) { LOG(ERROR) << "Failed to init model from: " << options_.model_path(); @@ -78,28 +66,8 @@ bool DiTEngine::init() { bool DiTEngine::init_model() { const std::string& model_path = options_.model_path(); - // init model for each worker in parallel - // multiple workers, call async init - std::vector> futures; - futures.reserve(worker_clients_num_); - for (auto& worker : worker_clients_) { - futures.push_back(worker->init_model_async( - model_path, - ::xllm::ExecutionConfig::get_instance().random_seed(), - MasterStatus::WAKEUP)); - } - - // wait for all futures to complete - auto results = folly::collectAll(futures).get(); - LOG(INFO) << "All workers completed model initialization."; - for (const auto& result : results) { - if (!result.value()) { - return false; - } - } - - LOG(INFO) << "All workers successfully initialized the model."; - return true; + return load_model_to_workers(model_path, + /*master_status=*/MasterStatus::WAKEUP); } // TODO : change to ForwardOutput? @@ -114,9 +82,10 @@ DiTForwardOutput DiTEngine::step(std::vector& batches) { COUNTER_ADD(prepare_input_latency_seconds, timer.elapsed_seconds()); std::vector>> futures; - futures.reserve(worker_clients_num_); + const size_t num_workers = worker_clients_num(); + futures.reserve(num_workers); - for (auto worker_rank = 0; worker_rank < worker_clients_num_; ++worker_rank) { + for (size_t worker_rank = 0; worker_rank < num_workers; ++worker_rank) { futures.emplace_back( worker_clients_[worker_rank]->step_remote_async(forward_input)); } diff --git a/xllm/core/distributed_runtime/dit_engine.h b/xllm/core/distributed_runtime/dit_engine.h index b41ab107bf..0855ebc226 100644 --- a/xllm/core/distributed_runtime/dit_engine.h +++ b/xllm/core/distributed_runtime/dit_engine.h @@ -21,61 +21,27 @@ limitations under the License. #include #include "common/macros.h" -#include "core/distributed_runtime/distributed_worker_manager.h" +#include "core/distributed_runtime/engine.h" #include "core/framework/batch/dit_forward_input_factory.h" -#include "engine.h" #include "framework/batch/dit_batch.h" namespace xllm { -class DiTEngine : public Engine { +class DiTEngine final : public Engine { public: - DiTEngine(const runtime::Options& options, - std::shared_ptr - distributed_worker_manager = nullptr); + explicit DiTEngine(const runtime::Options& options); ~DiTEngine() = default; DiTForwardOutput step(std::vector& batch); - const runtime::Options& options() const { return options_; } - bool init(); - // return the active activation memory - - std::shared_ptr get_distributed_worker_manager() - const { - return distributed_worker_manager_; - } - protected: - // worker client which is used for call worker - // The reason for adding a worker client is to unify the - // access code for both local and remote workers, thereby - // introducing an additional worker_client abstraction. - std::vector> worker_clients_; - - // For multi-node serving - // engine brpc server, all workers connect to engine_server_, - // engine_server_ will send a UniqueId for workers to - // create process group. And workers send worker brpc server - // address to engine, engine will create WorkerClient for each worker. - // Engine call workers to step via these WorkerClients. - std::shared_ptr distributed_worker_manager_ = - nullptr; - std::unique_ptr forward_input_factory_; private: - // setup workers internal - void setup_workers(const runtime::Options& options); - // init models bool init_model(); - // options - runtime::Options options_; - // num of worker_clients - int64_t worker_clients_num_; }; } // namespace xllm diff --git a/xllm/core/distributed_runtime/engine.cpp b/xllm/core/distributed_runtime/engine.cpp new file mode 100644 index 0000000000..93231d0ecb --- /dev/null +++ b/xllm/core/distributed_runtime/engine.cpp @@ -0,0 +1,451 @@ +/* Copyright 2026 The xLLM Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://github.com/xLLM-AI/xllm/blob/main/LICENSE + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "core/distributed_runtime/engine.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "core/common/metrics.h" +#include "core/common/options.h" +#include "core/distributed_runtime/distributed_vmm_coordinator.h" +#include "core/distributed_runtime/distributed_worker_manager.h" +#include "core/framework/allocator/virtual_memory/physical_page_pool.h" +#include "core/framework/allocator/vmm_arena_capacity.h" +#include "core/framework/config/execution_config.h" +#include "core/framework/config/kv_cache_config.h" +#include "core/framework/config/load_config.h" +#include "core/framework/config/model_config.h" +#include "core/framework/config/scheduler_config.h" +#include "core/framework/config/speculative_config.h" +#include "core/framework/model_loader/model_loader.h" +#include "core/kv_cache/layout/kv_cache_capacity.h" +#include "core/kv_cache/layout/kv_cache_estimation.h" +#include "core/kv_cache/layout/kv_cache_shape.h" +#include "core/kv_cache/layout/vmm_kv_layout.h" +#include "core/runtime/worker_client.h" +#include "core/util/env_var.h" +#include "core/util/pretty_print.h" +#include "core/util/tensor_options.h" +#include "models/model_registry.h" + +namespace xllm { + +namespace { + +std::vector poll_worker_memory( + const std::vector>& workers) { + std::vector>> futures; + futures.reserve(workers.size()); + for (auto& worker : workers) { + futures.emplace_back(worker->estimate_kv_cache_capacity_async()); + } + const auto results = folly::collectAll(futures).get(); + std::vector worker_memory; + worker_memory.reserve(results.size()); + for (size_t i = 0; i < results.size(); ++i) { + CHECK(results[i].hasValue()) + << "Failed to estimate KV cache capacity for worker: " << i; + const auto& [available_memory, total_memory] = results[i].value(); + worker_memory.emplace_back( + KVCacheMemorySnapshot{available_memory, total_memory}); + } + return worker_memory; +} + +KVCacheCapacity estimate_side_capacity(const ModelArgs& model_args, + const runtime::Options& options, + torch::ScalarType dtype, + int64_t world_size, + KVCacheEstimateContext& context, + bool is_multimodal, + int64_t reserved_memory_bytes) { + context.dtype = dtype; + context.world_size = world_size; + context.is_multimodal = is_multimodal; + context.reserved_memory_bytes = reserved_memory_bytes; + context.linear_state_cache_block_limit = + get_npu_linear_state_cache_block_limit(model_args.model_type()); + const KVCacheConfig& config = KVCacheConfig::get_instance(); + const auto& phy_pool = PhysicalPagePool::get_instance(); + if (config.enable_vmm_kvcache() && phy_pool.is_initialized()) { + context.virtual_memory_cache_size = + static_cast(phy_pool.num_total()) * + config.phy_page_granularity_size(); + } else if (config.enable_vmm_kvcache()) { + const int64_t encoder_bytes = + is_multimodal ? options.max_encoder_cache_size() * 1024 * 1024 : 0; + int64_t initial_bytes = std::numeric_limits::max(); + for (const KVCacheMemorySnapshot& memory : context.worker_memory) { + const VmmArenaCapacity arena = + calculate_vmm_arena_capacity(memory.available_memory, + memory.total_memory, + config.max_memory_utilization(), + config.vmm_elastic(), + config.max_cache_size(), + reserved_memory_bytes + encoder_bytes); + initial_bytes = std::min(initial_bytes, arena.initial_bytes); + } + // Elastic growth cannot fund startup state caches. + context.virtual_memory_cache_size = initial_bytes; + } + return KVCacheEstimator(model_args).estimate(options, context); +} + +} // namespace + +void Engine::reconcile_vocab_size(int64_t tokenizer_vocab_size) { + const int64_t model_vocab_size = args_.vocab_size(); + if (tokenizer_vocab_size == model_vocab_size) { + return; + } + if (model_vocab_size <= 0) { + LOG(WARNING) << "Model vocab size is not set, using tokenizer vocab size: " + << tokenizer_vocab_size; + args_.vocab_size(tokenizer_vocab_size); + } else if (tokenizer_vocab_size > model_vocab_size) { + LOG(WARNING) << "Unsafe vocab mismatch: tokenizer: " << tokenizer_vocab_size + << ", model: " << model_vocab_size; + } else { + LOG(INFO) << "Tokenizer/model vocab differ: tokenizer=" + << tokenizer_vocab_size << ", model=" << model_vocab_size; + } +} + +bool Engine::dispatch_model_load(const ModelLoader& model_loader, + MasterStatus master_status, + const ModelInitCallback& prepare_model) { + if (prepare_model && + !prepare_model(model_loader, + args_.n_layers(), + /*dp_size=*/static_cast(dp_size()), + static_cast(dp_local_tp_size_), + master_status)) { + return false; + } + if (master_status != MasterStatus::WAKEUP && + LoadConfig::get_instance().enable_vmm_weights() && + !KVCacheConfig::get_instance().enable_vmm_kvcache()) { + const size_t weight_pages = + DistributedVmmCoordinator::get_instance().get_weight_page_count( + options_.model_id()); + reserved_memory_bytes_ = + weight_pages * + KVCacheConfig::get_instance().phy_page_granularity_size(); + } + return load_model_to_workers(model_loader.model_weights_path(), + master_status); +} + +bool Engine::load_model_to_workers(const std::string& model_path, + MasterStatus master_status) { + std::vector> futures; + futures.reserve(worker_clients_num()); + for (auto& worker : worker_clients_) { + futures.push_back( + worker->init_model_async(model_path, + ExecutionConfig::get_instance().random_seed(), + master_status)); + } + const auto results = folly::collectAll(futures).get(); + for (const auto& result : results) { + if (!result.value()) { + return false; + } + } + return true; +} + +std::optional Engine::init_draft_model() { + const std::string& draft_model_path = options_.draft_model_path().value(); + auto model_loader = ModelLoader::create(draft_model_path, /*backend=*/"llm"); + ModelArgs draft_args = model_loader->model_args(); + ModelRegistry::configure_mtp_args( + draft_args, + options_.speculative_algorithm(), + /*is_draft_engine=*/true, + ModelConfig::is_python_model_impl( + ModelConfig::get_instance().model_impl())); + Options::validate(draft_args.model_type(), options_.model_impl()); + LOG(INFO) << "Initializing draft model from: " << draft_model_path; + + if (args_.max_position_embeddings() != draft_args.max_position_embeddings()) { + LOG(WARNING) << "draft and target models have different max context " + "lengths, draft max_position_embeddings: " + << draft_args.max_position_embeddings() + << ", target max_position_embeddings: " + << args_.max_position_embeddings() + << ", using the minimum between them"; + args_.max_position_embeddings() = std::min( + args_.max_position_embeddings(), draft_args.max_position_embeddings()); + } + + if (!load_model_to_workers(model_loader->model_weights_path(), + /*master_status=*/MasterStatus::WAKEUP)) { + return std::nullopt; + } + return draft_args; +} + +std::optional Engine::init_draft_and_estimate_capacity() { + const auto& config = KVCacheConfig::get_instance(); + const bool loads_draft = SpeculativeConfig::loads_draft_model(options_); + std::optional draft_args; + if (loads_draft) { + if (LoadConfig::get_instance().enable_vmm_weights()) { + LOG(ERROR) << "Virtual weight memory does not support an external " + "speculative draft engine."; + return std::nullopt; + } + if (config.enable_vmm_kvcache() && + (!SpeculativeConfig::is_mtp_algorithm( + options_.speculative_algorithm()) || + options_.enable_disagg_pd() || + options_.instance_role() != InstanceRole::DEFAULT)) { + LOG(ERROR) << "Virtual KV cache supports co-located MTP target and draft " + "engines only; PD is unsupported."; + return std::nullopt; + } + draft_args = init_draft_model(); + if (!draft_args) { + return std::nullopt; + } + } + + KVCacheEstimateContext context; + if (!config.enable_vmm_kvcache() || + !PhysicalPagePool::get_instance().is_initialized()) { + context.worker_memory = poll_worker_memory(worker_clients_); + } + KVCacheCapacity target = estimate_side_capacity(args_, + options_, + dtype_, + dp_local_tp_size_, + context, + is_multimodal(), + reserved_memory_bytes_); + std::optional shared_vmm_layout; + int64_t reserved_state_bytes = target.linear_cache_size_in_bytes(); + if (draft_args && (config.enable_vmm_kvcache() || + (target.c4_count() == 0 && target.c128_count() == 0))) { + runtime::Options draft_options = options_; + draft_options.enable_schedule_overlap(/*value=*/false) + .is_draft_engine(/*value=*/true); + const torch::ScalarType draft_dtype = + util::parse_dtype(draft_args->dtype(), options_.devices()[0]); + const int64_t draft_world_size = + options_.enable_mtp_draft_body_tp1() ? 1 : dp_local_tp_size_; + const KVCacheCapacity draft = + estimate_side_capacity(*draft_args, + draft_options, + draft_dtype, + draft_world_size, + context, + /*is_multimodal=*/false, + /*reserved_memory_bytes=*/0); + reserved_state_bytes += draft.linear_cache_size_in_bytes(); + if (config.enable_vmm_kvcache()) { + shared_vmm_layout.emplace(target, args_, dp_local_tp_size_, dtype_); + shared_vmm_layout->append( + VmmKVLayout(draft, *draft_args, draft_world_size, draft_dtype)); + } else if (target.shared_slot_bytes() > 0) { + target = plan_shared_static_kv_cache( + std::move(target), draft, args_, dp_local_tp_size_, dtype_) + .target; + } else { + target = combine_target_and_draft_kv_cache_capacity( + std::move(target), + draft, + args_, + *draft_args, + options_.is_draft_engine() ? 1 : options_.layerwise_split_size()); + } + } + if (config.enable_vmm_kvcache()) { + auto& coordinator = DistributedVmmCoordinator::get_instance(); + coordinator.prepare_kv_cache_pool( + options_, + dp_local_tp_size_, + static_cast(worker_clients_num()), + reserved_state_bytes, + is_multimodal()); + if (!shared_vmm_layout) { + shared_vmm_layout.emplace(target, args_, dp_local_tp_size_, dtype_); + } + const size_t total_pages = coordinator.get_num_total_phy_pages(); + const size_t page_size = config.phy_page_granularity_size(); + target + .n_blocks(static_cast( + shared_vmm_layout->block_capacity(total_pages, page_size))) + .cache_size_in_bytes(static_cast(total_pages) * page_size + + reserved_state_bytes); + } + GAUGE_SET(total_kv_cache_size_in_kilobytes, + target.cache_size_in_bytes() / 1024); + return KVCachePlan{std::move(target), std::move(shared_vmm_layout)}; +} + +void Engine::process_group_test() { +#if !defined(USE_NPU) + if (worker_clients_.size() <= 1) { + return; + } + std::vector> futures; + futures.reserve(worker_clients_num()); + for (auto& worker : worker_clients_) { + futures.emplace_back(worker->process_group_test_async()); + } + const auto timeout_seconds = util::get_process_group_test_timeout_seconds(); + folly::collectAll(futures) + .within(std::chrono::seconds(timeout_seconds)) + .get(); +#endif +} + +void Engine::log_capacity_and_validate_chunked_prefill( + const KVCacheCapacity& kv_cache_cap, + bool enable_state_cache) const { + LOG(INFO) << "kv cache capacity: " + << readable_size(kv_cache_cap.cache_size_in_bytes()) + << ", blocks: " << kv_cache_cap.n_blocks() + << ", slot_size: " << kv_cache_cap.slot_size() + << ", index_slot_size: " << kv_cache_cap.index_slot_size() + << ", indexer_layers: " << kv_cache_cap.num_indexer_layers() + << ", scale_slot_size: " << kv_cache_cap.scale_slot_size() + << ", linear_slot_size: " << kv_cache_cap.linear_slot_size() + << ", linear_blocks: " << kv_cache_cap.num_linear_state_blocks() + << ", state_slots: " + << (enable_state_cache ? kv_cache_cap.num_linear_state_blocks() : 0) + << ", gdn_state_bytes: " + << readable_size(kv_cache_cap.num_linear_attention_layers() * + kv_cache_cap.linear_slot_size()) + << ", kpool_state_bytes: " + << readable_size(kv_cache_cap.num_indexer_layers() * + kv_cache_cap.kpool_tail_slot_size()) + << ", max_linear_state_cache_slots: " + << options_.max_linear_state_cache_slots() + << ", reserved_state_bytes: " + << readable_size(kv_cache_cap.linear_cache_size_in_bytes()) + << ", n_layers: " << kv_cache_cap.n_layers() + << ", kv_cache_dtype: " << options_.kv_cache_dtype(); + + // DECODE disables the LINEAR prefix cache by role, and pd_launch.sh + // legitimately sets --enable_chunked_prefill=false there. + const bool is_decode = options_.instance_role() == InstanceRole::DECODE; + if (options_.enable_prefix_cache() && enable_state_cache && !is_decode) { + const int32_t block_size = static_cast(kv_cache_cap.block_size()); + CHECK(options_.enable_chunked_prefill()) + << "GDN/KPool state prefix cache requires block-aligned chunked " + "prefill to save matching linear states. Please set " + "--enable_chunked_prefill=true in your config."; + const int32_t chunk_stride = + SchedulerConfig::get_instance().max_tokens_per_chunk_for_prefill(); + CHECK(chunk_stride % block_size == 0) + << "state-cache prefix cache saves checkpoints at " + "chunk-end boundaries, so max_tokens_per_chunk_for_prefill (" + << chunk_stride << ") must be a multiple of block_size (" << block_size + << ")."; + } +} + +bool Engine::allocate_kv_cache_on_workers(const KVCacheShape& kv_cache_shape, + bool use_transfer_path) { + std::vector> futures; + futures.reserve(worker_clients_num()); + for (auto& worker : worker_clients_) { + futures.push_back( + use_transfer_path + ? worker->allocate_kv_cache_with_transfer_async(kv_cache_shape) + : worker->allocate_kv_cache_async(kv_cache_shape)); + } + const auto results = folly::collectAll(futures).get(); + for (const auto& result : results) { + if (!result.value()) { + return false; + } + } + kv_cache_manager_->reserve_virtual_memory_padding_blocks(); + return true; +} + +void Engine::setup_workers() { + runtime::Options worker_options = options_; + if (SpeculativeConfig::uses_speculative_pipeline(options_)) { + CHECK_GT(options_.num_speculative_tokens(), 0) + << "speculative tokens should not be zero"; + worker_options.enable_speculative_decode(/*value=*/true); + } + distributed_worker_manager_ = + std::make_shared(worker_options); + worker_clients_ = distributed_worker_manager_->get_worker_clients(); +} + +bool Engine::start_profile() { + std::lock_guard lock(profile_mutex_); + LOG(INFO) << "Starting profiler on " << worker_clients_num() << " worker(s)."; + if (!profile_workers(/*is_start=*/true)) { + // A partially successful broadcast must not leave other workers tracing. + if (!profile_workers(/*is_start=*/false)) { + LOG(ERROR) << "Failed to clean up profiling on some workers. " + "Retry /stop_profile."; + } + return false; + } + return true; +} + +bool Engine::stop_profile() { + std::lock_guard lock(profile_mutex_); + LOG(INFO) << "Stopping profiler on " << worker_clients_num() << " worker(s)."; + return profile_workers(/*is_start=*/false); +} + +bool Engine::profile_workers(bool is_start) { + if (worker_clients_.empty()) { + LOG(ERROR) << "No worker clients available for profiling."; + return false; + } + + std::vector> futures; + futures.reserve(worker_clients_num()); + for (auto& worker : worker_clients_) { + futures.emplace_back(is_start ? worker->start_profile_async() + : worker->stop_profile_async()); + } + + auto results = folly::collectAll(futures).get(); + bool success = true; + for (const auto& result : results) { + if (result.hasException()) { + LOG(ERROR) << "Profiling worker RPC failed: " + << result.exception().what(); + success = false; + continue; + } + if (!result.value()) { + LOG(ERROR) << "Profiling failed on a worker (start=" << is_start << ")."; + success = false; + } + } + + return success; +} + +} // namespace xllm diff --git a/xllm/core/distributed_runtime/engine.h b/xllm/core/distributed_runtime/engine.h index a2c0e8362f..3cfa3fe71e 100644 --- a/xllm/core/distributed_runtime/engine.h +++ b/xllm/core/distributed_runtime/engine.h @@ -15,11 +15,15 @@ limitations under the License. #pragma once -#include - +#include #include +#include +#include +#include #include "common/types.h" +#include "core/kv_cache/layout/kv_cache_capacity.h" +#include "core/kv_cache/layout/vmm_kv_layout.h" #include "core/kv_cache/manager/kv_cache_manager.h" #include "framework/model/model_args.h" #include "framework/tokenizer/tokenizer.h" @@ -28,53 +32,101 @@ limitations under the License. namespace xllm { +class DistributedWorkerManager; +class KVCacheShape; +class ModelLoader; +class WorkerClient; + +using ModelInitCallback = std::function< + bool(const ModelLoader&, int64_t, int32_t, int32_t, MasterStatus)>; + class Engine { public: - virtual ~Engine() = default; + explicit Engine(const runtime::Options& options) : options_(options) {} - virtual bool init() { return true; }; + std::shared_ptr get_distributed_worker_manager() + const { + return distributed_worker_manager_; + } - virtual bool init(MasterStatus master_status) { return true; }; + const Tokenizer* tokenizer() const { return tokenizer_.get(); } - // return the tokenizer - virtual const Tokenizer* tokenizer() const { return tokenizer_.get(); } + KVCacheManager* kv_cache_manager() const { return kv_cache_manager_.get(); } - // The initialized engine owns the manager throughout scheduler use. - virtual KVCacheManager* kv_cache_manager() const { - return kv_cache_manager_.get(); - } + const ModelArgs& model_args() const { return args_; } - // return the model args - virtual const ModelArgs& model_args() const { return args_; } + const TokenizerArgs& tokenizer_args() const { return tokenizer_args_; } - // return the tokenizer args - virtual const TokenizerArgs& tokenizer_args() const { - return tokenizer_args_; - } + bool start_profile(); - // Start/stop online timeline profiling on all workers. CUDA only for now. - virtual bool start_profile() { - LOG(ERROR) << "start_profile is not implemented for this engine!"; - return false; - }; + bool stop_profile(); - virtual bool stop_profile() { - LOG(ERROR) << "stop_profile is not implemented for this engine!"; - return false; + protected: + ~Engine() = default; + + void reconcile_vocab_size(int64_t tokenizer_vocab_size); + + struct KVCachePlan { + KVCacheCapacity capacity_; + std::optional shared_vmm_layout_; }; - protected: - // model args + bool dispatch_model_load(const ModelLoader& model_loader, + MasterStatus master_status, + const ModelInitCallback& prepare_model); + + std::optional init_draft_model(); + + bool is_multimodal() const { + return EngineType(options_.backend()) == EngineType::VLM; + } + + void log_capacity_and_validate_chunked_prefill( + const KVCacheCapacity& kv_cache_cap, + bool enable_state_cache) const; + + bool allocate_kv_cache_on_workers(const KVCacheShape& kv_cache_shape, + bool use_transfer_path = false); + + std::optional init_draft_and_estimate_capacity(); + + void setup_workers(); + + bool load_model_to_workers(const std::string& model_path, + MasterStatus master_status); + + void process_group_test(); + ModelArgs args_; - // Tokenizer args + runtime::Options options_; + + std::vector> worker_clients_; + + uint32_t dp_size() const { return options_.dp_size(); } + + uint32_t dp_local_tp_size_ = 1; + + size_t worker_clients_num() const { return worker_clients_.size(); } + TokenizerArgs tokenizer_args_; - // Request-cache coordination selected by KVCacheManagerFactory. + // Device allocations absent from the worker memory snapshot. + int64_t reserved_memory_bytes_ = 0; + std::unique_ptr kv_cache_manager_; // tokenizer std::unique_ptr tokenizer_; + + torch::ScalarType dtype_; + + std::shared_ptr distributed_worker_manager_ = + nullptr; + + private: + bool profile_workers(bool is_start); + std::mutex profile_mutex_; }; } // namespace xllm diff --git a/xllm/core/distributed_runtime/kv_capacity_planner.cpp b/xllm/core/distributed_runtime/kv_capacity_planner.cpp deleted file mode 100644 index 32833fd3ca..0000000000 --- a/xllm/core/distributed_runtime/kv_capacity_planner.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* Copyright 2026 The xLLM Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - https://github.com/xLLM-AI/xllm/blob/main/LICENSE - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "core/distributed_runtime/kv_capacity_planner.h" - -#include - -#include -#include -#include - -#include "core/common/metrics.h" -#include "core/distributed_runtime/distributed_vmm_coordinator.h" -#include "core/framework/allocator/virtual_memory/physical_page_pool.h" -#include "core/framework/allocator/vmm_arena_capacity.h" -#include "core/framework/config/kv_cache_config.h" -#include "core/kv_cache/layout/vmm_kv_layout.h" -#include "core/runtime/options.h" -#include "core/runtime/worker_client.h" -#include "models/model_registry.h" - -namespace xllm { - -KVCapacityPlanner::KVCapacityPlanner( - const ModelArgs& model_args, - const runtime::Options& options, - torch::ScalarType dtype, - int64_t world_size, - const std::vector>& worker_clients, - bool is_multimodal, - int64_t reserved_memory_bytes) - : model_args_(model_args), - options_(options), - worker_clients_(worker_clients), - dtype_(dtype), - world_size_(world_size), - is_multimodal_(is_multimodal), - reserved_memory_bytes_(reserved_memory_bytes) {} - -KVCacheEstimateContext KVCapacityPlanner::observe_memory() const { - KVCacheEstimateContext context; - context.dtype = dtype_; - context.world_size = world_size_; - context.is_multimodal = is_multimodal_; - context.reserved_memory_bytes = reserved_memory_bytes_; - context.linear_state_cache_block_limit = - get_npu_linear_state_cache_block_limit(model_args_.model_type()); - const KVCacheConfig& config = KVCacheConfig::get_instance(); - const auto& phy_pool = PhysicalPagePool::get_instance(); - if (config.enable_vmm_kvcache() && phy_pool.is_initialized()) { - context.virtual_memory_cache_size = - static_cast(phy_pool.num_total()) * - config.phy_page_granularity_size(); - } else { - CHECK(!worker_clients_.empty()) << "KV cache estimation requires workers"; - std::vector>> futures; - futures.reserve(worker_clients_.size()); - for (const auto& worker : worker_clients_) { - futures.emplace_back(worker->estimate_kv_cache_capacity_async()); - } - auto results = folly::collectAll(futures).get(); - context.worker_memory.reserve(results.size()); - for (size_t i = 0; i < results.size(); ++i) { - CHECK(results[i].hasValue()) - << "Failed to estimate KV cache capacity for worker: " << i; - const auto& [available_memory, total_memory] = results[i].value(); - context.worker_memory.emplace_back( - KVCacheMemorySnapshot{available_memory, total_memory}); - } - if (config.enable_vmm_kvcache()) { - const int64_t encoder_bytes = - is_multimodal_ ? options_.max_encoder_cache_size() * 1024 * 1024 : 0; - int64_t initial_bytes = std::numeric_limits::max(); - for (const KVCacheMemorySnapshot& memory : context.worker_memory) { - const VmmArenaCapacity arena = calculate_vmm_arena_capacity( - memory.available_memory, - memory.total_memory, - config.max_memory_utilization(), - config.vmm_elastic(), - config.max_cache_size(), - reserved_memory_bytes_ + encoder_bytes); - initial_bytes = std::min(initial_bytes, arena.initial_bytes); - } - // Persistent states must fit startup memory, rather than the larger - // virtual arena that an elastic pool can grow into later. - context.virtual_memory_cache_size = initial_bytes; - } - } - return context; -} - -void KVCapacityPlanner::prepare_virtual_memory( - KVCacheCapacity& capacity) const { - auto& coordinator = DistributedVmmCoordinator::get_instance(); - coordinator.prepare_kv_cache_pool(options_, - world_size_, - worker_clients_.size(), - capacity.linear_cache_size_in_bytes(), - is_multimodal_); - const VmmKVLayout layout(capacity, model_args_, world_size_, dtype_); - const size_t total_pages = coordinator.get_num_total_phy_pages(); - const size_t page_size = - KVCacheConfig::get_instance().phy_page_granularity_size(); - capacity - .n_blocks( - static_cast(layout.block_capacity(total_pages, page_size))) - .cache_size_in_bytes(static_cast(total_pages) * page_size + - capacity.linear_cache_size_in_bytes()); -} - -KVCacheCapacity KVCapacityPlanner::plan(bool initialize_virtual_memory) const { - const KVCacheEstimateContext context = observe_memory(); - KVCacheCapacity capacity = - KVCacheEstimator(model_args_).estimate(options_, context); - if (KVCacheConfig::get_instance().enable_vmm_kvcache() && - initialize_virtual_memory) { - prepare_virtual_memory(capacity); - } - GAUGE_SET(total_kv_cache_size_in_kilobytes, - capacity.cache_size_in_bytes() / 1024); - return capacity; -} - -} // namespace xllm diff --git a/xllm/core/distributed_runtime/kv_capacity_planner.h b/xllm/core/distributed_runtime/kv_capacity_planner.h deleted file mode 100644 index 0c686ea40e..0000000000 --- a/xllm/core/distributed_runtime/kv_capacity_planner.h +++ /dev/null @@ -1,65 +0,0 @@ -/* Copyright 2026 The xLLM Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - https://github.com/xLLM-AI/xllm/blob/main/LICENSE - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#pragma once - -#include - -#include -#include -#include - -#include "core/kv_cache/layout/kv_cache_estimation.h" - -namespace xllm { - -class ModelArgs; -class WorkerClient; -namespace runtime { -struct Options; -} - -// Plans one engine's cache against its workers' memory. Model capacity rules -// stay in KVCacheEstimator; this runtime boundary supplies memory observations -// and prepares the shared VMM resources before manager construction. -class KVCapacityPlanner final { - public: - KVCapacityPlanner( - const ModelArgs& model_args, - const runtime::Options& options, - torch::ScalarType dtype, - int64_t world_size, - const std::vector>& worker_clients, - bool is_multimodal = false, - int64_t reserved_memory_bytes = 0); - - // A speculative pair defers VMM preparation until both state budgets and - // tensor layouts are known. - KVCacheCapacity plan(bool initialize_virtual_memory = true) const; - - private: - KVCacheEstimateContext observe_memory() const; - void prepare_virtual_memory(KVCacheCapacity& capacity) const; - - const ModelArgs& model_args_; - const runtime::Options& options_; - const std::vector>& worker_clients_; - torch::ScalarType dtype_; - int64_t world_size_; - bool is_multimodal_; - int64_t reserved_memory_bytes_; -}; - -} // namespace xllm diff --git a/xllm/core/distributed_runtime/llm_engine.cpp b/xllm/core/distributed_runtime/llm_engine.cpp index b741c7fdab..277519a773 100644 --- a/xllm/core/distributed_runtime/llm_engine.cpp +++ b/xllm/core/distributed_runtime/llm_engine.cpp @@ -35,11 +35,9 @@ limitations under the License. #include "core/common/prefill_policy.h" #include "core/common/types.h" #include "core/distributed_runtime/distributed_vmm_coordinator.h" -#include "core/distributed_runtime/kv_capacity_planner.h" #include "core/distributed_runtime/worker_step_dispatch.h" #include "core/framework/config/execution_config.h" #include "core/framework/config/kv_cache_config.h" -#include "core/framework/config/load_config.h" #include "core/framework/config/model_config.h" #include "core/framework/config/service_config.h" #include "core/framework/config/speculative_config.h" @@ -52,6 +50,7 @@ limitations under the License. #include "core/kv_cache/manager/kv_cache_manager_factory.h" #include "core/kv_cache/storage/host_cache_layout.h" #include "core/platform/platform.h" +#include "core/runtime/worker_client.h" #include "core/util/tensor_helper.h" #include "core/util/tensor_options.h" #include "framework/model/model_args.h" @@ -60,16 +59,11 @@ limitations under the License. #include "runtime/worker.h" #include "server/xllm_server_registry.h" #include "util/env_var.h" -#include "util/pretty_print.h" #include "util/utils.h" namespace xllm { -LLMEngine::LLMEngine( - const runtime::Options& options, - std::shared_ptr distributed_worker_manager) - : options_(options), - distributed_worker_manager_(std::move(distributed_worker_manager)) { +LLMEngine::LLMEngine(const runtime::Options& options) : Engine(options) { auto master_node_addr = options.master_node_addr().value_or(""); CHECK(!master_node_addr.empty()) << " LLM need to set master node addr, Please set --master_node_addr."; @@ -84,14 +78,13 @@ LLMEngine::LLMEngine( } // setup all workers and create worker clients in nnode_rank=0 engine side. - setup_workers(options); + setup_workers(); - dp_size_ = options_.dp_size(); const uint32_t cp_size = options_.cp_size(); forward_input_factory_ = std::make_unique>( ForwardInputFactoryOptions{ - .dp_size = dp_size_, + .dp_size = dp_size(), .cp_size = cp_size, .input_options = {.kv_split_size = options_.kv_split_size(), .build_execution_batch = @@ -105,13 +98,12 @@ LLMEngine::LLMEngine( static_cast(options_.max_tokens_per_batch()), .enable_graph = options_.enable_graph(), .enable_dp_global_json_object_active = - dp_size_ > 1 && !options_.is_draft_engine() && + dp_size() > 1 && !options_.is_draft_engine() && options_.num_speculative_tokens() > 0, .enable_shared_kv_cache_deltas = KVCacheConfig::get_instance().enable_shared_kv_cache(), }); - worker_clients_num_ = worker_clients_.size(); - dp_local_size_ = get_workers_per_dp_rank(worker_clients_num_, dp_size_); + dp_local_size_ = get_workers_per_dp_rank(worker_clients_num(), dp_size()); // MLU and NPU model-side CP both use orthogonal CP x attention-TP, so the // DP-local TP width is divided by CP. dp_local_tp_size_ = dp_local_size_ / cp_size; @@ -121,34 +113,6 @@ LLMEngine::LLMEngine( LLMEngine::~LLMEngine() = default; -void LLMEngine::process_group_test() { -#if !defined(USE_NPU) - // In multi-node serving mode, only driver engine - // create worker_clients_. - if (worker_clients_num_ > 1) { - // test process group - std::vector> futures; - futures.reserve(worker_clients_num_); - for (auto& worker : worker_clients_) { - futures.emplace_back(worker->process_group_test_async()); - } - // Wait for all futures to complete with a configurable timeout. - // The timeout can be adjusted via the - // XLLM_PROCESS_GROUP_ASYNC_TIMEOUT_SECONDS environment variable (default: 4 - // seconds). This is particularly important in multi-node multi-device - // scenarios where network latency may require a longer timeout period. - const int timeout_seconds = util::get_process_group_test_timeout_seconds(); - folly::collectAll(futures) - .within(std::chrono::seconds(timeout_seconds)) - .get(); - } -#endif -} - -bool LLMEngine::init(MasterStatus master_status) { - return init(master_status, /*prepare_model=*/{}); -} - bool LLMEngine::init( MasterStatus master_status, const ModelInitCallback& prepare_model, @@ -160,14 +124,20 @@ bool LLMEngine::init( eplb_controller_ = EplbController::create(args_, - static_cast(worker_clients_num_), + static_cast(worker_clients_num()), options_.ep_size(), options_.eplb_controller_config()); forward_input_factory_->set_eplb_controller(eplb_controller_.get()); - auto kv_cache_cap = estimate_kv_cache_capacity(); + const auto plan = init_draft_and_estimate_capacity(); + if (!plan.has_value()) { + return false; + } - if (!allocate_kv_cache(kv_cache_cap, std::move(transfer_coordinator))) { + if (!allocate_kv_cache( + plan->capacity_, + std::move(transfer_coordinator), + plan->shared_vmm_layout_ ? &*plan->shared_vmm_layout_ : nullptr)) { LOG(ERROR) << "Failed to initialize kv cache"; return false; } else { @@ -194,8 +164,17 @@ bool LLMEngine::init_model(MasterStatus master_status, Options::validate(args_.model_type(), options_.model_impl()); } - // A draft engine is fed token ids and detokenized by the target, so it - // shares the target vocabulary and loads no tokenizer of its own. +#if defined(USE_NPU) + if (!options_.is_draft_engine() && options_.num_speculative_tokens() > 0 && + SpeculativeConfig::is_eagle3_algorithm( + options_.speculative_algorithm()) && + args_.layers_to_capture().empty()) { + args_.layers_to_capture( + read_eagle3_capture_layer_ids(options_.draft_model_path().value(), + static_cast(args_.n_layers()))); + } +#endif + if (!options_.is_draft_engine()) { tokenizer_ = model_loader->tokenizer(); CHECK(tokenizer_ != nullptr); @@ -208,23 +187,7 @@ bool LLMEngine::init_model(MasterStatus master_status, << ", kv_cache_dtype: " << options_.kv_cache_dtype(); if (tokenizer_ != nullptr) { - const int64_t tokenizer_vocab_size = tokenizer_->vocab_size(); - int64_t model_vocab_size = args_.vocab_size(); - if (tokenizer_vocab_size != model_vocab_size) { - // use tokenizer vocab size if model vocab size is not set - if (model_vocab_size <= 0) { - LOG(WARNING) << "Model vocab size is not set, using tokenizer vocab " - "size: " - << tokenizer_vocab_size; - args_.vocab_size(tokenizer_vocab_size); - } else if (tokenizer_vocab_size > model_vocab_size) { - LOG(WARNING) << "Unsafe vocab mismatch: tokenizer: " - << tokenizer_vocab_size << ", model: " << model_vocab_size; - } else { - LOG(INFO) << "Tokenizer/model vocab differ: tokenizer=" - << tokenizer_vocab_size << ", model=" << model_vocab_size; - } - } + reconcile_vocab_size(tokenizer_->vocab_size()); } if (!options_.is_draft_engine() && options_.num_speculative_tokens() > 0 && @@ -241,58 +204,7 @@ bool LLMEngine::init_model(MasterStatus master_status, LOG(INFO) << "Initializing model with random seed: " << ::xllm::ExecutionConfig::get_instance().random_seed(); - if (prepare_model && !prepare_model(*model_loader, - args_.n_layers(), - static_cast(dp_size_), - static_cast(dp_local_tp_size_), - master_status)) { - return false; - } - - if (LoadConfig::get_instance().enable_vmm_weights() && - !KVCacheConfig::get_instance().enable_vmm_kvcache() && - master_status != MasterStatus::WAKEUP) { - // Sleeping weights have no device allocation yet. Keep ordinary KV - // tensors from consuming the page budget needed by the first wakeup. - const size_t weight_pages = - DistributedVmmCoordinator::get_instance().get_weight_page_count( - options_.model_id()); - initial_weight_reservation_bytes_ = - weight_pages * - KVCacheConfig::get_instance().phy_page_granularity_size(); - } - - // init model for each worker in parallel - // multiple workers, call async init - std::vector> futures; - futures.reserve(worker_clients_num_); - for (auto& worker : worker_clients_) { - futures.push_back(worker->init_model_async( - model_path, - ::xllm::ExecutionConfig::get_instance().random_seed(), - master_status)); - } - // wait for all futures to complete - auto results = folly::collectAll(futures).get(); - for (const auto& result : results) { - if (!result.value()) { - return false; - } - } - - return true; -} - -KVCacheCapacity LLMEngine::estimate_kv_cache_capacity( - bool initialize_virtual_memory) { - return KVCapacityPlanner(args_, - options_, - dtype_, - dp_local_tp_size_, - worker_clients_, - /*is_multimodal=*/false, - initial_weight_reservation_bytes_) - .plan(initialize_virtual_memory); + return dispatch_model_load(*model_loader, master_status, prepare_model); } bool LLMEngine::allocate_kv_cache( @@ -304,29 +216,7 @@ bool LLMEngine::allocate_kv_cache( const bool enable_state_cache = has_linear_attention_layers(args_) || kv_cache_cap.kpool_tail_slot_size() > 0; - LOG(INFO) << "kv cache capacity: " - << readable_size(kv_cache_cap.cache_size_in_bytes()) - << ", blocks: " << kv_cache_cap.n_blocks() - << ", slot_size: " << kv_cache_cap.slot_size() - << ", index_slot_size: " << kv_cache_cap.index_slot_size() - << ", indexer_layers: " << kv_cache_cap.num_indexer_layers() - << ", scale_slot_size: " << kv_cache_cap.scale_slot_size() - << ", linear_slot_size: " << kv_cache_cap.linear_slot_size() - << ", linear_blocks: " << kv_cache_cap.num_linear_state_blocks() - << ", state_slots: " - << (enable_state_cache ? kv_cache_cap.num_linear_state_blocks() : 0) - << ", gdn_state_bytes: " - << readable_size(kv_cache_cap.num_linear_attention_layers() * - kv_cache_cap.linear_slot_size()) - << ", kpool_state_bytes: " - << readable_size(kv_cache_cap.num_indexer_layers() * - kv_cache_cap.kpool_tail_slot_size()) - << ", max_linear_state_cache_slots: " - << options_.max_linear_state_cache_slots() - << ", reserved_state_bytes: " - << readable_size(kv_cache_cap.linear_cache_size_in_bytes()) - << ", n_layers: " << kv_cache_cap.n_layers() - << ", kv_cache_dtype: " << options_.kv_cache_dtype(); + log_capacity_and_validate_chunked_prefill(kv_cache_cap, enable_state_cache); CHECK_GT(kv_cache_cap.n_blocks(), 0) << "no memory for kv cache"; const int32_t block_size = static_cast(kv_cache_cap.block_size()); @@ -417,37 +307,19 @@ bool LLMEngine::allocate_kv_cache( std::move(options), prefill_policy, std::move(transfer_coordinator), - dp_size_, + dp_size(), std::move(host_cache_validation_options), shared_vmm_layout); factory_result.shape.print_shapes(); KVCacheShape kv_cache_shape = std::move(factory_result.shape); kv_cache_manager_ = std::move(factory_result.manager); - // init kv cache for each worker in parallel - std::vector> futures; - futures.reserve(worker_clients_num_); - if (instance_role == InstanceRole::DEFAULT) { - for (auto& worker : worker_clients_) { - futures.push_back(worker->allocate_kv_cache_async(kv_cache_shape)); - } - } else { - for (auto& worker : worker_clients_) { - futures.push_back( - worker->allocate_kv_cache_with_transfer_async(kv_cache_shape)); - } - } - // wait for all futures to complete - auto results = folly::collectAll(futures).get(); - for (const auto& result : results) { - if (!result.value()) { - return false; - } + if (!allocate_kv_cache_on_workers( + kv_cache_shape, + /*use_transfer_path=*/instance_role != InstanceRole::DEFAULT)) { + return false; } forward_input_factory_->reset_shared_kv_mapping_tracker(); - // VirtualMemory mode: reserve padding blocks and start prealloc thread. - kv_cache_manager_->reserve_virtual_memory_padding_blocks(); - return true; } @@ -457,9 +329,6 @@ ForwardOutput LLMEngine::step(BatchGroup& batch) { return {}; } Timer timer; - DCHECK(dp_size_ == batch.size()) - << "Split DP batch failed with dp_size as " << dp_size_ - << " and actual batch size as " << batch.size() << "."; std::vector forward_inputs; const bool is_graph_warmup = @@ -467,9 +336,9 @@ ForwardOutput LLMEngine::step(BatchGroup& batch) { if (eplb_controller_ != nullptr) { eplb_controller_->on_step_dispatched(forward_inputs, is_graph_warmup); } - DCHECK(dp_size_ == forward_inputs.size()) + DCHECK(dp_size() == forward_inputs.size()) << "The processed forward inputs size " << forward_inputs.size() - << " is not equal to dp size " << dp_size_ << "."; + << " is not equal to dp size " << dp_size() << "."; auto results = dispatch_worker_step(worker_clients_, forward_inputs, dp_local_size_); @@ -477,7 +346,7 @@ ForwardOutput LLMEngine::step(BatchGroup& batch) { // Every worker must have produced a value before EPLB consumes all results // and before promotions are committed to the shared prefix cache below; a // failed worker must not reach those non-reversible steps. - for (uint32_t worker_rank = 0; worker_rank < worker_clients_num_; + for (uint32_t worker_rank = 0; worker_rank < worker_clients_num(); ++worker_rank) { CHECK(results[worker_rank].value().has_value()) << "Failed to execute model, result has no value"; @@ -491,8 +360,8 @@ ForwardOutput LLMEngine::step(BatchGroup& batch) { } std::vector outputs; - outputs.reserve(dp_size_); - for (uint32_t worker_rank = 0; worker_rank < worker_clients_num_; + outputs.reserve(dp_size()); + for (uint32_t worker_rank = 0; worker_rank < worker_clients_num(); worker_rank += dp_local_size_) { auto& result = results[worker_rank].value(); outputs.emplace_back(std::move(result.value())); @@ -508,10 +377,10 @@ ForwardOutput LLMEngine::step(BatchGroup& batch) { std::vector LLMEngine::collect_step_outputs( const BatchGroup& batch) { - CHECK_EQ(batch.size(), dp_size_); + CHECK_EQ(batch.size(), dp_size()); const bool is_graph_warmup = batch.contains_graph_warmup(); std::vector raw_forward_outputs; - raw_forward_outputs.reserve(dp_size_); + raw_forward_outputs.reserve(dp_size()); // NOTE: We only need to get the output from the driver worker, // cause the output on other workers is the same as that on driver. @@ -539,7 +408,7 @@ std::vector LLMEngine::collect_step_outputs( eplb_controller_->on_step_completed(last_step_results, is_graph_warmup); } - for (auto worker_rank = 0; worker_rank < worker_clients_num_; + for (size_t worker_rank = 0; worker_rank < worker_clients_num(); worker_rank += dp_local_size_) { auto& result = last_step_results[worker_rank / stride].value(); raw_forward_outputs.emplace_back(std::move(result.value())); @@ -548,63 +417,4 @@ std::vector LLMEngine::collect_step_outputs( return raw_forward_outputs; } -void LLMEngine::setup_workers(const runtime::Options& options) { - if (!distributed_worker_manager_) { - distributed_worker_manager_ = - std::make_shared(options); - } - worker_clients_ = distributed_worker_manager_->get_worker_clients(); -} - -bool LLMEngine::start_profile() { - std::lock_guard lock(profile_mutex_); - LOG(INFO) << "Starting profiler on " << worker_clients_num_ << " worker(s)."; - if (!profile_workers(/*is_start=*/true)) { - // A partially successful broadcast must not leave other workers tracing. - if (!profile_workers(/*is_start=*/false)) { - LOG(ERROR) << "Failed to clean up profiling on some workers. " - "Retry /stop_profile."; - } - return false; - } - return true; -} - -bool LLMEngine::stop_profile() { - std::lock_guard lock(profile_mutex_); - LOG(INFO) << "Stopping profiler on " << worker_clients_num_ << " worker(s)."; - return profile_workers(/*is_start=*/false); -} - -bool LLMEngine::profile_workers(bool is_start) { - if (worker_clients_.empty()) { - LOG(ERROR) << "No worker clients available for profiling."; - return false; - } - - std::vector> futures; - futures.reserve(worker_clients_num_); - for (auto& worker : worker_clients_) { - futures.emplace_back(is_start ? worker->start_profile_async() - : worker->stop_profile_async()); - } - - auto results = folly::collectAll(futures).get(); - bool success = true; - for (const auto& result : results) { - if (result.hasException()) { - LOG(ERROR) << "Profiling worker RPC failed: " - << result.exception().what(); - success = false; - continue; - } - if (!result.value()) { - LOG(ERROR) << "Profiling failed on a worker (start=" << is_start << ")."; - success = false; - } - } - - return success; -} - } // namespace xllm diff --git a/xllm/core/distributed_runtime/llm_engine.h b/xllm/core/distributed_runtime/llm_engine.h index d6665218c7..23f1082806 100644 --- a/xllm/core/distributed_runtime/llm_engine.h +++ b/xllm/core/distributed_runtime/llm_engine.h @@ -16,124 +16,46 @@ limitations under the License. #pragma once -#include -#include -#include - #include -#include #include -#include -#include #include -#include "common/macros.h" -#include "common/types.h" -#include "core/distributed_runtime/distributed_worker_manager.h" -#include "core/kv_cache/layout/kv_cache_capacity.h" -#include "engine.h" +#include "core/distributed_runtime/engine.h" +#include "core/runtime/forward_params.h" #include "framework/batch/batch_group.h" #include "framework/batch/forward_input_factory.h" -#include "framework/tokenizer/tokenizer.h" -#include "framework/tokenizer/tokenizer_args.h" -#include "runtime/worker.h" -#include "runtime/worker_client.h" namespace xllm { class EplbController; class KVTransferCoordinatorBase; -class ModelLoader; -class VmmKVLayout; -class LLMEngine : public Engine { +class LLMEngine final : public Engine { public: - // Optional hook that runs synchronously before workers load weights. The - // caller supplies any required resource preparation; the engine does not - // retain the callback or own the resources prepared by it. - using ModelInitCallback = std::function< - bool(const ModelLoader&, int64_t, int32_t, int32_t, MasterStatus)>; - // create an engine with the given devices - LLMEngine(const runtime::Options& options, - std::shared_ptr - distributed_worker_manager = nullptr); + explicit LLMEngine(const runtime::Options& options); - ~LLMEngine() override; + ~LLMEngine(); ForwardOutput step(BatchGroup& batch); - const runtime::Options& options() const { return options_; } - - // The caller must prepare any required external model resources before - // initializing without a preparation callback. - bool init(MasterStatus master_status) override; - bool init(MasterStatus master_status, const ModelInitCallback& prepare_model, - std::shared_ptr transfer_coordinator = - nullptr); + std::shared_ptr transfer_coordinator); std::vector collect_step_outputs(const BatchGroup& batch); - std::shared_ptr get_distributed_worker_manager() - const { - return distributed_worker_manager_; - } - - bool start_profile() override; - - bool stop_profile() override; - private: - bool profile_workers(bool is_start); - std::mutex profile_mutex_; - int64_t initial_weight_reservation_bytes_ = 0; - - template - friend class SpeculativeEngineBase; - // setup workers internal - void setup_workers(const runtime::Options& options); bool init_model(MasterStatus master_status, const ModelInitCallback& prepare_model); - KVCacheCapacity estimate_kv_cache_capacity( - bool initialize_virtual_memory = true); bool allocate_kv_cache( const KVCacheCapacity& kv_cache_cap, std::shared_ptr transfer_coordinator, - const VmmKVLayout* shared_vmm_layout = nullptr); - void process_group_test(); - - protected: - // options - runtime::Options options_; - - // dtype - torch::ScalarType dtype_; - - // worker client which is used for call worker - // The reason for adding a worker client is to unify the - // access code for both local and remote workers, thereby - // introducing an additional worker_client abstraction. - std::vector> worker_clients_; - - // common frequently used args - uint32_t dp_size_ = 1; - uint32_t worker_clients_num_; - // Effective TP width (MLU=dp_local; NPU=dp_local/cp). - uint32_t dp_local_tp_size_; + const VmmKVLayout* shared_vmm_layout); + uint32_t dp_local_size_; std::unique_ptr> forward_input_factory_; - // For multi-node serving - // engine brpc server, all workers connect to engine_server_, - // engine_server_ will send a UniqueId for workers to - // create process group. And workers send worker brpc server - // address to engine, engine will create WorkerClient for each worker. - // Engine call workers to step via these WorkerClients. - std::shared_ptr distributed_worker_manager_ = - nullptr; - std::unique_ptr eplb_controller_; }; diff --git a/xllm/core/distributed_runtime/llm_master.cpp b/xllm/core/distributed_runtime/llm_master.cpp index 55a2efdbeb..308d27bb42 100644 --- a/xllm/core/distributed_runtime/llm_master.cpp +++ b/xllm/core/distributed_runtime/llm_master.cpp @@ -30,7 +30,7 @@ limitations under the License. #include "api_service/call.h" #include "common/metrics.h" #include "core/disaggregation/pd_service_impl.h" -#include "core/distributed_runtime/engine_dispatch.h" +#include "core/distributed_runtime/distributed_worker_manager.h" #include "core/distributed_runtime/kv_transfer_coordinator.h" #include "core/distributed_runtime/model_residency_coordinator.h" #include "core/distributed_runtime/runtime_options_creator.h" @@ -38,7 +38,6 @@ limitations under the License. #include "core/framework/config/kv_cache_store_config.h" #include "core/framework/config/load_config.h" #include "core/framework/config/model_config.h" -#include "core/framework/config/parallel_config.h" #include "core/framework/config/parallel_config_validation.h" #include "core/framework/config/scheduler_config.h" #include "core/framework/config/service_config.h" @@ -50,7 +49,8 @@ limitations under the License. #if defined(USE_NPU) #include "models/model_registry.h" #endif -#include "core/common/types.h" +#include "core/distributed_runtime/llm_engine.h" +#include "core/scheduler/scheduler.h" #include "distributed_runtime/xservice_client.h" #include "runtime/options.h" #include "scheduler/profile/profile_manager.h" @@ -65,7 +65,8 @@ namespace xllm { LLMMaster::LLMMaster(const Options& options) : Master(options), master_status_(options.master_status()) { - const SchedulerConfig& scheduler_config = SchedulerConfig::get_instance(); + const bool enable_speculative_decode = + SpeculativeConfig::uses_speculative_pipeline(options); #if defined(USE_NPU) resolve_npu_kernel_backend(&options_, /*model_component=*/"causal_lm"); #endif @@ -76,11 +77,8 @@ LLMMaster::LLMMaster(const Options& options) options_.validate(model_type); validate_layerwise_split_size_startup_config(options_, model_type); options_.enable_mla(model_args_.enable_mla()); - const bool use_ssm_engine = options_.num_speculative_tokens() > 0; - const EngineType engine_type = - use_ssm_engine ? EngineType::SSM : EngineType::LLM; - const std::optional cp_error = - validate_context_parallel_config(options_, engine_type, model_type); + const std::optional cp_error = validate_context_parallel_config( + options_, /*engine_type=*/EngineType::LLM, model_type); CHECK(!cp_error.has_value()) << cp_error.value(); const std::optional speculative_error = ModelConfig::validate_python_speculative_decode( @@ -91,16 +89,14 @@ LLMMaster::LLMMaster(const Options& options) CHECK(!speculative_error.has_value()) << speculative_error.value(); if (options_.host_blocks_factor() > 1.0) { - const bool supports_host_offload = - engine_type == EngineType::LLM || - SpeculativeConfig::supports_host_kv_cache( - options_.speculative_algorithm()); - CHECK(supports_host_offload) + CHECK(!enable_speculative_decode || + SpeculativeConfig::supports_host_kv_cache( + options_.speculative_algorithm())) << "Basic host KV cache offload supports the LLM engine and " "model-based speculative engines only."; } - if (!use_ssm_engine && + if (!enable_speculative_decode && (options_.task_type() == "embed" || options_.task_type() == "mm_embed")) { options_.enable_schedule_overlap(false); LOG(WARNING) << "Force to disable schedule overlap for embedding model, " @@ -109,25 +105,12 @@ LLMMaster::LLMMaster(const Options& options) runtime::Options engine_options = create_runtime_options(options_, devices_); - if (!use_ssm_engine) { - llm_engine_ = std::make_unique(engine_options); - } else { - engine_options.draft_model_path(options_.draft_model_path()) - .num_speculative_tokens(options_.num_speculative_tokens()) - .speculative_algorithm(options_.speculative_algorithm()) - .enable_probabilistic_draft(options_.enable_probabilistic_draft()) - .enable_mtp_draft_body_tp1(options_.enable_mtp_draft_body_tp1()) - .speculative_suffix_cache_max_depth( - options_.speculative_suffix_cache_max_depth()) - .speculative_suffix_max_cached_requests( - options_.speculative_suffix_max_cached_requests()); - speculative_engine_ = - std::make_unique>(engine_options); + if (enable_speculative_decode) { + SpeculativeConfig::apply_speculative_options(options_, engine_options); } - distributed_worker_manager_ = dispatch_engine( - [](auto* engine) { return engine->get_distributed_worker_manager(); }, - llm_engine_.get(), - speculative_engine_.get()); + + llm_engine_ = std::make_unique(engine_options); + distributed_worker_manager_ = llm_engine_->get_distributed_worker_manager(); model_residency_coordinator_ = std::make_shared( ModelResidencyCoordinator::Options{ .enabled = KVCacheConfig::get_instance().enable_vmm_kvcache() || @@ -145,114 +128,35 @@ LLMMaster::LLMMaster(const Options& options) .prefetch_batch_size = options_.prefetch_batch_size()}, distributed_worker_manager_); - const LLMEngine::ModelInitCallback prepare_model = - [this](const ModelLoader& model_loader, - int64_t num_layers, - int32_t dp_size, - int32_t tp_size, - MasterStatus master_status) { - return model_residency_coordinator_->initialize_model( - model_loader, num_layers, dp_size, tp_size, master_status); - }; - auto initialize_engine = [this, &prepare_model](auto* engine) { - CHECK( - engine->init(master_status_, prepare_model, kv_transfer_coordinator_)); - if (llm_engine_ != nullptr) { - CHECK( - model_residency_coordinator_->finish_initialization(master_status_)); - } - model_args_ = engine->model_args(); - if (options_.enable_service_routing()) { - xservice_client_ = XServiceClient::get_instance(); - CHECK(xservice_client_->init(options_.etcd_addr().value_or(""), - options_.instance_name().value_or(""), - options_.etcd_namespace().value_or(""))) - << "XServiceClient init fail!"; - } - }; - dispatch_engine( - initialize_engine, llm_engine_.get(), speculative_engine_.get()); + const ModelInitCallback prepare_model = + make_model_init_callback(model_residency_coordinator_.get()); + CHECK(llm_engine_->init( + master_status_, prepare_model, kv_transfer_coordinator_)); + if (supports_model_residency()) { + CHECK(model_residency_coordinator_->finish_initialization(master_status_)); + } + model_args_ = llm_engine_->model_args(); + xservice_client_ = init_service_routing(); task_type_ = options_.task_type(); - SchedulerOptions scheduler_options; - scheduler_options.model_id(engine_options.model_id()) - .model_impl(engine_options.model_impl()) - .enable_graph(options_.enable_graph()) - .disable_graph_warmup(options_.disable_graph_warmup()) - .enable_fia_decode(engine_options.enable_fia_decode()) - .enable_prefix_cache(options_.enable_prefix_cache()) - .enable_in_batch_prefix_cache( - KVCacheConfig::get_instance().enable_in_batch_prefix_cache()) - .max_tokens_per_batch(options_.max_tokens_per_batch()) - .max_seqs_per_batch(options_.max_seqs_per_batch()) - .max_concurrent_requests(options_.max_concurrent_requests()) - .num_response_handling_threads( - ServiceConfig::get_instance().num_response_handling_threads()) - .request_queue_size(options_.request_queue_size()) - .max_tokens_per_chunk_for_prefill( - options_.max_tokens_per_chunk_for_prefill()) - .num_speculative_tokens(options_.num_speculative_tokens()) - .speculative_algorithm(options_.speculative_algorithm()) - .decode_graph_warmup_config(options_.decode_graph_warmup_config()) - .nnodes(options_.nnodes()) - .dp_size(options_.dp_size()) - .cp_size(options_.cp_size()) - .kv_split_size(ParallelConfig::get_instance().kv_split_size_effective()) - .enable_mix_batch(scheduler_config.enable_mix_batch()) - .prefill_scheduling_memory_usage_threshold( - scheduler_config.prefill_scheduling_memory_usage_threshold()) - .chunked_match_frequency(scheduler_config.chunked_match_frequency()) - .aggressive_coeff(scheduler_config.aggressive_coeff()) - .enable_starve_prevent(scheduler_config.enable_starve_prevent()) - .starve_threshold(scheduler_config.starve_threshold()) - .enable_disagg_pd(options_.enable_disagg_pd()) - .enable_schedule_overlap(options_.enable_schedule_overlap()) - .enable_chunked_prefill(options_.enable_chunked_prefill()) - .enable_dp_fair_token_budget(options_.enable_dp_fair_token_budget()) - .instance_name(options_.instance_name()) - .instance_role(options_.instance_role()) - .kv_cache_transfer_mode(options_.kv_cache_transfer_mode()) - .enable_service_routing(options_.enable_service_routing()) - .disable_log_stats(options_.disable_log_stats()) - .priority_strategy(options_.priority_strategy()) - .enable_profile_step_time(options_.enable_profile_step_time()) - .enable_profile_token_budget(options_.enable_profile_token_budget()) - .enable_latency_aware_schedule(options_.enable_latency_aware_schedule()) - .enable_control_h2d_block_num( - KVCacheStoreConfig::get_instance().enable_control_h2d_block_num()) - .profile_max_prompt_length(options_.profile_max_prompt_length()) - .enable_profile_kv_blocks(options_.enable_profile_kv_blocks()) - .disable_ttft_profiling(options_.disable_ttft_profiling()) - .max_global_ttft_ms(options_.max_global_ttft_ms()) - .max_global_tpot_ms(options_.max_global_tpot_ms()) - .server_idx(options_.server_idx()); - PDServiceOptions response_options = - make_pd_service_options(options_, model_args_); - auto create_scheduler = - [this, &scheduler_options, &response_options](auto* engine) { - scheduler_ = create_continuous_scheduler( - engine, - scheduler_options, - distributed_worker_manager_, - llm_engine_ != nullptr ? model_residency_coordinator_ : nullptr, - kv_transfer_coordinator_, - std::move(response_options)); - }; - dispatch_engine( - create_scheduler, llm_engine_.get(), speculative_engine_.get()); - - if (options_.enable_service_routing()) { - auto& instance_info = scheduler_->get_instance_info(); - XServiceClient::get_instance()->register_instance(instance_info); + scheduler_ = create_continuous_scheduler( + llm_engine_->kv_cache_manager(), + &llm_engine_->model_args(), + llm_engine_->tokenizer(), + make_scheduler_callbacks(llm_engine_.get()), + make_scheduler_options(), + supports_model_residency() ? model_residency_coordinator_ : nullptr, + distributed_worker_manager_, + kv_transfer_coordinator_, + make_pd_service_options(options_, model_args_)); + + if (xservice_client_ != nullptr) { + xservice_client_->register_instance(scheduler_->get_instance_info()); } - auto initialize_tokenizer = [this](auto* engine) { - chat_template_ = ChatTemplateFactory::create(engine->tokenizer_args(), - model_args_.model_type()); - tokenizer_ = engine->tokenizer()->clone(); - }; - dispatch_engine( - initialize_tokenizer, llm_engine_.get(), speculative_engine_.get()); + chat_template_ = ChatTemplateFactory::create(llm_engine_->tokenizer_args(), + model_args_.model_type()); + tokenizer_ = llm_engine_->tokenizer()->clone(); Tokenizer* request_tokenizer = tokenizer_.get(); threadpool_ = std::make_unique( /*num_threads=*/options_.num_request_handling_threads(), @@ -537,26 +441,22 @@ void LLMMaster::generate() { running_.store(false, std::memory_order_relaxed); } -bool LLMMaster::handle_rpc_response(const RequestOutput& output) { - // response to xllm service to avoid the redirect cost. - if (xservice_client_ == nullptr) return false; - auto return_status = xservice_client_->generations({output}); - CHECK_EQ(return_status.size(), 1) - << "return size of generations is not equal to 1"; - return return_status[0]; -} - std::vector LLMMaster::handle_rpc_responses( const std::vector& outputs) { - // response to xllm service to avoid the redirect cost. - if (xservice_client_ == nullptr) + if (xservice_client_ == nullptr) { return std::vector(outputs.size(), false); + } return xservice_client_->generations(outputs); } +bool LLMMaster::supports_model_residency() const { + return !SpeculativeConfig::uses_speculative_pipeline(options_) && + model_residency_coordinator_->enabled(); +} + bool LLMMaster::sleep() { - if (llm_engine_ == nullptr) { - LOG(ERROR) << "Sleep is not supported for speculative engines."; + if (!supports_model_residency()) { + LOG(ERROR) << "Sleep is not supported for this engine type."; return false; } return model_residency_coordinator_->sleep(master_status_); @@ -568,8 +468,8 @@ bool LLMMaster::requires_wakeup() const { } bool LLMMaster::wakeup(const WakeupOptions& options) { - if (llm_engine_ == nullptr) { - LOG(ERROR) << "Wakeup is not supported for speculative engines."; + if (!supports_model_residency()) { + LOG(ERROR) << "Wakeup is not supported for this engine type."; return false; } WakeupOptions opts = options; @@ -585,16 +485,8 @@ bool LLMMaster::unlink_p2p(const std::vector& remote_addrs) { return distributed_worker_manager_->unlink_p2p(remote_addrs); } -bool LLMMaster::start_profile() { - return dispatch_engine([](auto* engine) { return engine->start_profile(); }, - llm_engine_.get(), - speculative_engine_.get()); -} +bool LLMMaster::start_profile() { return llm_engine_->start_profile(); } -bool LLMMaster::stop_profile() { - return dispatch_engine([](auto* engine) { return engine->stop_profile(); }, - llm_engine_.get(), - speculative_engine_.get()); -} +bool LLMMaster::stop_profile() { return llm_engine_->stop_profile(); } } // namespace xllm diff --git a/xllm/core/distributed_runtime/llm_master.h b/xllm/core/distributed_runtime/llm_master.h index ebae2f5f97..c59d221b5e 100644 --- a/xllm/core/distributed_runtime/llm_master.h +++ b/xllm/core/distributed_runtime/llm_master.h @@ -33,15 +33,15 @@ limitations under the License. #include "framework/request/request_params.h" #include "llm_engine.h" #include "master.h" -#include "scheduler/continuous_scheduler.h" -#include "speculative_engine.h" namespace xllm { class Call; class Tokenizer; class ModelResidencyCoordinator; +class Scheduler; class KVTransferCoordinator; +class XServiceClient; class LLMMaster : public Master { public: @@ -81,8 +81,6 @@ class LLMMaster : public Master { BatchOutputCallback callback); // handle rpc response, send stream generations to xllm service - bool handle_rpc_response(const RequestOutput& output); - std::vector handle_rpc_responses( const std::vector& outputs); @@ -123,8 +121,8 @@ class LLMMaster : public Master { bool unlink_p2p(const std::vector& remote_addrs); - bool start_profile(); - bool stop_profile(); + bool start_profile() override; + bool stop_profile() override; private: template @@ -132,10 +130,12 @@ class LLMMaster : public Master { std::vector params, BatchOutputCallback callback); + bool supports_model_residency() const; + std::shared_ptr kv_transfer_coordinator_; + XServiceClient* xservice_client_ = nullptr; MasterStatus master_status_; - XServiceClient* xservice_client_ = nullptr; // Shared workers outlive the scheduler and every engine using them. std::shared_ptr distributed_worker_manager_; @@ -143,10 +143,7 @@ class LLMMaster : public Master { // Created by the master after worker setup and shared with serving consumers. std::shared_ptr model_residency_coordinator_; - // Exactly one of these owners is populated, depending on the configured - // LLM execution mode. std::unique_ptr llm_engine_; - std::unique_ptr> speculative_engine_; // Scheduler must be destroyed before the engine it references. std::unique_ptr scheduler_; diff --git a/xllm/core/distributed_runtime/master.cpp b/xllm/core/distributed_runtime/master.cpp index a8f67e2142..742b2f85f9 100644 --- a/xllm/core/distributed_runtime/master.cpp +++ b/xllm/core/distributed_runtime/master.cpp @@ -31,14 +31,20 @@ limitations under the License. #include "common/types.h" #include "core/common/xllm_build_info.h" +#include "core/distributed_runtime/xservice_client.h" #include "core/framework/config/eplb_config.h" +#include "core/framework/config/execution_config.h" #include "core/framework/config/kv_cache_config.h" +#include "core/framework/config/kv_cache_store_config.h" +#include "core/framework/config/model_config.h" #include "core/framework/config/parallel_config.h" #include "core/framework/config/scheduler_config.h" +#include "core/framework/config/service_config.h" #if defined(USE_NPU) #include "framework/parallel_state/npu_rank_table_env.h" #endif #include "core/platform/device_name_utils.h" +#include "core/scheduler/scheduler.h" #include "platform/platform.h" namespace brpc { @@ -221,6 +227,75 @@ void Master::wait() { } } +SchedulerOptions Master::make_scheduler_options() const { + const SchedulerConfig& scheduler_config = SchedulerConfig::get_instance(); + SchedulerOptions scheduler_options; + scheduler_options.model_id(options_.model_id()) + .model_impl(ModelConfig::get_instance().model_impl()) + .enable_graph(options_.enable_graph()) + .disable_graph_warmup(options_.disable_graph_warmup()) + .enable_fia_decode(ExecutionConfig::get_instance().enable_fia_decode()) + .enable_prefix_cache(options_.enable_prefix_cache()) + .enable_in_batch_prefix_cache( + KVCacheConfig::get_instance().enable_in_batch_prefix_cache()) + .max_tokens_per_batch(options_.max_tokens_per_batch()) + .max_seqs_per_batch(options_.max_seqs_per_batch()) + .max_concurrent_requests(options_.max_concurrent_requests()) + .num_response_handling_threads( + ServiceConfig::get_instance().num_response_handling_threads()) + .request_queue_size(options_.request_queue_size()) + .max_tokens_per_chunk_for_prefill( + options_.max_tokens_per_chunk_for_prefill()) + .num_speculative_tokens(options_.num_speculative_tokens()) + .speculative_algorithm(options_.speculative_algorithm()) + .decode_graph_warmup_config(options_.decode_graph_warmup_config()) + .nnodes(options_.nnodes()) + .dp_size(options_.dp_size()) + .cp_size(options_.cp_size()) + .kv_split_size(ParallelConfig::get_instance().kv_split_size_effective()) + .enable_mix_batch(scheduler_config.enable_mix_batch()) + .prefill_scheduling_memory_usage_threshold( + scheduler_config.prefill_scheduling_memory_usage_threshold()) + .chunked_match_frequency(scheduler_config.chunked_match_frequency()) + .aggressive_coeff(scheduler_config.aggressive_coeff()) + .enable_starve_prevent(scheduler_config.enable_starve_prevent()) + .starve_threshold(scheduler_config.starve_threshold()) + .enable_disagg_pd(options_.enable_disagg_pd()) + .enable_schedule_overlap(options_.enable_schedule_overlap()) + .enable_chunked_prefill(options_.enable_chunked_prefill()) + .enable_dp_fair_token_budget(options_.enable_dp_fair_token_budget()) + .instance_name(options_.instance_name()) + .instance_role(options_.instance_role()) + .kv_cache_transfer_mode(options_.kv_cache_transfer_mode()) + .enable_service_routing(options_.enable_service_routing()) + .enable_control_h2d_block_num( + KVCacheStoreConfig::get_instance().enable_control_h2d_block_num()) + .disable_log_stats(options_.disable_log_stats()) + .priority_strategy(options_.priority_strategy()) + .enable_profile_step_time(options_.enable_profile_step_time()) + .enable_profile_token_budget(options_.enable_profile_token_budget()) + .enable_latency_aware_schedule(options_.enable_latency_aware_schedule()) + .profile_max_prompt_length(options_.profile_max_prompt_length()) + .enable_profile_kv_blocks(options_.enable_profile_kv_blocks()) + .disable_ttft_profiling(options_.disable_ttft_profiling()) + .max_global_ttft_ms(options_.max_global_ttft_ms()) + .max_global_tpot_ms(options_.max_global_tpot_ms()) + .server_idx(options_.server_idx()); + return scheduler_options; +} + +XServiceClient* Master::init_service_routing() { + if (!options_.enable_service_routing()) { + return nullptr; + } + XServiceClient* xservice_client = XServiceClient::get_instance(); + CHECK(xservice_client->init(options_.etcd_addr().value_or(""), + options_.instance_name().value_or(""), + options_.etcd_namespace().value_or(""))) + << "XServiceClient init fail!"; + return xservice_client; +} + void Master::run() { idle_running_.store(true, std::memory_order_relaxed); signal(SIGINT, Master::handle_shutdown_signal); diff --git a/xllm/core/distributed_runtime/master.h b/xllm/core/distributed_runtime/master.h index 60cad6b5af..62a464c318 100644 --- a/xllm/core/distributed_runtime/master.h +++ b/xllm/core/distributed_runtime/master.h @@ -27,6 +27,8 @@ limitations under the License. namespace xllm { class ModelArgs; +class XServiceClient; +struct SchedulerOptions; class Master { public: @@ -43,6 +45,9 @@ class Master { virtual const ModelArgs* model_args() const = 0; + virtual bool start_profile() { return false; } + virtual bool stop_profile() { return false; } + RateLimiter* get_rate_limiter() { return &rate_limiter_; } protected: @@ -50,6 +55,9 @@ class Master { // no external caller needs it. bool is_leader() const { return options_.node_rank() == 0; } + SchedulerOptions make_scheduler_options() const; + XServiceClient* init_service_routing(); + Options options_; std::vector devices_; RateLimiter rate_limiter_; diff --git a/xllm/core/distributed_runtime/master_manager.cpp b/xllm/core/distributed_runtime/master_manager.cpp index 62ad2fe922..4d36e6c31c 100644 --- a/xllm/core/distributed_runtime/master_manager.cpp +++ b/xllm/core/distributed_runtime/master_manager.cpp @@ -429,12 +429,7 @@ bool MasterManager::start_profile(std::string* error_message) { return false; } - bool started = false; - if (auto* llm_master = dynamic_cast(master.get())) { - started = llm_master->start_profile(); - } else if (auto* vlm_master = dynamic_cast(master.get())) { - started = vlm_master->start_profile(); - } + const bool started = master->start_profile(); if (!started && error_message != nullptr) { *error_message = "Failed to start profiler"; } @@ -451,12 +446,7 @@ bool MasterManager::stop_profile(std::string* error_message) { return false; } - bool stopped = false; - if (auto* llm_master = dynamic_cast(master.get())) { - stopped = llm_master->stop_profile(); - } else if (auto* vlm_master = dynamic_cast(master.get())) { - stopped = vlm_master->stop_profile(); - } + const bool stopped = master->stop_profile(); if (!stopped && error_message != nullptr) { *error_message = "Failed to stop profiler"; } diff --git a/xllm/core/distributed_runtime/model_residency_coordinator.h b/xllm/core/distributed_runtime/model_residency_coordinator.h index 181a01c88d..8b09dce4d1 100644 --- a/xllm/core/distributed_runtime/model_residency_coordinator.h +++ b/xllm/core/distributed_runtime/model_residency_coordinator.h @@ -68,6 +68,8 @@ class ModelResidencyCoordinator final { // This query does not wait for an in-progress allocator transition. bool is_suspended() const; + bool enabled() const { return options_.enabled; } + private: struct PendingSleep { MasterStatus master_status; @@ -91,4 +93,15 @@ class ModelResidencyCoordinator final { std::optional pending_wakeup_; }; +inline auto make_model_init_callback(ModelResidencyCoordinator* coordinator) { + return [coordinator](const ModelLoader& model_loader, + int64_t num_layers, + int32_t dp_size, + int32_t tp_size, + MasterStatus status) { + return coordinator->initialize_model( + model_loader, num_layers, dp_size, tp_size, status); + }; +} + } // namespace xllm diff --git a/xllm/core/distributed_runtime/speculative_engine.cpp b/xllm/core/distributed_runtime/speculative_engine.cpp deleted file mode 100644 index 838c9548f6..0000000000 --- a/xllm/core/distributed_runtime/speculative_engine.cpp +++ /dev/null @@ -1,357 +0,0 @@ -/* Copyright 2025-2026 The xLLM Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - https://github.com/xLLM-AI/xllm/blob/main/LICENSE - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#include "speculative_engine.h" - -#include - -#include -#include -#include -#include -#include - -#include "common/metrics.h" -#include "core/common/types.h" -#include "core/distributed_runtime/distributed_vmm_coordinator.h" -#include "core/framework/config/kv_cache_config.h" -#include "core/framework/config/speculative_config.h" -#include "core/framework/eplb/eplb_controller.h" -#include "core/kv_cache/layout/kv_cache_estimation.h" -#include "core/kv_cache/layout/vmm_kv_layout.h" -#include "core/util/tensor_options.h" -#include "llm_engine.h" -#include "util/utils.h" -#include "vlm_engine.h" - -namespace xllm { - -template -SpeculativeEngineBase::~SpeculativeEngineBase() = default; - -template -SpeculativeEngineBase::SpeculativeEngineBase( - const runtime::Options& options) - : options_(options) { - runtime::Options dist_options = options; - dist_options.enable_speculative_decode(true); - distributed_worker_manager_ = - std::make_shared(dist_options); - - engine_ = - std::make_unique(options_, distributed_worker_manager_); - - if (!SpeculativeConfig::is_suffix_algorithm( - options.speculative_algorithm())) { - // draft engine - // In vlm mtp case, we'd like to use llm backend instead of vlm backend for - // draft engine. - runtime::Options draft_engine_options = options_; - // The draft engine always runs on the target's device list. - draft_engine_options.model_path(options_.draft_model_path().value()) - .devices(options.devices()) - .backend("llm") - .enable_speculative_decode(/*enable_speculative_decode=*/false) - .enable_graph(/*enable_graph=*/false) - .is_draft_engine(true); - if (KVCacheConfig::get_instance().enable_vmm_kvcache()) { - draft_engine_options.model_id(options_.model_id() + "::mtp_draft"); - } - draft_engine_ = std::make_unique(draft_engine_options, - distributed_worker_manager_); - } -} - -template -bool SpeculativeEngineBase::init(MasterStatus master_status) { - return init(master_status, /*prepare_model=*/{}); -} - -template -bool SpeculativeEngineBase::init( - MasterStatus master_status, - const LLMEngine::ModelInitCallback& prepare_model, - std::shared_ptr transfer_coordinator) { - if (!init_model(master_status, prepare_model)) { - return false; - } - - if (!allocate_kv_cache(std::move(transfer_coordinator))) { - return false; - } - - return true; -} - -template -bool SpeculativeEngineBase::init_model( - MasterStatus master_status, - const LLMEngine::ModelInitCallback& prepare_model) { - if constexpr (std::is_same_v) { - if (!engine_->init_model(master_status, prepare_model)) { - return false; - } - } else { - if (!engine_->init_model(master_status)) { - return false; - } - } - - model_args_ = engine_->model_args(); - - if (draft_engine_ != nullptr) { - if (!draft_engine_->init_model(/*master_status=*/MasterStatus::WAKEUP, - prepare_model)) { - return false; - } - - // Draft tokens are detokenized by the target, so the draft engine needs no - // tokenizer and no draft/target vocab-compatibility check (not universal; - // see llm_engine.cpp). - - // check if the max context length are the same - const auto& draft_model_args = draft_engine_->model_args(); - if (model_args_.max_position_embeddings() != - draft_model_args.max_position_embeddings()) { - LOG(WARNING) << "draft and target models have different max context " - "lengths, draft max_position_embeddings: " - << draft_model_args.max_position_embeddings() - << ", target max_position_embeddings: " - << model_args_.max_position_embeddings() - << ", using the minimum between them"; - model_args_.max_position_embeddings() = - std::min(model_args_.max_position_embeddings(), - draft_model_args.max_position_embeddings()); - } - } - - engine_->eplb_controller_ = - EplbController::create(engine_->model_args(), - static_cast(engine_->worker_clients_num_), - engine_->options_.ep_size(), - engine_->options_.eplb_controller_config()); - engine_->forward_input_factory_->set_eplb_controller( - engine_->eplb_controller_.get()); - dtype_ = util::parse_dtype(model_args_.dtype(), options_.devices()[0]); - return true; -} - -template -bool SpeculativeEngineBase::allocate_kv_cache( - std::shared_ptr transfer_coordinator) { - const bool shared_vmm = KVCacheConfig::get_instance().enable_vmm_kvcache() && - draft_engine_ != nullptr; - KVCacheCapacity target_kv_cache_cap = - engine_->estimate_kv_cache_capacity(!shared_vmm); - std::optional shared_vmm_layout; - const auto allocate_target_cache = [this, - &transfer_coordinator, - shared_vmm, - &shared_vmm_layout]( - const KVCacheCapacity& capacity) { - const VmmKVLayout* layout = shared_vmm ? &*shared_vmm_layout : nullptr; - if constexpr (std::is_same_v) { - return engine_->allocate_kv_cache(capacity, transfer_coordinator, layout); - } else { - return engine_->allocate_kv_cache(capacity, layout, transfer_coordinator); - } - }; - - if (draft_engine_ == nullptr) { - return allocate_target_cache(target_kv_cache_cap); - } - - KVCacheCapacity draft_kv_cache_cap = - draft_engine_->estimate_kv_cache_capacity(!shared_vmm); - if (target_kv_cache_cap.shared_slot_bytes() > 0) { - const SharedStaticKVCachePlan plan = - plan_shared_static_kv_cache(std::move(target_kv_cache_cap), - std::move(draft_kv_cache_cap), - engine_->model_args(), - engine_->dp_local_tp_size_, - dtype_); - return allocate_target_cache(plan.target) && - draft_engine_->allocate_kv_cache(plan.draft, - std::move(transfer_coordinator)); - } - - int64_t shared_vmm_blocks = 0; - if (shared_vmm) { - shared_vmm_layout.emplace(target_kv_cache_cap, - engine_->model_args(), - engine_->dp_local_tp_size_, - dtype_); - const int64_t draft_world_size = options_.enable_mtp_draft_body_tp1() - ? 1 - : draft_engine_->dp_local_tp_size_; - VmmKVLayout draft_layout(draft_kv_cache_cap, - draft_engine_->model_args(), - draft_world_size, - draft_engine_->dtype_); - shared_vmm_layout->append(std::move(draft_layout)); - const int64_t reserved_state_bytes = - target_kv_cache_cap.linear_cache_size_in_bytes() + - draft_kv_cache_cap.linear_cache_size_in_bytes(); - auto& coordinator = DistributedVmmCoordinator::get_instance(); - coordinator.prepare_kv_cache_pool( - engine_->options_, - engine_->dp_local_tp_size_, - engine_->worker_clients_.size(), - reserved_state_bytes, - /*is_multimodal=*/std::is_same_v); - const KVCacheConfig& config = KVCacheConfig::get_instance(); - const size_t total_pages = coordinator.get_num_total_phy_pages(); - const int64_t pool_bytes = - static_cast(total_pages) * config.phy_page_granularity_size(); - const size_t n_blocks = shared_vmm_layout->block_capacity( - total_pages, config.phy_page_granularity_size()); - shared_vmm_blocks = static_cast(n_blocks); - // Report the combined budget, while paged K/V block capacity depends only - // on the pool. Persistent states have already been reserved outside it. - target_kv_cache_cap.cache_size_in_bytes(pool_bytes + reserved_state_bytes); - draft_kv_cache_cap.cache_size_in_bytes(pool_bytes + reserved_state_bytes); - } - - if (target_kv_cache_cap.c4_count() > 0 || - target_kv_cache_cap.c128_count() > 0) { - draft_kv_cache_cap.n_blocks() = target_kv_cache_cap.n_blocks(); - return allocate_target_cache(target_kv_cache_cap) && - draft_engine_->allocate_kv_cache(draft_kv_cache_cap, - std::move(transfer_coordinator)); - } - - if (target_kv_cache_cap.kpool_tail_slot_size() > 0 && - draft_kv_cache_cap.kpool_tail_slot_size() > 0) { - const SharedKPoolPlan plan = - plan_shared_kpool(std::move(target_kv_cache_cap), - std::move(draft_kv_cache_cap), - draft_engine_->model_args()); - return allocate_target_cache(plan.target) && - draft_engine_->allocate_kv_cache(plan.draft, - std::move(transfer_coordinator)); - } - - const int64_t kv_cache_size = - std::min(target_kv_cache_cap.cache_size_in_bytes(), - draft_kv_cache_cap.cache_size_in_bytes()); - - // Target and draft run on the same device list, so they share a common KV - // cache budget. - const int64_t n_blocks = - shared_vmm ? shared_vmm_blocks - : calculate_kv_cache(target_kv_cache_cap, draft_kv_cache_cap); - CHECK_GT(n_blocks, 0) << "no memory for kv cache"; - - // allocate kv cache - target_kv_cache_cap.n_blocks() = n_blocks; - target_kv_cache_cap.cache_size_in_bytes() = kv_cache_size; - draft_kv_cache_cap.n_blocks() = n_blocks; - draft_kv_cache_cap.cache_size_in_bytes() = kv_cache_size; - return allocate_target_cache(target_kv_cache_cap) && - draft_engine_->allocate_kv_cache(draft_kv_cache_cap, - std::move(transfer_coordinator)); -} - -// TODO: support dp batches later -template -ForwardOutput SpeculativeEngineBase::step(BatchGroup& batches) { - return engine_->step(batches); -} - -template -int64_t SpeculativeEngineBase::calculate_kv_cache( - const KVCacheCapacity& target_kv_cache_cap, - const KVCacheCapacity& draft_kv_cache_cap) const { - CHECK_GT(target_kv_cache_cap.cache_size_in_bytes(), 0) - << "no memory for target kv cache"; - CHECK_GT(draft_kv_cache_cap.cache_size_in_bytes(), 0) - << "no memory for draft kv cache"; - const int64_t block_size = target_kv_cache_cap.block_size(); - CHECK_EQ(block_size, draft_kv_cache_cap.block_size()) - << "target and draft kv cache block size must be the same"; - - const int64_t cache_size_in_bytes = - std::min(target_kv_cache_cap.cache_size_in_bytes(), - draft_kv_cache_cap.cache_size_in_bytes()); - const int64_t linear_cache_size_in_bytes = - target_kv_cache_cap.linear_cache_size_in_bytes() + - draft_kv_cache_cap.linear_cache_size_in_bytes(); - CHECK_GT(cache_size_in_bytes, linear_cache_size_in_bytes) - << "no memory left for speculative full-attention kv cache after " - "reserving target and draft state caches, cache_size: " - << cache_size_in_bytes - << ", linear_cache_size: " << linear_cache_size_in_bytes; - - CHECK_GT(target_kv_cache_cap.slot_size() + - target_kv_cache_cap.index_slot_size() + - target_kv_cache_cap.scale_slot_size(), - 0) - << "target full-attention kv cache slot size must be greater than 0"; - CHECK_GT(draft_kv_cache_cap.slot_size() + - draft_kv_cache_cap.index_slot_size() + - draft_kv_cache_cap.scale_slot_size(), - 0) - << "draft full-attention kv cache slot size must be greater than 0"; - - const int64_t target_full_attention_layers = - std::max(target_kv_cache_cap.num_full_attention_layers(), 1); - // Draft model has no linear-attention layers in the current MTP/Eagle path. - const int64_t draft_full_attention_layers = draft_kv_cache_cap.n_layers(); - const int64_t target_full_attention_block_size_in_bytes = - block_size * (target_full_attention_layers * - (target_kv_cache_cap.slot_size() + - target_kv_cache_cap.scale_slot_size())) + - target_kv_cache_cap.num_indexer_layers() * - target_kv_cache_cap.index_block_bytes(); - // The draft KV cache is allocated from the draft's own KVCacheShape, so its - // per-block cost uses the draft's own slot size, which may exceed the - // target's (e.g. a full-attention draft against an MLA target). - const int64_t draft_full_attention_block_size_in_bytes = - block_size * (draft_full_attention_layers * - (draft_kv_cache_cap.slot_size() + - draft_kv_cache_cap.scale_slot_size())) + - draft_kv_cache_cap.num_indexer_layers() * - draft_kv_cache_cap.index_block_bytes(); - const int32_t layerwise_split_size = - options_.is_draft_engine() ? 1 : options_.layerwise_split_size(); - if (layerwise_split_size > 1) { - return estimate_layerwise_split_block_count( - model_args_, - layerwise_split_size, - target_kv_cache_cap, - cache_size_in_bytes - linear_cache_size_in_bytes, - draft_full_attention_block_size_in_bytes); - } - const int64_t full_attention_block_size_in_bytes = - target_full_attention_block_size_in_bytes + - draft_full_attention_block_size_in_bytes; - CHECK_GT(full_attention_block_size_in_bytes, 0) - << "speculative kv cache block size in bytes must be greater than 0"; - - return (cache_size_in_bytes - linear_cache_size_in_bytes) / - full_attention_block_size_in_bytes; -} - -template -std::vector -SpeculativeEngineBase::collect_step_outputs( - const BatchGroup& batch) { - return engine_->collect_step_outputs(batch); -} - -template class SpeculativeEngineBase; -template class SpeculativeEngineBase; - -} // namespace xllm diff --git a/xllm/core/distributed_runtime/speculative_engine.h b/xllm/core/distributed_runtime/speculative_engine.h deleted file mode 100644 index 69141fc161..0000000000 --- a/xllm/core/distributed_runtime/speculative_engine.h +++ /dev/null @@ -1,103 +0,0 @@ -/* Copyright 2025-2026 The xLLM Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - https://github.com/xLLM-AI/xllm/blob/main/LICENSE - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - -#pragma once - -#include "common/macros.h" -#include "core/kv_cache/layout/kv_cache_capacity.h" -#include "engine.h" -#include "framework/batch/batch_group.h" -#include "framework/model/model_args.h" -#include "framework/tokenizer/tokenizer.h" -#include "framework/tokenizer/tokenizer_args.h" -#include "llm_engine.h" -#include "vlm_engine.h" - -namespace xllm { - -template -class SpeculativeEngineBase : public Engine { - public: - // create an engine with the given devices - explicit SpeculativeEngineBase(const runtime::Options& options); - - ~SpeculativeEngineBase() override; - - bool init(MasterStatus master_status) override; - - bool init(MasterStatus master_status, - const LLMEngine::ModelInitCallback& prepare_model, - std::shared_ptr transfer_coordinator = - nullptr); - - // step the engine forward - ForwardOutput step(BatchGroup& batch); - - const Tokenizer* tokenizer() const override { return engine_->tokenizer(); } - - KVCacheManager* kv_cache_manager() const override { - return engine_->kv_cache_manager(); - } - - const ModelArgs& model_args() const override { return model_args_; } - - // Return the options used by the target engine. - const runtime::Options& options() const { return engine_->options(); } - - std::shared_ptr get_distributed_worker_manager() - const { - return distributed_worker_manager_; - } - - const TokenizerArgs& tokenizer_args() const override { - return engine_->tokenizer_args(); - } - - // Target and draft share workers, so profile their processes only once. - bool start_profile() override { return engine_->start_profile(); } - - bool stop_profile() override { return engine_->stop_profile(); } - - std::vector collect_step_outputs(const BatchGroup& batch); - - private: - bool init_model(MasterStatus master_status, - const LLMEngine::ModelInitCallback& prepare_model); - - bool allocate_kv_cache( - std::shared_ptr transfer_coordinator); - - int64_t calculate_kv_cache(const KVCacheCapacity& target_kv_cache_cap, - const KVCacheCapacity& draft_kv_cache_cap) const; - - // dtype - torch::ScalarType dtype_; - - // options - const runtime::Options options_; - - // engine - std::unique_ptr engine_; - - // draft engine - std::unique_ptr draft_engine_; - - ModelArgs model_args_; - - std::shared_ptr distributed_worker_manager_ = - nullptr; -}; - -} // namespace xllm diff --git a/xllm/core/distributed_runtime/vlm_engine.cpp b/xllm/core/distributed_runtime/vlm_engine.cpp index 72c4ea4124..a910fcc4d0 100644 --- a/xllm/core/distributed_runtime/vlm_engine.cpp +++ b/xllm/core/distributed_runtime/vlm_engine.cpp @@ -34,11 +34,9 @@ limitations under the License. #include "core/common/prefill_policy.h" #include "core/common/types.h" #include "core/distributed_runtime/distributed_vmm_coordinator.h" -#include "core/distributed_runtime/kv_capacity_planner.h" #include "core/distributed_runtime/worker_step_dispatch.h" #include "core/framework/config/execution_config.h" #include "core/framework/config/kv_cache_config.h" -#include "core/framework/config/load_config.h" #include "core/framework/config/model_config.h" #include "core/framework/config/service_config.h" #include "core/framework/config/speculative_config.h" @@ -48,6 +46,7 @@ limitations under the License. #include "core/kv_cache/layout/kv_cache_shape.h" #include "core/kv_cache/manager/kv_cache_manager_factory.h" #include "core/kv_cache/storage/host_cache_layout.h" +#include "core/runtime/worker_client.h" #include "core/util/tensor_helper.h" #include "core/util/tensor_options.h" #include "framework/model/model_args.h" @@ -57,7 +56,6 @@ limitations under the License. #include "runtime/vlm_forward_params.h" #include "runtime/worker.h" #include "util/env_var.h" -#include "util/pretty_print.h" #include "util/utils.h" namespace xllm { @@ -111,11 +109,7 @@ void attach_embedding_output_metadata(const ModelArgs& args, } // namespace -VLMEngine::VLMEngine( - const runtime::Options& options, - std::shared_ptr distributed_worker_manager) - : options_(options), - distributed_worker_manager_(std::move(distributed_worker_manager)) { +VLMEngine::VLMEngine(const runtime::Options& options) : Engine(options) { auto master_node_addr = options.master_node_addr().value_or(""); CHECK(!master_node_addr.empty()) << " VLM need to set master node addr, Please set --master_node_addr."; @@ -130,19 +124,16 @@ VLMEngine::VLMEngine( } // setup all workers and create worker clients in nnode_rank=0 engine side. - setup_workers(options); + setup_workers(); - dp_size_ = options_.dp_size(); - worker_clients_num_ = worker_clients_.size(); - dp_local_size_ = get_workers_per_dp_rank(worker_clients_num_, dp_size_); + dp_local_size_ = get_workers_per_dp_rank(worker_clients_num(), dp_size()); dp_local_tp_size_ = dp_local_size_ / options_.cp_size(); - process_group_test(); forward_input_factory_ = std::make_unique>( ForwardInputFactoryOptions{ - .dp_size = dp_size_, + .dp_size = dp_size(), .cp_size = static_cast(options_.cp_size()), .input_options = {.kv_split_size = options_.kv_split_size(), .build_execution_batch = @@ -156,48 +147,12 @@ VLMEngine::VLMEngine( static_cast(options_.max_tokens_per_batch()), .enable_graph = options_.enable_graph(), .enable_dp_global_json_object_active = - dp_size_ > 1 && !options_.is_draft_engine() && + dp_size() > 1 && !options_.is_draft_engine() && options_.num_speculative_tokens() > 0, .enable_shared_kv_cache_deltas = KVCacheConfig::get_instance().enable_shared_kv_cache()}); } -void VLMEngine::process_group_test() { -#if !defined(USE_NPU) - // In multi-node serving mode, only driver engine - // create worker_clients_. - if (worker_clients_num_ > 1) { - // test process group - std::vector> futures; - futures.reserve(worker_clients_num_); - for (auto& worker : worker_clients_) { - futures.emplace_back(worker->process_group_test_async()); - } - // Wait for all futures to complete with a configurable timeout. - // The timeout can be adjusted via the - // XLLM_PROCESS_GROUP_ASYNC_TIMEOUT_SECONDS environment variable (default: 4 - // seconds). This is particularly important in multi-node multi-device - // communication scenarios where network latency may require a longer - // timeout period. - const int timeout_seconds = util::get_process_group_test_timeout_seconds(); - folly::collectAll(futures) - .within(std::chrono::seconds(timeout_seconds)) - .get(); - } -#endif -} - -bool VLMEngine::init(MasterStatus master_status) { - return init(master_status, /*transfer_coordinator=*/nullptr); -} - -bool VLMEngine::init( - MasterStatus master_status, - std::shared_ptr transfer_coordinator) { - return init( - master_status, /*prepare_model=*/{}, std::move(transfer_coordinator)); -} - bool VLMEngine::init( MasterStatus master_status, const ModelInitCallback& prepare_model, @@ -209,16 +164,20 @@ bool VLMEngine::init( eplb_controller_ = EplbController::create(args_, - static_cast(worker_clients_num_), + static_cast(worker_clients_num()), options_.ep_size(), options_.eplb_controller_config()); forward_input_factory_->set_eplb_controller(eplb_controller_.get()); - auto kv_cache_cap = estimate_kv_cache_capacity(); + const auto plan = init_draft_and_estimate_capacity(); + if (!plan.has_value()) { + return false; + } - if (!allocate_kv_cache(kv_cache_cap, - /*shared_vmm_layout=*/nullptr, - std::move(transfer_coordinator))) { + if (!allocate_kv_cache( + plan->capacity_, + plan->shared_vmm_layout_ ? &*plan->shared_vmm_layout_ : nullptr, + std::move(transfer_coordinator))) { LOG(ERROR) << "Failed to allocate kv cache"; return false; } @@ -242,24 +201,7 @@ bool VLMEngine::init_model(MasterStatus master_status, LOG(INFO) << "Block info, block_size: " << options_.block_size() << ", n_layers: " << args_.n_layers() << ", dtype: " << dtype_; - const int64_t tokenizer_vocab_size = - static_cast(tokenizer_->vocab_size()); - int64_t model_vocab_size = args_.vocab_size(); - if (tokenizer_vocab_size != model_vocab_size) { - // use tokenizer vocab size if model vocab size is not set - if (model_vocab_size <= 0) { - LOG(WARNING) << "Model vocab size is not set, using tokenizer vocab " - "size: " - << tokenizer_vocab_size; - args_.vocab_size(tokenizer_vocab_size); - } else if (tokenizer_vocab_size > model_vocab_size) { - LOG(WARNING) << "Unsafe vocab mismatch: tokenizer: " - << tokenizer_vocab_size << ", model: " << model_vocab_size; - } else { - LOG(INFO) << "Tokenizer/model vocab differ: tokenizer=" - << tokenizer_vocab_size << ", model=" << model_vocab_size; - } - } + reconcile_vocab_size(static_cast(tokenizer_->vocab_size())); LOG(INFO) << "Initializing model with " << args_; LOG(INFO) << "Initializing model with quant args: " @@ -268,52 +210,7 @@ bool VLMEngine::init_model(MasterStatus master_status, LOG(INFO) << "Initializing model with random seed: " << ::xllm::ExecutionConfig::get_instance().random_seed(); - if (prepare_model && !prepare_model(*model_loader, - args_.n_layers(), - static_cast(dp_size_), - static_cast(dp_local_tp_size_), - master_status)) { - return false; - } - if (LoadConfig::get_instance().enable_vmm_weights() && - !KVCacheConfig::get_instance().enable_vmm_kvcache() && - master_status != MasterStatus::WAKEUP) { - initial_weight_reservation_bytes_ = - DistributedVmmCoordinator::get_instance().get_weight_page_count( - options_.model_id()) * - KVCacheConfig::get_instance().phy_page_granularity_size(); - } - - // init model for each worker in parallel - // multiple workers, call async init - std::vector> futures; - futures.reserve(worker_clients_num_); - for (auto& worker : worker_clients_) { - futures.push_back(worker->init_model_async( - model_path, - ::xllm::ExecutionConfig::get_instance().random_seed(), - master_status)); - } - // wait for all futures to complete - auto results = folly::collectAll(futures).get(); - for (const auto& result : results) { - if (!result.value()) { - return false; - } - } - return true; -} - -KVCacheCapacity VLMEngine::estimate_kv_cache_capacity( - bool initialize_virtual_memory) { - return KVCapacityPlanner(args_, - options_, - dtype_, - dp_local_tp_size_, - worker_clients_, - /*is_multimodal=*/true, - initial_weight_reservation_bytes_) - .plan(initialize_virtual_memory); + return dispatch_model_load(*model_loader, master_status, prepare_model); } bool VLMEngine::allocate_kv_cache( @@ -323,29 +220,7 @@ bool VLMEngine::allocate_kv_cache( const bool enable_state_cache = has_linear_attention_layers(args_) || kv_cache_cap.kpool_tail_slot_size() > 0; - LOG(INFO) << "kv cache capacity: " - << readable_size(kv_cache_cap.cache_size_in_bytes()) - << ", blocks: " << kv_cache_cap.n_blocks() - << ", slot_size: " << kv_cache_cap.slot_size() - << ", index_slot_size: " << kv_cache_cap.index_slot_size() - << ", indexer_layers: " << kv_cache_cap.num_indexer_layers() - << ", scale_slot_size: " << kv_cache_cap.scale_slot_size() - << ", linear_slot_size: " << kv_cache_cap.linear_slot_size() - << ", linear_blocks: " << kv_cache_cap.num_linear_state_blocks() - << ", state_slots: " - << (enable_state_cache ? kv_cache_cap.num_linear_state_blocks() : 0) - << ", gdn_state_bytes: " - << readable_size(kv_cache_cap.num_linear_attention_layers() * - kv_cache_cap.linear_slot_size()) - << ", kpool_state_bytes: " - << readable_size(kv_cache_cap.num_indexer_layers() * - kv_cache_cap.kpool_tail_slot_size()) - << ", max_linear_state_cache_slots: " - << options_.max_linear_state_cache_slots() - << ", reserved_state_bytes: " - << readable_size(kv_cache_cap.linear_cache_size_in_bytes()) - << ", n_layers: " << kv_cache_cap.n_layers() - << ", kv_cache_dtype: " << options_.kv_cache_dtype(); + log_capacity_and_validate_chunked_prefill(kv_cache_cap, enable_state_cache); const int32_t block_size = static_cast(kv_cache_cap.block_size()); const double host_blocks_factor = options_.host_blocks_factor(); @@ -416,31 +291,19 @@ bool VLMEngine::allocate_kv_cache( std::move(options), prefill_policy, std::move(transfer_coordinator), - dp_size_, + dp_size(), std::move(host_cache_validation_options), shared_vmm_layout); factory_result.shape.print_shapes(); KVCacheShape kv_cache_shape = std::move(factory_result.shape); kv_cache_manager_ = std::move(factory_result.manager); - // init kv cache for each worker in parallel - std::vector> futures; - futures.reserve(worker_clients_.size()); - for (auto& worker : worker_clients_) { - futures.emplace_back( - instance_role == InstanceRole::DEFAULT - ? worker->allocate_kv_cache_async(kv_cache_shape) - : worker->allocate_kv_cache_with_transfer_async(kv_cache_shape)); - } - // wait for all futures to complete - auto results = folly::collectAll(futures).get(); - for (const auto& result : results) { - if (!result.value()) { - return false; - } + if (!allocate_kv_cache_on_workers( + kv_cache_shape, + /*use_transfer_path=*/instance_role != InstanceRole::DEFAULT)) { + return false; } forward_input_factory_->reset_shared_kv_mapping_tracker(); - kv_cache_manager_->reserve_virtual_memory_padding_blocks(); return true; } @@ -450,9 +313,6 @@ ForwardOutput VLMEngine::step(BatchGroup& batch) { return {}; } Timer timer; - DCHECK(dp_size_ == batch.size()) - << "Split DP batch failed with dp_size as " << dp_size_ - << " and actual batch size as " << batch.size() << "."; std::vector forward_inputs; const bool is_graph_warmup = @@ -461,9 +321,9 @@ ForwardOutput VLMEngine::step(BatchGroup& batch) { eplb_controller_->on_step_dispatched(forward_inputs, is_graph_warmup); } - DCHECK(dp_size_ == forward_inputs.size()) + DCHECK(dp_size() == forward_inputs.size()) << "The processed forward inputs size " << forward_inputs.size() - << " is not equal to dp size " << dp_size_ << "."; + << " is not equal to dp size " << dp_size() << "."; auto results = dispatch_worker_step(worker_clients_, forward_inputs, dp_local_size_); @@ -474,9 +334,9 @@ ForwardOutput VLMEngine::step(BatchGroup& batch) { } std::vector outputs; - outputs.reserve(dp_size_); + outputs.reserve(dp_size()); size_t dp_rank = 0; - for (int32_t worker_rank = 0; worker_rank < worker_clients_num_; + for (size_t worker_rank = 0; worker_rank < worker_clients_num(); worker_rank += dp_local_size_) { const bool empty_shard = batch[dp_rank].size() == 0 && (!forward_inputs[dp_rank].token_ids.defined() || @@ -489,7 +349,6 @@ ForwardOutput VLMEngine::step(BatchGroup& batch) { CHECK(results[worker_rank].value().has_value()) << "Failed to execute model, result has no value"; auto& result = results[worker_rank].value(); - attach_embedding_output_metadata( args_, batch[dp_rank].get_sequences(), result.value()); @@ -508,10 +367,10 @@ ForwardOutput VLMEngine::step(BatchGroup& batch) { std::vector VLMEngine::collect_step_outputs( const BatchGroup& batch) { - CHECK_EQ(batch.size(), dp_size_); + CHECK_EQ(batch.size(), dp_size()); const bool is_graph_warmup = batch.contains_graph_warmup(); std::vector raw_forward_outputs; - raw_forward_outputs.reserve(dp_size_); + raw_forward_outputs.reserve(dp_size()); // NOTE: We only need to get the output from the driver worker, // cause the output on other workers is the same as that on driver. @@ -525,7 +384,7 @@ std::vector VLMEngine::collect_step_outputs( eplb_controller_->on_step_completed(last_step_results, is_graph_warmup); } - for (int32_t worker_rank = 0; worker_rank < worker_clients_num_; + for (size_t worker_rank = 0; worker_rank < worker_clients_num(); worker_rank += dp_local_size_) { auto& result = last_step_results[worker_rank / stride].value(); raw_forward_outputs.emplace_back(std::move(result.value())); @@ -538,56 +397,4 @@ std::vector VLMEngine::collect_step_outputs( return raw_forward_outputs; } -void VLMEngine::setup_workers(const runtime::Options& options) { - if (!distributed_worker_manager_) { - distributed_worker_manager_ = - std::make_shared(options); - } - worker_clients_ = distributed_worker_manager_->get_worker_clients(); -} - -bool VLMEngine::start_profile() { - std::lock_guard lock(profile_mutex_); - if (!profile_workers(/*is_start=*/true)) { - if (!profile_workers(/*is_start=*/false)) { - LOG(ERROR) << "Failed to stop partially started VLM profiling."; - } - return false; - } - return true; -} - -bool VLMEngine::stop_profile() { - std::lock_guard lock(profile_mutex_); - return profile_workers(/*is_start=*/false); -} - -bool VLMEngine::profile_workers(bool is_start) { - if (worker_clients_.empty()) { - LOG(ERROR) << "No worker clients available for profiling."; - return false; - } - std::vector> futures; - futures.reserve(worker_clients_.size()); - for (auto& worker : worker_clients_) { - futures.emplace_back(is_start ? worker->start_profile_async() - : worker->stop_profile_async()); - } - auto results = folly::collectAll(futures).get(); - bool success = true; - for (const auto& result : results) { - if (result.hasException()) { - LOG(ERROR) << "Profiling worker RPC failed: " - << result.exception().what(); - success = false; - continue; - } - if (!result.value()) { - LOG(ERROR) << "Profiling failed on a worker (start=" << is_start << ")."; - success = false; - } - } - return success; -} - } // namespace xllm diff --git a/xllm/core/distributed_runtime/vlm_engine.h b/xllm/core/distributed_runtime/vlm_engine.h index 8c5f2e998e..58456b8300 100644 --- a/xllm/core/distributed_runtime/vlm_engine.h +++ b/xllm/core/distributed_runtime/vlm_engine.h @@ -16,101 +16,47 @@ limitations under the License. #pragma once -#include - -#include #include -#include #include #include "common/macros.h" #include "core/distributed_runtime/distributed_worker_manager.h" +#include "core/distributed_runtime/engine.h" #include "core/framework/batch/forward_input_factory.h" #include "core/framework/eplb/eplb_controller.h" -#include "engine.h" +#include "core/runtime/forward_params.h" #include "framework/batch/batch_group.h" -#include "framework/tokenizer/tokenizer.h" -#include "framework/tokenizer/tokenizer_args.h" -#include "runtime/vlm_forward_params.h" namespace xllm { -class ModelLoader; - -class VmmKVLayout; class KVTransferCoordinatorBase; -class VLMEngine : public Engine { +class VLMEngine final : public Engine { public: - using ModelInitCallback = std::function< - bool(const ModelLoader&, int64_t, int32_t, int32_t, MasterStatus)>; - // create an engine with the given devices - VLMEngine(const runtime::Options& options, - std::shared_ptr - distributed_worker_manager = nullptr); + explicit VLMEngine(const runtime::Options& options); - virtual ~VLMEngine() = default; + ~VLMEngine() = default; ForwardOutput step(BatchGroup& batch); - const runtime::Options& options() const { return options_; } - - std::shared_ptr get_distributed_worker_manager() - const { - return distributed_worker_manager_; - } - - bool init(MasterStatus master_status) override; - bool init(MasterStatus master_status, - std::shared_ptr transfer_coordinator); bool init(MasterStatus master_status, const ModelInitCallback& prepare_model, std::shared_ptr transfer_coordinator); - bool start_profile() override; - bool stop_profile() override; - std::vector collect_step_outputs(const BatchGroup& batch); private: - template - friend class SpeculativeEngineBase; bool init_model(MasterStatus master_status, - const ModelInitCallback& prepare_model = {}); - KVCacheCapacity estimate_kv_cache_capacity( - bool initialize_virtual_memory = true); - bool allocate_kv_cache(const KVCacheCapacity& kv_cache_cap, - const VmmKVLayout* shared_vmm_layout = nullptr, - std::shared_ptr - transfer_coordinator = nullptr); - void setup_workers(const runtime::Options& options); - void process_group_test(); - bool profile_workers(bool is_start); - - private: - // options - runtime::Options options_; - - // dtype - torch::ScalarType dtype_; - - // a list of workers, with each worker handling a partial of model - std::vector> worker_clients_; - - // common frequently used args - uint32_t dp_size_; - uint32_t worker_clients_num_; - uint32_t dp_local_size_; - uint32_t dp_local_tp_size_; - - std::shared_ptr distributed_worker_manager_ = - nullptr; + const ModelInitCallback& prepare_model); + bool allocate_kv_cache( + const KVCacheCapacity& kv_cache_cap, + const VmmKVLayout* shared_vmm_layout, + std::shared_ptr transfer_coordinator); std::unique_ptr> forward_input_factory_; std::unique_ptr eplb_controller_; - std::mutex profile_mutex_; - int64_t initial_weight_reservation_bytes_ = 0; + uint32_t dp_local_size_; }; } // namespace xllm diff --git a/xllm/core/distributed_runtime/vlm_master.cpp b/xllm/core/distributed_runtime/vlm_master.cpp index 4a0ceb7aa8..bb82836c64 100644 --- a/xllm/core/distributed_runtime/vlm_master.cpp +++ b/xllm/core/distributed_runtime/vlm_master.cpp @@ -31,7 +31,7 @@ limitations under the License. #include "common/metrics.h" #include "core/common/message.h" #include "core/disaggregation/pd_service_impl.h" -#include "core/distributed_runtime/engine_dispatch.h" +#include "core/distributed_runtime/distributed_worker_manager.h" #include "core/distributed_runtime/kv_transfer_coordinator.h" #include "core/distributed_runtime/model_residency_coordinator.h" #include "core/distributed_runtime/runtime_options_creator.h" @@ -39,7 +39,6 @@ limitations under the License. #include "core/framework/config/kv_cache_store_config.h" #include "core/framework/config/load_config.h" #include "core/framework/config/model_config.h" -#include "core/framework/config/parallel_config.h" #include "core/framework/config/parallel_config_validation.h" #include "core/framework/config/scheduler_config.h" #include "core/framework/config/service_config.h" @@ -53,7 +52,6 @@ limitations under the License. #if defined(USE_NPU) #include "models/model_registry.h" #endif -#include "core/common/types.h" #include "distributed_runtime/xservice_client.h" #include "runtime/options.h" #include "scheduler/scheduler_factory.h" @@ -147,15 +145,11 @@ VLMMaster::VLMMaster(const Options& options) CHECK(!options_.enable_disagg_pd() || options_.kv_cache_transfer_mode() != "PULL") << "VLM disaggregated PD does not support KV cache PULL."; + const bool loads_draft_model = SpeculativeConfig::loads_draft_model(options_); options_.validate(model_type); validate_layerwise_split_size_startup_config(options_, model_type); - const bool use_speculative_engine = - options_.num_speculative_tokens() > 0 && - !SpeculativeConfig::is_suffix_algorithm(options_.speculative_algorithm()); const std::optional cp_error = validate_context_parallel_config( - options_, - use_speculative_engine ? EngineType::VLMSSM : EngineType::VLM, - model_type); + options_, /*engine_type=*/EngineType::VLM, model_type); CHECK(!cp_error.has_value()) << cp_error.value(); const std::optional speculative_error = ModelConfig::validate_python_speculative_decode( @@ -164,7 +158,7 @@ VLMMaster::VLMMaster(const Options& options) options_.num_speculative_tokens(), options_.speculative_algorithm()); CHECK(!speculative_error.has_value()) << speculative_error.value(); - CHECK(options_.host_blocks_factor() <= 1.0 || !use_speculative_engine || + CHECK(options_.host_blocks_factor() <= 1.0 || !loads_draft_model || SpeculativeConfig::supports_host_kv_cache( options_.speculative_algorithm())) << "Host KV cache requires ordinary generation or model-based " @@ -174,37 +168,16 @@ VLMMaster::VLMMaster(const Options& options) engine_options.max_encoder_cache_size(options_.max_encoder_cache_size()) .max_processor_cache_items(options_.max_processor_cache_items()); - if (use_speculative_engine) { + if (loads_draft_model) { CHECK(!options_.enable_disagg_pd()) << "VLM speculative decoding does not support disaggregated PD"; CHECK(!options_.enable_service_routing()) << "VLM speculative decoding does not support service routing"; - engine_options.draft_model_path(options_.draft_model_path()) - .num_speculative_tokens(options_.num_speculative_tokens()) - .speculative_algorithm(options_.speculative_algorithm()) - .enable_probabilistic_draft(options_.enable_probabilistic_draft()) - .enable_mtp_draft_body_tp1(options_.enable_mtp_draft_body_tp1()) - .speculative_suffix_cache_max_depth( - options_.speculative_suffix_cache_max_depth()) - .speculative_suffix_max_cached_requests( - options_.speculative_suffix_max_cached_requests()); - speculative_engine_ = - std::make_unique>(engine_options); - draft_model_residency_coordinator_ = - std::make_unique( - ModelResidencyCoordinator::Options{ - .enabled = KVCacheConfig::get_instance().enable_vmm_kvcache() || - LoadConfig::get_instance().enable_vmm_weights(), - .model_id = engine_options.model_id()}, - speculative_engine_->get_distributed_worker_manager()); - } else { - vlm_engine_ = std::make_unique(engine_options); + SpeculativeConfig::apply_speculative_options(options_, engine_options); } - distributed_worker_manager_ = dispatch_engine( - [](auto* engine) { return engine->get_distributed_worker_manager(); }, - vlm_engine_.get(), - speculative_engine_.get()); - if (vlm_engine_ != nullptr) { + vlm_engine_ = std::make_unique(engine_options); + distributed_worker_manager_ = vlm_engine_->get_distributed_worker_manager(); + if (!loads_draft_model) { model_residency_coordinator_ = std::make_shared( ModelResidencyCoordinator::Options{ .enabled = KVCacheConfig::get_instance().enable_vmm_kvcache() || @@ -223,129 +196,41 @@ VLMMaster::VLMMaster(const Options& options) .prefetch_batch_size = options_.prefetch_batch_size()}, distributed_worker_manager_); - auto finish_engine_initialization = [this](auto* engine) { - model_args_ = engine->model_args(); - if (options_.enable_service_routing()) { - xservice_client_ = XServiceClient::get_instance(); - CHECK(xservice_client_->init(options_.etcd_addr().value_or(""), - options_.instance_name().value_or(""), - options_.etcd_namespace().value_or(""))) - << "XServiceClient init fail!"; - } - }; - if (use_speculative_engine) { - const LLMEngine::ModelInitCallback prepare_draft = - [this](const ModelLoader& model_loader, - int64_t num_layers, - int32_t dp_size, - int32_t tp_size, - MasterStatus master_status) { - return draft_model_residency_coordinator_->initialize_model( - model_loader, num_layers, dp_size, tp_size, master_status); - }; - CHECK(speculative_engine_->init( - options_.master_status(), prepare_draft, kv_transfer_coordinator_)); - finish_engine_initialization(speculative_engine_.get()); - } else { - const VLMEngine::ModelInitCallback prepare_model = - [this](const ModelLoader& loader, - int64_t num_layers, - int32_t dp_size, - int32_t tp_size, - MasterStatus status) { - return model_residency_coordinator_->initialize_model( - loader, num_layers, dp_size, tp_size, status); - }; - CHECK(vlm_engine_->init( - master_status_, prepare_model, kv_transfer_coordinator_)); + const ModelInitCallback prepare_model = + model_residency_coordinator_ + ? make_model_init_callback(model_residency_coordinator_.get()) + : ModelInitCallback{}; + CHECK(vlm_engine_->init( + master_status_, prepare_model, kv_transfer_coordinator_)); + if (model_residency_coordinator_) { CHECK(model_residency_coordinator_->finish_initialization(master_status_)); - finish_engine_initialization(vlm_engine_.get()); } - - SchedulerOptions scheduler_options; - scheduler_options.model_id(engine_options.model_id()) - .model_impl(engine_options.model_impl()) - .enable_graph(options_.enable_graph()) - .disable_graph_warmup(options_.disable_graph_warmup()) - .enable_fia_decode(engine_options.enable_fia_decode()) - .enable_prefix_cache(options_.enable_prefix_cache()) - .enable_in_batch_prefix_cache( - KVCacheConfig::get_instance().enable_in_batch_prefix_cache()) - .max_tokens_per_batch(options_.max_tokens_per_batch()) - .max_seqs_per_batch(options_.max_seqs_per_batch()) - .max_concurrent_requests(options_.max_concurrent_requests()) - .num_response_handling_threads( - ServiceConfig::get_instance().num_response_handling_threads()) - .request_queue_size(options_.request_queue_size()) - .max_tokens_per_chunk_for_prefill( - options_.max_tokens_per_chunk_for_prefill()) - .num_speculative_tokens(options_.num_speculative_tokens()) - .speculative_algorithm(options_.speculative_algorithm()) - .decode_graph_warmup_config(options_.decode_graph_warmup_config()) - .nnodes(options_.nnodes()) - .dp_size(options_.dp_size()) - .cp_size(options_.cp_size()) - .kv_split_size(ParallelConfig::get_instance().kv_split_size_effective()) - .enable_mix_batch(scheduler_config.enable_mix_batch()) - .prefill_scheduling_memory_usage_threshold( - scheduler_config.prefill_scheduling_memory_usage_threshold()) - .chunked_match_frequency(scheduler_config.chunked_match_frequency()) - .aggressive_coeff(scheduler_config.aggressive_coeff()) - .enable_starve_prevent(scheduler_config.enable_starve_prevent()) - .starve_threshold(scheduler_config.starve_threshold()) - .enable_disagg_pd(options_.enable_disagg_pd()) - .enable_chunked_prefill(options_.enable_chunked_prefill()) - .enable_dp_fair_token_budget(options_.enable_dp_fair_token_budget()) - .instance_name(options_.instance_name()) - .instance_role(options_.instance_role()) - .kv_cache_transfer_mode(options_.kv_cache_transfer_mode()) - .enable_service_routing(options_.enable_service_routing()) - .disable_log_stats(options_.disable_log_stats()) - .priority_strategy(options_.priority_strategy()) - .enable_profile_step_time(options_.enable_profile_step_time()) - .enable_profile_token_budget(options_.enable_profile_token_budget()) - .enable_latency_aware_schedule(options_.enable_latency_aware_schedule()) - .enable_control_h2d_block_num( - KVCacheStoreConfig::get_instance().enable_control_h2d_block_num()) - .profile_max_prompt_length(options_.profile_max_prompt_length()) - .enable_profile_kv_blocks(options_.enable_profile_kv_blocks()) - .disable_ttft_profiling(options_.disable_ttft_profiling()) - .max_global_ttft_ms(options_.max_global_ttft_ms()) - .max_global_tpot_ms(options_.max_global_tpot_ms()) - .enable_schedule_overlap(options_.enable_schedule_overlap()) - .server_idx(options_.server_idx()); - dispatch_engine( - [&](auto* engine) { - scheduler_ = create_continuous_scheduler( - engine, - scheduler_options, - distributed_worker_manager_, - model_residency_coordinator_, - kv_transfer_coordinator_, - make_pd_service_options(options_, model_args_)); - }, - vlm_engine_.get(), - speculative_engine_.get()); - - if (options_.enable_service_routing()) { - auto& instance_info = scheduler_->get_instance_info(); - XServiceClient::get_instance()->register_instance(instance_info); + model_args_ = vlm_engine_->model_args(); + xservice_client_ = init_service_routing(); + + scheduler_ = create_continuous_scheduler( + vlm_engine_->kv_cache_manager(), + &vlm_engine_->model_args(), + vlm_engine_->tokenizer(), + make_scheduler_callbacks(vlm_engine_.get()), + make_scheduler_options(), + model_residency_coordinator_, + distributed_worker_manager_, + kv_transfer_coordinator_, + make_pd_service_options(options_, model_args_)); + + if (xservice_client_ != nullptr) { + xservice_client_->register_instance(scheduler_->get_instance_info()); } - dispatch_engine( - [this](auto* engine) { - chat_template_ = ChatTemplateFactory::create(engine->tokenizer_args(), - model_args_.model_type()); - tokenizer_ = engine->tokenizer()->clone(); - processor_ = - create_multimodal_processor(options_.model_path(), - model_args_, - tokenizer_, - options_.max_processor_cache_items(), - engine->tokenizer_args()); - }, - vlm_engine_.get(), - speculative_engine_.get()); + chat_template_ = ChatTemplateFactory::create(vlm_engine_->tokenizer_args(), + model_args_.model_type()); + tokenizer_ = vlm_engine_->tokenizer()->clone(); + processor_ = create_multimodal_processor(options_.model_path(), + model_args_, + tokenizer_, + options_.max_processor_cache_items(), + vlm_engine_->tokenizer_args()); request_factory_ = std::make_unique( processor_.get(), @@ -765,15 +650,6 @@ void VLMMaster::count_chat_tokens( }); } -bool VLMMaster::handle_rpc_response(const RequestOutput& output) { - if (xservice_client_ == nullptr) { - return false; - } - auto accepted = xservice_client_->generations({output}); - CHECK_EQ(accepted.size(), 1); - return accepted.front(); -} - std::vector VLMMaster::handle_rpc_responses( const std::vector& outputs) { if (xservice_client_ == nullptr) { @@ -783,7 +659,7 @@ std::vector VLMMaster::handle_rpc_responses( } bool VLMMaster::sleep() { - if (vlm_engine_ == nullptr) { + if (!model_residency_coordinator_) { LOG(ERROR) << "Sleep is not supported for speculative engines."; return false; } @@ -796,7 +672,7 @@ bool VLMMaster::requires_wakeup() const { } bool VLMMaster::wakeup(const WakeupOptions& options) { - if (vlm_engine_ == nullptr) { + if (!model_residency_coordinator_) { LOG(ERROR) << "Wakeup is not supported for speculative engines."; return false; } @@ -905,16 +781,8 @@ void VLMMaster::generate() { running_.store(false, std::memory_order_relaxed); } -bool VLMMaster::start_profile() { - return dispatch_engine([](auto* engine) { return engine->start_profile(); }, - vlm_engine_.get(), - speculative_engine_.get()); -} +bool VLMMaster::start_profile() { return vlm_engine_->start_profile(); } -bool VLMMaster::stop_profile() { - return dispatch_engine([](auto* engine) { return engine->stop_profile(); }, - vlm_engine_.get(), - speculative_engine_.get()); -} +bool VLMMaster::stop_profile() { return vlm_engine_->stop_profile(); } } // namespace xllm diff --git a/xllm/core/distributed_runtime/vlm_master.h b/xllm/core/distributed_runtime/vlm_master.h index 32b11eed97..d79718444f 100644 --- a/xllm/core/distributed_runtime/vlm_master.h +++ b/xllm/core/distributed_runtime/vlm_master.h @@ -28,15 +28,15 @@ limitations under the License. #include "common/options.h" #include "common/types.h" +#include "core/distributed_runtime/vlm_engine.h" #include "core/framework/multimodal/mm_input.h" +#include "core/scheduler/scheduler.h" #include "framework/chat_template/chat_template.h" #include "framework/request/request_output.h" #include "framework/request/request_params.h" #include "framework/request/vlm_request_factory.h" #include "framework/tokenizer/tokenizer.h" #include "master.h" -#include "scheduler/continuous_scheduler.h" -#include "speculative_engine.h" #include "xllm/processors/multimodal_processor.h" namespace xllm { @@ -112,7 +112,6 @@ class VLMMaster : public Master { RequestParams params, std::function callback); - bool handle_rpc_response(const RequestOutput& output); std::vector handle_rpc_responses( const std::vector& outputs); @@ -130,12 +129,12 @@ class VLMMaster : public Master { // start the handling loop void run() override; + bool start_profile() override; + bool stop_profile() override; + // generate will run all requests, this is an blocking call void generate(); - bool start_profile(); - bool stop_profile(); - MasterStatus get_master_status() const { return master_status_; } bool is_sleeping() const { return master_status_ != MasterStatus::WAKEUP; } void set_master_status(MasterStatus status) { master_status_ = status; } @@ -147,8 +146,6 @@ class VLMMaster : public Master { int get_image_limit() { return options_.limit_image_per_prompt(); } - const std::string& model_type() const { return model_args_.model_type(); } - private: struct CompletionBatchInputs { std::vector prompts; @@ -175,13 +172,7 @@ class VLMMaster : public Master { std::shared_ptr kv_transfer_coordinator_; XServiceClient* xservice_client_ = nullptr; - // The LLM draft prepares VirtualMemory pages before loading worker weights. - std::unique_ptr draft_model_residency_coordinator_; - - // Exactly one of these owners is populated for VLM and VLM speculative - // execution respectively. std::unique_ptr vlm_engine_; - std::unique_ptr> speculative_engine_; // Scheduler must be destroyed before the engine it references. std::unique_ptr scheduler_; diff --git a/xllm/core/framework/config/parallel_config_validation.cpp b/xllm/core/framework/config/parallel_config_validation.cpp index 5f6f6e2282..5ebe3978a4 100644 --- a/xllm/core/framework/config/parallel_config_validation.cpp +++ b/xllm/core/framework/config/parallel_config_validation.cpp @@ -184,7 +184,7 @@ std::optional validate_context_parallel_config( const int64_t parallel_width = static_cast(options.dp_size()) * options.cp_size(); if (Platform::is_mlu()) { - if (engine_type != EngineType::LLM && engine_type != EngineType::SSM) { + if (engine_type != EngineType::LLM) { return "MLU CP supports only LLM text generation"; } if (options.task_type() != "generate") { @@ -220,14 +220,14 @@ std::optional validate_context_parallel_config( } if (Platform::is_npu()) { - if (engine_type != EngineType::LLM && engine_type != EngineType::SSM) { + if (engine_type != EngineType::LLM) { return "Model-side CP supports only LLM text generation"; } if (options.task_type() != "generate") { return "Model-side CP supports only the generate task"; } const bool is_dsv4_model = is_deepseek_v4_family(model_type); - if (engine_type == EngineType::SSM && + if (SpeculativeConfig::uses_speculative_pipeline(options) && SpeculativeConfig::requires_aux_hidden_capture( options.speculative_algorithm()) && (!is_dsv4_model || ModelConfig::is_python_model_impl( @@ -295,7 +295,7 @@ std::optional validate_context_parallel_config( "kv_split_size=1"; } if (is_glm5_next_target_model_type(model_type)) { - if (engine_type == EngineType::SSM) { + if (SpeculativeConfig::uses_speculative_pipeline(options)) { return "Python GLM-5 Next CP does not support target-side " "speculative " "verification; run speculation on a cp_size=1 Decode instance"; diff --git a/xllm/core/framework/config/speculative_config.cpp b/xllm/core/framework/config/speculative_config.cpp index 427b5aa85b..2f259443fb 100644 --- a/xllm/core/framework/config/speculative_config.cpp +++ b/xllm/core/framework/config/speculative_config.cpp @@ -22,7 +22,9 @@ limitations under the License. #include #include "core/common/global_flags.h" +#include "core/common/options.h" #include "core/framework/config/config_utils.h" +#include "core/runtime/options.h" DEFINE_string(draft_model, "", "draft hf model path to the model file."); @@ -93,6 +95,43 @@ bool SpeculativeConfig::supports_host_kv_cache(std::string_view algorithm) { return is_eagle_family(algorithm) || is_block_diffusion_algorithm(algorithm); } +template +bool SpeculativeConfig::loads_draft_model(const OptionsT& options) { + const auto& draft_path = options.draft_model_path(); + return draft_path && !draft_path->empty() && + !is_suffix_algorithm(options.speculative_algorithm()); +} + +template +bool SpeculativeConfig::uses_speculative_pipeline(const OptionsT& options) { + const auto& draft_path = options.draft_model_path(); + return (draft_path && !draft_path->empty()) || + (is_suffix_algorithm(options.speculative_algorithm()) && + options.num_speculative_tokens() > 0); +} + +template +void SpeculativeConfig::apply_speculative_options(const FromOptions& from, + ToOptions& to) { + to.draft_model_path(from.draft_model_path()) + .num_speculative_tokens(from.num_speculative_tokens()) + .speculative_algorithm(from.speculative_algorithm()) + .enable_probabilistic_draft(from.enable_probabilistic_draft()) + .enable_mtp_draft_body_tp1(from.enable_mtp_draft_body_tp1()) + .speculative_suffix_cache_max_depth( + from.speculative_suffix_cache_max_depth()) + .speculative_suffix_max_cached_requests( + from.speculative_suffix_max_cached_requests()); +} + +template bool SpeculativeConfig::loads_draft_model(const Options&); +template bool SpeculativeConfig::loads_draft_model(const runtime::Options&); +template bool SpeculativeConfig::uses_speculative_pipeline(const Options&); +template bool SpeculativeConfig::uses_speculative_pipeline( + const runtime::Options&); +template void SpeculativeConfig::apply_speculative_options(const Options&, + runtime::Options&); + void SpeculativeConfig::from_flags() { XLLM_CONFIG_ASSIGN_FROM_FLAG(draft_model); XLLM_CONFIG_ASSIGN_FROM_FLAG(num_speculative_tokens); @@ -175,6 +214,10 @@ void SpeculativeConfig::validate() const { << " does not support enable_probabilistic_draft. Supported: MTP, " "DSpark, DFlash2, Eagle3."; } + if (!draft_model().empty()) { + CHECK_GT(num_speculative_tokens(), 0) + << "speculative tokens should not be zero"; + } } } // namespace xllm diff --git a/xllm/core/framework/config/speculative_config.h b/xllm/core/framework/config/speculative_config.h index 4b9bdd8362..84aaba0263 100644 --- a/xllm/core/framework/config/speculative_config.h +++ b/xllm/core/framework/config/speculative_config.h @@ -59,6 +59,15 @@ class SpeculativeConfig final { return boost::iequals(algorithm, "Suffix"); } + template + static bool loads_draft_model(const OptionsT& options); + + template + static bool uses_speculative_pipeline(const OptionsT& options); + + template + static void apply_speculative_options(const FromOptions& from, ToOptions& to); + static bool is_mtp_algorithm(std::string_view algorithm) { return boost::iequals(algorithm, "MTP"); } diff --git a/xllm/core/framework/speculative/draft_config.cpp b/xllm/core/framework/speculative/draft_config.cpp index a8863b3e28..a891a72b51 100644 --- a/xllm/core/framework/speculative/draft_config.cpp +++ b/xllm/core/framework/speculative/draft_config.cpp @@ -25,6 +25,7 @@ limitations under the License. #include "core/framework/config/model_config.h" #include "core/framework/config/speculative_config.h" +#include "core/framework/model/aux_hidden_capture.h" #include "core/framework/model/model_args.h" #include "core/framework/model/model_type.h" #if defined(USE_CUDA) @@ -252,4 +253,14 @@ std::vector read_capture_layer_ids( : std::vector{}; } +std::vector read_eagle3_capture_layer_ids( + const std::string& model_weights_path, + int32_t num_layers) { + auto layers = read_capture_layer_ids(model_weights_path); + if (layers.empty()) { + return AuxHiddenCapture::legacy_default_capture_layer_ids(num_layers); + } + return layers; +} + } // namespace xllm diff --git a/xllm/core/framework/speculative/draft_config.h b/xllm/core/framework/speculative/draft_config.h index 2c8d00b86b..7a62d62288 100644 --- a/xllm/core/framework/speculative/draft_config.h +++ b/xllm/core/framework/speculative/draft_config.h @@ -35,4 +35,8 @@ void apply_block_diffusion_target_config(ModelArgs& args, std::vector read_capture_layer_ids( const std::string& model_weights_path); +std::vector read_eagle3_capture_layer_ids( + const std::string& model_weights_path, + int32_t num_layers); + } // namespace xllm diff --git a/xllm/core/kv_cache/layout/kv_cache_estimation.cpp b/xllm/core/kv_cache/layout/kv_cache_estimation.cpp index 73c62bde76..f69124f009 100644 --- a/xllm/core/kv_cache/layout/kv_cache_estimation.cpp +++ b/xllm/core/kv_cache/layout/kv_cache_estimation.cpp @@ -1152,4 +1152,46 @@ KVCacheCapacity estimate_kv_cache_capacity( return kv_cache_cap; } +KVCacheCapacity combine_target_and_draft_kv_cache_capacity( + KVCacheCapacity target_cap, + const KVCacheCapacity& draft_cap, + const ModelArgs& target_args, + const ModelArgs& draft_args, + int32_t layerwise_split_size) { + if (target_cap.kpool_tail_slot_size() > 0 && + draft_cap.kpool_tail_slot_size() > 0) { + return plan_shared_kpool(std::move(target_cap), draft_cap, draft_args) + .target; + } + + CHECK_EQ(target_cap.block_size(), draft_cap.block_size()) + << "target and draft kv cache block size must be the same"; + const int64_t cache_size_in_bytes = std::min(target_cap.cache_size_in_bytes(), + draft_cap.cache_size_in_bytes()); + const int64_t full_cache_bytes = cache_size_in_bytes - + target_cap.linear_cache_size_in_bytes() - + draft_cap.linear_cache_size_in_bytes(); + CHECK_GT(full_cache_bytes, 0) + << "no memory left for speculative full-attention kv cache after " + "reserving target and draft state caches"; + + // The draft's block can be larger than the target's, such as full attention + // against an MLA target. + const int64_t draft_block_bytes = + standard_full_cache_block_size_in_bytes(draft_cap); + const int64_t n_blocks = + layerwise_split_size > 1 + ? estimate_layerwise_split_block_count(target_args, + layerwise_split_size, + target_cap, + full_cache_bytes, + draft_block_bytes) + : full_cache_bytes / + (standard_full_cache_block_size_in_bytes(target_cap) + + draft_block_bytes); + CHECK_GT(n_blocks, 0) << "no memory for kv cache"; + target_cap.n_blocks(n_blocks).cache_size_in_bytes(cache_size_in_bytes); + return target_cap; +} + } // namespace xllm diff --git a/xllm/core/kv_cache/layout/kv_cache_estimation.h b/xllm/core/kv_cache/layout/kv_cache_estimation.h index 1acc3c68ae..a749a186e0 100644 --- a/xllm/core/kv_cache/layout/kv_cache_estimation.h +++ b/xllm/core/kv_cache/layout/kv_cache_estimation.h @@ -165,4 +165,11 @@ SharedStaticKVCachePlan plan_shared_static_kv_cache( int64_t world_size, torch::ScalarType dtype); +KVCacheCapacity combine_target_and_draft_kv_cache_capacity( + KVCacheCapacity target_cap, + const KVCacheCapacity& draft_cap, + const ModelArgs& target_args, + const ModelArgs& draft_args, + int32_t layerwise_split_size); + } // namespace xllm diff --git a/xllm/core/runtime/eagle3_worker_impl.cpp b/xllm/core/runtime/eagle3_worker_impl.cpp index 088816fbf6..7075eea642 100644 --- a/xllm/core/runtime/eagle3_worker_impl.cpp +++ b/xllm/core/runtime/eagle3_worker_impl.cpp @@ -62,13 +62,9 @@ void Eagle3WorkerImpl::apply_target_model_overrides( if (!args.layers_to_capture().empty()) { return; } - auto layers = - read_capture_layer_ids(this->options_.draft_model_path().value()); - if (layers.empty()) { - layers = AuxHiddenCapture::legacy_default_capture_layer_ids( - static_cast(args.n_layers())); - } - args.layers_to_capture(std::move(layers)); + args.layers_to_capture( + read_eagle3_capture_layer_ids(this->options_.draft_model_path().value(), + static_cast(args.n_layers()))); } #endif diff --git a/xllm/core/scheduler/CMakeLists.txt b/xllm/core/scheduler/CMakeLists.txt index b396b5011c..8c2c35ef10 100644 --- a/xllm/core/scheduler/CMakeLists.txt +++ b/xllm/core/scheduler/CMakeLists.txt @@ -9,6 +9,7 @@ cc_library( HDRS scheduler_policy.h continuous_scheduler.h + scheduler_callbacks.h request_output_dispatcher.h scheduler.h dit_scheduler.h diff --git a/xllm/core/scheduler/continuous_scheduler.cpp b/xllm/core/scheduler/continuous_scheduler.cpp index 399960df78..3ec852598f 100644 --- a/xllm/core/scheduler/continuous_scheduler.cpp +++ b/xllm/core/scheduler/continuous_scheduler.cpp @@ -31,7 +31,6 @@ limitations under the License. #include "core/common/metrics.h" #include "core/common/types.h" #include "core/distributed_runtime/distributed_worker_manager.h" -#include "core/distributed_runtime/engine.h" #include "core/distributed_runtime/model_residency_coordinator.h" #include "core/framework/batch/batch_factory.h" #include "core/framework/config/speculative_config.h" @@ -39,6 +38,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/scheduler/profile/profile_manager.h" #include "core/scheduler/request_priority_queue.h" #include "core/scheduler/scheduler_policy.h" #include "core/util/timer.h" @@ -55,11 +55,12 @@ constexpr char kDecodeRestoreTimeoutMessage[] = } // namespace -ContinuousSchedulerBase::ContinuousSchedulerBase( - Engine* engine, +ContinuousScheduler::ContinuousScheduler( + KVCacheManager* kv_cache_manager, + const ModelArgs* model_args, + const Tokenizer* tokenizer, + SchedulerCallbacks callbacks, const Options& options, - StepCallback step_callback, - ResultCallback result_callback, std::shared_ptr model_residency_coordinator, std::shared_ptr distributed_worker_manager) : options_(options), @@ -69,18 +70,17 @@ ContinuousSchedulerBase::ContinuousSchedulerBase( options.enable_dp_fair_token_budget()), batch_mode_(create_batch_mode(options)), batch_factory_(options.dp_size()), - resource_engine_(engine), + model_args_(model_args), + tokenizer_(tokenizer), + callbacks_(std::move(callbacks)), distributed_worker_manager_(std::move(distributed_worker_manager)), model_residency_coordinator_(std::move(model_residency_coordinator)), - step_callback_(std::move(step_callback)), - result_callback_(std::move(result_callback)), notifier_(std::make_shared()), request_queue_(options.request_queue_size()) { - CHECK(resource_engine_ != nullptr); - CHECK(step_callback_); - CHECK(result_callback_); + CHECK(callbacks_.step_); + CHECK(callbacks_.update_last_step_result_); - kv_cache_manager_ = resource_engine_->kv_cache_manager(); + kv_cache_manager_ = kv_cache_manager; CHECK(kv_cache_manager_ != nullptr); if (kv_cache_manager_->has_storage_prefetch()) { kv_cache_prefetcher_ = std::make_unique( @@ -124,19 +124,15 @@ ContinuousSchedulerBase::ContinuousSchedulerBase( .max_global_ttft_ms(options.max_global_ttft_ms()) .instance_role(options.instance_role().value_or(InstanceRole::DEFAULT)) .enable_profile_token_budget(options.enable_profile_token_budget()); - profile_manager_ = std::unique_ptr( - new ProfileManager(resource_engine_, - profile_manager_options, - step_callback_, - result_callback_, - distributed_worker_manager_)); + profile_manager_ = std::make_unique( + kv_cache_manager_, model_args_, profile_manager_options, callbacks_); // Construct the scheduling policy from the resolved BatchMode. policy_ = create_scheduler_policy(batch_mode_, options_); cancel_request_queue_ = std::make_shared(); output_dispatcher_ = std::make_unique( - resource_engine_->tokenizer(), + tokenizer_, options_.num_response_handling_threads(), options_.enable_service_routing(), options_.disable_log_stats(), @@ -188,7 +184,7 @@ ContinuousSchedulerBase::ContinuousSchedulerBase( } } -void ContinuousSchedulerBase::populate_heartbeat_request( +void ContinuousScheduler::populate_heartbeat_request( xllm_service::proto::HeartbeatRequest& request, bool include_virtual_memory_info) { request.mutable_load_metrics()->set_gpu_cache_usage_perc( @@ -232,7 +228,7 @@ void ContinuousSchedulerBase::populate_heartbeat_request( } } -ContinuousSchedulerBase::~ContinuousSchedulerBase() { +ContinuousScheduler::~ContinuousScheduler() { notifier_->request_stop(); if (xservice_client_ != nullptr) { @@ -255,12 +251,11 @@ ContinuousSchedulerBase::~ContinuousSchedulerBase() { running_requests_.clear(); } -bool ContinuousSchedulerBase::add_request(std::shared_ptr& request) { +bool ContinuousScheduler::add_request(std::shared_ptr& request) { CHECK(request != nullptr); CHECK(!request->sequences().empty()); - if (request->best_of() > 1 && - ::xllm::has_linear_attention_layers(resource_engine_->model_args())) { + if (request->best_of() > 1 && has_linear_attention_layers(*model_args_)) { output_dispatcher_->process_failed_request( request, {StatusCode::INVALID_ARGUMENT, @@ -287,11 +282,12 @@ bool ContinuousSchedulerBase::add_request(std::shared_ptr& request) { return true; } -size_t ContinuousSchedulerBase::num_queued_requests() const { - return static_cast(std::max(request_queue_.size(), 0)); +size_t ContinuousScheduler::num_queued_requests() const { + const auto queued = request_queue_.size(); + return queued > 0 ? static_cast(queued) : 0; } -bool ContinuousSchedulerBase::enqueue_ready_request( +bool ContinuousScheduler::enqueue_ready_request( std::shared_ptr request) { const bool queued = request_queue_.write(std::move(request)); if (queued) { @@ -300,7 +296,7 @@ bool ContinuousSchedulerBase::enqueue_ready_request( return queued; } -void ContinuousSchedulerBase::create_queues(const Options& options) { +void ContinuousScheduler::create_queues(const Options& options) { if (options.priority_strategy() == "multi_slo_and_prio" || options.priority_strategy() == "fcfs") { prefill_queue_ = std::make_unique(); @@ -315,7 +311,7 @@ void ContinuousSchedulerBase::create_queues(const Options& options) { } } -void ContinuousSchedulerBase::clear_mtp_bootstrap(Request* request) { +void ContinuousScheduler::clear_mtp_bootstrap(Request* request) { if (!options_.enable_disagg_pd() || options_.num_speculative_tokens() <= 0 || request == nullptr || request->sequences().empty()) { return; @@ -327,7 +323,7 @@ void ContinuousSchedulerBase::clear_mtp_bootstrap(Request* request) { sequence->clear_mtp_bootstrap_embedding(); } -void ContinuousSchedulerBase::drain_decode_restore_waiting( +void ContinuousScheduler::drain_decode_restore_waiting( std::vector>& finished) { const absl::Time now = absl::Now(); for (auto it = decode_restore_waiting_.begin(); @@ -356,7 +352,7 @@ void ContinuousSchedulerBase::drain_decode_restore_waiting( } } -BatchGroup ContinuousSchedulerBase::prepare_batch() { +BatchGroup ContinuousScheduler::prepare_batch() { Timer timer; drain_request_releases(); if (kv_cache_prefetcher_ != nullptr) { @@ -421,7 +417,7 @@ BatchGroup ContinuousSchedulerBase::prepare_batch() { return batches; } -SchedulerState ContinuousSchedulerBase::make_state() { +SchedulerState ContinuousScheduler::make_state() { return SchedulerState{ .prefill_queue = *prefill_queue_, .chunk_queue = *chunk_queue_, @@ -434,7 +430,7 @@ SchedulerState ContinuousSchedulerBase::make_state() { .kv_cache_manager = kv_cache_manager_, .profile_manager = profile_manager_.get(), .output_dispatcher = output_dispatcher_.get(), - .model_args = resource_engine_->model_args(), + .model_args = *model_args_, .last_step_prefill = last_step_prefill_, .options = options_, .min_speculative_tokens_required = min_speculative_tokens_required_, @@ -448,7 +444,7 @@ SchedulerState ContinuousSchedulerBase::make_state() { }; } -BatchGroup ContinuousSchedulerBase::schedule_request( +BatchGroup ContinuousScheduler::schedule_request( const absl::Duration& timeout) { const auto deadline = absl::Now() + timeout; BatchGroup batch; @@ -489,7 +485,7 @@ BatchGroup ContinuousSchedulerBase::schedule_request( return batch; } -void ContinuousSchedulerBase::apply_cancel_requests() { +void ContinuousScheduler::apply_cancel_requests() { std::vector> requests = cancel_request_queue_->take_all(); for (const std::shared_ptr& request : requests) { @@ -499,7 +495,7 @@ void ContinuousSchedulerBase::apply_cancel_requests() { // step the scheduler forward by one step // may get blocked if there are no requests to process -void ContinuousSchedulerBase::step(const absl::Duration& timeout) { +void ContinuousScheduler::step(const absl::Duration& timeout) { if (!options_.enable_schedule_overlap()) { // get a new batch of requests BatchGroup batch = schedule_request(timeout); @@ -511,7 +507,7 @@ void ContinuousSchedulerBase::step(const absl::Duration& timeout) { return; } - step_callback_(batch); + callbacks_.step_(batch); // process request output in batch process_batch_output(running_requests_); @@ -520,7 +516,7 @@ void ContinuousSchedulerBase::step(const absl::Duration& timeout) { } } -bool ContinuousSchedulerBase::step_with_schedule_overlap( +bool ContinuousScheduler::step_with_schedule_overlap( const absl::Duration& timeout) { // get a new batch of requests BatchGroup batch = schedule_request(timeout); @@ -533,12 +529,13 @@ bool ContinuousSchedulerBase::step_with_schedule_overlap( } if (!cur_batch_all_empty) { - step_callback_(batch); + callbacks_.step_(batch); } // producer-consumer mode, make sure only one step is scheduled in advance - if (pending_step_.has_value()) { - complete_pending_step(); + if (pending_step_) { + callbacks_.update_last_step_result_(pending_step_->batches); + process_batch_output(pending_step_->requests); } if (cur_batch_all_empty) { // An empty current batch drains the previous step without submitting work. @@ -555,13 +552,7 @@ bool ContinuousSchedulerBase::step_with_schedule_overlap( return true; } -void ContinuousSchedulerBase::complete_pending_step() { - CHECK(pending_step_.has_value()); - result_callback_(pending_step_->batches); - process_batch_output(pending_step_->requests); -} - -void ContinuousSchedulerBase::generate() { +void ContinuousScheduler::generate() { bool batch_empty = false; while (num_pending_requests() > 0 || !batch_empty || request_queue_.size() > 0 || has_pending_prefetch()) { @@ -577,7 +568,7 @@ void ContinuousSchedulerBase::generate() { } // run inference for the batch - step_callback_(batch); + callbacks_.step_(batch); // process request output in batch process_batch_output(running_requests_); @@ -587,7 +578,7 @@ void ContinuousSchedulerBase::generate() { output_dispatcher_->wait_completion(); } -void ContinuousSchedulerBase::generate_with_schedule_overlap() { +void ContinuousScheduler::generate_with_schedule_overlap() { bool batch_empty = false; while (num_pending_requests() > 0 || !batch_empty || request_queue_.size() > 0 || has_pending_prefetch() || @@ -597,7 +588,7 @@ void ContinuousSchedulerBase::generate_with_schedule_overlap() { output_dispatcher_->wait_completion(); } -void ContinuousSchedulerBase::process_batch_output( +void ContinuousScheduler::process_batch_output( const std::vector>& requests) { refresh_sequences_from_requests(requests, output_sequences_); scheduler_metrics_->update(output_sequences_); @@ -643,7 +634,7 @@ void ContinuousSchedulerBase::process_batch_output( } } -void ContinuousSchedulerBase::refresh_sequences_from_requests( +void ContinuousScheduler::refresh_sequences_from_requests( const std::vector>& requests, std::vector& sequences) const { sequences.clear(); diff --git a/xllm/core/scheduler/continuous_scheduler.h b/xllm/core/scheduler/continuous_scheduler.h index bcf3d796f6..eb7e98f904 100644 --- a/xllm/core/scheduler/continuous_scheduler.h +++ b/xllm/core/scheduler/continuous_scheduler.h @@ -20,7 +20,6 @@ limitations under the License. #include #include -#include #include #include #include @@ -35,7 +34,6 @@ limitations under the License. #include "core/common/macros.h" #include "core/common/prefill_policy.h" #include "core/common/types.h" -#include "core/distributed_runtime/engine.h" #include "core/distributed_runtime/xservice_client.h" #include "core/framework/batch/batch_factory.h" #include "core/framework/batch/batch_group.h" @@ -44,15 +42,16 @@ limitations under the License. #include "core/framework/request/sequence.h" #include "core/kv_cache/manager/kv_cache_manager.h" #include "core/scheduler/kv_cache_prefetcher.h" -#include "core/scheduler/profile/profile_manager.h" #include "core/scheduler/request_output_dispatcher.h" #include "core/scheduler/request_priority_queue.h" #include "core/scheduler/scheduler.h" +#include "core/scheduler/scheduler_callbacks.h" #include "core/scheduler/scheduler_metrics.h" #include "core/scheduler/scheduler_notifier.h" namespace xllm { class DistributedWorkerManager; +class ProfileManager; class RequestPriorityQueue; class SchedulerPolicy; class ModelResidencyCoordinator; @@ -87,13 +86,15 @@ struct BatchMode { std::string priority_strategy = "fcfs"; }; -class ContinuousSchedulerBase : public Scheduler { +class ContinuousScheduler : public Scheduler { public: using Options = SchedulerOptions; - using StepCallback = std::function; - using ResultCallback = std::function; - ~ContinuousSchedulerBase() override; + ~ContinuousScheduler() override; + + KVCacheManager* kv_cache_manager() const { return kv_cache_manager_; } + const Tokenizer* tokenizer() const { return tokenizer_; } + const ModelArgs* model_args() const { return model_args_; } bool add_request(std::shared_ptr& request) override; @@ -131,17 +132,18 @@ class ContinuousSchedulerBase : public Scheduler { const InstanceInfo& get_instance_info() override { return instance_info_; } - protected: - ContinuousSchedulerBase( - Engine* engine, + ContinuousScheduler( + KVCacheManager* kv_cache_manager, + const ModelArgs* model_args, + const Tokenizer* tokenizer, + SchedulerCallbacks callbacks, const Options& options, - StepCallback step_callback, - ResultCallback result_callback, std::shared_ptr model_residency_coordinator = nullptr, std::shared_ptr distributed_worker_manager = nullptr); + protected: void clear_mtp_bootstrap(Request* request); virtual void drain_request_releases() {} void populate_heartbeat_request( @@ -175,16 +177,15 @@ class ContinuousSchedulerBase : public Scheduler { // Policy object that encapsulates all batch-assembly logic. std::unique_ptr policy_; - // the engine to run the batch - Engine* resource_engine_; - std::shared_ptr distributed_worker_manager_; - std::shared_ptr model_residency_coordinator_; - - StepCallback step_callback_; - ResultCallback result_callback_; + const ModelArgs* model_args_; + const Tokenizer* tokenizer_; + SchedulerCallbacks callbacks_; KVCacheManager* kv_cache_manager_; + std::shared_ptr distributed_worker_manager_; + std::shared_ptr model_residency_coordinator_; + std::shared_ptr notifier_; // a thread safe queue of requests, bounded by options_.request_queue_size() @@ -244,10 +245,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(); - - // tokenizer - std::unique_ptr tokenizer_; + BatchGroup prepare_batch(); XServiceClient* xservice_client_ = nullptr; XServiceClient::HeartbeatCallbackRegistration @@ -276,8 +274,6 @@ class ContinuousSchedulerBase : public Scheduler { // Returns whether a new batch was submitted. bool step_with_schedule_overlap(const absl::Duration& timeout); - void complete_pending_step(); - void refresh_sequences_from_requests( const std::vector>& requests, std::vector& sequences) const; @@ -285,69 +281,4 @@ class ContinuousSchedulerBase : public Scheduler { void create_queues(const Options& options); }; -template - requires std::derived_from -class ContinuousScheduler : public ContinuousSchedulerBase { - public: - using Options = SchedulerOptions; - - ContinuousScheduler( - EngineType* engine, - const Options& options, - std::shared_ptr model_residency_coordinator = - nullptr, - std::shared_ptr distributed_worker_manager = - nullptr) - requires requires(EngineType* typed_engine, BatchGroup& batch) { - { typed_engine->step(batch) } -> std::same_as; - { - typed_engine->collect_step_outputs(batch) - } -> std::same_as>; - } - : ContinuousSchedulerBase( - engine, - options, - [engine](BatchGroup& batch) { return engine->step(batch); }, - [engine](BatchGroup& batch) { - batch.apply_outputs(engine->collect_step_outputs(batch), - BatchOutputAction::COMMIT_PENDING); - }, - std::move(model_residency_coordinator), - std::move(distributed_worker_manager)), - engine_(engine) {} - - template - requires std::same_as && - requires(TargetEngine* typed_engine, BatchGroup& batch) { - static_cast(typed_engine); - { typed_engine->step(batch) } -> std::same_as; - { - typed_engine->collect_step_outputs(batch) - } -> std::same_as>; - } - ContinuousScheduler( - TargetEngine* engine, - const Options& options, - std::shared_ptr model_residency_coordinator = - nullptr, - std::shared_ptr distributed_worker_manager = - nullptr) - : ContinuousSchedulerBase( - static_cast(engine), - options, - [engine](BatchGroup& batch) { return engine->step(batch); }, - [engine](BatchGroup& batch) { - batch.apply_outputs(engine->collect_step_outputs(batch), - BatchOutputAction::COMMIT_PENDING); - }, - std::move(model_residency_coordinator), - std::move(distributed_worker_manager)), - engine_(static_cast(engine)) {} - - ~ContinuousScheduler() override = default; - - protected: - EngineType* engine_; -}; - } // namespace xllm diff --git a/xllm/core/scheduler/continuous_scheduler_benchmark.cpp b/xllm/core/scheduler/continuous_scheduler_benchmark.cpp index 21deed3b1a..875ec6c741 100644 --- a/xllm/core/scheduler/continuous_scheduler_benchmark.cpp +++ b/xllm/core/scheduler/continuous_scheduler_benchmark.cpp @@ -56,7 +56,6 @@ limitations under the License. #include #include "core/common/types.h" -#include "core/distributed_runtime/engine.h" #include "core/framework/model/model_args.h" #include "core/framework/request/request.h" #include "core/framework/request/request_output.h" @@ -65,6 +64,7 @@ limitations under the License. #include "core/framework/sampling/sampling_params.h" #include "core/framework/tokenizer/tokenizer.h" #include "core/kv_cache/manager/block_manager_pool.h" +#include "core/runtime/forward_params.h" #include "core/scheduler/continuous_scheduler.h" namespace xllm { @@ -75,7 +75,7 @@ namespace { // local resolves to the deprecated one. Sinking the value into a non-const // parameter first selects the supported overload. template -inline BENCHMARK_ALWAYS_INLINE void do_not_optimize(T value) { +[[gnu::always_inline]] inline void do_not_optimize(T value) { benchmark::DoNotOptimize(value); } @@ -93,8 +93,7 @@ class FakeTokenizer final : public Tokenizer { } }; -// Engine stand-in: real BlockManagerPool, no model. -class FakeEngine final : public Engine { +class FakeEngine final { public: FakeEngine() { BlockManagerPool::Options options; @@ -106,17 +105,6 @@ class FakeEngine final : public Engine { std::make_unique(options, /*dp_size=*/1); } - virtual ForwardOutput step(BatchGroup& /*batch*/) { return {}; } - std::vector collect_step_outputs(const BatchGroup& batch) { - return std::vector(batch.size()); - } - const Tokenizer* tokenizer() const override { return &fake_tokenizer_; } - KVCacheManager* kv_cache_manager() const override { - return block_manager_pool_.get(); - } - const ModelArgs& model_args() const override { return model_args_; } - - private: FakeTokenizer fake_tokenizer_; std::unique_ptr block_manager_pool_; ModelArgs model_args_; @@ -124,16 +112,12 @@ class FakeEngine final : public Engine { // Exposes the response processor so each iteration can drain the async // completion callbacks before the next one starts. -class BenchContinuousScheduler final : public ContinuousScheduler<> { +class BenchContinuousScheduler final : public ContinuousScheduler { public: - template - BenchContinuousScheduler(TargetEngine* engine, const Options& options) - : ContinuousScheduler<>(engine, - options, - /*model_residency_coordinator=*/nullptr, - /*distributed_worker_manager=*/nullptr) {} + using ContinuousScheduler::prepare_batch; + using ContinuousScheduler::schedule_request; - BatchGroup prepare_batch_test() { return prepare_batch(); } + using ContinuousScheduler::ContinuousScheduler; void process_batch_output_test() { process_batch_output(running_requests_); } @@ -153,8 +137,16 @@ class SchedulerFixture final { } private: - SchedulerFixture() : scheduler_(&engine_, make_scheduler_options()) {} - + SchedulerFixture() + : scheduler_(engine_.block_manager_pool_.get(), + &engine_.model_args_, + &engine_.fake_tokenizer_, + SchedulerCallbacks{/*step=*/[](BatchGroup& /*batch*/) { + return ForwardOutput{}; + }, + /*update_last_step_result=*/ + [](BatchGroup& /*batch*/) {}}, + make_scheduler_options()) {} static SchedulerOptions make_scheduler_options() { SchedulerOptions options; options.max_tokens_per_batch(kMaxTokensPerBatch) @@ -258,7 +250,7 @@ void append_one_token(const std::vector>& requests) { // collect_finished step frees their blocks and dispatches the completion // callbacks, which are then awaited so the next iteration starts clean. void retire_finished(BenchContinuousScheduler& scheduler) { - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); CHECK(batches.empty() || batches[0].empty()) << "unfinished requests leaked into the next iteration"; scheduler.wait_for_responses(); @@ -277,7 +269,7 @@ void BM_Scheduler_AddRequest(benchmark::State& state) { add_requests(scheduler, requests); state.PauseTiming(); - (void)scheduler.prepare_batch_test(); + (void)scheduler.prepare_batch(); append_one_token(requests); retire_finished(scheduler); state.ResumeTiming(); @@ -297,7 +289,7 @@ void BM_Scheduler_PrepareBatch_Prefill(benchmark::State& state) { add_requests(scheduler, requests); state.ResumeTiming(); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); do_not_optimize(&batches); state.PauseTiming(); @@ -319,11 +311,11 @@ void BM_Scheduler_PrepareBatch_Decode(benchmark::State& state) { std::vector> requests = make_requests(num_requests, /*max_generated_tokens=*/2); add_requests(scheduler, requests); - (void)scheduler.prepare_batch_test(); // prefill step - append_one_token(requests); // first token sampled + (void)scheduler.prepare_batch(); // prefill step + append_one_token(requests); // first token sampled state.ResumeTiming(); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); do_not_optimize(&batches); state.PauseTiming(); @@ -347,8 +339,8 @@ void BM_Scheduler_ProcessBatchOutput(benchmark::State& state) { std::vector> requests = make_requests(num_requests, /*max_generated_tokens=*/2, stream); add_requests(scheduler, requests); - (void)scheduler.prepare_batch_test(); // prefill step - append_one_token(requests); // first token sampled + (void)scheduler.prepare_batch(); // prefill step + append_one_token(requests); // first token sampled state.ResumeTiming(); // Stream requests are dispatched to the response thread pool here; the @@ -384,15 +376,15 @@ void BM_Scheduler_DecodeWindow(benchmark::State& state) { /*stream=*/false, sequences_per_request); add_requests(scheduler, requests); - (void)scheduler.prepare_batch_test(); + (void)scheduler.prepare_batch(); append_one_token(requests); // Allocate the initial decode blocks before measuring. - (void)scheduler.prepare_batch_test(); + (void)scheduler.prepare_batch(); append_one_token(requests); for (int32_t step = 0; step < kDecodeSteps; ++step) { state.ResumeTiming(); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); do_not_optimize(&batches); state.PauseTiming(); @@ -434,11 +426,11 @@ void BM_Scheduler_CollectFinished(benchmark::State& state) { /*stream=*/false)); } add_requests(scheduler, requests); - (void)scheduler.prepare_batch_test(); + (void)scheduler.prepare_batch(); append_one_token(requests); state.ResumeTiming(); - BatchGroup batches = scheduler.prepare_batch_test(); + BatchGroup batches = scheduler.prepare_batch(); do_not_optimize(&batches); state.PauseTiming(); diff --git a/xllm/core/scheduler/dit_scheduler.h b/xllm/core/scheduler/dit_scheduler.h index 7b8c5a4d18..12a68349ab 100644 --- a/xllm/core/scheduler/dit_scheduler.h +++ b/xllm/core/scheduler/dit_scheduler.h @@ -29,7 +29,6 @@ limitations under the License. #include "core/common/macros.h" #include "core/common/types.h" #include "core/distributed_runtime/dit_engine.h" -#include "core/distributed_runtime/engine.h" #include "core/framework/batch/dit_batch.h" #include "core/framework/batch/dit_batch_factory.h" #include "core/framework/request/dit_request.h" @@ -104,10 +103,6 @@ class DiTDynamicBatchScheduler : public DiTScheduler { return pending_requests_.load(std::memory_order_relaxed); } - std::vector> get_running_requests() { - return running_requests_; - } - protected: const Options options_; diff --git a/xllm/core/scheduler/profile/profile_manager.cpp b/xllm/core/scheduler/profile/profile_manager.cpp index 3d22e6a8fe..b3650f4caf 100644 --- a/xllm/core/scheduler/profile/profile_manager.cpp +++ b/xllm/core/scheduler/profile/profile_manager.cpp @@ -24,10 +24,10 @@ limitations under the License. #include #include "core/common/types.h" -#include "core/distributed_runtime/distributed_worker_manager.h" #include "core/framework/batch/batch_factory.h" #include "core/framework/config/model_config.h" #include "core/framework/config/speculative_config.h" +#include "core/framework/model/model_args.h" #include "core/framework/request/request_state.h" #include "core/runtime/acl_graph_bucket_policy.h" #include "core/runtime/decode_graph_bucket.h" @@ -38,26 +38,22 @@ limitations under the License. namespace xllm { -ProfileManager::ProfileManager( - Engine* engine, - const Options& options, - StepCallback step_callback, - ResultCallback result_callback, - std::shared_ptr distributed_worker_manager) +ProfileManager::ProfileManager(KVCacheManager* kv_cache_manager, + const ModelArgs* model_args, + const Options& options, + SchedulerCallbacks callbacks) : options_(options), prefill_policy_(options.max_tokens_per_batch(), options.max_tokens_per_chunk_for_prefill(), options.enable_chunked_prefill(), options.enable_dp_fair_token_budget()), - engine_(engine), - distributed_worker_manager_(std::move(distributed_worker_manager)), - step_callback_(std::move(step_callback)), - result_callback_(std::move(result_callback)), - batch_factory_(options.dp_size()) { - CHECK(engine_ != nullptr); - CHECK(step_callback_); - CHECK(result_callback_); - kv_cache_manager_ = engine_->kv_cache_manager(); + model_args_(model_args), + callbacks_(std::move(callbacks)), + batch_factory_(options.dp_size()), + kv_cache_manager_(kv_cache_manager) { + CHECK(model_args_ != nullptr); + CHECK(callbacks_.step_); + CHECK(callbacks_.update_last_step_result_); CHECK(kv_cache_manager_ != nullptr); prefill_time_predictor_ = std::make_unique( options.enable_profile_kv_blocks(), true /*is_prefill*/); @@ -92,7 +88,7 @@ ProfileManager::ProfileManager( void ProfileManager::profile_step_time() { // get the maximum prefill token length - auto& model_args = engine_->model_args(); + const auto& model_args = *model_args_; int32_t max_context_len = model_args.max_position_embeddings(); // TODO: support length for decode request profile @@ -292,7 +288,7 @@ double ProfileManager::predict_copy_blocks_time( std::shared_ptr ProfileManager::generate_single_request( int32_t token_length, int32_t prefix_length) { - auto& model_args = engine_->model_args(); + const auto& model_args = *model_args_; int32_t vocab_size = model_args.vocab_size(); int32_t eos_token_id = model_args.eos_token_id(); @@ -356,7 +352,7 @@ std::shared_ptr ProfileManager::try_generate_single_decode_request( std::optional dp_rank) { CHECK_GT(total_length, 1) << "Decode profiling requires total_length > 1."; - auto& model_args = engine_->model_args(); + const auto& model_args = *model_args_; int32_t vocab_size = model_args.vocab_size(); int32_t eos_token_id = model_args.eos_token_id(); @@ -467,9 +463,9 @@ double ProfileManager::run_profile_batch( sequences, std::vector(sequences.size(), max_tokens_per_sequence)); const absl::Time start_time = absl::Now(); - step_callback_(batches); + callbacks_.step_(batches); if (options_.enable_schedule_overlap()) { - result_callback_(batches); + callbacks_.update_last_step_result_(batches); } const double latency = absl::ToDoubleMilliseconds(absl::Now() - start_time); for (auto* sequence : sequences) { @@ -544,15 +540,14 @@ void ProfileManager::generate_random_decode_batch( void ProfileManager::warmup_for_eager() { constexpr int32_t kMaxEagerWarmupTokens = 256; - const int32_t max_context_len = - engine_->model_args().max_position_embeddings(); + const int32_t max_context_len = model_args_->max_position_embeddings(); const int32_t prefill_tokens = std::min({options_.max_tokens_per_batch(), max_context_len, kMaxEagerWarmupTokens}); - if (prefill_tokens <= 0 || engine_->model_args().vocab_size() <= 2) { + if (prefill_tokens <= 0 || model_args_->vocab_size() <= 2) { LOG(INFO) << "Skipping eager warmup because model metadata is incomplete: " << "tokens=" << prefill_tokens - << ", vocab_size=" << engine_->model_args().vocab_size(); + << ", vocab_size=" << model_args_->vocab_size(); return; } const double prefill_latency = @@ -578,7 +573,7 @@ void ProfileManager::warmup_for_graph() { } void ProfileManager::warmup_prefill_for_graph() { - auto& model_args = engine_->model_args(); + const auto& model_args = *model_args_; int32_t max_context_len = model_args.max_position_embeddings(); int32_t prefill_tokens = @@ -598,8 +593,7 @@ void ProfileManager::warmup_unified_for_graph() { } void ProfileManager::warmup_decode_for_graph() { - const int32_t max_context_len = - engine_->model_args().max_position_embeddings(); + const int32_t max_context_len = model_args_->max_position_embeddings(); const DecodeGraphWarmupConfig& config = options_.decode_graph_warmup_config(); const bool is_npu = Platform::is_npu(); int32_t max_decode_batch_size = options_.max_seqs_per_batch(); diff --git a/xllm/core/scheduler/profile/profile_manager.h b/xllm/core/scheduler/profile/profile_manager.h index e24803069d..02556a0390 100644 --- a/xllm/core/scheduler/profile/profile_manager.h +++ b/xllm/core/scheduler/profile/profile_manager.h @@ -15,8 +15,7 @@ limitations under the License. #pragma once -#include -#include +#include #include #include #include @@ -27,7 +26,6 @@ limitations under the License. #include "core/common/macros.h" #include "core/common/prefill_policy.h" #include "core/common/types.h" -#include "core/distributed_runtime/engine.h" #include "core/framework/batch/batch_factory.h" #include "core/framework/config/execution_config.h" #include "core/framework/request/request.h" @@ -35,15 +33,12 @@ limitations under the License. #include "core/kv_cache/manager/kv_cache_manager.h" #include "core/runtime/options.h" #include "core/scheduler/profile/time_predictor.h" +#include "core/scheduler/scheduler_callbacks.h" namespace xllm { -class DistributedWorkerManager; - -class ProfileManager { - private: - using StepCallback = std::function; - using ResultCallback = std::function; +class ModelArgs; +class ProfileManager final { public: struct Options { PROPERTY(std::string, model_id); @@ -93,27 +88,10 @@ class ProfileManager { PROPERTY(bool, enable_disagg_pd) = false; }; - template - requires requires(TargetEngine* engine, BatchGroup& batch) { - static_cast(engine); - { engine->step(batch) } -> std::same_as; - { - engine->collect_step_outputs(batch) - } -> std::same_as>; - } - ProfileManager(TargetEngine* engine, + ProfileManager(KVCacheManager* kv_cache_manager, + const ModelArgs* model_args, const Options& options, - std::shared_ptr - distributed_worker_manager = nullptr) - : ProfileManager( - static_cast(engine), - options, - [engine](BatchGroup& batch) { return engine->step(batch); }, - [engine](BatchGroup& batch) { - batch.apply_outputs(engine->collect_step_outputs(batch), - BatchOutputAction::COMMIT_PENDING); - }, - std::move(distributed_worker_manager)) {} + SchedulerCallbacks callbacks); int32_t get_token_budget(); @@ -195,25 +173,14 @@ class ProfileManager { std::pair copy_block_coefficients() const; private: - friend class ContinuousSchedulerBase; - - ProfileManager( - Engine* engine, - const Options& options, - StepCallback step_callback, - ResultCallback result_callback, - std::shared_ptr distributed_worker_manager); - std::unique_ptr prefill_time_predictor_; std::unique_ptr decode_time_predictor_; const Options options_; const PrefillPolicy prefill_policy_; - Engine* engine_; - std::shared_ptr distributed_worker_manager_; - StepCallback step_callback_; - ResultCallback result_callback_; + const ModelArgs* model_args_; + SchedulerCallbacks callbacks_; BatchFactory batch_factory_; KVCacheManager* kv_cache_manager_; diff --git a/xllm/core/distributed_runtime/engine_dispatch.h b/xllm/core/scheduler/scheduler_callbacks.h similarity index 51% rename from xllm/core/distributed_runtime/engine_dispatch.h rename to xllm/core/scheduler/scheduler_callbacks.h index 7ddd6d1aa1..1b6d2be39d 100644 --- a/xllm/core/distributed_runtime/engine_dispatch.h +++ b/xllm/core/scheduler/scheduler_callbacks.h @@ -15,16 +15,27 @@ limitations under the License. #pragma once +#include + +#include "core/framework/batch/batch_group.h" + namespace xllm { -template -decltype(auto) dispatch_engine(const Function& function, - Engine* engine, - OtherEngine* other_engine) { - if (engine != nullptr) { - return function(engine); - } - return function(other_engine); +using StepCallback = std::function; + +struct SchedulerCallbacks { + StepCallback step_; + std::function update_last_step_result_; +}; + +// The engine must outlive the scheduler. +template +SchedulerCallbacks make_scheduler_callbacks(EngineT* engine) { + return {[engine](BatchGroup& batch) { return engine->step(batch); }, + [engine](BatchGroup& batch) { + batch.apply_outputs(engine->collect_step_outputs(batch), + /*action=*/BatchOutputAction::COMMIT_PENDING); + }}; } } // namespace xllm diff --git a/xllm/core/scheduler/scheduler_factory.cpp b/xllm/core/scheduler/scheduler_factory.cpp index e0f226c8e0..e5aabf9427 100644 --- a/xllm/core/scheduler/scheduler_factory.cpp +++ b/xllm/core/scheduler/scheduler_factory.cpp @@ -25,12 +25,45 @@ namespace xllm { SchedulerKind select_scheduler_kind(const SchedulerOptions& options) { if (options.enable_disagg_pd()) { - return SchedulerKind::PD; + return SchedulerKind::DISAGG_PD; } return SchedulerKind::CONTINUOUS; } +std::unique_ptr create_continuous_scheduler( + KVCacheManager* kv_cache_manager, + const ModelArgs* model_args, + const Tokenizer* tokenizer, + SchedulerCallbacks callbacks, + SchedulerOptions options, + std::shared_ptr model_residency_coordinator, + std::shared_ptr distributed_worker_manager, + std::shared_ptr kv_transfer_coordinator, + PDServiceOptions response_options) { + if (select_scheduler_kind(options) == SchedulerKind::DISAGG_PD) { + auto scheduler = + std::make_unique(kv_cache_manager, + model_args, + tokenizer, + std::move(callbacks), + options, + std::move(distributed_worker_manager), + std::move(model_residency_coordinator), + std::move(kv_transfer_coordinator)); + scheduler->start_runtime(std::move(response_options)); + return scheduler; + } + return std::make_unique( + kv_cache_manager, + model_args, + tokenizer, + std::move(callbacks), + options, + std::move(model_residency_coordinator), + std::move(distributed_worker_manager)); +} + std::unique_ptr create_dit_scheduler( DiTEngine* engine, DiTScheduler::Options options) { diff --git a/xllm/core/scheduler/scheduler_factory.h b/xllm/core/scheduler/scheduler_factory.h index 5a7cbd2c5f..d0a11b338f 100644 --- a/xllm/core/scheduler/scheduler_factory.h +++ b/xllm/core/scheduler/scheduler_factory.h @@ -15,61 +15,33 @@ limitations under the License. #pragma once -#include #include #include #include -#include -#include "core/disaggregation/pd_scheduler.h" #include "scheduler/continuous_scheduler.h" #include "scheduler/dit_scheduler.h" namespace xllm { -enum class SchedulerKind : int8_t { CONTINUOUS = 0, PD = 5 }; +class DiTEngine; +class KVTransferCoordinator; +struct PDServiceOptions; + +enum class SchedulerKind : int8_t { CONTINUOUS = 0, DISAGG_PD = 5 }; SchedulerKind select_scheduler_kind(const SchedulerOptions& options); -template - requires requires(TargetEngine* engine, BatchGroup& batch) { - static_cast(engine); - { engine->step(batch) } -> std::same_as; - { - engine->collect_step_outputs(batch) - } -> std::same_as>; - } std::unique_ptr create_continuous_scheduler( - TargetEngine* engine, + KVCacheManager* kv_cache_manager, + const ModelArgs* model_args, + const Tokenizer* tokenizer, + SchedulerCallbacks callbacks, SchedulerOptions options, - std::shared_ptr distributed_worker_manager = - nullptr, - std::shared_ptr model_residency_coordinator = - nullptr, - std::shared_ptr kv_transfer_coordinator = nullptr, - PDServiceOptions response_options = {}) { - switch (select_scheduler_kind(options)) { - case SchedulerKind::PD: - return std::make_unique( - engine, - options, - std::move(distributed_worker_manager), - std::move(model_residency_coordinator), - std::move(kv_transfer_coordinator), - std::move(response_options)); - case SchedulerKind::CONTINUOUS: - return std::make_unique>( - engine, - options, - std::move(model_residency_coordinator), - std::move(distributed_worker_manager)); - } - return std::make_unique>( - engine, - options, - std::move(model_residency_coordinator), - std::move(distributed_worker_manager)); -} + std::shared_ptr model_residency_coordinator, + std::shared_ptr distributed_worker_manager, + std::shared_ptr kv_transfer_coordinator, + PDServiceOptions response_options); std::unique_ptr create_dit_scheduler( DiTEngine* engine,