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

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

7
use anyhow::Context as _;
8
use dynamo_runtime::component::Endpoint;
9
use dynamo_runtime::discovery::DiscoveryInstance;
10
use dynamo_runtime::discovery::DiscoverySpec;
11
use dynamo_runtime::protocols::EndpointId;
12
use dynamo_runtime::slug::Slug;
13
use dynamo_runtime::traits::DistributedRuntimeProvider;
14
use dynamo_runtime::utils::get_http_rpc_host_from_env;
15

16
use crate::entrypoint::RouterConfig;
17
use crate::mocker::protocols::{MockEngineArgs, WorkerType};
18
use crate::model_card::ModelDeploymentCard;
19
use crate::model_type::{ModelInput, ModelType};
20
use crate::preprocessor::media::{ImageDecoder, MediaDecoder, MediaFetcher};
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

pub struct LocalModelBuilder {
    model_path: Option<PathBuf>,
40
    source_path: Option<PathBuf>,
41
42
43
44
45
46
    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,
47
    http_host: Option<String>,
48
    http_port: u16,
49
    http_metrics_port: Option<u16>,
Graham King's avatar
Graham King committed
50
51
    tls_cert_path: Option<PathBuf>,
    tls_key_path: Option<PathBuf>,
52
    migration_limit: u32,
53
    is_mocker: bool,
54
55
    extra_engine_args: Option<PathBuf>,
    runtime_config: ModelRuntimeConfig,
56
    user_data: Option<serde_json::Value>,
57
    custom_template_path: Option<PathBuf>,
58
    namespace: Option<String>,
59
60
    custom_backend_metrics_endpoint: Option<String>,
    custom_backend_metrics_polling_interval: Option<f64>,
61
62
    media_decoder: Option<MediaDecoder>,
    media_fetcher: Option<MediaFetcher>,
63
64
}

65
impl Default for LocalModelBuilder {
66
    fn default() -> Self {
67
68
        LocalModelBuilder {
            kv_cache_block_size: DEFAULT_KV_CACHE_BLOCK_SIZE,
69
            http_host: Default::default(),
70
            http_port: DEFAULT_HTTP_PORT,
71
            http_metrics_port: None,
Graham King's avatar
Graham King committed
72
73
            tls_cert_path: Default::default(),
            tls_key_path: Default::default(),
74
            model_path: Default::default(),
75
            source_path: Default::default(),
76
77
78
79
80
            model_name: Default::default(),
            endpoint_id: Default::default(),
            context_length: Default::default(),
            template_file: Default::default(),
            router_config: Default::default(),
81
            migration_limit: Default::default(),
82
            is_mocker: Default::default(),
83
84
            extra_engine_args: Default::default(),
            runtime_config: Default::default(),
85
            user_data: Default::default(),
86
            custom_template_path: Default::default(),
87
            namespace: Default::default(),
88
89
            custom_backend_metrics_endpoint: Default::default(),
            custom_backend_metrics_polling_interval: Default::default(),
90
91
            media_decoder: Default::default(),
            media_fetcher: Default::default(),
92
93
94
95
        }
    }
}

96
impl LocalModelBuilder {
97
    /// The path must exist, the model is already downloaded
98
99
    pub fn model_path(&mut self, model_path: PathBuf) -> &mut Self {
        self.model_path = Some(model_path);
100
        self
101
102
    }

103
104
105
106
107
108
109
110
    /// The HF name of the model before we downloaded it, or a local path if
    /// that was given on the cmd line. We need this because `model_path` is always
    /// a local path.
    pub fn source_path(&mut self, source_path: PathBuf) -> &mut Self {
        self.source_path = Some(source_path);
        self
    }

111
112
113
    pub fn model_name(&mut self, model_name: Option<String>) -> &mut Self {
        self.model_name = model_name;
        self
114
115
    }

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

121
122
123
    pub fn context_length(&mut self, context_length: Option<u32>) -> &mut Self {
        self.context_length = context_length;
        self
124
125
    }

126
127
128
129
    /// 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
130
131
    }

132
133
134
135
136
    pub fn http_host(&mut self, host: Option<String>) -> &mut Self {
        self.http_host = host;
        self
    }

Graham King's avatar
Graham King committed
137
138
139
140
141
    pub fn http_port(&mut self, port: u16) -> &mut Self {
        self.http_port = port;
        self
    }

142
143
144
145
146
    pub fn http_metrics_port(&mut self, port: Option<u16>) -> &mut Self {
        self.http_metrics_port = port;
        self
    }

Graham King's avatar
Graham King committed
147
148
149
150
151
152
153
    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;
154
        self
155
156
    }

157
158
    pub fn router_config(&mut self, router_config: Option<RouterConfig>) -> &mut Self {
        self.router_config = router_config;
159
160
161
        self
    }

162
163
164
165
166
    pub fn namespace(&mut self, namespace: Option<String>) -> &mut Self {
        self.namespace = namespace;
        self
    }

167
168
169
    pub fn request_template(&mut self, template_file: Option<PathBuf>) -> &mut Self {
        self.template_file = template_file;
        self
170
171
    }

172
173
174
175
176
    pub fn custom_template_path(&mut self, custom_template_path: Option<PathBuf>) -> &mut Self {
        self.custom_template_path = custom_template_path;
        self
    }

177
178
179
180
181
    pub fn migration_limit(&mut self, migration_limit: Option<u32>) -> &mut Self {
        self.migration_limit = migration_limit.unwrap_or(0);
        self
    }

182
183
184
185
186
    pub fn is_mocker(&mut self, is_mocker: bool) -> &mut Self {
        self.is_mocker = is_mocker;
        self
    }

187
188
189
190
191
192
193
194
195
196
    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
    }

197
198
199
200
201
    pub fn user_data(&mut self, user_data: Option<serde_json::Value>) -> &mut Self {
        self.user_data = user_data;
        self
    }

202
203
204
205
206
207
208
209
210
211
    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
    }

212
213
214
215
216
217
218
219
220
221
    pub fn media_decoder(&mut self, media_decoder: Option<MediaDecoder>) -> &mut Self {
        self.media_decoder = media_decoder;
        self
    }

    pub fn media_fetcher(&mut self, media_fetcher: Option<MediaFetcher>) -> &mut Self {
        self.media_fetcher = media_fetcher;
        self
    }

222
223
224
225
226
227
228
229
    /// 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"
230
231
232
233
234
235
236
237
    /// - 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"));
238

239
240
241
242
243
244
        let template = self
            .template_file
            .as_deref()
            .map(RequestTemplate::load)
            .transpose()?;

Yan Ru Pei's avatar
Yan Ru Pei committed
245
246
247
248
249
250
251
252
253
254
255
        // Override runtime configs with mocker engine args (applies to both paths)
        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.kv_cache_block_size = mocker_engine_args.block_size as u32;
            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);
256
            self.runtime_config.enable_local_indexer = mocker_engine_args.enable_local_indexer;
Yan Ru Pei's avatar
Yan Ru Pei committed
257
            self.runtime_config.data_parallel_size = mocker_engine_args.dp_size;
258
259
260
261
262
            self.media_decoder = Some(MediaDecoder {
                image: Some(ImageDecoder::default()),
                #[cfg(feature = "media-ffmpeg")]
                video: None,
            });
263
            self.media_fetcher = Some(MediaFetcher::default());
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279

            // Set bootstrap endpoint for prefill workers with bootstrap_port configured
            if mocker_engine_args.worker_type == WorkerType::Prefill
                && let Some(port) = mocker_engine_args.bootstrap_port
            {
                let host = get_http_rpc_host_from_env();
                self.runtime_config.disaggregated_endpoint =
                    Some(runtime_config::DisaggregatedEndpoint {
                        bootstrap_host: Some(host),
                        bootstrap_port: Some(port),
                    });
                tracing::info!(
                    bootstrap_port = port,
                    "Mocker prefill worker: publishing bootstrap endpoint to discovery"
                );
            }
Yan Ru Pei's avatar
Yan Ru Pei committed
280
281
        }

282
        // frontend and echo engine don't need a path.
283
        if self.model_path.is_none() {
284
285
286
            let mut card = ModelDeploymentCard::with_name_only(
                self.model_name.as_deref().unwrap_or(DEFAULT_NAME),
            );
Yan Ru Pei's avatar
Yan Ru Pei committed
287
            card.kv_cache_block_size = self.kv_cache_block_size;
288
            card.migration_limit = self.migration_limit;
289
            card.user_data = self.user_data.take();
290
            card.runtime_config = self.runtime_config.clone();
291
292
            card.media_decoder = self.media_decoder.clone();
            card.media_fetcher = self.media_fetcher.clone();
293

294
            return Ok(LocalModel {
295
                card,
296
297
298
                full_path: PathBuf::new(),
                endpoint_id,
                template,
299
                http_host: self.http_host.take(),
300
                http_port: self.http_port,
301
                http_metrics_port: self.http_metrics_port,
Graham King's avatar
Graham King committed
302
303
                tls_cert_path: self.tls_cert_path.take(),
                tls_key_path: self.tls_key_path.take(),
304
                router_config: self.router_config.take().unwrap_or_default(),
305
                runtime_config: self.runtime_config.clone(),
306
                namespace: self.namespace.clone(),
307
308
309
                custom_backend_metrics_endpoint: self.custom_backend_metrics_endpoint.clone(),
                custom_backend_metrics_polling_interval: self
                    .custom_backend_metrics_polling_interval,
310
311
312
313
314
            });
        }

        // Main logic. We are running a model.
        let model_path = self.model_path.take().unwrap();
315
316
317
318
319
320
321
        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)?;
322

323
        let mut card =
324
            ModelDeploymentCard::load_from_disk(&model_path, self.custom_template_path.as_deref())?;
325
326
327
328
329
        // Source path is the `--model-path` the user passed. By now our `model_path` is the local
        // path of the downloaded model.
        if let Some(source_path) = self.source_path.take() {
            card.set_source_path(source_path);
        }
330
331
        // The served model name defaults to the full model path.
        // This matches what vllm and sglang do.
332
333
        let alt = card.source_path().to_string();
        card.set_name(self.model_name.as_deref().unwrap_or(&alt));
334

335
        card.kv_cache_block_size = self.kv_cache_block_size;
336

337
338
339
340
        // 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;
        }
341

342
        card.migration_limit = self.migration_limit;
343
        card.user_data = self.user_data.take();
344
        card.runtime_config = self.runtime_config.clone();
345
346
        card.media_decoder = self.media_decoder.clone();
        card.media_fetcher = self.media_fetcher.clone();
347

348
349
        Ok(LocalModel {
            card,
350
            full_path: model_path,
351
352
            endpoint_id,
            template,
353
            http_host: self.http_host.take(),
354
            http_port: self.http_port,
355
            http_metrics_port: self.http_metrics_port,
Graham King's avatar
Graham King committed
356
357
            tls_cert_path: self.tls_cert_path.take(),
            tls_key_path: self.tls_key_path.take(),
358
            router_config: self.router_config.take().unwrap_or_default(),
359
            runtime_config: self.runtime_config.clone(),
360
            namespace: self.namespace.clone(),
361
362
            custom_backend_metrics_endpoint: self.custom_backend_metrics_endpoint.clone(),
            custom_backend_metrics_polling_interval: self.custom_backend_metrics_polling_interval,
363
364
365
366
367
368
369
370
371
372
        })
    }
}

#[derive(Debug, Clone)]
pub struct LocalModel {
    full_path: PathBuf,
    card: ModelDeploymentCard,
    endpoint_id: EndpointId,
    template: Option<RequestTemplate>,
373
    http_host: Option<String>,
Graham King's avatar
Graham King committed
374
    http_port: u16,
375
    http_metrics_port: Option<u16>,
Graham King's avatar
Graham King committed
376
377
    tls_cert_path: Option<PathBuf>,
    tls_key_path: Option<PathBuf>,
378
    router_config: RouterConfig,
379
    runtime_config: ModelRuntimeConfig,
380
    namespace: Option<String>,
381
382
    custom_backend_metrics_endpoint: Option<String>,
    custom_backend_metrics_polling_interval: Option<f64>,
383
384
385
}

impl LocalModel {
386
387
388
389
390
391
392
393
394
    /// 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
    }

395
396
397
398
399
400
401
402
    pub fn card(&self) -> &ModelDeploymentCard {
        &self.card
    }

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

403
    /// Human friendly model name. This is the correct name.
404
405
406
407
    pub fn display_name(&self) -> &str {
        &self.card.display_name
    }

408
409
    /// 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.
410
    pub fn service_name(&self) -> &str {
411
        self.card.slug().as_ref()
412
413
414
415
416
417
    }

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

418
419
420
421
    pub fn http_host(&self) -> Option<String> {
        self.http_host.clone()
    }

422
423
424
425
    pub fn http_port(&self) -> u16 {
        self.http_port
    }

426
427
428
429
    pub fn http_metrics_port(&self) -> Option<u16> {
        self.http_metrics_port
    }

Graham King's avatar
Graham King committed
430
431
432
433
434
435
436
437
    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()
    }

438
439
440
441
    pub fn router_config(&self) -> &RouterConfig {
        &self.router_config
    }

442
443
444
445
    pub fn runtime_config(&self) -> &ModelRuntimeConfig {
        &self.runtime_config
    }

446
447
448
449
    pub fn namespace(&self) -> Option<&str> {
        self.namespace.as_deref()
    }

450
451
452
453
454
455
456
457
    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
    }

458
459
460
461
462
463
464
465
466
    /// 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
467
468
    }

469
    /// Attach this model to the endpoint. This registers it on the network
470
    /// allowing ingress to discover it.
471
472
473
    ///
    /// For base models, pass `lora_name = None`.
    /// For LoRA adapters, pass `lora_name = Some("adapter-name")`.
474
475
476
477
    pub async fn attach(
        &mut self,
        endpoint: &Endpoint,
        model_type: ModelType,
478
        model_input: ModelInput,
479
        lora_name: Option<&str>,
480
    ) -> anyhow::Result<()> {
481
482
        self.card.model_type = model_type;
        self.card.model_input = model_input;
483
        self.card.lora_name = lora_name.map(|name| name.to_string());
484

485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
        // Compute model_suffix from lora_name if present
        let model_suffix = lora_name.map(|name| Slug::slugify(name).to_string());

        let suffix_for_log = model_suffix
            .as_ref()
            .map(|s| format!("/{}", s))
            .unwrap_or_default();
        tracing::debug!(
            "Registering MDC at path: {}/{}/{}/{:x}{}",
            endpoint.component().namespace().name(),
            endpoint.component().name(),
            endpoint.name(),
            endpoint.drt().connection_id(),
            suffix_for_log
        );

501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
        let source_path = PathBuf::from(self.card.source_path());
        if !source_path.exists() {
            // The consumers of MDC (frontend) might not have the same local path as us, so
            // replace disk paths with a custom URL like "hf://Qwen/Qwen3-0.6B/config.json".
            //
            // We can't do this if the model came from disk, as it might not be the same version
            // as on Hugging Face (if it exists there at all).
            //
            // The URL is not used by anything. Frontend will download the repo and edit these
            // paths to be local, so only the filename part matters currently.
            // Possibly we should just use the filenames here. The URL feels nicer to me, it makes
            // each field fully identified and fetchable independently.
            self.card
                .move_to_url(&format!("hf://{}/", self.card.source_path()))
                .context("move_to_url")?;
        }

518
        // Register the Model Deployment Card via discovery interface
519
        // The model_suffix (for LoRA) will be appended AFTER the instance_id
520
        let discovery = endpoint.drt().discovery();
521
        let spec = DiscoverySpec::from_model_with_suffix(
522
523
524
525
            endpoint.component().namespace().name().to_string(),
            endpoint.component().name().to_string(),
            endpoint.name().to_string(),
            &self.card,
526
            model_suffix,
527
528
        )?;
        let _instance = discovery.register(spec).await?;
529

530
        Ok(())
531
    }
532
533

    /// Helper associated function to detach a model from an endpoint
534
535
536
537
538
539
540
    ///
    /// For base models, pass `lora_name = None`.
    /// For LoRA adapters, pass `lora_name = Some("adapter-name")`.
    pub async fn detach_from_endpoint(
        endpoint: &Endpoint,
        lora_name: Option<&str>,
    ) -> anyhow::Result<()> {
541
542
543
544
        let drt = endpoint.drt();
        let instance_id = drt.connection_id();
        let endpoint_id = endpoint.id();

545
546
547
        // Compute model_suffix from lora_name if present
        let model_suffix = lora_name.map(|name| Slug::slugify(name).to_string());

548
549
550
551
552
553
        let instance = DiscoveryInstance::Model {
            namespace: endpoint_id.namespace,
            component: endpoint_id.component,
            endpoint: endpoint_id.name,
            instance_id,
            card_json: serde_json::Value::Null,
554
            model_suffix,
555
556
557
558
559
        };

        let discovery = drt.discovery();
        discovery.unregister(instance).await?;

560
561
562
563
564
565
566
567
        if let Some(lora_name) = lora_name {
            tracing::info!(
                "Successfully unregistered LoRA '{}' from discovery",
                lora_name
            );
        } else {
            tracing::info!("Successfully unregistered model from discovery");
        }
568
569
570

        Ok(())
    }
571
}
572
573
574
575
576
577
578
579
580
581

/// 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(),
    }
}