numr 1.0.0

Numerical computing and tensor library for Rust, in the role of NumPy: n-dimensional arrays, linear algebra, FFT, statistics and autograd on CPU, CUDA and WebGPU
Documentation
//! Matrix decomposition implementations (LU, Cholesky, QR) for CUDA

use super::super::CudaRuntime;
use super::super::client::CudaClient;
use super::super::kernels;
use crate::algorithm::linalg::{
    CholeskyDecomposition, LuDecomposition, QrDecomposition, validate_linalg_dtype,
    validate_matrix_2d, validate_square_matrix,
};
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::runtime::{AllocGuard, Runtime, RuntimeClient};
use crate::tensor::{Layout, Storage, Tensor};

/// LU decomposition with partial pivoting
pub fn lu_decompose_impl(
    client: &CudaClient,
    a: &Tensor<CudaRuntime>,
) -> Result<LuDecomposition<CudaRuntime>> {
    validate_linalg_dtype(a.dtype())?;
    let (m, n) = validate_matrix_2d(a.shape())?;
    let k = m.min(n);
    let dtype = a.dtype();
    let device = client.device();

    // Allocate output tensors on GPU
    let lu_size = m * n * dtype.size_in_bytes();
    let pivots_size = k * std::mem::size_of::<i64>();
    let num_swaps_size = std::mem::size_of::<i32>();
    let singular_flag_size = std::mem::size_of::<i32>();

    let lu_guard = AllocGuard::new(client.allocator(), lu_size)?;
    let pivots_guard = AllocGuard::new(client.allocator(), pivots_size)?;
    let num_swaps_guard = AllocGuard::new(client.allocator(), num_swaps_size)?;
    let singular_flag_guard = AllocGuard::new(client.allocator(), singular_flag_size)?;

    let lu_ptr = lu_guard.ptr();
    let pivots_ptr = pivots_guard.ptr();
    let num_swaps_ptr = num_swaps_guard.ptr();
    let singular_flag_ptr = singular_flag_guard.ptr();

    // Copy input to LU buffer
    CudaRuntime::copy_within_device(a.ptr(), lu_ptr, lu_size, device)?;

    // Zero-initialize flags
    let zero_i32: [u8; 4] = [0; 4];
    CudaRuntime::copy_to_device(&zero_i32, num_swaps_ptr, device)?;
    CudaRuntime::copy_to_device(&zero_i32, singular_flag_ptr, device)?;

    // Launch kernel
    unsafe {
        kernels::launch_lu_decompose(
            client.context(),
            client.stream(),
            device.index,
            dtype,
            lu_ptr,
            pivots_ptr,
            num_swaps_ptr,
            singular_flag_ptr,
            m,
            n,
        )?;
    }

    client.synchronize();

    // Read back flags
    let mut num_swaps_bytes = [0u8; 4];
    let mut singular_flag_bytes = [0u8; 4];
    CudaRuntime::copy_from_device(num_swaps_ptr, &mut num_swaps_bytes, device)?;
    CudaRuntime::copy_from_device(singular_flag_ptr, &mut singular_flag_bytes, device)?;

    let num_swaps = i32::from_ne_bytes(num_swaps_bytes) as usize;
    let singular = i32::from_ne_bytes(singular_flag_bytes) != 0;

    if singular {
        return Err(Error::Internal(format!(
            "LU decomposition failed: {}x{} matrix is singular (zero pivot encountered)",
            m, n
        )));
    }

    // Create tensors from GPU memory
    let lu = unsafe { CudaClient::tensor_from_raw(lu_guard.release(), &[m, n], dtype, device) };
    let pivots =
        unsafe { CudaClient::tensor_from_raw(pivots_guard.release(), &[k], DType::I64, device) };

    Ok(LuDecomposition {
        lu,
        pivots,
        num_swaps,
    })
}

/// Cholesky decomposition
pub fn cholesky_decompose_impl(
    client: &CudaClient,
    a: &Tensor<CudaRuntime>,
) -> Result<CholeskyDecomposition<CudaRuntime>> {
    validate_linalg_dtype(a.dtype())?;
    let n = validate_square_matrix(a.shape())?;
    let dtype = a.dtype();
    let device = client.device();

    // Allocate output on GPU
    let l_size = n * n * dtype.size_in_bytes();
    let not_pd_flag_size = std::mem::size_of::<i32>();

    let l_guard = AllocGuard::new(client.allocator(), l_size)?;
    let not_pd_flag_guard = AllocGuard::new(client.allocator(), not_pd_flag_size)?;

    let l_ptr = l_guard.ptr();
    let not_pd_flag_ptr = not_pd_flag_guard.ptr();

    // Copy input to L buffer
    CudaRuntime::copy_within_device(a.ptr(), l_ptr, l_size, device)?;

    // Zero-initialize flag
    let zero_i32: [u8; 4] = [0; 4];
    CudaRuntime::copy_to_device(&zero_i32, not_pd_flag_ptr, device)?;

    // Launch kernel
    unsafe {
        kernels::launch_cholesky_decompose(
            client.context(),
            client.stream(),
            device.index,
            dtype,
            l_ptr,
            not_pd_flag_ptr,
            n,
        )?;
    }

    client.synchronize();

    // Read back flag
    let mut not_pd_bytes = [0u8; 4];
    CudaRuntime::copy_from_device(not_pd_flag_ptr, &mut not_pd_bytes, device)?;
    let not_pd = i32::from_ne_bytes(not_pd_bytes) != 0;

    if not_pd {
        return Err(Error::Internal(format!(
            "Cholesky decomposition failed: {}x{} matrix is not positive definite",
            n, n
        )));
    }

    let l = unsafe { CudaClient::tensor_from_raw(l_guard.release(), &[n, n], dtype, device) };

    Ok(CholeskyDecomposition { l })
}

/// QR decomposition (internal implementation)
pub fn qr_decompose_internal(
    client: &CudaClient,
    a: &Tensor<CudaRuntime>,
    thin: bool,
) -> Result<QrDecomposition<CudaRuntime>> {
    validate_linalg_dtype(a.dtype())?;
    let (m, n) = validate_matrix_2d(a.shape())?;
    let k = m.min(n);
    let dtype = a.dtype();
    let device = client.device();

    // Q dimensions: [m, m] for full, [m, k] for thin
    let q_cols = if thin { k } else { m };
    let q_size = m * q_cols * dtype.size_in_bytes();
    let r_size = m * n * dtype.size_in_bytes();
    // One Householder vector of `m` elements per reflection.
    let workspace_size = m * k * dtype.size_in_bytes();

    let q_guard = AllocGuard::new(client.allocator(), q_size)?;
    let r_guard = AllocGuard::new(client.allocator(), r_size)?;
    let workspace_guard = AllocGuard::new(client.allocator(), workspace_size)?;

    let q_ptr = q_guard.ptr();
    let r_ptr = r_guard.ptr();
    let workspace_ptr = workspace_guard.ptr();

    // Copy A to R (will be modified in place)
    CudaRuntime::copy_within_device(a.ptr(), r_ptr, r_size, device)?;

    let result = unsafe {
        kernels::launch_qr_decompose(
            client.context(),
            client.stream(),
            device.index,
            dtype,
            q_ptr,
            r_ptr,
            workspace_ptr,
            m,
            n,
            thin,
        )
    };

    // Handle kernel error
    result?;

    client.synchronize();

    let q = unsafe { CudaClient::tensor_from_raw(q_guard.release(), &[m, q_cols], dtype, device) };

    // R holds the first `r_rows` rows of its `m` x `n` allocation. Thin QR with
    // `m > n` reads fewer rows than it allocates, and the storage states the
    // allocation, so the drop frees the same size it allocated.
    let r_rows = if thin && m > n { k } else { m };
    let r_storage =
        unsafe { Storage::<CudaRuntime>::from_ptr_owned(r_guard.release(), m * n, dtype, device) };
    let r = Tensor::from_parts(r_storage, Layout::contiguous(&[r_rows, n]));

    Ok(QrDecomposition { q, r })
}

#[cfg(test)]
mod tests {
    use super::super::test_support::*;
    use super::*;
    use crate::algorithm::linalg::LinearAlgebraAlgorithms;
    use crate::algorithm::linalg::decompositions::qr_check;
    use crate::ops::MatmulOps;

    #[test]
    fn test_lu_decomposition() {
        let Some(client) = create_client() else {
            return;
        };
        let device = client.device();

        // 2x2 matrix: [[4, 3], [6, 3]]
        let a =
            Tensor::<CudaRuntime>::from_slice(&[4.0f32, 3.0, 6.0, 3.0], &[2, 2], device).unwrap();

        let lu = client.lu_decompose(&a).unwrap();

        assert_eq!(lu.lu.shape(), &[2, 2]);
        assert_eq!(lu.pivots.shape(), &[2]);
    }

    #[test]
    fn test_cholesky() {
        let Some(client) = create_client() else {
            return;
        };
        let device = client.device();

        // Symmetric positive definite: [[4, 2], [2, 5]]
        let a =
            Tensor::<CudaRuntime>::from_slice(&[4.0f32, 2.0, 2.0, 5.0], &[2, 2], device).unwrap();

        let chol = client.cholesky_decompose(&a).unwrap();

        assert_eq!(chol.l.shape(), &[2, 2]);

        // L should be lower triangular
        let l_data: Vec<f32> = chol.l.to_vec();
        assert!((l_data[1]).abs() < 1e-5); // Upper triangle should be 0
    }

    /// Thin QR with `m > n` shows `[n, n]` of an `m` x `n` allocation. The drop
    /// returns the whole allocation to the free list. Storage that states
    /// `[n, n]` returns `n * n` elements, to the wrong bucket, and the byte count
    /// below fails.
    #[test]
    fn thin_qr_frees_its_whole_r_allocation() {
        let Some(client) = create_client() else {
            return;
        };
        let device = client.device();
        let (m, n) = (7, 3);
        let a =
            Tensor::<CudaRuntime>::from_slice(&qr_check::matrix(m, n), &[m, n], device).unwrap();

        let qr = client.qr_decompose_thin(&a).unwrap();
        assert_eq!(qr.r.shape(), &[n, n]);
        assert!(qr.r.owns_memory());

        let before = client.allocator().memory_stats().free_list_bytes;
        drop(qr.r);
        let returned = client.allocator().memory_stats().free_list_bytes - before;
        assert_eq!(returned, (m * n * std::mem::size_of::<f32>()) as u64);
    }

    #[test]
    fn qr_reconstructs_every_shape() {
        let Some(client) = create_client() else {
            return;
        };
        for &(m, n, thin) in qr_check::CASES {
            let values = qr_check::matrix(m, n);
            let a = Tensor::<CudaRuntime>::from_slice(&values, &[m, n], client.device()).unwrap();
            let qr = if thin {
                client.qr_decompose_thin(&a).unwrap()
            } else {
                client.qr_decompose(&a).unwrap()
            };
            qr_check::assert_holds(
                &values,
                (m, n, thin),
                (qr.q.shape(), &qr.q.to_vec::<f32>()),
                (qr.r.shape(), &qr.r.to_vec::<f32>()),
            );
        }
    }

    #[test]
    fn test_qr_decomposition() {
        let Some(client) = create_client() else {
            return;
        };
        let device = client.device();

        // Test QR: A = Q @ R
        let a =
            Tensor::<CudaRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2], device).unwrap();

        let qr = client.qr_decompose(&a).unwrap();

        // Verify Q @ R == A
        let reconstructed = client.matmul(&qr.q, &qr.r).unwrap();
        let a_data: Vec<f32> = a.to_vec();
        let reconstructed_data: Vec<f32> = reconstructed.to_vec();

        for i in 0..4 {
            assert!(
                (a_data[i] - reconstructed_data[i]).abs() < 1e-4,
                "Mismatch at {}: {} vs {}",
                i,
                a_data[i],
                reconstructed_data[i]
            );
        }
    }
}