use std::collections::HashMap;
use crate::compressive::CompressiveSpectralDecoder;
use crate::holotensor::HoloFragment;
use crate::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoadPriority {
EssentialsOnly,
QuickStart,
Balanced,
Full,
}
impl LoadPriority {
#[must_use]
pub fn detail_fraction(&self) -> f32 {
match self {
LoadPriority::EssentialsOnly => 0.0,
LoadPriority::QuickStart => 0.15,
LoadPriority::Balanced => 0.5,
LoadPriority::Full => 1.0,
}
}
}
#[derive(Debug, Clone)]
pub struct LoadStatus {
pub essentials_loaded: bool,
pub details_loaded: u16,
pub total_details: u16,
pub estimated_quality: f32,
pub complete: bool,
}
pub struct StreamingTensorLoader {
name: String,
width: usize,
height: usize,
decoder: CompressiveSpectralDecoder,
pending_fragments: Vec<HoloFragment>,
essentials_loaded: bool,
details_loaded: u16,
total_details: u16,
cached_reconstruction: Option<Vec<f32>>,
mean_value: f32,
}
impl StreamingTensorLoader {
pub fn new(name: impl Into<String>, width: usize, height: usize) -> Self {
Self {
name: name.into(),
width,
height,
decoder: CompressiveSpectralDecoder::new(),
pending_fragments: Vec::new(),
essentials_loaded: false,
details_loaded: 0,
total_details: 0,
cached_reconstruction: None,
mean_value: 0.0,
}
}
pub fn with_mean(mut self, mean: f32) -> Self {
self.mean_value = mean;
self
}
pub fn add_fragment(&mut self, fragment: HoloFragment) -> Result<()> {
self.cached_reconstruction = None;
if fragment.index == 0 {
self.decoder.add_essentials(&fragment)?;
self.essentials_loaded = true;
self.total_details = self.decoder.quality().ceil() as u16; } else {
self.decoder.add_detail(&fragment)?;
self.details_loaded += 1;
}
Ok(())
}
pub fn queue_fragment(&mut self, fragment: HoloFragment) {
self.pending_fragments.push(fragment);
}
pub fn load_next(&mut self) -> Result<bool> {
if let Some(fragment) = self.pending_fragments.pop() {
self.add_fragment(fragment)?;
Ok(true)
} else {
Ok(false)
}
}
pub fn load_all_pending(&mut self) -> Result<usize> {
let count = self.pending_fragments.len();
while !self.pending_fragments.is_empty() {
self.load_next()?;
}
Ok(count)
}
#[must_use]
pub fn can_reconstruct(&self) -> bool {
self.essentials_loaded && self.decoder.can_reconstruct()
}
#[must_use]
pub fn status(&self) -> LoadStatus {
LoadStatus {
essentials_loaded: self.essentials_loaded,
details_loaded: self.details_loaded,
total_details: self.total_details,
estimated_quality: self.decoder.quality(),
complete: self.pending_fragments.is_empty() && self.essentials_loaded,
}
}
pub fn reconstruct(&mut self) -> Result<Vec<f32>> {
if !self.can_reconstruct() {
return Err(Error::corrupted(
"essentials not loaded, cannot reconstruct",
));
}
if let Some(ref cached) = self.cached_reconstruction {
return Ok(cached.clone());
}
let mut values = self.decoder.reconstruct()?;
if self.mean_value.abs() > 1e-10 {
for v in &mut values {
*v += self.mean_value;
}
}
self.cached_reconstruction = Some(values.clone());
Ok(values)
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn dimensions(&self) -> (usize, usize) {
(self.width, self.height)
}
}
pub struct StreamingModelLoader {
loaders: HashMap<String, StreamingTensorLoader>,
priority: LoadPriority,
parallel: bool,
}
impl StreamingModelLoader {
pub fn new(priority: LoadPriority) -> Self {
Self {
loaders: HashMap::new(),
priority,
parallel: true,
}
}
pub fn with_parallel(mut self, parallel: bool) -> Self {
self.parallel = parallel;
self
}
pub fn add_tensor(&mut self, loader: StreamingTensorLoader) {
self.loaders.insert(loader.name.clone(), loader);
}
pub fn get(&self, name: &str) -> Option<&StreamingTensorLoader> {
self.loaders.get(name)
}
pub fn get_mut(&mut self, name: &str) -> Option<&mut StreamingTensorLoader> {
self.loaders.get_mut(name)
}
#[must_use]
pub fn tensor_count(&self) -> usize {
self.loaders.len()
}
#[must_use]
pub fn ready_count(&self) -> usize {
self.loaders
.values()
.filter(|l| l.can_reconstruct())
.count()
}
#[must_use]
pub fn progress(&self) -> f32 {
if self.loaders.is_empty() {
return 1.0;
}
let total_quality: f32 = self.loaders.values().map(|l| l.decoder.quality()).sum();
total_quality / self.loaders.len() as f32
}
pub fn load_next_round(&mut self) -> Result<usize> {
let mut loaded = 0;
for loader in self.loaders.values_mut() {
if loader.load_next()? {
loaded += 1;
}
}
Ok(loaded)
}
pub fn tensor_names(&self) -> impl Iterator<Item = &String> {
self.loaders.keys()
}
#[must_use]
pub fn priority(&self) -> LoadPriority {
self.priority
}
#[must_use]
pub fn is_parallel(&self) -> bool {
self.parallel
}
}
pub type ProgressCallback = Box<dyn Fn(&str, f32) + Send + Sync>;
#[derive(Debug, Clone)]
pub struct ProgressiveLoadConfig {
pub initial_priority: LoadPriority,
pub target_priority: LoadPriority,
pub batch_size: usize,
pub prioritize_attention: bool,
pub prioritize_embeddings: bool,
}
impl Default for ProgressiveLoadConfig {
fn default() -> Self {
Self {
initial_priority: LoadPriority::EssentialsOnly,
target_priority: LoadPriority::Full,
batch_size: 10,
prioritize_attention: true,
prioritize_embeddings: true,
}
}
}
impl ProgressiveLoadConfig {
#[must_use]
pub fn fast_start() -> Self {
Self {
initial_priority: LoadPriority::EssentialsOnly,
target_priority: LoadPriority::Balanced,
batch_size: 20,
..Default::default()
}
}
#[must_use]
pub fn balanced() -> Self {
Self {
initial_priority: LoadPriority::QuickStart,
target_priority: LoadPriority::Full,
batch_size: 10,
..Default::default()
}
}
#[must_use]
pub fn high_quality() -> Self {
Self {
initial_priority: LoadPriority::Balanced,
target_priority: LoadPriority::Full,
batch_size: 5,
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::compressive::CompressiveSpectralEncoder;
#[test]
fn test_load_priority_fraction() {
assert!((LoadPriority::EssentialsOnly.detail_fraction() - 0.0).abs() < 0.01);
assert!((LoadPriority::QuickStart.detail_fraction() - 0.15).abs() < 0.01);
assert!((LoadPriority::Balanced.detail_fraction() - 0.5).abs() < 0.01);
assert!((LoadPriority::Full.detail_fraction() - 1.0).abs() < 0.01);
}
#[test]
fn test_streaming_tensor_loader_creation() {
let loader = StreamingTensorLoader::new("test.weight", 128, 128);
assert_eq!(loader.name(), "test.weight");
assert_eq!(loader.dimensions(), (128, 128));
assert!(!loader.can_reconstruct());
}
#[test]
fn test_streaming_tensor_loader_with_mean() {
let loader = StreamingTensorLoader::new("test", 64, 64).with_mean(0.5);
assert!((loader.mean_value - 0.5).abs() < 0.01);
}
#[test]
fn test_load_status() {
let loader = StreamingTensorLoader::new("test", 64, 64);
let status = loader.status();
assert!(!status.essentials_loaded);
assert_eq!(status.details_loaded, 0);
assert!(!status.complete);
}
#[test]
fn test_streaming_model_loader() {
let mut model = StreamingModelLoader::new(LoadPriority::Balanced);
model.add_tensor(StreamingTensorLoader::new("layer.0.weight", 64, 64));
model.add_tensor(StreamingTensorLoader::new("layer.1.weight", 64, 64));
assert_eq!(model.tensor_count(), 2);
assert_eq!(model.ready_count(), 0);
}
#[test]
fn test_progressive_load_config() {
let config = ProgressiveLoadConfig::default();
assert_eq!(config.initial_priority, LoadPriority::EssentialsOnly);
assert_eq!(config.target_priority, LoadPriority::Full);
let fast = ProgressiveLoadConfig::fast_start();
assert_eq!(fast.batch_size, 20);
let balanced = ProgressiveLoadConfig::balanced();
assert_eq!(balanced.initial_priority, LoadPriority::QuickStart);
}
#[test]
fn test_streaming_loader_integration() {
let encoder = CompressiveSpectralEncoder::new(4, 0.70);
let data: Vec<f32> = (0..4096).map(|i| (i as f32 * 0.01).sin()).collect();
let mean: f32 = data.iter().sum::<f32>() / data.len() as f32;
let fragments = encoder.encode_2d(&data, 64, 64).unwrap();
let mut loader = StreamingTensorLoader::new("test", 64, 64).with_mean(mean);
for frag in &fragments {
if frag.index == 0 {
loader.add_fragment(frag.clone()).unwrap();
break;
}
}
assert!(loader.can_reconstruct());
let status = loader.status();
assert!(status.essentials_loaded);
for frag in &fragments {
if frag.index > 0 {
loader.queue_fragment(frag.clone());
}
}
let initial_quality = loader.decoder.quality();
loader.load_all_pending().unwrap();
let final_quality = loader.decoder.quality();
assert!(final_quality >= initial_quality);
}
}