common.rs 10.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

16
17
use std::pin::Pin;

18
use dynamo_llm::{
19
    backend::{Backend, ExecutionContext},
20
    engines::StreamingEngineAdapter,
21
    http::service::discovery::ModelNetworkName,
22
    kv_router::{scheduler::DefaultWorkerSelector, KvPushRouter, KvRouter},
23
    model_card::ModelDeploymentCard,
24
    model_type::ModelType,
25
    preprocessor::OpenAIPreprocessor,
26
    protocols::common::llm_backend::{BackendInput, BackendOutput, LLMEngineOutput},
27
28
29
30
31
32
33
34
35
    types::{
        openai::chat_completions::{
            NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse,
            OpenAIChatCompletionsStreamingEngine,
        },
        Annotated,
    },
};
use dynamo_runtime::{
36
    engine::{AsyncEngineStream, Data},
37
    pipeline::{
38
39
        Context, ManyOut, Operator, PushRouter, SegmentSource, ServiceBackend, ServiceFrontend,
        SingleIn, Source,
40
    },
41
42
43
44
    DistributedRuntime, Runtime,
};
use std::sync::Arc;

45
46
use crate::{flags::RouterMode, EngineConfig, Flags};

47
48
49
50
51
52
53
pub struct PreparedEngine {
    pub service_name: String,
    pub engine: OpenAIChatCompletionsStreamingEngine,
    pub inspect_template: bool,
    pub _cache_dir: Option<tempfile::TempDir>,
}

54
/// Turns an EngineConfig into an OpenAI chat-completions and completions supported StreamingEngine.
55
56
pub async fn prepare_engine(
    runtime: Runtime,
57
    flags: Flags,
58
    engine_config: EngineConfig,
59
) -> anyhow::Result<PreparedEngine> {
60
61
62
63
64
    match engine_config {
        EngineConfig::Dynamic(endpoint_id) => {
            let distributed_runtime = DistributedRuntime::from_settings(runtime.clone()).await?;

            let endpoint = distributed_runtime
65
66
67
                .namespace(endpoint_id.namespace.clone())?
                .component(endpoint_id.component.clone())?
                .endpoint(endpoint_id.name.clone());
68

69
            let client = endpoint.client().await?;
70
            let mut cache_dir = None;
71

72
            tracing::info!("Waiting for remote model..");
73

74
75
76
            let remote_endpoints = client.wait_for_endpoints().await?;
            debug_assert!(!remote_endpoints.is_empty());
            tracing::info!(count = remote_endpoints.len(), "Model(s) discovered");
77

78
79
80
81
            let network_name: ModelNetworkName = (&remote_endpoints[0]).into();
            let Some(etcd_client) = distributed_runtime.etcd_client() else {
                anyhow::bail!("Cannot run distributed components without etcd");
            };
82
83
            let network_entry = network_name.load_entry(&etcd_client).await?;
            let mut card = network_entry.load_mdc(endpoint_id, &etcd_client).await?;
84

85
86
87
88
89
90
91
            let engine: OpenAIChatCompletionsStreamingEngine = match network_entry.model_type {
                ModelType::Backend => {
                    // Download tokenizer.json etc to local disk
                    cache_dir = Some(
                        card.move_from_nats(distributed_runtime.nats_client())
                            .await?,
                    );
92

93
94
95
96
97
98
99
100
101
102
103
104
                    // The backend doesn't mind what we expose to the user (chat or
                    // completions), and this function is only used by text and batch input so
                    // the user doesn't see the HTTP request. So use Chat.
                    let frontend = SegmentSource::<
                        SingleIn<NvCreateChatCompletionRequest>,
                        ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>,
                    >::new();
                    let preprocessor = OpenAIPreprocessor::new(card.clone()).await?.into_operator();
                    let backend = Backend::from_mdc(card.clone()).await?.into_operator();
                    let router =
                        PushRouter::<BackendInput, Annotated<LLMEngineOutput>>::from_client(
                            client,
105
                            flags.router_mode.into(),
106
107
108
109
110
                        )
                        .await?;
                    let service_backend = match &flags.router_mode {
                        RouterMode::Random | RouterMode::RoundRobin => {
                            ServiceBackend::from_engine(Arc::new(router))
111
                        }
112
113
114
115
116
117
                        RouterMode::KV => {
                            let selector = Box::new(DefaultWorkerSelector {});
                            let chooser = KvRouter::new(
                                endpoint.component().clone(),
                                dynamo_llm::DEFAULT_KV_BLOCK_SIZE,
                                Some(selector),
118
                            )
119
120
121
                            .await?;
                            let kv_push_router = KvPushRouter::new(router, Arc::new(chooser));
                            ServiceBackend::from_engine(Arc::new(kv_push_router))
122
                        }
123
124
125
126
127
128
129
130
131
132
133
134
135
                    };
                    frontend
                        .link(preprocessor.forward_edge())?
                        .link(backend.forward_edge())?
                        .link(service_backend)?
                        .link(backend.backward_edge())?
                        .link(preprocessor.backward_edge())?
                        .link(frontend)?
                }
                ModelType::Chat => Arc::new(
                    PushRouter::<
                        NvCreateChatCompletionRequest,
                        Annotated<NvCreateChatCompletionStreamResponse>,
136
                    >::from_client(client, flags.router_mode.into())
137
138
139
140
141
142
143
144
145
146
147
148
149
                    .await?,
                ),
                ModelType::Completion => {
                    anyhow::bail!(
                        "text and batch input only accept remote Chat models, not Completion"
                    );
                    /*
                    Arc::new(
                        PushRouter::<
                            CompletionRequest,
                            Annotated<CompletionResponse>,
                        >::from_client(
                            client, flags.router_mode.into()
150
151
152
153
154
155
156
157
158
                            )
                            .await?,
                            )
                            */
                }
                ModelType::Embedding => {
                    anyhow::bail!(
                        "text and batch input only accept remote Chat models, not Embedding"
                    );
159
                }
160
            };
161
162
163
            // The service_name isn't used for text chat outside of logs,
            // so use the path. That avoids having to listen on etcd for model registration.
            let service_name = endpoint.subject();
164
165
166
167
168
169
            Ok(PreparedEngine {
                service_name,
                engine,
                inspect_template: false,
                _cache_dir: cache_dir,
            })
170
        }
171
172
        EngineConfig::StaticFull { engine, model } => {
            let service_name = model.service_name().to_string();
173
            tracing::debug!("Model: {service_name} with engine pre-processing");
174
            let engine = Arc::new(StreamingEngineAdapter::new(engine));
175
176
177
178
179
180
            Ok(PreparedEngine {
                service_name,
                engine,
                inspect_template: false,
                _cache_dir: None,
            })
181
182
183
        }
        EngineConfig::StaticCore {
            engine: inner_engine,
184
            model,
185
        } => {
186
187
188
            let pipeline = build_pipeline::<
                NvCreateChatCompletionRequest,
                NvCreateChatCompletionStreamResponse,
189
            >(model.card(), inner_engine)
190
            .await?;
191

192
            let service_name = model.service_name().to_string();
193
194
195
196
197
198
199
            tracing::debug!("Model: {service_name} with Dynamo pre-processing");
            Ok(PreparedEngine {
                service_name,
                engine: pipeline,
                inspect_template: true,
                _cache_dir: None,
            })
200
201
202
        }
    }
}
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

pub async fn build_pipeline<Req, Resp>(
    card: &ModelDeploymentCard,
    engine: ExecutionContext,
) -> anyhow::Result<Arc<ServiceFrontend<SingleIn<Req>, ManyOut<Annotated<Resp>>>>>
where
    Req: Data,
    Resp: Data,
    OpenAIPreprocessor: Operator<
        Context<Req>,
        Pin<Box<dyn AsyncEngineStream<Annotated<Resp>>>>,
        Context<BackendInput>,
        Pin<Box<dyn AsyncEngineStream<Annotated<BackendOutput>>>>,
    >,
{
    let frontend = ServiceFrontend::<SingleIn<Req>, ManyOut<Annotated<Resp>>>::new();
    let preprocessor = OpenAIPreprocessor::new((*card).clone())
        .await?
        .into_operator();
    let backend = Backend::from_mdc((*card).clone()).await?.into_operator();
    let engine = ServiceBackend::from_engine(engine);

    Ok(frontend
        .link(preprocessor.forward_edge())?
        .link(backend.forward_edge())?
        .link(engine)?
        .link(backend.backward_edge())?
        .link(preprocessor.backward_edge())?
        .link(frontend)?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use dynamo_llm::types::openai::{
        chat_completions::{NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse},
        completions::{CompletionRequest, CompletionResponse},
    };

    const HF_PATH: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../lib/llm/tests/data/sample-models/mock-llama-3.1-8b-instruct"
    );

    #[tokio::test]
    async fn test_build_chat_completions_pipeline_core_engine_succeeds() -> anyhow::Result<()> {
        // Create test model card
250
        let card = ModelDeploymentCard::load(HF_PATH).await?;
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
        let engine = dynamo_llm::engines::make_engine_core();

        // Build pipeline for chat completions
        let pipeline = build_pipeline::<
            NvCreateChatCompletionRequest,
            NvCreateChatCompletionStreamResponse,
        >(&card, engine)
        .await?;

        // Verify pipeline was created
        assert!(Arc::strong_count(&pipeline) >= 1);

        Ok(())
    }

    #[tokio::test]
    async fn test_build_completions_pipeline_core_engine_succeeds() -> anyhow::Result<()> {
        // Create test model card
269
        let card = ModelDeploymentCard::load(HF_PATH).await?;
270
271
272
273
274
275
276
277
278
279
280
281
        let engine = dynamo_llm::engines::make_engine_core();

        // Build pipeline for completions
        let pipeline =
            build_pipeline::<CompletionRequest, CompletionResponse>(&card, engine).await?;

        // Verify pipeline was created
        assert!(Arc::strong_count(&pipeline) >= 1);

        Ok(())
    }
}