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

4
5
6
7
8
9
10
11
12
13
14
15
//! # Model Deployment Card
//!
//! The ModelDeploymentCard (MDC) is the primary model configuration structure that will be available to any
//! component that needs to interact with the model or its dependent artifacts.
//!
//! The ModelDeploymentCard contains LLM model deployment configuration information:
//! - Display name and service name for the model
//! - Model information (ModelInfoType)
//! - Tokenizer configuration (TokenizerKind)
//! - Prompt formatter settings (PromptFormatterArtifact)

use std::fmt;
16
use std::path::{Path, PathBuf};
17
use std::sync::{Arc, OnceLock};
18

19
use crate::common::checked_file::CheckedFile;
20
use crate::local_model::runtime_config::ModelRuntimeConfig;
21
use crate::model_type::{ModelInput, ModelType};
22
23
use anyhow::{Context, Result};
use derive_builder::Builder;
24
use dynamo_runtime::{slug::Slug, storage::kv};
25
26
27
use serde::{Deserialize, Serialize};
use tokenizers::Tokenizer as HfTokenizer;

28
use crate::preprocessor::media::{MediaDecoder, MediaFetcher};
29
use crate::protocols::TokenIdType;
30
31

/// Identify model deployment cards in the key-value store
32
pub const ROOT_PATH: &str = "v1/mdc";
33
34
35
36

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ModelInfoType {
37
    HfConfigJson(CheckedFile),
38
39
}

40
41
42
43
44
45
impl ModelInfoType {
    pub fn checksum(&self) -> String {
        match self {
            ModelInfoType::HfConfigJson(c) => c.checksum().to_string(),
        }
    }
46
47
48
49
50
51
52
53
54
55
56
57

    pub fn is_local(&self) -> bool {
        match self {
            ModelInfoType::HfConfigJson(c) => c.is_local(),
        }
    }

    pub fn update_dir(&mut self, dir: &Path) {
        match self {
            ModelInfoType::HfConfigJson(c) => c.update_dir(dir),
        }
    }
58
59
}

60
61
62
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum TokenizerKind {
63
    HfTokenizerJson(CheckedFile),
Nikita's avatar
Nikita committed
64
    TikTokenModel(CheckedFile),
65
66
}

67
68
69
impl TokenizerKind {
    pub fn checksum(&self) -> String {
        match self {
Nikita's avatar
Nikita committed
70
71
72
            TokenizerKind::HfTokenizerJson(c) | TokenizerKind::TikTokenModel(c) => {
                c.checksum().to_string()
            }
73
74
        }
    }
75
76
77

    pub fn is_local(&self) -> bool {
        match self {
Nikita's avatar
Nikita committed
78
            TokenizerKind::HfTokenizerJson(c) | TokenizerKind::TikTokenModel(c) => c.is_local(),
79
80
81
82
83
        }
    }

    pub fn update_dir(&mut self, dir: &Path) {
        match self {
Nikita's avatar
Nikita committed
84
85
86
            TokenizerKind::HfTokenizerJson(c) | TokenizerKind::TikTokenModel(c) => {
                c.update_dir(dir)
            }
87
88
        }
    }
89
90
}

91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/// Supported types of prompt formatters.
///
/// We need a way to associate the prompt formatter template definition with an associated
/// data model which is expected for rendering.
///
/// All current prompt formatters are Jinja2 templates which use the OpenAI ChatCompletionRequest
/// format. However, we currently do not have a discovery path to know if the model supports tool use
/// unless we inspect the template.
///
/// TODO(): Add an enum for the PromptFormatDataModel with at minimum arms for:
/// - OaiChat
/// - OaiChatToolUse
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum PromptFormatterArtifact {
106
    HfTokenizerConfigJson(CheckedFile),
107
    HfChatTemplate { is_custom: bool, file: CheckedFile },
108
109
}

110
111
112
113
impl PromptFormatterArtifact {
    pub fn checksum(&self) -> String {
        match self {
            PromptFormatterArtifact::HfTokenizerConfigJson(c) => c.checksum().to_string(),
114
            PromptFormatterArtifact::HfChatTemplate { file: c, .. } => c.checksum().to_string(),
115
116
        }
    }
117
118
119
120
121

    /// Is this file available locally
    pub fn is_local(&self) -> bool {
        match self {
            PromptFormatterArtifact::HfTokenizerConfigJson(c) => c.is_local(),
122
            PromptFormatterArtifact::HfChatTemplate { file: c, .. } => c.is_local(),
123
124
125
126
127
128
        }
    }

    pub fn update_dir(&mut self, dir: &Path) {
        match self {
            PromptFormatterArtifact::HfTokenizerConfigJson(c) => c.update_dir(dir),
129
130
131
132
133
134
135
136
            PromptFormatterArtifact::HfChatTemplate { file: c, .. } => c.update_dir(dir),
        }
    }

    pub fn is_custom(&self) -> bool {
        match self {
            PromptFormatterArtifact::HfTokenizerConfigJson(_) => false,
            PromptFormatterArtifact::HfChatTemplate { is_custom, .. } => *is_custom,
137
138
        }
    }
139
140
}

141
142
143
144
145
146
147
148
149
150
151
152
153
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum PromptContextMixin {
    /// Support OAI Chat Messages and Tools
    OaiChat,

    /// Enables templates with `{{datetime}}` to be rendered with the current date and time.
    Llama3DateTime,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum GenerationConfig {
154
    HfGenerationConfigJson(CheckedFile),
155
156
}

157
158
159
160
161
162
impl GenerationConfig {
    pub fn checksum(&self) -> String {
        match self {
            GenerationConfig::HfGenerationConfigJson(c) => c.checksum().to_string(),
        }
    }
163
164
165
166
167
168
169
170
171
172
173
174

    pub fn is_local(&self) -> bool {
        match self {
            GenerationConfig::HfGenerationConfigJson(c) => c.is_local(),
        }
    }

    pub fn update_dir(&mut self, dir: &Path) {
        match self {
            GenerationConfig::HfGenerationConfigJson(c) => c.update_dir(dir),
        }
    }
175
176
}

177
178
179
180
181
/// Check if our model only has config fields for a Mistral-format model.
fn is_exclusively_mistral_model(directory: &Path) -> bool {
    !directory.join("config.json").exists() && directory.join("params.json").exists()
}

182
183
184
185
186
187
188
189
#[derive(Serialize, Deserialize, Clone, Debug, Builder, Default)]
pub struct ModelDeploymentCard {
    /// Human readable model name, e.g. "Meta Llama 3.1 8B Instruct"
    pub display_name: String,

    // Cache the Slugified display_name so we can share references to it
    slug: Slug,

190
191
192
193
194
    /// Original HuggingFace repository path for downloading model files.
    /// When `display_name` is customized (e.g., via `--served-model-name`),
    /// this field preserves the original repository path needed for downloads.
    /// Falls back to `display_name` if not set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
195
    pub source_path: Option<String>,
196

197
198
199
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
    /// Model information
    pub model_info: Option<ModelInfoType>,

    /// Tokenizer configuration
    pub tokenizer: Option<TokenizerKind>,

    /// Prompt Formatter configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt_formatter: Option<PromptFormatterArtifact>,

    /// chat template may be stored as a separate file instead of in `prompt_formatter`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chat_template_file: Option<PromptFormatterArtifact>,

    /// Generation config - default sampling params
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gen_config: Option<GenerationConfig>,

    /// Prompt Formatter Config
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt_context: Option<Vec<PromptContextMixin>>,

    /// Max context (in number of tokens) this model can handle
    pub context_length: u32,

    /// Size of a KV cache block - vllm only currently
    /// Passed to the engine and the KV router.
    pub kv_cache_block_size: u32,

    /// How many times a request can be migrated to another worker if the HTTP server lost
    /// connection to the current worker.
    pub migration_limit: u32,

230
231
232
233
234
235
236
237
    /// Specifies whether the model is a chat, completions, etc model.
    pub model_type: ModelType,

    /// Specifies the model input type.
    /// `Tokens` for engines that expect pre-processed input.
    /// `Text` for engines that take care of pre-processing themselves.
    pub model_input: ModelInput,

238
    /// LoRA metadata for routing
239
    #[serde(default, skip_serializing_if = "Option::is_none")]
240
    pub lora: Option<LoraInfo>,
241

242
243
244
    /// User-defined metadata for custom worker behavior
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_data: Option<serde_json::Value>,
245
246
247

    #[serde(default)]
    pub runtime_config: ModelRuntimeConfig,
248

249
250
251
252
253
254
255
256
    /// Media decoding configuration
    #[serde(default)]
    pub media_decoder: Option<MediaDecoder>,

    /// Media fetching configuration
    #[serde(default)]
    pub media_fetcher: Option<MediaFetcher>,

257
258
    #[serde(skip, default)]
    checksum: OnceLock<String>,
259
260
}

261
262
263
264
265
266
267
268
269
270
271
/// LoRA adapter information for routing decisions
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct LoraInfo {
    /// LoRA adapter name (e.g., "customer-123-v2")
    pub name: String,

    /// Maximum number of LoRA adapters that can be loaded at once on a single GPU
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_gpu_lora_count: Option<u32>,
}

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
impl ModelDeploymentCard {
    pub fn builder() -> ModelDeploymentCardBuilder {
        ModelDeploymentCardBuilder::default()
    }

    /// Create a ModelDeploymentCard where only the name is filled in.
    ///
    /// Single-process setups don't need an MDC to communicate model details, but it
    /// simplifies the code to assume we always have one. This is how you get one in those
    /// cases. A quasi-null object: <https://en.wikipedia.org/wiki/Null_object_pattern>
    pub fn with_name_only(name: &str) -> ModelDeploymentCard {
        ModelDeploymentCard {
            display_name: name.to_string(),
            slug: Slug::from_string(name),
            ..Default::default()
        }
    }

    /// Load a model deployment card from a JSON file
    pub fn load_from_json_file<P: AsRef<Path>>(file: P) -> std::io::Result<Self> {
292
293
294
295
        let contents = std::fs::read_to_string(&file)?;
        Ok(serde_json::from_str(&contents).inspect_err(|err| {
            crate::log_json_err(&file.as_ref().display().to_string(), &contents, err)
        })?)
296
297
298
    }

    /// Load a model deployment card from a JSON string
299
300
301
    pub fn load_from_json_str(contents: &str) -> Result<Self, anyhow::Error> {
        Ok(serde_json::from_str(contents)
            .inspect_err(|err| crate::log_json_err("unknown", contents, err))?)
302
303
304
305
306
307
308
309
310
311
312
313
    }

    //
    // Methods
    //

    /// Save the model deployment card to a JSON file
    pub fn save_to_json_file(&self, file: &str) -> Result<(), anyhow::Error> {
        std::fs::write(file, self.to_json()?)?;
        Ok(())
    }

314
315
316
317
318
319
    #[inline]
    pub fn name(&self) -> &str {
        &self.display_name
    }

    #[inline]
320
321
322
323
324
325
326
327
328
    pub fn slug(&self) -> &Slug {
        &self.slug
    }

    /// Serialize the model deployment card to a JSON string
    pub fn to_json(&self) -> Result<String, anyhow::Error> {
        Ok(serde_json::to_string(self)?)
    }

329
330
331
332
333
334
    pub fn mdcsum(&self) -> &str {
        self.checksum
            .get_or_init(|| {
                // Only include the important fields
                let mut bytes_to_hash: Vec<u8> = Vec::with_capacity(512);
                bytes_to_hash.extend(self.display_name.as_bytes());
335
336
337
                if let Some(source_path) = self.source_path.as_ref() {
                    bytes_to_hash.extend(source_path.as_bytes());
                }
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370

                // The files can be either a URL or a local path, so we ignore that and hash their
                // checksum instead, which won't change wherever they are.

                if let Some(model_info) = self.model_info.as_ref() {
                    bytes_to_hash.extend(model_info.checksum().as_bytes());
                }
                if let Some(tokenizer) = self.tokenizer.as_ref() {
                    bytes_to_hash.extend(tokenizer.checksum().as_bytes());
                }
                if let Some(prompt_formatter) = self.prompt_formatter.as_ref() {
                    bytes_to_hash.extend(prompt_formatter.checksum().as_bytes());
                }
                if let Some(chat_template) = self.chat_template_file.as_ref() {
                    bytes_to_hash.extend(chat_template.checksum().as_bytes());
                }
                if let Some(gen_config) = self.gen_config.as_ref() {
                    bytes_to_hash.extend(gen_config.checksum().as_bytes());
                }

                if let Some(prompt_context_vec) = self.prompt_context.as_ref() {
                    // Paste it as the bytes of the debug format. It's a Vec of enum, so this should be
                    // fine. If the debug representation changes that only happens in a new release.
                    bytes_to_hash.extend(format!("{prompt_context_vec:?}").as_bytes());
                }
                bytes_to_hash.extend(self.context_length.to_be_bytes());
                bytes_to_hash.extend(self.kv_cache_block_size.to_be_bytes());

                // TODO: Do we want any of user_data or runtime_config?

                blake3::hash(&bytes_to_hash).to_string()
            })
            .as_ref()
371
372
373
374
375
376
377
378
    }

    /// Is this a full model card with tokenizer?
    /// There are cases where we have a placeholder card (see `with_name_only`).
    pub fn has_tokenizer(&self) -> bool {
        self.tokenizer.is_some()
    }

Nikita's avatar
Nikita committed
379
380
    /// Load the tokenizer as a generic, backend-agnostic `Tokenizer` trait object.
    /// This supports both HuggingFace `tokenizer.json` and tiktoken `.model`/`.tiktoken` files.
381
382
    ///
    /// When the `DYN_TOKENIZER=fastokens` env var is set, uses `fastokens` for encoding
Nikita's avatar
Nikita committed
383
    pub fn tokenizer(&self) -> anyhow::Result<crate::tokenizers::Tokenizer> {
384
385
386
387
388
389
390
391
392
393
394
395
396
        let use_fast = match std::env::var("DYN_TOKENIZER") {
            Ok(v) if v == "fastokens" => true,
            Ok(v) if v == "default" || v.is_empty() => false,
            Ok(v) => {
                tracing::warn!(
                    value = %v,
                    "Unrecognized DYN_TOKENIZER value, expected 'fastokens' or 'default'; falling back to default"
                );
                false
            }
            Err(_) => false,
        };

397
        match &self.tokenizer {
398
            Some(TokenizerKind::HfTokenizerJson(checked_file)) => {
399
400
401
                let p = checked_file.path().ok_or_else(|| {
                    anyhow::anyhow!("Tokenizer is URL-backed ({:?})", checked_file.url())
                })?;
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425

                // Try fastokens backend if requested
                if use_fast {
                    if let Some(path_str) = p.to_str() {
                        match crate::tokenizers::FastTokenizer::from_file(path_str) {
                            Ok(fast) => {
                                tracing::info!("Using fastokens tokenizer backend");
                                return Ok(crate::tokenizers::Tokenizer::from(Arc::new(fast)));
                            }
                            Err(e) => {
                                tracing::warn!(
                                    %e,
                                    "Failed to load fastokens, falling back to HuggingFace"
                                );
                            }
                        }
                    } else {
                        tracing::warn!(
                            path = %p.display(),
                            "Tokenizer path contains non-UTF-8 characters, skipping fastokens; falling back to HuggingFace"
                        );
                    }
                }

Nikita's avatar
Nikita committed
426
                let hf = HfTokenizer::from_file(p)
427
428
429
430
431
432
433
434
                    .inspect_err(|err| {
                        if let Some(serde_err) = err.downcast_ref::<serde_json::Error>()
                            && let Ok(contents) = std::fs::read_to_string(p)
                        {
                            crate::log_json_err(&p.display().to_string(), &contents, serde_err);
                        }
                    })
                    .map_err(anyhow::Error::msg)
Nikita's avatar
Nikita committed
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
                    .with_context(|| p.display().to_string())?;
                Ok(crate::tokenizers::Tokenizer::from(Arc::new(
                    crate::tokenizers::HuggingFaceTokenizer::from_tokenizer(hf),
                )))
            }
            Some(TokenizerKind::TikTokenModel(checked_file)) => {
                let p = checked_file.path().ok_or_else(|| {
                    anyhow::anyhow!("Tokenizer is URL-backed ({:?})", checked_file.url())
                })?;
                let path_str = p.to_str().ok_or_else(|| {
                    anyhow::anyhow!("Tokenizer path contains invalid UTF-8: {}", p.display())
                })?;
                let tokenizer = crate::tokenizers::TikTokenTokenizer::from_file_auto(path_str)
                    .with_context(|| {
                        format!("Failed to load tiktoken tokenizer from {}", p.display())
                    })?;
                Ok(crate::tokenizers::Tokenizer::from(Arc::new(tokenizer)))
452
453
            }
            None => {
454
455
456
                anyhow::bail!(
                    "Blank ModelDeploymentCard does not have a tokenizer. Is this a mistral model? If so, the `--use-<framework>-tokenizer` flag in the engine command is required."
                );
457
458
459
460
            }
        }
    }

461
462
463
464
    pub(crate) fn set_source_path(&mut self, source_path: PathBuf) {
        self.source_path = Some(source_path.display().to_string());
    }

465
466
467
468
469
470
471
    /// Allow user to override the name we register this model under.
    /// Corresponds to vllm's `--served-model-name`.
    pub fn set_name(&mut self, name: &str) {
        self.display_name = name.to_string();
        self.slug = Slug::from_string(name);
    }

472
473
474
475
    pub fn source_path(&self) -> &str {
        self.source_path.as_ref().unwrap_or(&self.display_name)
    }

476
477
478
    /// Build an in-memory ModelDeploymentCard from a folder containing config.json,
    /// tokenizer.json and tokenizer_config.json (i.e. a huggingface repo checkout).
    /// Optional custom template.
479
    pub fn load_from_disk(
480
481
482
        config_path: impl AsRef<Path>,
        custom_template_path: Option<&Path>,
    ) -> anyhow::Result<ModelDeploymentCard> {
483
        Self::from_local_path(config_path.as_ref(), custom_template_path)
484
485
    }

486
487
488
489
    pub fn requires_preprocessing(&self) -> bool {
        matches!(self.model_input, ModelInput::Tokens)
    }

490
491
492
493
494
495
496
    /// Download the files this card needs to work: config.json, tokenizer.json, etc.
    pub async fn download_config(&mut self) -> anyhow::Result<()> {
        if self.has_local_files() {
            tracing::trace!("All model config is local, not downloading");
            return Ok(());
        }

497
498
499
500
501
502
503
504
505
        // For TensorBased models, config files are not used - they handle everything in the backend
        if self.model_type.supports_tensor() {
            tracing::debug!(
                display_name = %self.display_name,
                "Skipping config download for TensorBased model"
            );
            return Ok(());
        }

506
        let ignore_weights = true;
507
        let local_path = crate::hub::from_hf(self.source_path(), ignore_weights).await?;
508
509
510
511
512

        self.update_dir(&local_path);
        Ok(())
    }

513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
    /// Re-write all the local disk paths as a URL. Do this before publishing the MDC.
    /// The opposite of `move_to_url` is `update_dir`.
    pub fn move_to_url(&mut self, base_url: &str) -> anyhow::Result<()> {
        macro_rules! change {
            ($field:expr, $enum_variant:path) => {
                if let Some($enum_variant(src_file)) = $field.as_mut()
                    && let Some(filename) = src_file
                        .path()
                        .and_then(|p| p.file_name())
                        .and_then(|f| f.to_str())
                        .map(|f| f.to_string())
                {
                    let hf_url = url::Url::parse(base_url)
                        .and_then(|u| u.join(filename.as_ref()))
                        .context(filename)?;
                    src_file.move_to_url(hf_url);
                }
            };
        }

        // config.json
        change!(self.model_info, ModelInfoType::HfConfigJson);

        // generation_config.json
        change!(self.gen_config, GenerationConfig::HfGenerationConfigJson);

        // tokenizer_config.json
        change!(
            self.prompt_formatter,
            PromptFormatterArtifact::HfTokenizerConfigJson
        );

Nikita's avatar
Nikita committed
545
        // tokenizer.json or tiktoken.model
546
        change!(self.tokenizer, TokenizerKind::HfTokenizerJson);
Nikita's avatar
Nikita committed
547
        change!(self.tokenizer, TokenizerKind::TikTokenModel);
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574

        // We only "move" the chat template if it came form the repo. If we have a custom template
        // file we cannot download that from HF.
        if let Some(PromptFormatterArtifact::HfChatTemplate {
            file: src_file,
            is_custom,
        }) = self.chat_template_file.as_mut()
        {
            if *is_custom {
                tracing::info!(
                    "Detected custom chat template. Ensure file exists in the same location on all hosts."
                );
            } else if let Some(filename) = src_file
                .path()
                .and_then(|p| p.file_name())
                .and_then(|f| f.to_str())
                .map(|f| f.to_string())
            {
                let hf_url = url::Url::parse(base_url)
                    .and_then(|u| u.join(filename.as_ref()))
                    .context(filename)?;
                src_file.move_to_url(hf_url);
            }
        }
        Ok(())
    }

575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
    /// Are all the files we need (tokenizer.json, etc) available locally?
    fn has_local_files(&self) -> bool {
        let has_model_info = self
            .model_info
            .as_ref()
            .map(|p| p.is_local())
            .unwrap_or(true);
        let has_tokenizer = self
            .tokenizer
            .as_ref()
            .map(|p| p.is_local())
            .unwrap_or(true);
        let has_prompt_formatter = self
            .prompt_formatter
            .as_ref()
            .map(|p| p.is_local())
            .unwrap_or(true);
        let has_chat_template_file = self
            .chat_template_file
            .as_ref()
            .map(|p| p.is_local())
            .unwrap_or(true);
        let has_gen_config = self
            .gen_config
            .as_ref()
            .map(|p| p.is_local())
            .unwrap_or(true);

        has_model_info
            && has_tokenizer
            && has_prompt_formatter
            && has_chat_template_file
            && has_gen_config
    }

    /// Update the directory for files like tokenizer.json be in here.
    fn update_dir(&mut self, dir: &Path) {
        if let Some(model_info) = self.model_info.as_mut() {
            model_info.update_dir(dir);
        }
        if let Some(tk) = self.tokenizer.as_mut() {
            tk.update_dir(dir);
        }
        if let Some(pf) = self.prompt_formatter.as_mut() {
            pf.update_dir(dir);
        }
        if let Some(gc) = self.gen_config.as_mut() {
            gc.update_dir(dir);
        }
624
625
626
627
628
629
        // If it's a custom chat template we didn't download it, so leave the path untouched
        if let Some(ct) = self.chat_template_file.as_mut()
            && !ct.is_custom()
        {
            ct.update_dir(dir);
        }
630
631
    }

632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
    /// Creates a ModelDeploymentCard from a local directory path.
    ///
    /// Currently HuggingFace format is supported and following files are expected:
    /// - config.json: Model configuration in HuggingFace format
    /// - tokenizer.json: Tokenizer configuration in HuggingFace format
    /// - tokenizer_config.json: Optional prompt formatter configuration
    ///
    /// # Arguments
    /// * `local_root_dir` - Path to the local model directory
    ///
    /// # Errors
    /// Returns an error if:
    /// - The path doesn't exist or isn't a directory
    /// - The path contains invalid Unicode characters
    /// - Required model files are missing or invalid
647
    fn from_local_path(
648
        local_path: impl AsRef<Path>,
649
650
        custom_template_path: Option<&Path>,
    ) -> anyhow::Result<Self> {
651
652
653
654
655
656
        check_valid_local_repo_path(&local_path)?;
        Self::from_repo_checkout(&local_path, custom_template_path)
    }

    fn from_repo_checkout(
        local_path: impl AsRef<Path>,
657
658
        custom_template_path: Option<&Path>,
    ) -> anyhow::Result<Self> {
659
660
        let local_path = local_path.as_ref();

661
        // This is usually the right choice
662
663
664
665
666
667
668
669
670
671
672
        let context_length =
            crate::file_json_field(&local_path.join("config.json"), "max_position_embeddings")
                // But sometimes this is
                .or_else(|_| {
                    crate::file_json_field(
                        &local_path.join("tokenizer_config.json"),
                        "model_max_length",
                    )
                })
                // If neither of those are present let the engine default it
                .unwrap_or(0);
673

674
675
676
677
678
679
680
681
682
683
684
685
686
        let is_mistral_model = is_exclusively_mistral_model(local_path);

        let (model_info, tokenizer, gen_config, prompt_formatter) = if !is_mistral_model {
            (
                Some(ModelInfoType::from_disk(local_path)?),
                Some(TokenizerKind::from_disk(local_path)?),
                GenerationConfig::from_disk(local_path).ok(),
                PromptFormatterArtifact::from_disk(local_path)?,
            )
        } else {
            (None, None, None, None)
        };

687
        // Load chat template - either custom or from repo
688
689
690
        let chat_template_file = if is_mistral_model {
            None
        } else if let Some(template_path) = custom_template_path {
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
            if !template_path.exists() {
                anyhow::bail!(
                    "Custom template file does not exist: {}",
                    template_path.display()
                );
            }

            // Verify the file is readable
            let _template_content = std::fs::read_to_string(template_path).with_context(|| {
                format!(
                    "Failed to read custom template file: {}",
                    template_path.display()
                )
            })?;

706
707
708
709
            Some(PromptFormatterArtifact::HfChatTemplate {
                is_custom: custom_template_path.is_some(),
                file: CheckedFile::from_disk(template_path)?,
            })
710
        } else {
711
            PromptFormatterArtifact::chat_template_from_disk(local_path)?
712
713
        };

714
        // This gets replaced when we `set_name`
715
        let display_name = local_path.display().to_string();
716

717
        Ok(Self {
718
719
            slug: Slug::from_string(&display_name),
            display_name,
720
            source_path: None,
721
722
723
724
            model_info,
            tokenizer,
            gen_config,
            prompt_formatter,
725
            chat_template_file,
726
727
728
729
            prompt_context: None, // TODO - auto-detect prompt context
            context_length,
            kv_cache_block_size: 0, // set later
            migration_limit: 0,
730
731
            model_type: Default::default(),  // set later
            model_input: Default::default(), // set later
732
            lora: None,
733
            user_data: None,
734
            runtime_config: ModelRuntimeConfig::default(),
735
736
            media_decoder: None,
            media_fetcher: None,
737
            checksum: OnceLock::new(),
738
739
740
741
        })
    }
}

742
743
744
745
746
747
impl PartialEq for ModelDeploymentCard {
    fn eq(&self, other: &ModelDeploymentCard) -> bool {
        self.mdcsum() == other.mdcsum()
    }
}

748
/// A ModelDeploymentCard is published a single time per instance and never updated.
749
impl kv::Versioned for ModelDeploymentCard {
750
    fn revision(&self) -> u64 {
751
        0
752
753
    }

754
    fn set_revision(&mut self, _revision: u64) {}
755
756
757
758
759
760
761
762
763
764
765
}

impl fmt::Display for ModelDeploymentCard {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.slug())
    }
}
pub trait ModelInfo: Send + Sync {
    /// Model type
    fn model_type(&self) -> String;

766
767
    /// Token ID for the beginning of sequence (optional - not all models have it)
    fn bos_token_id(&self) -> Option<TokenIdType>;
768
769
770
771
772
773
774
775
776
777
778
779
780
781

    /// Token ID for the end of sequence
    fn eos_token_ids(&self) -> Vec<TokenIdType>;

    /// Maximum position embeddings / max sequence length
    /// TODO: This is only used in a single test, no other code. Remove?
    fn max_position_embeddings(&self) -> Option<usize>;

    /// Vocabulary size
    /// TODO: This is only used in a single test, no other code. Remove?
    fn vocab_size(&self) -> Option<usize>;
}

impl ModelInfoType {
782
    pub fn get_model_info(&self) -> Result<Arc<dyn ModelInfo>> {
783
        match self {
784
785
786
787
788
789
            Self::HfConfigJson(checked_file) => {
                let Some(path) = checked_file.path() else {
                    anyhow::bail!("model info is not a local path: {checked_file:?}");
                };
                Ok(HFConfig::from_json_file(path)?)
            }
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct HFConfig {
    /// denotes the mixin to the flattened data model which can be present
    /// in the config.json file
    architectures: Vec<String>,

    /// general model type
    model_type: String,

    text_config: Option<HFTextConfig>,

    // Sometimes it's inside HFTextConfig, sometimes it's here
    eos_token_id: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct HFTextConfig {
811
    // Optional - not all models have a bos_token_id
812
813
814
815
816
817
818
819
820
821
822
    bos_token_id: Option<TokenIdType>,

    eos_token_id: Option<serde_json::Value>,

    #[serde(default)]
    final_eos_token_ids: Vec<TokenIdType>,

    /// max sequence length
    max_position_embeddings: Option<usize>,

    /// number of layers in the model
823
824
    /// Optional because some multimodal models (e.g., LLaVA) don't include this in text_config
    num_hidden_layers: Option<usize>,
825
826
827
828
829
830
831
832
833

    /// number of attention heads in the model
    num_attention_heads: Option<usize>,

    /// Vocabulary size
    vocab_size: Option<usize>,
}

impl HFConfig {
834
835
836
    fn from_json_file<P: AsRef<Path>>(file: P) -> Result<Arc<dyn ModelInfo>> {
        let file_path = file.as_ref();
        let contents = std::fs::read_to_string(file_path)?;
837
838
839
840
        let mut config: Self = json_five::from_str(&contents)
            .inspect_err(|err| {
                tracing::error!(path=%file_path.display(), %err, "Failed to parse config.json as JSON5");
            })?;
841
        if config.text_config.is_none() {
842
843
844
845
            let text_config: HFTextConfig = json_five::from_str(&contents)
                .inspect_err(|err| {
                    tracing::error!(path=%file_path.display(), %err, "Failed to parse text config from config.json as JSON5");
                })?;
846
847
            config.text_config = Some(text_config);
        }
848

849
850
851
852
853
854
        let Some(text_config) = config.text_config.as_mut() else {
            anyhow::bail!(
                "Missing text config fields (model_type, eos_token_ids, etc) in config.json"
            );
        };

855
856
857
858
        let gencfg_path = file_path
            .parent()
            .unwrap_or_else(|| Path::new(""))
            .join("generation_config.json");
859
860
861

        // bos_token_id is optional - not all models have it
        // Try to load from generation_config.json if not in config.json
862
        if text_config.bos_token_id.is_none() {
863
864
            text_config.bos_token_id =
                crate::file_json_field::<TokenIdType>(&gencfg_path, "bos_token_id").ok();
865
866
867
        }

        // TODO: refactor this when we switch to per-architecture tokenization
868
869
870
871
872
873
874
        // eos_token_id can appear in multiple places, and as suggested by HuggingFace
        // community that the priority should be:
        // 1. generation_config.json;
        // 2. config.json, or text_config field in config.json.
        // https://github.com/huggingface/transformers/issues/25395#issuecomment-1671863257
        let final_eos_token_ids: Vec<TokenIdType> = {
                // Firstly check the generation_config.json
875
                crate::file_json_field::<serde_json::Value>(&gencfg_path, "eos_token_id")
876
877
878
                .inspect_err(
                    |err| tracing::warn!(%err, "Missing eos_token_id in generation_config.json"),
                )
879
                .ok().and_then(|v| {
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
                    if v.is_number() {
                        v.as_number()
                            .and_then(|n| n.as_u64())
                            .map(|n| vec![n as TokenIdType])
                    } else if v.is_array() {
                        let arr = v.as_array().unwrap();
                        Some(
                            arr.iter()
                                .filter_map(|inner_v| {
                                    inner_v
                                        .as_number()
                                        .and_then(|n| n.as_u64())
                                        .map(|n| n as TokenIdType)
                                })
                                .collect(),
                        )
                    } else {
                        None
                    }
                })
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
            }.or_else(|| {
                // Check config.json and text_config
                config
                .eos_token_id
                .as_ref()
                .or(text_config.eos_token_id.as_ref())
                .and_then(|v| {
                    if v.is_number() {
                        v.as_number()
                            .and_then(|n| n.as_u64())
                            .map(|n| vec![n as TokenIdType])
                    } else {
                        serde_json::from_value(v.clone())
                            .map(Some)
                            .unwrap_or_else(|err| {
                                tracing::error!(
                                    ?v,
                                    path = %file_path.display(),
                                    "eos_token_id is not a number or an array, cannot deserialize: {err}",
                                );
                                None
                            })
                    }
                })
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
            })
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "missing eos_token_id in config.json and generation_config.json, cannot load"
                )
            })?;
        text_config.final_eos_token_ids = final_eos_token_ids;

        Ok(Arc::new(config))
    }
}

impl ModelInfo for HFConfig {
    fn model_type(&self) -> String {
        self.model_type.clone()
    }

941
942
    fn bos_token_id(&self) -> Option<TokenIdType> {
        self.text_config.as_ref().and_then(|tc| tc.bos_token_id)
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
    }

    fn eos_token_ids(&self) -> Vec<TokenIdType> {
        self.text_config
            .as_ref()
            .unwrap()
            .final_eos_token_ids
            .clone()
    }

    fn max_position_embeddings(&self) -> Option<usize> {
        self.text_config.as_ref().unwrap().max_position_embeddings
    }

    fn vocab_size(&self) -> Option<usize> {
        self.text_config.as_ref().unwrap().vocab_size
    }
}

impl ModelInfoType {
963
964
965
966
967
968
969
    pub fn from_disk(directory: &Path) -> Result<Self> {
        let f = CheckedFile::from_disk(directory.join("config.json")).with_context(|| {
            format!(
                "unable to extract config.json from directory {}",
                directory.display()
            )
        })?;
970
        Ok(Self::HfConfigJson(f))
971
    }
972
}
973

974
impl GenerationConfig {
975
976
977
978
979
980
981
982
983
    pub fn from_disk(directory: &Path) -> Result<Self> {
        let f = CheckedFile::from_disk(directory.join("generation_config.json")).with_context(
            || {
                format!(
                    "unable to extract generation_config from directory {}",
                    directory.display()
                )
            },
        )?;
984
        Ok(Self::HfGenerationConfigJson(f))
985
986
987
988
    }
}

impl PromptFormatterArtifact {
989
    pub fn from_disk(directory: &Path) -> Result<Option<Self>> {
990
991
        // we should only error if we expect a prompt formatter and it's not found
        // right now, we don't know when to expect it, so we just return Ok(Some/None)
992
        match CheckedFile::from_disk(directory.join("tokenizer_config.json")) {
993
994
995
            Ok(f) => Ok(Some(Self::HfTokenizerConfigJson(f))),
            Err(_) => Ok(None),
        }
996
997
    }

998
999
    pub fn chat_template_from_disk(directory: &Path) -> Result<Option<Self>> {
        match CheckedFile::from_disk(directory.join("chat_template.jinja")) {
1000
1001
1002
1003
            Ok(f) => Ok(Some(Self::HfChatTemplate {
                file: f,
                is_custom: false,
            })),
1004
1005
            Err(_) => Ok(None),
        }
1006
1007
1008
1009
    }
}

impl TokenizerKind {
1010
    pub fn from_disk(directory: &Path) -> Result<Self> {
Nikita's avatar
Nikita committed
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
        // 1. Try tokenizer.json (HuggingFace)
        if let Ok(f) = CheckedFile::from_disk(directory.join("tokenizer.json")) {
            return Ok(Self::HfTokenizerJson(f));
        }

        // 2. Try tiktoken.model
        if let Ok(f) = CheckedFile::from_disk(directory.join("tiktoken.model")) {
            return Ok(Self::TikTokenModel(f));
        }

        // 3. Search for any *.tiktoken file
        let tiktoken_files: Vec<_> = std::fs::read_dir(directory)
            .into_iter()
            .flatten()
            .flatten()
            .filter(|entry| entry.path().extension().is_some_and(|e| e == "tiktoken"))
            .collect();

        if tiktoken_files.len() == 1 {
            if let Ok(f) = CheckedFile::from_disk(tiktoken_files[0].path()) {
                return Ok(Self::TikTokenModel(f));
            }
        } else if tiktoken_files.len() > 1 {
            let names: Vec<_> = tiktoken_files
                .iter()
                .map(|e| e.path().display().to_string())
                .collect();
            anyhow::bail!(
                "Multiple .tiktoken files found in {}: {:?}. Cannot determine which to use.",
                directory.display(),
                names
            );
        }

        anyhow::bail!(
            "No tokenizer.json or tiktoken model file found in {}",
            directory.display()
        )
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
    }
}

/// Checks if the provided path is a valid local repository path.
///
/// # Arguments
/// * `path` - Path to validate
///
/// # Errors
/// Returns an error if the path doesn't exist or isn't a directory
fn check_valid_local_repo_path(path: impl AsRef<Path>) -> Result<()> {
    let path = path.as_ref();
    if !path.exists() {
        return Err(anyhow::anyhow!(
            "Model path does not exist: {}",
            path.display()
        ));
    }

    if !path.is_dir() {
        return Err(anyhow::anyhow!(
            "Model path is not a directory: {}",
            path.display()
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::HFConfig;
1080
    use std::collections::HashSet;
1081
1082
    use std::path::Path;

1083
1084
    #[test]
    pub fn test_config_json_llama3() -> anyhow::Result<()> {
1085
1086
        let config_file = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/data/sample-models/mock-llama-3.1-8b-instruct/config.json");
1087
        let config = HFConfig::from_json_file(&config_file)?;
1088
        assert_eq!(config.bos_token_id(), Some(128000));
1089
1090
1091
        // eos_token_ids can be in any order as long as the set is correct
        let eos_token_id_set: HashSet<_> = config.eos_token_ids().iter().cloned().collect();
        assert_eq!(eos_token_id_set, vec![128001, 128009].into_iter().collect());
1092
1093
1094
        Ok(())
    }

1095
1096
    #[test]
    pub fn test_config_json_llama4() -> anyhow::Result<()> {
1097
1098
        let config_file = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/data/sample-models/Llama-4-Scout-17B-16E-Instruct/config.json");
1099
        let config = HFConfig::from_json_file(&config_file)?;
1100
        assert_eq!(config.bos_token_id(), Some(200000));
1101
1102
        Ok(())
    }
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112

    /// The Python JSON parser accepts `Infinity` as a numeric value. This is explicitly against the
    /// JSON spec, but inevitably people rely on it, so we have to allow it.
    /// We treat that file as JSON5 (a lenient superset of JSON) to be able to parse it.
    #[test]
    fn test_invalid_json_but_py_accepts_it() {
        dynamo_runtime::logging::init();
        let path = "tests/data/sample-models/NVIDIA-Nemotron-Nano-12B-v2-Base/config.json";
        let _ = HFConfig::from_json_file(path).unwrap();
    }
1113
}