numr 0.9.0

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
Documentation
//! Triangular solves (Lx = b, Ux = b) for CUDA

use super::super::super::CudaRuntime;
use super::super::super::client::CudaClient;
use super::super::super::kernels;
use crate::algorithm::linalg::{validate_linalg_dtype, validate_square_matrix};
use crate::error::{Error, Result};
use crate::runtime::{AllocGuard, RuntimeClient};
use crate::tensor::Tensor;

/// Solve lower triangular system Lx = b
/// Supports both single RHS (b is 1D vector) and multi-RHS (b is 2D matrix [n, nrhs])
pub fn solve_triangular_lower_impl(
    client: &CudaClient,
    l: &Tensor<CudaRuntime>,
    b: &Tensor<CudaRuntime>,
    unit_diagonal: bool,
) -> Result<Tensor<CudaRuntime>> {
    validate_linalg_dtype(l.dtype())?;
    if l.dtype() != b.dtype() {
        return Err(Error::DTypeMismatch {
            lhs: l.dtype(),
            rhs: b.dtype(),
        });
    }
    let n = validate_square_matrix(l.shape())?;
    let dtype = l.dtype();
    let device = client.device();

    // Handle 1D or 2D b
    let b_shape = b.shape();
    let (num_rhs, b_is_vector) = if b_shape.len() == 1 {
        if b_shape[0] != n {
            return Err(Error::ShapeMismatch {
                expected: vec![n],
                got: b_shape.to_vec(),
            });
        }
        (1, true)
    } else if b_shape.len() == 2 {
        if b_shape[0] != n {
            return Err(Error::ShapeMismatch {
                expected: vec![n, b_shape[1]],
                got: b_shape.to_vec(),
            });
        }
        (b_shape[1], false)
    } else {
        return Err(Error::Internal(format!(
            "solve_triangular_lower requires b to be 1D or 2D, got {}D with shape {:?}",
            b_shape.len(),
            b_shape
        )));
    };

    // Allocate output
    let x_size = n * num_rhs * dtype.size_in_bytes();
    let x_guard = AllocGuard::new(client.allocator(), x_size)?;
    let x_ptr = x_guard.ptr();

    if b_is_vector {
        // Single RHS: direct solve
        unsafe {
            kernels::launch_forward_sub(
                client.context(),
                client.stream(),
                device.index,
                dtype,
                l.ptr(),
                b.ptr(),
                x_ptr,
                n,
                unit_diagonal,
            )?;
        }
    } else {
        // Multi-RHS: solve for each column
        let col_size = n * dtype.size_in_bytes();
        let b_col_guard = AllocGuard::new(client.allocator(), col_size)?;
        let x_col_guard = AllocGuard::new(client.allocator(), col_size)?;

        let b_col_ptr = b_col_guard.ptr();
        let x_col_ptr = x_col_guard.ptr();

        for rhs in 0..num_rhs {
            // Extract column from B
            unsafe {
                kernels::launch_extract_column(
                    client.context(),
                    client.stream(),
                    device.index,
                    dtype,
                    b.ptr(),
                    b_col_ptr,
                    n,
                    num_rhs,
                    rhs,
                )?;
            }

            // Solve L @ x_col = b_col
            unsafe {
                kernels::launch_forward_sub(
                    client.context(),
                    client.stream(),
                    device.index,
                    dtype,
                    l.ptr(),
                    b_col_ptr,
                    x_col_ptr,
                    n,
                    unit_diagonal,
                )?;
            }

            // Scatter solution into X
            unsafe {
                kernels::launch_scatter_column(
                    client.context(),
                    client.stream(),
                    device.index,
                    dtype,
                    x_col_ptr,
                    x_ptr,
                    n,
                    rhs,
                )?;
            }
        }
    }

    client.synchronize();

    let released_ptr = x_guard.release();
    let x = if b_is_vector {
        unsafe { CudaClient::tensor_from_raw(released_ptr, &[n], dtype, device) }
    } else {
        unsafe { CudaClient::tensor_from_raw(released_ptr, &[n, num_rhs], dtype, device) }
    };

    Ok(x)
}

/// Solve upper triangular system Ux = b
/// Supports both single RHS (b is 1D vector) and multi-RHS (b is 2D matrix [n, nrhs])
pub fn solve_triangular_upper_impl(
    client: &CudaClient,
    u: &Tensor<CudaRuntime>,
    b: &Tensor<CudaRuntime>,
) -> Result<Tensor<CudaRuntime>> {
    validate_linalg_dtype(u.dtype())?;
    if u.dtype() != b.dtype() {
        return Err(Error::DTypeMismatch {
            lhs: u.dtype(),
            rhs: b.dtype(),
        });
    }
    let n = validate_square_matrix(u.shape())?;
    let dtype = u.dtype();
    let device = client.device();

    // Handle 1D or 2D b
    let b_shape = b.shape();
    let (num_rhs, b_is_vector) = if b_shape.len() == 1 {
        if b_shape[0] != n {
            return Err(Error::ShapeMismatch {
                expected: vec![n],
                got: b_shape.to_vec(),
            });
        }
        (1, true)
    } else if b_shape.len() == 2 {
        if b_shape[0] != n {
            return Err(Error::ShapeMismatch {
                expected: vec![n, b_shape[1]],
                got: b_shape.to_vec(),
            });
        }
        (b_shape[1], false)
    } else {
        return Err(Error::Internal(format!(
            "solve_triangular_upper requires b to be 1D or 2D, got {}D with shape {:?}",
            b_shape.len(),
            b_shape
        )));
    };

    // Allocate output
    let x_size = n * num_rhs * dtype.size_in_bytes();
    let x_guard = AllocGuard::new(client.allocator(), x_size)?;
    let x_ptr = x_guard.ptr();

    if b_is_vector {
        // Single RHS: direct solve
        unsafe {
            kernels::launch_backward_sub(
                client.context(),
                client.stream(),
                device.index,
                dtype,
                u.ptr(),
                b.ptr(),
                x_ptr,
                n,
            )?;
        }
    } else {
        // Multi-RHS: solve for each column
        let col_size = n * dtype.size_in_bytes();
        let b_col_guard = AllocGuard::new(client.allocator(), col_size)?;
        let x_col_guard = AllocGuard::new(client.allocator(), col_size)?;

        let b_col_ptr = b_col_guard.ptr();
        let x_col_ptr = x_col_guard.ptr();

        for rhs in 0..num_rhs {
            // Extract column from B
            unsafe {
                kernels::launch_extract_column(
                    client.context(),
                    client.stream(),
                    device.index,
                    dtype,
                    b.ptr(),
                    b_col_ptr,
                    n,
                    num_rhs,
                    rhs,
                )?;
            }

            // Solve U @ x_col = b_col
            unsafe {
                kernels::launch_backward_sub(
                    client.context(),
                    client.stream(),
                    device.index,
                    dtype,
                    u.ptr(),
                    b_col_ptr,
                    x_col_ptr,
                    n,
                )?;
            }

            // Scatter solution into X
            unsafe {
                kernels::launch_scatter_column(
                    client.context(),
                    client.stream(),
                    device.index,
                    dtype,
                    x_col_ptr,
                    x_ptr,
                    n,
                    rhs,
                )?;
            }
        }
    }

    client.synchronize();

    let released_ptr = x_guard.release();
    let x = if b_is_vector {
        unsafe { CudaClient::tensor_from_raw(released_ptr, &[n], dtype, device) }
    } else {
        unsafe { CudaClient::tensor_from_raw(released_ptr, &[n, num_rhs], dtype, device) }
    };

    Ok(x)
}