scheduler.rs 6.35 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
            kv_router_config.router_track_prefill_tokens,
85
86
87
            component.drt().child_token(),
            worker_type,
            watch_worker_configs,
88
89
        ));

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

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

107
        Ok(Self { inner })
108
109
    }

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

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

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

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

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

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

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

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

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

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