kv_manager.rs 19.3 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// SPDX-License-Identifier: Apache-2.0

//! # KV Manager
//! A synchronous implementation of a block manager that handles MoveBlock signals for caching KV blocks.
//!
//! ## Block Operations
//! The KV manager processes four types of MoveBlock signals:
//!
//! ### Use
//! - Checks if block exists in active pool → increment reference count
//! - If in inactive pool → move to active pool
//! - If neither → try evicting from inactive pool to make room
//! - If inactive pool is empty → pre-empt the oldest running request
//!
//! ### Destroy
//! - Removes the block from the active pool
//!
//! ### Deref
//! - Decrements reference count of a block in active pool
//! - If count reaches zero → move block to inactive pool
//!
//! ### Promote
//! - Converts a partial block (uuid) into a full block (global block hash)
//!
//! ## Preemption
//! If a Use operation fails (typically due to insufficient space), a false boolean signal
//! is returned to the scheduler for preemption. Initial KV block allocations for new requests
//! should not fail due to the watermark checking.
//!
//! ## NOTE
//! For simplicity (or non-simplicity), reference counting is tracked manually instead of using
//! the more idiomatic built-in Arc reference counter. This can be considered a shadow / mirror
//! implementation of the main block manager.

Yan Ru Pei's avatar
Yan Ru Pei committed
36
37
38
39
40
use crate::kv_router::protocols::{
    ExternalSequenceBlockHash, KvCacheEvent, KvCacheEventData, KvCacheRemoveData, KvCacheStoreData,
    KvCacheStoredBlockData, LocalBlockHash,
};
use crate::kv_router::publisher::KvEventPublisher;
41
use crate::mocker::evictor::LRUEvictor;
Yan Ru Pei's avatar
Yan Ru Pei committed
42
use crate::mocker::protocols::{MoveBlock, PrefillCost};
43
44
use crate::mocker::sequence::ActiveSequence;
use derive_getters::Getters;
Yan Ru Pei's avatar
Yan Ru Pei committed
45
use dynamo_runtime::component::Component;
46
47
use dynamo_tokens::blocks::UniqueBlock;
use dynamo_tokens::{BlockHash, SequenceHash};
48
use std::collections::HashMap;
Yan Ru Pei's avatar
Yan Ru Pei committed
49
use std::sync::Arc;
50
51
52
53
54
55
56

#[derive(Getters)]
pub struct KvManager {
    #[getter(copy)]
    max_capacity: usize,

    #[getter(copy)]
57
    block_size: usize,
58
59
60
61
62

    active_blocks: HashMap<UniqueBlock, usize>,

    inactive_blocks: LRUEvictor<UniqueBlock>,

Yan Ru Pei's avatar
Yan Ru Pei committed
63
64
65
66
67
68
    kv_event_publisher: Option<Arc<KvEventPublisher>>,

    #[getter(copy)]
    dp_rank: u32,

    next_event_id: u64,
69
70
71
}

impl KvManager {
72
    pub fn new(max_capacity: usize, block_size: usize) -> Self {
73
        Self::new_with_publisher(max_capacity, block_size, None, 0, false)
74
75
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
76
    pub fn new_with_publisher(
77
78
        max_capacity: usize,
        block_size: usize,
Yan Ru Pei's avatar
Yan Ru Pei committed
79
80
        component: Option<Component>,
        dp_rank: u32,
81
        enable_local_indexer: bool,
82
    ) -> Self {
83
84
85
        let active_blocks = HashMap::new();
        let inactive_blocks = LRUEvictor::default();

Yan Ru Pei's avatar
Yan Ru Pei committed
86
87
        let kv_event_publisher = component.map(|comp| {
            tracing::info!(
88
                "Initializing KV event publisher for DP rank {dp_rank} with block_size {block_size}, enable_local_indexer={enable_local_indexer}"
Yan Ru Pei's avatar
Yan Ru Pei committed
89
90
            );
            Arc::new(
91
                KvEventPublisher::new_with_local_indexer(comp, block_size as u32, None, enable_local_indexer, dp_rank)
Yan Ru Pei's avatar
Yan Ru Pei committed
92
93
94
95
                    .expect("Failed to create KV event publisher"),
            )
        });

96
97
98
99
100
        KvManager {
            max_capacity,
            block_size,
            active_blocks,
            inactive_blocks,
Yan Ru Pei's avatar
Yan Ru Pei committed
101
102
103
            kv_event_publisher,
            dp_rank,
            next_event_id: 0,
104
105
106
        }
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
107
108
109
110
111
    /// Converts stored/removed blocks into KvCacheEventData and publishes if publisher is available
    fn publish_kv_event(
        &mut self,
        full_blocks: Vec<SequenceHash>,
        local_hashes: &[BlockHash],
112
        parent_hash: Option<u64>,
Yan Ru Pei's avatar
Yan Ru Pei committed
113
        is_store: bool,
114
    ) {
Yan Ru Pei's avatar
Yan Ru Pei committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
        if full_blocks.is_empty() {
            return;
        }

        let Some(ref publisher) = self.kv_event_publisher else {
            return;
        };

        let event_data = if is_store {
            let num_blocks = full_blocks.len();
            let local_hashes_slice = &local_hashes[local_hashes
                .len()
                .checked_sub(num_blocks)
                .expect("local hashes fewer than stored blocks")..];

            KvCacheEventData::Stored(KvCacheStoreData {
                parent_hash: parent_hash.map(ExternalSequenceBlockHash),
                blocks: full_blocks
                    .into_iter()
                    .zip(local_hashes_slice.iter())
                    .map(|(global_hash, local_hash)| KvCacheStoredBlockData {
                        block_hash: ExternalSequenceBlockHash(global_hash),
                        tokens_hash: LocalBlockHash(*local_hash),
138
                        mm_extra_info: None,
Yan Ru Pei's avatar
Yan Ru Pei committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
                    })
                    .collect(),
            })
        } else {
            KvCacheEventData::Removed(KvCacheRemoveData {
                block_hashes: full_blocks
                    .into_iter()
                    .map(ExternalSequenceBlockHash)
                    .collect(),
            })
        };

        // Use incremental event ID starting from 0
        let event_id = self.next_event_id;
        self.next_event_id += 1;

        let event = KvCacheEvent {
            event_id,
            data: event_data,
            dp_rank: self.dp_rank,
        };

        if let Err(e) = publisher.publish(event) {
            tracing::warn!("Failed to publish KV event: {e}");
163
164
165
166
167
168
        }
    }

    /// Process a MoveBlock instruction synchronously
    pub fn process(&mut self, event: &MoveBlock) -> bool {
        match event {
Yan Ru Pei's avatar
Yan Ru Pei committed
169
            MoveBlock::Use(hashes, local_hashes) => {
170
171
172
                let mut blocks_stored = Vec::<u64>::new();

                let mut parent_block: Option<&UniqueBlock> = None;
173
174
175
176
177
                for hash in hashes {
                    // First check if it already exists in active blocks
                    if let Some(ref_count) = self.active_blocks.get_mut(hash) {
                        // Block already active, just increment reference count
                        *ref_count += 1;
178
                        parent_block = Some(hash);
179
180
181
182
183
184
185
                        continue;
                    }

                    // Then check if it exists in inactive and move it to active if found
                    if self.inactive_blocks.remove(hash) {
                        // Insert into active with reference count 1
                        self.active_blocks.insert(hash.clone(), 1);
186
                        parent_block = Some(hash);
187
188
189
190
191
192
193
194
195
                        continue;
                    }

                    // Get counts for capacity check
                    let active_count = self.active_blocks.len();
                    let inactive_count = self.inactive_blocks.len();

                    // If at max capacity, evict the oldest entry from inactive blocks
                    if active_count + inactive_count >= self.max_capacity {
196
                        let Some(evicted) = self.inactive_blocks.evict() else {
197
                            return false;
198
                        };
Yan Ru Pei's avatar
Yan Ru Pei committed
199
200
201
202
                        tracing::trace!(
                            "Evicting block from inactive pool: {evicted:?}, dp_rank={}",
                            self.dp_rank
                        );
203
                        if let UniqueBlock::FullBlock(evicted_full_block) = evicted {
Yan Ru Pei's avatar
Yan Ru Pei committed
204
                            self.publish_kv_event(vec![evicted_full_block], &[], None, false);
205
206
207
208
209
                        }
                    }

                    // Now insert the new block in active blocks with reference count 1
                    self.active_blocks.insert(hash.clone(), 1);
Yan Ru Pei's avatar
Yan Ru Pei committed
210
                    if self.kv_event_publisher.is_some()
211
212
213
                        && let UniqueBlock::FullBlock(stored_full_block) = hash
                    {
                        blocks_stored.push(*stored_full_block);
214
                    }
215
                }
216
217
218
219
220
221

                let parent_hash = match parent_block {
                    None => None,
                    Some(UniqueBlock::FullBlock(block)) => Some(*block),
                    Some(UniqueBlock::PartialBlock(_)) => panic!("parent block cannot be partial"),
                };
Yan Ru Pei's avatar
Yan Ru Pei committed
222
                self.publish_kv_event(blocks_stored, local_hashes, parent_hash, true);
223
            }
224

225
            MoveBlock::Destroy(hashes) => {
226
227
                let mut blocks_destroyed = Vec::<u64>::new();

Yan Ru Pei's avatar
Yan Ru Pei committed
228
229
                // Process blocks in order (already reversed by caller if needed)
                for hash in hashes.iter() {
230
                    self.active_blocks.remove(hash).unwrap();
231
232

                    // Track blocks for batch sending
Yan Ru Pei's avatar
Yan Ru Pei committed
233
                    if self.kv_event_publisher.is_some()
234
235
236
                        && let UniqueBlock::FullBlock(destroyed_full_block) = hash
                    {
                        blocks_destroyed.push(*destroyed_full_block);
237
                    }
238
                }
239

Yan Ru Pei's avatar
Yan Ru Pei committed
240
                self.publish_kv_event(blocks_destroyed, &[], None, false);
241
            }
242

243
            MoveBlock::Deref(hashes) => {
Yan Ru Pei's avatar
Yan Ru Pei committed
244
245
                // Process blocks in order (already reversed by caller if needed)
                for hash in hashes.iter() {
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
                    // Decrement reference count and check if we need to move to inactive
                    if let Some(ref_count) = self.active_blocks.get_mut(hash) {
                        if *ref_count == 0 {
                            panic!("Negative reference count would be encountered after Deref.");
                        }
                        *ref_count -= 1;

                        // If reference count reaches zero, remove from active and move to inactive
                        if *ref_count == 0 {
                            self.active_blocks.remove(hash);
                            // Use the LRUEvictor's timing functionality
                            self.inactive_blocks.insert(hash.clone());
                        }
                    }
                }
            }
262

Yan Ru Pei's avatar
Yan Ru Pei committed
263
            MoveBlock::Promote(uuid, hash, parent_hash, local_hash) => {
264
265
266
                let uuid_block = UniqueBlock::PartialBlock(*uuid);
                let hash_block = UniqueBlock::FullBlock(*hash);

Yan Ru Pei's avatar
Yan Ru Pei committed
267
268
269
270
271
272
273
274
275
276
277
278
279
                assert_eq!(
                    self.active_blocks.remove(&uuid_block),
                    Some(1),
                    "uuid_block {uuid_block:?} should exist and be unique with ref_count=1"
                );

                let hash_ref_count = if let Some(ref_count) = self.active_blocks.get(&hash_block) {
                    *ref_count
                } else if self.inactive_blocks.remove(&hash_block) {
                    0
                } else {
                    self.publish_kv_event(vec![*hash], &[*local_hash], *parent_hash, true);
                    0
280
281
                };

Yan Ru Pei's avatar
Yan Ru Pei committed
282
283
                self.active_blocks
                    .insert(hash_block.clone(), hash_ref_count + 1);
284
285
286
287
288
289
290
            }
        }

        // Return true if we made it this far
        true
    }

291
    /// Get the count of blocks that aren't in active or inactive pools
292
293
294
    pub fn probe_new_blocks(&self, blocks: &[UniqueBlock]) -> usize {
        blocks
            .iter()
295
296
297
            .filter(|&block| {
                !self.active_blocks.contains_key(block) && !self.inactive_blocks.contains(block)
            })
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
            .count()
    }

    /// Get the current capacity (active blocks + inactive blocks)
    pub fn current_capacity(&self) -> usize {
        let active = self.active_blocks.len();
        let inactive = self.inactive_blocks.len();
        active + inactive
    }

    /// Get the current capacity as a percentage of the maximum capacity
    pub fn current_capacity_perc(&self) -> f64 {
        let current = self.current_capacity() as f64;
        current / self.max_capacity as f64
    }

    /// Get the number of active blocks
    pub fn num_active_blocks(&self) -> usize {
        self.active_blocks.len()
    }

319
320
321
322
323
    /// Get the percentage of active blocks relative to maximum capacity
    pub fn get_active_perc(&self) -> f64 {
        self.active_blocks.len() as f64 / self.max_capacity as f64
    }

324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
    /// Get the number of inactive blocks
    pub fn num_inactive_blocks(&self) -> usize {
        self.inactive_blocks.len()
    }

    /// Get the keys of inactive blocks
    pub fn get_inactive_blocks(&self) -> Vec<&UniqueBlock> {
        self.inactive_blocks.keys().collect()
    }

    /// Get the keys of active blocks
    pub fn get_active_blocks(&self) -> Vec<&UniqueBlock> {
        self.active_blocks.keys().collect()
    }

    /// Check if a sequence can be scheduled and calculate cost if possible
340
341
    pub fn get_prefill_cost(&self, sequence: &ActiveSequence) -> PrefillCost {
        let seq_blocks = sequence.unique_blocks();
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357

        // Find the longest prefix that exists in cache
        // We must stop at the first cache miss since KV states are computed sequentially
        let mut overlap_blocks = 0;
        for block in seq_blocks {
            if !self.active_blocks.contains_key(block) && !self.inactive_blocks.contains(block) {
                // First cache miss - can't use anything after this point
                break;
            }
            overlap_blocks += 1;
        }

        let new_blocks = seq_blocks.len() - overlap_blocks;
        // Clamp cached_tokens to handle partial blocks (last block may have < block_size tokens)
        let cached_tokens = (overlap_blocks * self.block_size).min(sequence.num_input_tokens());
        let new_tokens = sequence.num_input_tokens() - cached_tokens;
358

359
360
        PrefillCost {
            new_blocks,
361
            new_tokens,
362
        }
363
364
365
366
367
368
369
370
371
372
373
374
375
376
    }
}

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

    #[test]
    fn test_failure_on_max_capacity() {
        // Create a KvManager with 10 blocks capacity
        let mut manager = KvManager::new(10, 16);

        // Helper function to use multiple blocks that returns the response
        fn use_blocks(manager: &mut KvManager, ids: Vec<u64>) -> bool {
Yan Ru Pei's avatar
Yan Ru Pei committed
377
378
379
            let blocks: Vec<_> = ids.iter().map(|&id| UniqueBlock::FullBlock(id)).collect();
            let hashes: Vec<_> = ids.into_iter().collect();
            manager.process(&MoveBlock::Use(blocks, hashes))
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
        }

        // First use 10 blocks (0 to 9) in a batch
        let response = use_blocks(&mut manager, (0..10).collect());
        assert!(response, "Expected success response");

        // Verify we are at capacity
        assert_eq!(manager.current_capacity(), 10);

        // The 11th block should return false, not panic
        let response = use_blocks(&mut manager, vec![10]);
        assert!(
            !response,
            "Expected failure response when exceeding max capacity"
        );
    }

    #[test]
    fn test_block_lifecycle_stringent() {
Yan Ru Pei's avatar
Yan Ru Pei committed
399
400
        // Create a KvManager with 10 blocks capacity (no KV event publisher for tests)
        let mut manager = KvManager::new(10, 16);
401
402
403

        // Helper function to use multiple blocks
        fn use_blocks(manager: &mut KvManager, ids: Vec<u64>) {
Yan Ru Pei's avatar
Yan Ru Pei committed
404
405
406
            let blocks: Vec<_> = ids.iter().map(|&id| UniqueBlock::FullBlock(id)).collect();
            let hashes: Vec<_> = ids.into_iter().collect();
            manager.process(&MoveBlock::Use(blocks, hashes));
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
        }

        // Helper function to destroy multiple blocks
        fn destroy_blocks(manager: &mut KvManager, ids: Vec<u64>) {
            let blocks = ids.into_iter().map(UniqueBlock::FullBlock).collect();
            manager.process(&MoveBlock::Destroy(blocks));
        }

        // Helper function to deref multiple blocks
        fn deref_blocks(manager: &mut KvManager, ids: Vec<u64>) {
            let blocks = ids.into_iter().map(UniqueBlock::FullBlock).collect();
            manager.process(&MoveBlock::Deref(blocks));
        }

        // Helper function to check if active blocks contain expected blocks with expected ref counts
        fn assert_active_blocks(manager: &KvManager, expected_blocks: &[(u64, usize)]) {
            assert_eq!(
                manager.active_blocks().len(),
                expected_blocks.len(),
                "Active blocks count doesn't match expected"
            );

            for &(id, ref_count) in expected_blocks {
                let block = UniqueBlock::FullBlock(id);
                assert!(
                    manager.active_blocks().contains_key(&block),
433
                    "Block {id} not found in active blocks",
434
435
436
437
                );
                assert_eq!(
                    manager.active_blocks().get(&block),
                    Some(&ref_count),
438
                    "Block {id} has wrong reference count",
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
                );
            }
        }

        // Helper function to check if inactive blocks contain expected blocks
        fn assert_inactive_blocks(
            manager: &KvManager,
            expected_size: usize,
            expected_blocks: &[u64],
        ) {
            let inactive_blocks = manager.get_inactive_blocks();
            let inactive_blocks_count = manager.inactive_blocks().len();

            assert_eq!(
                inactive_blocks_count, expected_size,
                "Inactive blocks count doesn't match expected"
            );

            for &id in expected_blocks {
                let block = UniqueBlock::FullBlock(id);
                assert!(
                    inactive_blocks.iter().any(|&b| *b == block),
461
                    "Block {id} not found in inactive blocks",
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
                );
            }
        }

        // First use blocks 0, 1, 2, 3, 4 in a batch
        use_blocks(&mut manager, (0..5).collect());

        // Then use blocks 0, 1, 5, 6 in a batch
        use_blocks(&mut manager, vec![0, 1, 5, 6]);

        // Check that the blocks 0 and 1 are in active blocks, both with reference counts of 2
        assert_active_blocks(
            &manager,
            &[(0, 2), (1, 2), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1)],
        );

        // Now destroy block 4
        destroy_blocks(&mut manager, vec![4]);

        // And deref blocks 3, 2, 1, 0 in this order as a batch
        deref_blocks(&mut manager, vec![0, 1, 2, 3]);

        // Check that the inactive_blocks is size 2 (via num_objects) and contains 3 and 2
        assert_inactive_blocks(&manager, 2, &[3, 2]);
        assert_active_blocks(&manager, &[(0, 1), (1, 1), (5, 1), (6, 1)]);

        // Now destroy block 6
        destroy_blocks(&mut manager, vec![6]);

        // And deref blocks 5, 1, 0 as a batch
        deref_blocks(&mut manager, vec![0, 1, 5]);

        // Check that the inactive_blocks is size 5, and contains 0, 1, 2, 3, 5
        assert_inactive_blocks(&manager, 5, &[0, 1, 2, 3, 5]);
        assert_active_blocks(&manager, &[]);

        // Now use 0, 1, 2, 7, 8, 9 as a batch
        use_blocks(&mut manager, vec![0, 1, 2, 7, 8, 9]);

        // Check that the inactive_blocks is size 2, and contains 3 and 5
        assert_inactive_blocks(&manager, 2, &[3, 5]);
        assert_active_blocks(&manager, &[(0, 1), (1, 1), (2, 1), (7, 1), (8, 1), (9, 1)]);

        // Test the new_blocks method - only block 4 should be new out of [0,1,2,3,4]
        let blocks_to_check: Vec<UniqueBlock> = vec![0, 1, 2, 3, 4]
            .into_iter()
            .map(UniqueBlock::FullBlock)
            .collect();
        assert_eq!(manager.probe_new_blocks(&blocks_to_check), 1);

        // Now use blocks 10, 11, 12 as a batch
        use_blocks(&mut manager, vec![10, 11, 12]);

        // Check that the inactive_blocks is size 1 and contains only 5
        assert_inactive_blocks(&manager, 1, &[5]);
517
518

        use_blocks(&mut manager, vec![13]);
519
520
    }
}