"lib/llm/src/discovery/watcher.rs" did not exist on "5ed8c1c0ffb607136ff52777ad65c878a33a393d"
flags.rs 8.49 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::collections::HashMap;
5
6
use std::path::PathBuf;

7
use clap::ValueEnum;
8
use dynamo_llm::entrypoint::RouterConfig;
9
use dynamo_llm::kv_router::KvRouterConfig;
10
use dynamo_llm::mocker::protocols::MockEngineArgs;
11
use dynamo_runtime::pipeline::RouterMode as RuntimeRouterMode;
12

13
14
use crate::Output;

15
16
17
18
/// Required options depend on the in and out choices
#[derive(clap::Parser, Debug, Clone)]
#[command(version, about, long_about = None)]
pub struct Flags {
19
20
21
22
23
24
    /// The model. The options depend on the engine.
    ///
    /// The full list - only mistralrs supports all three currently:
    /// - Full path of a checked out Hugging Face repository containing safetensor files
    /// - Name of a Hugging Face repository, e.g 'google/flan-t5-small'. The model will be
    ///   downloaded and cached.
25
26
27
    #[arg(index = 1)]
    pub model_path_pos: Option<PathBuf>,

28
    // `--model-path`. The one above is `dynamo-run <positional-model-path>`
29
30
31
32
    #[arg(long = "model-path")]
    pub model_path_flag: Option<PathBuf>,

    /// HTTP port. `in=http` only
Graham King's avatar
Graham King committed
33
    /// If tls_cert_path and tls_key_path are provided, this will be TLS/HTTPS.
34
35
36
    #[arg(long, default_value = "8080")]
    pub http_port: u16,

Graham King's avatar
Graham King committed
37
38
39
40
41
42
43
44
    /// TLS certificate file
    #[arg(long, requires = "tls_key_path")]
    pub tls_cert_path: Option<PathBuf>,

    /// TLS certificate key file
    #[arg(long, requires = "tls_cert_path")]
    pub tls_key_path: Option<PathBuf>,

45
46
47
48
    /// The name of the model we are serving
    #[arg(long)]
    pub model_name: Option<String>,

49
50
51
52
    /// Verbose output (-v for debug, -vv for trace)
    #[arg(short = 'v', action = clap::ArgAction::Count, default_value_t = 0)]
    pub verbosity: u8,

53
    /// If using `out=dyn` with multiple instances, this says how to route the requests.
54
55
    ///
    /// Mostly interesting for KV-aware routing.
56
57
    /// Defaults to RouterMode::RoundRobin
    #[arg(long, default_value = "round-robin")]
58
59
    pub router_mode: RouterMode,

60
    /// KV Router: Weight for overlap score in worker selection.
61
    /// Higher values prioritize KV cache reuse. Default: 1.0
62
63
64
    #[arg(long)]
    pub kv_overlap_score_weight: Option<f64>,

65
66
    /// KV Router: Temperature for worker sampling via softmax.
    /// Higher values promote more randomness, and 0 fallbacks to deterministic.
67
    /// Default: 0.0
68
    #[arg(long)]
69
    pub router_temperature: Option<f64>,
70

71
72
73
74
75
76
77
    /// KV Router: Whether to use KV events to maintain the view of cached blocks
    /// If false, would use ApproxKvRouter for predicting block creation / deletion
    /// based only on incoming requests at a timer.
    /// Default: true
    #[arg(long)]
    pub use_kv_events: Option<bool>,

78
79
80
81
82
83
    /// KV Router: Whether to enable replica synchronization across multiple router instances.
    /// When true, routers will publish and subscribe to events to maintain consistent state.
    /// Default: false
    #[arg(long)]
    pub router_replica_sync: Option<bool>,

84
85
86
87
88
89
90
    /// KV Router: Whether to track active blocks in the router for memory management.
    /// When false, the router will not maintain state about which blocks are active,
    /// reducing memory overhead but potentially affecting scheduling decisions.
    /// Default: true
    #[arg(long)]
    pub router_track_active_blocks: Option<bool>,

91
92
93
94
    /// Max model context length. Reduce this if you don't have enough VRAM for the full model
    /// context length (e.g. Llama 4).
    /// Defaults to the model's max, which is usually model_max_length in tokenizer_config.json.
    #[arg(long)]
95
    pub context_length: Option<u32>,
96

97
    /// KV cache block size (is this used? Maybe by Python vllm worker?)
98
    #[arg(long)]
99
    pub kv_cache_block_size: Option<u32>,
100

101
    /// Mocker engine only.
102
103
104
105
106
    /// Additional engine-specific arguments from a JSON file.
    /// Contains a mapping of parameter names to values.
    #[arg(long)]
    pub extra_engine_args: Option<PathBuf>,

107
108
109
110
111
112
113
114
115
116
117
    /// Path to a JSON file containing default request fields.
    /// These fields will be merged with each request, but can be overridden by the request.
    /// Example file contents:
    /// {
    ///     "model": "Qwen2.5-3B-Instruct",
    ///     "temperature": 0.7,
    ///     "max_completion_tokens": 4096
    /// }
    #[arg(long)]
    pub request_template: Option<PathBuf>,

118
119
120
121
122
    /// How many times a request can be migrated to another worker if the HTTP server lost
    /// connection to the current worker.
    #[arg(long, value_parser = clap::value_parser!(u32).range(0..1024))]
    pub migration_limit: Option<u32>,

123
124
125
126
127
128
    /// Which key-value backend to use: etcd, mem, file.
    /// Etcd uses the ETCD_* env vars (e.g. ETCD_ENPOINTS) for connection details.
    /// File uses root dir from env var DYN_FILE_KV or defaults to $TMPDIR/dynamo_store_kv.
    #[arg(long, default_value = "etcd")]
    pub store_kv: String,

129
130
131
132
133
134
135
    /// Everything after a `--`.
    /// These are the command line arguments to the python engine when using `pystr` or `pytok`.
    #[arg(index = 2, last = true, hide = true, allow_hyphen_values = true)]
    pub last: Vec<String>,
}

impl Flags {
136
137
    /// For each Output variant, check if it would be able to run.
    /// This takes validation out of the main engine creation path.
138
    pub fn validate(&self, out_opt: &Output) -> anyhow::Result<()> {
139
        match out_opt {
140
            Output::Auto => {
141
                if self.context_length.is_some() {
142
143
144
                    anyhow::bail!(
                        "'--context-length' flag should only be used on the worker node, not on the ingress"
                    );
145
146
                }
                if self.kv_cache_block_size.is_some() {
147
148
149
                    anyhow::bail!(
                        "'--kv-cache-block-size' flag should only be used on the worker node, not on the ingress"
                    );
150
                }
151
                if self.migration_limit.is_some() {
152
153
154
                    anyhow::bail!(
                        "'--migration-limit' flag should only be used on the worker node, not on the ingress"
                    );
155
                }
156
            }
157
            Output::Echo => {}
158
159
            #[cfg(feature = "mistralrs")]
            Output::MistralRs => {}
160
161
162
            Output::Mocker => {
                // nothing to check here
            }
163
        }
164
165
166
167
168
169
170
171
172
173

        match out_opt {
            Output::Mocker => {}
            _ => {
                if self.extra_engine_args.is_some() {
                    anyhow::bail!("`--extra-engine-args` is only for the mocker engine");
                }
            }
        }

174
        Ok(())
175
176
    }

177
178
179
180
181
    pub fn router_config(&self) -> RouterConfig {
        RouterConfig::new(
            self.router_mode.into(),
            KvRouterConfig::new(
                self.kv_overlap_score_weight,
182
                self.router_temperature,
183
                self.use_kv_events,
184
                self.router_replica_sync,
185
                self.router_track_active_blocks,
186
187
188
                // defaulting below args (no longer maintaining new flags for dynamo-run)
                None,
                None,
189
190
            ),
        )
191
    }
192
193
194
195
196
197
198
199
200
201
202
203
204
205

    /// Load extra engine arguments from a JSON file
    /// Returns a HashMap of parameter names to values
    pub fn load_extra_engine_args(
        &self,
    ) -> anyhow::Result<Option<HashMap<String, serde_json::Value>>> {
        if let Some(path) = &self.extra_engine_args {
            let file_content = std::fs::read_to_string(path)?;
            let args: HashMap<String, serde_json::Value> = serde_json::from_str(&file_content)?;
            Ok(Some(args))
        } else {
            Ok(None)
        }
    }
206
207
208
209
210
211
212
213
214

    pub fn mocker_config(&self) -> MockEngineArgs {
        let Some(path) = &self.extra_engine_args else {
            tracing::warn!("Did not specify extra engine args. Using default mocker args.");
            return MockEngineArgs::default();
        };
        MockEngineArgs::from_json_file(path)
            .unwrap_or_else(|e| panic!("Failed to build mocker engine args from {path:?}: {e}"))
    }
215
216
}

217
#[derive(Default, PartialEq, Eq, ValueEnum, Clone, Debug, Copy)]
218
219
220
221
pub enum RouterMode {
    #[default]
    #[value(name = "round-robin")]
    RoundRobin,
222
    Random,
223
224
225
226
    #[value(name = "kv")]
    KV,
}

227
228
229
230
231
232
impl From<RouterMode> for RuntimeRouterMode {
    fn from(r: RouterMode) -> RuntimeRouterMode {
        match r {
            RouterMode::RoundRobin => RuntimeRouterMode::RoundRobin,
            RouterMode::Random => RuntimeRouterMode::Random,
            RouterMode::KV => RuntimeRouterMode::KV,
233
234
235
        }
    }
}