numr 0.14.0

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
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
//! CPU implementation of iterative solvers.
//!
//! This module provides CPU implementations of iterative solvers
//! using the generic algorithms in `algorithm::iterative::impl_generic`.

use super::{CpuClient, CpuRuntime};
use crate::algorithm::iterative::{
    BiCgStabOptions, BiCgStabResult, CgOptions, CgResult, CgsOptions, CgsResult, GmresOptions,
    GmresResult, IterativeSolvers, JacobiOptions, JacobiResult, LgmresOptions, LgmresResult,
    MinresOptions, MinresResult, QmrOptions, QmrResult, SorOptions, SorResult,
    SparseEigComplexResult, SparseEigOptions, SparseEigResult, SparseSvdResult, SvdsOptions,
};
use crate::algorithm::iterative::{
    arnoldi_eig_impl, bicgstab_impl, cg_impl, cgs_impl, gmres_impl, jacobi_impl, lanczos_eig_impl,
    lgmres_impl, minres_impl, qmr_impl, sor_impl, svds_impl,
};
use crate::error::Result;
use crate::sparse::CsrData;
use crate::tensor::Tensor;

impl IterativeSolvers<CpuRuntime> for CpuClient {
    fn gmres(
        &self,
        a: &CsrData<CpuRuntime>,
        b: &Tensor<CpuRuntime>,
        x0: Option<&Tensor<CpuRuntime>>,
        options: GmresOptions,
    ) -> Result<GmresResult<CpuRuntime>> {
        gmres_impl(self, a, b, x0, options)
    }

    fn bicgstab(
        &self,
        a: &CsrData<CpuRuntime>,
        b: &Tensor<CpuRuntime>,
        x0: Option<&Tensor<CpuRuntime>>,
        options: BiCgStabOptions,
    ) -> Result<BiCgStabResult<CpuRuntime>> {
        bicgstab_impl(self, a, b, x0, options)
    }

    fn cg(
        &self,
        a: &CsrData<CpuRuntime>,
        b: &Tensor<CpuRuntime>,
        x0: Option<&Tensor<CpuRuntime>>,
        options: CgOptions,
    ) -> Result<CgResult<CpuRuntime>> {
        cg_impl(self, a, b, x0, options)
    }

    fn minres(
        &self,
        a: &CsrData<CpuRuntime>,
        b: &Tensor<CpuRuntime>,
        x0: Option<&Tensor<CpuRuntime>>,
        options: MinresOptions,
    ) -> Result<MinresResult<CpuRuntime>> {
        minres_impl(self, a, b, x0, options)
    }

    fn cgs(
        &self,
        a: &CsrData<CpuRuntime>,
        b: &Tensor<CpuRuntime>,
        x0: Option<&Tensor<CpuRuntime>>,
        options: CgsOptions,
    ) -> Result<CgsResult<CpuRuntime>> {
        cgs_impl(self, a, b, x0, options)
    }

    fn lgmres(
        &self,
        a: &CsrData<CpuRuntime>,
        b: &Tensor<CpuRuntime>,
        x0: Option<&Tensor<CpuRuntime>>,
        options: LgmresOptions,
    ) -> Result<LgmresResult<CpuRuntime>> {
        lgmres_impl(self, a, b, x0, options)
    }

    fn qmr(
        &self,
        a: &CsrData<CpuRuntime>,
        b: &Tensor<CpuRuntime>,
        x0: Option<&Tensor<CpuRuntime>>,
        options: QmrOptions,
    ) -> Result<QmrResult<CpuRuntime>> {
        qmr_impl(self, a, b, x0, options)
    }

    fn jacobi(
        &self,
        a: &CsrData<CpuRuntime>,
        b: &Tensor<CpuRuntime>,
        x0: Option<&Tensor<CpuRuntime>>,
        options: JacobiOptions,
    ) -> Result<JacobiResult<CpuRuntime>> {
        jacobi_impl(self, a, b, x0, options)
    }

    fn sor(
        &self,
        a: &CsrData<CpuRuntime>,
        b: &Tensor<CpuRuntime>,
        x0: Option<&Tensor<CpuRuntime>>,
        options: SorOptions,
    ) -> Result<SorResult<CpuRuntime>> {
        sor_impl(self, a, b, x0, options)
    }

    fn sparse_eig_symmetric(
        &self,
        a: &CsrData<CpuRuntime>,
        k: usize,
        options: SparseEigOptions,
    ) -> Result<SparseEigResult<CpuRuntime>> {
        lanczos_eig_impl(self, a, k, options)
    }

    fn sparse_eig(
        &self,
        a: &CsrData<CpuRuntime>,
        k: usize,
        options: SparseEigOptions,
    ) -> Result<SparseEigComplexResult<CpuRuntime>> {
        arnoldi_eig_impl(self, a, k, options)
    }

    fn svds(
        &self,
        a: &CsrData<CpuRuntime>,
        k: usize,
        options: SvdsOptions,
    ) -> Result<SparseSvdResult<CpuRuntime>> {
        svds_impl(self, a, k, options)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::algorithm::iterative::PreconditionerType;
    use crate::runtime::Runtime;

    fn get_client() -> CpuClient {
        let device = CpuRuntime::default_device();
        CpuRuntime::default_client(&device)
    }

    /// Create 1D Laplacian (tridiagonal) matrix:
    /// [ 2, -1,  0,  0, ...]
    /// [-1,  2, -1,  0, ...]
    /// [ 0, -1,  2, -1, ...]
    /// ...
    fn create_1d_laplacian(
        n: usize,
        device: &<CpuRuntime as Runtime>::Device,
    ) -> CsrData<CpuRuntime> {
        let mut row_ptrs = Vec::with_capacity(n + 1);
        let mut col_indices = Vec::new();
        let mut values = Vec::new();

        row_ptrs.push(0i64);
        for i in 0..n {
            if i > 0 {
                col_indices.push((i - 1) as i64);
                values.push(-1.0f64);
            }
            col_indices.push(i as i64);
            values.push(2.0f64);
            if i < n - 1 {
                col_indices.push((i + 1) as i64);
                values.push(-1.0f64);
            }
            row_ptrs.push(col_indices.len() as i64);
        }

        let row_ptrs_tensor =
            Tensor::<CpuRuntime>::from_slice(&row_ptrs, &[row_ptrs.len()], device).unwrap();
        let col_indices_tensor =
            Tensor::<CpuRuntime>::from_slice(&col_indices, &[col_indices.len()], device).unwrap();
        let values_tensor =
            Tensor::<CpuRuntime>::from_slice(&values, &[values.len()], device).unwrap();

        CsrData::new(row_ptrs_tensor, col_indices_tensor, values_tensor, [n, n])
            .expect("CSR creation should succeed")
    }

    #[test]
    fn test_gmres_tridiagonal() {
        let client = get_client();
        let device = &client.device;

        let n = 5;
        let a = create_1d_laplacian(n, device);
        let b =
            Tensor::<CpuRuntime>::from_slice(&[1.0f64, 0.0, 0.0, 0.0, 1.0], &[n], device).unwrap();

        let options = GmresOptions {
            max_iter: 100,
            restart: 10,
            rtol: 1e-10,
            atol: 1e-14,
            preconditioner: PreconditionerType::None,
            ..Default::default()
        };

        let result = client
            .gmres(&a, &b, None, options)
            .expect("GMRES should succeed");

        assert!(result.converged, "GMRES should converge");
        assert!(
            result.iterations <= 10,
            "GMRES should converge quickly on tridiagonal"
        );
        assert!(
            result.residual_norm < 1e-8,
            "Residual should be small: {}",
            result.residual_norm
        );

        let ax = a.spmv(&result.solution).expect("spmv should work");
        use crate::ops::BinaryOps;
        let residual = client.sub(&b, &ax).expect("sub should work");
        let res_data: Vec<f64> = residual.to_vec();
        let res_norm: f64 = res_data.iter().map(|x| x * x).sum::<f64>().sqrt();
        assert!(res_norm < 1e-8, "Verification residual: {}", res_norm);
    }

    #[test]
    fn test_gmres_with_ilu0() {
        let client = get_client();
        let device = &client.device;

        let n = 20;
        let a = create_1d_laplacian(n, device);

        let b_data: Vec<f64> = (0..n).map(|i| (i as f64).sin()).collect();
        let b = Tensor::<CpuRuntime>::from_slice(&b_data, &[n], device).unwrap();

        let options_no_precond = GmresOptions {
            max_iter: 100,
            restart: 30,
            rtol: 1e-10,
            atol: 1e-14,
            preconditioner: PreconditionerType::None,
            ..Default::default()
        };

        let options_ilu = GmresOptions {
            max_iter: 100,
            restart: 10,
            rtol: 1e-10,
            atol: 1e-14,
            preconditioner: PreconditionerType::Ilu0,
            ..Default::default()
        };

        let result_no_precond = client
            .gmres(&a, &b, None, options_no_precond)
            .expect("GMRES should succeed");
        let result_ilu = client
            .gmres(&a, &b, None, options_ilu)
            .expect("GMRES with ILU should succeed");

        assert!(result_no_precond.converged, "GMRES should converge");
        assert!(result_ilu.converged, "GMRES+ILU should converge");

        assert!(
            result_ilu.iterations <= result_no_precond.iterations,
            "ILU should help convergence: {} vs {}",
            result_ilu.iterations,
            result_no_precond.iterations
        );
    }

    #[test]
    fn test_gmres_identity_matrix() {
        let client = get_client();
        let device = &client.device;

        let n = 5;
        let row_ptrs =
            Tensor::<CpuRuntime>::from_slice(&[0i64, 1, 2, 3, 4, 5], &[n + 1], device).unwrap();
        let col_indices =
            Tensor::<CpuRuntime>::from_slice(&[0i64, 1, 2, 3, 4], &[n], device).unwrap();
        let values = Tensor::<CpuRuntime>::from_slice(&[1.0f64; 5], &[n], device).unwrap();
        let a = CsrData::new(row_ptrs, col_indices, values, [n, n])
            .expect("CSR creation should succeed");

        let b =
            Tensor::<CpuRuntime>::from_slice(&[1.0f64, 2.0, 3.0, 4.0, 5.0], &[n], device).unwrap();

        let options = GmresOptions::default();
        let result = client
            .gmres(&a, &b, None, options)
            .expect("GMRES should succeed");

        assert!(result.converged);
        assert_eq!(
            result.iterations, 1,
            "Identity should converge in 1 iteration"
        );

        let x_data: Vec<f64> = result.solution.to_vec();
        let b_data: Vec<f64> = b.to_vec();
        for i in 0..n {
            assert!(
                (x_data[i] - b_data[i]).abs() < 1e-10,
                "x[{}] = {} != b[{}] = {}",
                i,
                x_data[i],
                i,
                b_data[i]
            );
        }
    }

    #[test]
    fn test_bicgstab_tridiagonal() {
        let client = get_client();
        let device = &client.device;

        let n = 5;
        let a = create_1d_laplacian(n, device);
        let b =
            Tensor::<CpuRuntime>::from_slice(&[1.0f64, 0.0, 0.0, 0.0, 1.0], &[n], device).unwrap();

        let options = crate::algorithm::iterative::BiCgStabOptions {
            max_iter: 100,
            rtol: 1e-10,
            atol: 1e-14,
            preconditioner: PreconditionerType::None,
        };

        let result = client
            .bicgstab(&a, &b, None, options)
            .expect("BiCGSTAB should succeed");

        assert!(result.converged, "BiCGSTAB should converge");
        assert!(
            result.residual_norm < 1e-8,
            "Residual: {}",
            result.residual_norm
        );

        let ax = a.spmv(&result.solution).expect("spmv should work");
        use crate::ops::BinaryOps;
        let residual = client.sub(&b, &ax).expect("sub should work");
        let res_data: Vec<f64> = residual.to_vec();
        let res_norm: f64 = res_data.iter().map(|x| x * x).sum::<f64>().sqrt();
        assert!(res_norm < 1e-8, "Verification residual: {}", res_norm);
    }

    #[test]
    fn test_gmres_zero_rhs() {
        let client = get_client();
        let device = &client.device;

        let n = 5;
        let a = create_1d_laplacian(n, device);
        let b = Tensor::<CpuRuntime>::zeros(&[n], crate::dtype::DType::F64, device).unwrap();

        let options = GmresOptions::default();
        let result = client
            .gmres(&a, &b, None, options)
            .expect("GMRES should succeed");

        assert!(result.converged);
        assert_eq!(result.iterations, 0);

        let x_data: Vec<f64> = result.solution.to_vec();
        for (i, &xi) in x_data.iter().enumerate() {
            assert!(xi.abs() < 1e-14, "x[{}] = {} should be zero", i, xi);
        }
    }

    #[test]
    fn test_gmres_with_initial_guess() {
        let client = get_client();
        let device = &client.device;

        let n = 5;
        let a = create_1d_laplacian(n, device);
        let b =
            Tensor::<CpuRuntime>::from_slice(&[1.0f64, 0.0, 0.0, 0.0, 1.0], &[n], device).unwrap();

        let result1 = client
            .gmres(&a, &b, None, GmresOptions::default())
            .expect("GMRES should succeed");
        assert!(result1.converged);

        let result2 = client
            .gmres(&a, &b, Some(&result1.solution), GmresOptions::default())
            .expect("GMRES should succeed");
        assert!(result2.converged);
        assert!(
            result2.iterations <= 1,
            "With good initial guess, should converge in 0-1 iterations"
        );
    }

    #[test]
    fn test_iterative_solvers_mixed_dtype_return_error() {
        use crate::dtype::DType;
        use crate::error::Error;

        let client = get_client();
        let device = &client.device;

        let n = 5;
        // The Laplacian holds f64 values.
        let a = create_1d_laplacian(n, device);
        let b_f32 =
            Tensor::<CpuRuntime>::from_slice(&[1.0f32, 0.0, 0.0, 0.0, 1.0], &[n], device).unwrap();
        let b_f64 =
            Tensor::<CpuRuntime>::from_slice(&[1.0f64, 0.0, 0.0, 0.0, 1.0], &[n], device).unwrap();

        let expect_mismatch = |err: Option<Error>| match err {
            Some(Error::DTypeMismatch { lhs, rhs }) => {
                assert_eq!((lhs, rhs), (DType::F64, DType::F32));
            }
            other => panic!("expected DTypeMismatch, got {other:?}"),
        };

        expect_mismatch(client.cg(&a, &b_f32, None, CgOptions::default()).err());
        expect_mismatch(
            client
                .gmres(&a, &b_f64, Some(&b_f32), GmresOptions::default())
                .err(),
        );
        expect_mismatch(client.sor(&a, &b_f32, None, SorOptions::default()).err());
    }
}