grpc.rs 5.02 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, RouterConfig, input::common},
GuanLuo's avatar
GuanLuo committed
10
    grpc::service::kserve,
11
    namespace::is_global_namespace,
GuanLuo's avatar
GuanLuo committed
12
13
14
15
16
    types::openai::{
        chat_completions::{NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse},
        completions::{NvCreateCompletionRequest, NvCreateCompletionResponse},
    },
};
17
use dynamo_runtime::DistributedRuntime;
GuanLuo's avatar
GuanLuo committed
18
19

/// Build and run an KServe gRPC service
20
21
22
23
pub async fn run(
    distributed_runtime: DistributedRuntime,
    engine_config: EngineConfig,
) -> anyhow::Result<()> {
24
    let grpc_service_builder = kserve::KserveService::builder()
GuanLuo's avatar
GuanLuo committed
25
26
27
28
        .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 {
29
        EngineConfig::Dynamic { ref model, .. } => {
GuanLuo's avatar
GuanLuo committed
30
            let grpc_service = grpc_service_builder.build()?;
31
            let router_config = model.router_config();
32
            // Listen for models registering themselves, add them to gRPC service
33
            let namespace = model.namespace().unwrap_or("");
34
35
36
37
38
39
            let target_namespace = if is_global_namespace(namespace) {
                None
            } else {
                Some(namespace.to_string())
            };
            run_watcher(
40
                distributed_runtime.clone(),
41
                grpc_service.state().manager_clone(),
42
                router_config.clone(),
43
44
45
                target_namespace,
            )
            .await?;
GuanLuo's avatar
GuanLuo committed
46
47
            grpc_service
        }
48
        EngineConfig::InProcessText { engine, model, .. } => {
GuanLuo's avatar
GuanLuo committed
49
50
51
            let grpc_service = grpc_service_builder.build()?;
            let engine = Arc::new(StreamingEngineAdapter::new(engine));
            let manager = grpc_service.model_manager();
52
53
54
            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
55
56
            grpc_service
        }
57
        EngineConfig::InProcessTokens {
GuanLuo's avatar
GuanLuo committed
58
59
60
61
62
63
            engine: inner_engine,
            model,
            ..
        } => {
            let grpc_service = grpc_service_builder.build()?;
            let manager = grpc_service.model_manager();
64
            let checksum = model.card().mdcsum();
GuanLuo's avatar
GuanLuo committed
65

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

            let cmpl_pipeline = common::build_pipeline::<
                NvCreateCompletionRequest,
                NvCreateCompletionResponse,
78
            >(model.card(), inner_engine, tokenizer_hf)
GuanLuo's avatar
GuanLuo committed
79
            .await?;
80
            manager.add_completions_model(model.service_name(), checksum, cmpl_pipeline)?;
GuanLuo's avatar
GuanLuo committed
81
82
83
            grpc_service
        }
    };
84
85
86
87
88
89
90
91
92
93
94
95

    // 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)
    )?;

96
    distributed_runtime.shutdown(); // Cancel primary token
GuanLuo's avatar
GuanLuo committed
97
98
99
    Ok(())
}

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

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

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

    Ok(())
}