krylovscope 0.1.0

GPU-resident Krylov spectral endpoint estimation for large symmetric operators
Documentation
//! Reusable prepared estimator API.

use crate::{
    cuda::{Pass64, ResidentF64Operator, RobustRunner, RobustStats},
    RitzBounds,
};
use cubecl::prelude::Runtime;
use std::time::Instant;

pub const MAX_STEPS: usize = 32;

#[derive(Clone, Copy, Debug)]
pub struct EstimatorConfig {
    pub steps: usize,
}
impl Default for EstimatorConfig {
    fn default() -> Self {
        Self { steps: 32 }
    }
}
impl EstimatorConfig {
    pub fn validate(self) -> Result<Self, String> {
        if self.steps == 0 || self.steps > MAX_STEPS {
            return Err(format!(
                "krylovscope: steps must be in 1..={MAX_STEPS}, got {}",
                self.steps
            ));
        }
        Ok(self)
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Estimate {
    pub bounds: Option<RitzBounds>,
    pub steps: usize,
    /// `None` after all requested steps, otherwise one of
    /// `cuda::EVENT_BREAKDOWN`, `cuda::EVENT_NONFINITE_ALPHA`, or
    /// `cuda::EVENT_NONFINITE_BETA`.
    pub event: Option<i32>,
    pub stats: RobustStats,
    pub elapsed_ms: f64,
}
impl Estimate {
    pub fn require_bounds(self) -> Result<RitzBounds, String> {
        self.bounds.ok_or_else(|| {
            format!(
                "krylovscope: no Ritz bounds (steps={}, event={:?})",
                self.steps, self.event
            )
        })
    }
    pub fn resident_sync_ok(&self) -> bool {
        self.stats.scalar_readbacks == 0 && self.stats.batch_readbacks == 1
    }
    pub fn condition_estimate(&self) -> Option<f64> {
        self.bounds.and_then(|b| b.condition_estimate())
    }
    pub fn completed_requested_steps(&self) -> bool {
        self.event.is_none()
    }
    pub fn converged_by_breakdown(&self) -> bool {
        self.event == Some(crate::cuda::EVENT_BREAKDOWN)
    }
}

#[derive(Debug, Clone, Copy)]
pub struct PreparationReport {
    pub elapsed_ms: f64,
    pub executed: bool,
    pub resident_sync_ok: bool,
}

#[derive(Debug, Clone)]
pub struct EnsembleEstimate {
    pub estimates: Vec<Estimate>,
    pub min_relative_spread: f64,
    pub max_relative_spread: f64,
}
impl EnsembleEstimate {
    pub fn all_valid(&self) -> bool {
        self.estimates
            .iter()
            .all(|e| e.bounds.is_some() && e.resident_sync_ok())
    }
}

pub struct SpectralEstimator<R: Runtime, O: ResidentF64Operator<R>> {
    runner: RobustRunner<R, O>,
    config: EstimatorConfig,
    prepared: bool,
    prepare_ms: Option<f64>,
    estimate_count: usize,
}

impl<R: Runtime, O: ResidentF64Operator<R>> SpectralEstimator<R, O> {
    pub fn new(device: &R::Device, operator: O, config: EstimatorConfig) -> Result<Self, String> {
        let config = config.validate()?;
        let runner = RobustRunner::try_new(device, operator, config.steps)?;
        Ok(Self {
            runner,
            config,
            prepared: false,
            prepare_ms: None,
            estimate_count: 0,
        })
    }

    pub fn new_masked(
        device: &R::Device,
        operator: O,
        config: EstimatorConfig,
        free_mask: Vec<u32>,
    ) -> Result<Self, String> {
        let config = config.validate()?;
        if free_mask.len() != operator.len() {
            return Err(format!(
                "krylovscope: free-mask length {} != operator length {}",
                free_mask.len(),
                operator.len()
            ));
        }
        if !free_mask.iter().any(|&x| x != 0) {
            return Err("krylovscope: free-mask contains no active DOF".into());
        }
        let mut runner = RobustRunner::try_new(device, operator, config.steps)?;
        runner.set_free_mask(&free_mask)?;
        Ok(Self {
            runner,
            config,
            prepared: false,
            prepare_ms: None,
            estimate_count: 0,
        })
    }

    fn run(&mut self, seed: u64) -> Result<Pass64, String> {
        self.runner.run(self.config.steps, seed)
    }

    pub fn prepare(&mut self, seed: u64) -> Result<PreparationReport, String> {
        if self.prepared {
            return Ok(PreparationReport {
                elapsed_ms: self.prepare_ms.unwrap_or(0.0),
                executed: false,
                resident_sync_ok: true,
            });
        }
        let t = Instant::now();
        let pass = self.run(seed)?;
        let elapsed_ms = t.elapsed().as_secs_f64() * 1e3;
        let ok = pass.stats.scalar_readbacks == 0 && pass.stats.batch_readbacks == 1;
        if !ok {
            return Err(format!(
                "krylovscope: prepare violated resident sync contract: scalar={} batch={}",
                pass.stats.scalar_readbacks, pass.stats.batch_readbacks
            ));
        }
        self.prepared = true;
        self.prepare_ms = Some(elapsed_ms);
        Ok(PreparationReport {
            elapsed_ms,
            executed: true,
            resident_sync_ok: true,
        })
    }

    pub fn estimate(&mut self, seed: u64) -> Result<Estimate, String> {
        let t = Instant::now();
        let pass = self.run(seed)?;
        let elapsed_ms = t.elapsed().as_secs_f64() * 1e3;
        self.estimate_count += 1;
        Ok(Estimate {
            bounds: pass.ritz,
            steps: pass.steps,
            event: pass.event,
            stats: pass.stats,
            elapsed_ms,
        })
    }
    pub fn estimate_prepared(&mut self, seed: u64) -> Result<Estimate, String> {
        if !self.prepared {
            return Err("krylovscope: estimator is not prepared; call prepare(seed) first".into());
        }
        self.estimate(seed)
    }
    pub fn estimate_ensemble_prepared(
        &mut self,
        seeds: &[u64],
    ) -> Result<EnsembleEstimate, String> {
        if seeds.is_empty() {
            return Err("krylovscope: ensemble requires at least one seed".into());
        }
        let mut estimates = Vec::with_capacity(seeds.len());
        for &s in seeds {
            estimates.push(self.estimate_prepared(s)?);
        }
        let mut mins = Vec::new();
        let mut maxs = Vec::new();
        for e in &estimates {
            if let Some(b) = e.bounds {
                mins.push(b.lambda_min);
                maxs.push(b.lambda_max);
            }
        }
        let spread = |v: &[f64]| -> f64 {
            if v.len() < 2 {
                return 0.0;
            }
            let lo = v.iter().copied().fold(f64::INFINITY, f64::min);
            let hi = v.iter().copied().fold(f64::NEG_INFINITY, f64::max);
            (hi - lo).abs() / lo.abs().max(hi.abs()).max(f64::MIN_POSITIVE)
        };
        Ok(EnsembleEstimate {
            min_relative_spread: spread(&mins),
            max_relative_spread: spread(&maxs),
            estimates,
        })
    }
    pub fn is_prepared(&self) -> bool {
        self.prepared
    }
    pub fn prepare_ms(&self) -> Option<f64> {
        self.prepare_ms
    }
    pub fn estimate_count(&self) -> usize {
        self.estimate_count
    }
    pub fn steps(&self) -> usize {
        self.config.steps
    }
    pub fn operator_name(&self) -> &'static str {
        self.runner.operator_name()
    }
}