watcher.rs 26.2 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

Ryan Olson's avatar
Ryan Olson committed
4
use std::sync::Arc;
5
use tokio::sync::Notify;
6
use tokio::sync::mpsc::Sender;
7

8
use anyhow::Context as _;
9
use futures::StreamExt;
Ryan Olson's avatar
Ryan Olson committed
10

Neelay Shah's avatar
Neelay Shah committed
11
use dynamo_runtime::{
12
    DistributedRuntime,
13
    discovery::{DiscoveryEvent, DiscoveryInstance, DiscoveryQuery, DiscoveryStream},
14
    pipeline::{
15
16
        ManyOut, Operator, RouterMode, SegmentSource, ServiceBackend, SingleIn, Source,
        network::egress::push_router::PushRouter,
17
    },
18
    protocols::{EndpointId, annotated::Annotated},
19
};
Ryan Olson's avatar
Ryan Olson committed
20

21
22
use crate::{
    backend::Backend,
23
24
    entrypoint::{self, RouterConfig},
    kv_router::PrefillRouter,
25
    model_card::ModelDeploymentCard,
26
27
    model_type::{ModelInput, ModelType},
    preprocessor::{OpenAIPreprocessor, PreprocessedEmbeddingRequest, prompt::PromptFormatter},
28
29
30
31
32
33
34
35
36
    protocols::{
        common::llm_backend::EmbeddingsEngineOutput,
        openai::{
            chat_completions::{
                NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse,
            },
            completions::{NvCreateCompletionRequest, NvCreateCompletionResponse},
            embeddings::{NvCreateEmbeddingRequest, NvCreateEmbeddingResponse},
        },
37
        tensor::{NvCreateTensorRequest, NvCreateTensorResponse},
38
39
    },
};
40

41
use super::ModelManager;
42
use crate::namespace::is_global_namespace;
43

44
#[derive(Debug, Clone)]
45
pub enum ModelUpdate {
46
47
    Added(ModelDeploymentCard),
    Removed(ModelDeploymentCard),
48
49
}

50
pub struct ModelWatcher {
51
    manager: Arc<ModelManager>,
52
    drt: DistributedRuntime,
53
    router_config: RouterConfig,
54
    notify_on_model: Notify,
55
    model_update_tx: Option<Sender<ModelUpdate>>,
Ryan Olson's avatar
Ryan Olson committed
56
57
}

58
59
60
61
const ALL_MODEL_TYPES: &[ModelType] = &[
    ModelType::Chat,
    ModelType::Completions,
    ModelType::Embedding,
62
    ModelType::TensorBased,
63
    ModelType::Prefill,
64
];
65

66
impl ModelWatcher {
67
    pub fn new(
68
        runtime: DistributedRuntime,
69
        model_manager: Arc<ModelManager>,
70
        router_config: RouterConfig,
71
72
    ) -> ModelWatcher {
        Self {
73
            manager: model_manager,
74
            drt: runtime,
75
            router_config,
76
            notify_on_model: Notify::new(),
77
            model_update_tx: None,
78
        }
79
    }
Ryan Olson's avatar
Ryan Olson committed
80

81
82
83
84
    pub fn set_notify_on_model_update(&mut self, tx: Sender<ModelUpdate>) {
        self.model_update_tx = Some(tx);
    }

85
86
87
88
89
90
91
92
93
94
95
    /// Wait until we have at least one chat completions model and return it's name.
    pub async fn wait_for_chat_model(&self) -> String {
        // Loop in case it gets added and immediately deleted
        loop {
            if let Some(model_name) = self.manager.list_chat_completions_models().first() {
                return model_name.to_owned();
            }
            self.notify_on_model.notified().await
        }
    }

96
    /// Common watch logic with optional namespace filtering
97
98
99
100
101
    pub async fn watch(
        &self,
        mut discovery_stream: DiscoveryStream,
        target_namespace: Option<&str>,
    ) {
102
        let global_namespace = target_namespace.is_none_or(is_global_namespace);
103

104
105
106
107
108
109
110
111
112
        while let Some(result) = discovery_stream.next().await {
            let event = match result {
                Ok(event) => event,
                Err(err) => {
                    tracing::error!(%err, "Error in discovery stream");
                    continue;
                }
            };

113
            match event {
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
                DiscoveryEvent::Added(instance) => {
                    // Extract EndpointId, instance_id, and card from the discovery instance
                    let (endpoint_id, instance_id, mut card) = match &instance {
                        DiscoveryInstance::Model {
                            namespace,
                            component,
                            endpoint,
                            instance_id,
                            ..
                        } => {
                            let eid = EndpointId {
                                namespace: namespace.clone(),
                                component: component.clone(),
                                name: endpoint.clone(),
                            };

                            match instance.deserialize_model::<ModelDeploymentCard>() {
                                Ok(card) => (eid, *instance_id, card),
                                Err(err) => {
                                    tracing::error!(%err, instance_id, "Failed to deserialize model card");
                                    continue;
                                }
                            }
                        }
                        _ => {
                            tracing::error!(
                                "Unexpected discovery instance type (expected ModelCard)"
                            );
142
143
144
                            continue;
                        }
                    };
145
146
147
148

                    // Filter by namespace if target_namespace is specified
                    if !global_namespace
                        && let Some(target_ns) = target_namespace
149
                        && endpoint_id.namespace != target_ns
150
151
                    {
                        tracing::debug!(
152
                            model_namespace = endpoint_id.namespace,
153
154
155
156
157
158
                            target_namespace = target_ns,
                            "Skipping model from different namespace"
                        );
                        continue;
                    }

159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
                    // If we already have a worker for this model, and the ModelDeploymentCard
                    // cards don't match, alert, and don't add the new instance
                    let can_add =
                        self.manager
                            .is_valid_checksum(card.model_type, card.name(), card.mdcsum());
                    if can_add.is_some_and(|is_valid| !is_valid) {
                        tracing::error!(
                            model_name = card.name(),
                            "Checksum for new model does not match existing model."
                        );

                        // TODO: mark that instance down in clients
                        // Not obvious how to do that given the current design
                        // Instances come from an `InstanceSource` in a `Client` in a `PushRouter`.
                        // Calling `report_instance_down` on the Client should do it (although
                        // needs more testing).
                        // The `PushRouter` is in `ModelMananger` (`self.manager` here), but inside
                        // interface `AsyncEngine` which only has a `generate` method.

                        continue;
                    }
180

181
182
183
184
                    // Use instance_id as the HashMap key (simpler and sufficient since keys are opaque)
                    let key = format!("{:x}", instance_id);

                    match self.handle_put(&key, &endpoint_id, &mut card).await {
185
                        Ok(()) => {
186
                            tracing::info!(
187
188
                                model_name = card.name(),
                                namespace = endpoint_id.namespace,
189
190
                                "added model"
                            );
191
                            self.notify_on_model.notify_waiters();
192
                        }
193
194
                        Err(err) => {
                            tracing::error!(
195
196
                                model_name = card.name(),
                                namespace = endpoint_id.namespace,
197
                                error = format!("{err:#}"),
198
                                "Error adding model from discovery",
199
                            );
200
201
202
                        }
                    }
                }
203
204
205
206
                DiscoveryEvent::Removed(instance_id) => {
                    // Use instance_id hex as the HashMap key (matches what we saved with)
                    let key = format!("{:x}", instance_id);

207
                    match self
208
                        .handle_delete(&key, target_namespace, global_namespace)
209
210
211
212
213
214
215
216
217
218
219
                        .await
                    {
                        Ok(Some(model_name)) => {
                            tracing::info!(model_name, "removed model");
                        }
                        Ok(None) => {
                            // There are other instances running this model, nothing to do
                        }
                        Err(e) => {
                            tracing::error!(error = %e, "error removing model");
                        }
220
                    }
221
                }
222
            }
Ryan Olson's avatar
Ryan Olson committed
223
224
225
        }
    }

226
227
    /// If the last instance running this model has gone delete it.
    /// Returns the name of the model we just deleted, if any.
228
229
    async fn handle_delete(
        &self,
230
        key: &str,
231
232
233
        target_namespace: Option<&str>,
        is_global_namespace: bool,
    ) -> anyhow::Result<Option<String>> {
234
235
        let card = match self.manager.remove_model_card(key) {
            Some(card) => card,
236
            None => {
237
                anyhow::bail!("Missing ModelDeploymentCard for {key}");
238
239
            }
        };
240
        let model_name = card.name().to_string();
241
        let active_instances = self
242
            .cards_for_model(&model_name, target_namespace, is_global_namespace)
243
244
245
            .await
            .with_context(|| model_name.clone())?;
        if !active_instances.is_empty() {
246
247
248
249
250
251
            tracing::debug!(
                model_name,
                target_namespace = ?target_namespace,
                active_instance_count = active_instances.len(),
                "Model has other active instances, not removing"
            );
252
253
            return Ok(None);
        }
254

255
        // Ignore the errors because model could be either type
256
257
258
        let chat_model_remove_err = self.manager.remove_chat_completions_model(&model_name);
        let completions_model_remove_err = self.manager.remove_completions_model(&model_name);
        let embeddings_model_remove_err = self.manager.remove_embeddings_model(&model_name);
259
        let tensor_model_remove_err = self.manager.remove_tensor_model(&model_name);
260
        let prefill_model_remove_err = self.manager.remove_prefill_model(&model_name);
261
262
263
264

        let mut chat_model_removed = false;
        let mut completions_model_removed = false;
        let mut embeddings_model_removed = false;
265
        let mut tensor_model_removed = false;
266
        let mut prefill_model_removed = false;
267
268
269
270
271
272
273
274
275
276
277

        if chat_model_remove_err.is_ok() && self.manager.list_chat_completions_models().is_empty() {
            chat_model_removed = true;
        }
        if completions_model_remove_err.is_ok() && self.manager.list_completions_models().is_empty()
        {
            completions_model_removed = true;
        }
        if embeddings_model_remove_err.is_ok() && self.manager.list_embeddings_models().is_empty() {
            embeddings_model_removed = true;
        }
278
279
280
        if tensor_model_remove_err.is_ok() && self.manager.list_tensor_models().is_empty() {
            tensor_model_removed = true;
        }
281
282
283
        if prefill_model_remove_err.is_ok() && self.manager.list_prefill_models().is_empty() {
            prefill_model_removed = true;
        }
284

285
286
287
288
        if !chat_model_removed
            && !completions_model_removed
            && !embeddings_model_removed
            && !tensor_model_removed
289
            && !prefill_model_removed
290
        {
291
            tracing::debug!(
292
                "No updates to send for model {}: chat_model_removed: {}, completions_model_removed: {}, embeddings_model_removed: {}, tensor_model_removed: {}, prefill_model_removed: {}",
293
294
295
                model_name,
                chat_model_removed,
                completions_model_removed,
296
                embeddings_model_removed,
297
298
                tensor_model_removed,
                prefill_model_removed
299
300
301
            );
        } else {
            for model_type in ALL_MODEL_TYPES {
302
                if ((chat_model_removed && *model_type == ModelType::Chat)
303
                    || (completions_model_removed && *model_type == ModelType::Completions)
304
                    || (embeddings_model_removed && *model_type == ModelType::Embedding)
305
306
                    || (tensor_model_removed && *model_type == ModelType::TensorBased)
                    || (prefill_model_removed && *model_type == ModelType::Prefill))
307
                    && let Some(tx) = &self.model_update_tx
308
                {
309
                    tx.send(ModelUpdate::Removed(card.clone())).await.ok();
310
311
312
                }
            }
        }
313

314
        Ok(Some(model_name))
315
    }
Ryan Olson's avatar
Ryan Olson committed
316

317
    // Handles a PUT event from store, this usually means adding a new model to the list of served
318
    // models.
319
320
321
322
323
324
    async fn handle_put(
        &self,
        key: &str,
        endpoint_id: &EndpointId,
        card: &mut ModelDeploymentCard,
    ) -> anyhow::Result<()> {
325
326
        card.download_config().await?;

327
        let component = self
328
329
            .drt
            .namespace(&endpoint_id.namespace)?
330
            .component(&endpoint_id.component)?;
331
332
        let endpoint = component.endpoint(&endpoint_id.name);
        let client = endpoint.client().await?;
333
334
        tracing::debug!(model_name = card.name(), "adding model");
        self.manager.save_model_card(key, card.clone())?;
335

336
337
338
339
340
341
342
343
344
345
        // Check if we should skip registration:
        // - Skip if a model with this name already exists
        // - UNLESS this is a prefill model and no prefill model exists yet for this name
        let is_new_prefill = card.model_type.supports_prefill()
            && !self
                .manager
                .list_prefill_models()
                .contains(&card.name().to_string());

        if self.manager.has_model_any(card.name()) && !is_new_prefill {
346
347
348
            tracing::debug!(
                model_name = card.name(),
                namespace = endpoint_id.namespace,
349
350
                model_type = %card.model_type,
                "New endpoint for existing model, skipping"
351
352
353
354
355
356
357
            );
            return Ok(());
        }

        if let Some(tx) = &self.model_update_tx {
            tx.send(ModelUpdate::Added(card.clone())).await.ok();
        }
358
        let checksum = card.mdcsum();
359
360
361

        if card.model_input == ModelInput::Tokens
            && (card.model_type.supports_chat() || card.model_type.supports_completions())
362
363
364
365
366
        {
            // Case 1: Tokens + (Chat OR Completions OR Both)
            // A model that expects pre-processed requests meaning it's up to us whether we
            // handle Chat or Completions requests, so handle whatever the model supports.

367
            let endpoint = component.endpoint(&endpoint_id.name);
368
            let kv_chooser = if self.router_config.router_mode == RouterMode::KV {
369
370
                Some(
                    self.manager
371
372
373
374
375
                        .kv_chooser_for(
                            &endpoint,
                            card.kv_cache_block_size,
                            Some(self.router_config.kv_router_config),
                        )
376
377
378
379
380
                        .await?,
                )
            } else {
                None
            };
381

382
            // This is expensive, we are loading ~10MiB JSON, so only do it once
383
            let tokenizer_hf = card.tokenizer_hf().context("tokenizer_hf")?;
384

385
386
387
388
389
390
391
            // Create prefill chooser once if we're building pipelines
            // Both chat and completions will share the same prefill chooser instance
            let prefill_chooser = self
                .manager
                .register_prefill_router(card.name().to_string())
                .map(|rx| {
                    // Create prefill-specific config with track_active_blocks disabled
392
                    let mut prefill_config = self.router_config.kv_router_config;
393
394
395
396
397
                    prefill_config.router_track_active_blocks = false;

                    PrefillRouter::new(
                        rx,
                        self.manager.clone(),
398
                        self.router_config.router_mode,
399
400
                        card.kv_cache_block_size,
                        Some(prefill_config),
401
                        self.router_config.enforce_disagg,
402
403
404
                    )
                });

405
            // Add chat engine only if the model supports chat
406
            if card.model_type.supports_chat() {
407
408
409
410
                let chat_engine = entrypoint::build_routed_pipeline::<
                    NvCreateChatCompletionRequest,
                    NvCreateChatCompletionStreamResponse,
                >(
411
                    card,
412
                    &client,
413
414
                    self.router_config.router_mode,
                    self.router_config.busy_threshold,
415
                    kv_chooser.clone(),
416
                    tokenizer_hf.clone(),
417
                    prefill_chooser.clone(),
418
                    self.router_config.enforce_disagg,
419
                )
420
421
                .await
                .context("build_routed_pipeline")?;
422
                self.manager
423
                    .add_chat_completions_model(card.name(), checksum, chat_engine)
424
                    .context("add_chat_completions_model")?;
425
                tracing::info!("Chat completions is ready");
426
            }
427

428
            // Add completions engine only if the model supports completions
429
            if card.model_type.supports_completions() {
430
431
                let formatter = PromptFormatter::no_op();
                let PromptFormatter::OAI(formatter) = formatter;
432
433
434
435
                let preprocessor = OpenAIPreprocessor::new_with_parts(
                    card.clone(),
                    formatter,
                    tokenizer_hf.clone(),
436
437
                )
                .context("OpenAIPreprocessor::new_with_parts")?;
438
                let completions_engine = entrypoint::build_routed_pipeline_with_preprocessor::<
439
440
441
                    NvCreateCompletionRequest,
                    NvCreateCompletionResponse,
                >(
442
                    card,
443
                    &client,
444
445
                    self.router_config.router_mode,
                    self.router_config.busy_threshold,
446
                    kv_chooser,
447
                    preprocessor,
448
                    tokenizer_hf,
449
                    prefill_chooser,
450
                    self.router_config.enforce_disagg,
451
                )
452
453
                .await
                .context("build_routed_pipeline_with_preprocessor")?;
454
                self.manager
455
                    .add_completions_model(card.name(), checksum, completions_engine)
456
                    .context("add_completions_model")?;
457
                tracing::info!("Completions is ready");
458
            }
459
460
461
462
463
464
        } else if card.model_input == ModelInput::Text && card.model_type.supports_embedding() {
            // Case: Text + Embeddings
            let push_router = PushRouter::<
                NvCreateEmbeddingRequest,
                Annotated<NvCreateEmbeddingResponse>,
            >::from_client_with_threshold(
465
                client, self.router_config.router_mode, None, None
466
467
468
469
            )
            .await?;
            let engine = Arc::new(push_router);
            self.manager
470
                .add_embeddings_model(card.name(), checksum, engine)?;
471
        } else if card.model_input == ModelInput::Text && card.model_type.supports_chat() {
472
            // Case 3: Text + Chat
473
474
475
476
477
478
479
            let push_router = PushRouter::<
                NvCreateChatCompletionRequest,
                Annotated<NvCreateChatCompletionStreamResponse>,
            >::from_client_with_threshold(
                client, self.router_config.router_mode, None, None
            )
            .await?;
480
481
            let engine = Arc::new(push_router);
            self.manager
482
                .add_chat_completions_model(card.name(), checksum, engine)?;
483
        } else if card.model_input == ModelInput::Text && card.model_type.supports_completions() {
484
485
486
487
488
            // Case 2: Text + Completions
            let push_router = PushRouter::<
                NvCreateCompletionRequest,
                Annotated<NvCreateCompletionResponse>,
            >::from_client_with_threshold(
489
                client, self.router_config.router_mode, None, None
490
491
492
493
            )
            .await?;
            let engine = Arc::new(push_router);
            self.manager
494
                .add_completions_model(card.name(), checksum, engine)?;
495
        } else if card.model_input == ModelInput::Tokens && card.model_type.supports_embedding() {
496
497
498
499
500
501
502
503
            // Case 4: Tokens + Embeddings

            // Create preprocessing pipeline similar to Backend
            let frontend = SegmentSource::<
                SingleIn<NvCreateEmbeddingRequest>,
                ManyOut<Annotated<NvCreateEmbeddingResponse>>,
            >::new();

504
            let preprocessor = OpenAIPreprocessor::new(card.clone())?.into_operator();
505
            let backend = Backend::from_mdc(card).into_operator();
506
507
508
509
510

            let router = PushRouter::<
                PreprocessedEmbeddingRequest,
                Annotated<EmbeddingsEngineOutput>,
            >::from_client_with_threshold(
511
                client, self.router_config.router_mode, None, None
512
513
514
            )
            .await?;

515
            // Note: Embeddings don't need KV routing complexity or load monitoring
516
517
518
519
520
521
522
523
524
525
526
527
            let service_backend = ServiceBackend::from_engine(Arc::new(router));

            // Link the pipeline: frontend -> preprocessor -> backend -> service_backend -> backend -> preprocessor -> frontend
            let embedding_engine = frontend
                .link(preprocessor.forward_edge())?
                .link(backend.forward_edge())?
                .link(service_backend)?
                .link(backend.backward_edge())?
                .link(preprocessor.backward_edge())?
                .link(frontend)?;

            self.manager
528
                .add_embeddings_model(card.name(), checksum, embedding_engine)?;
529
        } else if card.model_input == ModelInput::Tensor && card.model_type.supports_tensor() {
530
            // Case 5: Tensor + Tensor (non-LLM)
531
            // No KV cache concepts - not an LLM model
532
533
534
535
            let push_router = PushRouter::<
                NvCreateTensorRequest,
                Annotated<NvCreateTensorResponse>,
            >::from_client_with_threshold(
536
                client, self.router_config.router_mode, None, None
537
538
539
            )
            .await?;
            let engine = Arc::new(push_router);
540
541
            self.manager
                .add_tensor_model(card.name(), checksum, engine)?;
542
543
544
545
546
547
548
549
550
551
552
553
        } else if card.model_type.supports_prefill() {
            // Case 6: Prefill
            // Guardrail: Verify model_input is Tokens
            if card.model_input != ModelInput::Tokens {
                anyhow::bail!(
                    "Prefill models must use ModelInput::Tokens, got {}",
                    card.model_input.as_str()
                );
            }

            tracing::info!(
                model_name = card.name(),
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
                "Prefill model detected, registering and activating prefill router"
            );

            // Register prefill model for tracking (no engine needed, just lifecycle)
            self.manager
                .add_prefill_model(card.name(), checksum)
                .context("add_prefill_model")?;

            // Activate the prefill router with the endpoint for this prefill model
            let Ok(()) = self.manager.activate_prefill_router(card.name(), endpoint) else {
                tracing::warn!(
                    model_name = card.name(),
                    "Failed to activate prefill router - prefill model may already be activated"
                );
                return Ok(());
            };

            tracing::info!(
                model_name = card.name(),
                "Prefill model registered and router activated successfully"
574
            );
575
576
577
578
        } else {
            // Reject unsupported combinations
            anyhow::bail!(
                "Unsupported model configuration: {} with {} input. Supported combinations: \
579
                Tokens+(Chat|Completions|Prefill), Text+Chat, Text+Completions, Tokens+Embeddings, Tensor+TensorBased",
580
581
                card.model_type,
                card.model_input.as_str()
582
            );
583
        }
Ryan Olson's avatar
Ryan Olson committed
584

585
586
        Ok(())
    }
587

588
    /// All the registered ModelDeploymentCard with the EndpointId they are attached to, one per instance
589
    async fn all_cards(&self) -> anyhow::Result<Vec<(EndpointId, ModelDeploymentCard)>> {
590
591
        let discovery = self.drt.discovery();
        let instances = discovery.list(DiscoveryQuery::AllModels).await?;
592

593
594
595
        let mut results = Vec::with_capacity(instances.len());
        for instance in instances {
            match instance.deserialize_model::<ModelDeploymentCard>() {
596
                Ok(card) => {
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
                    // Extract EndpointId from the instance
                    let endpoint_id = match &instance {
                        dynamo_runtime::discovery::DiscoveryInstance::Model {
                            namespace,
                            component,
                            endpoint,
                            ..
                        } => EndpointId {
                            namespace: namespace.clone(),
                            component: component.clone(),
                            name: endpoint.clone(),
                        },
                        _ => {
                            tracing::error!(
                                "Unexpected discovery instance type (expected ModelCard)"
                            );
613
614
615
                            continue;
                        }
                    };
616
                    results.push((endpoint_id, card));
617
                }
618
                Err(err) => {
619
                    tracing::error!(%err, "Failed to deserialize model card");
620
621
                    continue;
                }
622
            }
623
        }
624
        Ok(results)
625
626
    }

627
    pub async fn cards_for_model(
628
629
630
631
        &self,
        model_name: &str,
        target_namespace: Option<&str>,
        is_global_namespace: bool,
632
633
634
635
    ) -> anyhow::Result<Vec<ModelDeploymentCard>> {
        let mut all = self.all_cards().await?;
        all.retain(|(endpoint_id, card)| {
            let matches_name = card.name() == model_name;
636
637
638
            let matches_namespace = match (is_global_namespace, target_namespace) {
                (true, _) => true,
                (false, None) => true,
639
                (false, Some(target_ns)) => endpoint_id.namespace == target_ns,
640
641
642
            };
            matches_name && matches_namespace
        });
643
644
645
        Ok(all.into_iter().map(|(_eid, card)| card).collect())
    }
}