colmat 0.34.0

Dense and sparse linear algebra for HPC applications with caller owned thread teams.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! the packed $LQ$ factorization: $L$ in the lower triangle of the input, the
//! householder vectors of $Q$ along its rows, and the block coefficients apart.
//!
//! The output conventions of this module (the factor shapes, the placement of the
//! null-space block at the end of the full $Q$, and the optional positive diagonal
//! gauge) follow MatrixAlgebraKit.jl `src/implementations/lq.jl` and
//! `src/common/gauge.jl` (MIT, Copyright (c) QuantumKitHub contributors). The
//! factorization itself is faer's own blocked $QR$ kernel applied to the
//! transposed view; no arithmetic is copied from that project.
use crate::assert;
use crate::internal_prelude::*;
/// information about the resulting $LQ$ factorization.
#[derive(Copy, Clone, Debug)]
pub struct LqInfo {
	/// estimated rank of the matrix: the $QR$ kernel's estimate for the transposed
	/// view, which is an upper bound on the true rank (a run of zero rows of $A$
	/// inside the block structure can leave it above the exact rank).
	pub rank: usize,
}
/// the recommended block size to use for an $LQ$ decomposition of a matrix with
/// the given shape.
#[inline]
pub fn recommended_block_size<T: ComplexField>(
	nrows: usize,
	ncols: usize,
) -> usize {
	linalg::qr::no_pivoting::factor::recommended_block_size::<T>(nrows, ncols)
}
/// $LQ$ factorization tuning parameters.
///
/// An $LQ$ factorization is the $QR$ factorization of the transposed view, so
/// these are the $QR$ tuning parameters, applied to that view.
pub use linalg::qr::no_pivoting::factor::QrParams as LqParams;
/// applies the $QR$ factorization of the transposed view in place, which is this
/// matrix's $LQ$ factorization.
///
/// `Q_coeff` holds the block coefficients, one block per `Q_coeff.nrows()` steps,
/// as in [`qr::no_pivoting::factor::qr_in_place`](crate::linalg::qr::no_pivoting::factor::qr_in_place).
///
/// The panel of each block, `Q_coeff.nrows()` rows of `A`, is copied into a
/// buffer from `stack` that holds the rows contiguous, factored there, and copied
/// back; the update of the rows below it is a pair of matrix products on `A` in
/// place, reading the basis from the buffer. The buffers are part of
/// [`lq_in_place_scratch`]; with a smaller `stack` the panels are factored on
/// `A`'s own strides. Either way the packed form is the same up to rounding.
#[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 }
}
/// computes the layout of required workspace for performing an $LQ$
/// decomposition with no pivoting
#[inline]
pub fn lq_in_place_scratch<T: ComplexField>(
	nrows: usize,
	ncols: usize,
	block_size: usize,
	par: ParShape,
	params: Spec<LqParams, T>,
) -> StackReq {
	// the QR query of the transposed view, which includes the staged panels
	linalg::qr::no_pivoting::factor::qr_in_place_scratch::<T>(
		ncols,
		nrows,
		block_size,
		par,
		params,
	)
}
/// copies the triangular factor $L$ out of the packed factorization in `packed`,
/// leaving the householder vectors intact.
///
/// `out` is either the compact $m \times \min(m, n)$ factor or the full
/// $m \times n$ one, whose columns past $\min(m, n)$ are zero. The strict upper
/// triangle is zero, so every entry of `out` is written.
///
/// with `positive`, column $j$ is scaled by $\overline{d_j} / |d_j|$, where
/// $d_j$ is the diagonal of $L$, which makes every diagonal entry of the result
/// real and nonnegative. [`unitary`](crate::linalg::lq::no_pivoting::unitary::unitary)
/// applies the matching phase to $Q$, so that the product is unchanged.
#[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));
	// every entry of `out` is written: the strict upper triangle and the full
	// factor's trailing columns are zero.
	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;
	/// [`copy_l`] hands `MatMut::copy_from_triangular_lower` a row-major packed
	/// matrix and a column-major destination, which is the tiled gate of
	/// `copy_lower_across_layouts`, with the working set of the `m x k` factor.
	/// The route is pinned on both sides of the threshold, square, tall and
	/// wide: the per-thread tiled-copy counter moves by exactly one where the
	/// gate should tile and stays put where it should fall back, which equal
	/// values alone cannot tell apart.
	///
	/// The destination here is the column-major `m x k` allocation, so its column
	/// stride is `m`: the `m = 2048` and `k = 256` cells tile on
	/// `tensor4all/faer#352`'s power-of-two stride although their working set is
	/// below the byte threshold.
	#[test]
	fn copy_l_reaches_the_tiled_copy_gate() {
		use crate::linalg::tiled_copies;
		for (m, n, tiled) in [
			(512, 512, true),
			// square, 2048 bytes of stride: #352's measured cell
			(256, 256, true),
			// tall: `k = 256`, a `2048 x 256` factor is 8 MiB over both buffers
			(2048, 256, true),
			// tall: 2 MiB, tiled only because the stride is 16 KiB, a power of two
			(2048, 64, true),
			// wide: the factor is only `m x k = 256 x 256`, and its stride is 2 KiB
			(256, 2048, true),
		] {
			let k = Ord::min(m, n);
			// `packed` as a row-major view of a column-major `n x m` allocation
			let packed_col = Mat::<f64>::from_fn(n, m, |j, i| (i + 2 * j) as f64);
			let packed = packed_col.as_ref().transpose();
			// the dispatch the route actually took, not a stride re-derived here:
			// the gate reads the padded column stride of the packed destination and
			// the row stride of the source, which this route holds as views
			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})");
				}
			}
		}
	}

	/// `lq_in_place` factors each panel (a block of rows of `A`) in a
	/// column-major buffer and takes the trailing apply's basis from there
	/// (`qr::no_pivoting::factor::factor_panel_staged`). The packed form must be
	/// the one the kernel writes on the transposed view without staging
	/// (`qr_in_place_packed(.., false)`, the route before tensor4all/faer#314
	/// slice 3), so `unitary`, `reconstruct` and `copy_l` read the same thing:
	/// the same rank; the zeros and the `infinity` markers of the coefficient
	/// blocks, and the zeros the rank-deficient path writes into `A`, at the same
	/// positions; every other entry equal up to rounding. The cases cover the
	/// unblocked size, square, wide and tall, a block size that does not divide
	/// the factorization, zero rows at the start, inside a panel and from a block
	/// boundary on (the out-of-place reflectors), and a padded leading dimension.
	#[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| {
				// the input in a padded column-major allocation (leading dimension
				// `m + 3`)
				let mut storage = Mat::<T>::zeros(m + 3, n);
				let mut packed = storage.as_mut().subrows_mut(0, m);
				packed.copy_from(a);
				// entries neither route writes stay infinite in both
				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);
	}

	/// the look-ahead overlaps the next panel's factorization with the trailing
	/// apply. For LQ the panel is the block of *rows* of `A`, which the transposed
	/// view presents with a stride of `A.col_stride()`, so the transposed path and
	/// its factor layout need the same check as the QR one: the packed form and
	/// the reconstructed matrix agree with the sequential run, and the forced
	/// steps actually ran.
	#[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;
				// the packed factor, the coefficients and the rank are the
				// sequential ones to rounding: the overlap changes only the order of
				// the apply against the panel.
				let approx_eq =
					CwiseMat(ApproxEq::eps() * (Ord::max(m, n) as f64) * 40.0);
				assert!(p1 ~ p0, "{tag}: packed factor");
				// the coefficients of a prefactored panel are assembled in a
				// different order, so the factors are compared through what a
				// consumer reads: $L$, $Q$, and $A = LQ$.
				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);
	}
	/// the forced look-ahead must not lose rank on a prefactored panel that runs
	/// out of rank, which is the case the QR test names explicitly.
	#[test]
	fn test_lookahead_rank_loss() {
		let rng = &mut StdRng::seed_from_u64(11);
		// `n` clears the kernel's look-ahead floor, so the panel that runs out of
		// rank is a prefactored one.
		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);
		// every row from 40 on is zero, so the factorization's rank stops inside a
		// panel that the preceding look-ahead step has already prefactored.
		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");
	}
}