state.rs 18.4 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

Ryan Olson's avatar
Ryan Olson committed
4
5
6
7
mod local;
mod logical;
mod resources;

8
use crate::block_manager::block::{MutableBlock, factory::IntoBlocks};
Ryan Olson's avatar
Ryan Olson committed
9
10
11
use crate::block_manager::locality::LogicalResources;
use crate::block_manager::offload::request::BlockResult;

Ryan Olson's avatar
Ryan Olson committed
12
13
use super::*;

14
// use super::offload::{OffloadManager, OffloadManagerConfig};
15
use super::{
Ryan Olson's avatar
Ryan Olson committed
16
    block::{
17
18
        Block, GlobalRegistry, ImmutableBlock, factory::LocalBlockDataFactory,
        locality::LocalityProvider,
Ryan Olson's avatar
Ryan Olson committed
19
    },
20
    config::NixlOptions,
21
    events::{EventManager, NullEventManager},
Ryan Olson's avatar
Ryan Olson committed
22
    metrics::BlockManagerMetrics,
23
    offload::{OffloadManager, OffloadManagerConfig},
24
};
Ryan Olson's avatar
Ryan Olson committed
25
use derive_getters::Dissolve;
Ryan Olson's avatar
Ryan Olson committed
26
use std::sync::Arc;
27
use tokio::runtime::Handle;
Ryan Olson's avatar
Ryan Olson committed
28
use tokio::sync::oneshot;
Ryan Olson's avatar
Ryan Olson committed
29

Ryan Olson's avatar
Ryan Olson committed
30
31
32
33
pub(crate) struct Resources {
    pub worker_id: WorkerID,
    pub cancellation_token: CancellationToken,
    pub async_rt_handle: Handle,
Ryan Olson's avatar
Ryan Olson committed
34

Ryan Olson's avatar
Ryan Olson committed
35
36
37
38
    // nixl agent/backends for the block manager
    pub nixl_agent: Arc<Option<NixlAgent>>,
    #[expect(dead_code)]
    pub nixl_backends: HashMap<String, Arc<nixl_sys::Backend>>,
Ryan Olson's avatar
Ryan Olson committed
39

Ryan Olson's avatar
Ryan Olson committed
40
41
    // registry for blocks across all storage types
    pub global_registry: GlobalRegistry,
Ryan Olson's avatar
Ryan Olson committed
42

Ryan Olson's avatar
Ryan Olson committed
43
44
    // event manager for block manager events
    pub event_manager: Arc<dyn EventManager>,
45

Ryan Olson's avatar
Ryan Olson committed
46
47
48
49
50
    // metrics for the block manager
    pub metrics: Arc<BlockManagerMetrics>,

    // config for the block manager
    pub config: KvBlockManagerConfig,
Ryan Olson's avatar
Ryan Olson committed
51
52
}

Ryan Olson's avatar
Ryan Olson committed
53
54
55
#[allow(dead_code)]
pub struct KvBlockManagerState<Locality: LocalityProvider, Metadata: BlockMetadata> {
    resources: Arc<Resources>,
Ryan Olson's avatar
Ryan Olson committed
56

Ryan Olson's avatar
Ryan Olson committed
57
58
59
    disk_pool: Option<Arc<dyn BlockPool<DiskStorage, Locality, Metadata>>>,
    host_pool: Option<Arc<dyn BlockPool<PinnedStorage, Locality, Metadata>>>,
    device_pool: Option<Arc<dyn BlockPool<DeviceStorage, Locality, Metadata>>>,
Ryan Olson's avatar
Ryan Olson committed
60

Ryan Olson's avatar
Ryan Olson committed
61
62
63
64
    local_block_set: NixlBlockSet,
    remote_block_sets: RwLock<HashMap<WorkerID, HashMap<usize, RemoteBlocks>>>,
    offload_manager: Arc<OffloadManager<Locality, Metadata>>,
}
Ryan Olson's avatar
Ryan Olson committed
65

Ryan Olson's avatar
Ryan Olson committed
66
67
68
69
impl<Locality: LocalityProvider, Metadata: BlockMetadata> KvBlockManagerState<Locality, Metadata> {
    pub fn disk(&self) -> Option<&dyn BlockPool<DiskStorage, Locality, Metadata>> {
        self.disk_pool.as_ref().map(|pool| pool.as_ref())
    }
Ryan Olson's avatar
Ryan Olson committed
70

Ryan Olson's avatar
Ryan Olson committed
71
72
73
    pub fn host(&self) -> Option<&dyn BlockPool<PinnedStorage, Locality, Metadata>> {
        self.host_pool.as_ref().map(|pool| pool.as_ref())
    }
74

Ryan Olson's avatar
Ryan Olson committed
75
76
77
    pub fn device(&self) -> Option<&dyn BlockPool<DeviceStorage, Locality, Metadata>> {
        self.device_pool.as_ref().map(|pool| pool.as_ref())
    }
78

Ryan Olson's avatar
Ryan Olson committed
79
80
81
    pub fn worker_id(&self) -> WorkerID {
        self.resources.worker_id
    }
82

Ryan Olson's avatar
Ryan Olson committed
83
84
85
86
87
88
    pub(crate) async fn enqueue_offload_block<S: Storage + 'static>(
        &self,
        block: &ImmutableBlock<S, Locality, Metadata>,
        priority: u64,
    ) -> Result<()> {
        self.offload_manager.offload(block, priority).await?;
Ryan Olson's avatar
Ryan Olson committed
89

Ryan Olson's avatar
Ryan Olson committed
90
91
        Ok(())
    }
92

Ryan Olson's avatar
Ryan Olson committed
93
94
95
96
97
98
99
100
    pub fn onboard_blocks<S: Storage + 'static>(
        &self,
        blocks: Vec<ImmutableBlock<S, Locality, Metadata>>,
        targets: Option<Vec<MutableBlock<DeviceStorage, Locality, Metadata>>>,
    ) -> oneshot::Receiver<BlockResult<DeviceStorage, Locality, Metadata>> {
        self.offload_manager.onboard(blocks, targets)
    }
}
101

Ryan Olson's avatar
Ryan Olson committed
102
103
104
105
impl<R: LogicalResources, Metadata: BlockMetadata>
    KvBlockManagerState<locality::Logical<R>, Metadata>
{
    pub async fn new(config: KvBlockManagerConfig, logical_resources: R) -> Result<Arc<Self>> {
106
        let model_config = config.model.clone();
Ryan Olson's avatar
Ryan Olson committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
        let mut resources = Resources::new(config)?;
        let block_data_factories =
            logical::LogicalBlockFactories::new(&mut resources, logical_resources)?;

        let (disk_factory, host_factory, device_factory) = block_data_factories.dissolve();

        let (disk_pool, disk_blocks) = match disk_factory {
            Some(factory) => {
                let (pool, blocks) =
                    create_block_pool::<_, _, Metadata>(factory, &resources, "disk")?;
                (Some(pool), Some(blocks))
            }
            None => {
                tracing::debug!("No disk layout provided; will not allocate disk blocks.");
                (None, None)
            }
        };
Ryan Olson's avatar
Ryan Olson committed
124

Ryan Olson's avatar
Ryan Olson committed
125
126
127
128
129
        let (host_pool, host_blocks) = match host_factory {
            Some(factory) => {
                let (pool, blocks) =
                    create_block_pool::<_, _, Metadata>(factory, &resources, "host")?;
                (Some(pool), Some(blocks))
Ryan Olson's avatar
Ryan Olson committed
130
            }
Ryan Olson's avatar
Ryan Olson committed
131
132
133
134
135
            None => {
                tracing::debug!("No host layout provided; will not allocate host blocks.");
                (None, None)
            }
        };
Ryan Olson's avatar
Ryan Olson committed
136

Ryan Olson's avatar
Ryan Olson committed
137
138
139
140
141
142
143
144
145
146
        let (device_pool, device_blocks) = match device_factory {
            Some(factory) => {
                let (pool, blocks) =
                    create_block_pool::<_, _, Metadata>(factory, &resources, "device")?;
                (Some(pool), Some(blocks))
            }
            None => {
                tracing::debug!("No device layout provided; will not allocate device blocks.");
                (None, None)
            }
147
148
        };

149
150
151
152
153
154
155
156
        let offload_config = OffloadManagerConfig {
            nixl_agent: resources.nixl_agent.clone(),
            async_rt_handle: resources.async_rt_handle.clone(),
            metrics: resources.metrics.clone(),
            cancellation_token: resources.cancellation_token.clone(),
            model_config,
        };

Ryan Olson's avatar
Ryan Olson committed
157
158
159
160
        let offload_manager = OffloadManager::new(
            disk_pool.clone(),
            host_pool.clone(),
            device_pool.clone(),
161
            offload_config,
Ryan Olson's avatar
Ryan Olson committed
162
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
189
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
        )?;

        let resources = Arc::new(resources);

        let state = Arc::new(Self {
            resources: resources.clone(),
            disk_pool,
            host_pool,
            device_pool,
            local_block_set: NixlBlockSet::new(resources.worker_id),
            remote_block_sets: RwLock::new(HashMap::new()),
            offload_manager,
        });

        if let Some(mut blocks) = disk_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state.disk_pool.as_ref().unwrap().add_blocks(blocks).await?;
        }

        if let Some(mut blocks) = host_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state.host_pool.as_ref().unwrap().add_blocks(blocks).await?;
        }

        if let Some(mut blocks) = device_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state
                .device_pool
                .as_ref()
                .unwrap()
                .add_blocks(blocks)
                .await?;
        }

        Ok(state)
    }
}

// move into mod local
// move local block data factory into mod super::block
// create a method on locality to construct a block data factory from a layout builder and resources
// - this will allow us to use the locality abstraction to build our factories and block pools
impl<Metadata: BlockMetadata> KvBlockManagerState<locality::Local, Metadata> {
    pub async fn new(config: KvBlockManagerConfig) -> Result<Arc<Self>> {
215
        let model_config = config.model.clone();
Ryan Olson's avatar
Ryan Olson committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
        let mut resources = Resources::new(config)?;
        let block_data_factories = local::LocalBlockDataFactories::new(&mut resources)?;

        let (mut local_block_set, disk_factory, host_factory, device_factory) =
            block_data_factories.dissolve();

        let (disk_pool, disk_blocks) = match disk_factory {
            Some(factory) => {
                let (pool, blocks) =
                    create_block_pool::<_, _, Metadata>(factory, &resources, "disk")?;
                (Some(pool), Some(blocks))
            }
            None => {
                tracing::debug!("No disk layout provided; will not allocate disk blocks.");
230
                (None, None)
231
232
233
            }
        };

Ryan Olson's avatar
Ryan Olson committed
234
235
236
237
238
239
240
241
242
243
        let (host_pool, host_blocks) = match host_factory {
            Some(factory) => {
                let (pool, blocks) =
                    create_block_pool::<_, _, Metadata>(factory, &resources, "host")?;
                (Some(pool), Some(blocks))
            }
            None => {
                tracing::debug!("No disk layout provided; will not allocate disk blocks.");
                (None, None)
            }
Ryan Olson's avatar
Ryan Olson committed
244
245
        };

Ryan Olson's avatar
Ryan Olson committed
246
247
248
249
250
251
252
253
254
255
        let (device_pool, device_blocks) = match device_factory {
            Some(factory) => {
                let (pool, blocks) =
                    create_block_pool::<_, _, Metadata>(factory, &resources, "disk")?;
                (Some(pool), Some(blocks))
            }
            None => {
                tracing::debug!("No disk layout provided; will not allocate disk blocks.");
                (None, None)
            }
Ryan Olson's avatar
Ryan Olson committed
256
257
258
        };

        // Finalize the local block set by adding NIXL metadata
Ryan Olson's avatar
Ryan Olson committed
259
        if let Some(nixl_agent) = resources.nixl_agent.as_ref() {
Ryan Olson's avatar
Ryan Olson committed
260
261
262
263
            tracing::debug!("Finalize NixlBlockSet: adding NIXL metadata.");
            local_block_set.set_nixl_metadata(nixl_agent.get_local_md()?);
        }

264
265
266
267
268
269
270
271
        let offload_config = OffloadManagerConfig {
            nixl_agent: resources.nixl_agent.clone(),
            async_rt_handle: resources.async_rt_handle.clone(),
            metrics: resources.metrics.clone(),
            cancellation_token: resources.cancellation_token.clone(),
            model_config,
        };

272
273
274
275
        let offload_manager = OffloadManager::new(
            disk_pool.clone(),
            host_pool.clone(),
            device_pool.clone(),
276
            offload_config,
277
        )?;
278

Ryan Olson's avatar
Ryan Olson committed
279
280
        let resources = Arc::new(resources);

Ryan Olson's avatar
Ryan Olson committed
281
        let state = Arc::new(Self {
Ryan Olson's avatar
Ryan Olson committed
282
            resources: resources.clone(),
283
            disk_pool,
Ryan Olson's avatar
Ryan Olson committed
284
285
286
287
            host_pool,
            device_pool,
            local_block_set,
            remote_block_sets: RwLock::new(HashMap::new()),
288
            offload_manager,
Ryan Olson's avatar
Ryan Olson committed
289
290
        });

291
292
293
294
295
        if let Some(mut blocks) = disk_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

Ryan Olson's avatar
Ryan Olson committed
296
            state.disk_pool.as_ref().unwrap().add_blocks(blocks).await?;
297
298
        }

Ryan Olson's avatar
Ryan Olson committed
299
300
301
302
303
        if let Some(mut blocks) = host_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

Ryan Olson's avatar
Ryan Olson committed
304
            state.host_pool.as_ref().unwrap().add_blocks(blocks).await?;
Ryan Olson's avatar
Ryan Olson committed
305
306
307
308
309
310
311
312
313
314
315
        }

        if let Some(mut blocks) = device_blocks {
            blocks.iter_mut().for_each(|block| {
                block.set_manager(state.clone());
            });

            state
                .device_pool
                .as_ref()
                .unwrap()
Ryan Olson's avatar
Ryan Olson committed
316
317
                .add_blocks(blocks)
                .await?;
Ryan Olson's avatar
Ryan Olson committed
318
319
320
321
322
323
324
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
        }

        Ok(state)
    }

    /// Exports the local blockset configuration as a serialized object.
    pub fn export_local_blockset(&self) -> Result<SerializedNixlBlockSet> {
        SerializedNixlBlockSet::try_from(&self.local_block_set)
            .context("Failed to serialize local blockset")
    }

    /// Imports a remote blockset configuration from a serialized object.
    // TODO: NIXL will validate the every descriptor list against the memory registration list for
    // a given agent; this is can be an expensive operation. To avoid this, NIXL offers the ability
    // to generate "partial pre-validated (PPV)" descriptor lists. However, to support per-block and per-layer
    // PPV lists we will need as many as `num_layers + 1` PPV lists per block:
    // - one for representing the entire block
    // - one for representing each layer individually
    //
    // A deeper dive into the performance impact of PPV lists is required to determine if this is
    // the best approach.
    //
    // If PPV are valuable, it might be beneficial to lazily instantiate PPV lists when they are
    // needed; alternatively, we could generate the entire PPV list for each block at import time.
    pub fn import_remote_blockset(
        &self,
        serialized_blockset: SerializedNixlBlockSet,
    ) -> Result<()> {
        let remote = NixlBlockSet::try_from(serialized_blockset)
            .context("Failed to deserialize remote blockset")?;

        let (block_sets, metadata, worker_id) = remote.dissolve();
        tracing::debug!("Importing remote blockset from worker {}", worker_id);

        assert_ne!(
Ryan Olson's avatar
Ryan Olson committed
353
            worker_id, self.resources.worker_id,
Ryan Olson's avatar
Ryan Olson committed
354
355
356
357
            "Cannot import blockset from self"
        );

        let agent = self
Ryan Olson's avatar
Ryan Olson committed
358
            .resources
Ryan Olson's avatar
Ryan Olson committed
359
360
            .nixl_agent
            .as_ref()
361
            .as_ref()
Ryan Olson's avatar
Ryan Olson committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
            .ok_or_else(|| anyhow::anyhow!("NIXL agent not initialized"))?;

        let mut remote_block_sets = self.remote_block_sets.write().unwrap();

        if remote_block_sets.contains_key(&worker_id) {
            anyhow::bail!(
                "Worker ID {} already exists; cannot update remote blockset",
                worker_id
            );
        }

        let mut inner_map = HashMap::new();

        for (block_set_idx, block_set_layout) in block_sets {
            // Deserialize the individual layout and create RemoteBlocks
            let remote_blocks =
                RemoteBlocks::from_serialized(block_set_layout.clone(), block_set_idx, worker_id)?;

            // check the storage type of the remote blocks
            let layout = remote_blocks.layout();
            let storage = layout.storage();

            let storage = storage
                .first()
                .ok_or_else(|| anyhow::anyhow!("No storage found in remote blockset"))?;

            match storage.mem_type() {
                MemType::Dram => {
                    tracing::trace!(block_set_idx, "Detected Host/DRAM remote descriptor");
                }
                MemType::Vram => {
                    tracing::trace!(block_set_idx, "Detected GPU/Device/VRAM remote descriptor");
                }
                _ => {
                    tracing::warn!(
                        block_set_idx,
                        "Detected unknown remote descriptor; skipping blockset..."
                    );
                    continue;
                }
            }

            inner_map.insert(block_set_idx, remote_blocks);
        }

        let agent_id = agent
            .load_remote_md(&metadata)
            .context("Loading remote metadata")?;

        // try to convert the agent_id (String) to a WorkerID (u64)
        let agent_id: WorkerID =
            agent_id // Assuming agent_id is String here
                .parse() // Parse the String into u64 (WorkerID)
                .context("Failed to parse agent ID string into WorkerID (u64)")?;

        assert_eq!(agent_id, worker_id, "Mismatch with remote worker ID");

        remote_block_sets.insert(worker_id, inner_map);

        Ok(())
    }

    /// Get a [`Vec<RemoteBlock<IsImmutable>>`] from a [`BlockDescriptorList`]
    pub fn get_remote_blocks_immutable(
        &self,
        bds: &BlockDescriptorList,
    ) -> Result<Vec<RemoteBlock<IsImmutable>>> {
        // no checks - we can always create an immutable remote block even if the bds is mutable
        self.get_remote_blocks::<IsImmutable>(bds)
    }

    /// Get a [`Vec<RemoteBlock<IsMutable>>`] from a [`BlockDescriptorList`]
    pub fn get_remote_blocks_mutable(
        &self,
        bds: &BlockDescriptorList,
    ) -> Result<Vec<RemoteBlock<IsMutable>>> {
        if bds.mutability() == BlockMutability::Mutable {
            self.get_remote_blocks::<IsMutable>(bds)
        } else {
            anyhow::bail!("Cannot get mutable remote blocks for immutable block descriptor set");
        }
    }

    /// Generate a [`Vec<RemoteBlock>`] from a [`BlockDescriptorList`]
    fn get_remote_blocks<M: MutabilityKind>(
        &self,
        bds: &BlockDescriptorList,
    ) -> Result<Vec<RemoteBlock<M>>> {
        // Get a read lock on the remote block sets
        let remote_block_sets = self.remote_block_sets.read().unwrap();

        // validate we have loaded a remote blockset for the worker and the specific block_set_idx
        let remote_blocks = remote_block_sets
            .get(&bds.worker_id())
            .and_then(|map| map.get(&bds.block_set_idx()))
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "No remote blockset found for worker {} and block_set_idx {}",
                    bds.worker_id(),
                    bds.block_set_idx()
                )
            })?;

        // Iterate through indices, call .block() for each, and collect results.
        // The collect::<Result<...>>() handles potential errors from .block()
        let blocks: Vec<block::nixl::RemoteBlock<M>> = bds
            .block_indices()
            .iter()
            .map(|block_idx| remote_blocks.block(*block_idx))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(blocks)
    }
}

Ryan Olson's avatar
Ryan Olson committed
477
478
479
impl<Locality: LocalityProvider, Metadata: BlockMetadata> std::fmt::Debug
    for KvBlockManagerState<Locality, Metadata>
{
Ryan Olson's avatar
Ryan Olson committed
480
481
482
483
484
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "KvBlockManagerState")
    }
}

Ryan Olson's avatar
Ryan Olson committed
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
//     if let Some(storage) = config.storage {
//         let mut layout = layout.create_layout(config.layout_type, storage, false)?;
//         if let Some(nixl_agent) = nixl_agent {
//             layout.nixl_register(nixl_agent, None)?;
//         }
//         return Ok(layout.into());
//     }

//     if let Some(allocator) = config.allocator {
//         let mut layout = layout.allocate_layout(config.layout_type, allocator)?;
//         if let Some(nixl_agent) = nixl_agent {
//             layout.nixl_register(nixl_agent, None)?;
//         }
//         return Ok(layout.into());
//     }

//     anyhow::bail!("failed to create layout");
// }

#[expect(clippy::type_complexity)]
pub(crate) fn create_block_pool<S: Storage, L: LocalityProvider, M: BlockMetadata>(
    factory: impl IntoBlocks<S, L>,
    resources: &Resources,
    pool_name: &str,
) -> Result<(Arc<dyn BlockPool<S, L, M>>, Vec<Block<S, L, M>>)> {
    let pool = ManagedBlockPool::<S, L, M>::builder()
        .cancel_token(resources.cancellation_token.clone())
        .global_registry(resources.global_registry.clone())
        .async_runtime(resources.async_rt_handle.clone())
        .event_manager(resources.event_manager.clone())
        .pool_metrics(resources.metrics.pool(pool_name))
        .build()?;
Ryan Olson's avatar
Ryan Olson committed
517

Ryan Olson's avatar
Ryan Olson committed
518
519
    let blocks = factory.into_blocks()?;
    Ok((Arc::new(pool), blocks))
Ryan Olson's avatar
Ryan Olson committed
520
521
}

Ryan Olson's avatar
Ryan Olson committed
522
// Block state operations moved to block.rs for better organization and private field access