utils.rs 12.8 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

4
use crate::block_manager::layout::{BlockLayoutConfig, GenericBlockLayout, LayoutError};
Ryan Olson's avatar
Ryan Olson committed
5
6
7
8
use crate::block_manager::storage::Storage;

use validator::ValidationError;

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
/// Verification result for a memory region
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct RegionVerificationResult {
    /// Block index that was verified
    pub block_idx: usize,
    /// Layer index that was verified
    pub layer_idx: usize,
    /// Outer dimension index that was verified
    pub outer_idx: usize,
    /// Expected memory address for this region
    pub expected_addr: usize,
    /// Actual memory address for this region
    pub actual_addr: usize,
    /// Expected size in bytes for this region
    pub expected_size: usize,
    /// Actual size in bytes for this region
    pub actual_size: usize,
    /// Whether the addresses match
    pub addr_matches: bool,
    /// Whether the sizes match
    pub size_matches: bool,
}

/// Layout verification statistics
#[derive(Debug, Clone, Default)]
#[allow(dead_code)]
pub struct LayoutVerificationStats {
    /// Total number of memory regions verified
    pub total_regions: usize,
    /// Number of regions with address mismatches
    pub addr_mismatches: usize,
    /// Number of regions with size mismatches
    pub size_mismatches: usize,
    /// Number of regions that passed all verifications
    pub successful_verifications: usize,
}

47
48
49
50
51
52
53
54
55
/// A utility for verifying the consistency and correctness of memory layout implementations.
///
/// This verifier systematically checks all memory regions within a layout to ensure:
/// - Memory addresses are calculated correctly
/// - Memory region sizes match expected values
/// - Layout configuration is internally consistent
///
/// The verifier maintains statistics about verification results and can identify
/// critical mismatches that indicate layout implementation errors.
56
57
58
59
60
61
#[derive(Debug)]
#[allow(dead_code)]
pub struct WorkerLayoutVerifier {
    stats: LayoutVerificationStats,
}

62
63
64
65
66
67
impl Default for WorkerLayoutVerifier {
    fn default() -> Self {
        Self::new()
    }
}

68
69
#[allow(dead_code)]
impl WorkerLayoutVerifier {
70
71
72
73
    /// Creates a new layout verifier with clean statistics.
    ///
    /// The verifier starts with zero counts for all verification metrics
    /// and is ready to verify layout consistency.
74
75
76
77
78
79
    pub fn new() -> Self {
        Self {
            stats: LayoutVerificationStats::default(),
        }
    }

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
    /// Verifies the consistency of all memory regions in a layout.
    ///
    /// This is the main orchestrator method that systematically checks every memory region
    /// in the layout to ensure consistency. It resets the internal statistics and then
    /// iterates through all valid combinations of block, layer, and outer dimension indices.
    ///
    /// # Arguments
    ///
    /// * `layout` - The layout to verify
    ///
    /// # Returns
    ///
    /// A vector of verification results for each memory region, or an error if
    /// verification fails for any region.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let mut verifier = WorkerLayoutVerifier::new();
    /// let results = verifier.verify_layout_consistency(&layout)?;
    /// if verifier.has_critical_mismatches() {
    ///     // Handle verification failures
    /// }
    /// ```
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
    pub fn verify_layout_consistency<L: GenericBlockLayout>(
        &mut self,
        layout: &L,
    ) -> Result<Vec<RegionVerificationResult>, LayoutError> {
        // This is the main orchestrator method.
        // It systematically checks every memory region in
        // the layout to ensure consistency.

        self.stats = LayoutVerificationStats::default();
        let mut results = Vec::new();

        // Iterate over all blocks, layers, and outer dimensions
        for block_idx in 0..layout.num_blocks() {
            for layer_idx in 0..layout.num_layers() {
                for outer_idx in 0..layout.outer_dim() {
                    let result =
                        self.verify_memory_region(layout, block_idx, layer_idx, outer_idx)?;
                    self.update_stats(&result);
                    results.push(result);
                }
            }
        }

        Ok(results)
    }

130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
    /// Verifies a specific memory region within a layout.
    ///
    /// This method checks a single memory region identified by the provided indices
    /// and compares the actual memory address and size against expected values.
    ///
    /// # Arguments
    ///
    /// * `layout` - The layout containing the memory region to verify
    /// * `block_idx` - The block index (must be < layout.num_blocks())
    /// * `layer_idx` - The layer index (must be < layout.num_layers())
    /// * `outer_idx` - The outer dimension index (must be < layout.outer_dim())
    ///
    /// # Returns
    ///
    /// A verification result containing the comparison between expected and actual
    /// values, or an error if the indices are invalid or layout access fails.
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
    pub fn verify_memory_region<L: GenericBlockLayout>(
        &mut self,
        layout: &L,
        block_idx: usize,
        layer_idx: usize,
        outer_idx: usize,
    ) -> Result<RegionVerificationResult, LayoutError> {
        let memory_region = layout.memory_region(block_idx, layer_idx, outer_idx)?;

        let config = layout.config();
        let expected_size = config.page_size * config.inner_dim * config.dtype_width_bytes;

        let expected_addr = memory_region.addr();

        Ok(RegionVerificationResult {
            block_idx,
            layer_idx,
            outer_idx,
            expected_addr,
            actual_addr: memory_region.addr(),
            expected_size,
            actual_size: memory_region.size(),
            addr_matches: expected_addr == memory_region.addr(),
            size_matches: expected_size == memory_region.size(),
        })
    }

    fn update_stats(&mut self, result: &RegionVerificationResult) {
        self.stats.total_regions += 1;
        if !result.addr_matches {
            self.stats.addr_mismatches += 1;
        }
        if !result.size_matches {
            self.stats.size_mismatches += 1;
        }
        if result.addr_matches && result.size_matches {
            self.stats.successful_verifications += 1;
        }
    }

186
187
188
189
190
191
192
193
194
    /// Checks if any critical mismatches were found during verification.
    ///
    /// Critical mismatches are currently defined as size mismatches, which indicate
    /// that the layout is calculating memory region sizes incorrectly. This is
    /// considered more critical than address mismatches as it affects memory safety.
    ///
    /// # Returns
    ///
    /// `true` if any memory regions had size mismatches, `false` otherwise.
195
196
197
198
199
    pub fn has_critical_mismatches(&self) -> bool {
        self.stats.size_mismatches > 0
    }
}

Ryan Olson's avatar
Ryan Olson committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/// Validation function for Option<usize> to check if it's Some(power_of_2).
pub fn validate_power_of_2(alignment: usize) -> Result<(), ValidationError> {
    if !alignment.is_power_of_two() {
        // Return validation error if alignment is not a power of 2
        return Err(validator::ValidationError::new(
            "alignment_must_be_power_of_2",
        ));
    }
    // Passes validation if alignment is a power of 2
    Ok(())
}

/// Helper to align a value up to the nearest multiple of alignment.
/// Alignment must be a power of 2.
214
#[inline(always)]
Ryan Olson's avatar
Ryan Olson committed
215
pub fn align_up(value: usize, alignment: usize) -> usize {
216
217
218
219
    debug_assert!(
        alignment.is_power_of_two(),
        "Alignment must be a power of 2"
    );
Ryan Olson's avatar
Ryan Olson committed
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
    (value + alignment - 1) & !(alignment - 1)
}

/// Helper to validate that a storage allocation is large enough for a layout.
pub fn validate_storage<S: Storage, C: BlockLayoutConfig>(
    storage: &S,
    config: &C,
) -> Result<usize, LayoutError> {
    let provided_size = storage.size();
    let storage_addr = storage.addr();
    let alignment = config.layout_config().alignment;

    // Calculate base offset needed to align the start of block 0
    let base_offset = if alignment > 1 {
        align_up(storage_addr as usize, alignment) - storage_addr as usize
    } else {
        0
    };

    let total_required_size_with_offset = base_offset + config.layout_data_bytes();

    tracing::debug!(
        provided_size,
        total_required_size_with_offset,
        base_offset,
        required_layout_data_bytes = config.layout_data_bytes(),
        alignment,
        "Validating storage size with base offset and alignment"
    );

    // Validate storage size fits the configuration *with base offset and alignment*
    if provided_size < total_required_size_with_offset {
        tracing::warn!(
            provided_size,
            total_required_size_with_offset,
            "Storage size too small for aligned layout including base offset"
        );
        return Err(LayoutError::InvalidConfig(format!(
            "Storage size {} is less than required size {} (including base offset for alignment)",
            provided_size, total_required_size_with_offset
        )));
    }

    Ok(base_offset)
}

266
/// Validate that the provided indices are within bounds for the given layout configuration
Ryan Olson's avatar
Ryan Olson committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
pub fn validate_indices<C: BlockLayoutConfig>(
    config: &C,
    block_idx: usize,
    layer_idx: usize,
    outer_idx: usize,
) -> Result<(), LayoutError> {
    if block_idx >= config.num_blocks() {
        return Err(LayoutError::InvalidBlockIndex(block_idx));
    }

    if layer_idx >= config.num_layers() {
        return Err(LayoutError::InvalidLayerIndex(layer_idx));
    }

    if outer_idx >= config.outer_dim() {
        return Err(LayoutError::InvalidOuterIndex(outer_idx));
    }

    Ok(())
}
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373

#[cfg(test)]
mod worker_verification_tests {
    use super::*;
    use crate::block_manager::LayoutConfig;
    use crate::block_manager::layout::{FullyContiguous, LayerSeparate};
    use crate::block_manager::storage::tests::{NullDeviceAllocator, NullDeviceStorage};

    // Test constants (same as layout.rs tests)
    const NUM_BLOCKS: usize = 7;
    const NUM_LAYERS: usize = 5;
    const OUTER_DIM: usize = 2;
    const PAGE_SIZE: usize = 4;
    const INNER_DIM: usize = 13;
    const DTYPE_WIDTH_BYTES: usize = 4;

    fn create_test_config() -> LayoutConfig {
        LayoutConfig {
            num_blocks: NUM_BLOCKS,
            num_layers: NUM_LAYERS,
            outer_dim: OUTER_DIM,
            page_size: PAGE_SIZE,
            inner_dim: INNER_DIM,
            alignment: 1,
            dtype_width_bytes: DTYPE_WIDTH_BYTES,
        }
    }

    fn create_fully_contiguous_layout() -> Result<FullyContiguous<NullDeviceStorage>, LayoutError> {
        let config = create_test_config();
        FullyContiguous::allocate(config, &NullDeviceAllocator)
    }

    fn create_layer_separate_layout() -> Result<LayerSeparate<NullDeviceStorage>, LayoutError> {
        let config = create_test_config();
        LayerSeparate::allocate(config, &NullDeviceAllocator, true) // outer_contiguous = true
    }

    #[test]
    fn test_verify_initialisation() {
        let verifier = WorkerLayoutVerifier::new();

        assert_eq!(verifier.stats.total_regions, 0);
        assert_eq!(verifier.stats.addr_mismatches, 0);
        assert_eq!(verifier.stats.size_mismatches, 0);
        assert_eq!(verifier.stats.successful_verifications, 0);

        assert!(!verifier.has_critical_mismatches());
    }

    #[test]
    fn test_layer_separate_verification() {
        let layout = create_layer_separate_layout().expect("Failed to create LayerSeparate layout");
        let mut verifier = WorkerLayoutVerifier::new();
        let results = verifier
            .verify_layout_consistency(&layout)
            .expect("Failed to verify layout");

        assert_eq!(results.len(), NUM_BLOCKS * NUM_LAYERS * OUTER_DIM);
        assert!(
            !verifier.has_critical_mismatches(),
            "Expected no critical mismatches but got: total={}, size_mismatches={}, successful={}",
            verifier.stats.total_regions,
            verifier.stats.size_mismatches,
            verifier.stats.successful_verifications
        );
    }

    #[test]
    fn test_fully_contiguous_verification() {
        let layout =
            create_fully_contiguous_layout().expect("Failed to create FullyContiguous layout");
        let mut verifier = WorkerLayoutVerifier::new();
        let results = verifier
            .verify_layout_consistency(&layout)
            .expect("Failed to verify layout");
        assert_eq!(results.len(), NUM_BLOCKS * NUM_LAYERS * OUTER_DIM);

        assert!(
            !verifier.has_critical_mismatches(),
            "Expected no critical mismatches but got: total={}, size_mismatches={}, successful={}",
            verifier.stats.total_regions,
            verifier.stats.size_mismatches,
            verifier.stats.successful_verifications
        );
    }
}