"docs/templates/component-guide.md" did not exist on "dd6c399565fe203898e14f1d92c87be35f07f24f"
grpc.rs 5.96 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
GuanLuo's avatar
GuanLuo committed
2
3
4
5
6
// SPDX-License-Identifier: Apache-2.0

use std::sync::Arc;

use crate::{
7
    discovery::{ModelManager, ModelWatcher},
GuanLuo's avatar
GuanLuo committed
8
    engines::StreamingEngineAdapter,
9
    entrypoint::{EngineConfig, RouterConfig, input::common},
GuanLuo's avatar
GuanLuo committed
10
    grpc::service::kserve,
11
    http::service::metrics::Metrics,
12
    namespace::NamespaceFilter,
GuanLuo's avatar
GuanLuo committed
13
14
15
16
17
    types::openai::{
        chat_completions::{NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse},
        completions::{NvCreateCompletionRequest, NvCreateCompletionResponse},
    },
};
18
use dynamo_runtime::DistributedRuntime;
GuanLuo's avatar
GuanLuo committed
19
20

/// Build and run an KServe gRPC service
21
22
23
24
pub async fn run(
    distributed_runtime: DistributedRuntime,
    engine_config: EngineConfig,
) -> anyhow::Result<()> {
25
    let mut grpc_service_builder = kserve::KserveService::builder()
GuanLuo's avatar
GuanLuo committed
26
        .port(engine_config.local_model().http_port()) // [WIP] generalize port..
27
        .http_cancel_token(Some(distributed_runtime.primary_token()))
GuanLuo's avatar
GuanLuo committed
28
29
        .with_request_template(engine_config.local_model().request_template());

30
31
32
33
34
    // Set HTTP metrics port if provided (for parallel test execution)
    if let Some(http_metrics_port) = engine_config.local_model().http_metrics_port() {
        grpc_service_builder = grpc_service_builder.http_metrics_port(http_metrics_port);
    }

GuanLuo's avatar
GuanLuo committed
35
    let grpc_service = match engine_config {
36
37
38
39
40
        EngineConfig::Dynamic {
            ref model,
            ref prefill_load_estimator,
            ..
        } => {
GuanLuo's avatar
GuanLuo committed
41
            let grpc_service = grpc_service_builder.build()?;
42
            let router_config = model.router_config();
43
            let migration_limit = model.migration_limit();
44
            let migration_max_seq_len = model.migration_max_seq_len();
45
            // Listen for models registering themselves, add them to gRPC service
46
47
48
49
            let namespace_filter = NamespaceFilter::from_namespace_and_prefix(
                model.namespace(),
                model.namespace_prefix(),
            );
50
            run_watcher(
51
                distributed_runtime.clone(),
52
                grpc_service.state().manager_clone(),
53
                router_config.clone(),
54
                migration_limit,
55
                migration_max_seq_len,
56
                namespace_filter,
57
                prefill_load_estimator.clone(),
58
59
            )
            .await?;
GuanLuo's avatar
GuanLuo committed
60
61
            grpc_service
        }
62
        EngineConfig::InProcessText { engine, model, .. } => {
GuanLuo's avatar
GuanLuo committed
63
64
65
            let grpc_service = grpc_service_builder.build()?;
            let engine = Arc::new(StreamingEngineAdapter::new(engine));
            let manager = grpc_service.model_manager();
66
67
68
            let checksum = model.card().mdcsum();
            manager.add_completions_model(model.service_name(), checksum, engine.clone())?;
            manager.add_chat_completions_model(model.service_name(), checksum, engine)?;
GuanLuo's avatar
GuanLuo committed
69
70
            grpc_service
        }
71
        EngineConfig::InProcessTokens {
GuanLuo's avatar
GuanLuo committed
72
73
74
75
76
77
            engine: inner_engine,
            model,
            ..
        } => {
            let grpc_service = grpc_service_builder.build()?;
            let manager = grpc_service.model_manager();
78
            let checksum = model.card().mdcsum();
GuanLuo's avatar
GuanLuo committed
79

Nikita's avatar
Nikita committed
80
81
82
83
84
85
            let tokenizer = model.card().tokenizer()?;
            let chat_pipeline = common::build_pipeline::<
                NvCreateChatCompletionRequest,
                NvCreateChatCompletionStreamResponse,
            >(model.card(), inner_engine.clone(), tokenizer.clone())
            .await?;
86
            manager.add_chat_completions_model(model.service_name(), checksum, chat_pipeline)?;
GuanLuo's avatar
GuanLuo committed
87
88
89
90

            let cmpl_pipeline = common::build_pipeline::<
                NvCreateCompletionRequest,
                NvCreateCompletionResponse,
Nikita's avatar
Nikita committed
91
            >(model.card(), inner_engine, tokenizer)
GuanLuo's avatar
GuanLuo committed
92
            .await?;
93
            manager.add_completions_model(model.service_name(), checksum, cmpl_pipeline)?;
GuanLuo's avatar
GuanLuo committed
94
95
96
            grpc_service
        }
    };
97
98
99
100
101
102
103
104
105
106
107
108

    // Run both HTTP (for metrics) and gRPC servers concurrently
    let http_service = grpc_service.http_service().clone();
    let shutdown_token = distributed_runtime.primary_token();

    // Wait for both servers to complete, propagating the first error if any occurs
    // Both tasks should run indefinitely until cancelled by the shutdown token
    tokio::try_join!(
        grpc_service.run(shutdown_token.clone()),
        http_service.run(shutdown_token)
    )?;

109
    distributed_runtime.shutdown(); // Cancel primary token
GuanLuo's avatar
GuanLuo committed
110
111
112
    Ok(())
}

113
/// Spawns a task that watches for new models in store,
GuanLuo's avatar
GuanLuo committed
114
115
116
117
/// and registers them with the ModelManager so that the HTTP service can use them.
async fn run_watcher(
    runtime: DistributedRuntime,
    model_manager: Arc<ModelManager>,
118
    router_config: RouterConfig,
119
    migration_limit: u32,
120
    migration_max_seq_len: Option<u32>,
121
    namespace_filter: NamespaceFilter,
122
    prefill_load_estimator: Option<Arc<dyn dynamo_kv_router::PrefillLoadEstimator>>,
GuanLuo's avatar
GuanLuo committed
123
) -> anyhow::Result<()> {
124
125
    // Create metrics for migration tracking (not exposed via /metrics in gRPC mode)
    let metrics = Arc::new(Metrics::new());
126
127
128
129
130
    let watch_obj = ModelWatcher::new(
        runtime.clone(),
        model_manager,
        router_config,
        migration_limit,
131
        migration_max_seq_len,
132
        None,
133
        prefill_load_estimator,
134
135
        metrics,
    );
136
    tracing::debug!("Waiting for remote model");
137
138
139
140
141
142
143
    let discovery = runtime.discovery();
    let discovery_stream = discovery
        .list_and_watch(
            dynamo_runtime::discovery::DiscoveryQuery::AllModels,
            Some(runtime.primary_token()),
        )
        .await?;
GuanLuo's avatar
GuanLuo committed
144
145
146
147
148

    // [gluo NOTE] This is different from http::run_watcher where it alters the HTTP service
    // endpoint being exposed, gRPC doesn't have the same concept as the KServe service
    // only has one kind of inference endpoint.

149
    // Pass the discovery stream to the watcher
GuanLuo's avatar
GuanLuo committed
150
    let _watcher_task = tokio::spawn(async move {
151
        watch_obj.watch(discovery_stream, namespace_filter).await;
GuanLuo's avatar
GuanLuo committed
152
153
154
155
    });

    Ok(())
}