use mlmf::{
CachedModelLoader, CacheConfig, CacheConfigBuilder, LoadOptions, MemoryPressure,
Device, DType,
};
use std::time::Duration;
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let cache_config = CacheConfigBuilder::new()
.max_models(5) .max_memory_gb(4) .memory_pressure_threshold(0.8) .ttl(Duration::from_secs(1800)) .enable_cache_warming(true) .cache_warming_interval(Duration::from_secs(300)) .build();
let cached_loader = CachedModelLoader::with_config(cache_config);
let load_options = LoadOptions::new(Device::cuda_if_available(0)?, DType::F16)
.with_progress();
println!("🚀 MLMF Advanced Caching Demo");
println!("===============================");
println!("\n📦 Basic Caching");
println!("-----------------");
let model_path = "./models/llama-7b";
println!("Loading model for first time...");
let model1 = cached_loader.load_safetensors(model_path, load_options.clone()).await?;
let stats = cached_loader.cache_stats();
println!("Cache stats after first load: hits={}, misses={}", stats.hits, stats.misses);
println!("Loading same model again...");
let model2 = cached_loader.load_safetensors(model_path, load_options.clone()).await?;
let stats = cached_loader.cache_stats();
println!("Cache stats after second load: hits={}, misses={}", stats.hits, stats.misses);
println!("Models are same instance: {}", Arc::ptr_eq(&model1, &model2));
println!("\n💾 Memory Pressure Management");
println!("------------------------------");
let model_paths = vec![
"./models/llama-7b",
"./models/llama-13b",
"./models/mistral-7b",
"./models/codellama-7b",
"./models/phi-2",
];
for (i, path) in model_paths.iter().enumerate() {
println!("Loading model {}: {}", i + 1, path);
let _model = cached_loader.load_safetensors(path, load_options.clone()).await?;
let pressure = cached_loader.memory_pressure();
println!("Memory pressure: {:?}", pressure);
match pressure {
MemoryPressure::Normal => println!("✅ Memory usage normal"),
MemoryPressure::Moderate => println!("⚠️ Moderate memory pressure"),
MemoryPressure::High => println!("🔥 High memory pressure - evicting models"),
MemoryPressure::Critical => println!("🚨 Critical memory pressure - aggressive eviction"),
}
let stats = cached_loader.cache_stats();
println!("Evictions so far: {}", stats.evictions);
}
println!("\n🔥 Cache Warming");
println!("----------------");
println!("Pre-warming cache with frequently used models...");
let warmed = cached_loader.warm_cache().await?;
println!("Warmed {} models", warmed);
let stats = cached_loader.cache_stats();
println!("Cache warming operations: {}", stats.cache_warming_operations);
println!("\n🎛️ Manual Cache Management");
println!("---------------------------");
let stats = cached_loader.cache_stats();
println!("Current cache stats:");
println!(" Hits: {}", stats.hits);
println!(" Misses: {}", stats.misses);
println!(" Hit ratio: {:.2}%", stats.hit_ratio() * 100.0);
println!(" Evictions: {}", stats.evictions);
println!(" Memory pressure events: {}", stats.memory_pressure_events);
println!(" Average load time: {}ms", stats.avg_load_time_us / 1000);
println!("\nManually evicting 2 LRU models...");
let evicted = cached_loader.evict_lru(2)?;
println!("Evicted {} models", evicted);
println!("Clearing entire cache...");
cached_loader.clear_cache();
let stats = cached_loader.cache_stats();
println!("Cache cleared - current hits: {}, misses: {}", stats.hits, stats.misses);
println!("\n🌍 Global Cached Loader");
println!("------------------------");
println!("Loading model with global cached loader...");
let _global_model = mlmf::load_cached(model_path, load_options).await?;
println!("Model loaded successfully with global cache");
println!("\n⚙️ Advanced Configuration Examples");
println!("-----------------------------------");
let production_config = CacheConfigBuilder::new()
.max_models(3) .max_memory_gb(16) .memory_pressure_threshold(0.75) .ttl(Duration::from_secs(3600)) .enable_cache_warming(true)
.cache_warming_interval(Duration::from_secs(600)) .build();
println!("Production config: max {} models, {}GB memory limit",
production_config.max_models,
production_config.max_memory_bytes / (1024 * 1024 * 1024)
);
let dev_config = CacheConfigBuilder::new()
.max_models(10) .max_memory_gb(8) .memory_pressure_threshold(0.9) .no_ttl() .enable_cache_warming(false) .build();
println!("Development config: max {} models, no TTL, warming disabled",
dev_config.max_models
);
println!("\n✅ Advanced caching demo completed successfully!");
println!(" The caching system provides intelligent memory management,");
println!(" predictive loading, and comprehensive monitoring for optimal");
println!(" performance in both development and production environments.");
Ok(())
}