kv_router.rs 7.44 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
5
use std::sync::Arc;

6
use anyhow::Result;
7
use dynamo_runtime::{
8
    component::{Component, InstanceSource},
9
    pipeline::{
10
11
        async_trait, AsyncEngine, AsyncEngineContextProvider, Error, ManyOut, PushRouter,
        ResponseStream, SingleIn,
12
13
14
15
16
    },
    prelude::*,
    protocols::annotated::Annotated,
};
use futures::stream::{self, StreamExt};
17
18

pub mod indexer;
19
pub mod metrics_aggregator;
20
21
pub mod protocols;
pub mod publisher;
22
pub mod recorder;
23
24
pub mod scheduler;
pub mod scoring;
25

26
27
28
29
30
31
32
33
use crate::{
    kv_router::{
        indexer::{KvIndexer, KvIndexerInterface, RouterEvent},
        metrics_aggregator::KvMetricsAggregator,
        protocols::{LocalBlockHash, RouterRequest, RouterResponse, WorkerSelectionResult},
        scheduler::{KvScheduler, KvSchedulerError, SchedulingRequest},
        scoring::ProcessedEndpoints,
    },
34
35
    preprocessor::BackendInput,
    protocols::common::llm_backend::LLMEngineOutput,
Ryan Olson's avatar
Ryan Olson committed
36
    tokens::TokenBlockSequence,
37
38
};

39
use dynamo_runtime::traits::events::EventSubscriber;
40
41
42

// [gluo TODO] shouldn't need to be public
// this should be discovered from the component
43
pub const KV_EVENT_SUBJECT: &str = "kv_events";
44
pub const KV_HIT_RATE_SUBJECT: &str = "kv-hit-rate";
45
pub const KV_METRICS_ENDPOINT: &str = "load_metrics";
46

47
48
49
50
51
52
53
54
55
/// A trait that users can implement to define custom selection logic
pub trait WorkerSelector {
    fn select_worker(
        &self,
        workers: &ProcessedEndpoints,
        request: &SchedulingRequest,
        block_size: usize,
    ) -> Result<WorkerSelectionResult, KvSchedulerError>;
}
56

57
58
/// A KvRouter only decides which worker you should use. It doesn't send you there.
/// TODO: Rename this to indicate it only selects a worker, it does not route.
59
pub struct KvRouter {
60
    indexer: KvIndexer,
61
62
    scheduler: KvScheduler,
    block_size: usize,
63
64
65
66
}

impl KvRouter {
    pub async fn new(
67
        component: Component,
68
69
        block_size: usize,
        selector: Option<Box<dyn WorkerSelector + Send + Sync>>,
70
    ) -> Result<Self> {
71
72
73
74
75
        let cancellation_token = component
            .drt()
            .primary_lease()
            .expect("Cannot KV route static workers")
            .primary_token();
76
        tracing::info!("KV Routing initialized");
77
78
79
80
81
82
83
84
85
86
        let metrics_aggregator =
            KvMetricsAggregator::new(component.clone(), cancellation_token.clone()).await;
        let indexer = KvIndexer::new(cancellation_token.clone(), block_size);
        let scheduler = KvScheduler::start(
            component.namespace().clone(),
            block_size,
            metrics_aggregator.endpoints_watcher(),
            selector,
        )
        .await?;
87

88
89
90
        // [gluo TODO] try subscribe_with_type::<RouterEvent>,
        // error checking below will be different.
        let mut kv_events_rx = component.subscribe(KV_EVENT_SUBJECT).await?;
91
92
93
94
        let kv_events_tx = indexer.event_sender();

        tokio::spawn(async move {
            while let Some(event) = kv_events_rx.next().await {
Alec's avatar
Alec committed
95
                let event: RouterEvent = match serde_json::from_slice(&event.payload) {
96
                    Ok(event) => event,
Alec's avatar
Alec committed
97
98
99
100
101
102
103
                    Err(e) => {
                        tracing::warn!("Failed to deserialize RouterEvent: {:?}", e);
                        // Choosing warn and continue to process other events from other workers
                        // A bad event likely signals a problem with a worker, but potentially other workers are still healthy
                        continue;
                    }
                };
104
                if let Err(e) = kv_events_tx.send(event).await {
105
                    tracing::debug!("failed to send kv event to indexer; shutting down: {:?}", e);
106
107
108
109
                }
            }
        });

110
        Ok(Self {
111
112
            scheduler,
            indexer,
113
            block_size,
114
        })
115
116
117
    }

    // [TODO] indexer needs to take 'lora_id' as parameter
GuanLuo's avatar
GuanLuo committed
118
    pub async fn schedule(&self, token_ids: &Vec<u32>, _lora_id: u64) -> Result<i64> {
119
120
121
122
123
124
125
        // Extracting part of the code in KvRouter::generate() for only
        // the decision making part, routing is done by the caller
        let isl_tokens = token_ids.len();
        let overlap_scores = self
            .indexer
            .find_matches_for_request(token_ids.as_slice())
            .await?;
Alec's avatar
Alec committed
126
        tracing::debug!("KV router overlap_scores: {:?}", overlap_scores);
GuanLuo's avatar
GuanLuo committed
127
128
        let worker_id = self.scheduler.schedule(overlap_scores, isl_tokens).await?;
        Ok(worker_id)
129
    }
130

131
    /// Give these tokens, find the worker with the best match in it's KV cache.
132
133
    /// Returned overlap amount is in number of blocks.
    async fn find_best_match(&self, tokens: &[u32]) -> anyhow::Result<(i64, u32)> {
134
        let isl_tokens = tokens.len();
135
136
        let block_size = self.block_size;

Ryan Olson's avatar
Ryan Olson committed
137
        let (complete_blocks, _partial_block) =
138
            TokenBlockSequence::split_tokens(tokens, block_size, 1337_u64);
Ryan Olson's avatar
Ryan Olson committed
139
140
141
142
143

        let local_block_hashes = complete_blocks
            .into_iter()
            .map(|block| LocalBlockHash(block.block_hash()))
            .collect();
144
        let overlap_scores = self.indexer.find_matches(local_block_hashes).await?;
145
146
147
148
149
150
        let worker_id = self
            .scheduler
            .schedule(overlap_scores.clone(), isl_tokens)
            .await?;
        let overlap_amount = overlap_scores.scores.get(&worker_id).copied().unwrap_or(0);
        Ok((worker_id, overlap_amount))
151
    }
152
153
154
155
156

    /// Get the block size this router was configured with
    pub fn block_size(&self) -> usize {
        self.block_size
    }
157
158
159
160
161
162
163
164
165
}

#[async_trait]
impl AsyncEngine<SingleIn<RouterRequest>, ManyOut<Annotated<RouterResponse>>, Error> for KvRouter {
    async fn generate(
        &self,
        request: SingleIn<RouterRequest>,
    ) -> Result<ManyOut<Annotated<RouterResponse>>> {
        let (request, ctx) = request.into_parts();
166
        let (worker_id, _) = self.find_best_match(&request.tokens).await?;
167
168
169
170
171
172
173

        let response = RouterResponse { worker_id };
        let response = Annotated::from_data(response);
        let stream = stream::iter(vec![response]);
        Ok(ResponseStream::new(Box::pin(stream), ctx.context()))
    }
}
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196

pub struct KvPushRouter {
    inner: PushRouter<BackendInput, Annotated<LLMEngineOutput>>,
    chooser: Arc<KvRouter>,
}

impl KvPushRouter {
    pub fn new(
        inner: PushRouter<BackendInput, Annotated<LLMEngineOutput>>,
        chooser: Arc<KvRouter>,
    ) -> Self {
        KvPushRouter { inner, chooser }
    }
}

#[async_trait]
impl AsyncEngine<SingleIn<BackendInput>, ManyOut<Annotated<LLMEngineOutput>>, Error>
    for KvPushRouter
{
    async fn generate(
        &self,
        request: SingleIn<BackendInput>,
    ) -> Result<ManyOut<Annotated<LLMEngineOutput>>, Error> {
197
        match self.inner.client.instance_source.as_ref() {
198
199
            InstanceSource::Static => self.inner.r#static(request).await,
            InstanceSource::Dynamic(_) => {
200
201
202
203
204
205
206
                let (instance_id, overlap_amount) =
                    self.chooser.find_best_match(&request.token_ids).await?;
                // Update the request with the estimated prefix hit blocks
                let (mut backend_input, context) = request.into_parts();
                backend_input.estimated_prefix_hit_num_blocks = Some(overlap_amount);
                let updated_request = context.map(|_| backend_input);
                self.inner.direct(updated_request, instance_id).await
207
208
209
210
            }
        }
    }
}