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

use std::fmt::Display;
5
use std::future::Future;
6
use std::path::PathBuf;
7
8
use std::pin::Pin;
use std::sync::Arc;
9

10
use pyo3::{exceptions::PyException, exceptions::PyValueError, prelude::*};
11
use pyo3_async_runtimes::TaskLocals;
12

13
14
15
use dynamo_kv_router::config::{
    KvRouterConfig as RsKvRouterConfig, RouterPrefillLoadModel as RsRouterPrefillLoadModel,
};
16
use dynamo_llm::discovery::LoadThresholdConfig as RsLoadThresholdConfig;
17
use dynamo_llm::entrypoint::ChatEngineFactoryCallback;
18
use dynamo_llm::entrypoint::EngineConfig as RsEngineConfig;
19
use dynamo_llm::entrypoint::RouterConfig as RsRouterConfig;
20
use dynamo_llm::entrypoint::input::Input;
Graham King's avatar
Graham King committed
21
use dynamo_llm::local_model::DEFAULT_HTTP_PORT;
22
use dynamo_llm::local_model::{LocalModel, LocalModelBuilder};
23
use dynamo_llm::mocker::make_mocker_engine;
24
25
use dynamo_llm::model_card::ModelDeploymentCard as RsModelDeploymentCard;
use dynamo_llm::types::openai::chat_completions::OpenAIChatCompletionsStreamingEngine;
26
27
use dynamo_mocker::common::perf_model::PerfModel;

28
use super::aic_callback::{create_aic_callback, create_aic_prefill_load_estimator};
29
30
use super::replay::MockEngineArgs as PyMockEngineArgs;
use dynamo_mocker::common::protocols::MockEngineArgs as RsMockEngineArgs;
31
use dynamo_runtime::discovery::ModelCardInstanceId as RsModelCardInstanceId;
32
use dynamo_runtime::protocols::EndpointId;
33

34
use super::local_model::ModelRuntimeConfig;
35
use super::model_card::ModelDeploymentCard;
36
use crate::RouterMode;
37
use crate::engine::PythonAsyncEngine;
38

39
40
41
42
43
#[pyclass(eq, eq_int)]
#[derive(Clone, Debug, PartialEq)]
#[repr(i32)]
pub enum EngineType {
    Echo = 1,
44
45
    Dynamic = 2,
    Mocker = 3,
46
47
}

48
#[pyclass]
49
#[derive(Default, Clone, Debug)]
50
51
52
53
pub struct KvRouterConfig {
    inner: RsKvRouterConfig,
}

54
55
impl KvRouterConfig {
    pub fn inner(&self) -> RsKvRouterConfig {
56
        self.inner.clone()
57
58
59
    }
}

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#[pyclass]
#[derive(Clone, Debug)]
pub struct AicPerfConfig {
    aic_backend: String,
    aic_system: String,
    aic_backend_version: Option<String>,
    aic_tp_size: usize,
    aic_model_path: String,
}

impl AicPerfConfig {
    pub(crate) fn backend_name(&self) -> &str {
        &self.aic_backend
    }

    pub(crate) fn system(&self) -> &str {
        &self.aic_system
    }

    pub(crate) fn backend_version(&self) -> Option<&str> {
        self.aic_backend_version.as_deref()
    }

    pub(crate) fn tp_size(&self) -> usize {
        self.aic_tp_size
    }

    pub(crate) fn model_path(&self) -> &str {
        &self.aic_model_path
    }
}

#[pymethods]
impl AicPerfConfig {
    #[new]
    #[pyo3(signature = (aic_backend, aic_system, aic_model_path, aic_tp_size=1, aic_backend_version=None))]
    fn new(
        aic_backend: String,
        aic_system: String,
        aic_model_path: String,
        aic_tp_size: usize,
        aic_backend_version: Option<String>,
    ) -> PyResult<Self> {
        if aic_backend.is_empty() {
            return Err(PyValueError::new_err("aic_backend must be non-empty"));
        }
        if aic_system.is_empty() {
            return Err(PyValueError::new_err("aic_system must be non-empty"));
        }
        if aic_model_path.is_empty() {
            return Err(PyValueError::new_err("aic_model_path must be non-empty"));
        }
        if aic_tp_size == 0 {
            return Err(PyValueError::new_err("aic_tp_size must be >= 1"));
        }

        Ok(Self {
            aic_backend,
            aic_system,
            aic_backend_version,
            aic_tp_size,
            aic_model_path,
        })
    }
}

126
127
128
#[pymethods]
impl KvRouterConfig {
    #[new]
129
    #[pyo3(signature = (overlap_score_weight=1.0, router_temperature=0.0, use_kv_events=true, durable_kv_events=false, router_replica_sync=false, router_track_active_blocks=true, router_track_output_blocks=false, router_assume_kv_reuse=true, router_track_prefill_tokens=true, router_prefill_load_model="none", router_snapshot_threshold=1000000, router_reset_states=false, router_ttl_secs=120.0, router_max_tree_size=1048576, router_prune_target_ratio=0.8, router_queue_threshold=Some(4.0), router_event_threads=4, router_queue_policy="fcfs", use_remote_indexer=false, serve_indexer=false, shared_cache_multiplier=0.0, shared_cache_type="none"))]
130
    #[allow(clippy::too_many_arguments)]
131
132
133
134
    fn new(
        overlap_score_weight: f64,
        router_temperature: f64,
        use_kv_events: bool,
135
        durable_kv_events: bool,
136
        router_replica_sync: bool,
137
        router_track_active_blocks: bool,
138
        router_track_output_blocks: bool,
139
        router_assume_kv_reuse: bool,
140
        router_track_prefill_tokens: bool,
141
        router_prefill_load_model: &str,
142
143
        router_snapshot_threshold: Option<u32>,
        router_reset_states: bool,
144
145
146
        router_ttl_secs: f64,
        router_max_tree_size: usize,
        router_prune_target_ratio: f64,
147
        router_queue_threshold: Option<f64>,
Yan Ru Pei's avatar
Yan Ru Pei committed
148
        router_event_threads: u32,
149
        router_queue_policy: &str,
150
151
        use_remote_indexer: bool,
        serve_indexer: bool,
152
153
        shared_cache_multiplier: f64,
        shared_cache_type: &str,
154
    ) -> Self {
155
156
157
158
159
        KvRouterConfig {
            inner: RsKvRouterConfig {
                overlap_score_weight,
                router_temperature,
                use_kv_events,
160
                durable_kv_events,
161
                router_replica_sync,
162
                router_track_active_blocks,
163
                router_track_output_blocks,
164
                router_assume_kv_reuse,
165
                router_track_prefill_tokens,
166
167
168
169
170
                router_prefill_load_model: router_prefill_load_model
                    .parse::<RsRouterPrefillLoadModel>()
                    .unwrap_or_else(|_| {
                        panic!("invalid router_prefill_load_model: {router_prefill_load_model:?}")
                    }),
171
172
                router_snapshot_threshold,
                router_reset_states,
173
174
175
                router_ttl_secs,
                router_max_tree_size,
                router_prune_target_ratio,
176
                router_queue_threshold,
Yan Ru Pei's avatar
Yan Ru Pei committed
177
                router_event_threads,
178
                skip_initial_worker_wait: false,
179
180
181
                router_queue_policy: router_queue_policy.parse().unwrap_or_else(|_| {
                    panic!("invalid router_queue_policy: {router_queue_policy:?}")
                }),
182
183
                use_remote_indexer,
                serve_indexer,
184
185
186
187
                shared_cache_multiplier,
                shared_cache_type: shared_cache_type
                    .parse()
                    .unwrap_or_else(|_| panic!("invalid shared_cache_type: {shared_cache_type:?}")),
188
189
190
            },
        }
    }
191
192
193
194
195
196
197

    #[staticmethod]
    fn from_json(config_json: &str) -> PyResult<Self> {
        serde_json::from_str::<RsKvRouterConfig>(config_json)
            .map(|inner| KvRouterConfig { inner })
            .map_err(|e| PyException::new_err(format!("Failed to parse KvRouterConfig JSON: {e}")))
    }
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
230
231
232
233
234
235
236

    fn dump_json(&self) -> PyResult<String> {
        serde_json::to_string(&self.inner)
            .map_err(|e| PyException::new_err(format!("Failed to serialize KvRouterConfig: {e}")))
    }

    fn copy(&self) -> Self {
        self.clone()
    }

    #[getter]
    fn overlap_score_weight(&self) -> f64 {
        self.inner.overlap_score_weight
    }

    #[setter]
    fn set_overlap_score_weight(&mut self, value: f64) -> PyResult<()> {
        if value < 0.0 {
            return Err(PyValueError::new_err(
                "overlap_score_weight must be non-negative",
            ));
        }
        self.inner.overlap_score_weight = value;
        Ok(())
    }

    #[pyo3(signature = (overlap_score_weight=None))]
    fn with_overrides(&self, overlap_score_weight: Option<f64>) -> PyResult<Self> {
        let mut inner = self.inner.clone();
        if let Some(weight) = overlap_score_weight {
            if weight < 0.0 {
                return Err(PyValueError::new_err(
                    "overlap_score_weight must be non-negative",
                ));
            }
            inner.overlap_score_weight = weight;
        }
        Ok(Self { inner })
    }
237
238
239
240
241
}

#[pyclass]
#[derive(Clone, Debug)]
pub struct RouterConfig {
242
243
244
245
246
247
    #[pyo3(get, set)]
    pub router_mode: RouterMode,

    #[pyo3(get, set)]
    pub kv_router_config: KvRouterConfig,

248
249
250
251
    /// Threshold for active decode blocks utilization (0.0-1.0)
    active_decode_blocks_threshold: Option<f64>,
    /// Threshold for active prefill tokens utilization (literal token count)
    active_prefill_tokens_threshold: Option<u64>,
252
253
    /// Threshold for active prefill tokens as fraction of max_num_batched_tokens
    active_prefill_tokens_threshold_frac: Option<f64>,
254
    enforce_disagg: bool,
255
256
257
258
259
}

#[pymethods]
impl RouterConfig {
    #[new]
260
    #[pyo3(signature = (mode, config=None, active_decode_blocks_threshold=None, active_prefill_tokens_threshold=None, active_prefill_tokens_threshold_frac=None, enforce_disagg=false))]
261
262
263
    pub fn new(
        mode: RouterMode,
        config: Option<KvRouterConfig>,
264
265
        active_decode_blocks_threshold: Option<f64>,
        active_prefill_tokens_threshold: Option<u64>,
266
        active_prefill_tokens_threshold_frac: Option<f64>,
267
        enforce_disagg: bool,
268
    ) -> Self {
269
270
271
        Self {
            router_mode: mode,
            kv_router_config: config.unwrap_or_default(),
272
273
            active_decode_blocks_threshold,
            active_prefill_tokens_threshold,
274
            active_prefill_tokens_threshold_frac,
275
            enforce_disagg,
276
277
278
279
280
281
282
283
284
        }
    }
}

impl From<RouterConfig> for RsRouterConfig {
    fn from(rc: RouterConfig) -> RsRouterConfig {
        RsRouterConfig {
            router_mode: rc.router_mode.into(),
            kv_router_config: rc.kv_router_config.inner,
285
286
287
288
289
            load_threshold_config: RsLoadThresholdConfig {
                active_decode_blocks_threshold: rc.active_decode_blocks_threshold,
                active_prefill_tokens_threshold: rc.active_prefill_tokens_threshold,
                active_prefill_tokens_threshold_frac: rc.active_prefill_tokens_threshold_frac,
            },
290
            enforce_disagg: rc.enforce_disagg,
291
292
293
294
        }
    }
}

295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/// Wrapper to hold Python callback and its TaskLocals for async execution
#[derive(Clone)]
struct PyEngineFactory {
    callback: Arc<PyObject>,
    locals: Arc<TaskLocals>,
}

impl std::fmt::Debug for PyEngineFactory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PyEngineFactory")
            .field("callback", &"<PyObject>")
            .finish()
    }
}

310
311
312
313
314
315
316
317
318
#[pyclass]
#[derive(Clone, Debug)]
pub(crate) struct EntrypointArgs {
    engine_type: EngineType,
    model_path: Option<PathBuf>,
    model_name: Option<String>,
    endpoint_id: Option<EndpointId>,
    context_length: Option<u32>,
    template_file: Option<PathBuf>,
319
    router_config: Option<RouterConfig>,
320
    kv_cache_block_size: Option<u32>,
321
    http_host: Option<String>,
Graham King's avatar
Graham King committed
322
    http_port: u16,
323
    http_metrics_port: Option<u16>,
Graham King's avatar
Graham King committed
324
325
    tls_cert_path: Option<PathBuf>,
    tls_key_path: Option<PathBuf>,
326
    extra_engine_args: Option<PathBuf>,
327
    mocker_engine_args: Option<PyMockEngineArgs>,
328
    runtime_config: Option<ModelRuntimeConfig>,
329
    namespace: Option<String>,
330
    namespace_prefix: Option<String>,
331
    is_prefill: bool,
332
    migration_limit: u32,
333
    migration_max_seq_len: Option<u32>,
334
    chat_engine_factory: Option<PyEngineFactory>,
335
    aic_perf_config: Option<AicPerfConfig>,
336
337
338
339
340
341
}

#[pymethods]
impl EntrypointArgs {
    #[allow(clippy::too_many_arguments)]
    #[new]
342
    #[pyo3(signature = (engine_type, model_path=None, model_name=None, endpoint_id=None, context_length=None, template_file=None, router_config=None, kv_cache_block_size=None, http_host=None, http_port=None, http_metrics_port=None, tls_cert_path=None, tls_key_path=None, extra_engine_args=None, mocker_engine_args=None, runtime_config=None, namespace=None, namespace_prefix=None, is_prefill=false, migration_limit=0, migration_max_seq_len=None, chat_engine_factory=None, aic_perf_config=None))]
343
    pub fn new(
344
        py: Python<'_>,
345
346
347
348
349
350
        engine_type: EngineType,
        model_path: Option<PathBuf>,
        model_name: Option<String>, // e.g. "dyn://namespace.component.endpoint"
        endpoint_id: Option<String>,
        context_length: Option<u32>,
        template_file: Option<PathBuf>,
351
        router_config: Option<RouterConfig>,
352
        kv_cache_block_size: Option<u32>,
353
        http_host: Option<String>,
354
        http_port: Option<u16>,
355
        http_metrics_port: Option<u16>,
Graham King's avatar
Graham King committed
356
357
        tls_cert_path: Option<PathBuf>,
        tls_key_path: Option<PathBuf>,
358
        extra_engine_args: Option<PathBuf>,
359
        mocker_engine_args: Option<PyMockEngineArgs>,
360
        runtime_config: Option<ModelRuntimeConfig>,
361
        namespace: Option<String>,
362
        namespace_prefix: Option<String>,
363
        is_prefill: bool,
364
        migration_limit: u32,
365
        migration_max_seq_len: Option<u32>,
366
        chat_engine_factory: Option<PyObject>,
367
        aic_perf_config: Option<AicPerfConfig>,
368
    ) -> PyResult<Self> {
369
        let endpoint_id_obj: Option<EndpointId> = endpoint_id.as_deref().map(EndpointId::from);
Graham King's avatar
Graham King committed
370
371
372
373
374
375
376
        if (tls_cert_path.is_some() && tls_key_path.is_none())
            || (tls_cert_path.is_none() && tls_key_path.is_some())
        {
            return Err(pyo3::exceptions::PyValueError::new_err(
                "tls_cert_path and tls_key_path must be provided together",
            ));
        }
377

378
379
        // Capture TaskLocals at registration time for the chat engine factory callback
        let chat_engine_factory = chat_engine_factory
380
381
382
            .map(|callback| {
                let locals = pyo3_async_runtimes::tokio::get_current_locals(py).map_err(|e| {
                    pyo3::exceptions::PyRuntimeError::new_err(format!(
383
                        "Failed to get TaskLocals for chat_engine_factory: {}",
384
385
386
387
388
389
390
391
392
393
                        e
                    ))
                })?;
                Ok::<_, PyErr>(PyEngineFactory {
                    callback: Arc::new(callback),
                    locals: Arc::new(locals),
                })
            })
            .transpose()?;

394
395
396
397
398
399
400
        Ok(EntrypointArgs {
            engine_type,
            model_path,
            model_name,
            endpoint_id: endpoint_id_obj,
            context_length,
            template_file,
401
            router_config,
402
            kv_cache_block_size,
403
            http_host,
Graham King's avatar
Graham King committed
404
            http_port: http_port.unwrap_or(DEFAULT_HTTP_PORT),
405
            http_metrics_port,
Graham King's avatar
Graham King committed
406
407
            tls_cert_path,
            tls_key_path,
408
            extra_engine_args,
409
            mocker_engine_args,
410
            runtime_config,
411
            namespace,
412
            namespace_prefix,
413
            is_prefill,
414
            migration_limit,
415
            migration_max_seq_len,
416
            chat_engine_factory,
417
            aic_perf_config,
418
419
420
421
422
423
424
425
426
427
        })
    }
}

#[pyclass]
#[derive(Clone)]
pub(crate) struct EngineConfig {
    inner: RsEngineConfig,
}

428
429
/// Create the backend engine wrapper to run the model.
/// Download the model if necessary.
430
431
432
433
434
435
436
437
438
#[pyfunction]
#[pyo3(signature = (distributed_runtime, args))]
pub fn make_engine<'p>(
    py: Python<'p>,
    distributed_runtime: super::DistributedRuntime,
    args: EntrypointArgs,
) -> PyResult<Bound<'p, PyAny>> {
    let mut builder = LocalModelBuilder::default();
    builder
439
440
441
442
443
        .model_name(
            args.model_name
                .clone()
                .or_else(|| args.model_path.clone().map(|p| p.display().to_string())),
        )
444
        .endpoint_id(args.endpoint_id.clone())
445
        .context_length(args.context_length)
446
        .request_template(args.template_file.clone())
447
        .kv_cache_block_size(args.kv_cache_block_size)
448
        .router_config(args.router_config.clone().map(|rc| rc.into()))
449
        .migration_limit(Some(args.migration_limit))
450
        .migration_max_seq_len(args.migration_max_seq_len)
451
        .http_host(args.http_host.clone())
452
        .http_port(args.http_port)
453
        .http_metrics_port(args.http_metrics_port)
Graham King's avatar
Graham King committed
454
455
        .tls_cert_path(args.tls_cert_path.clone())
        .tls_key_path(args.tls_key_path.clone())
456
        .is_mocker(matches!(args.engine_type, EngineType::Mocker))
457
        .extra_engine_args(args.extra_engine_args.clone())
458
        .runtime_config(args.runtime_config.clone().unwrap_or_default().inner)
459
460
        .namespace(args.namespace.clone())
        .namespace_prefix(args.namespace_prefix.clone());
461
    pyo3_async_runtimes::tokio::future_into_py(py, async move {
462
463
464
465
        if let Some(model_path) = args.model_path.clone() {
            let local_path = if model_path.exists() {
                model_path
            } else {
466
467
                // Mocker only needs tokenizer, not weights
                let ignore_weights = matches!(args.engine_type, EngineType::Mocker);
468
469
470
471
472
                // Preserve the original HF model ID as source_path so the
                // frontend can resolve model metadata even when the served
                // model name differs (e.g., --model-name model-1 --model-path
                // Qwen/Qwen3-0.6B).
                builder.source_path(model_path.clone());
473
                LocalModel::fetch(&model_path.display().to_string(), ignore_weights)
474
475
476
477
478
479
                    .await
                    .map_err(to_pyerr)?
            };
            builder.model_path(local_path);
        }

480
        let local_model = builder.build().await.map_err(to_pyerr)?;
481
        let inner = select_engine(distributed_runtime, args, local_model)
482
483
484
485
486
487
            .await
            .map_err(to_pyerr)?;
        Ok(EngineConfig { inner })
    })
}

488
489
/// Convert a PyEngineFactory to a Rust ChatEngineFactoryCallback
fn py_engine_factory_to_callback(factory: PyEngineFactory) -> ChatEngineFactoryCallback {
490
491
492
493
    let callback = factory.callback;
    let locals = factory.locals;

    Arc::new(
494
495
496
        move |instance_id: RsModelCardInstanceId,
              card: RsModelDeploymentCard|
              -> Pin<
497
498
499
500
501
502
503
504
            Box<dyn Future<Output = anyhow::Result<OpenAIChatCompletionsStreamingEngine>> + Send>,
        > {
            let callback = callback.clone();
            let locals = locals.clone();

            Box::pin(async move {
                // Acquire GIL to call Python callback and convert coroutine to future
                let py_future = Python::with_gil(|py| {
505
506
507
508
                    let py_instance_id =
                        Py::new(py, crate::ModelCardInstanceId { inner: instance_id }).map_err(
                            |e| anyhow::anyhow!("Failed to create Python ModelCardInstanceId: {e}"),
                        )?;
509
510
511
                    // Create Python ModelDeploymentCard wrapper
                    let py_card = ModelDeploymentCard { inner: card };
                    let py_card_obj = Py::new(py, py_card)
512
                        .map_err(|e| anyhow::anyhow!("Failed to create Python MDC: {e}"))?;
513
514
515

                    // Call Python async function to get a coroutine
                    let coroutine = callback
516
517
                        .call1(py, (py_instance_id, py_card_obj))
                        .map_err(|e| anyhow::anyhow!("Failed to call chat_engine_factory: {e}"))?;
518
519
520

                    // Use the TaskLocals captured at registration time
                    pyo3_async_runtimes::into_future_with_locals(&locals, coroutine.into_bound(py))
521
                        .map_err(|e| anyhow::anyhow!("Failed to convert coroutine to future: {e}"))
522
523
524
525
526
                })?;

                // Await the Python coroutine (GIL is released during await)
                let py_result = py_future
                    .await
527
                    .map_err(|e| anyhow::anyhow!("chat_engine_factory callback failed: {}", e))?;
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542

                // Extract PythonAsyncEngine from the Python result and wrap in Arc
                let engine: OpenAIChatCompletionsStreamingEngine = Python::with_gil(|py| {
                    let engine: PythonAsyncEngine = py_result.extract(py).map_err(|e| {
                        anyhow::anyhow!("Failed to extract PythonAsyncEngine: {}", e)
                    })?;
                    Ok::<_, anyhow::Error>(Arc::new(engine))
                })?;

                Ok(engine)
            })
        },
    )
}

543
544
async fn select_engine(
    #[allow(unused_variables)] distributed_runtime: super::DistributedRuntime,
545
    args: EntrypointArgs,
546
547
    local_model: LocalModel,
) -> anyhow::Result<RsEngineConfig> {
548
    let inner = match args.engine_type {
549
550
        EngineType::Echo => {
            // There is no validation for the echo engine
551
            RsEngineConfig::InProcessText {
552
                model: Box::new(local_model),
553
                engine: dynamo_llm::engines::make_echo_engine(),
554
555
            }
        }
556
        EngineType::Dynamic => {
557
558
            //  Convert Python chat engine factory to Rust callback
            let chat_engine_factory = args.chat_engine_factory.map(py_engine_factory_to_callback);
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
            let prefill_load_estimator = args
                .aic_perf_config
                .as_ref()
                .map(|config| {
                    Python::with_gil(|py| {
                        create_aic_prefill_load_estimator(
                            py,
                            config.backend_name(),
                            config.system(),
                            config.model_path(),
                            config.tp_size(),
                            config.backend_version(),
                        )
                    })
                })
                .transpose()?;
575
576
            RsEngineConfig::Dynamic {
                model: Box::new(local_model),
577
                chat_engine_factory,
578
                prefill_load_estimator,
579
580
            }
        }
581
        EngineType::Mocker => {
582
583
584
585
            let mut mocker_args = if let Some(mocker_engine_args) = args.mocker_engine_args {
                mocker_engine_args.inner()
            } else if let Some(extra_args_path) = args.extra_engine_args {
                RsMockEngineArgs::from_json_file(&extra_args_path).map_err(|e| {
586
587
588
589
590
591
592
593
594
595
                    anyhow::anyhow!(
                        "Failed to load mocker args from {:?}: {}",
                        extra_args_path,
                        e
                    )
                })?
            } else {
                tracing::warn!(
                    "No extra_engine_args specified for mocker engine. Using default mocker args."
                );
596
                RsMockEngineArgs::default()
597
598
            };

599
600
601
602
603
604
605
606
607
608
            // If aic_backend is set, create Python AIC callback and override perf_model
            if let Some(ref backend_name) = mocker_args.aic_backend {
                let backend = backend_name.clone();
                let system = mocker_args.aic_system.as_deref().unwrap_or("h200_sxm");
                let model_name = mocker_args
                    .aic_model_path
                    .as_deref()
                    .unwrap_or_else(|| local_model.card().source_path());
                let backend_version = mocker_args.aic_backend_version.as_deref();
                let tp_size = mocker_args.aic_tp_size.unwrap_or(1);
609
610
611
                let moe_tp_size = mocker_args.aic_moe_tp_size;
                let moe_ep_size = mocker_args.aic_moe_ep_size;
                let attention_dp_size = mocker_args.aic_attention_dp_size;
612
                match Python::with_gil(|py| {
613
614
615
616
617
618
619
620
621
622
623
                    create_aic_callback(
                        py,
                        &backend,
                        system,
                        model_name,
                        tp_size,
                        backend_version,
                        moe_tp_size,
                        moe_ep_size,
                        attention_dp_size,
                    )
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
                }) {
                    Ok(callback) => {
                        tracing::info!(
                            "AIC perf model: backend={}, gpu={}, model={}, version={:?}",
                            backend,
                            system,
                            model_name,
                            backend_version
                        );
                        mocker_args.perf_model = Arc::new(PerfModel::from_aic_callback(callback));
                    }
                    Err(e) => {
                        return Err(anyhow::anyhow!(
                            "Failed to create AIC callback (--aic-perf-model was requested): {}",
                            e
                        ));
                    }
                }
            }

644
645
            let endpoint = local_model.endpoint_id().clone();

646
            let engine =
647
                make_mocker_engine(distributed_runtime.inner, endpoint, mocker_args).await?;
648

649
            RsEngineConfig::InProcessTokens {
650
651
                engine,
                model: Box::new(local_model),
652
                is_prefill: args.is_prefill,
653
654
            }
        }
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
    };

    Ok(inner)
}

#[pyfunction]
#[pyo3(signature = (distributed_runtime, input, engine_config))]
pub fn run_input<'p>(
    py: Python<'p>,
    distributed_runtime: super::DistributedRuntime,
    input: &str,
    engine_config: EngineConfig,
) -> PyResult<Bound<'p, PyAny>> {
    let input_enum: Input = input.parse().map_err(to_pyerr)?;
    pyo3_async_runtimes::tokio::future_into_py(py, async move {
        dynamo_llm::entrypoint::input::run_input(
671
            distributed_runtime.inner.clone(),
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
            input_enum,
            engine_config.inner,
        )
        .await
        .map_err(to_pyerr)?;
        Ok(())
    })
}

pub fn to_pyerr<E>(err: E) -> PyErr
where
    E: Display,
{
    PyException::new_err(format!("{}", err))
}