tenferro_tensor/validate/mod.rs
1//! Validation helpers shared across backends and exec layers.
2//!
3//! # Examples
4//!
5//! ```rust
6//! use tenferro_tensor::validate::validate_nonsingular_u;
7//! use tenferro_tensor::{Tensor, TypedTensor};
8//!
9//! let t = Tensor::from_typed::<f64>(TypedTensor::from_vec_col_major(vec![2, 2], vec![1.0, 0.0, 0.0, 1.0]).unwrap());
10//! assert!(validate_nonsingular_u(&t).is_ok());
11//! ```
12
13use num_complex::{Complex32, Complex64};
14
15use crate::{
16 DType, DotGeneralConfig, Error, ErrorKind, Result, ShapeMismatch, Tensor, TensorScalar,
17 TypedTensor, ValidationError,
18};
19
20/// Domain-specific reasons reported by triangular-factor validation.
21///
22/// The outer tensor error classifies these failures as numerical or unsupported
23/// while retaining this value as its typed source.
24///
25/// # Examples
26///
27/// ```rust
28/// use tenferro_tensor::validate::DiagonalError;
29///
30/// let error = DiagonalError::SingularOrNonFinite {
31/// index: 1,
32/// };
33/// assert!(error.to_string().contains("position [1,1]"));
34/// ```
35#[derive(Debug, thiserror::Error)]
36pub enum DiagonalError {
37 #[error("singular or non-finite diagonal at position [{index},{index}]")]
38 SingularOrNonFinite { index: usize },
39 #[error("singular or non-finite diagonal at batch {batch}, position [{index},{index}]")]
40 BatchedSingularOrNonFinite { batch: usize, index: usize },
41 #[error("triangular solve does not support dtype {dtype:?}")]
42 UnsupportedDType { dtype: DType },
43}
44
45/// Promote two dtypes according to tenferro's public dtype-promotion lattice.
46///
47/// # Examples
48///
49/// ```rust
50/// use tenferro_tensor::validate::promote_dtype;
51/// use tenferro_tensor::DType;
52///
53/// assert_eq!(promote_dtype(DType::I32, DType::F32), DType::F64);
54/// ```
55pub fn promote_dtype(lhs: DType, rhs: DType) -> DType {
56 // The lattice belongs to the scalar set that declares the members, and is
57 // derived from each member's declared kind, rank, and width. A set that
58 // declares a different set of scalars promotes within that set instead of
59 // using this one.
60 <crate::DefaultScalars as crate::ScalarSet>::promote(lhs, rhs)
61}
62
63/// Return whether public `convert` may change `from` into `to`.
64///
65/// Checked conversion follows the same dtype lattice as implicit promotion.
66/// Use explicit `cast` for value-changing projections outside this lattice.
67///
68/// # Examples
69///
70/// ```rust
71/// use tenferro_tensor::validate::can_convert_dtype;
72/// use tenferro_tensor::DType;
73///
74/// assert!(can_convert_dtype(DType::F32, DType::F64));
75/// assert!(!can_convert_dtype(DType::F64, DType::I32));
76/// ```
77pub fn can_convert_dtype(from: DType, to: DType) -> bool {
78 promote_dtype(from, to) == to
79}
80
81/// Validate a public checked dtype conversion.
82///
83/// # Examples
84///
85/// ```rust
86/// use tenferro_tensor::validate::validate_convert_dtype;
87/// use tenferro_tensor::DType;
88///
89/// assert!(validate_convert_dtype("convert", DType::F32, DType::F64).is_ok());
90/// assert!(validate_convert_dtype("convert", DType::C64, DType::F64).is_err());
91/// ```
92/// # Errors
93///
94/// Returns [`crate::Error::UnsupportedDTypeConversion`] when the requested
95/// conversion is outside the checked promotion lattice. Use an explicit cast
96/// for lossy projections.
97pub fn validate_convert_dtype(op: &'static str, from: DType, to: DType) -> Result<()> {
98 if can_convert_dtype(from, to) {
99 return Ok(());
100 }
101
102 Err(Error::unsupported_dtype_conversion(
103 op,
104 from,
105 to,
106 "checked convert only accepts conversions allowed by dtype promotion; use explicit cast for lossy dtype projection",
107 ))
108}
109
110/// Compute a shape product with overflow reported as a typed tensor error.
111///
112/// # Examples
113///
114/// ```rust
115/// use tenferro_tensor::validate::checked_shape_product;
116///
117/// assert_eq!(checked_shape_product("zeros", "shape", &[2, 3])?, 6);
118/// # Ok::<(), tenferro_tensor::Error>(())
119/// ```
120/// # Errors
121///
122/// Returns [`crate::Error::Validation`] containing
123/// [`tenferro_tensor_core::ValidationError::InvalidArgument`] when the
124/// product of `shape` exceeds `usize::MAX`; `role` identifies the shape-like
125/// argument in the diagnostic.
126pub fn checked_shape_product(
127 op: &'static str,
128 role: &'static str,
129 shape: &[usize],
130) -> Result<usize> {
131 if shape.contains(&0) {
132 return Ok(0);
133 }
134 shape
135 .iter()
136 .try_fold(1usize, |acc, &dim| acc.checked_mul(dim))
137 .ok_or_else(|| {
138 Error::invalid_argument(op, role, format!("product overflows for shape {shape:?}"))
139 })
140}
141
142/// Validate a full permutation for a tensor rank.
143///
144/// # Examples
145///
146/// ```rust
147/// use tenferro_tensor::validate::validate_permutation_axes;
148///
149/// validate_permutation_axes("transpose", 2, &[1, 0])?;
150/// # Ok::<(), tenferro_tensor::Error>(())
151/// ```
152/// # Errors
153///
154/// Returns [`crate::Error::Validation`] with `RankMismatch`,
155/// `AxisOutOfBounds`, or `DuplicateAxis` as appropriate.
156pub fn validate_permutation_axes(op: &'static str, rank: usize, perm: &[usize]) -> Result<()> {
157 if perm.len() != rank {
158 return Err(Error::validation(
159 op,
160 ValidationError::RankMismatch {
161 expected: rank,
162 actual: perm.len(),
163 },
164 ));
165 }
166
167 let mut seen = vec![false; rank];
168 for &axis in perm {
169 if axis >= rank {
170 return Err(Error::validation(
171 op,
172 ValidationError::AxisOutOfBounds {
173 axis: isize::try_from(axis).unwrap_or(isize::MAX),
174 rank,
175 },
176 ));
177 }
178 if seen[axis] {
179 return Err(Error::validation(
180 op,
181 ValidationError::DuplicateAxis {
182 axis,
183 role: "permutation",
184 },
185 ));
186 }
187 seen[axis] = true;
188 }
189 Ok(())
190}
191
192/// Validate a subset of axes for a tensor rank.
193///
194/// # Examples
195///
196/// ```rust
197/// use tenferro_tensor::validate::validate_unique_axes;
198///
199/// validate_unique_axes("reduce_sum", "axes", 3, &[0, 2])?;
200/// assert!(validate_unique_axes("reduce_sum", "axes", 2, &[2]).is_err());
201/// assert!(validate_unique_axes("reduce_sum", "axes", 2, &[0, 0]).is_err());
202/// # Ok::<(), tenferro_tensor::Error>(())
203/// ```
204/// # Errors
205///
206/// Returns [`crate::Error::Validation`] with `AxisOutOfBounds` for an invalid
207/// axis or `DuplicateAxis` when an axis occurs more than once.
208///
209/// `role` names the argument family and is the same for every surface that
210/// validates the same list: `"axes"` for a reduction or `reverse` axis list,
211/// `"dim"` for a linalg dimension list. A permutation list is validated by
212/// [`validate_permutation_axes`] instead.
213pub fn validate_unique_axes(
214 op: &'static str,
215 role: &'static str,
216 rank: usize,
217 axes: &[usize],
218) -> Result<()> {
219 let mut seen = vec![false; rank];
220 for &axis in axes {
221 if axis >= rank {
222 return Err(Error::validation(
223 op,
224 ValidationError::AxisOutOfBounds {
225 axis: isize::try_from(axis).unwrap_or(isize::MAX),
226 rank,
227 },
228 ));
229 }
230 if seen[axis] {
231 return Err(Error::validation(
232 op,
233 ValidationError::DuplicateAxis { axis, role },
234 ));
235 }
236 seen[axis] = true;
237 }
238 Ok(())
239}
240
241/// Validate rank-2 matrix multiplication shapes and return its dot-general config.
242///
243/// # Examples
244///
245/// ```rust
246/// use tenferro_tensor::validate::matmul_config_for_shapes;
247///
248/// let config = matmul_config_for_shapes("matmul", &[2, 3], &[3, 4])?;
249/// assert_eq!(config.lhs_contracting_dims.as_slice(), &[1]);
250/// # Ok::<(), tenferro_tensor::Error>(())
251/// ```
252/// # Errors
253///
254/// Returns [`crate::Error::Validation`] with `RankMismatch` for a non-matrix
255/// input or `ShapeMismatch` when the contracting dimensions differ.
256pub fn matmul_config_for_shapes(
257 op: &'static str,
258 lhs_shape: &[usize],
259 rhs_shape: &[usize],
260) -> Result<DotGeneralConfig> {
261 if lhs_shape.len() != 2 {
262 return Err(Error::validation(
263 op,
264 ValidationError::RankMismatch {
265 expected: 2,
266 actual: lhs_shape.len(),
267 },
268 ));
269 }
270 if rhs_shape.len() != 2 {
271 return Err(Error::validation(
272 op,
273 ValidationError::RankMismatch {
274 expected: 2,
275 actual: rhs_shape.len(),
276 },
277 ));
278 }
279 if lhs_shape[1] != rhs_shape[0] {
280 return Err(Error::validation(
281 op,
282 ShapeMismatch::IncompatibleShapes {
283 lhs: lhs_shape.iter().copied().collect(),
284 rhs: rhs_shape.iter().copied().collect(),
285 }
286 .into(),
287 ));
288 }
289
290 Ok(DotGeneralConfig {
291 lhs_contracting_dims: [1].as_slice().into(),
292 rhs_contracting_dims: [0].as_slice().into(),
293 lhs_batch_dims: [].as_slice().into(),
294 rhs_batch_dims: [].as_slice().into(),
295 })
296}
297
298/// Trait for detecting singular or non-finite diagonal entries.
299///
300/// Implemented for `f32`, `f64`, `Complex32`, and `Complex64`.
301/// A value is considered singular if it is zero, NaN, infinite,
302/// or (for complex types) if either component is non-finite.
303pub trait DiagSingularity {
304 /// Returns `true` if the value is singular or non-finite.
305 fn is_singular_or_nonfinite(&self) -> bool;
306}
307
308macro_rules! impl_diag_singularity_float {
309 ($($t:ty),* $(,)?) => {
310 $(
311 impl DiagSingularity for $t {
312 fn is_singular_or_nonfinite(&self) -> bool {
313 !self.is_finite() || *self == 0.0
314 }
315 }
316 )*
317 };
318}
319
320impl_diag_singularity_float!(f64, f32);
321
322macro_rules! impl_diag_singularity_complex {
323 ($($t:ty),* $(,)?) => {
324 $(
325 impl DiagSingularity for $t {
326 fn is_singular_or_nonfinite(&self) -> bool {
327 // Why not `norm_sqr() == 0`: squaring a representable tiny
328 // component can underflow and relabel a nonzero pivot as zero.
329 !self.re.is_finite()
330 || !self.im.is_finite()
331 || (self.re == 0.0 && self.im == 0.0)
332 }
333 }
334 )*
335 };
336}
337
338impl_diag_singularity_complex!(Complex64, Complex32);
339
340/// Checks that every diagonal element of a (possibly batched) upper-triangular
341/// factor is non-singular and finite.
342///
343/// Iterates over all batch slices and inspects the diagonal entries
344/// `data[i + i * rows]` for `i` in `0..min(rows, cols)`. Returns
345/// a numerical [`crate::Error::Extension`] carrying a typed
346/// [`DiagonalError::SingularOrNonFinite`] source for the first offending entry,
347/// or [`ValidationError::RankMismatch`] wrapped in [`Error::Validation`] when
348/// `t` has rank less than two.
349///
350/// # Examples
351///
352/// ```rust
353/// use tenferro_tensor::validate::check_singular_diagonal;
354/// use tenferro_tensor::TypedTensor;
355///
356/// let t = TypedTensor::from_vec_col_major(vec![2, 2], vec![1.0f32, 0.0, 0.0, 2.0]).unwrap();
357/// assert!(check_singular_diagonal(&t).is_ok());
358/// ```
359/// # Errors
360///
361/// Returns [`crate::Error::Validation`] with `RankMismatch` for a non-matrix
362/// tensor, a numerical [`crate::Error::Extension`] with a typed
363/// [`DiagonalError::SingularOrNonFinite`] source for a singular or non-finite
364/// diagonal, or an unsupported [`crate::Error::Extension`] with a typed
365/// [`DiagonalError::UnsupportedDType`] source for integer and boolean inputs.
366pub fn check_singular_diagonal<T: DiagSingularity + TensorScalar + std::fmt::Debug>(
367 t: &TypedTensor<T>,
368) -> Result<()> {
369 if t.shape().len() < 2 {
370 return Err(Error::validation(
371 "solve",
372 ValidationError::RankMismatch {
373 expected: 2,
374 actual: t.shape().len(),
375 },
376 ));
377 }
378 let rows = t.shape()[0];
379 let cols = t.shape()[1];
380 let n = rows.min(cols);
381 let batch_total = checked_shape_product("solve", "batch shape", &t.shape()[2..])?;
382 let slice_size = checked_shape_product("solve", "matrix shape", &t.shape()[..2])?;
383 let data = t.host_data()?;
384 for batch_idx in 0..batch_total {
385 let batch = &data[batch_idx * slice_size..(batch_idx + 1) * slice_size];
386 for i in 0..n {
387 let diag = batch[i + i * rows];
388 if diag.is_singular_or_nonfinite() {
389 return Err(Error::extension(
390 "solve",
391 "tensor-validation",
392 ErrorKind::NumericalFailure,
393 if batch_total > 1 {
394 DiagonalError::BatchedSingularOrNonFinite {
395 batch: batch_idx,
396 index: i,
397 }
398 } else {
399 DiagonalError::SingularOrNonFinite { index: i }
400 },
401 ));
402 }
403 }
404 }
405 Ok(())
406}
407
408/// Validates that the upper-triangular factor `u` of a matrix decomposition
409/// has no singular (zero) or non-finite diagonal entries.
410///
411/// Dispatches to [`check_singular_diagonal`] after unpacking the concrete
412/// tensor variant. Returns `Ok(())` when all diagonal entries are valid.
413///
414/// # Examples
415///
416/// ```rust
417/// use tenferro_tensor::validate::validate_nonsingular_u;
418/// use tenferro_tensor::{Tensor, TypedTensor};
419///
420/// let t = Tensor::from_typed::<f64>(TypedTensor::from_vec_col_major(vec![2, 2], vec![1.0, 0.0, 0.0, 1.0]).unwrap());
421/// assert!(validate_nonsingular_u(&t).is_ok());
422/// ```
423/// # Errors
424///
425/// Returns [`crate::Error::Validation`] with the applicable typed shape, rank,
426/// axis, dtype, or argument source when validation fails. Singular or
427/// non-finite diagonal checks return [`crate::Error::BackendFailure`].
428pub fn validate_nonsingular_u(u: &Tensor) -> Result<()> {
429 match u.dtype() {
430 DType::F64 => check_singular_diagonal(
431 u.as_typed::<f64>()
432 .ok_or_else(|| unsupported_diagonal_dtype(u))?,
433 ),
434 DType::F32 => check_singular_diagonal(
435 u.as_typed::<f32>()
436 .ok_or_else(|| unsupported_diagonal_dtype(u))?,
437 ),
438 DType::C64 => check_singular_diagonal(
439 u.as_typed::<Complex64>()
440 .ok_or_else(|| unsupported_diagonal_dtype(u))?,
441 ),
442 DType::C32 => check_singular_diagonal(
443 u.as_typed::<Complex32>()
444 .ok_or_else(|| unsupported_diagonal_dtype(u))?,
445 ),
446 DType::I32 | DType::I64 | DType::Bool | DType::External(_) => {
447 Err(unsupported_diagonal_dtype(u))
448 }
449 }
450}
451
452/// The refusal this module produces for a dtype it cannot validate a diagonal in.
453///
454/// Returning it from an accessor is the same refusal the wildcard arm produced; a
455/// caller reaches that accessor from a match on `u.dtype()`, so it is unreachable in
456/// practice rather than a caller mistake.
457fn unsupported_diagonal_dtype(u: &Tensor) -> Error {
458 Error::extension(
459 "solve",
460 "tensor-validation",
461 ErrorKind::Unsupported,
462 DiagonalError::UnsupportedDType { dtype: u.dtype() },
463 )
464}
465
466#[cfg(test)]
467mod tests;