lib.rs 17.3 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
use std::io::Read;
17
18
#[cfg(any(feature = "vllm", feature = "sglang"))]
use std::{future::Future, pin::Pin};
19

Neelay Shah's avatar
Neelay Shah committed
20
use dynamo_llm::{
21
22
    backend::ExecutionContext, model_card::model::ModelDeploymentCard,
    types::openai::chat_completions::OpenAIChatCompletionsStreamingEngine,
23
};
Neelay Shah's avatar
Neelay Shah committed
24
use dynamo_runtime::protocols::Endpoint;
25

26
27
mod flags;
pub use flags::Flags;
28
mod hub;
29
mod input;
30
#[cfg(any(feature = "vllm", feature = "sglang"))]
31
mod net;
32
33
34
mod opt;
pub use opt::{Input, Output};

35
36
37
/// How we identify a namespace/component/endpoint URL.
/// Technically the '://' is not part of the scheme but it eliminates several string
/// concatenations.
38
const ENDPOINT_SCHEME: &str = "dyn://";
39

40
41
42
43
/// When `in=text` the user doesn't need to know the model name, and doesn't need to provide it on
/// the command line. Hence it's optional, and defaults to this.
const INVISIBLE_MODEL_NAME: &str = "dynamo-run";

44
45
46
47
/// How we identify a python string endpoint
#[cfg(feature = "python")]
const PYTHON_STR_SCHEME: &str = "pystr:";

48
49
50
51
/// How we identify a python token endpoint
#[cfg(feature = "python")]
const PYTHON_TOK_SCHEME: &str = "pytok:";

52
pub enum EngineConfig {
53
    /// An remote networked engine we don't know about yet
54
    Dynamic(Endpoint),
55

56
57
58
59
60
    /// A Full service engine does it's own tokenization and prompt formatting.
    StaticFull {
        service_name: String,
        engine: OpenAIChatCompletionsStreamingEngine,
    },
61
62
63
64
65
66
67

    /// A core engine expects to be wrapped with pre/post processors that handle tokenization.
    StaticCore {
        service_name: String,
        engine: ExecutionContext,
        card: Box<ModelDeploymentCard>,
    },
68

69
70
    /// vllm multi-node doesn't run an engine on nodes other than 0. 'ray' does all the work.
    None,
71
72
}

73
#[allow(unused_mut)]
74
pub async fn run(
Neelay Shah's avatar
Neelay Shah committed
75
    runtime: dynamo_runtime::Runtime,
76
    mut in_opt: Input, // mut because vllm and sglang multi-node can change it
77
78
    out_opt: Output,
    flags: Flags,
79
    #[allow(unused_variables)] zmq_socket_prefix: Option<String>,
80
) -> anyhow::Result<()> {
81
82
    let cancel_token = runtime.primary_token();

83
    // Turn relative paths into absolute paths
84
    let mut model_path = flags
85
        .model_path_pos
86
87
        .clone()
        .or(flags.model_path_flag.clone())
88
89
90
91
92
93
94
        .and_then(|p| {
            if p.exists() {
                p.canonicalize().ok()
            } else {
                Some(p)
            }
        });
95

Graham King's avatar
Graham King committed
96
    // Serve the model under the name provided, or the name of the GGUF file or HF repo.
97
    let mut model_name = flags
98
        .model_name
99
        .clone()
100
101
102
        .or_else(|| {
            model_path
                .as_ref()
103
                .and_then(|p| p.iter().next_back())
104
105
106
107
108
109
110
111
112
                .map(|n| n.to_string_lossy().into_owned())
        })
        .or_else(|| {
            if in_opt == Input::Text {
                Some(INVISIBLE_MODEL_NAME.to_string())
            } else {
                None
            }
        });
113
114
115
116
117
118

    // If it's an HF repo download it
    if let Some(inner_model_path) = model_path.as_ref() {
        if !inner_model_path.exists() {
            model_name = inner_model_path
                .iter()
119
                .next_back()
120
121
122
123
124
                .map(|s| s.to_string_lossy().to_string());
            model_path = Some(hub::from_hf(inner_model_path).await?);
        }
    }

Graham King's avatar
Graham King committed
125
126
127
    // Load the model deployment card, if any
    // Only used by some engines, so without those feature flags it's unused.
    #[allow(unused_variables)]
128
    let maybe_card = match (&model_path, &flags.model_config) {
Graham King's avatar
Graham King committed
129
130
        // --model-config takes precedence
        (_, Some(model_config)) => {
131
132
133
134
135
136
137
138
139
140
            match ModelDeploymentCard::from_local_path(model_config, model_name.as_deref()).await {
                Ok(card) => Some(card),
                Err(e) => {
                    tracing::error!(
                        "Failed to load model card from --model-config path {}: {e}",
                        model_config.display(),
                    );
                    None
                }
            }
141
        }
Graham King's avatar
Graham King committed
142
143
        // If --model-path is an HF repo use that
        (Some(model_path), _) if model_path.is_dir() => {
144
            match ModelDeploymentCard::from_local_path(model_path, model_name.as_deref()).await {
145
146
147
                Ok(card) => Some(card),
                Err(e) => {
                    tracing::error!(
148
                        "Failed to load model card from --model-path {}: {e}",
149
150
151
152
                        model_path.display(),
                    );
                    None
                }
153
154
155
156
157
158
159
160
161
162
163
164
165
            }
        }
        (Some(model_path), _) if model_path.is_file() => {
            match ModelDeploymentCard::from_gguf(model_path, model_name.as_deref()).await {
                Ok(card) => Some(card),
                Err(e) => {
                    tracing::error!(
                        "Failed to load model card from GGUF {}: {e}",
                        model_path.display(),
                    );
                    None
                }
            }
Graham King's avatar
Graham King committed
166
167
        }
        // Otherwise we don't have one, but we only need it if we're tokenizing
168
169
        _ => {
            tracing::debug!("No model card path provided (neither --model-config nor a directory in --model-path)");
170
            None
171
        }
172
    };
173

Graham King's avatar
Graham King committed
174
    #[cfg(any(feature = "vllm", feature = "sglang"))]
175
    let mut extra: Option<Pin<Box<dyn Future<Output = ()> + Send>>> = None; // vllm and sglang sub-process
176

177
178
    // Create the engine matching `out`
    let engine_config = match out_opt {
179
180
181
182
183
184
185
186
        Output::EchoFull => {
            let Some(model_name) = model_name else {
                anyhow::bail!(
                    "Pass --model-name or --model-path so we know which model to imitate"
                );
            };
            EngineConfig::StaticFull {
                service_name: model_name,
187
                engine: dynamo_llm::engines::make_engine_full(),
188
189
            }
        }
190
191
192
193
194
195
196
197
198
        Output::EchoCore => {
            let Some(mut card) = maybe_card.clone() else {
                anyhow::bail!(
                    "out=echo_core need to find the tokenizer. Pass flag --model-path <path>"
                );
            };
            card.requires_preprocessing = true;
            EngineConfig::StaticCore {
                service_name: card.service_name.clone(),
199
                engine: dynamo_llm::engines::make_engine_core(),
200
201
202
                card: Box::new(card),
            }
        }
203
        Output::Endpoint(path) => {
204
            let endpoint: Endpoint = path.parse()?;
205
            EngineConfig::Dynamic(endpoint)
206
        }
207
208
209
210
211
212
213
214
215
216
        #[cfg(feature = "mistralrs")]
        Output::MistralRs => {
            let Some(model_path) = model_path else {
                anyhow::bail!("out=mistralrs requires flag --model-path=<full-path-to-model-gguf>");
            };
            let Some(model_name) = model_name else {
                unreachable!("We checked model_path earlier, and set model_name from model_path");
            };
            EngineConfig::StaticFull {
                service_name: model_name,
217
                engine: dynamo_engine_mistralrs::make_engine(&model_path).await?,
218
219
            }
        }
220
221
        #[cfg(feature = "sglang")]
        Output::SgLang => {
222
            use dynamo_engine_sglang;
223
224
225
226
227
228
229
230
231
232
233
            let Some(model_path) = model_path else {
                anyhow::bail!("out=sglang requires flag --model-path=<full-path-to-model-dir>");
            };
            if !model_path.is_dir() {
                anyhow::bail!("`--model-path should point at a HuggingFace repo checkout");
            }
            // Safety: Earlier we build maybe_card from model_path, which we checked right above
            let card = maybe_card.clone().unwrap();
            let Some(sock_prefix) = zmq_socket_prefix else {
                anyhow::bail!("sglang requires zmq_socket_prefix");
            };
Neelay Shah's avatar
Neelay Shah committed
234
            let node_conf = dynamo_llm::engines::MultiNodeConfig {
235
236
                num_nodes: flags.num_nodes,
                node_rank: flags.node_rank,
237
                leader_addr: flags.leader_addr.unwrap_or_default(),
238
239
240
241
242
243
244
            };
            if node_conf.num_nodes > 1 {
                if let Ok(Some(if_name)) = net::get_primary_interface().await {
                    tracing::info!("If you see 'gloo' errors from sglang try setting these environment variables:");
                    tracing::info!("export GLOO_SOCKET_IFNAME={if_name}");
                    tracing::info!("export NCCL_SOCKET_IFNAME={if_name}");
                }
245
246
247
248
249
                if node_conf.node_rank != 0 {
                    // Follower nodes take input from leader node over pytorch distributed, not
                    // from user.
                    in_opt = Input::None;
                }
250
251
            }

252
            let (engine, sglang_process) = dynamo_engine_sglang::make_engine(
253
254
255
256
257
258
                cancel_token.clone(),
                &model_path,
                &sock_prefix,
                node_conf,
                flags.tensor_parallel_size,
                flags.base_gpu_id,
259
                flags.extra_engine_args,
260
261
            )
            .await?;
262
263
264
            extra = Some(Box::pin(async move {
                let _ = sglang_process.await;
            }));
265
266
            EngineConfig::StaticCore {
                service_name: card.service_name.clone(),
267
268
269
270
                engine,
                card: Box::new(card),
            }
        }
Graham King's avatar
Graham King committed
271
272
        #[cfg(feature = "vllm")]
        Output::Vllm => {
273
274
275
            if flags.base_gpu_id != 0 {
                anyhow::bail!("vllm does not support base_gpu_id. Set environment variable CUDA_VISIBLE_DEVICES instead.");
            }
Graham King's avatar
Graham King committed
276
277
278
279
280
281
282
            let Some(model_path) = model_path else {
                anyhow::bail!(
                    "out=vllm requires flag --model-path=<full-path-to-hf-repo-or-model-gguf>"
                );
            };
            let Some(card) = maybe_card.clone() else {
                anyhow::bail!(
283
                    "Unable to build tokenizer. out=vllm requires --model-path to be an HF repo with fast tokenizer (tokenizer.json) or a GGUF file"
Graham King's avatar
Graham King committed
284
285
286
287
288
                );
            };
            let Some(sock_prefix) = zmq_socket_prefix else {
                anyhow::bail!("vllm requires zmq_socket_prefix");
            };
Neelay Shah's avatar
Neelay Shah committed
289
            let node_conf = dynamo_llm::engines::MultiNodeConfig {
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
                num_nodes: flags.num_nodes,
                node_rank: flags.node_rank,
                leader_addr: flags.leader_addr.unwrap_or_default(),
            };
            if node_conf.num_nodes > 1 {
                if let Ok(Some(if_name)) = net::get_primary_interface().await {
                    tracing::info!("If you see network errors from vllm try setting this environment variable:");
                    tracing::info!("export NCCL_SOCKET_IFNAME={if_name}");
                }
                if node_conf.node_rank != 0 {
                    // Only node 0 runs vllm, the others communicate over ray
                    in_opt = Input::None;
                }
            }
            if node_conf.node_rank == 0 {
                // vllm multi-node only the leader runs vllm
306
                let (engine, vllm_future) = dynamo_engine_vllm::make_leader_engine(
307
308
309
310
311
                    cancel_token.clone(),
                    &model_path,
                    &sock_prefix,
                    node_conf,
                    flags.tensor_parallel_size,
312
                    flags.extra_engine_args,
313
314
315
316
317
318
319
320
321
322
323
324
                )
                .await?;
                extra = Some(Box::pin(async move {
                    let _ = vllm_future.await;
                }));
                EngineConfig::StaticCore {
                    service_name: card.service_name.clone(),
                    engine,
                    card: Box::new(card),
                }
            } else {
                // Nodes rank > 0 only run 'ray'
325
326
                let stop_future =
                    dynamo_engine_vllm::start_follower(cancel_token.clone(), node_conf).await?;
327
328
                extra = Some(Box::pin(stop_future));
                EngineConfig::None
Graham King's avatar
Graham King committed
329
330
            }
        }
331
332
        #[cfg(feature = "llamacpp")]
        Output::LlamaCpp => {
333
            use dynamo_engine_llamacpp;
334
335
336
337
338
339
            let Some(model_path) = model_path else {
                anyhow::bail!("out=llamacpp requires flag --model-path=<full-path-to-model-gguf>");
            };
            if !model_path.is_file() {
                anyhow::bail!("--model-path should refer to a GGUF file. llama_cpp does not support safetensors.");
            }
340
            let Some(card) = maybe_card.clone() else {
Graham King's avatar
Graham King committed
341
342
343
                anyhow::bail!(
                    "Pass --model-config so we can find the tokenizer, should be an HF checkout."
                );
344
            };
345
346
            let engine =
                dynamo_engine_llamacpp::make_engine(cancel_token.clone(), &model_path).await?;
347
348
            EngineConfig::StaticCore {
                service_name: card.service_name.clone(),
349
                engine,
Graham King's avatar
Graham King committed
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
                card: Box::new(card),
            }
        }
        #[cfg(feature = "trtllm")]
        Output::TrtLLM => {
            let Some(model_path) = model_path else {
                anyhow::bail!("out=trtllm requires flag --model-path=<full-path-to-model-dir>");
            };
            if !model_path.is_dir() {
                anyhow::bail!(
                    "--model-path should point at a directory containing `.engine` files."
                );
            }
            // Safety: Earlier we build maybe_card from model_path, which we checked right above
            let card = maybe_card.clone().unwrap();
365
366
367
368
            let engine = dynamo_engine_trtllm::make_engine(
                model_path.display(),
                flags.tensor_parallel_size,
            )?;
Graham King's avatar
Graham King committed
369
370
371
            EngineConfig::StaticCore {
                service_name: card.service_name.clone(),
                engine,
372
373
374
                card: Box::new(card),
            }
        }
375
376
377
378
379
        #[cfg(feature = "python")]
        Output::PythonStr(path_str) => {
            let Some(model_name) = model_name else {
                anyhow::bail!("Provide model service name as `--model-name <this>`");
            };
380
            let py_args = flags.as_vec(&path_str, &model_name);
381
            let p = std::path::PathBuf::from(path_str);
382
383
            let engine =
                dynamo_engine_python::make_string_engine(cancel_token.clone(), &p, py_args).await?;
384
385
386
387
388
            EngineConfig::StaticFull {
                service_name: model_name,
                engine,
            }
        }
389
390
391
392
393
394
395
396
        #[cfg(feature = "python")]
        Output::PythonTok(path_str) => {
            let Some(card) = maybe_card.clone() else {
                anyhow::bail!("Could not find tokenizer. Pass flag --model-path <path>");
            };
            let Some(model_name) = model_name else {
                unreachable!("If we have a card we must have a model name");
            };
397
            let py_args = flags.as_vec(&path_str, &model_name);
398
            let p = std::path::PathBuf::from(path_str);
399
400
            let engine =
                dynamo_engine_python::make_token_engine(cancel_token.clone(), &p, py_args).await?;
401
402
403
404
405
406
            EngineConfig::StaticCore {
                service_name: model_name.clone(),
                engine,
                card: Box::new(card),
            }
        }
407
408
409
410
    };

    match in_opt {
        Input::Http => {
411
            crate::input::http::run(runtime.clone(), flags.http_port, engine_config).await?;
412
413
        }
        Input::Text => {
414
415
416
417
418
419
420
421
422
423
424
425
426
            crate::input::text::run(runtime.clone(), cancel_token.clone(), None, engine_config)
                .await?;
        }
        Input::Stdin => {
            let mut prompt = String::new();
            std::io::stdin().read_to_string(&mut prompt).unwrap();
            crate::input::text::run(
                runtime.clone(),
                cancel_token.clone(),
                Some(prompt),
                engine_config,
            )
            .await?;
427
        }
428
429
430
431
432
433
434
435
436
437
        Input::Batch(path) => {
            crate::input::batch::run(
                runtime.clone(),
                cancel_token.clone(),
                maybe_card,
                path,
                engine_config,
            )
            .await?;
        }
438
439
440
        Input::Endpoint(path) => {
            crate::input::endpoint::run(runtime.clone(), path, engine_config).await?;
        }
441
442
443
444
445
446
447
448
        Input::None => {
            // Multi-node setup. The engine sub-process has been started and is talking
            // to it's node_rank 0 controller. We do nothing.
            // TODO: Acquire an etcd lease, we are running
            cancel_token.cancelled().await;
        }
    }

Graham King's avatar
Graham King committed
449
    #[cfg(any(feature = "vllm", feature = "sglang"))]
450
451
    // Allow engines to ask main thread to wait on an extra future.
    if let Some(extra) = extra {
452
        extra.await;
453
454
455
456
    }

    Ok(())
}