serialize.rs 9.47 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
1
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Serialization types for physical layouts.
//!
//! This module provides types for serializing and deserializing physical layouts
//! so they can be transmitted to remote nodes and reconstructed there for RDMA operations.

use super::physical::NixlMetadata;
use super::{BlockDimension, KvBlockLayout, LayoutConfig};
use anyhow::Result;
use dynamo_memory::{MemoryRegion, StorageKind};
use serde::{Deserialize, Serialize};

/// Format of blocks in a fully contiguous layout.
///
/// This enum describes how the blocks are organized and formatted in memory.
/// Currently only `Operational` is supported, but future variants may include
/// different compression schemes or memory layouts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BlockFormat {
    /// Standard operational format - blocks are stored in their normal, uncompressed form.
    Operational,
}

impl Default for BlockFormat {
    fn default() -> Self {
        Self::Operational
    }
}

/// Details specific to fully contiguous layouts.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FullyContiguousDetails {
    /// Format of the blocks in memory
    pub block_format: BlockFormat,
    /// KV block layout describing dimension ordering within blocks
    #[serde(default)]
    pub kv_block_layout: KvBlockLayout,
}

/// Details specific to layer-separate layouts.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LayerSeparateDetails {
    /// Block dimension ordering (block-first or block-second)
    pub block_dim: BlockDimension,
    /// KV block layout for the inner tensor format (must be operational: NHD or HND)
    #[serde(default)]
    pub kv_block_layout: KvBlockLayout,
}

/// Layout-type-specific details.
///
/// This enum captures the information that differs between layout types
/// and is needed to reconstruct the layout on a remote node.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LayoutTypeDetails {
    /// Fully contiguous layout details
    FullyContiguous(FullyContiguousDetails),
    /// Layer-separate layout details
    LayerSeparate(LayerSeparateDetails),
}

/// Serializable representation of a physical layout.
///
/// This structure contains all information needed to reconstruct a layout
/// on a remote node, including:
/// - Layout configuration (dimensions, sizes, etc.)
/// - Storage location and NIXL metadata
/// - Memory descriptors for all regions
/// - Layout-type-specific details
///
/// The serialized form can be transmitted over the network and used to
/// build NIXL transfer descriptors for remote memory access.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LayoutDescriptor {
    /// Serialization format version (for future compatibility)
    pub version: u32,

    /// Layout configuration
    pub layout_config: LayoutConfig,

    /// Storage location
    pub location: StorageKind,

    /// NIXL metadata from the source node
    pub nixl_metadata: NixlMetadata,

    /// Memory descriptors for all regions backing this layout
    pub memory_descriptors: Vec<MemoryRegion>,

    /// Layout-type-specific details
    pub layout_type_details: LayoutTypeDetails,
}

impl LayoutDescriptor {
    /// Current serialization version
    pub const CURRENT_VERSION: u32 = 1;

    /// Serialize this layout to a JSON string.
    ///
    /// # Returns
    /// JSON string representation of the layout
    pub fn to_json(&self) -> Result<String> {
        serde_json::to_string(self)
            .map_err(|e| anyhow::anyhow!("failed to serialize layout to JSON: {}", e))
    }

    /// Serialize this layout to JSON bytes.
    ///
    /// # Returns
    /// UTF-8 encoded JSON bytes
    pub fn to_json_bytes(&self) -> Result<Vec<u8>> {
        serde_json::to_vec(self)
            .map_err(|e| anyhow::anyhow!("failed to serialize layout to JSON bytes: {}", e))
    }

    /// Deserialize a layout from a JSON string.
    ///
    /// # Arguments
    /// * `json` - JSON string representation
    ///
    /// # Returns
    /// Deserialized layout
    pub fn from_json(json: &str) -> Result<Self> {
        serde_json::from_str(json)
            .map_err(|e| anyhow::anyhow!("failed to deserialize layout from JSON: {}", e))
    }

    /// Deserialize a layout from JSON bytes.
    ///
    /// # Arguments
    /// * `bytes` - UTF-8 encoded JSON bytes
    ///
    /// # Returns
    /// Deserialized layout
    pub fn from_json_bytes(bytes: &[u8]) -> Result<Self> {
        serde_json::from_slice(bytes)
            .map_err(|e| anyhow::anyhow!("failed to deserialize layout from JSON bytes: {}", e))
    }

    /// Get the layout configuration.
    pub fn layout_config(&self) -> &LayoutConfig {
        &self.layout_config
    }

    /// Get the storage location.
    pub fn location(&self) -> StorageKind {
        self.location
    }

    /// Get the NIXL metadata from the source node.
    pub fn nixl_metadata(&self) -> &NixlMetadata {
        &self.nixl_metadata
    }

    /// Get the memory descriptors.
    pub fn memory_descriptors(&self) -> &[MemoryRegion] {
        &self.memory_descriptors
    }

    /// Get the layout type details.
    pub fn layout_type_details(&self) -> &LayoutTypeDetails {
        &self.layout_type_details
    }
}

#[cfg(all(test, feature = "testing-kvbm"))]
mod tests {
    use dynamo_memory::nixl::MemType;

    use super::*;

    fn make_test_config() -> LayoutConfig {
        LayoutConfig::builder()
            .num_blocks(10)
            .num_layers(4)
            .outer_dim(2)
            .page_size(16)
            .inner_dim(128)
            .dtype_width_bytes(2)
            .build()
            .unwrap()
    }

    #[test]
    fn test_block_format_default() {
        assert_eq!(BlockFormat::default(), BlockFormat::Operational);
    }

    #[test]
    fn test_serialized_layout_json_roundtrip() {
        let layout = LayoutDescriptor {
            version: LayoutDescriptor::CURRENT_VERSION,
            layout_config: make_test_config(),
            location: StorageKind::System,
            nixl_metadata: NixlMetadata::new("test_agent".to_string(), MemType::Dram, 0),
            memory_descriptors: vec![MemoryRegion::new(0x1000, 4096)],
            layout_type_details: LayoutTypeDetails::FullyContiguous(FullyContiguousDetails {
                block_format: BlockFormat::Operational,
                kv_block_layout: KvBlockLayout::OperationalNHD,
            }),
        };

        // Test to_json/from_json
        let json = layout.to_json().unwrap();
        let deserialized = LayoutDescriptor::from_json(&json).unwrap();

        assert_eq!(deserialized.version, layout.version);
        assert_eq!(deserialized.layout_config, layout.layout_config);
        assert_eq!(deserialized.location, layout.location);
        assert_eq!(
            deserialized.nixl_metadata.agent_name(),
            layout.nixl_metadata.agent_name()
        );
        assert_eq!(deserialized.memory_descriptors.len(), 1);
    }

    #[test]
    fn test_serialized_layout_json_bytes_roundtrip() {
        let layout = LayoutDescriptor {
            version: LayoutDescriptor::CURRENT_VERSION,
            layout_config: make_test_config(),
            location: StorageKind::System,
            nixl_metadata: NixlMetadata::new("test_agent".to_string(), MemType::Vram, 5),
            memory_descriptors: vec![
                MemoryRegion::new(0x1000, 2048),
                MemoryRegion::new(0x2000, 2048),
            ],
            layout_type_details: LayoutTypeDetails::LayerSeparate(LayerSeparateDetails {
                block_dim: BlockDimension::BlockIsFirstDim,
                kv_block_layout: KvBlockLayout::OperationalNHD,
            }),
        };

        // Test to_json_bytes/from_json_bytes
        let bytes = layout.to_json_bytes().unwrap();
        let deserialized = LayoutDescriptor::from_json_bytes(&bytes).unwrap();

        assert_eq!(deserialized.version, layout.version);
        assert_eq!(deserialized.nixl_metadata.device_id(), 5);
        assert_eq!(deserialized.memory_descriptors.len(), 2);
    }

    #[test]
    fn test_fully_contiguous_details_serialization() {
        let details = LayoutTypeDetails::FullyContiguous(FullyContiguousDetails {
            block_format: BlockFormat::Operational,
            kv_block_layout: KvBlockLayout::UniversalTP,
        });

        let json = serde_json::to_string(&details).unwrap();
        let deserialized: LayoutTypeDetails = serde_json::from_str(&json).unwrap();

        match deserialized {
            LayoutTypeDetails::FullyContiguous(d) => {
                assert_eq!(d.block_format, BlockFormat::Operational);
                assert_eq!(d.kv_block_layout, KvBlockLayout::UniversalTP);
            }
            _ => panic!("Expected FullyContiguous variant"),
        }
    }

    #[test]
    fn test_layer_separate_details_serialization() {
        let details = LayoutTypeDetails::LayerSeparate(LayerSeparateDetails {
            block_dim: BlockDimension::BlockIsSecondDim,
            kv_block_layout: KvBlockLayout::OperationalHND,
        });

        let json = serde_json::to_string(&details).unwrap();
        let deserialized: LayoutTypeDetails = serde_json::from_str(&json).unwrap();

        match deserialized {
            LayoutTypeDetails::LayerSeparate(d) => {
                assert_eq!(d.block_dim, BlockDimension::BlockIsSecondDim);
                assert_eq!(d.kv_block_layout, KvBlockLayout::OperationalHND);
            }
            _ => panic!("Expected LayerSeparate variant"),
        }
    }
}