oxicuda-solver 0.1.1

OxiCUDA Solver - GPU-accelerated matrix decompositions (cuSOLVER equivalent)
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
//! Conjugate Gradient (CG) iterative solver.
//!
//! Solves the linear system `A * x = b` where A is symmetric positive definite.
//! The solver is matrix-free: it only requires a closure that computes the
//! matrix-vector product `y = A * x`.
//!
//! # Algorithm
//!
//! The standard Conjugate Gradient algorithm (Hestenes & Stiefel, 1952):
//! 1. r = b - A*x; p = r; rsold = r^T * r
//! 2. For each iteration:
//!    a. Ap = A * p
//!    b. alpha = rsold / (p^T * Ap)
//!    c. x += alpha * p
//!    d. r -= alpha * Ap
//!    e. rsnew = r^T * r
//!    f. If sqrt(rsnew) < tol * ||b||: converged
//!    g. p = r + (rsnew / rsold) * p
//!    h. rsold = rsnew
//!
//! The solver operates on host-side vectors. For GPU-accelerated sparse
//! matrix-vector products, the `spmv` closure should internally manage
//! device memory transfers.

#![allow(dead_code)]

use oxicuda_blas::GpuFloat;

use crate::error::{SolverError, SolverResult};
use crate::handle::SolverHandle;

// ---------------------------------------------------------------------------
// GpuFloat <-> f64 conversion helpers
// ---------------------------------------------------------------------------

/// Converts a `GpuFloat` value to `f64` via bit reinterpretation.
fn to_f64<T: GpuFloat>(val: T) -> f64 {
    if T::SIZE == 4 {
        f32::from_bits(val.to_bits_u64() as u32) as f64
    } else {
        f64::from_bits(val.to_bits_u64())
    }
}

/// Converts an `f64` value to `T: GpuFloat` via bit reinterpretation.
fn from_f64<T: GpuFloat>(val: f64) -> T {
    if T::SIZE == 4 {
        T::from_bits_u64(u64::from((val as f32).to_bits()))
    } else {
        T::from_bits_u64(val.to_bits())
    }
}

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Configuration for the Conjugate Gradient solver.
#[derive(Debug, Clone)]
pub struct CgConfig {
    /// Maximum number of iterations.
    pub max_iter: u32,
    /// Convergence tolerance (relative to ||b||).
    pub tol: f64,
}

impl Default for CgConfig {
    fn default() -> Self {
        Self {
            max_iter: 1000,
            tol: 1e-6,
        }
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Solves `A * x = b` using the Conjugate Gradient method.
///
/// The matrix A is not passed directly. Instead, the caller provides a closure
/// `spmv` that computes `y = A * x` given `x` and `y` buffers. This enables
/// use with any sparse format, preconditioner, or matrix-free operator.
///
/// On entry, `x` should contain an initial guess (e.g., zeros). On exit, `x`
/// contains the approximate solution.
///
/// # Arguments
///
/// * `_handle` — solver handle (reserved for future GPU-accelerated variants).
/// * `spmv` — closure computing `y = A * x`: `spmv(x, y)`.
/// * `b` — right-hand side vector (length n).
/// * `x` — initial guess / solution vector (length n), modified in-place.
/// * `n` — system dimension.
/// * `config` — solver configuration (tolerance, max iterations).
///
/// # Returns
///
/// The number of iterations performed.
///
/// # Errors
///
/// Returns [`SolverError::ConvergenceFailure`] if the solver does not converge
/// within `max_iter` iterations.
/// Returns [`SolverError::DimensionMismatch`] if vector lengths are invalid.
pub fn cg_solve<T, F>(
    _handle: &SolverHandle,
    spmv: F,
    b: &[T],
    x: &mut [T],
    n: u32,
    config: &CgConfig,
) -> SolverResult<u32>
where
    T: GpuFloat,
    F: Fn(&[T], &mut [T]) -> SolverResult<()>,
{
    let n_usize = n as usize;

    // Validate dimensions.
    if b.len() < n_usize {
        return Err(SolverError::DimensionMismatch(format!(
            "cg_solve: b length ({}) < n ({n})",
            b.len()
        )));
    }
    if x.len() < n_usize {
        return Err(SolverError::DimensionMismatch(format!(
            "cg_solve: x length ({}) < n ({n})",
            x.len()
        )));
    }
    if n == 0 {
        return Ok(0);
    }

    // Compute ||b|| for relative convergence check.
    let b_norm = vec_norm(b, n_usize);
    let abs_tol = if b_norm > 0.0 {
        config.tol * b_norm
    } else {
        // b = 0 => x = 0 is the exact solution.
        for xi in x.iter_mut().take(n_usize) {
            *xi = T::gpu_zero();
        }
        return Ok(0);
    };

    // r = b - A*x
    let mut r = vec![T::gpu_zero(); n_usize];
    let mut ap = vec![T::gpu_zero(); n_usize];
    spmv(x, &mut ap)?;
    for i in 0..n_usize {
        r[i] = sub_t(b[i], ap[i]);
    }

    // p = r.clone()
    let mut p = r.clone();

    // rsold = r^T * r
    let mut rsold = dot_product(&r, &r, n_usize);

    if rsold.sqrt() < abs_tol {
        return Ok(0);
    }

    for iter in 0..config.max_iter {
        // Ap = A * p
        spmv(&p, &mut ap)?;

        // alpha = rsold / (p^T * Ap)
        let pap = dot_product(&p, &ap, n_usize);
        if pap.abs() < 1e-300 {
            return Err(SolverError::InternalError(
                "cg_solve: p^T * A * p is near zero (A may not be SPD)".into(),
            ));
        }
        let alpha = rsold / pap;
        let alpha_t = from_f64(alpha);

        // x += alpha * p
        for i in 0..n_usize {
            x[i] = add_t(x[i], mul_t(alpha_t, p[i]));
        }

        // r -= alpha * Ap
        for i in 0..n_usize {
            r[i] = sub_t(r[i], mul_t(alpha_t, ap[i]));
        }

        // rsnew = r^T * r
        let rsnew = dot_product(&r, &r, n_usize);

        // Check convergence.
        if rsnew.sqrt() < abs_tol {
            return Ok(iter + 1);
        }

        // beta = rsnew / rsold
        let beta = rsnew / rsold;
        let beta_t = from_f64(beta);

        // p = r + beta * p
        for i in 0..n_usize {
            p[i] = add_t(r[i], mul_t(beta_t, p[i]));
        }

        rsold = rsnew;
    }

    Err(SolverError::ConvergenceFailure {
        iterations: config.max_iter,
        residual: rsold.sqrt(),
    })
}

// ---------------------------------------------------------------------------
// Vector arithmetic helpers (host-side, generic over GpuFloat)
// ---------------------------------------------------------------------------

/// Computes the dot product of two vectors as f64.
fn dot_product<T: GpuFloat>(a: &[T], b: &[T], n: usize) -> f64 {
    let mut sum = 0.0_f64;
    for i in 0..n {
        sum += to_f64(a[i]) * to_f64(b[i]);
    }
    sum
}

/// Computes the 2-norm of a vector as f64.
fn vec_norm<T: GpuFloat>(v: &[T], n: usize) -> f64 {
    dot_product(v, v, n).sqrt()
}

/// Adds two GpuFloat values.
fn add_t<T: GpuFloat>(a: T, b: T) -> T {
    from_f64(to_f64(a) + to_f64(b))
}

/// Subtracts two GpuFloat values.
fn sub_t<T: GpuFloat>(a: T, b: T) -> T {
    from_f64(to_f64(a) - to_f64(b))
}

/// Multiplies two GpuFloat values.
fn mul_t<T: GpuFloat>(a: T, b: T) -> T {
    from_f64(to_f64(a) * to_f64(b))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn cg_config_default() {
        let cfg = CgConfig::default();
        assert_eq!(cfg.max_iter, 1000);
        assert!((cfg.tol - 1e-6).abs() < 1e-15);
    }

    #[test]
    fn dot_product_basic() {
        let a = [1.0_f64, 2.0, 3.0];
        let b = [4.0_f64, 5.0, 6.0];
        let result = dot_product(&a, &b, 3);
        assert!((result - 32.0).abs() < 1e-10);
    }

    #[test]
    fn vec_norm_basic() {
        let v = [3.0_f64, 4.0];
        let result = vec_norm(&v, 2);
        assert!((result - 5.0).abs() < 1e-10);
    }

    #[test]
    fn add_sub_mul() {
        let a = 3.0_f64;
        let b = 4.0_f64;
        assert!((to_f64(add_t(a, b)) - 7.0).abs() < 1e-15);
        assert!((to_f64(sub_t(a, b)) - (-1.0)).abs() < 1e-15);
        assert!((to_f64(mul_t(a, b)) - 12.0).abs() < 1e-15);
    }

    #[test]
    fn cg_config_custom() {
        let cfg = CgConfig {
            max_iter: 500,
            tol: 1e-10,
        };
        assert_eq!(cfg.max_iter, 500);
        assert!((cfg.tol - 1e-10).abs() < 1e-20);
    }

    // -----------------------------------------------------------------------
    // Quality gate: CG convergence on a 2×2 SPD system (CPU simulation)
    // -----------------------------------------------------------------------

    /// CPU-only conjugate gradient implementation for testing purposes.
    ///
    /// Solves A * x = b without requiring a `SolverHandle` (GPU context).
    /// This isolates the algorithmic correctness from the GPU infrastructure.
    fn cpu_cg_f64(
        spmv: impl Fn(&[f64], &mut [f64]),
        b: &[f64],
        x: &mut [f64],
        n: usize,
        max_iter: usize,
        tol: f64,
    ) -> usize {
        let b_norm = b.iter().map(|v| v * v).sum::<f64>().sqrt();
        let abs_tol = tol * b_norm;

        let mut ap = vec![0.0_f64; n];
        spmv(x, &mut ap);
        let mut r: Vec<f64> = (0..n).map(|i| b[i] - ap[i]).collect();
        let mut p = r.clone();
        let mut rsold: f64 = r.iter().map(|v| v * v).sum();

        for iter in 0..max_iter {
            spmv(&p, &mut ap);
            let pap: f64 = p.iter().zip(&ap).map(|(pi, api)| pi * api).sum();
            if pap.abs() < 1e-300 {
                return iter;
            }
            let alpha = rsold / pap;
            for i in 0..n {
                x[i] += alpha * p[i];
                r[i] -= alpha * ap[i];
            }
            let rsnew: f64 = r.iter().map(|v| v * v).sum();
            if rsnew.sqrt() < abs_tol {
                return iter + 1;
            }
            let beta = rsnew / rsold;
            for i in 0..n {
                p[i] = r[i] + beta * p[i];
            }
            rsold = rsnew;
        }
        max_iter
    }

    /// Quality gate: CG convergence on A = [[4, 1], [1, 3]], b = [1, 2].
    ///
    /// Exact solution: x = A^{-1} b
    ///   det(A) = 4*3 - 1*1 = 11
    ///   A^{-1} = (1/11) * [[3, -1], [-1, 4]]
    ///   x = (1/11) * [3*1 + (-1)*2, (-1)*1 + 4*2] = [1/11, 7/11]
    ///
    /// CG must converge in ≤ 5 iterations (at most n=2 for exact arithmetic).
    #[test]
    fn test_cg_convergence_spd_2x2() {
        // A = [[4, 1], [1, 3]] — symmetric positive definite (eigenvalues 3.27, 3.73)
        let a = [[4.0_f64, 1.0], [1.0, 3.0]];
        let spmv = |x: &[f64], y: &mut [f64]| {
            y[0] = a[0][0] * x[0] + a[0][1] * x[1];
            y[1] = a[1][0] * x[0] + a[1][1] * x[1];
        };

        let b = [1.0_f64, 2.0];
        let mut x = [0.0_f64, 0.0]; // zero initial guess

        let iters = cpu_cg_f64(spmv, &b, &mut x, 2, 100, 1e-12);

        // CG on an n×n SPD system converges in at most n steps in exact arithmetic.
        assert!(
            iters <= 5,
            "CG on 2×2 SPD system must converge in ≤ 5 iterations, took {iters}"
        );

        // Verify solution matches x = [1/11, 7/11]
        let x_exact = [1.0_f64 / 11.0, 7.0 / 11.0];
        assert!(
            (x[0] - x_exact[0]).abs() < 1e-10,
            "CG 2×2: x[0]={} expected {}",
            x[0],
            x_exact[0],
        );
        assert!(
            (x[1] - x_exact[1]).abs() < 1e-10,
            "CG 2×2: x[1]={} expected {}",
            x[1],
            x_exact[1],
        );
    }

    /// Quality gate: CG convergence on a 5×5 diagonal SPD system.
    ///
    /// For D = diag(1, 2, 3, 4, 5) and b = [1, 2, 3, 4, 5],
    /// the exact solution is x = [1, 1, 1, 1, 1].
    /// CG must converge in ≤ 10 iterations.
    #[test]
    fn test_cg_convergence_diagonal_5x5() {
        let diag = [1.0_f64, 2.0, 3.0, 4.0, 5.0];
        let spmv = |x: &[f64], y: &mut [f64]| {
            for i in 0..5 {
                y[i] = diag[i] * x[i];
            }
        };
        let b = [1.0_f64, 2.0, 3.0, 4.0, 5.0];
        let mut x = [0.0_f64; 5];

        let iters = cpu_cg_f64(spmv, &b, &mut x, 5, 100, 1e-12);

        assert!(
            iters <= 10,
            "CG on 5×5 diagonal SPD must converge in ≤ 10 iterations, took {iters}"
        );

        for (i, &xi) in x.iter().enumerate() {
            assert!(
                (xi - 1.0).abs() < 1e-10,
                "CG diagonal 5×5: x[{i}]={xi} expected 1.0",
            );
        }
    }
}