use crate::assert;
use crate::internal_prelude::*;
#[derive(Copy, Clone, Debug)]
pub struct LqInfo {
pub rank: usize,
}
#[inline]
pub fn recommended_block_size<T: ComplexField>(
nrows: usize,
ncols: usize,
) -> usize {
linalg::qr::no_pivoting::factor::recommended_block_size::<T>(nrows, ncols)
}
pub use linalg::qr::no_pivoting::factor::QrParams as LqParams;
#[track_caller]
pub fn lq_in_place<T: ComplexField>(
A: MatMut<'_, T>,
Q_coeff: MatMut<'_, T>,
par: Par,
stack: &mut MemStack,
params: Spec<LqParams, T>,
) -> LqInfo {
let info = linalg::qr::no_pivoting::factor::qr_in_place_packed(
A.transpose_mut(),
Q_coeff,
par,
stack,
params,
true,
);
LqInfo { rank: info.rank }
}
#[inline]
pub fn lq_in_place_scratch<T: ComplexField>(
nrows: usize,
ncols: usize,
block_size: usize,
par: ParShape,
params: Spec<LqParams, T>,
) -> StackReq {
linalg::qr::no_pivoting::factor::qr_in_place_scratch::<T>(
ncols,
nrows,
block_size,
par,
params,
)
}
#[track_caller]
pub fn copy_l<T: ComplexField>(
out: MatMut<'_, T>,
packed: MatRef<'_, T>,
positive: bool,
) {
let (m, n) = packed.shape();
let k = Ord::min(m, n);
let mut out = out;
assert!(all(out.nrows() == m, out.ncols() == k || out.ncols() == n));
out.rb_mut().fill(zero());
out.rb_mut().get_mut(.., ..k).copy_from_triangular_lower(packed.get(.., ..k));
if positive {
for j in 0..k {
let phase = linalg::positive_phase(packed[(j, j)].clone()).conj();
for i in j..m {
out[(i, j)] *= &phase;
}
}
}
}
#[cfg(all(test, feature = "threadteam"))]
mod tests {
use super::*;
use crate::assert;
use crate::internal_prelude::*;
use crate::linalg::qr::no_pivoting::factor::{
LOOKAHEAD_FORCE, LOOKAHEAD_STEPS,
};
use crate::stats::prelude::*;
use crate::utils::approx::*;
use crate::{Mat, c64};
use core::sync::atomic::Ordering::Relaxed;
use dyn_stack::MemBuffer;
#[test]
fn copy_l_reaches_the_tiled_copy_gate() {
use crate::linalg::tiled_copies;
for (m, n, tiled) in [
(512, 512, true),
(256, 256, true),
(2048, 256, true),
(2048, 64, true),
(256, 2048, true),
] {
let k = Ord::min(m, n);
let packed_col = Mat::<f64>::from_fn(n, m, |j, i| (i + 2 * j) as f64);
let packed = packed_col.as_ref().transpose();
let mut out = Mat::<f64>::from_fn(m, k, |_, _| -1.0);
let before = tiled_copies();
copy_l(out.as_mut(), packed, false);
assert!(
tiled_copies() - before == tiled as usize,
"{m}x{n}: copy_l took the {} path",
if tiled { "elementwise" } else { "tiled" }
);
for j in 0..k {
for i in 0..m {
let want = if i >= j { packed[(i, j)] } else { 0.0 };
assert!(out[(i, j)] == want, "{m}x{n}: entry ({i}, {j})");
}
}
}
}
#[test]
fn staged_panels_write_the_unstaged_packed_form() {
use crate::linalg::qr::no_pivoting::factor::qr_in_place_packed;
fn check<T: ComplexField<Real = f64>>(
a: MatRef<'_, T>,
bs: usize,
threads: usize,
tag: &str,
) {
let (m, n) = a.shape();
let k = Ord::min(m, n);
let mut mem = MemBuffer::new(lq_in_place_scratch::<T>(
m,
n,
bs,
crate::ParShape::team(threads),
default(),
));
let mut run = |staged: bool| {
let mut storage = Mat::<T>::zeros(m + 3, n);
let mut packed = storage.as_mut().subrows_mut(0, m);
packed.copy_from(a);
let mut coeff = Mat::<T>::full(bs, k, infinity());
let mut go = |par: Par| {
if staged {
lq_in_place(
packed.rb_mut(),
coeff.as_mut(),
par,
MemStack::new(&mut mem),
default(),
)
.rank
} else {
qr_in_place_packed(
packed.rb_mut().transpose_mut(),
coeff.as_mut(),
par,
MemStack::new(&mut mem),
default(),
false,
)
.rank
}
};
let rank = if threads == 1 {
go(Par::Seq)
} else {
crate::team::with_team(threads, go)
};
(packed.to_owned(), coeff, rank)
};
let (p1, c1, r1) = run(true);
let (p0, c0, r0) = run(false);
assert_eq!(r1, r0, "{tag}: rank");
let tol = f64::EPSILON * (Ord::max(m, n) as f64) * 64.0;
let same = |x: &T, y: &T, what: &str, i: usize, j: usize| {
assert_eq!(
abs(x) == 0.0,
abs(y) == 0.0,
"{tag}: {what} ({i}, {j}) zero in one route only"
);
assert_eq!(
is_finite(x),
is_finite(y),
"{tag}: {what} ({i}, {j}) infinite in one route only"
);
if is_finite(y) {
assert!(
abs(&(x.clone() - y.clone())) <= tol * (1.0 + abs(y)),
"{tag}: {what} ({i}, {j})"
);
}
};
for j in 0..n {
for i in 0..m {
same(&p1[(i, j)], &p0[(i, j)], "packed", i, j);
}
}
for j in 0..k {
for i in 0..bs {
same(&c1[(i, j)], &c0[(i, j)], "coefficients", i, j);
}
}
}
let rng = &mut StdRng::seed_from_u64(314);
let mut cases = 0usize;
for (m, n, bs) in [
(7, 9, 4),
(40, 60, 8),
(64, 200, 16),
(200, 64, 16),
(130, 300, 48),
(256, 256, 32),
] {
for zero_rows in [0..0, 0..1, 5..9, 32..m] {
let mut a = CwiseMatDistribution {
nrows: m,
ncols: n,
dist: StandardNormal,
}
.rand::<Mat<f64>>(rng);
let mut z = CwiseMatDistribution {
nrows: m,
ncols: n,
dist: ComplexDistribution::new(StandardNormal, StandardNormal),
}
.rand::<Mat<c64>>(rng);
for i in zero_rows.clone().filter(|&i| i < m) {
for j in 0..n {
a[(i, j)] = 0.0;
z[(i, j)] = c64::new(0.0, 0.0);
}
}
for threads in [1, 4] {
let tag = format!("{m}x{n} block {bs} zero rows {zero_rows:?} threads {threads}");
check(a.as_ref(), bs, threads, &format!("f64 {tag}"));
check(z.as_ref(), bs, threads, &format!("c64 {tag}"));
cases += 1;
}
}
}
assert!(cases == 48);
}
#[test]
fn test_lookahead_matches_sequential() {
let rng = &mut StdRng::seed_from_u64(7);
let mut ran = 0usize;
for (m, n) in [(200, 512), (512, 512), (512, 320)] {
for threads in [4, 8] {
let a = CwiseMatDistribution {
nrows: m,
ncols: n,
dist: ComplexDistribution::new(
StandardNormal,
StandardNormal,
),
}
.rand::<Mat<c64>>(rng);
let k = Ord::min(m, n);
let bs = 8;
let mut mem = MemBuffer::new(lq_in_place_scratch::<c64>(
m,
n,
bs,
crate::ParShape::team(threads),
default(),
));
let mut run = |force: usize, steps: &mut usize, team: bool| {
let mut packed = a.clone();
let mut coeff = Mat::<c64>::zeros(bs, k);
let rank = if team {
crate::team::with_team(threads, |par| {
LOOKAHEAD_FORCE.store(force, Relaxed);
let before = LOOKAHEAD_STEPS.load(Relaxed);
let info = lq_in_place(
packed.as_mut(),
coeff.as_mut(),
par,
MemStack::new(&mut mem),
default(),
);
*steps = LOOKAHEAD_STEPS.load(Relaxed) - before;
LOOKAHEAD_FORCE.store(0, Relaxed);
info.rank
})
} else {
lq_in_place(
packed.as_mut(),
coeff.as_mut(),
Par::Seq,
MemStack::new(&mut mem),
default(),
)
.rank
};
(packed, coeff, rank)
};
let (p0, c0, r0) = run(0, &mut 0, false);
let mut steps = 0;
let (p1, c1, r1) = run(4, &mut steps, true);
let tag = format!("{m}x{n} threads {threads}");
assert_eq!(r0, r1, "{tag}: rank");
assert!(steps > 0, "{tag}: the forced look-ahead ran no step");
ran += 1;
let approx_eq =
CwiseMat(ApproxEq::eps() * (Ord::max(m, n) as f64) * 40.0);
assert!(p1 ~ p0, "{tag}: packed factor");
let mut l = Mat::<c64>::zeros(m, k);
copy_l(l.as_mut(), p1.as_ref(), true);
let mut q = Mat::<c64>::zeros(k, n);
let _ = &c1;
crate::linalg::lq::no_pivoting::unitary::unitary(
q.as_mut(),
p1.as_ref(),
c1.as_ref(),
true,
Par::Seq,
MemStack::new(&mut MemBuffer::new(
crate::linalg::lq::no_pivoting::unitary::unitary_scratch::<c64>(
m,
n,
k,
bs,
ParShape::Seq,
),
)),
);
assert!((&l * &q) ~ a, "{tag}: L Q");
assert!((&q * q.adjoint()) ~ Mat::<c64>::identity(k, k), "{tag}: Q orthonormal");
for j in 0..k {
let d = l[(j, j)].clone();
assert!(
real(&d) >= 0.0
&& imag(&d).abs() <= 1e-13 * d.abs().max(1.0)
);
}
}
}
assert!(ran == 6);
}
#[test]
fn test_lookahead_rank_loss() {
let rng = &mut StdRng::seed_from_u64(11);
let (m, n, bs, threads) = (512usize, 400usize, 8usize, 4usize);
let k = Ord::min(m, n);
let mut a = CwiseMatDistribution {
nrows: m,
ncols: n,
dist: ComplexDistribution::new(StandardNormal, StandardNormal),
}
.rand::<Mat<c64>>(rng);
for i in 40..m {
for j in 0..n {
a[(i, j)] = c64::new(0.0, 0.0);
}
}
let mut mem = MemBuffer::new(lq_in_place_scratch::<c64>(
m,
n,
bs,
crate::ParShape::team(threads),
default(),
));
let mut run = |force: usize, team: bool| {
let mut packed = a.clone();
let mut coeff = Mat::<c64>::zeros(bs, k);
let rank = if team {
crate::team::with_team(threads, |par| {
LOOKAHEAD_FORCE.store(force, Relaxed);
let info = lq_in_place(
packed.as_mut(),
coeff.as_mut(),
par,
MemStack::new(&mut mem),
default(),
);
LOOKAHEAD_FORCE.store(0, Relaxed);
info.rank
})
} else {
lq_in_place(
packed.as_mut(),
coeff.as_mut(),
Par::Seq,
MemStack::new(&mut mem),
default(),
)
.rank
};
(packed, rank)
};
let (p0, r0) = run(0, false);
let (p1, r1) = run(4, true);
assert_eq!(r0, r1, "rank under look-ahead");
assert!(r0 < k, "the fixture must be rank deficient");
let approx_eq =
CwiseMat(ApproxEq::eps() * (Ord::max(m, n) as f64) * 40.0);
assert!(p1 ~ p0, "packed factor under look-ahead");
}
}