grpc.rs 7.38 KB
Newer Older
GuanLuo's avatar
GuanLuo committed
1
2
3
4
5
6
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::sync::Arc;

use crate::{
7
    discovery::{ModelManager, ModelWatcher},
GuanLuo's avatar
GuanLuo committed
8
9
10
11
    engines::StreamingEngineAdapter,
    entrypoint::{self, EngineConfig, input::common},
    grpc::service::kserve,
    kv_router::KvRouterConfig,
12
    model_card,
13
    namespace::is_global_namespace,
GuanLuo's avatar
GuanLuo committed
14
15
16
17
18
    types::openai::{
        chat_completions::{NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse},
        completions::{NvCreateCompletionRequest, NvCreateCompletionResponse},
    },
};
19
20
use dynamo_runtime::pipeline::RouterMode;
use dynamo_runtime::{DistributedRuntime, storage::key_value_store::KeyValueStoreManager};
GuanLuo's avatar
GuanLuo committed
21
22

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

    let grpc_service = match engine_config {
        EngineConfig::Dynamic(_) => {
33
            let store = Arc::new(distributed_runtime.store().clone());
GuanLuo's avatar
GuanLuo committed
34
            let grpc_service = grpc_service_builder.build()?;
35
36
37
38
39
40
41
42
43
            let router_config = engine_config.local_model().router_config();
            // Listen for models registering themselves, add them to gRPC service
            let namespace = engine_config.local_model().namespace().unwrap_or("");
            let target_namespace = if is_global_namespace(namespace) {
                None
            } else {
                Some(namespace.to_string())
            };
            run_watcher(
44
                distributed_runtime.clone(),
45
46
47
48
49
50
51
52
                grpc_service.state().manager_clone(),
                store,
                router_config.router_mode,
                Some(router_config.kv_router_config),
                router_config.busy_threshold,
                target_namespace,
            )
            .await?;
GuanLuo's avatar
GuanLuo committed
53
54
55
56
            grpc_service
        }
        EngineConfig::StaticRemote(local_model) => {
            let card = local_model.card();
57
            let checksum = card.mdcsum();
GuanLuo's avatar
GuanLuo committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
            let router_mode = local_model.router_config().router_mode;

            let grpc_service = grpc_service_builder.build()?;
            let manager = grpc_service.model_manager();

            let endpoint_id = local_model.endpoint_id();
            let component = distributed_runtime
                .namespace(&endpoint_id.namespace)?
                .component(&endpoint_id.component)?;
            let client = component.endpoint(&endpoint_id.name).client().await?;

            let kv_chooser = if router_mode == RouterMode::KV {
                Some(
                    manager
                        .kv_chooser_for(
                            &component,
                            card.kv_cache_block_size,
                            Some(local_model.router_config().kv_router_config),
                        )
                        .await?,
                )
            } else {
                None
            };

83
            let tokenizer_hf = card.tokenizer_hf()?;
GuanLuo's avatar
GuanLuo committed
84
85
86
            let chat_engine = entrypoint::build_routed_pipeline::<
                NvCreateChatCompletionRequest,
                NvCreateChatCompletionStreamResponse,
87
88
89
90
91
92
93
            >(
                card,
                &client,
                router_mode,
                None,
                kv_chooser.clone(),
                tokenizer_hf.clone(),
94
                None, // No prefill chooser in grpc static mode
95
            )
GuanLuo's avatar
GuanLuo committed
96
            .await?;
97
98
99
100
101
            manager.add_chat_completions_model(
                local_model.display_name(),
                checksum,
                chat_engine,
            )?;
GuanLuo's avatar
GuanLuo committed
102

103
104
105
106
107
108
109
110
111
112
113
114
115
            let completions_engine = entrypoint::build_routed_pipeline::<
                NvCreateCompletionRequest,
                NvCreateCompletionResponse,
            >(
                card,
                &client,
                router_mode,
                None,
                kv_chooser,
                tokenizer_hf,
                None, // No prefill chooser in grpc static mode
            )
            .await?;
116
117
118
119
120
            manager.add_completions_model(
                local_model.display_name(),
                checksum,
                completions_engine,
            )?;
GuanLuo's avatar
GuanLuo committed
121
122
123
124
125
126
127

            grpc_service
        }
        EngineConfig::StaticFull { engine, model, .. } => {
            let grpc_service = grpc_service_builder.build()?;
            let engine = Arc::new(StreamingEngineAdapter::new(engine));
            let manager = grpc_service.model_manager();
128
129
130
            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
131
132
133
134
135
136
137
138
139
            grpc_service
        }
        EngineConfig::StaticCore {
            engine: inner_engine,
            model,
            ..
        } => {
            let grpc_service = grpc_service_builder.build()?;
            let manager = grpc_service.model_manager();
140
            let checksum = model.card().mdcsum();
GuanLuo's avatar
GuanLuo committed
141

142
143
144
145
146
147
148
            let tokenizer_hf = model.card().tokenizer_hf()?;
            let chat_pipeline =
                common::build_pipeline::<
                    NvCreateChatCompletionRequest,
                    NvCreateChatCompletionStreamResponse,
                >(model.card(), inner_engine.clone(), tokenizer_hf.clone())
                .await?;
149
            manager.add_chat_completions_model(model.service_name(), checksum, chat_pipeline)?;
GuanLuo's avatar
GuanLuo committed
150
151
152
153

            let cmpl_pipeline = common::build_pipeline::<
                NvCreateCompletionRequest,
                NvCreateCompletionResponse,
154
            >(model.card(), inner_engine, tokenizer_hf)
GuanLuo's avatar
GuanLuo committed
155
            .await?;
156
            manager.add_completions_model(model.service_name(), checksum, cmpl_pipeline)?;
GuanLuo's avatar
GuanLuo committed
157
158
159
            grpc_service
        }
    };
160
161
162
163
    grpc_service
        .run(distributed_runtime.primary_token())
        .await?;
    distributed_runtime.shutdown(); // Cancel primary token
GuanLuo's avatar
GuanLuo committed
164
165
166
    Ok(())
}

167
/// Spawns a task that watches for new models in store,
GuanLuo's avatar
GuanLuo committed
168
/// and registers them with the ModelManager so that the HTTP service can use them.
169
#[allow(clippy::too_many_arguments)]
GuanLuo's avatar
GuanLuo committed
170
171
172
async fn run_watcher(
    runtime: DistributedRuntime,
    model_manager: Arc<ModelManager>,
173
    store: Arc<KeyValueStoreManager>,
GuanLuo's avatar
GuanLuo committed
174
175
176
    router_mode: RouterMode,
    kv_router_config: Option<KvRouterConfig>,
    busy_threshold: Option<f64>,
177
    target_namespace: Option<String>,
GuanLuo's avatar
GuanLuo committed
178
) -> anyhow::Result<()> {
179
    let cancellation_token = runtime.primary_token();
GuanLuo's avatar
GuanLuo committed
180
181
182
183
184
185
186
    let watch_obj = ModelWatcher::new(
        runtime,
        model_manager,
        router_mode,
        kv_router_config,
        busy_threshold,
    );
187
188
    tracing::debug!("Waiting for remote model");
    let (_, receiver) = store.watch(model_card::ROOT_PATH, None, cancellation_token);
GuanLuo's avatar
GuanLuo committed
189
190
191
192
193
194
195

    // [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.

    // Pass the sender to the watcher
    let _watcher_task = tokio::spawn(async move {
196
        watch_obj.watch(receiver, target_namespace.as_deref()).await;
GuanLuo's avatar
GuanLuo committed
197
198
199
200
    });

    Ok(())
}