local_model.rs 15.3 KB
Newer Older
1
2
3
4
5
6
7
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;

8
use dynamo_runtime::protocols::EndpointId;
9
use dynamo_runtime::slug::Slug;
10
use dynamo_runtime::storage::key_value_store::Key;
11
use dynamo_runtime::traits::DistributedRuntimeProvider;
12
use dynamo_runtime::{
13
    component::Endpoint,
14
    storage::key_value_store::{EtcdStore, KeyValueStore, KeyValueStoreManager},
15
};
16

17
use crate::entrypoint::RouterConfig;
18
use crate::mocker::protocols::MockEngineArgs;
19
use crate::model_card::{self, ModelDeploymentCard};
20
use crate::model_type::{ModelInput, ModelType};
21
use crate::request_template::RequestTemplate;
22

23
24
25
pub mod runtime_config;

use runtime_config::ModelRuntimeConfig;
26

27
28
29
30
/// What we call a model if the user didn't provide a name. Usually this means the name
/// is invisible, for example in a text chat.
const DEFAULT_NAME: &str = "dynamo";

31
32
33
34
/// Engines don't usually provide a default, so we do.
const DEFAULT_KV_CACHE_BLOCK_SIZE: u32 = 16;

/// We can't have it default to 0, so pick something
Graham King's avatar
Graham King committed
35
36
/// 'pub' because the bindings use it for consistency.
pub const DEFAULT_HTTP_PORT: u16 = 8080;
37
38
39
40
41
42
43
44
45

pub struct LocalModelBuilder {
    model_path: Option<PathBuf>,
    model_name: Option<String>,
    endpoint_id: Option<EndpointId>,
    context_length: Option<u32>,
    template_file: Option<PathBuf>,
    router_config: Option<RouterConfig>,
    kv_cache_block_size: u32,
46
    http_host: Option<String>,
47
    http_port: u16,
Graham King's avatar
Graham King committed
48
49
    tls_cert_path: Option<PathBuf>,
    tls_key_path: Option<PathBuf>,
50
    migration_limit: u32,
51
    is_mocker: bool,
52
53
    extra_engine_args: Option<PathBuf>,
    runtime_config: ModelRuntimeConfig,
54
    user_data: Option<serde_json::Value>,
55
    custom_template_path: Option<PathBuf>,
56
    namespace: Option<String>,
57
58
    custom_backend_metrics_endpoint: Option<String>,
    custom_backend_metrics_polling_interval: Option<f64>,
59
60
}

61
impl Default for LocalModelBuilder {
62
    fn default() -> Self {
63
64
        LocalModelBuilder {
            kv_cache_block_size: DEFAULT_KV_CACHE_BLOCK_SIZE,
65
            http_host: Default::default(),
66
            http_port: DEFAULT_HTTP_PORT,
Graham King's avatar
Graham King committed
67
68
            tls_cert_path: Default::default(),
            tls_key_path: Default::default(),
69
70
71
72
73
74
            model_path: Default::default(),
            model_name: Default::default(),
            endpoint_id: Default::default(),
            context_length: Default::default(),
            template_file: Default::default(),
            router_config: Default::default(),
75
            migration_limit: Default::default(),
76
            is_mocker: Default::default(),
77
78
            extra_engine_args: Default::default(),
            runtime_config: Default::default(),
79
            user_data: Default::default(),
80
            custom_template_path: Default::default(),
81
            namespace: Default::default(),
82
83
            custom_backend_metrics_endpoint: Default::default(),
            custom_backend_metrics_polling_interval: Default::default(),
84
85
86
87
        }
    }
}

88
impl LocalModelBuilder {
89
90
91
    /// The path must exist
    pub fn model_path(&mut self, model_path: PathBuf) -> &mut Self {
        self.model_path = Some(model_path);
92
        self
93
94
    }

95
96
97
    pub fn model_name(&mut self, model_name: Option<String>) -> &mut Self {
        self.model_name = model_name;
        self
98
99
    }

100
101
    pub fn endpoint_id(&mut self, endpoint_id: Option<EndpointId>) -> &mut Self {
        self.endpoint_id = endpoint_id;
102
        self
103
104
    }

105
106
107
    pub fn context_length(&mut self, context_length: Option<u32>) -> &mut Self {
        self.context_length = context_length;
        self
108
109
    }

110
111
112
113
    /// Passing None resets it to default
    pub fn kv_cache_block_size(&mut self, kv_cache_block_size: Option<u32>) -> &mut Self {
        self.kv_cache_block_size = kv_cache_block_size.unwrap_or(DEFAULT_KV_CACHE_BLOCK_SIZE);
        self
114
115
    }

116
117
118
119
120
    pub fn http_host(&mut self, host: Option<String>) -> &mut Self {
        self.http_host = host;
        self
    }

Graham King's avatar
Graham King committed
121
122
123
124
125
126
127
128
129
130
131
132
    pub fn http_port(&mut self, port: u16) -> &mut Self {
        self.http_port = port;
        self
    }

    pub fn tls_cert_path(&mut self, p: Option<PathBuf>) -> &mut Self {
        self.tls_cert_path = p;
        self
    }

    pub fn tls_key_path(&mut self, p: Option<PathBuf>) -> &mut Self {
        self.tls_key_path = p;
133
        self
134
135
    }

136
137
    pub fn router_config(&mut self, router_config: Option<RouterConfig>) -> &mut Self {
        self.router_config = router_config;
138
139
140
        self
    }

141
142
143
144
145
    pub fn namespace(&mut self, namespace: Option<String>) -> &mut Self {
        self.namespace = namespace;
        self
    }

146
147
148
    pub fn request_template(&mut self, template_file: Option<PathBuf>) -> &mut Self {
        self.template_file = template_file;
        self
149
150
    }

151
152
153
154
155
    pub fn custom_template_path(&mut self, custom_template_path: Option<PathBuf>) -> &mut Self {
        self.custom_template_path = custom_template_path;
        self
    }

156
157
158
159
160
    pub fn migration_limit(&mut self, migration_limit: Option<u32>) -> &mut Self {
        self.migration_limit = migration_limit.unwrap_or(0);
        self
    }

161
162
163
164
165
    pub fn is_mocker(&mut self, is_mocker: bool) -> &mut Self {
        self.is_mocker = is_mocker;
        self
    }

166
167
168
169
170
171
172
173
174
175
    pub fn extra_engine_args(&mut self, extra_engine_args: Option<PathBuf>) -> &mut Self {
        self.extra_engine_args = extra_engine_args;
        self
    }

    pub fn runtime_config(&mut self, runtime_config: ModelRuntimeConfig) -> &mut Self {
        self.runtime_config = runtime_config;
        self
    }

176
177
178
179
180
    pub fn user_data(&mut self, user_data: Option<serde_json::Value>) -> &mut Self {
        self.user_data = user_data;
        self
    }

181
182
183
184
185
186
187
188
189
190
    pub fn custom_backend_metrics_endpoint(&mut self, endpoint: Option<String>) -> &mut Self {
        self.custom_backend_metrics_endpoint = endpoint;
        self
    }

    pub fn custom_backend_metrics_polling_interval(&mut self, interval: Option<f64>) -> &mut Self {
        self.custom_backend_metrics_polling_interval = interval;
        self
    }

191
192
193
194
195
196
197
198
    /// Make an LLM ready for use:
    /// - Download it from Hugging Face (and NGC in future) if necessary
    /// - Resolve the path
    /// - Load it's ModelDeploymentCard card
    /// - Name it correctly
    ///
    /// The model name will depend on what "model_path" is:
    /// - A folder: The last part of the folder name: "/data/llms/Qwen2.5-3B-Instruct" -> "Qwen2.5-3B-Instruct"
199
200
201
202
203
204
205
206
    /// - An HF repo: The HF repo name: "Qwen/Qwen3-0.6B" stays the same
    pub async fn build(&mut self) -> anyhow::Result<LocalModel> {
        // Generate an endpoint ID for this model if the user didn't provide one.
        // The user only provides one if exposing the model.
        let endpoint_id = self
            .endpoint_id
            .take()
            .unwrap_or_else(|| internal_endpoint("local_model"));
207

208
209
210
211
212
213
        let template = self
            .template_file
            .as_deref()
            .map(RequestTemplate::load)
            .transpose()?;

214
        // frontend and echo engine don't need a path.
215
        if self.model_path.is_none() {
216
217
218
219
            let mut card = ModelDeploymentCard::with_name_only(
                self.model_name.as_deref().unwrap_or(DEFAULT_NAME),
            );
            card.migration_limit = self.migration_limit;
220
            card.user_data = self.user_data.take();
221
            card.runtime_config = self.runtime_config.clone();
222

223
            return Ok(LocalModel {
224
                card,
225
226
227
                full_path: PathBuf::new(),
                endpoint_id,
                template,
228
                http_host: self.http_host.take(),
229
                http_port: self.http_port,
Graham King's avatar
Graham King committed
230
231
                tls_cert_path: self.tls_cert_path.take(),
                tls_key_path: self.tls_key_path.take(),
232
                router_config: self.router_config.take().unwrap_or_default(),
233
                runtime_config: self.runtime_config.clone(),
234
                namespace: self.namespace.clone(),
235
236
237
                custom_backend_metrics_endpoint: self.custom_backend_metrics_endpoint.clone(),
                custom_backend_metrics_polling_interval: self
                    .custom_backend_metrics_polling_interval,
238
239
240
241
242
            });
        }

        // Main logic. We are running a model.
        let model_path = self.model_path.take().unwrap();
243
244
245
246
247
248
249
        if !model_path.exists() {
            anyhow::bail!(
                "Path does not exist: '{}'. Use LocalModel::fetch to download it.",
                model_path.display(),
            );
        }
        let model_path = fs::canonicalize(model_path)?;
250

251
        let mut card =
252
253
254
255
256
257
258
259
260
            ModelDeploymentCard::load_from_disk(&model_path, self.custom_template_path.as_deref())?;
        // The served model name defaults to the full model path.
        // This matches what vllm and sglang do.
        card.set_name(
            &self
                .model_name
                .clone()
                .unwrap_or_else(|| model_path.display().to_string()),
        );
261

262
        card.kv_cache_block_size = self.kv_cache_block_size;
263

264
265
266
267
        // Override max number of tokens in context. We usually only do this to limit kv cache allocation.
        if let Some(context_length) = self.context_length {
            card.context_length = context_length;
        }
268

269
        // Override runtime configs with mocker engine args
270
271
272
273
274
275
276
277
278
        if self.is_mocker
            && let Some(path) = &self.extra_engine_args
        {
            let mocker_engine_args = MockEngineArgs::from_json_file(path)
                .expect("Failed to load mocker engine args for runtime config overriding.");
            self.runtime_config.total_kv_blocks = Some(mocker_engine_args.num_gpu_blocks as u64);
            self.runtime_config.max_num_seqs = mocker_engine_args.max_num_seqs.map(|v| v as u64);
            self.runtime_config.max_num_batched_tokens =
                mocker_engine_args.max_num_batched_tokens.map(|v| v as u64);
279
280
        }

281
        card.migration_limit = self.migration_limit;
282
        card.user_data = self.user_data.take();
283
        card.runtime_config = self.runtime_config.clone();
284

285
286
        Ok(LocalModel {
            card,
287
            full_path: model_path,
288
289
            endpoint_id,
            template,
290
            http_host: self.http_host.take(),
291
            http_port: self.http_port,
Graham King's avatar
Graham King committed
292
293
            tls_cert_path: self.tls_cert_path.take(),
            tls_key_path: self.tls_key_path.take(),
294
            router_config: self.router_config.take().unwrap_or_default(),
295
            runtime_config: self.runtime_config.clone(),
296
            namespace: self.namespace.clone(),
297
298
            custom_backend_metrics_endpoint: self.custom_backend_metrics_endpoint.clone(),
            custom_backend_metrics_polling_interval: self.custom_backend_metrics_polling_interval,
299
300
301
302
303
304
305
306
307
308
        })
    }
}

#[derive(Debug, Clone)]
pub struct LocalModel {
    full_path: PathBuf,
    card: ModelDeploymentCard,
    endpoint_id: EndpointId,
    template: Option<RequestTemplate>,
309
    http_host: Option<String>,
Graham King's avatar
Graham King committed
310
311
312
    http_port: u16,
    tls_cert_path: Option<PathBuf>,
    tls_key_path: Option<PathBuf>,
313
    router_config: RouterConfig,
314
    runtime_config: ModelRuntimeConfig,
315
    namespace: Option<String>,
316
317
    custom_backend_metrics_endpoint: Option<String>,
    custom_backend_metrics_polling_interval: Option<f64>,
318
319
320
}

impl LocalModel {
321
322
323
324
325
326
327
328
329
    /// Ensure a model is accessible locally, returning it's path.
    /// Downloads the model from Hugging Face if necessary.
    /// If ignore_weights is true, model weight files will be skipped and only the model config
    /// will be downloaded.
    /// Returns the path to the model files
    pub async fn fetch(remote_name: &str, ignore_weights: bool) -> anyhow::Result<PathBuf> {
        super::hub::from_hf(remote_name, ignore_weights).await
    }

330
331
332
333
334
335
336
337
    pub fn card(&self) -> &ModelDeploymentCard {
        &self.card
    }

    pub fn path(&self) -> &Path {
        &self.full_path
    }

338
    /// Human friendly model name. This is the correct name.
339
340
341
342
    pub fn display_name(&self) -> &str {
        &self.card.display_name
    }

343
344
    /// The name under which we make this model available over HTTP.
    /// A slugified version of the model's name, for use in NATS, etcd, etc.
345
    pub fn service_name(&self) -> &str {
346
        self.card.slug().as_ref()
347
348
349
350
351
352
    }

    pub fn request_template(&self) -> Option<RequestTemplate> {
        self.template.clone()
    }

353
354
355
356
    pub fn http_host(&self) -> Option<String> {
        self.http_host.clone()
    }

357
358
359
360
    pub fn http_port(&self) -> u16 {
        self.http_port
    }

Graham King's avatar
Graham King committed
361
362
363
364
365
366
367
368
    pub fn tls_cert_path(&self) -> Option<&Path> {
        self.tls_cert_path.as_deref()
    }

    pub fn tls_key_path(&self) -> Option<&Path> {
        self.tls_key_path.as_deref()
    }

369
370
371
372
    pub fn router_config(&self) -> &RouterConfig {
        &self.router_config
    }

373
374
375
376
    pub fn runtime_config(&self) -> &ModelRuntimeConfig {
        &self.runtime_config
    }

377
378
379
380
    pub fn namespace(&self) -> Option<&str> {
        self.namespace.as_deref()
    }

381
382
383
384
385
386
387
388
389
390
391
392
393
394
    pub fn custom_backend_metrics_endpoint(&self) -> Option<&str> {
        self.custom_backend_metrics_endpoint.as_deref()
    }

    pub fn custom_backend_metrics_polling_interval(&self) -> Option<f64> {
        self.custom_backend_metrics_polling_interval
    }

    pub fn is_gguf(&self) -> bool {
        // GGUF is the only file (not-folder) we accept, so we don't need to check the extension
        // We will error when we come to parse it
        self.full_path.is_file()
    }

395
396
397
398
399
400
401
402
403
    /// An endpoint to identify this model by.
    pub fn endpoint_id(&self) -> &EndpointId {
        &self.endpoint_id
    }

    /// Drop the LocalModel returning it's ModelDeploymentCard.
    /// For the case where we only need the card and don't want to clone it.
    pub fn into_card(self) -> ModelDeploymentCard {
        self.card
404
405
406
407
408
409
410
411
    }

    /// Attach this model the endpoint. This registers it on the network
    /// allowing ingress to discover it.
    pub async fn attach(
        &mut self,
        endpoint: &Endpoint,
        model_type: ModelType,
412
        model_input: ModelInput,
413
414
415
416
417
    ) -> anyhow::Result<()> {
        // A static component doesn't have an etcd_client because it doesn't need to register
        let Some(etcd_client) = endpoint.drt().etcd_client() else {
            anyhow::bail!("Cannot attach to static endpoint");
        };
418
419
        self.card.model_type = model_type;
        self.card.model_input = model_input;
420

421
422
423
424
        // Store model config files in NATS object store
        let nats_client = endpoint.drt().nats_client();
        self.card.move_to_nats(nats_client.clone()).await?;

425
        // Publish the Model Deployment Card to KV store
426
        let kvstore: Box<dyn KeyValueStore> = Box::new(EtcdStore::new(etcd_client.clone()));
427
        let card_store = Arc::new(KeyValueStoreManager::new(kvstore));
428
429
        let lease_id = endpoint.drt().primary_lease().map(|l| l.id()).unwrap_or(0);
        let key = Key::from_raw(endpoint.unique_path(lease_id));
430

431
432
433
434
        let _outcome = card_store
            .publish(model_card::ROOT_PATH, None, &key, &mut self.card)
            .await?;
        Ok(())
435
436
    }
}
437
438
439
440
441
442
443
444
445
446

/// A random endpoint to use for internal communication
/// We can't hard code because we may be running several on the same machine (GPUs 0-3 and 4-7)
fn internal_endpoint(engine: &str) -> EndpointId {
    EndpointId {
        namespace: Slug::slugify(&uuid::Uuid::new_v4().to_string()).to_string(),
        component: engine.to_string(),
        name: "generate".to_string(),
    }
}