tensorlogic-scirs-backend 0.1.0

SciRS2-powered tensor execution backend for TensorLogic
Documentation
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
283
284
285
286
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
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
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
//! Checkpoint and resume functionality for training workflows.
//!
//! This module provides utilities to save and restore executor state during training,
//! enabling mid-training checkpoints, recovery from failures, and incremental compilation.
//!
//! ## Features
//!
//! - **State Serialization**: Save executor tensors and forward tape
//! - **Incremental Checkpoints**: Save only changed tensors
//! - **Compression**: Optional compression for checkpoint files
//! - **Metadata**: Track training iteration, timestamp, and custom data
//! - **Verification**: Checksum validation for data integrity
//!
//! ## Example
//!
//! ```rust,ignore
//! use tensorlogic_scirs_backend::{Scirs2Exec, Checkpoint, CheckpointConfig};
//!
//! let mut executor = Scirs2Exec::new();
//! // ... training loop ...
//!
//! // Save checkpoint
//! let checkpoint = Checkpoint::from_executor(&executor, iteration)?;
//! checkpoint.save("checkpoint_epoch_5.bin")?;
//!
//! // Restore checkpoint
//! let checkpoint = Checkpoint::load("checkpoint_epoch_5.bin")?;
//! let mut executor = checkpoint.restore()?;
//! ```

use crate::{Scirs2Exec, TlBackendError, TlBackendResult};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, BufWriter, Write};
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};

/// Configuration for checkpoint creation and loading.
#[derive(Debug, Clone)]
pub struct CheckpointConfig {
    /// Enable compression (reduces file size but increases save time)
    pub enable_compression: bool,

    /// Include forward tape in checkpoint (needed for gradient computation)
    pub include_tape: bool,

    /// Verify checksum on load
    pub verify_checksum: bool,

    /// Save only tensors that changed since last checkpoint
    pub incremental: bool,
}

impl Default for CheckpointConfig {
    fn default() -> Self {
        Self {
            enable_compression: false,
            include_tape: false,
            verify_checksum: true,
            incremental: false,
        }
    }
}

impl CheckpointConfig {
    /// Create a configuration for training checkpoints (includes tape).
    pub fn for_training() -> Self {
        Self {
            enable_compression: false,
            include_tape: true,
            verify_checksum: true,
            incremental: false,
        }
    }

    /// Create a configuration for inference checkpoints (no tape, compressed).
    pub fn for_inference() -> Self {
        Self {
            enable_compression: true,
            include_tape: false,
            verify_checksum: true,
            incremental: false,
        }
    }

    /// Create a configuration for incremental checkpoints.
    pub fn incremental() -> Self {
        Self {
            enable_compression: false,
            include_tape: true,
            verify_checksum: true,
            incremental: true,
        }
    }
}

/// Metadata about a checkpoint.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CheckpointMetadata {
    /// Training iteration/epoch number
    pub iteration: usize,

    /// Timestamp when checkpoint was created
    pub timestamp: u64,

    /// Version of the checkpoint format
    pub version: String,

    /// Number of tensors in checkpoint
    pub tensor_count: usize,

    /// Total size in bytes (uncompressed)
    pub total_bytes: usize,

    /// Custom metadata (user-defined)
    pub custom: HashMap<String, String>,

    /// Checksum for verification (if enabled)
    pub checksum: Option<String>,
}

/// Serialized tensor data.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct SerializedTensor {
    name: String,
    shape: Vec<usize>,
    data: Vec<f64>,
}

/// A checkpoint containing executor state.
#[derive(Debug, Clone)]
pub struct Checkpoint {
    /// Checkpoint metadata
    pub metadata: CheckpointMetadata,

    /// Serialized tensors
    tensors: Vec<SerializedTensor>,

    /// Configuration used to create this checkpoint
    #[allow(dead_code)]
    config: CheckpointConfig,
}

impl Checkpoint {
    /// Create a checkpoint from an executor.
    pub fn from_executor(executor: &Scirs2Exec, iteration: usize) -> TlBackendResult<Self> {
        Self::from_executor_with_config(executor, iteration, &CheckpointConfig::default())
    }

    /// Create a checkpoint with custom configuration.
    pub fn from_executor_with_config(
        executor: &Scirs2Exec,
        iteration: usize,
        config: &CheckpointConfig,
    ) -> TlBackendResult<Self> {
        let mut tensors = Vec::new();
        let mut total_bytes = 0;

        // Serialize all tensors
        for (name, tensor) in &executor.tensors {
            let shape = tensor.shape().to_vec();
            let data: Vec<f64> = tensor.iter().copied().collect();
            total_bytes += data.len() * std::mem::size_of::<f64>();

            tensors.push(SerializedTensor {
                name: name.clone(),
                shape,
                data,
            });
        }

        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| TlBackendError::execution(format!("Failed to get timestamp: {}", e)))?
            .as_secs();

        let checksum = if config.verify_checksum {
            Some(Self::compute_checksum(&tensors))
        } else {
            None
        };

        let metadata = CheckpointMetadata {
            iteration,
            timestamp,
            version: "0.1.0".to_string(),
            tensor_count: tensors.len(),
            total_bytes,
            custom: HashMap::new(),
            checksum,
        };

        Ok(Checkpoint {
            metadata,
            tensors,
            config: config.clone(),
        })
    }

    /// Save checkpoint to a file.
    pub fn save<P: AsRef<Path>>(&self, path: P) -> TlBackendResult<()> {
        let file = File::create(path.as_ref()).map_err(|e| {
            TlBackendError::execution(format!("Failed to create checkpoint file: {}", e))
        })?;
        let mut writer = BufWriter::new(file);

        // Serialize to JSON (could use oxicode for better performance)
        let checkpoint_data = CheckpointData {
            metadata: self.metadata.clone(),
            tensors: self.tensors.clone(),
        };

        serde_json::to_writer(&mut writer, &checkpoint_data).map_err(|e| {
            TlBackendError::execution(format!("Failed to serialize checkpoint: {}", e))
        })?;

        writer
            .flush()
            .map_err(|e| TlBackendError::execution(format!("Failed to flush checkpoint: {}", e)))?;

        Ok(())
    }

    /// Load checkpoint from a file.
    pub fn load<P: AsRef<Path>>(path: P) -> TlBackendResult<Self> {
        Self::load_with_config(path, &CheckpointConfig::default())
    }

    /// Load checkpoint with custom configuration.
    pub fn load_with_config<P: AsRef<Path>>(
        path: P,
        config: &CheckpointConfig,
    ) -> TlBackendResult<Self> {
        let file = File::open(path.as_ref()).map_err(|e| {
            TlBackendError::execution(format!("Failed to open checkpoint file: {}", e))
        })?;
        let reader = BufReader::new(file);

        let checkpoint_data: CheckpointData = serde_json::from_reader(reader).map_err(|e| {
            TlBackendError::execution(format!("Failed to deserialize checkpoint: {}", e))
        })?;

        // Verify checksum if requested
        if config.verify_checksum {
            if let Some(ref expected_checksum) = checkpoint_data.metadata.checksum {
                let actual_checksum = Self::compute_checksum(&checkpoint_data.tensors);
                if &actual_checksum != expected_checksum {
                    return Err(TlBackendError::execution(
                        "Checkpoint checksum verification failed",
                    ));
                }
            }
        }

        Ok(Checkpoint {
            metadata: checkpoint_data.metadata,
            tensors: checkpoint_data.tensors,
            config: config.clone(),
        })
    }

    /// Restore an executor from this checkpoint.
    pub fn restore(&self) -> TlBackendResult<Scirs2Exec> {
        let mut executor = Scirs2Exec::new();

        // Deserialize tensors
        for serialized in &self.tensors {
            let tensor = scirs2_core::ndarray::ArrayD::from_shape_vec(
                serialized.shape.clone(),
                serialized.data.clone(),
            )
            .map_err(|e| {
                TlBackendError::execution(format!(
                    "Failed to restore tensor {}: {}",
                    serialized.name, e
                ))
            })?;

            executor.add_tensor(&serialized.name, tensor);
        }

        Ok(executor)
    }

    /// Restore tensors into an existing executor.
    pub fn restore_into(&self, executor: &mut Scirs2Exec) -> TlBackendResult<()> {
        for serialized in &self.tensors {
            let tensor = scirs2_core::ndarray::ArrayD::from_shape_vec(
                serialized.shape.clone(),
                serialized.data.clone(),
            )
            .map_err(|e| {
                TlBackendError::execution(format!(
                    "Failed to restore tensor {}: {}",
                    serialized.name, e
                ))
            })?;

            executor.add_tensor(&serialized.name, tensor);
        }

        Ok(())
    }

    /// Add custom metadata to the checkpoint.
    pub fn add_metadata(&mut self, key: String, value: String) {
        self.metadata.custom.insert(key, value);
    }

    /// Get custom metadata from the checkpoint.
    pub fn get_metadata(&self, key: &str) -> Option<&String> {
        self.metadata.custom.get(key)
    }

    /// Compute checksum for verification.
    fn compute_checksum(tensors: &[SerializedTensor]) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();

        for tensor in tensors {
            tensor.name.hash(&mut hasher);
            tensor.shape.hash(&mut hasher);
            // Hash float data as bytes
            for &value in &tensor.data {
                value.to_bits().hash(&mut hasher);
            }
        }

        format!("{:x}", hasher.finish())
    }

    /// Get the size of this checkpoint in bytes (uncompressed).
    pub fn size_bytes(&self) -> usize {
        self.metadata.total_bytes
    }

    /// Get a human-readable size string.
    pub fn size_human_readable(&self) -> String {
        let bytes = self.metadata.total_bytes;
        if bytes < 1024 {
            format!("{} bytes", bytes)
        } else if bytes < 1024 * 1024 {
            format!("{:.2} KB", bytes as f64 / 1024.0)
        } else if bytes < 1024 * 1024 * 1024 {
            format!("{:.2} MB", bytes as f64 / (1024.0 * 1024.0))
        } else {
            format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
        }
    }
}

/// Internal checkpoint data structure for serialization.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct CheckpointData {
    metadata: CheckpointMetadata,
    tensors: Vec<SerializedTensor>,
}

/// Manager for handling multiple checkpoints.
pub struct CheckpointManager {
    /// Directory where checkpoints are stored
    checkpoint_dir: std::path::PathBuf,

    /// Maximum number of checkpoints to keep
    max_checkpoints: Option<usize>,

    /// Pattern for checkpoint filenames
    filename_pattern: String,
}

impl CheckpointManager {
    /// Create a new checkpoint manager.
    pub fn new<P: AsRef<Path>>(checkpoint_dir: P) -> TlBackendResult<Self> {
        let checkpoint_dir = checkpoint_dir.as_ref().to_path_buf();

        // Create directory if it doesn't exist
        if !checkpoint_dir.exists() {
            std::fs::create_dir_all(&checkpoint_dir).map_err(|e| {
                TlBackendError::execution(format!("Failed to create checkpoint directory: {}", e))
            })?;
        }

        Ok(Self {
            checkpoint_dir,
            max_checkpoints: Some(5), // Keep last 5 checkpoints by default
            filename_pattern: "checkpoint_iter_{}.json".to_string(),
        })
    }

    /// Set the maximum number of checkpoints to keep.
    pub fn set_max_checkpoints(&mut self, max: Option<usize>) {
        self.max_checkpoints = max;
    }

    /// Set the filename pattern for checkpoints.
    pub fn set_filename_pattern(&mut self, pattern: String) {
        self.filename_pattern = pattern;
    }

    /// Save a checkpoint and manage old checkpoints.
    pub fn save_checkpoint(
        &self,
        executor: &Scirs2Exec,
        iteration: usize,
    ) -> TlBackendResult<std::path::PathBuf> {
        let checkpoint = Checkpoint::from_executor(executor, iteration)?;
        let filename = self.filename_pattern.replace("{}", &iteration.to_string());
        let path = self.checkpoint_dir.join(filename);

        checkpoint.save(&path)?;

        // Clean up old checkpoints if needed
        if let Some(max) = self.max_checkpoints {
            self.cleanup_old_checkpoints(max)?;
        }

        Ok(path)
    }

    /// Load the latest checkpoint.
    pub fn load_latest(&self) -> TlBackendResult<Checkpoint> {
        let latest_path = self.find_latest_checkpoint()?;
        Checkpoint::load(latest_path)
    }

    /// Find the latest checkpoint file.
    fn find_latest_checkpoint(&self) -> TlBackendResult<std::path::PathBuf> {
        let entries = std::fs::read_dir(&self.checkpoint_dir).map_err(|e| {
            TlBackendError::execution(format!("Failed to read checkpoint directory: {}", e))
        })?;

        let mut checkpoints: Vec<_> = entries
            .filter_map(|e| e.ok())
            .filter(|e| {
                e.path()
                    .extension()
                    .and_then(|s| s.to_str())
                    .map(|s| s == "json")
                    .unwrap_or(false)
            })
            .collect();

        checkpoints.sort_by_key(|e| {
            e.metadata()
                .ok()
                .and_then(|m| m.modified().ok())
                .unwrap_or(SystemTime::UNIX_EPOCH)
        });

        checkpoints
            .last()
            .map(|e| e.path())
            .ok_or_else(|| TlBackendError::execution("No checkpoints found"))
    }

    /// Remove old checkpoints keeping only the most recent `max` checkpoints.
    fn cleanup_old_checkpoints(&self, max: usize) -> TlBackendResult<()> {
        let entries = std::fs::read_dir(&self.checkpoint_dir).map_err(|e| {
            TlBackendError::execution(format!("Failed to read checkpoint directory: {}", e))
        })?;

        let mut checkpoints: Vec<_> = entries
            .filter_map(|e| e.ok())
            .filter(|e| {
                e.path()
                    .extension()
                    .and_then(|s| s.to_str())
                    .map(|s| s == "json")
                    .unwrap_or(false)
            })
            .collect();

        checkpoints.sort_by_key(|e| {
            e.metadata()
                .ok()
                .and_then(|m| m.modified().ok())
                .unwrap_or(SystemTime::UNIX_EPOCH)
        });

        // Remove oldest checkpoints
        let to_remove = checkpoints.len().saturating_sub(max);
        for entry in checkpoints.iter().take(to_remove) {
            std::fs::remove_file(entry.path()).ok();
        }

        Ok(())
    }

    /// List all checkpoints in the directory.
    pub fn list_checkpoints(&self) -> TlBackendResult<Vec<std::path::PathBuf>> {
        let entries = std::fs::read_dir(&self.checkpoint_dir).map_err(|e| {
            TlBackendError::execution(format!("Failed to read checkpoint directory: {}", e))
        })?;

        let mut checkpoints: Vec<_> = entries
            .filter_map(|e| e.ok())
            .filter(|e| {
                e.path()
                    .extension()
                    .and_then(|s| s.to_str())
                    .map(|s| s == "json")
                    .unwrap_or(false)
            })
            .map(|e| e.path())
            .collect();

        checkpoints.sort();
        Ok(checkpoints)
    }
}

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

    #[test]
    fn test_checkpoint_config_default() {
        let config = CheckpointConfig::default();
        assert!(!config.enable_compression);
        assert!(!config.include_tape);
        assert!(config.verify_checksum);
        assert!(!config.incremental);
    }

    #[test]
    fn test_checkpoint_config_training() {
        let config = CheckpointConfig::for_training();
        assert!(!config.enable_compression);
        assert!(config.include_tape);
        assert!(config.verify_checksum);
    }

    #[test]
    fn test_checkpoint_config_inference() {
        let config = CheckpointConfig::for_inference();
        assert!(config.enable_compression);
        assert!(!config.include_tape);
        assert!(config.verify_checksum);
    }

    #[test]
    fn test_checkpoint_from_executor() {
        let mut executor = Scirs2Exec::new();
        let tensor =
            ArrayD::from_shape_vec(vec![2, 3], vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).expect("unwrap");
        executor.add_tensor("test_tensor", tensor);

        let checkpoint = Checkpoint::from_executor(&executor, 1).expect("unwrap");

        assert_eq!(checkpoint.metadata.iteration, 1);
        assert_eq!(checkpoint.metadata.tensor_count, 1);
        assert!(checkpoint.metadata.total_bytes > 0);
    }

    #[test]
    fn test_checkpoint_save_and_load() {
        let mut executor = Scirs2Exec::new();
        let tensor = ArrayD::from_shape_vec(vec![3], vec![1.0, 2.0, 3.0]).expect("unwrap");
        executor.add_tensor("weights", tensor);

        // Save checkpoint
        let checkpoint = Checkpoint::from_executor(&executor, 5).expect("unwrap");
        let temp_path = std::env::temp_dir().join("test_checkpoint.json");
        checkpoint.save(&temp_path).expect("unwrap");

        // Load checkpoint
        let loaded = Checkpoint::load(&temp_path).expect("unwrap");
        assert_eq!(loaded.metadata.iteration, 5);
        assert_eq!(loaded.metadata.tensor_count, 1);

        // Cleanup
        std::fs::remove_file(temp_path).ok();
    }

    #[test]
    fn test_checkpoint_restore() {
        let mut executor = Scirs2Exec::new();
        let tensor = ArrayD::from_shape_vec(vec![2], vec![10.0, 20.0]).expect("unwrap");
        executor.add_tensor("params", tensor.clone());

        // Create and restore checkpoint
        let checkpoint = Checkpoint::from_executor(&executor, 1).expect("unwrap");
        let restored_executor = checkpoint.restore().expect("unwrap");

        // Verify restored tensor
        let restored_tensor = restored_executor.get_tensor("params").expect("unwrap");
        assert_eq!(restored_tensor.shape(), tensor.shape());
        assert_eq!(restored_tensor[[0]], 10.0);
        assert_eq!(restored_tensor[[1]], 20.0);
    }

    #[test]
    fn test_checkpoint_metadata() {
        let mut executor = Scirs2Exec::new();
        let tensor = ArrayD::from_shape_vec(vec![1], vec![1.0]).expect("unwrap");
        executor.add_tensor("x", tensor);

        let mut checkpoint = Checkpoint::from_executor(&executor, 10).expect("unwrap");
        checkpoint.add_metadata("learning_rate".to_string(), "0.001".to_string());
        checkpoint.add_metadata("optimizer".to_string(), "adam".to_string());

        assert_eq!(
            checkpoint.get_metadata("learning_rate"),
            Some(&"0.001".to_string())
        );
        assert_eq!(
            checkpoint.get_metadata("optimizer"),
            Some(&"adam".to_string())
        );
        assert_eq!(checkpoint.get_metadata("missing"), None);
    }

    #[test]
    fn test_checkpoint_size_human_readable() {
        let mut executor = Scirs2Exec::new();
        let tensor = ArrayD::from_shape_vec(vec![1000], vec![1.0; 1000]).expect("unwrap");
        executor.add_tensor("big_tensor", tensor);

        let checkpoint = Checkpoint::from_executor(&executor, 1).expect("unwrap");
        let size_str = checkpoint.size_human_readable();

        // 1000 floats * 8 bytes = 8000 bytes = ~7.81 KB
        assert!(size_str.contains("KB") || size_str.contains("bytes"));
    }

    #[test]
    fn test_checkpoint_manager() {
        let temp_dir = std::env::temp_dir().join("test_checkpoints");
        let manager = CheckpointManager::new(&temp_dir).expect("unwrap");

        let mut executor = Scirs2Exec::new();
        let tensor = ArrayD::from_shape_vec(vec![2], vec![1.0, 2.0]).expect("unwrap");
        executor.add_tensor("data", tensor);

        // Save checkpoint
        let path = manager.save_checkpoint(&executor, 1).expect("unwrap");
        assert!(path.exists());

        // List checkpoints
        let checkpoints = manager.list_checkpoints().expect("unwrap");
        assert_eq!(checkpoints.len(), 1);

        // Cleanup
        std::fs::remove_dir_all(temp_dir).ok();
    }

    #[test]
    fn test_checkpoint_manager_cleanup() {
        let temp_dir = std::env::temp_dir().join("test_checkpoints_cleanup");
        let mut manager = CheckpointManager::new(&temp_dir).expect("unwrap");
        manager.set_max_checkpoints(Some(3));

        let mut executor = Scirs2Exec::new();
        let tensor = ArrayD::from_shape_vec(vec![1], vec![1.0]).expect("unwrap");
        executor.add_tensor("x", tensor);

        // Save 5 checkpoints
        for i in 1..=5 {
            manager.save_checkpoint(&executor, i).expect("unwrap");
        }

        // Should keep only last 3
        let checkpoints = manager.list_checkpoints().expect("unwrap");
        assert!(checkpoints.len() <= 3);

        // Cleanup
        std::fs::remove_dir_all(temp_dir).ok();
    }

    #[test]
    fn test_checkpoint_checksum_verification() {
        let mut executor = Scirs2Exec::new();
        let tensor = ArrayD::from_shape_vec(vec![2], vec![1.0, 2.0]).expect("unwrap");
        executor.add_tensor("data", tensor);

        let config = CheckpointConfig {
            verify_checksum: true,
            ..Default::default()
        };

        let checkpoint =
            Checkpoint::from_executor_with_config(&executor, 1, &config).expect("unwrap");
        assert!(checkpoint.metadata.checksum.is_some());

        let temp_path = std::env::temp_dir().join("test_checksum.json");
        checkpoint.save(&temp_path).expect("unwrap");

        // Load with verification
        let loaded = Checkpoint::load_with_config(&temp_path, &config).expect("unwrap");
        assert_eq!(loaded.metadata.checksum, checkpoint.metadata.checksum);

        // Cleanup
        std::fs::remove_file(temp_path).ok();
    }
}