diffsol-la 0.3.0

Linear algebra traits and backends (vectors, matrices, linear solvers) for diffsol.
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
use std::{cell::RefCell, mem::MaybeUninit};

use crate::context::broadcast_batch;
use crate::{
    error::LaError, linear_solver_error, Context, CudaContext, CudaMat, CudaVec, LinearOp,
    LinearSolver, Matrix, ScalarCuda,
};
use cudarc::{
    cusolver::sys::{
        cublasOperation_t, cusolverDnCreate, cusolverDnDestroy, cusolverDnDgetrf,
        cusolverDnDgetrf_bufferSize, cusolverDnDgetrs, cusolverDnHandle_t, cusolverStatus_t,
    },
    driver::{CudaSlice, DevicePtr, DevicePtrMut},
};

#[deprecated(
    since = "0.2.1",
    note = "the `cuda` backend is deprecated, use the `cuda-oxide` backend (`OxideContext`, `OxideVec`, `OxideMat`, `OxideLU`) instead"
)]
pub struct CudaLU<T>
where
    T: ScalarCuda,
{
    work: Option<CudaSlice<T>>,
    pivots: Option<CudaSlice<i32>>,
    nfo: Option<RefCell<CudaSlice<i32>>>,
    matrix: Option<CudaMat<T>>,
    handle: cusolverDnHandle_t,
    linearisation_set: bool,
}

impl<T> Default for CudaLU<T>
where
    T: ScalarCuda,
{
    fn default() -> Self {
        let handle = {
            let mut handle = MaybeUninit::uninit();
            unsafe {
                let stat = cusolverDnCreate(handle.as_mut_ptr());
                assert_eq!(stat, cusolverStatus_t::CUSOLVER_STATUS_SUCCESS);
                handle.assume_init()
            }
        };
        Self {
            matrix: None,
            work: None,
            pivots: None,
            nfo: None,
            handle,
            linearisation_set: false,
        }
    }
}

impl<T: ScalarCuda> Drop for CudaLU<T> {
    fn drop(&mut self) {
        unsafe {
            cusolverDnDestroy(self.handle);
        }
    }
}

impl<T: ScalarCuda> CudaLU<T> {
    fn solve_impl(&self, x: &mut CudaVec<T>, transpose: bool) -> Result<(), LaError> {
        let matrix = if let Some(ref matrix) = self.matrix {
            if matrix.nrows() != matrix.ncols() {
                Err(linear_solver_error!(LinearSolverMatrixNotSquare))?;
            }
            matrix
        } else {
            Err(linear_solver_error!(LinearSolverNotSetup))?
        };
        if !self.linearisation_set {
            Err(linear_solver_error!(LinearSolverNotSetup))?;
        }
        let nbatch = x.context.nbatch();
        let lu_nbatch = matrix.context().nbatch();
        x.context.assert_broadcastable_into(lu_nbatch, "lu_solve");
        let nrows = matrix.nrows();
        let ncols = matrix.ncols();
        let x_nstates = x.data.len() / nbatch;
        if x_nstates != nrows {
            Err(linear_solver_error!(LinearSolverMatrixVectorNotCompatible))?;
        }
        let mut nfo = self.nfo.as_ref().expect("NFO not set").borrow_mut();
        let stream = &x.context.stream;
        let lda = i32::try_from(nrows).unwrap();
        let n = i32::try_from(nrows).unwrap();
        let nrhs = 1i32;
        let (a_ptr, _) = matrix.data.device_ptr(stream);
        let (p_ptr, _) = self.pivots.as_ref().unwrap().device_ptr(stream);
        let (x_ptr, _) = x.data.device_ptr_mut(stream);
        let (n_ptr, _) = nfo.device_ptr_mut(stream);
        for b in 0..nbatch {
            // one factorization can serve several right-hand side batches
            let lu_b = broadcast_batch(b, lu_nbatch, nbatch);
            let a_offset = lu_b * nrows * ncols;
            let p_offset = lu_b * nrows;
            let x_offset = b * x_nstates;
            unsafe {
                cusolverDnDgetrs(
                    self.handle,
                    if transpose {
                        cublasOperation_t::CUBLAS_OP_T
                    } else {
                        cublasOperation_t::CUBLAS_OP_N
                    },
                    n,
                    nrhs,
                    (a_ptr as *const f64).add(a_offset),
                    lda,
                    (p_ptr as *const i32).add(p_offset),
                    (x_ptr as *mut f64).add(x_offset),
                    n,
                    (n_ptr as *mut i32).add(lu_b),
                )
            };
        }
        Ok(())
    }
}

impl<T: ScalarCuda> LinearSolver<CudaMat<T>> for CudaLU<T> {
    fn set_linearisation<C: LinearOp<T = T, V = CudaVec<T>, M = CudaMat<T>, C = CudaContext>>(
        &mut self,
        op: &C,
    ) {
        let matrix = self.matrix.as_mut().expect("Matrix not set");
        let work = self.work.as_mut().expect("Work space not set");
        let pivots = self.pivots.as_mut().expect("Pivots not set");
        let nfo = self.nfo.as_mut().expect("NFO not set").get_mut();
        op.matrix_inplace(matrix);
        let nbatch = op.context().nbatch();
        let nrows = matrix.nrows();
        let ncols = matrix.ncols();
        let stream = &op.context().stream;
        let m = i32::try_from(nrows).unwrap();
        let n = i32::try_from(ncols).unwrap();
        let lda = i32::try_from(nrows).unwrap();
        let (a_ptr, _) = matrix.data.device_ptr_mut(stream);
        let (ws_ptr, _) = work.device_ptr_mut(stream);
        let (p_ptr, _) = pivots.device_ptr_mut(stream);
        let (n_ptr, _) = nfo.device_ptr_mut(stream);
        for b in 0..nbatch {
            let a_offset = b * nrows * ncols;
            let p_offset = b * nrows;
            unsafe {
                cusolverDnDgetrf(
                    self.handle,
                    m,
                    n,
                    (a_ptr as *mut f64).add(a_offset),
                    lda,
                    ws_ptr as *mut f64,
                    (p_ptr as *mut i32).add(p_offset),
                    (n_ptr as *mut i32).add(b),
                )
            };
        }
        self.linearisation_set = true;
    }

    fn solve_in_place(&self, x: &mut CudaVec<T>) -> Result<(), LaError> {
        self.solve_impl(x, false)
    }

    fn solve_transpose_in_place(&self, x: &mut CudaVec<T>) -> Result<(), LaError> {
        self.solve_impl(x, true)
    }

    fn set_sparsity<C: LinearOp<T = T, V = CudaVec<T>, M = CudaMat<T>, C = CudaContext>>(
        &mut self,
        op: &C,
    ) {
        crate::context::cuda::assert_f64::<T>();
        let ncols = op.ncols();
        let nrows = op.nrows();
        let nbatch = op.context().nbatch();
        let matrix = C::M::new_from_sparsity(nrows, ncols, op.sparsity(), op.context().clone());

        self.matrix = Some(matrix);

        /* step 3: query working space of getrf */
        let stream = &op.context().stream;
        let lwork = {
            let mut lwork = 0;
            let (a, _syn) = self.matrix.as_mut().unwrap().data.device_ptr_mut(stream);
            let m = i32::try_from(nrows).unwrap();
            let n = i32::try_from(ncols).unwrap();
            let lda = i32::try_from(nrows).unwrap();
            unsafe {
                cusolverDnDgetrf_bufferSize(self.handle, m, n, a as *mut f64, lda, &mut lwork);
            }
            lwork
        };
        unsafe {
            self.work = Some(
                stream
                    .alloc(lwork as usize)
                    .expect("Failed to allocate work space"),
            );
            self.pivots = Some(
                stream
                    .alloc(nrows * nbatch)
                    .expect("Failed to allocate pivots"),
            );
            self.nfo = Some(RefCell::new(
                stream.alloc(nbatch).expect("Failed to allocate NFO"),
            ));
        }

        self.linearisation_set = false;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        linear_solver::tests::{
            diagonal_op, test_grouped_lu_solve, test_narrow_state_lu_solve, test_transpose_lu_solve,
        },
        Vector,
    };

    #[test]
    fn test_lu() {
        let mut s = CudaLU::<f64>::default();
        let op = diagonal_op::<CudaMat<f64>>(2.0);
        s.set_sparsity(&op);
        s.set_linearisation(&op);
        let b = CudaVec::from_vec(vec![2.0, 4.0], Default::default());
        let x = s.solve(&b).unwrap();
        x.assert_eq_st(
            &CudaVec::from_vec(vec![1.0, 2.0], Default::default()),
            1e-10,
        );
    }

    #[test]
    #[should_panic(expected = "incompatible nbatch")]
    fn test_narrow_state_lu() {
        test_narrow_state_lu_solve::<CudaMat<f64>, CudaLU<f64>>(
            CudaContext::default().with_nbatch(2),
        );
    }

    #[test]
    fn test_grouped_lu() {
        test_grouped_lu_solve::<CudaMat<f64>, CudaLU<f64>>(CudaContext::default().with_nbatch(2));
    }

    #[test]
    fn test_transpose_lu() {
        test_transpose_lu_solve::<CudaMat<f64>, CudaLU<f64>>(CudaContext::default().with_nbatch(2));
    }
}

//cusolverDnHandle_t cusolverH = NULL;
//cudaStream_t stream = NULL;
//
//const int m = 3;
//const int lda = m;
//const int ldb = m;
//
// *       | 1 2 3  |
// *   A = | 4 5 6  |
// *       | 7 8 10 |
// *
// * without pivoting: A = L*U
// *       | 1 0 0 |      | 1  2  3 |
// *   L = | 4 1 0 |, U = | 0 -3 -6 |
// *       | 7 2 1 |      | 0  0  1 |
// *
// * with pivoting: P*A = L*U
// *       | 0 0 1 |
// *   P = | 1 0 0 |
// *       | 0 1 0 |
// *
// *       | 1       0     0 |      | 7  8       10     |
// *   L = | 0.1429  1     0 |, U = | 0  0.8571  1.5714 |
// *       | 0.5714  0.5   1 |      | 0  0       -0.5   |
// */
//
//const std::vector<double> A = {1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 10.0};
//const std::vector<double> B = {1.0, 2.0, 3.0};
//std::vector<double> X(m, 0);
//std::vector<double> LU(lda * m, 0);
//std::vector<int> Ipiv(m, 0);
//int info = 0;
//
//double *d_A = nullptr; /* device copy of A */
//double *d_B = nullptr; /* device copy of B */
//int *d_Ipiv = nullptr; /* pivoting sequence */
//int *d_info = nullptr; /* error info */
//
//int lwork = 0;            /* size of workspace */
//double *d_work = nullptr; /* device workspace for getrf */
//
//const int pivot_on = 0;
//
//if (pivot_on) {
//    printf("pivot is on : compute P*A = L*U \n");
//} else {
//    printf("pivot is off: compute A = L*U (not numerically stable)\n");
//}
//
//printf("A = (matlab base-1)\n");
//print_matrix(m, m, A.data(), lda);
//printf("=====\n");
//
//printf("B = (matlab base-1)\n");
//print_matrix(m, 1, B.data(), ldb);
//printf("=====\n");
//
//CUSOLVER_CHECK(cusolverDnCreate(&cusolverH));
//
//CUDA_CHECK(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking));
//CUSOLVER_CHECK(cusolverDnSetStream(cusolverH, stream));
//
//CUDA_CHECK(cudaMalloc(reinterpret_cast<void **>(&d_A), sizeof(double) * A.size()));
//CUDA_CHECK(cudaMalloc(reinterpret_cast<void **>(&d_B), sizeof(double) * B.size()));
//CUDA_CHECK(cudaMalloc(reinterpret_cast<void **>(&d_Ipiv), sizeof(int) * Ipiv.size()));
//CUDA_CHECK(cudaMalloc(reinterpret_cast<void **>(&d_info), sizeof(int)));
//
//CUDA_CHECK(
//    cudaMemcpyAsync(d_A, A.data(), sizeof(double) * A.size(), cudaMemcpyHostToDevice, stream));
//CUDA_CHECK(
//    cudaMemcpyAsync(d_B, B.data(), sizeof(double) * B.size(), cudaMemcpyHostToDevice, stream));
//
//CUSOLVER_CHECK(cusolverDnDgetrf_bufferSize(cusolverH, m, m, d_A, lda, &lwork));
//
//CUDA_CHECK(cudaMalloc(reinterpret_cast<void **>(&d_work), sizeof(double) * lwork));
//
/* step 4: LU factorization */
//if (pivot_on) {
//    CUSOLVER_CHECK(cusolverDnDgetrf(cusolverH, m, m, d_A, lda, d_work, d_Ipiv, d_info));
//} else {
//    CUSOLVER_CHECK(cusolverDnDgetrf(cusolverH, m, m, d_A, lda, d_work, NULL, d_info));
//}
//
//if (pivot_on) {
//    CUDA_CHECK(cudaMemcpyAsync(Ipiv.data(), d_Ipiv, sizeof(int) * Ipiv.size(),
//                               cudaMemcpyDeviceToHost, stream));
//}
//CUDA_CHECK(
//    cudaMemcpyAsync(LU.data(), d_A, sizeof(double) * A.size(), cudaMemcpyDeviceToHost, stream));
//CUDA_CHECK(cudaMemcpyAsync(&info, d_info, sizeof(int), cudaMemcpyDeviceToHost, stream));
//
//CUDA_CHECK(cudaStreamSynchronize(stream));
//
//if (0 > info) {
//    printf("%d-th parameter is wrong \n", -info);
//    exit(1);
//}
//if (pivot_on) {
//    printf("pivoting sequence, matlab base-1\n");
//    for (int j = 0; j < m; j++) {
//        printf("Ipiv(%d) = %d\n", j + 1, Ipiv[j]);
//    }
//}
//printf("L and U = (matlab base-1)\n");
//print_matrix(m, m, LU.data(), lda);
//printf("=====\n");
//
//*
// * step 5: solve A*X = B
// *       | 1 |       | -0.3333 |
// *   B = | 2 |,  X = |  0.6667 |
// *       | 3 |       |  0      |
// *
// */
//if (pivot_on) {
//    CUSOLVER_CHECK(cusolverDnDgetrs(cusolverH, CUBLAS_OP_N, m, 1, /* nrhs */
//                                    d_A, lda, d_Ipiv, d_B, ldb, d_info));
//} else {
//    CUSOLVER_CHECK(cusolverDnDgetrs(cusolverH, CUBLAS_OP_N, m, 1, /* nrhs */
//                                    d_A, lda, NULL, d_B, ldb, d_info));
//}
//
//CUDA_CHECK(
//    cudaMemcpyAsync(X.data(), d_B, sizeof(double) * X.size(), cudaMemcpyDeviceToHost, stream));
//CUDA_CHECK(cudaStreamSynchronize(stream));
//
//printf("X = (matlab base-1)\n");
//print_matrix(m, 1, X.data(), ldb);
//printf("=====\n");
//
/* free resources */
//CUDA_CHECK(cudaFree(d_A));
//CUDA_CHECK(cudaFree(d_B));
//CUDA_CHECK(cudaFree(d_Ipiv));
//CUDA_CHECK(cudaFree(d_info));
//CUDA_CHECK(cudaFree(d_work));
//
//CUSOLVER_CHECK(cusolverDnDestroy(cusolverH));
//
//CUDA_CHECK(cudaStreamDestroy(stream));
//
//CUDA_CHECK(cudaDeviceReset());
//
//return EXIT_SUCCESS;
//}