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

19
20
21
22
23
use triton_distributed_llm::{
    backend::ExecutionContext,
    model_card::model::ModelDeploymentCard,
    types::{
        openai::chat_completions::{
24
            NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse,
25
26
27
            OpenAIChatCompletionsStreamingEngine,
        },
        Annotated,
28
29
    },
};
30
use triton_distributed_runtime::{component::Client, protocols::Endpoint, DistributedRuntime};
31

32
33
mod flags;
pub use flags::Flags;
34
mod input;
35
#[cfg(any(feature = "vllm", feature = "sglang"))]
36
mod net;
37
38
39
40
mod opt;
mod output;
pub use opt::{Input, Output};

41
42
43
/// How we identify a namespace/component/endpoint URL.
/// Technically the '://' is not part of the scheme but it eliminates several string
/// concatenations.
44
const ENDPOINT_SCHEME: &str = "dyn://";
45

46
pub enum EngineConfig {
47
48
    /// An remote networked engine we don't know about yet
    /// We don't have the pre-processor yet so this is only text requests. Type will change later.
49
    Dynamic(Client<NvCreateChatCompletionRequest, Annotated<NvCreateChatCompletionStreamResponse>>),
50

51
52
53
54
55
    /// A Full service engine does it's own tokenization and prompt formatting.
    StaticFull {
        service_name: String,
        engine: OpenAIChatCompletionsStreamingEngine,
    },
56
57
58
59
60
61
62

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

64
65
    /// vllm multi-node doesn't run an engine on nodes other than 0. 'ray' does all the work.
    None,
66
67
}

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

78
    // Turn relative paths into absolute paths
79
80
81
82
    let model_path = flags
        .model_path_pos
        .or(flags.model_path_flag)
        .and_then(|p| p.canonicalize().ok());
Graham King's avatar
Graham King committed
83
    // Serve the model under the name provided, or the name of the GGUF file or HF repo.
84
85
86
87
88
89
    let model_name = flags.model_name.or_else(|| {
        model_path
            .as_ref()
            .and_then(|p| p.iter().last())
            .map(|n| n.to_string_lossy().into_owned())
    });
Graham King's avatar
Graham King committed
90
91
92
93
94
95
96
    // Load the model deployment card, if any
    // Only used by some engines, so without those feature flags it's unused.
    #[allow(unused_variables)]
    let (maybe_card_path, maybe_card) = match (&model_path, &flags.model_config) {
        // --model-config takes precedence
        (_, Some(model_config)) => {
            let card = ModelDeploymentCard::from_local_path(model_config, model_name.as_deref())
97
                .await
Graham King's avatar
Graham King committed
98
99
                .ok();
            (Some(model_config.clone()), card)
100
        }
Graham King's avatar
Graham King committed
101
102
103
104
105
106
107
108
109
        // If --model-path is an HF repo use that
        (Some(model_path), _) if model_path.is_dir() => {
            let card = ModelDeploymentCard::from_local_path(model_path, model_name.as_deref())
                .await
                .ok();
            (Some(model_path.clone()), card)
        }
        // Otherwise we don't have one, but we only need it if we're tokenizing
        _ => (None, None),
110
    };
111

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

115
116
    // Create the engine matching `out`
    let engine_config = match out_opt {
117
118
119
120
121
122
123
124
125
126
127
        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,
                engine: output::echo_full::make_engine_full(),
            }
        }
128
129
130
131
132
133
134
135
136
137
138
139
140
        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(),
                engine: output::echo_core::make_engine_core(),
                card: Box::new(card),
            }
        }
141
        Output::Endpoint(path) => {
142
143
            let endpoint: Endpoint = path.parse()?;

144
145
146
147
            // This will attempt to connect to NATS and etcd
            let distributed_runtime = DistributedRuntime::from_settings(runtime.clone()).await?;

            let client = distributed_runtime
148
149
150
                .namespace(endpoint.namespace)?
                .component(endpoint.component)?
                .endpoint(endpoint.name)
151
                .client::<NvCreateChatCompletionRequest, Annotated<NvCreateChatCompletionStreamResponse>>()
152
153
154
155
156
157
158
159
160
161
162
163
164
165
                .await?;

            tracing::info!("Waiting for remote {}...", client.path());
            tokio::select! {
                _ = cancel_token.cancelled() => {
                    return Ok(());
                }
                r = client.wait_for_endpoints() => {
                    r?;
                }
            }

            EngineConfig::Dynamic(client)
        }
166
167
168
169
170
171
172
173
174
175
        #[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,
176
177
                engine: triton_distributed_llm::engines::mistralrs::make_engine(&model_path)
                    .await?,
178
179
            }
        }
180
181
182
183
184
185
186
187
188
189
190
191
192
193
        #[cfg(feature = "sglang")]
        Output::SgLang => {
            use triton_distributed_llm::engines::sglang;
            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");
            };
194
            let node_conf = triton_distributed_llm::engines::MultiNodeConfig {
195
196
                num_nodes: flags.num_nodes,
                node_rank: flags.node_rank,
197
                leader_addr: flags.leader_addr.unwrap_or_default(),
198
199
200
201
202
203
204
            };
            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}");
                }
205
206
207
208
209
                if node_conf.node_rank != 0 {
                    // Follower nodes take input from leader node over pytorch distributed, not
                    // from user.
                    in_opt = Input::None;
                }
210
211
212
213
214
215
216
217
218
219
220
            }

            let (engine, sglang_process) = sglang::make_engine(
                cancel_token.clone(),
                &model_path,
                &sock_prefix,
                node_conf,
                flags.tensor_parallel_size,
                flags.base_gpu_id,
            )
            .await?;
221
222
223
            extra = Some(Box::pin(async move {
                let _ = sglang_process.await;
            }));
224
225
            EngineConfig::StaticCore {
                service_name: card.service_name.clone(),
226
227
228
229
                engine,
                card: Box::new(card),
            }
        }
Graham King's avatar
Graham King committed
230
231
232
        #[cfg(feature = "vllm")]
        Output::Vllm => {
            use triton_distributed_llm::engines::vllm;
233
234
235
            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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
            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_path) = maybe_card_path else {
                // If we have a gguf we also need a model card because we don't currently parse
                // tokenizer et al out of gguf.
                anyhow::bail!(
                    "Running GGUF files also requires a `--model-config` for the tokenizer et al."
                );
            };
            let Some(card) = maybe_card.clone() else {
                anyhow::bail!(
                    "out=vllm requires --model-path to be an HF repo, or for GGUF add flag --model-config <hf-repo>"
                );
            };
            let Some(sock_prefix) = zmq_socket_prefix else {
                anyhow::bail!("vllm requires zmq_socket_prefix");
            };
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
            let node_conf = triton_distributed_llm::engines::MultiNodeConfig {
                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
                let (engine, vllm_future) = vllm::make_leader_engine(
                    cancel_token.clone(),
                    &card_path,
                    &model_path,
                    &sock_prefix,
                    node_conf,
                    flags.tensor_parallel_size,
                )
                .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'
                let stop_future = vllm::start_follower(cancel_token.clone(), node_conf).await?;
                extra = Some(Box::pin(stop_future));
                EngineConfig::None
Graham King's avatar
Graham King committed
295
296
            }
        }
297
298
299
300
301
302
303
304
305
        #[cfg(feature = "llamacpp")]
        Output::LlamaCpp => {
            use triton_distributed_llm::engines::llamacpp;
            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.");
            }
Graham King's avatar
Graham King committed
306
307
308
309
            let Some(card) = maybe_card else {
                anyhow::bail!(
                    "Pass --model-config so we can find the tokenizer, should be an HF checkout."
                );
310
311
312
313
            };
            let engine = llamacpp::make_engine(cancel_token.clone(), &model_path).await?;
            EngineConfig::StaticCore {
                service_name: card.service_name.clone(),
314
                engine,
Graham King's avatar
Graham King committed
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
                card: Box::new(card),
            }
        }
        #[cfg(feature = "trtllm")]
        Output::TrtLLM => {
            use triton_distributed_llm::engines::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();
            let engine = trtllm::make_engine(model_path.display(), flags.tensor_parallel_size)?;
            EngineConfig::StaticCore {
                service_name: card.service_name.clone(),
                engine,
335
336
337
                card: Box::new(card),
            }
        }
338
339
340
341
    };

    match in_opt {
        Input::Http => {
342
            crate::input::http::run(runtime.clone(), flags.http_port, engine_config).await?;
343
344
345
346
        }
        Input::Text => {
            crate::input::text::run(cancel_token.clone(), engine_config).await?;
        }
347
348
349
        Input::Endpoint(path) => {
            crate::input::endpoint::run(runtime.clone(), path, engine_config).await?;
        }
350
351
352
353
354
355
356
357
        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
358
    #[cfg(any(feature = "vllm", feature = "sglang"))]
359
360
    // Allow engines to ask main thread to wait on an extra future.
    if let Some(extra) = extra {
361
        extra.await;
362
363
364
365
    }

    Ok(())
}