scheduler.rs 6.24 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
// SPDX-License-Identifier: Apache-2.0
3

4
pub use dynamo_kv_router::scheduling::policy::RouterSchedulingPolicy;
5
pub use dynamo_kv_router::scheduling::{
6
    KvSchedulerError, LocalScheduler, PotentialLoad, SchedulingRequest, SchedulingResponse,
7
8
};
pub use dynamo_kv_router::selector::DefaultWorkerSelector;
9
use dynamo_kv_router::selector::WorkerSelector as WorkerSelectorTrait;
10

11
use super::metrics::ROUTER_QUEUE_METRICS;
12
use super::sequence::{
13
    RuntimeSequencePublisher, SequenceError, SequenceRequest, create_multi_worker_sequences,
14
};
15
use crate::discovery::RuntimeConfigWatch;
16
use crate::local_model::runtime_config::ModelRuntimeConfig;
17
use anyhow::Result;
18
19
20
21
use dynamo_kv_router::{
    config::{KvRouterConfig, RouterConfigOverride},
    protocols::{OverlapScores, WorkerId},
};
22
use dynamo_runtime::component::Component;
Yan Ru Pei's avatar
Yan Ru Pei committed
23
use dynamo_runtime::traits::DistributedRuntimeProvider;
24
use dynamo_tokens::SequenceHash;
25
use std::collections::{HashMap, HashSet};
26
27
use std::sync::Arc;
use std::time::Duration;
28

29
30
31
32
33
34
35
pub struct KvScheduler<Sel = DefaultWorkerSelector>
where
    Sel: WorkerSelectorTrait<ModelRuntimeConfig>,
{
    inner: Arc<
        LocalScheduler<RuntimeSequencePublisher, ModelRuntimeConfig, RouterSchedulingPolicy, Sel>,
    >,
36
37
}

38
39
40
41
impl<Sel> KvScheduler<Sel>
where
    Sel: WorkerSelectorTrait<ModelRuntimeConfig> + Send + Sync + 'static,
{
42
    pub async fn start(
43
        component: Component,
44
        block_size: u32,
45
        workers_with_configs: RuntimeConfigWatch,
46
        selector: Sel,
47
        kv_router_config: &KvRouterConfig,
48
        worker_type: &'static str,
49
    ) -> Result<Self, KvSchedulerError> {
50
51
        let initial_workers: HashMap<WorkerId, ModelRuntimeConfig> =
            workers_with_configs.borrow().clone();
52

53
        let router_id = component.drt().discovery().instance_id();
54
55
56
57
58
59
60
61
62
63
        let slots = create_multi_worker_sequences(
            component.clone(),
            block_size as usize,
            initial_workers,
            kv_router_config.router_replica_sync,
            router_id,
            worker_type,
        )
        .await
        .map_err(|e| KvSchedulerError::InitFailed(e.to_string()))?;
64

65
66
        let watch_worker_configs = !kv_router_config.skip_initial_worker_wait;
        if !watch_worker_configs {
67
68
            tracing::info!("skipping discovery-based worker monitoring");
        }
Yan Ru Pei's avatar
Yan Ru Pei committed
69

70
71
72
73
74
75
76
        let policy =
            RouterSchedulingPolicy::new(kv_router_config.router_queue_policy, block_size as usize);
        tracing::info!(
            "Router queue policy: {}",
            kv_router_config.router_queue_policy
        );

77
78
        let inner = Arc::new(LocalScheduler::new(
            slots,
79
            workers_with_configs.clone(),
80
            kv_router_config.router_queue_threshold,
81
82
            block_size,
            selector,
83
            policy,
84
85
86
            component.drt().child_token(),
            worker_type,
            watch_worker_configs,
87
88
        ));

89
90
        let metrics_scheduler = Arc::clone(&inner);
        let metrics_cancel_token = component.drt().child_token();
Yan Ru Pei's avatar
Yan Ru Pei committed
91
        tokio::spawn(async move {
92
            let mut recheck_interval = tokio::time::interval(Duration::from_secs(60));
93
            ROUTER_QUEUE_METRICS.set_pending(worker_type, metrics_scheduler.pending_count());
Yan Ru Pei's avatar
Yan Ru Pei committed
94
95

            loop {
96
                tokio::select! {
97
                    _ = metrics_cancel_token.cancelled() => break,
98
                    _ = recheck_interval.tick() => {
99
100
                        ROUTER_QUEUE_METRICS
                            .set_pending(worker_type, metrics_scheduler.pending_count());
101
102
                    }
                }
103
104
105
            }
        });

106
        Ok(Self { inner })
107
108
    }

109
    #[expect(clippy::too_many_arguments)]
110
111
    pub async fn schedule(
        &self,
Yan Ru Pei's avatar
Yan Ru Pei committed
112
        maybe_request_id: Option<String>,
113
        isl_tokens: usize,
114
        token_seq: Option<Vec<SequenceHash>>,
115
        overlaps: OverlapScores,
116
        router_config_override: Option<&RouterConfigOverride>,
117
        update_states: bool,
118
        lora_name: Option<String>,
119
        priority_jump: f64,
120
        expected_output_tokens: Option<u32>,
121
122
        allowed_worker_ids: Option<HashSet<WorkerId>>,
    ) -> Result<SchedulingResponse, KvSchedulerError> {
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        let response = self
            .inner
            .schedule(
                maybe_request_id,
                isl_tokens,
                token_seq,
                overlaps,
                router_config_override,
                update_states,
                lora_name,
                priority_jump,
                expected_output_tokens,
                allowed_worker_ids,
            )
            .await;
        ROUTER_QUEUE_METRICS.set_pending(self.worker_type(), self.pending_count());
        response
140
141
    }

142
    pub fn register_workers(&self, worker_ids: &HashSet<WorkerId>) {
143
        self.inner.register_workers(worker_ids);
144
145
    }

146
    pub async fn add_request(&self, req: SequenceRequest) -> Result<(), SequenceError> {
147
        self.inner.add_request(req).await
148
149
    }

150
    pub async fn mark_prefill_completed(&self, request_id: &str) -> Result<(), SequenceError> {
151
152
        self.inner.mark_prefill_completed(request_id).await?;
        ROUTER_QUEUE_METRICS.set_pending(self.worker_type(), self.pending_count());
153
        Ok(())
154
155
    }

156
    pub async fn free(&self, request_id: &str) -> Result<(), SequenceError> {
157
158
        self.inner.free(request_id).await?;
        ROUTER_QUEUE_METRICS.set_pending(self.worker_type(), self.pending_count());
159
        Ok(())
160
    }
161

162
    pub fn pending_count(&self) -> usize {
163
        self.inner.pending_count()
164
165
    }

166
    pub fn worker_type(&self) -> &'static str {
167
        self.inner.worker_type()
168
169
    }

170
    pub fn add_output_block(
171
172
173
174
        &self,
        request_id: &str,
        decay_fraction: Option<f64>,
    ) -> Result<(), SequenceError> {
175
        self.inner.add_output_block(request_id, decay_fraction)
176
177
    }

178
    pub fn get_potential_loads(
179
        &self,
180
        token_seq: Option<Vec<SequenceHash>>,
181
182
183
        isl_tokens: usize,
        overlaps: OverlapScores,
    ) -> Vec<PotentialLoad> {
184
185
        self.inner
            .get_potential_loads(token_seq, isl_tokens, overlaps)
186
    }
187
188

    pub fn get_active_lora_counts(&self) -> HashMap<String, usize> {
189
        self.inner.get_active_lora_counts()
190
    }
191
}