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

4
use std::env;
5
6
use std::path::{Path, PathBuf};

7
use modelexpress_client::{
8
9
    Client as MxClient, ClientConfig as MxClientConfig, ModelProvider as MxModelProvider,
};
10
use modelexpress_common::download as mx;
11

12
use dynamo_runtime::config::environment_names::model as env_model;
13

14
15
/// Download a model using ModelExpress client. The client first requests for the model
/// from the server and fallbacks to direct download in case of server failure.
16
/// If ignore_weights is true, model weight files will be skipped
17
/// Returns the path to the model files
18
pub async fn from_hf(name: impl AsRef<Path>, ignore_weights: bool) -> anyhow::Result<PathBuf> {
19
    let name = name.as_ref();
20
21
    let model_name = name.display().to_string();

22
    let mut config: MxClientConfig = MxClientConfig::default();
23
    if let Ok(endpoint) = env::var(env_model::model_express::MODEL_EXPRESS_URL) {
24
25
        config = config.with_endpoint(endpoint);
    }
26

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    let result = match MxClient::new(config).await {
        Ok(mut client) => {
            tracing::info!("Successfully connected to ModelExpress server");
            match client
                .request_model_with_provider_and_fallback(
                    &model_name,
                    MxModelProvider::HuggingFace,
                    ignore_weights,
                )
                .await
            {
                Ok(()) => {
                    tracing::info!("Server download succeeded for model: {model_name}");
                    match client.get_model_path(&model_name).await {
                        Ok(path) => Ok(path),
                        Err(e) => {
                            tracing::warn!(
                                "Failed to resolve local model path after server download for '{model_name}': {e}. \
                                Falling back to direct download."
                            );
                            mx_download_direct(&model_name, ignore_weights).await
                        }
49
50
                    }
                }
51
52
53
54
55
56
                Err(e) => {
                    tracing::warn!(
                        "Server download failed for model '{model_name}': {e}. Falling back to direct download."
                    );
                    mx_download_direct(&model_name, ignore_weights).await
                }
57
58
            }
        }
59
60
61
        Err(e) => {
            tracing::warn!("Cannot connect to ModelExpress server: {e}. Using direct download.");
            mx_download_direct(&model_name, ignore_weights).await
62
        }
63
    };
64

65
66
67
68
    match result {
        Ok(path) => {
            tracing::info!("ModelExpress download completed successfully for model: {model_name}");
            Ok(path)
69
        }
70
71
72
        Err(e) => {
            tracing::warn!("ModelExpress download failed for model '{model_name}': {e}");
            Err(e)
73
        }
74
    }
75
76
}

77
78
// Direct download using the ModelExpress client.
async fn mx_download_direct(model_name: &str, ignore_weights: bool) -> anyhow::Result<PathBuf> {
79
    let cache_dir = get_model_express_cache_dir();
80
81
82
83
84
85
86
    mx::download_model(
        model_name,
        MxModelProvider::HuggingFace,
        Some(cache_dir),
        ignore_weights,
    )
    .await
87
88
}

89
90
// TODO: remove in the future. This is a temporary workaround to find common
// cache directory between client and server.
91
fn get_model_express_cache_dir() -> PathBuf {
92
93
    // Check HF_HUB_CACHE environment variable
    // reference: https://huggingface.co/docs/huggingface_hub/en/package_reference/environment_variables#hfhubcache
94
    if let Ok(cache_path) = env::var(env_model::huggingface::HF_HUB_CACHE) {
95
96
97
        return PathBuf::from(cache_path);
    }

98
99
    // Check HF_HOME environment variable (standard Hugging Face cache directory)
    // reference: https://huggingface.co/docs/huggingface_hub/en/package_reference/environment_variables#hfhome
100
    if let Ok(hf_home) = env::var(env_model::huggingface::HF_HOME) {
101
102
103
        return PathBuf::from(hf_home).join("hub");
    }

104
    if let Ok(cache_path) = env::var(env_model::model_express::MODEL_EXPRESS_CACHE_PATH) {
105
106
        return PathBuf::from(cache_path);
    }
107

108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
    let home = env::var("HOME")
        .or_else(|_| env::var("USERPROFILE"))
        .unwrap_or_else(|_| ".".to_string());

    PathBuf::from(home).join(".cache/huggingface/hub")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_from_hf_with_model_express() {
        let test_path = PathBuf::from("test-model");
        let _result: anyhow::Result<PathBuf> = from_hf(test_path, false).await;
    }

    #[test]
    fn test_get_model_express_cache_dir() {
        let cache_dir = get_model_express_cache_dir();
        assert!(!cache_dir.to_string_lossy().is_empty());
        assert!(cache_dir.is_absolute() || cache_dir.starts_with("."));
    }
131
132
133
134
135
136
137

    #[serial_test::serial]
    #[test]
    fn test_get_model_express_cache_dir_with_hf_home() {
        // Test that HF_HOME is respected when set
        unsafe {
            // Clear other cache env vars to ensure HF_HOME is tested
138
139
140
            env::remove_var(env_model::huggingface::HF_HUB_CACHE);
            env::remove_var(env_model::model_express::MODEL_EXPRESS_CACHE_PATH);
            env::set_var(env_model::huggingface::HF_HOME, "/custom/cache/path");
141
142
143
144
            let cache_dir = get_model_express_cache_dir();
            assert_eq!(cache_dir, PathBuf::from("/custom/cache/path/hub"));

            // Clean up
145
            env::remove_var(env_model::huggingface::HF_HOME);
146
147
        }
    }
148
}