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

4
5
6
7
8
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};

use dashmap::DashMap;
9
use serde::{Deserialize, Serialize};
10

11
use crate::kv_router::KV_METRICS_SUBJECT;
12
use crate::kv_router::protocols::ActiveLoad;
13
use crate::model_card::ModelDeploymentCard;
14
use dynamo_runtime::component::Client;
15
use dynamo_runtime::discovery::{DiscoveryQuery, watch_and_extract_field};
16
17
use dynamo_runtime::pipeline::{WorkerLoadMonitor, async_trait};
use dynamo_runtime::traits::DistributedRuntimeProvider;
18
use dynamo_runtime::transports::event_plane::EventSubscriber;
19

20
21
22
/// Scale factor for storing f64 thresholds as u32 (10000 = 4 decimal places)
const THRESHOLD_SCALE: u32 = 10000;

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/// Default value for max_num_batched_tokens and active_prefill_tokens_threshold
/// when not configured. Set high enough to effectively disable busy detection.
const DEFAULT_MAX_TOKENS: u64 = 10_000_000;

/// Configuration for worker load thresholds used in busy detection.
///
/// All thresholds are optional. When not set, defaults are applied:
/// - `active_decode_blocks_threshold`: 1.0 (effectively disabled)
/// - `active_prefill_tokens_threshold`: 10,000,000 (effectively disabled)
/// - `active_prefill_tokens_threshold_frac`: 1.5 (effectively disabled)
/// - `max_num_batched_tokens` (from runtime config): 10,000,000 if not reported
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct LoadThresholdConfig {
    /// KV cache block utilization threshold (0.0-1.0).
    /// Worker is busy when `active_decode_blocks / total_blocks > threshold`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_decode_blocks_threshold: Option<f64>,

    /// Absolute prefill token count threshold.
    /// Worker is busy when `active_prefill_tokens > threshold`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_prefill_tokens_threshold: Option<u64>,

    /// Fraction of max_num_batched_tokens (0.0-1.5+).
    /// Worker is busy when `active_prefill_tokens > frac * max_num_batched_tokens`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_prefill_tokens_threshold_frac: Option<f64>,
}

impl LoadThresholdConfig {
    /// Returns true if any threshold is configured.
    pub fn is_configured(&self) -> bool {
        self.active_decode_blocks_threshold.is_some()
            || self.active_prefill_tokens_threshold.is_some()
            || self.active_prefill_tokens_threshold_frac.is_some()
    }
}

Yan Ru Pei's avatar
Yan Ru Pei committed
61
62
/// Worker load monitoring state per dp_rank
#[derive(Clone, Debug, Default)]
63
pub struct WorkerLoadState {
64
    pub active_decode_blocks: HashMap<u32, u64>,
Yan Ru Pei's avatar
Yan Ru Pei committed
65
    pub kv_total_blocks: HashMap<u32, u64>,
66
    pub active_prefill_tokens: HashMap<u32, u64>,
67
68
    /// max_num_batched_tokens from runtime config (same for all dp_ranks)
    pub max_num_batched_tokens: HashMap<u32, u64>,
69
70
71
}

impl WorkerLoadState {
72
73
74
75
76
77
    /// Returns true if ALL dp_ranks are considered busy based on the threshold logic.
    ///
    /// For each dp_rank, a dp_rank is busy if ANY of these conditions is met (OR logic):
    /// 1. `active_prefill_tokens > active_prefill_tokens_threshold` (absolute threshold)
    /// 2. `active_prefill_tokens > frac * max_num_batched_tokens` (fraction-based threshold)
    /// 3. `active_decode_blocks / total_blocks > active_decode_blocks_threshold` (blocks threshold)
78
    ///
79
    /// If none of these checks can be performed (missing data), that dp_rank is considered free.
80
81
82
83
84
85
    ///
    /// The worker is busy only if ALL dp_ranks are busy.
    pub fn is_busy(
        &self,
        active_decode_blocks_threshold: f64,
        active_prefill_tokens_threshold: u64,
86
        active_prefill_tokens_threshold_frac: f64,
87
88
89
90
    ) -> bool {
        // Get all dp_ranks we know about
        let all_dp_ranks: std::collections::HashSet<_> = self
            .active_decode_blocks
Yan Ru Pei's avatar
Yan Ru Pei committed
91
            .keys()
92
93
            .chain(self.active_prefill_tokens.keys())
            .copied()
Yan Ru Pei's avatar
Yan Ru Pei committed
94
95
            .collect();

96
97
        // If no dp_ranks known, not busy
        if all_dp_ranks.is_empty() {
Yan Ru Pei's avatar
Yan Ru Pei committed
98
            return false;
99
        }
Yan Ru Pei's avatar
Yan Ru Pei committed
100

101
102
        // Check if ALL dp_ranks are busy
        all_dp_ranks.iter().all(|&dp_rank| {
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
            // Check 1: prefill tokens threshold (absolute token count)
            if let Some(&active_tokens) = self.active_prefill_tokens.get(&dp_rank) {
                if active_tokens > active_prefill_tokens_threshold {
                    return true; // This dp_rank is busy due to absolute token threshold
                }

                // Check 2: prefill tokens threshold (fraction of max_num_batched_tokens)
                let max_batched = self
                    .max_num_batched_tokens
                    .get(&dp_rank)
                    .copied()
                    .unwrap_or(DEFAULT_MAX_TOKENS);
                let frac_threshold =
                    (active_prefill_tokens_threshold_frac * max_batched as f64) as u64;
                if active_tokens > frac_threshold {
                    return true; // This dp_rank is busy due to frac-based token threshold
                }
120
121
            }

122
            // Check 3: blocks threshold
123
124
125
            // Skip if total_blocks is 0 (no capacity means threshold check is meaningless)
            if let (Some(&active_blocks), Some(&total_blocks)) = (
                self.active_decode_blocks.get(&dp_rank),
Yan Ru Pei's avatar
Yan Ru Pei committed
126
                self.kv_total_blocks.get(&dp_rank),
127
128
129
130
            ) && total_blocks > 0
                && (active_blocks as f64) > (active_decode_blocks_threshold * total_blocks as f64)
            {
                return true; // This dp_rank is busy due to blocks
Yan Ru Pei's avatar
Yan Ru Pei committed
131
            }
132

133
            // If we can't perform any check or no threshold exceeded, this dp_rank is free
134
            false
Yan Ru Pei's avatar
Yan Ru Pei committed
135
        })
136
137
138
    }
}

139
140
/// Worker monitor for tracking KV cache usage and busy states.
///
141
/// Cloning shares state via internal Arc-wrapped fields. This allows multiple pipelines
142
143
/// (e.g., chat and completions) to share the same monitor instance.
#[derive(Clone)]
144
pub struct KvWorkerMonitor {
145
    client: Client,
146
    worker_load_states: Arc<DashMap<u64, WorkerLoadState>>,
147
148
149
150
    /// Active decode blocks threshold stored as parts-per-10000 (e.g., 8500 = 0.85)
    active_decode_blocks_threshold: Arc<AtomicU32>,
    /// Active prefill tokens threshold stored as literal token count (u64)
    active_prefill_tokens_threshold: Arc<AtomicU64>,
151
152
    /// Active prefill tokens threshold as fraction of max_num_batched_tokens, stored scaled
    active_prefill_tokens_threshold_frac: Arc<AtomicU32>,
153
154
    /// Guard to ensure start_monitoring() only runs once across clones
    started: Arc<AtomicBool>,
155
156
}

157
impl KvWorkerMonitor {
158
    /// Create a new worker monitor with the given threshold configuration.
159
    ///
160
161
    /// All thresholds can be dynamically updated via setter methods or
    /// `set_load_threshold_config()`.
162
    ///
163
164
165
166
167
168
169
170
171
172
173
    /// Defaults are applied for any threshold not specified in the config:
    /// - `active_decode_blocks_threshold`: 1.0 (effectively disabled)
    /// - `active_prefill_tokens_threshold`: DEFAULT_MAX_TOKENS (effectively disabled)
    /// - `active_prefill_tokens_threshold_frac`: 1.5 (effectively disabled)
    pub fn new(client: Client, config: LoadThresholdConfig) -> Self {
        let active_decode_blocks = config.active_decode_blocks_threshold.unwrap_or(1.0);
        let active_prefill_tokens = config
            .active_prefill_tokens_threshold
            .unwrap_or(DEFAULT_MAX_TOKENS);
        let active_prefill_tokens_frac = config.active_prefill_tokens_threshold_frac.unwrap_or(1.5);

174
175
        Self {
            client,
176
            worker_load_states: Arc::new(DashMap::new()),
177
178
179
180
181
182
183
            active_decode_blocks_threshold: Arc::new(AtomicU32::new(Self::f64_to_scaled(
                active_decode_blocks,
            ))),
            active_prefill_tokens_threshold: Arc::new(AtomicU64::new(active_prefill_tokens)),
            active_prefill_tokens_threshold_frac: Arc::new(AtomicU32::new(Self::f64_to_scaled(
                active_prefill_tokens_frac,
            ))),
184
            started: Arc::new(AtomicBool::new(false)),
185
186
187
        }
    }

188
    /// Convert a f64 threshold to scaled u32 for atomic storage.
189
    #[inline]
190
    fn f64_to_scaled(threshold: f64) -> u32 {
191
192
193
        (threshold * THRESHOLD_SCALE as f64) as u32
    }

194
    /// Convert a scaled u32 back to f64 threshold.
195
    #[inline]
196
    fn scaled_to_f64(scaled: u32) -> f64 {
197
198
199
        scaled as f64 / THRESHOLD_SCALE as f64
    }

200
201
    /// Get the current active decode blocks threshold value as f64.
    pub fn active_decode_blocks_threshold(&self) -> f64 {
202
        Self::scaled_to_f64(self.active_decode_blocks_threshold.load(Ordering::Relaxed))
203
204
205
206
    }

    /// Set the active decode blocks threshold value from f64.
    pub fn set_active_decode_blocks_threshold(&self, threshold: f64) {
207
208
        self.active_decode_blocks_threshold
            .store(Self::f64_to_scaled(threshold), Ordering::Relaxed);
209
210
211
212
213
    }

    /// Get the current active prefill tokens threshold value as u64.
    pub fn active_prefill_tokens_threshold(&self) -> u64 {
        self.active_prefill_tokens_threshold.load(Ordering::Relaxed)
214
215
    }

216
217
218
219
    /// Set the active prefill tokens threshold value from u64.
    pub fn set_active_prefill_tokens_threshold(&self, threshold: u64) {
        self.active_prefill_tokens_threshold
            .store(threshold, Ordering::Relaxed);
220
221
    }

222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
    /// Get the current active prefill tokens threshold frac value as f64.
    pub fn active_prefill_tokens_threshold_frac(&self) -> f64 {
        Self::scaled_to_f64(
            self.active_prefill_tokens_threshold_frac
                .load(Ordering::Relaxed),
        )
    }

    /// Set the active prefill tokens threshold frac value from f64.
    pub fn set_active_prefill_tokens_threshold_frac(&self, frac: f64) {
        self.active_prefill_tokens_threshold_frac
            .store(Self::f64_to_scaled(frac), Ordering::Relaxed);
    }

    /// Get the current load threshold configuration.
    pub fn load_threshold_config(&self) -> LoadThresholdConfig {
        LoadThresholdConfig {
            active_decode_blocks_threshold: Some(self.active_decode_blocks_threshold()),
            active_prefill_tokens_threshold: Some(self.active_prefill_tokens_threshold()),
            active_prefill_tokens_threshold_frac: Some(self.active_prefill_tokens_threshold_frac()),
        }
    }

    /// Update all thresholds from a LoadThresholdConfig.
    /// Only updates fields that are Some in the config.
    pub fn set_load_threshold_config(&self, config: &LoadThresholdConfig) {
        if let Some(threshold) = config.active_decode_blocks_threshold {
            self.set_active_decode_blocks_threshold(threshold);
        }
        if let Some(threshold) = config.active_prefill_tokens_threshold {
            self.set_active_prefill_tokens_threshold(threshold);
        }
        if let Some(frac) = config.active_prefill_tokens_threshold_frac {
            self.set_active_prefill_tokens_threshold_frac(frac);
        }
257
    }
258
}
259

260
261
#[async_trait]
impl WorkerLoadMonitor for KvWorkerMonitor {
262
263
264
265
    /// Start background monitoring of worker KV cache usage.
    ///
    /// This is safe to call multiple times (e.g., from cloned monitors shared across
    /// pipelines) - only the first call spawns the background task.
266
    async fn start_monitoring(&self) -> anyhow::Result<()> {
267
268
269
270
271
272
        // Guard: only start once across all clones
        if self.started.swap(true, Ordering::SeqCst) {
            tracing::debug!("Worker monitoring already started, skipping");
            return Ok(());
        }

273
274
275
        let endpoint = &self.client.endpoint;
        let component = endpoint.component();

276
277
278
279
280
281
282
283
284
285
286
        let cancellation_token = component.drt().child_token();

        // Watch for runtime config updates from model deployment cards via discovery interface
        let discovery = component.drt().discovery();
        let discovery_stream = discovery
            .list_and_watch(DiscoveryQuery::AllModels, Some(cancellation_token.clone()))
            .await?;
        let mut config_events_rx =
            watch_and_extract_field(discovery_stream, |card: ModelDeploymentCard| {
                card.runtime_config
            });
287

288
289
290
291
292
        // Subscribe to KV metrics events using EventSubscriber (Msgpack payloads)
        let mut kv_metrics_rx =
            EventSubscriber::for_namespace(component.namespace(), KV_METRICS_SUBJECT)
                .await?
                .typed::<ActiveLoad>();
293
294
295

        let worker_load_states = self.worker_load_states.clone();
        let client = self.client.clone();
296
297
        let active_decode_blocks_threshold = self.active_decode_blocks_threshold.clone();
        let active_prefill_tokens_threshold = self.active_prefill_tokens_threshold.clone();
298
299
        let active_prefill_tokens_threshold_frac =
            self.active_prefill_tokens_threshold_frac.clone();
300
301
302
303
304
305
306
307
308
309
310
311

        // Spawn background monitoring task
        tokio::spawn(async move {
            let mut previous_busy_instances = Vec::new(); // Track previous state

            loop {
                tokio::select! {
                    _ = cancellation_token.cancelled() => {
                        tracing::debug!("Worker monitoring cancelled");
                        break;
                    }

312
                    // Handle runtime config updates
313
314
315
                    _ = config_events_rx.changed() => {
                        let runtime_configs = config_events_rx.borrow().clone();

316
                        worker_load_states.retain(|lease_id, _| runtime_configs.contains_key(lease_id));
317

318
                        // Update worker load states with runtime config values for all dp_ranks
Yan Ru Pei's avatar
Yan Ru Pei committed
319
                        for (lease_id, runtime_config) in runtime_configs.iter() {
320
                            let mut state = worker_load_states.entry(*lease_id).or_default();
Yan Ru Pei's avatar
Yan Ru Pei committed
321
322
323
324
325
326
327

                            // Populate total_blocks for all dp_ranks (they share the same total)
                            if let Some(total_blocks) = runtime_config.total_kv_blocks {
                                for dp_rank in 0..runtime_config.data_parallel_size {
                                    state.kv_total_blocks.insert(dp_rank, total_blocks);
                                }
                            }
328
329
330
331
332
333
334

                            // Populate max_num_batched_tokens for all dp_ranks
                            if let Some(max_batched) = runtime_config.max_num_batched_tokens {
                                for dp_rank in 0..runtime_config.data_parallel_size {
                                    state.max_num_batched_tokens.insert(dp_rank, max_batched);
                                }
                            }
335
336
337
                        }
                    }

338
                    // Handle KV metrics updates (ActiveLoad)
339
                    kv_event = kv_metrics_rx.next() => {
340
                        let Some(event_result) = kv_event else {
341
342
343
344
                            tracing::debug!("KV metrics stream closed");
                            break;
                        };

345
346
                        let Ok((_envelope, active_load)) = event_result else {
                            tracing::error!("Error receiving KV metrics event: {event_result:?}");
347
348
349
350
351
352
353
                            continue;
                        };

                        let worker_id = active_load.worker_id;
                        let dp_rank = active_load.dp_rank;

                        // Update worker load state per dp_rank
354
355
356
357
358
359
360
361
                        {
                            let mut state = worker_load_states.entry(worker_id).or_default();
                            if let Some(active_blocks) = active_load.active_decode_blocks {
                                state.active_decode_blocks.insert(dp_rank, active_blocks);
                            }
                            if let Some(active_tokens) = active_load.active_prefill_tokens {
                                state.active_prefill_tokens.insert(dp_rank, active_tokens);
                            }
362
363
364
                        }

                        // Load thresholds dynamically - allows runtime updates
365
366
367
368
369
370
                        let current_active_decode_blocks_threshold =
                            Self::scaled_to_f64(active_decode_blocks_threshold.load(Ordering::Relaxed));
                        let current_active_prefill_tokens_threshold =
                            active_prefill_tokens_threshold.load(Ordering::Relaxed);
                        let current_active_prefill_tokens_threshold_frac =
                            Self::scaled_to_f64(active_prefill_tokens_threshold_frac.load(Ordering::Relaxed));
371
372

                        // Recalculate all busy instances and update
373
                        let busy_instances: Vec<u64> = worker_load_states
374
                            .iter()
375
376
377
378
379
380
381
382
383
                            .filter_map(|entry| {
                                entry
                                    .value()
                                    .is_busy(
                                        current_active_decode_blocks_threshold,
                                        current_active_prefill_tokens_threshold,
                                        current_active_prefill_tokens_threshold_frac,
                                    )
                                    .then_some(*entry.key())
384
385
386
387
388
389
390
391
                            })
                            .collect();

                        // Only update if busy_instances has changed
                        if busy_instances != previous_busy_instances {
                            tracing::debug!("Busy instances changed: {:?}", busy_instances);
                            client.update_free_instances(&busy_instances);
                            previous_busy_instances = busy_instances;
392
393
394
395
396
397
398
399
400
401
402
                        }
                    }
                }
            }

            tracing::info!("Worker monitoring task exiting");
        });

        Ok(())
    }
}