use super::super::super::CudaRuntime;
use super::super::super::client::CudaClient;
use super::super::svd::svd_decompose_impl;
use crate::algorithm::linalg::{
LinearAlgebraAlgorithms, MatrixNormOrder, validate_linalg_dtype, validate_matrix_2d,
};
use crate::dtype::DType;
use crate::error::Result;
use crate::ops::{CompareOps, ReduceOps, ScalarOps, TypeConversionOps, UnaryOps};
use crate::tensor::Tensor;
pub fn matrix_rank_impl(
client: &CudaClient,
a: &Tensor<CudaRuntime>,
tol: Option<f64>,
) -> Result<Tensor<CudaRuntime>> {
validate_linalg_dtype(a.dtype())?;
let (m, n) = validate_matrix_2d(a.shape())?;
let dtype = a.dtype();
let k = m.min(n);
if k == 0 {
return Tensor::<CudaRuntime>::from_slice(&[0i64], &[], a.device());
}
let base_tol = tol.unwrap_or_else(|| {
let eps = match dtype {
DType::F32 => f32::EPSILON as f64,
DType::F64 => f64::EPSILON,
_ => f32::EPSILON as f64,
};
(m.max(n) as f64) * eps
});
let qr = client.qr_decompose(a)?;
let r_diag = LinearAlgebraAlgorithms::diag(client, &qr.r)?;
let abs_diag = client.abs(&r_diag)?;
let max_val = client.max(&abs_diag, &[], false)?;
let threshold = client.mul_scalar(&max_val, base_tol)?;
let above_mask = client.gt(&abs_diag, &threshold)?;
let rank_float = client.sum(&above_mask, &[], false)?;
let rank_tensor = client.cast(&rank_float, DType::I64)?;
Ok(rank_tensor)
}
pub fn matrix_norm_impl(
client: &CudaClient,
a: &Tensor<CudaRuntime>,
ord: MatrixNormOrder,
) -> Result<Tensor<CudaRuntime>> {
validate_linalg_dtype(a.dtype())?;
let (_m, _n) = validate_matrix_2d(a.shape())?;
match ord {
MatrixNormOrder::Frobenius => {
let squared = client.square(a)?;
let sum_sq = client.sum(&squared, &[], false)?;
client.sqrt(&sum_sq)
}
MatrixNormOrder::Spectral => {
let svd = svd_decompose_impl(client, a)?;
client.max(&svd.s, &[], false)
}
MatrixNormOrder::Nuclear => {
let svd = svd_decompose_impl(client, a)?;
client.sum(&svd.s, &[], false)
}
}
}
#[cfg(test)]
mod tests {
use super::super::super::test_support::*;
use super::*;
use crate::runtime::RuntimeClient;
#[test]
fn test_matrix_rank_full() {
let Some(client) = create_client() else {
return;
};
let device = client.device();
let a =
Tensor::<CudaRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2], device).unwrap();
let rank = LinearAlgebraAlgorithms::matrix_rank(&client, &a, None).unwrap();
let result: Vec<i64> = rank.to_vec();
assert_eq!(result[0], 2);
}
#[test]
fn test_matrix_rank_deficient() {
let Some(client) = create_client() else {
return;
};
let device = client.device();
let a =
Tensor::<CudaRuntime>::from_slice(&[1.0f32, 2.0, 2.0, 4.0], &[2, 2], device).unwrap();
let rank = LinearAlgebraAlgorithms::matrix_rank(&client, &a, None).unwrap();
let result: Vec<i64> = rank.to_vec();
assert_eq!(result[0], 1);
}
}