kv.rs 35.4 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 pythonize::{depythonize, pythonize};
5
use std::collections::HashMap;
6
use std::sync::atomic::AtomicU32;
7
use tokio_stream::StreamExt;
8

9
use super::*;
10
use crate::Component;
Yan Ru Pei's avatar
Yan Ru Pei committed
11
use llm_rs::kv_router::indexer::compute_block_hash_for_seq;
12
use llm_rs::kv_router::indexer::KvIndexerInterface;
13
14
15
16
use llm_rs::kv_router::protocols::ForwardPassMetrics as RsForwardPassMetrics;
use llm_rs::kv_router::protocols::KvStats as RsKvStats;
use llm_rs::kv_router::protocols::SpecDecodeStats as RsSpecDecodeStats;
use llm_rs::kv_router::protocols::WorkerStats as RsWorkerStats;
17
use rs::traits::events::EventSubscriber;
18
use tracing;
19

20
use llm_rs::kv_router::protocols::*;
21
use llm_rs::kv_router::publisher::{create_stored_blocks, KvEventSourceConfig};
22
use llm_rs::protocols::common::{OutputOptions, SamplingOptions, StopConditions};
23

Yan Ru Pei's avatar
Yan Ru Pei committed
24
25
26
27
28
29
#[pyfunction]
pub fn compute_block_hash_for_seq_py(tokens: Vec<u32>, kv_block_size: usize) -> PyResult<Vec<u64>> {
    if kv_block_size == 0 {
        return Err(to_pyerr(anyhow::anyhow!("kv_block_size cannot be 0")));
    }

30
    let hashes = compute_block_hash_for_seq(&tokens, kv_block_size as u32);
Yan Ru Pei's avatar
Yan Ru Pei committed
31
32
33
    Ok(hashes.into_iter().map(|h| h.0).collect())
}

GuanLuo's avatar
GuanLuo committed
34
#[pyclass]
35
36
pub(crate) struct WorkerMetricsPublisher {
    inner: Arc<llm_rs::kv_router::publisher::WorkerMetricsPublisher>,
GuanLuo's avatar
GuanLuo committed
37
38
39
}

#[pymethods]
40
impl WorkerMetricsPublisher {
GuanLuo's avatar
GuanLuo committed
41
42
    #[new]
    fn new() -> PyResult<Self> {
43
44
        let inner =
            llm_rs::kv_router::publisher::WorkerMetricsPublisher::new().map_err(to_pyerr)?;
GuanLuo's avatar
GuanLuo committed
45
46
47
48
49
        Ok(Self {
            inner: inner.into(),
        })
    }

50
    #[pyo3(signature = (component, metrics_labels = None))]
Alec's avatar
Alec committed
51
    fn create_endpoint<'p>(
GuanLuo's avatar
GuanLuo committed
52
53
54
        &self,
        py: Python<'p>,
        component: Component,
55
        metrics_labels: Option<Vec<(String, String)>>,
GuanLuo's avatar
GuanLuo committed
56
57
58
59
    ) -> PyResult<Bound<'p, PyAny>> {
        let rs_publisher = self.inner.clone();
        let rs_component = component.inner.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
            // Convert Python labels to Option<&[(&str, &str)]> expected by Rust API
            let metrics_labels_ref: Option<Vec<(&str, &str)>> =
                if let Some(metrics_labels) = metrics_labels.as_ref() {
                    if metrics_labels.is_empty() {
                        None
                    } else {
                        Some(
                            metrics_labels
                                .iter()
                                .map(|(k, v)| (k.as_str(), v.as_str()))
                                .collect(),
                        )
                    }
                } else {
                    None
                };

77
78
79
80
81
            // Register Prometheus metrics first
            rs_publisher
                .register_prometheus_metrics(&rs_component)
                .map_err(to_pyerr)?;

82
            rs_publisher
83
                .create_endpoint(rs_component, metrics_labels_ref.as_deref())
GuanLuo's avatar
GuanLuo committed
84
85
86
87
88
89
                .await
                .map_err(to_pyerr)?;
            Ok(())
        })
    }

90
91
92
    #[pyo3(signature = (metrics))]
    fn publish(&self, _py: Python, metrics: &ForwardPassMetrics) -> PyResult<()> {
        // Create and publish the complete metrics
GuanLuo's avatar
GuanLuo committed
93
        self.inner
94
            .publish(metrics.0.clone().into())
GuanLuo's avatar
GuanLuo committed
95
96
97
            .map_err(to_pyerr)
    }
}
98

99
100
#[pyclass]
#[derive(Clone)]
101
pub struct ZmqKvEventPublisherConfig {
102
103
104
105
106
107
108
109
110
111
112
    #[pyo3(get, set)]
    pub worker_id: i64,
    #[pyo3(get, set)]
    pub kv_block_size: usize,
    #[pyo3(get, set)]
    pub zmq_endpoint: String,
    #[pyo3(get, set)]
    pub zmq_topic: String,
}

#[pymethods]
113
impl ZmqKvEventPublisherConfig {
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
    #[new]
    #[pyo3(signature = (
        worker_id,
        kv_block_size,
        zmq_endpoint = "tcp://127.0.0.1:5557".to_string(),
        zmq_topic = "".to_string()
    ))]
    pub fn new(
        worker_id: i64,
        kv_block_size: usize,
        zmq_endpoint: String,
        zmq_topic: String,
    ) -> Self {
        Self {
            worker_id,
            kv_block_size,
            zmq_endpoint,
            zmq_topic,
        }
    }
}

#[pyclass]
137
pub(crate) struct ZmqKvEventPublisher {
138
    inner: llm_rs::kv_router::publisher::KvEventPublisher,
139
140
141
}

#[pymethods]
142
impl ZmqKvEventPublisher {
143
    #[new]
144
    fn new(component: Component, config: ZmqKvEventPublisherConfig) -> PyResult<Self> {
145
        let inner = llm_rs::kv_router::publisher::KvEventPublisher::new(
146
147
            component.inner,
            config.worker_id,
148
            config.kv_block_size as u32,
149
150
151
152
153
154
            Some(KvEventSourceConfig::Zmq {
                endpoint: config.zmq_endpoint,
                topic: config.zmq_topic,
            }),
        )
        .map_err(to_pyerr)?;
155
156
157
158
159
160
161
162
        Ok(Self { inner })
    }

    fn shutdown(&mut self) {
        self.inner.shutdown()
    }
}

Yan Ru Pei's avatar
Yan Ru Pei committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/// A ZMQ-based key-value cache event listener that operates independently
/// of the dynamo runtime or event plane infrastructure.
#[pyclass]
pub(crate) struct ZmqKvEventListener {
    event_receiver: Arc<tokio::sync::Mutex<tokio::sync::mpsc::UnboundedReceiver<KvCacheEvent>>>,
    shutdown_token: tokio_util::sync::CancellationToken,
}

#[pymethods]
impl ZmqKvEventListener {
    #[new]
    fn new(zmq_endpoint: String, zmq_topic: String, kv_block_size: usize) -> PyResult<Self> {
        if kv_block_size == 0 {
            return Err(to_pyerr(anyhow::anyhow!("kv_block_size cannot be 0")));
        }

        let runtime = pyo3_async_runtimes::tokio::get_runtime();
        runtime.block_on(async {
            let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<KvCacheEvent>();
            let shutdown_token = tokio_util::sync::CancellationToken::new();

            tokio::spawn(llm_rs::kv_router::publisher::start_zmq_listener(
                zmq_endpoint,
                zmq_topic,
                tx,
                shutdown_token.clone(),
189
                kv_block_size as u32,
Yan Ru Pei's avatar
Yan Ru Pei committed
190
191
192
193
194
195
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
230
231
            ));

            Ok(Self {
                event_receiver: Arc::new(tokio::sync::Mutex::new(rx)),
                shutdown_token,
            })
        })
    }

    fn get_events<'p>(&self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> {
        let receiver = self.event_receiver.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let mut rx = receiver.lock().await;
            let mut events = Vec::new();

            // Drain all available events
            while let Ok(event) = rx.try_recv() {
                events.push(event);
            }

            // Convert events to JSON strings
            let json_events: Result<Vec<String>, _> =
                events.iter().map(serde_json::to_string).collect();

            match json_events {
                Ok(json_strings) => Ok(json_strings),
                Err(e) => Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                    "Failed to serialize events to JSON: {}",
                    e
                ))),
            }
        })
    }
}

// manual shutdown needed as it's not tied to the dynamo DRT
impl Drop for ZmqKvEventListener {
    fn drop(&mut self) {
        self.shutdown_token.cancel();
    }
}

232
233
234
#[pyclass]
pub(crate) struct KvEventPublisher {
    inner: Arc<llm_rs::kv_router::publisher::KvEventPublisher>,
235
236
    kv_block_size: usize,
    warning_count: Arc<AtomicU32>,
237
238
239
240
241
242
}

#[pymethods]
impl KvEventPublisher {
    #[new]
    fn new(component: Component, worker_id: i64, kv_block_size: usize) -> PyResult<Self> {
Yan Ru Pei's avatar
Yan Ru Pei committed
243
244
245
246
        if kv_block_size == 0 {
            return Err(to_pyerr(anyhow::anyhow!("kv_block_size cannot be 0")));
        }

247
        let inner = llm_rs::kv_router::publisher::KvEventPublisher::new(
248
            component.inner,
249
            worker_id,
250
            kv_block_size as u32,
251
            None,
252
253
        )
        .map_err(to_pyerr)?;
254

255
256
        Ok(Self {
            inner: inner.into(),
257
258
            kv_block_size,
            warning_count: Arc::new(AtomicU32::new(0)),
259
260
261
262
263
264
265
266
267
268
269
        })
    }

    #[allow(clippy::too_many_arguments)]
    #[pyo3(signature = (event_id, token_ids, num_block_tokens, block_hashes, lora_id, parent_hash=None))]
    fn publish_stored(
        &mut self,
        _py: Python,
        event_id: u64,
        token_ids: Vec<u32>,
        num_block_tokens: Vec<u64>,
270
        block_hashes: Vec<i64>,
271
        lora_id: u64,
272
        parent_hash: Option<i64>,
273
274
275
276
    ) -> PyResult<()> {
        let event = KvCacheEvent {
            event_id,
            data: KvCacheEventData::Stored(KvCacheStoreData {
277
278
                parent_hash: parent_hash.map(ExternalSequenceBlockHash::from),
                blocks: create_stored_blocks(
279
                    self.kv_block_size as u32,
280
281
282
283
                    &token_ids,
                    &num_block_tokens,
                    &block_hashes,
                    lora_id,
284
                    &self.warning_count,
285
286
287
288
289
290
291
                ),
            }),
        };

        self.inner.publish(event).map_err(to_pyerr)
    }

292
    fn publish_removed(&self, _py: Python, event_id: u64, block_hashes: Vec<i64>) -> PyResult<()> {
293
294
        let block_hashes: Vec<ExternalSequenceBlockHash> = block_hashes
            .iter()
295
            .map(|&h| ExternalSequenceBlockHash::from(h))
296
297
298
299
300
301
302
303
304
305
            .collect();
        let event = KvCacheEvent {
            event_id,
            data: KvCacheEventData::Removed(KvCacheRemoveData { block_hashes }),
        };

        self.inner.publish(event).map_err(to_pyerr)
    }
}

306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#[pyclass]
#[derive(Clone)]
pub(crate) struct OverlapScores {
    inner: llm_rs::kv_router::indexer::OverlapScores,
}

#[pymethods]
impl OverlapScores {
    #[getter]
    fn scores(&self) -> HashMap<llm_rs::kv_router::indexer::WorkerId, u32> {
        self.inner.scores.clone()
    }

    #[getter]
    fn frequencies(&self) -> Vec<usize> {
        self.inner.frequencies.clone()
    }
}

Yan Ru Pei's avatar
Yan Ru Pei committed
325
326
327
328
329
330
331
332
333
334
335
336
337
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
371
372
373
// NOTE: the user needs to guarantee that this stays single threaded in Python land
#[pyclass(unsendable)]
pub(crate) struct RadixTree {
    inner: llm_rs::kv_router::indexer::RadixTree,
}

#[pymethods]
impl RadixTree {
    #[new]
    #[pyo3(signature = (expiration_duration_secs=None))]
    fn new(expiration_duration_secs: Option<f64>) -> PyResult<Self> {
        let expiration_duration = expiration_duration_secs.map(std::time::Duration::from_secs_f64);
        let inner = llm_rs::kv_router::indexer::RadixTree::new_with_frequency(expiration_duration);
        Ok(Self { inner })
    }

    #[pyo3(signature = (sequence, early_exit=false))]
    fn find_matches(
        &self,
        _py: Python,
        sequence: Vec<u64>,
        early_exit: bool,
    ) -> PyResult<OverlapScores> {
        let local_block_hashes: Vec<llm_rs::kv_router::protocols::LocalBlockHash> = sequence
            .into_iter()
            .map(llm_rs::kv_router::protocols::LocalBlockHash)
            .collect();

        let rs_overlap_scores = self.inner.find_matches(local_block_hashes, early_exit);
        Ok(OverlapScores {
            inner: rs_overlap_scores,
        })
    }

    fn apply_event(
        &mut self,
        _py: Python,
        worker_id: i64,
        kv_cache_event_bytes: &[u8],
    ) -> PyResult<()> {
        let kv_cache_event: llm_rs::kv_router::protocols::KvCacheEvent =
            serde_json::from_slice(kv_cache_event_bytes).map_err(|e| {
                PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                    "Failed to deserialize KvCacheEvent: {}",
                    e
                ))
            })?;

        let router_event = llm_rs::kv_router::indexer::RouterEvent::new(worker_id, kv_cache_event);
374
        let _ = self.inner.apply_event(router_event);
Yan Ru Pei's avatar
Yan Ru Pei committed
375
376
377
378
379
380
381
382
383
384
385
386
387
388
        Ok(())
    }

    fn remove_worker(&mut self, _py: Python, worker_id: i64) -> PyResult<()> {
        self.inner.remove_worker(worker_id);
        Ok(())
    }

    fn clear_all_blocks(&mut self, _py: Python, worker_id: i64) -> PyResult<()> {
        self.inner.clear_all_blocks(worker_id);
        Ok(())
    }
}

389
390
391
392
393
394
395
396
#[pyclass]
pub(crate) struct KvIndexer {
    inner: Arc<llm_rs::kv_router::indexer::KvIndexer>,
}

#[pymethods]
impl KvIndexer {
    #[new]
397
398
399
400
401
402
    #[pyo3(signature = (component, kv_block_size, consumer_uuid=None))]
    fn new(
        component: Component,
        kv_block_size: usize,
        consumer_uuid: Option<String>,
    ) -> PyResult<Self> {
403
404
        let runtime = pyo3_async_runtimes::tokio::get_runtime();
        runtime.block_on(async {
405
            let cancellation_token = component.inner.drt().runtime().child_token();
406
407
            let kv_indexer_metrics =
                llm_rs::kv_router::indexer::KvIndexerMetrics::from_component(&component.inner);
408
409
            let inner: Arc<llm_rs::kv_router::indexer::KvIndexer> =
                llm_rs::kv_router::indexer::KvIndexer::new(
410
                    cancellation_token.clone(),
411
                    kv_block_size as u32,
412
                    kv_indexer_metrics,
413
414
415
                )
                .into();

416
417
418
419
420
421
422
423
424
425
426
427
428
429
            // Use the shared start_kv_router_background function for event consumption
            // Pass None for snapshot_tx to skip snapshot handling in Python bindings
            llm_rs::kv_router::subscriber::start_kv_router_background(
                component.inner.clone(),
                consumer_uuid.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
                inner.event_sender(),
                None,
                cancellation_token,
                None,
                true,
            )
            .await
            .map_err(to_pyerr)?;

430
431
432
433
            Ok(Self { inner })
        })
    }

434
    fn block_size(&self) -> usize {
435
        self.inner.block_size() as usize
436
437
    }

438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
    fn find_matches<'p>(&self, py: Python<'p>, sequence: Vec<u64>) -> PyResult<Bound<'p, PyAny>> {
        let indexer = self.inner.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let local_block_hashes: Vec<llm_rs::kv_router::protocols::LocalBlockHash> = sequence
                .into_iter()
                .map(llm_rs::kv_router::protocols::LocalBlockHash)
                .collect();

            let rs_overlap_scores = indexer
                .find_matches(local_block_hashes)
                .await
                .map_err(to_pyerr)?;
            Ok(OverlapScores {
                inner: rs_overlap_scores,
            })
        })
    }

456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
    fn find_matches_for_request<'p>(
        &self,
        py: Python<'p>,
        token_ids: Vec<u32>,
        _lora_id: u64,
    ) -> PyResult<Bound<'p, PyAny>> {
        let indexer = self.inner.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let rs_overlap_scores = indexer
                .find_matches_for_request(token_ids.as_slice())
                .await
                .map_err(to_pyerr)?;
            Ok(OverlapScores {
                inner: rs_overlap_scores,
            })
        })
    }
}

475
476
477
478
479
480
481
482
483
484
485
486
487
488
/// Bindings for the approximate KV indexer. We need to exactly match the regular KV Indexer
/// interface, so that the router can switch between the two.
#[pyclass]
pub(crate) struct ApproxKvIndexer {
    inner: Arc<llm_rs::kv_router::approx::ApproxKvIndexer>,
}

#[pymethods]
impl ApproxKvIndexer {
    #[new]
    fn new(component: Component, kv_block_size: usize, ttl_secs: f64) -> PyResult<Self> {
        let ttl = tokio::time::Duration::from_secs_f64(ttl_secs);
        let inner = Arc::new(llm_rs::kv_router::approx::ApproxKvIndexer::new(
            component.inner.drt().runtime().child_token(),
jthomson04's avatar
jthomson04 committed
489
            kv_block_size as u32,
490
491
492
493
494
            ttl,
        ));
        Ok(Self { inner })
    }

jthomson04's avatar
jthomson04 committed
495
    fn block_size(&self) -> u32 {
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
        self.inner.block_size()
    }

    fn find_matches_for_request<'p>(
        &self,
        py: Python<'p>,
        token_ids: Vec<u32>,
    ) -> PyResult<Bound<'p, PyAny>> {
        let indexer = self.inner.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let rs_overlap_scores = indexer
                .find_matches_for_request(token_ids.as_slice())
                .await
                .map_err(to_pyerr)?;
            Ok(OverlapScores {
                inner: rs_overlap_scores,
            })
        })
    }

    fn process_routing_decision_for_request<'p>(
        &self,
        py: Python<'p>,
        tokens: Vec<u32>,
        worker_id: i64,
    ) -> PyResult<Bound<'p, PyAny>> {
        let indexer = self.inner.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            indexer
                .process_routing_decision_for_request(tokens.as_slice(), worker_id)
                .await
                .map_err(to_pyerr)?;
            Ok(())
        })
    }
}

533
534
535
536
537
538
539
540
541
542
543
544
545
#[pyclass]
#[derive(Clone)]
pub(crate) struct EndpointKvMetrics {
    #[pyo3(get, set)]
    pub worker_id: i64,
    #[pyo3(get, set)]
    pub request_active_slots: u64,
    #[pyo3(get, set)]
    pub request_total_slots: u64,
    #[pyo3(get, set)]
    pub kv_active_blocks: u64,
    #[pyo3(get, set)]
    pub kv_total_blocks: u64,
546
547
548
549
550
551
    #[pyo3(get, set)]
    pub num_requests_waiting: u64,
    #[pyo3(get, set)]
    pub gpu_cache_usage_perc: f32,
    #[pyo3(get, set)]
    pub gpu_prefix_cache_hit_rate: f32,
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
}

#[pyclass]
#[derive(Clone)]
pub(crate) struct AggregatedMetrics {
    #[pyo3(get, set)]
    pub endpoints: Vec<EndpointKvMetrics>,
    #[pyo3(get, set)]
    pub load_avg: f64,
    #[pyo3(get, set)]
    pub load_std: f64,
}

#[pyclass]
pub(crate) struct KvMetricsAggregator {
    inner: Arc<llm_rs::kv_router::metrics_aggregator::KvMetricsAggregator>,
}

#[pymethods]
impl KvMetricsAggregator {
    #[new]
    fn new(component: Component) -> PyResult<Self> {
        let runtime = pyo3_async_runtimes::tokio::get_runtime();
        runtime.block_on(async {
            let inner = llm_rs::kv_router::metrics_aggregator::KvMetricsAggregator::new(
                component.inner.clone(),
                component.inner.drt().runtime().child_token(),
            )
            .await;
            Ok(Self {
                inner: inner.into(),
            })
        })
    }

    fn get_metrics<'p>(&self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> {
588
        // TODO: update EndpointKvMetrics to match the new ForwardPassMetrics struct
589
        let endpoints = self.inner.get_endpoints();
590
591
592
        let load_avg = endpoints.load_avg;
        let load_std = endpoints.load_std;

593
594
        let endpoint_kv_metrics = endpoints
            .endpoints
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
            .into_iter()
            .map(|(worker_id, endpoint)| {
                let metrics = endpoint.data;
                let LoadMetrics::EngineLoadMetrics(fwd_pass_metrics) = metrics else {
                    panic!("Endpoints do not contain forward pass metrics.");
                };
                EndpointKvMetrics {
                    worker_id,
                    request_active_slots: fwd_pass_metrics.worker_stats.request_active_slots,
                    request_total_slots: fwd_pass_metrics.worker_stats.request_total_slots,
                    kv_active_blocks: fwd_pass_metrics.kv_stats.kv_active_blocks,
                    kv_total_blocks: fwd_pass_metrics.kv_stats.kv_total_blocks,
                    num_requests_waiting: fwd_pass_metrics.worker_stats.num_requests_waiting,
                    gpu_cache_usage_perc: fwd_pass_metrics.kv_stats.gpu_cache_usage_perc,
                    gpu_prefix_cache_hit_rate: fwd_pass_metrics.kv_stats.gpu_prefix_cache_hit_rate,
                }
611
612
613
614
615
            })
            .collect();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            Ok(AggregatedMetrics {
                endpoints: endpoint_kv_metrics,
616
617
                load_avg,
                load_std,
618
619
620
621
            })
        })
    }
}
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740

#[pyclass]
pub(crate) struct KvRecorder {
    inner: Arc<llm_rs::kv_router::recorder::KvRecorder>,
}

#[pymethods]
impl KvRecorder {
    #[new]
    #[pyo3(signature = (component, output_path=None, max_lines_per_file=None, max_count=None, max_time=None))]
    fn new(
        component: Component,
        output_path: Option<String>,
        max_lines_per_file: Option<usize>,
        max_count: Option<usize>,
        max_time: Option<f64>,
    ) -> PyResult<Self> {
        let runtime = pyo3_async_runtimes::tokio::get_runtime();
        runtime.block_on(async {
            let token = component.inner.drt().runtime().child_token();

            // Create a temp path if none provided
            let path = match output_path {
                Some(p) => p,
                None => {
                    let temp_dir = std::env::temp_dir();
                    temp_dir
                        .join("kv_events.jsonl")
                        .to_string_lossy()
                        .to_string()
                }
            };

            let inner = llm_rs::kv_router::recorder::KvRecorder::new(
                token.clone(),
                path,
                max_lines_per_file,
                max_count,
                max_time,
            )
            .await
            .map_err(to_pyerr)?;

            // Subscribe to KV events
            let mut kv_events_rx = component
                .inner
                .subscribe(llm_rs::kv_router::KV_EVENT_SUBJECT)
                .await
                .map_err(to_pyerr)?;
            let event_tx = inner.event_sender();

            // Spawn a task to forward events to the recorder
            tokio::spawn(async move {
                while let Some(event) = kv_events_rx.next().await {
                    let event: llm_rs::kv_router::indexer::RouterEvent =
                        serde_json::from_slice(&event.payload).unwrap();
                    tracing::debug!("KvRecorder received kv event: {:?}", event);
                    if let Err(e) = event_tx.send(event).await {
                        tracing::trace!(
                            "KvRecorder failed to send kv event; shutting down: {:?}",
                            e
                        );
                    }
                }
            });

            Ok(Self {
                inner: Arc::new(inner),
            })
        })
    }

    fn event_count<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let recorder = self.inner.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let count = recorder.event_count().await;
            Ok(count)
        })
    }

    fn elapsed_time<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let recorder = self.inner.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            match recorder.elapsed_time().await {
                Ok(elapsed) => Ok(elapsed.as_secs_f64()),
                Err(_) => Ok(0.0), // Return 0.0 when no events have been received yet
            }
        })
    }

    #[pyo3(signature = (indexer, timed=false, max_count=None, max_time=None))]
    fn replay_events<'py>(
        &self,
        py: Python<'py>,
        indexer: &KvIndexer,
        timed: bool,
        max_count: Option<usize>,
        max_time: Option<f64>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let event_tx = indexer.inner.event_sender();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let count = llm_rs::kv_router::recorder::KvRecorder::send_events(
                "dummy_path", // This doesn't matter as we'll use the provided event_tx
                &event_tx,
                timed,
                max_count,
                max_time,
            )
            .await
            .map_err(to_pyerr)?;
            Ok(count)
        })
    }

    fn shutdown(&self) -> PyResult<()> {
        self.inner.shutdown();
        Ok(())
    }
}
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832

#[pyclass]
#[repr(transparent)]
pub struct ForwardPassMetrics(pub RsForwardPassMetrics);

#[pyclass]
#[repr(transparent)]
pub struct WorkerStats(pub RsWorkerStats);

#[pyclass]
#[repr(transparent)]
pub struct KvStats(pub RsKvStats);

#[pyclass]
#[repr(transparent)]
pub struct SpecDecodeStats(pub RsSpecDecodeStats);

#[pymethods]
impl ForwardPassMetrics {
    #[new]
    #[pyo3(signature = (worker_stats, kv_stats, spec_decode_stats = None))]
    fn new(
        worker_stats: &WorkerStats,
        kv_stats: &KvStats,
        spec_decode_stats: Option<&SpecDecodeStats>,
    ) -> Self {
        Self(RsForwardPassMetrics {
            worker_stats: worker_stats.0.clone(),
            kv_stats: kv_stats.0.clone(),
            spec_decode_stats: spec_decode_stats.map(|s| s.0.clone()),
        })
    }
}

#[pymethods]
impl WorkerStats {
    #[new]
    #[pyo3(signature = (request_active_slots, request_total_slots, num_requests_waiting, data_parallel_rank=None))]
    fn new(
        request_active_slots: u64,
        request_total_slots: u64,
        num_requests_waiting: u64,
        data_parallel_rank: Option<u32>,
    ) -> Self {
        Self(RsWorkerStats {
            data_parallel_rank,
            request_active_slots,
            request_total_slots,
            num_requests_waiting,
        })
    }
}

#[pymethods]
impl KvStats {
    #[new]
    #[pyo3(signature = (kv_active_blocks, kv_total_blocks, gpu_cache_usage_perc, gpu_prefix_cache_hit_rate))]
    fn new(
        kv_active_blocks: u64,
        kv_total_blocks: u64,
        gpu_cache_usage_perc: f32,
        gpu_prefix_cache_hit_rate: f32,
    ) -> Self {
        Self(RsKvStats {
            kv_active_blocks,
            kv_total_blocks,
            gpu_cache_usage_perc,
            gpu_prefix_cache_hit_rate,
        })
    }
}

#[pymethods]
impl SpecDecodeStats {
    #[new]
    #[pyo3(signature = (num_spec_tokens, num_drafts, num_draft_tokens, num_accepted_tokens, num_accepted_tokens_per_pos))]
    fn new(
        num_spec_tokens: Option<u32>,
        num_drafts: Option<u32>,
        num_draft_tokens: Option<u32>,
        num_accepted_tokens: Option<u32>,
        num_accepted_tokens_per_pos: Option<Vec<u32>>,
    ) -> Self {
        Self(RsSpecDecodeStats {
            num_spec_tokens,
            num_drafts,
            num_draft_tokens,
            num_accepted_tokens,
            num_accepted_tokens_per_pos,
        })
    }
}
833
834
835
836

#[pyclass]
pub(crate) struct KvPushRouter {
    inner: Arc<llm_rs::kv_router::KvPushRouter>,
837
    primary_token: tokio_util::sync::CancellationToken,
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
}

#[pymethods]
impl KvPushRouter {
    #[new]
    fn new(
        endpoint: &Endpoint,
        block_size: usize,
        kv_router_config: &super::entrypoint::KvRouterConfig,
    ) -> PyResult<Self> {
        let runtime = pyo3_async_runtimes::tokio::get_runtime();
        runtime.block_on(async move {
            let client = endpoint.inner.client().await.map_err(to_pyerr)?;

            // Create PushRouter with KV router mode
            let push_router = rs::pipeline::PushRouter::<
                llm_rs::protocols::common::preprocessor::PreprocessedRequest,
                rs::protocols::annotated::Annotated<
                    llm_rs::protocols::common::llm_backend::LLMEngineOutput,
                >,
            >::from_client(
                client,
                rs::pipeline::network::egress::push_router::RouterMode::KV,
            )
            .await
            .map_err(to_pyerr)?;

            // Get component from endpoint
            let component = endpoint.inner.component();

868
869
870
871
872
873
874
875
876
877
878
879
880
            // Get the primary token from the component's primary lease
            let primary_token = component
                .drt()
                .primary_lease()
                .ok_or_else(|| {
                    PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                        "Failed to get primary lease: Cannot KV route static workers",
                    )
                })?
                .primary_token();

            // Create KvRouter with a unique consumer UUID
            let consumer_uuid = uuid::Uuid::new_v4().to_string();
881
882
883
884
885
            let kv_router = llm_rs::kv_router::KvRouter::new(
                component.clone(),
                block_size as u32,
                None, // default selector
                Some(kv_router_config.inner()),
886
                consumer_uuid,
887
888
889
890
891
892
893
894
895
896
            )
            .await
            .map_err(to_pyerr)?;

            // Create KvPushRouter
            let kv_push_router =
                llm_rs::kv_router::KvPushRouter::new(push_router, Arc::new(kv_router));

            Ok(Self {
                inner: Arc::new(kv_push_router),
897
                primary_token,
898
899
900
901
902
            })
        })
    }

    #[allow(clippy::too_many_arguments)]
903
    #[pyo3(signature = (token_ids, model, stop_conditions=None, sampling_options=None, output_options=None, router_config_override=None, worker_id=None))]
904
905
906
907
908
909
910
911
912
    fn generate<'p>(
        &self,
        py: Python<'p>,
        token_ids: Vec<u32>,
        model: String,
        stop_conditions: Option<PyObject>,
        sampling_options: Option<PyObject>,
        output_options: Option<PyObject>,
        router_config_override: Option<PyObject>,
913
        worker_id: Option<i64>,
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
    ) -> PyResult<Bound<'p, PyAny>> {
        // Depythonize the options with defaults
        let (stop_conditions, sampling_options, output_options, router_config_override) =
            Python::with_gil(|py| {
                let stop_conditions: StopConditions = if let Some(obj) = stop_conditions {
                    depythonize(obj.bind(py)).map_err(to_pyerr)?
                } else {
                    StopConditions::default()
                };

                let sampling_options: SamplingOptions = if let Some(obj) = sampling_options {
                    depythonize(obj.bind(py)).map_err(to_pyerr)?
                } else {
                    SamplingOptions::default()
                };

                let output_options: OutputOptions = if let Some(obj) = output_options {
                    depythonize(obj.bind(py)).map_err(to_pyerr)?
                } else {
                    OutputOptions::default()
                };

                let router_config_override: Option<llm_rs::kv_router::RouterConfigOverride> =
                    if let Some(obj) = router_config_override {
                        Some(depythonize(obj.bind(py)).map_err(to_pyerr)?)
                    } else {
                        None
                    };

                Ok::<_, PyErr>((
                    stop_conditions,
                    sampling_options,
                    output_options,
                    router_config_override,
                ))
            })?;

        // Build the PreprocessedRequest
952
953
954
        let mut request_builder =
            llm_rs::protocols::common::preprocessor::PreprocessedRequest::builder();
        request_builder
955
956
957
958
959
            .model(model)
            .token_ids(token_ids)
            .stop_conditions(stop_conditions)
            .sampling_options(sampling_options)
            .output_options(output_options)
960
961
962
963
964
965
966
967
            .router_config_override(router_config_override);

        // Set backend_instance_id if worker_id is provided
        if let Some(worker_id) = worker_id {
            request_builder.backend_instance_id(Some(worker_id));
        }

        let request = request_builder.build().map_err(to_pyerr)?;
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010

        let inner = self.inner.clone();

        // Create a Python async generator that wraps the Rust stream
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            use rs::pipeline::{AsyncEngine, SingleIn};
            use tokio_stream::StreamExt;

            let single_in = SingleIn::new(request);
            let stream = inner.generate(single_in).await.map_err(to_pyerr)?;
            let (tx, rx) = tokio::sync::mpsc::channel(100);

            // Spawn a task to process the stream
            tokio::spawn(async move {
                let mut stream = stream;
                while let Some(response) = stream.next().await {
                    // Convert LLMEngineOutput to PyObject
                    let py_response = Python::with_gil(|py| {
                        pythonize(py, &response.data)
                            .map(|obj| obj.unbind())
                            .map_err(|e| e.to_string())
                    });

                    match py_response {
                        Ok(obj) => {
                            if tx.send(obj).await.is_err() {
                                break; // Receiver dropped
                            }
                        }
                        Err(e) => {
                            tracing::error!("Failed to pythonize response: {}", e);
                            break;
                        }
                    }
                }
            });

            // Return a Python async generator wrapper
            Ok(KvPushRouterStream {
                rx: Arc::new(tokio::sync::Mutex::new(rx)),
            })
        })
    }
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
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
    #[pyo3(signature = (context_id, token_ids, router_config_override=None))]
    fn best_worker_id<'p>(
        &self,
        py: Python<'p>,
        context_id: String,
        token_ids: Vec<u32>,
        router_config_override: Option<PyObject>,
    ) -> PyResult<Bound<'p, PyAny>> {
        let router_config_override = if let Some(obj) = router_config_override {
            Python::with_gil(|py| {
                let override_config: llm_rs::kv_router::RouterConfigOverride =
                    depythonize(obj.bind(py)).map_err(to_pyerr)?;
                Ok::<_, PyErr>(Some(override_config))
            })?
        } else {
            None
        };

        let inner = self.inner.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let (worker_id, overlap_blocks) = inner
                .find_best_match(&context_id, &token_ids, router_config_override.as_ref())
                .await
                .map_err(to_pyerr)?;

            // Return a tuple of (worker_id, overlap_blocks)
            Ok((worker_id, overlap_blocks))
        })
    }

    fn get_potential_loads<'p>(
        &self,
        py: Python<'p>,
        token_ids: Vec<u32>,
    ) -> PyResult<Bound<'p, PyAny>> {
        let inner = self.inner.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let loads = inner
                .get_potential_loads(&token_ids)
                .await
                .map_err(to_pyerr)?;

            // Use pythonize to convert Vec<PotentialLoad> to Python list of dicts
            Python::with_gil(|py| {
                pythonize(py, &loads)
                    .map(|obj| obj.unbind())
                    .map_err(to_pyerr)
            })
        })
    }

1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
    /// Dump all events from the KV router's indexer as a JSON string
    fn dump_events<'p>(&self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> {
        let inner = self.inner.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let events = inner.dump_events().await.map_err(to_pyerr)?;
            // Serialize to JSON string
            let json_str = serde_json::to_string(&events).map_err(to_pyerr)?;
            Ok(json_str)
        })
    }
}

impl Drop for KvPushRouter {
    fn drop(&mut self) {
        // Cancel the primary token to shut down background tasks
        self.primary_token.cancel();
    }
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
}

// Python async generator wrapper for the stream
#[pyclass]
pub(crate) struct KvPushRouterStream {
    rx: Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<PyObject>>>,
}

#[pymethods]
impl KvPushRouterStream {
    #[pyo3(name = "__aiter__")]
    fn aiter(slf: Bound<'_, Self>) -> PyResult<Py<PyAny>> {
        Ok(slf.clone().into_any().unbind())
    }

    #[pyo3(name = "__anext__")]
    fn anext<'p>(&self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> {
        let rx = self.rx.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let mut rx = rx.lock().await;
            match rx.recv().await {
                Some(obj) => Ok(obj),
                None => Err(pyo3::exceptions::PyStopAsyncIteration::new_err(
                    "Stream exhausted",
                )),
            }
        })
    }
}