grpc.rs 4.96 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
    engines::StreamingEngineAdapter,
9
    entrypoint::{EngineConfig, input::common},
GuanLuo's avatar
GuanLuo committed
10
11
    grpc::service::kserve,
    kv_router::KvRouterConfig,
12
    namespace::is_global_namespace,
GuanLuo's avatar
GuanLuo committed
13
14
15
16
17
    types::openai::{
        chat_completions::{NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse},
        completions::{NvCreateCompletionRequest, NvCreateCompletionResponse},
    },
};
18
use dynamo_runtime::DistributedRuntime;
19
use dynamo_runtime::pipeline::RouterMode;
GuanLuo's avatar
GuanLuo committed
20
21

/// Build and run an KServe gRPC service
22
23
24
25
pub async fn run(
    distributed_runtime: DistributedRuntime,
    engine_config: EngineConfig,
) -> anyhow::Result<()> {
26
    let grpc_service_builder = kserve::KserveService::builder()
GuanLuo's avatar
GuanLuo committed
27
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(_) => {
            let grpc_service = grpc_service_builder.build()?;
33
34
35
36
37
38
39
40
41
            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(
42
                distributed_runtime.clone(),
43
44
45
46
47
48
49
                grpc_service.state().manager_clone(),
                router_config.router_mode,
                Some(router_config.kv_router_config),
                router_config.busy_threshold,
                target_namespace,
            )
            .await?;
GuanLuo's avatar
GuanLuo committed
50
51
52
53
54
55
            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();
56
57
58
            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
59
60
61
62
63
64
65
66
67
            grpc_service
        }
        EngineConfig::StaticCore {
            engine: inner_engine,
            model,
            ..
        } => {
            let grpc_service = grpc_service_builder.build()?;
            let manager = grpc_service.model_manager();
68
            let checksum = model.card().mdcsum();
GuanLuo's avatar
GuanLuo committed
69

70
71
72
73
74
75
76
            let tokenizer_hf = model.card().tokenizer_hf()?;
            let chat_pipeline =
                common::build_pipeline::<
                    NvCreateChatCompletionRequest,
                    NvCreateChatCompletionStreamResponse,
                >(model.card(), inner_engine.clone(), tokenizer_hf.clone())
                .await?;
77
            manager.add_chat_completions_model(model.service_name(), checksum, chat_pipeline)?;
GuanLuo's avatar
GuanLuo committed
78
79
80
81

            let cmpl_pipeline = common::build_pipeline::<
                NvCreateCompletionRequest,
                NvCreateCompletionResponse,
82
            >(model.card(), inner_engine, tokenizer_hf)
GuanLuo's avatar
GuanLuo committed
83
            .await?;
84
            manager.add_completions_model(model.service_name(), checksum, cmpl_pipeline)?;
GuanLuo's avatar
GuanLuo committed
85
86
87
            grpc_service
        }
    };
88
89
90
91
    grpc_service
        .run(distributed_runtime.primary_token())
        .await?;
    distributed_runtime.shutdown(); // Cancel primary token
GuanLuo's avatar
GuanLuo committed
92
93
94
    Ok(())
}

95
/// Spawns a task that watches for new models in store,
GuanLuo's avatar
GuanLuo committed
96
97
98
99
100
101
102
/// and registers them with the ModelManager so that the HTTP service can use them.
async fn run_watcher(
    runtime: DistributedRuntime,
    model_manager: Arc<ModelManager>,
    router_mode: RouterMode,
    kv_router_config: Option<KvRouterConfig>,
    busy_threshold: Option<f64>,
103
    target_namespace: Option<String>,
GuanLuo's avatar
GuanLuo committed
104
105
) -> anyhow::Result<()> {
    let watch_obj = ModelWatcher::new(
106
        runtime.clone(),
GuanLuo's avatar
GuanLuo committed
107
108
109
110
111
        model_manager,
        router_mode,
        kv_router_config,
        busy_threshold,
    );
112
    tracing::debug!("Waiting for remote model");
113
114
115
116
117
118
119
    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
120
121
122
123
124

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

125
    // Pass the discovery stream to the watcher
GuanLuo's avatar
GuanLuo committed
126
    let _watcher_task = tokio::spawn(async move {
127
128
129
        watch_obj
            .watch(discovery_stream, target_namespace.as_deref())
            .await;
GuanLuo's avatar
GuanLuo committed
130
131
132
133
    });

    Ok(())
}