"vscode:/vscode.git/clone" did not exist on "155ad56d7b567441685a8f8ebf51b7077e68e054"
model_manager.rs 18.3 KB
Newer Older
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

4
5
use std::{
    collections::{HashMap, HashSet},
6
    sync::Arc,
7
8
};

9
use parking_lot::{Mutex, RwLock};
10
use tokio::sync::oneshot;
11

12
use dynamo_runtime::prelude::DistributedRuntimeProvider;
13
use dynamo_runtime::{component::Endpoint, storage::key_value_store::Key};
14
15

use crate::{
16
17
18
    discovery::KV_ROUTERS_ROOT_PATH,
    kv_router::{KvRouter, KvRouterConfig, scheduler::DefaultWorkerSelector},
    model_card::ModelDeploymentCard,
19
    model_type::ModelType,
20
21
22
23
24
25
26
27
    types::{
        generic::tensor::TensorStreamingEngine,
        openai::{
            chat_completions::OpenAIChatCompletionsStreamingEngine,
            completions::OpenAICompletionsStreamingEngine,
            embeddings::OpenAIEmbeddingsStreamingEngine,
        },
    },
28
};
29

30
31
32
33
34
35
36
37
/// State for prefill router activation rendezvous
enum PrefillActivationState {
    /// Decode model registered, waiting for prefill endpoint
    DecodeWaiting(oneshot::Sender<Endpoint>),
    /// Prefill endpoint arrived, waiting for decode model to register
    PrefillReady(oneshot::Receiver<Endpoint>),
}

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#[derive(Debug, thiserror::Error)]
pub enum ModelManagerError {
    #[error("Model not found: {0}")]
    ModelNotFound(String),

    #[error("Model already exists: {0}")]
    ModelAlreadyExists(String),
}

// Don't implement Clone for this, put it in an Arc instead.
pub struct ModelManager {
    // We read a lot and write rarely, so these three are RwLock
    completion_engines: RwLock<ModelEngines<OpenAICompletionsStreamingEngine>>,
    chat_completion_engines: RwLock<ModelEngines<OpenAIChatCompletionsStreamingEngine>>,
    embeddings_engines: RwLock<ModelEngines<OpenAIEmbeddingsStreamingEngine>>,
53
    tensor_engines: RwLock<ModelEngines<TensorStreamingEngine>>,
54
55
    // Prefill models don't have engines - they're only tracked for discovery/lifecycle
    prefill_engines: RwLock<ModelEngines<()>>,
56

57
    // These are Mutex because we read and write rarely and equally
58
    cards: Mutex<HashMap<String, ModelDeploymentCard>>,
59
60
    kv_choosers: Mutex<HashMap<String, Arc<KvRouter>>>, // Key: component service_name
    prefill_router_activators: Mutex<HashMap<String, PrefillActivationState>>,
61
62
63
64
65
66
67
68
69
70
71
72
73
74
}

impl Default for ModelManager {
    fn default() -> Self {
        Self::new()
    }
}

impl ModelManager {
    pub fn new() -> Self {
        Self {
            completion_engines: RwLock::new(ModelEngines::default()),
            chat_completion_engines: RwLock::new(ModelEngines::default()),
            embeddings_engines: RwLock::new(ModelEngines::default()),
75
            tensor_engines: RwLock::new(ModelEngines::default()),
76
            prefill_engines: RwLock::new(ModelEngines::default()),
77
            cards: Mutex::new(HashMap::new()),
78
            kv_choosers: Mutex::new(HashMap::new()),
79
            prefill_router_activators: Mutex::new(HashMap::new()),
80
81
82
        }
    }

83
84
85
86
87
88
89
90
91
92
93
94
95
    pub fn is_valid_checksum(
        &self,
        model_type: ModelType,
        model_name: &str,
        candidate_checksum: &str,
    ) -> Option<bool> {
        let mut results = vec![];
        for unit in model_type.units() {
            let maybe_valid_checksum = match unit {
                ModelType::Chat => self.chat_completion_engines.read().checksum(model_name),
                ModelType::Completions => self.completion_engines.read().checksum(model_name),
                ModelType::Embedding => self.embeddings_engines.read().checksum(model_name),
                ModelType::TensorBased => self.tensor_engines.read().checksum(model_name),
96
                ModelType::Prefill => self.prefill_engines.read().checksum(model_name),
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
                _ => {
                    continue;
                }
            };
            if let Some(is_valid) = maybe_valid_checksum.map(|valid_checksum| {
                tracing::debug!(
                    model_name,
                    valid_checksum,
                    candidate_checksum,
                    "is_valid_checksum: check case"
                );
                valid_checksum == candidate_checksum
            }) {
                results.push(is_valid)
            }
        }
        if results.is_empty() {
            None
        } else {
            // The checksum is valid if it is correct for all the ModelType in the bitflag.
            Some(results.into_iter().all(|x| x))
        }
    }

121
122
    pub fn get_model_cards(&self) -> Vec<ModelDeploymentCard> {
        self.cards.lock().values().cloned().collect()
123
124
    }

125
    pub fn has_model_any(&self, model: &str) -> bool {
126
127
        self.chat_completion_engines.read().contains(model)
            || self.completion_engines.read().contains(model)
128
129
    }

130
131
132
133
134
    pub fn model_display_names(&self) -> HashSet<String> {
        self.list_chat_completions_models()
            .into_iter()
            .chain(self.list_completions_models())
            .chain(self.list_embeddings_models())
135
            .chain(self.list_tensor_models())
136
            .chain(self.list_prefill_models())
137
138
139
            .collect()
    }

140
    pub fn list_chat_completions_models(&self) -> Vec<String> {
141
        self.chat_completion_engines.read().list()
142
143
144
    }

    pub fn list_completions_models(&self) -> Vec<String> {
145
        self.completion_engines.read().list()
146
147
148
    }

    pub fn list_embeddings_models(&self) -> Vec<String> {
149
        self.embeddings_engines.read().list()
150
151
    }

152
153
154
155
    pub fn list_tensor_models(&self) -> Vec<String> {
        self.tensor_engines.read().list()
    }

156
157
158
159
    pub fn list_prefill_models(&self) -> Vec<String> {
        self.prefill_engines.read().list()
    }

160
161
162
    pub fn add_completions_model(
        &self,
        model: &str,
163
        card_checksum: &str,
164
165
        engine: OpenAICompletionsStreamingEngine,
    ) -> Result<(), ModelManagerError> {
166
        let mut clients = self.completion_engines.write();
167
        clients.add(model, card_checksum, engine)
168
169
170
171
172
    }

    pub fn add_chat_completions_model(
        &self,
        model: &str,
173
        card_checksum: &str,
174
175
        engine: OpenAIChatCompletionsStreamingEngine,
    ) -> Result<(), ModelManagerError> {
176
        let mut clients = self.chat_completion_engines.write();
177
        clients.add(model, card_checksum, engine)
178
179
180
181
182
    }

    pub fn add_embeddings_model(
        &self,
        model: &str,
183
        card_checksum: &str,
184
185
        engine: OpenAIEmbeddingsStreamingEngine,
    ) -> Result<(), ModelManagerError> {
186
        let mut clients = self.embeddings_engines.write();
187
        clients.add(model, card_checksum, engine)
188
189
    }

190
191
192
    pub fn add_tensor_model(
        &self,
        model: &str,
193
        card_checksum: &str,
194
195
196
        engine: TensorStreamingEngine,
    ) -> Result<(), ModelManagerError> {
        let mut clients = self.tensor_engines.write();
197
        clients.add(model, card_checksum, engine)
198
199
    }

200
201
202
203
204
205
    pub fn add_prefill_model(
        &self,
        model: &str,
        card_checksum: &str,
    ) -> Result<(), ModelManagerError> {
        let mut clients = self.prefill_engines.write();
206
        clients.add(model, card_checksum, ())
207
208
    }

209
    pub fn remove_completions_model(&self, model: &str) -> Result<(), ModelManagerError> {
210
        let mut clients = self.completion_engines.write();
211
212
213
214
        clients.remove(model)
    }

    pub fn remove_chat_completions_model(&self, model: &str) -> Result<(), ModelManagerError> {
215
        let mut clients = self.chat_completion_engines.write();
216
217
218
219
        clients.remove(model)
    }

    pub fn remove_embeddings_model(&self, model: &str) -> Result<(), ModelManagerError> {
220
        let mut clients = self.embeddings_engines.write();
221
222
223
        clients.remove(model)
    }

224
225
226
227
228
    pub fn remove_tensor_model(&self, model: &str) -> Result<(), ModelManagerError> {
        let mut clients = self.tensor_engines.write();
        clients.remove(model)
    }

229
230
231
232
233
    pub fn remove_prefill_model(&self, model: &str) -> Result<(), ModelManagerError> {
        let mut clients = self.prefill_engines.write();
        clients.remove(model)
    }

234
    pub fn get_embeddings_engine(
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
        &self,
        model: &str,
    ) -> Result<OpenAIEmbeddingsStreamingEngine, ModelManagerError> {
        self.embeddings_engines
            .read()
            .get(model)
            .cloned()
            .ok_or(ModelManagerError::ModelNotFound(model.to_string()))
    }

    pub fn get_completions_engine(
        &self,
        model: &str,
    ) -> Result<OpenAICompletionsStreamingEngine, ModelManagerError> {
        self.completion_engines
            .read()
            .get(model)
            .cloned()
            .ok_or(ModelManagerError::ModelNotFound(model.to_string()))
    }

    pub fn get_chat_completions_engine(
        &self,
        model: &str,
    ) -> Result<OpenAIChatCompletionsStreamingEngine, ModelManagerError> {
        self.chat_completion_engines
            .read()
            .get(model)
            .cloned()
            .ok_or(ModelManagerError::ModelNotFound(model.to_string()))
    }

267
268
269
270
271
272
273
274
275
276
277
    pub fn get_tensor_engine(
        &self,
        model: &str,
    ) -> Result<TensorStreamingEngine, ModelManagerError> {
        self.tensor_engines
            .read()
            .get(model)
            .cloned()
            .ok_or(ModelManagerError::ModelNotFound(model.to_string()))
    }

278
279
280
281
282
    /// Save a ModelDeploymentCard from an instance's ModelDeploymentCard key so we can fetch it later when the key is
    /// deleted.
    pub fn save_model_card(&self, key: &str, card: ModelDeploymentCard) -> anyhow::Result<()> {
        self.cards.lock().insert(key.to_string(), card);
        Ok(())
283
284
    }

285
286
287
    /// Remove and return model card for this instance's etcd key. We do this when the instance stops.
    pub fn remove_model_card(&self, key: &str) -> Option<ModelDeploymentCard> {
        self.cards.lock().remove(key)
288
289
290
291
    }

    pub async fn kv_chooser_for(
        &self,
292
        endpoint: &Endpoint,
293
        kv_cache_block_size: u32,
294
        kv_router_config: Option<KvRouterConfig>,
295
    ) -> anyhow::Result<Arc<KvRouter>> {
296
        let endpoint_path = endpoint.path();
297

298
        if let Some(kv_chooser) = self.get_kv_chooser(&endpoint_path) {
299
300
301
            // Check if the existing router has a different block size
            if kv_chooser.block_size() != kv_cache_block_size {
                tracing::warn!(
302
                    endpoint = %endpoint_path,
303
304
                    existing_block_size = %kv_chooser.block_size(),
                    requested_block_size = %kv_cache_block_size,
305
                    "KV Router block size mismatch! Endpoint is requesting a different kv_cache_block_size than the existing router. \
306
307
308
                     This will cause routing to fail silently. Consider using the same block size or restarting the router."
                );
            }
309
310
311
            return Ok(kv_chooser);
        }

312
313
        let client = endpoint.client().await?;
        let store = endpoint.component().drt().store();
314
315
316
        let router_bucket = store
            .get_or_create_bucket(KV_ROUTERS_ROOT_PATH, None)
            .await?;
317
        let router_uuid = uuid::Uuid::new_v4();
318
        let router_key = Key::from_raw(format!("{}/{router_uuid}", endpoint.path()));
319
320
321
        let json_router_config = serde_json::to_vec_pretty(&kv_router_config.unwrap_or_default())?;
        router_bucket
            .insert(&router_key, json_router_config.into(), 0)
322
323
            .await?;

324
        let selector = Box::new(DefaultWorkerSelector::new(kv_router_config));
325
        let chooser = KvRouter::new(
326
327
            endpoint.clone(),
            client,
328
329
            kv_cache_block_size,
            Some(selector),
330
            kv_router_config,
331
            router_uuid.to_string(),
332
333
        )
        .await?;
334
335
336
        let new_kv_chooser = Arc::new(chooser);
        self.kv_choosers
            .lock()
337
            .insert(endpoint_path, new_kv_chooser.clone());
338
339
        Ok(new_kv_chooser)
    }
340

341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
    fn get_kv_chooser(&self, service_name: &str) -> Option<Arc<KvRouter>> {
        self.kv_choosers.lock().get(service_name).cloned()
    }

    /// Register a prefill router for a decode model. Returns a receiver that will be
    /// activated when the corresponding prefill model is discovered.
    /// Returns None if the decode model was already registered.
    pub fn register_prefill_router(
        &self,
        model_name: String,
    ) -> Option<oneshot::Receiver<Endpoint>> {
        let mut activators = self.prefill_router_activators.lock();

        match activators.remove(&model_name) {
            Some(PrefillActivationState::PrefillReady(rx)) => {
                // Prefill endpoint already arrived - rx will immediately resolve
                tracing::debug!(
                    model_name = %model_name,
                    "Prefill endpoint already available, returning receiver with endpoint"
                );
                Some(rx)
            }
            Some(PrefillActivationState::DecodeWaiting(tx)) => {
                // Decode already registered - this shouldn't happen, restore state and return None
                tracing::error!(
                    model_name = %model_name,
                    "Decode model already registered for this prefill router"
                );
                activators.insert(model_name, PrefillActivationState::DecodeWaiting(tx));
                None
            }
            None => {
                // New registration: create tx/rx pair, store sender and return receiver
                let (tx, rx) = oneshot::channel();
                activators.insert(
                    model_name.clone(),
                    PrefillActivationState::DecodeWaiting(tx),
                );
                tracing::debug!(
                    model_name = %model_name,
                    "No prefill endpoint available yet, storing sender for future activation"
                );
                Some(rx)
            }
        }
    }

    /// Activate a prefill router by sending the endpoint through the oneshot channel.
    /// If no decode model has registered yet, stores the endpoint for future retrieval.
    pub fn activate_prefill_router(
        &self,
        model_name: &str,
        endpoint: Endpoint,
    ) -> anyhow::Result<()> {
        let mut activators = self.prefill_router_activators.lock();

        match activators.remove(model_name) {
            Some(PrefillActivationState::DecodeWaiting(sender)) => {
                // Decode model already registered
                sender.send(endpoint).map_err(|_| {
                    anyhow::anyhow!(
                        "Failed to send endpoint to prefill router activator for model: {}",
                        model_name
                    )
                })?;

                tracing::info!(
                    model_name = %model_name,
                    "Activated prefill router for already-registered decode model"
                );

                Ok(())
            }
            Some(PrefillActivationState::PrefillReady(_)) => {
                // Prefill already activated - this shouldn't happen
                anyhow::bail!("Prefill router for model {} already activated", model_name);
            }
            None => {
                // Decode model not registered yet - create pair and immediately send endpoint
                let (tx, rx) = oneshot::channel();

                tx.send(endpoint).map_err(|_| {
                    anyhow::anyhow!("Failed to send endpoint for prefill model: {}", model_name)
                })?;

                // Store the receiver for when decode model registers
                activators.insert(
                    model_name.to_string(),
                    PrefillActivationState::PrefillReady(rx),
                );

                tracing::info!(
                    model_name = %model_name,
                    "Stored prefill endpoint for future decode model registration"
                );

                Ok(())
            }
        }
440
441
    }

442
    pub fn get_model_tool_call_parser(&self, model: &str) -> Option<String> {
443
        self.cards
444
445
            .lock()
            .values()
446
447
            .find(|c| c.display_name == model)
            .and_then(|c| c.runtime_config.tool_call_parser.as_ref())
448
            .map(|parser| parser.to_string())
449
    }
450
451
452
453
454
455
456
457
458

    /// Creates parsing options with tool call parser and reasoning parser for the specified model.
    /// Currently reasoning parser is not implemented (returns None).
    pub fn get_parsing_options(&self, model: &str) -> crate::protocols::openai::ParsingOptions {
        let tool_call_parser = self.get_model_tool_call_parser(model);
        let reasoning_parser = None; // TODO: Implement reasoning parser

        crate::protocols::openai::ParsingOptions::new(tool_call_parser, reasoning_parser)
    }
459
460
461
462
463
464
}

pub struct ModelEngines<E> {
    /// Optional default model name
    default: Option<String>,
    engines: HashMap<String, E>,
465
466
467
    /// Key: Model name, value: Checksum of the ModelDeploymentCard. New instances must have the
    /// same card.
    checksums: HashMap<String, String>,
468
469
470
471
472
473
474
}

impl<E> Default for ModelEngines<E> {
    fn default() -> Self {
        Self {
            default: None,
            engines: HashMap::new(),
475
            checksums: HashMap::new(),
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
        }
    }
}

impl<E> ModelEngines<E> {
    #[allow(dead_code)]
    fn set_default(&mut self, model: &str) {
        self.default = Some(model.to_string());
    }

    #[allow(dead_code)]
    fn clear_default(&mut self) {
        self.default = None;
    }

491
    fn add(&mut self, model: &str, checksum: &str, engine: E) -> Result<(), ModelManagerError> {
492
493
494
495
        if self.engines.contains_key(model) {
            return Err(ModelManagerError::ModelAlreadyExists(model.to_string()));
        }
        self.engines.insert(model.to_string(), engine);
496
497
        self.checksums
            .insert(model.to_string(), checksum.to_string());
498
499
500
501
502
503
504
        Ok(())
    }

    fn remove(&mut self, model: &str) -> Result<(), ModelManagerError> {
        if self.engines.remove(model).is_none() {
            return Err(ModelManagerError::ModelNotFound(model.to_string()));
        }
505
        let _ = self.checksums.remove(model);
506
507
508
509
510
511
512
513
514
515
516
517
518
519
        Ok(())
    }

    fn get(&self, model: &str) -> Option<&E> {
        self.engines.get(model)
    }

    fn contains(&self, model: &str) -> bool {
        self.engines.contains_key(model)
    }

    pub fn list(&self) -> Vec<String> {
        self.engines.keys().map(|k| k.to_owned()).collect()
    }
520
521
522
523
524
525

    /// Returns a newly allocated String for called convenience. All the places I use
    /// this I need a String.
    pub fn checksum(&self, model: &str) -> Option<String> {
        self.checksums.get(model).map(|s| s.to_string())
    }
526
}