tenflowers-dataset 0.1.1

Data pipeline and dataset utilities for TenfloweRS
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! Predictive prefetching with access pattern learning
//!
//! This module provides intelligent prefetching capabilities that learn from
//! access patterns to predict and preload data before it's requested.

use crate::Dataset;
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use tenflowers_core::{Result, Tensor};

/// Access pattern types detected by the system
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AccessPattern {
    /// Sequential access (i, i+1, i+2, ...)
    Sequential { stride: usize },
    /// Random access with no detectable pattern
    Random,
    /// Repeating pattern (cycles through a set of indices)
    Cyclic { pattern: Vec<usize> },
    /// Strided access (i, i+k, i+2k, ...)
    Strided { start: usize, stride: usize },
}

/// Statistics about access patterns
#[derive(Debug, Clone, Default)]
pub struct AccessStats {
    pub total_accesses: u64,
    pub sequential_accesses: u64,
    pub random_accesses: u64,
    pub pattern_hits: u64,
    pub pattern_misses: u64,
    pub prefetch_hits: u64,
    pub prefetch_misses: u64,
    pub bandwidth_saved: u64, // Bytes saved by avoiding disk I/O
}

impl AccessStats {
    /// Calculate pattern prediction accuracy
    pub fn pattern_accuracy(&self) -> f64 {
        let total_predictions = self.pattern_hits + self.pattern_misses;
        if total_predictions == 0 {
            0.0
        } else {
            self.pattern_hits as f64 / total_predictions as f64
        }
    }

    /// Calculate prefetch efficiency
    pub fn prefetch_efficiency(&self) -> f64 {
        let total_prefetches = self.prefetch_hits + self.prefetch_misses;
        if total_prefetches == 0 {
            0.0
        } else {
            self.prefetch_hits as f64 / total_prefetches as f64
        }
    }

    /// Calculate sequential access ratio
    pub fn sequential_ratio(&self) -> f64 {
        if self.total_accesses == 0 {
            0.0
        } else {
            self.sequential_accesses as f64 / self.total_accesses as f64
        }
    }
}

/// Prefetch entry stored in cache
#[derive(Debug)]
struct PrefetchEntry<T> {
    data: (Tensor<T>, Tensor<T>),
    timestamp: Instant,
    access_count: u32,
}

/// Pattern detector that learns access patterns
#[derive(Debug)]
struct PatternDetector {
    /// Recent access history
    access_history: VecDeque<usize>,
    /// Detected patterns and their confidence scores
    detected_patterns: HashMap<AccessPattern, f64>,
    /// Maximum history size to keep
    max_history: usize,
    /// Minimum pattern length to detect
    min_pattern_length: usize,
}

impl PatternDetector {
    fn new(max_history: usize) -> Self {
        Self {
            access_history: VecDeque::new(),
            detected_patterns: HashMap::new(),
            max_history,
            min_pattern_length: 3,
        }
    }

    /// Record a new access
    fn record_access(&mut self, index: usize) {
        self.access_history.push_back(index);

        // Trim history if too long
        while self.access_history.len() > self.max_history {
            self.access_history.pop_front();
        }

        // Analyze patterns
        self.analyze_patterns();
    }

    /// Analyze recent accesses to detect patterns
    fn analyze_patterns(&mut self) {
        if self.access_history.len() < self.min_pattern_length {
            return;
        }

        // Clear old patterns with low confidence
        self.detected_patterns
            .retain(|_, confidence| *confidence > 0.1);

        // Check for sequential pattern
        self.detect_sequential_pattern();

        // Check for strided pattern
        self.detect_strided_pattern();

        // Check for cyclic pattern
        self.detect_cyclic_pattern();
    }

    /// Detect sequential access pattern
    fn detect_sequential_pattern(&mut self) {
        let history: Vec<_> = self.access_history.iter().cloned().collect();
        let mut sequential_count = 0;

        for window in history.windows(2) {
            if window[1] == window[0] + 1 {
                sequential_count += 1;
            }
        }

        let confidence = sequential_count as f64 / (history.len() - 1) as f64;
        if confidence > 0.7 {
            self.detected_patterns
                .insert(AccessPattern::Sequential { stride: 1 }, confidence);
        }
    }

    /// Detect strided access pattern
    fn detect_strided_pattern(&mut self) {
        let history: Vec<_> = self.access_history.iter().cloned().collect();
        if history.len() < 3 {
            return;
        }

        // Try different stride values
        for stride in 2..=10 {
            let mut matches = 0;
            let start = history[0];

            for (i, &index) in history.iter().enumerate() {
                if index == start + i * stride {
                    matches += 1;
                }
            }

            let confidence = matches as f64 / history.len() as f64;
            if confidence > 0.8 {
                self.detected_patterns
                    .insert(AccessPattern::Strided { start, stride }, confidence);
            }
        }
    }

    /// Detect cyclic access pattern
    fn detect_cyclic_pattern(&mut self) {
        let history: Vec<_> = self.access_history.iter().cloned().collect();

        // Look for repeating subsequences
        for pattern_length in self.min_pattern_length..=(history.len() / 2) {
            if history.len() < pattern_length * 2 {
                continue;
            }

            let pattern: Vec<_> = history[history.len() - pattern_length..].to_vec();
            let mut repeats = 0;
            let mut total_checks = 0;

            let mut pos = history.len() - pattern_length * 2;
            while pos < history.len() - pattern_length {
                total_checks += 1;
                let segment = &history[pos..pos + pattern_length];
                if segment == pattern {
                    repeats += 1;
                }
                pos += pattern_length;
            }

            if total_checks > 0 {
                let confidence = repeats as f64 / total_checks as f64;
                if confidence > 0.8 {
                    self.detected_patterns
                        .insert(AccessPattern::Cyclic { pattern }, confidence);
                }
            }
        }
    }

    /// Predict next indices based on detected patterns
    fn predict_next(&self, current_index: usize, count: usize) -> Vec<usize> {
        let mut predictions = Vec::new();

        // Use the pattern with highest confidence
        if let Some((pattern, _)) = self.detected_patterns.iter().max_by(|a, b| {
            a.1.partial_cmp(b.1)
                .expect("partial_cmp should not return None for valid values")
        }) {
            match pattern {
                AccessPattern::Sequential { stride } => {
                    for i in 1..=count {
                        predictions.push(current_index + i * stride);
                    }
                }
                AccessPattern::Strided { start: _, stride } => {
                    let next_in_sequence = current_index + stride;
                    predictions.push(next_in_sequence);
                    for i in 1..count {
                        predictions.push(next_in_sequence + i * stride);
                    }
                }
                AccessPattern::Cyclic { pattern } => {
                    if let Some(current_pos) = pattern.iter().position(|&x| x == current_index) {
                        for i in 1..=count {
                            let next_pos = (current_pos + i) % pattern.len();
                            predictions.push(pattern[next_pos]);
                        }
                    }
                }
                AccessPattern::Random => {
                    // No predictions for random access
                }
            }
        }

        predictions
    }

    /// Get the most confident pattern
    pub fn dominant_pattern(&self) -> Option<AccessPattern> {
        self.detected_patterns
            .iter()
            .max_by(|a, b| {
                a.1.partial_cmp(b.1)
                    .expect("partial_cmp should not return None for valid values")
            })
            .map(|(pattern, _)| pattern.clone())
    }
}

/// Predictive prefetcher that learns access patterns and preloads data
pub struct PredictivePrefetcher<T, D: Dataset<T>>
where
    T: Clone + Send + Sync + 'static,
    D: Send + Sync + 'static,
{
    /// Reference to the dataset
    dataset: Arc<D>,
    /// Pattern detector for learning access patterns
    pattern_detector: Arc<RwLock<PatternDetector>>,
    /// Prefetch cache
    prefetch_cache: Arc<RwLock<HashMap<usize, PrefetchEntry<T>>>>,
    /// Configuration
    config: PrefetchConfig,
    /// Background prefetch worker
    worker_handle: Option<JoinHandle<()>>,
    /// Shutdown signal
    shutdown_signal: Arc<AtomicBool>,
    /// Statistics
    stats: Arc<RwLock<AccessStats>>,
    /// Pending prefetch requests
    prefetch_queue: Arc<Mutex<VecDeque<usize>>>,
}

/// Configuration for predictive prefetching
#[derive(Debug, Clone)]
pub struct PrefetchConfig {
    /// Maximum number of items to prefetch ahead
    pub max_prefetch_count: usize,
    /// Maximum cache size (number of items)
    pub max_cache_size: usize,
    /// Pattern detection history size
    pub pattern_history_size: usize,
    /// Cache entry TTL (time to live)
    pub cache_ttl: Duration,
    /// Prefetch worker sleep duration when idle
    pub worker_sleep_duration: Duration,
    /// Enable bandwidth optimization
    pub bandwidth_optimization: bool,
}

impl Default for PrefetchConfig {
    fn default() -> Self {
        Self {
            max_prefetch_count: 8,
            max_cache_size: 128,
            pattern_history_size: 50,
            cache_ttl: Duration::from_secs(300), // 5 minutes
            worker_sleep_duration: Duration::from_millis(10),
            bandwidth_optimization: true,
        }
    }
}

impl<T, D> PredictivePrefetcher<T, D>
where
    T: Clone + Send + Sync + 'static,
    D: Dataset<T> + Send + Sync + 'static,
{
    /// Create a new predictive prefetcher
    pub fn new(dataset: Arc<D>) -> Self {
        Self::with_config(dataset, PrefetchConfig::default())
    }

    /// Create a new predictive prefetcher with custom configuration
    pub fn with_config(dataset: Arc<D>, config: PrefetchConfig) -> Self {
        let pattern_detector = Arc::new(RwLock::new(PatternDetector::new(
            config.pattern_history_size,
        )));
        let prefetch_cache = Arc::new(RwLock::new(HashMap::new()));
        let shutdown_signal = Arc::new(AtomicBool::new(false));
        let stats = Arc::new(RwLock::new(AccessStats::default()));
        let prefetch_queue = Arc::new(Mutex::new(VecDeque::new()));

        // Start background prefetch worker
        let worker_handle = Self::start_prefetch_worker(
            dataset.clone(),
            prefetch_cache.clone(),
            prefetch_queue.clone(),
            shutdown_signal.clone(),
            config.clone(),
            stats.clone(),
        );

        Self {
            dataset,
            pattern_detector,
            prefetch_cache,
            config,
            worker_handle: Some(worker_handle),
            shutdown_signal,
            stats,
            prefetch_queue,
        }
    }

    /// Start the background prefetch worker
    fn start_prefetch_worker(
        dataset: Arc<D>,
        cache: Arc<RwLock<HashMap<usize, PrefetchEntry<T>>>>,
        queue: Arc<Mutex<VecDeque<usize>>>,
        shutdown: Arc<AtomicBool>,
        config: PrefetchConfig,
        stats: Arc<RwLock<AccessStats>>,
    ) -> JoinHandle<()> {
        thread::spawn(move || {
            while !shutdown.load(Ordering::Relaxed) {
                // Process prefetch requests
                let indices_to_prefetch: Vec<usize> = {
                    let mut queue_guard = queue.lock().expect("lock should not be poisoned");
                    let mut indices = Vec::new();

                    // Take up to max_prefetch_count items
                    for _ in 0..config.max_prefetch_count {
                        if let Some(index) = queue_guard.pop_front() {
                            indices.push(index);
                        } else {
                            break;
                        }
                    }
                    indices
                };

                // Prefetch the data
                for index in indices_to_prefetch {
                    if let Ok(data) = dataset.get(index) {
                        let mut cache_guard =
                            cache.write().expect("write lock should not be poisoned");

                        // Check cache size limit
                        if cache_guard.len() >= config.max_cache_size {
                            // Remove oldest entries
                            let oldest_key = cache_guard
                                .iter()
                                .min_by_key(|(_, entry)| entry.timestamp)
                                .map(|(k, _)| *k);

                            if let Some(key) = oldest_key {
                                cache_guard.remove(&key);
                            }
                        }

                        cache_guard.insert(
                            index,
                            PrefetchEntry {
                                data,
                                timestamp: Instant::now(),
                                access_count: 0,
                            },
                        );

                        // Update stats
                        let mut stats_guard =
                            stats.write().expect("write lock should not be poisoned");
                        stats_guard.bandwidth_saved +=
                            std::mem::size_of::<(Tensor<T>, Tensor<T>)>() as u64;
                    }
                }

                // Clean up expired entries
                {
                    let mut cache_guard = cache.write().expect("write lock should not be poisoned");
                    let now = Instant::now();
                    cache_guard
                        .retain(|_, entry| now.duration_since(entry.timestamp) < config.cache_ttl);
                }

                thread::sleep(config.worker_sleep_duration);
            }
        })
    }

    /// Get data with predictive prefetching
    pub fn get(&self, index: usize) -> Result<(Tensor<T>, Tensor<T>)> {
        // Update statistics
        {
            let mut stats = self
                .stats
                .write()
                .expect("write lock should not be poisoned");
            stats.total_accesses += 1;
        }

        // Record access pattern
        {
            let mut detector = self
                .pattern_detector
                .write()
                .expect("write lock should not be poisoned");
            detector.record_access(index);
        }

        // Check cache first
        {
            let mut cache = self
                .prefetch_cache
                .write()
                .expect("write lock should not be poisoned");
            if let Some(entry) = cache.get_mut(&index) {
                entry.access_count += 1;
                entry.timestamp = Instant::now(); // Update LRU

                let mut stats = self
                    .stats
                    .write()
                    .expect("write lock should not be poisoned");
                stats.prefetch_hits += 1;

                return Ok(entry.data.clone());
            } else {
                let mut stats = self
                    .stats
                    .write()
                    .expect("write lock should not be poisoned");
                stats.prefetch_misses += 1;
            }
        }

        // Predict and queue future accesses
        self.predict_and_queue_prefetch(index);

        // Get data from dataset
        self.dataset.get(index)
    }

    /// Predict future accesses and queue them for prefetching
    fn predict_and_queue_prefetch(&self, current_index: usize) {
        let predictions = {
            let detector = self
                .pattern_detector
                .read()
                .expect("read lock should not be poisoned");
            detector.predict_next(current_index, self.config.max_prefetch_count)
        };

        if !predictions.is_empty() {
            let mut queue = self
                .prefetch_queue
                .lock()
                .expect("lock should not be poisoned");
            for predicted_index in predictions {
                // Only queue if not already cached
                let cache = self
                    .prefetch_cache
                    .read()
                    .expect("read lock should not be poisoned");
                if !cache.contains_key(&predicted_index) {
                    queue.push_back(predicted_index);
                }
            }

            // Update pattern prediction stats
            let mut stats = self
                .stats
                .write()
                .expect("write lock should not be poisoned");
            stats.pattern_hits += 1;
        } else {
            let mut stats = self
                .stats
                .write()
                .expect("write lock should not be poisoned");
            stats.pattern_misses += 1;
        }
    }

    /// Get current statistics
    pub fn stats(&self) -> AccessStats {
        self.stats
            .read()
            .expect("read lock should not be poisoned")
            .clone()
    }

    /// Get the dominant access pattern
    pub fn dominant_pattern(&self) -> Option<AccessPattern> {
        self.pattern_detector
            .read()
            .expect("read lock should not be poisoned")
            .dominant_pattern()
    }

    /// Clear the prefetch cache
    pub fn clear_cache(&self) {
        let mut cache = self
            .prefetch_cache
            .write()
            .expect("write lock should not be poisoned");
        cache.clear();
    }

    /// Get cache statistics
    pub fn cache_info(&self) -> (usize, usize) {
        let cache = self
            .prefetch_cache
            .read()
            .expect("read lock should not be poisoned");
        (cache.len(), self.config.max_cache_size)
    }
}

impl<T, D> Drop for PredictivePrefetcher<T, D>
where
    T: Clone + Send + Sync + 'static,
    D: Dataset<T> + Send + Sync + 'static,
{
    fn drop(&mut self) {
        // Signal shutdown and wait for worker to finish
        self.shutdown_signal.store(true, Ordering::Relaxed);

        if let Some(handle) = self.worker_handle.take() {
            let _ = handle.join();
        }
    }
}

/// Dataset wrapper that provides predictive prefetching
pub struct PredictivePrefetchDataset<T, D: Dataset<T>>
where
    T: Clone + Send + Sync + 'static,
    D: Send + Sync + 'static,
{
    prefetcher: PredictivePrefetcher<T, D>,
}

impl<T, D> PredictivePrefetchDataset<T, D>
where
    T: Clone + Send + Sync + 'static,
    D: Dataset<T> + Send + Sync + 'static,
{
    /// Create a new predictive prefetch dataset
    pub fn new(dataset: D) -> Self {
        Self {
            prefetcher: PredictivePrefetcher::new(Arc::new(dataset)),
        }
    }

    /// Create with custom configuration
    pub fn with_config(dataset: D, config: PrefetchConfig) -> Self {
        Self {
            prefetcher: PredictivePrefetcher::with_config(Arc::new(dataset), config),
        }
    }

    /// Get access statistics
    pub fn stats(&self) -> AccessStats {
        self.prefetcher.stats()
    }

    /// Get the dominant access pattern
    pub fn dominant_pattern(&self) -> Option<AccessPattern> {
        self.prefetcher.dominant_pattern()
    }
}

impl<T, D> Dataset<T> for PredictivePrefetchDataset<T, D>
where
    T: Clone + Send + Sync + 'static,
    D: Dataset<T> + Send + Sync + 'static,
{
    fn len(&self) -> usize {
        self.prefetcher.dataset.len()
    }

    fn get(&self, index: usize) -> Result<(Tensor<T>, Tensor<T>)> {
        self.prefetcher.get(index)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::TensorDataset;
    use tenflowers_core::Tensor;

    #[test]
    fn test_pattern_detector_sequential() {
        let mut detector = PatternDetector::new(10);

        // Create sequential access pattern
        for i in 0..5 {
            detector.record_access(i);
        }

        let dominant = detector.dominant_pattern();
        assert!(matches!(
            dominant,
            Some(AccessPattern::Sequential { stride: 1 })
        ));
    }

    #[test]
    fn test_pattern_detector_strided() {
        let mut detector = PatternDetector::new(10);

        // Create strided access pattern (0, 2, 4, 6, 8)
        for i in 0..5 {
            detector.record_access(i * 2);
        }

        let dominant = detector.dominant_pattern();
        assert!(matches!(
            dominant,
            Some(AccessPattern::Strided {
                start: 0,
                stride: 2
            })
        ));
    }

    #[test]
    fn test_predictive_prefetcher() {
        // Create test dataset
        let features = Tensor::<f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[3, 2])
            .expect("test: tensor creation should succeed");
        let labels = Tensor::<f32>::from_vec(vec![0.0, 1.0, 2.0], &[3])
            .expect("test: tensor creation should succeed");
        let dataset = Arc::new(TensorDataset::new(features, labels));

        let config = PrefetchConfig {
            max_prefetch_count: 2,
            max_cache_size: 10,
            pattern_history_size: 10,
            cache_ttl: Duration::from_secs(60),
            worker_sleep_duration: Duration::from_millis(1),
            bandwidth_optimization: true,
        };

        let prefetcher = PredictivePrefetcher::with_config(dataset, config);

        // Access in sequential pattern
        let _ = prefetcher.get(0).expect("index should be in bounds");
        let _ = prefetcher.get(1).expect("index should be in bounds");
        let _ = prefetcher.get(2).expect("index should be in bounds");

        // Give prefetcher time to work
        thread::sleep(Duration::from_millis(50));

        let stats = prefetcher.stats();
        assert!(stats.total_accesses >= 3);
    }

    #[test]
    fn test_predictive_prefetch_dataset() {
        let features = Tensor::<f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0], &[2, 2])
            .expect("test: tensor creation should succeed");
        let labels = Tensor::<f32>::from_vec(vec![0.0, 1.0], &[2])
            .expect("test: tensor creation should succeed");
        let base_dataset = TensorDataset::new(features, labels);

        let dataset = PredictivePrefetchDataset::new(base_dataset);

        assert_eq!(dataset.len(), 2);

        let (feat, label) = dataset.get(0).expect("index should be in bounds");
        assert_eq!(feat.shape().dims(), &[2]);
        assert_eq!(label.shape().dims(), &[] as &[usize]);

        let stats = dataset.stats();
        assert_eq!(stats.total_accesses, 1);
    }
}